当前位置: 首页>>代码示例>>Python>>正文


Python numpy.triu_indices_from方法代码示例

本文整理汇总了Python中numpy.triu_indices_from方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.triu_indices_from方法的具体用法?Python numpy.triu_indices_from怎么用?Python numpy.triu_indices_from使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.triu_indices_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _featurize

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def _featurize(self, mol):
    """
    Calculate Coulomb matrices for molecules. If extra randomized
    matrices are generated, they are treated as if they are features
    for additional conformers.

    Since Coulomb matrices are symmetric, only the (flattened) upper
    triangular portion is returned.

    Parameters
    ----------
    mol : RDKit Mol
        Molecule.
    """
    features = self.coulomb_matrix(mol)
    if self.upper_tri:
      features = [f[np.triu_indices_from(f)] for f in features]
    features = np.asarray(features)
    return features 
开发者ID:deepchem,项目名称:deepchem,代码行数:21,代码来源:coulomb_matrices.py

示例2: predict

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def predict(self, output_dir, model_path):
        x1d, x2d, name, size, iterator = self.build_input_test()
        preds, logits = self.resn(x1d, x2d)
        saver = tf.train.Saver()
        saver.restore(self.sess, model_path)
        self.sess.run(iterator.initializer,
                feed_dict={self.input_tfrecord_files:self.dataset.get_chunks(RunMode.TEST)})
        while True:
            try:
                preds_, names_, sizes_, = self.sess.run([preds, name, size])
                for pred_, name_, size_ in zip(preds_, names_, sizes_):
                    pred_ = pred_[:size_, :size_]
                    #inds = np.triu_indices_from(pred_, k=1)
                    #pred_[(inds[1], inds[0])] = pred_[inds]
                    #pred_ = (pred_ + np.transpose(pred_)) / 2.0
                    output_path = '{}/{}.concat'.format(output_dir, name_)
                    np.savetxt(output_path, pred_)
            except tf.errors.OutOfRangeError:
                break 
开发者ID:zhanghaicang,项目名称:DeepFolding,代码行数:21,代码来源:resnet.py

示例3: get_triangle

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def get_triangle(hic_matrix, cut, window_len, return_mean=False):
    """
    like get_cut_weight which is the 'diamond' representing the counts
    from a region -window_len to +window_len from the given bin position (cut):

    """
    if cut < 0 or cut > hic_matrix.matrix.shape[0]:
        return None

    left_idx, right_idx = get_idx_of_bins_at_given_distance(hic_matrix, cut, window_len)

    def remove_lower_triangle(matrix):
        """
        remove all values in the lower triangle of a matrix
        """
        return matrix[np.triu_indices_from(matrix)].A1

    edges_left = remove_lower_triangle(hic_matrix.matrix[left_idx:cut, :][:, left_idx:cut].todense())
    edges_right = remove_lower_triangle(hic_matrix.matrix[cut:right_idx, :][:, cut:right_idx].todense())
#    if cut > 1000:
#        import ipdb;ipdb.set_trace()
    return np.concatenate([edges_left, edges_right]) 
开发者ID:deeptools,项目名称:HiCExplorer,代码行数:24,代码来源:hicFindTADs.py

示例4: from_sym_2_tri

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def from_sym_2_tri(symm):
    """convert a 2D symmetric matrix to an upper
       triangular matrix in 1D format

    Parameters
    ----------

    symm : 2D array
          Symmetric matrix


    Returns
    -------

    tri: 1D array
          Contains elements of upper triangular matrix
    """

    inds = np.triu_indices_from(symm)
    tri = symm[inds]
    return tri 
开发者ID:brainiak,项目名称:brainiak,代码行数:23,代码来源:utils.py

示例5: test_rbfize

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def test_rbfize():
    X = np.random.normal(size=(20, 4))
    dists = euclidean_distances(X)
    median = np.median(dists[np.triu_indices_from(dists, k=1)])

    rbf = RBFize(gamma=.25)
    res = rbf.fit_transform(dists)
    assert not hasattr(res, 'median_')
    assert np.allclose(res, np.exp(-.25 * dists ** 2))

    rbf = RBFize(gamma=.25, squared=True)
    res = rbf.fit_transform(dists)
    assert np.allclose(res, np.exp(-.25 * dists))

    rbf = RBFize(gamma=4, scale_by_median=True)
    res = rbf.fit_transform(dists)
    assert np.allclose(rbf.median_, median)
    assert np.allclose(res, np.exp((-4 * median**2) * dists ** 2))

    rbf = RBFize(gamma=4, scale_by_median=True, squared=True)
    res = rbf.fit_transform(dists)
    assert np.allclose(rbf.median_, median)
    assert np.allclose(res, np.exp((-4 * median) * dists)) 
开发者ID:djsutherland,项目名称:skl-groups,代码行数:25,代码来源:test_transforms.py

示例6: fit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def fit(self, X, y=None):
        '''
        If scale_by_median, find :attr:`median_`; otherwise, do nothing.

        Parameters
        ----------
        X : array
            The raw pairwise distances.
        '''

        X = check_array(X)
        if self.scale_by_median:
            self.median_ = np.median(X[np.triu_indices_from(X, k=1)],
                                     overwrite_input=True)
        elif hasattr(self, 'median_'):
            del self.median_
        return self 
开发者ID:djsutherland,项目名称:skl-groups,代码行数:19,代码来源:transform.py

示例7: get_net_vectors

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def get_net_vectors(subject_list, kind, atlas_name="aal"):
    """
        subject_list : the subject short IDs list
        kind         : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation
        atlas_name   : name of the atlas used

    returns:
        matrix       : matrix of connectivity vectors (num_subjects x num_connections)
    """

    # This is an alternative implementation
    networks = load_all_networks(subject_list, kind, atlas_name=atlas_name)
    # Get Fisher transformed matrices
    norm_networks = [np.arctanh(mat) for mat in networks]
    # Get upper diagonal indices
    idx = np.triu_indices_from(norm_networks[0], 1)
    # Get vectorised matrices
    vec_networks = [mat[idx] for mat in norm_networks]
    # Each subject should be a row of the matrix
    matrix = np.vstack(vec_networks)

    return matrix 
开发者ID:sk1712,项目名称:gcn_metric_learning,代码行数:24,代码来源:abide_utils.py

示例8: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def __init__(
        self, relative_rates, equilibrium_frequencies=None, root_distribution=None
    ):
        alleles = _ACGT_ALLELES
        assert len(relative_rates) == 6
        if equilibrium_frequencies is None:
            equilibrium_frequencies = [0.25, 0.25, 0.25, 0.25]
        if root_distribution is None:
            root_distribution = equilibrium_frequencies

        transition_matrix = np.zeros((4, 4))
        # relative_rates: [A->C, A->G,A->T,C->G,C->T,G->T]
        tri_upper = np.triu_indices_from(transition_matrix, k=1)
        transition_matrix[tri_upper] = relative_rates
        transition_matrix += transition_matrix.T
        transition_matrix *= equilibrium_frequencies
        row_sums = transition_matrix.sum(axis=1)
        transition_matrix = transition_matrix / max(row_sums)
        row_sums = transition_matrix.sum(axis=1, dtype="float64")
        np.fill_diagonal(transition_matrix, 1.0 - row_sums)

        super().__init__(alleles, root_distribution, transition_matrix) 
开发者ID:tskit-dev,项目名称:msprime,代码行数:24,代码来源:mutations.py

示例9: tangent_space

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def tangent_space(covmats, Cref):
    """Project a set of covariance matrices in the tangent space according to the given reference point Cref

    :param covmats: Covariance matrices set, Ntrials X Nchannels X Nchannels
    :param Cref: The reference covariance matrix
    :returns: the Tangent space , a matrix of Ntrials X (Nchannels*(Nchannels+1)/2)

    """
    Nt, Ne, Ne = covmats.shape
    Cm12 = invsqrtm(Cref)
    idx = numpy.triu_indices_from(Cref)
    T = numpy.empty((Nt, Ne * (Ne + 1) / 2))
    coeffs = (
        numpy.sqrt(2) *
        numpy.triu(
            numpy.ones(
                (Ne,
                 Ne)),
            1) +
        numpy.eye(Ne))[idx]
    for index in range(Nt):
        tmp = numpy.dot(numpy.dot(Cm12, covmats[index, :, :]), Cm12)
        tmp = logm(tmp)
        T[index, :] = numpy.multiply(coeffs, tmp[idx])
    return T 
开发者ID:alexandrebarachant,项目名称:decoding-brain-challenge-2016,代码行数:27,代码来源:tangentspace.py

示例10: untangent_space

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def untangent_space(T, Cref):
    """Project a set of Tangent space vectors in the manifold according to the given reference point Cref

    :param T: the Tangent space , a matrix of Ntrials X (Nchannels*(Nchannels+1)/2)
    :param Cref: The reference covariance matrix
    :returns: A set of Covariance matrix, Ntrials X Nchannels X Nchannels

    """
    Nt, Nd = T.shape
    Ne = int((numpy.sqrt(1 + 8 * Nd) - 1) / 2)
    C12 = sqrtm(Cref)

    idx = numpy.triu_indices_from(Cref)
    covmats = numpy.empty((Nt, Ne, Ne))
    covmats[:, idx[0], idx[1]] = T
    for i in range(Nt):
        covmats[i] = numpy.diag(numpy.diag(covmats[i])) + numpy.triu(
            covmats[i], 1) / numpy.sqrt(2) + numpy.triu(covmats[i], 1).T / numpy.sqrt(2)
        covmats[i] = expm(covmats[i])
        covmats[i] = numpy.dot(numpy.dot(C12, covmats[i]), C12)

    return covmats 
开发者ID:alexandrebarachant,项目名称:decoding-brain-challenge-2016,代码行数:24,代码来源:tangentspace.py

示例11: _fractal_correlation_Corr_Dim

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def _fractal_correlation_Corr_Dim(embedded, r_vals, dist):
    """References
    -----------
    - `Corr_Dim <https://github.com/jcvasquezc/Corr_Dim>`_
    """
    ED = dist[np.triu_indices_from(dist, k=1)]

    Npairs = (len(embedded[1, :])) * ((len(embedded[1, :]) - 1))
    corr = np.zeros(len(r_vals))

    for i, r in enumerate(r_vals):
        N = np.where(((ED < r) & (ED > 0)))
        corr[i] = len(N[0]) / Npairs

    omit_pts = 1
    k1 = omit_pts
    k2 = len(r_vals) - omit_pts
    r_vals = r_vals[k1:k2]
    corr = corr[k1:k2]

    return r_vals, corr


# =============================================================================
# Utilities
# ============================================================================= 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:28,代码来源:fractal_correlation.py

示例12: _exec

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def _exec(self):
        M = np.zeros((self.labels.size, self.labels.size))

        with closing(Pool(processes=self.n_threads)) as pool:
            values = pool.map(self._partial_mutinf,
                              combinations(self.labels, 2))
            pool.terminate()

        idx = np.triu_indices_from(M)
        M[idx] = values

        return M + M.T - np.diag(M.diagonal()) 
开发者ID:msmbuilder,项目名称:mdentropy,代码行数:14,代码来源:mutinf.py

示例13: test_tensor_iterator

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def test_tensor_iterator():
    a = np.arange(16).reshape((4, 4))
    test_tensor = Tensor(tensor=a)
    assert np.allclose(test_tensor.data, a)
    assert test_tensor.size == 16
    assert isinstance(test_tensor.basis, Bijection)

    a_triu = a[np.triu_indices_from(a)]
    a_tril = a[np.tril_indices_from(a)]

    counter = 0
    for val, idx in test_tensor.utri_iterator():
        assert val == a[tuple(idx)]
        assert val == a_triu[counter]
        counter += 1
    assert counter == 4 * (4 + 1) / 2

    counter = 0
    for val, idx in test_tensor.ltri_iterator():
        assert val == a[tuple(idx)]
        assert val == a_tril[counter]
        counter += 1
    assert counter == 4 * (4 + 1) / 2

    counter = 0
    for val, idx in test_tensor.all_iterator():
        assert val == a[tuple(idx)]
        counter += 1

    assert np.allclose(test_tensor.vectorize(), a.reshape((-1, 1), order='C'))

    with pytest.raises(TypeError):
        list(test_tensor._iterator('blah')) 
开发者ID:quantumlib,项目名称:OpenFermion,代码行数:35,代码来源:_namedtensor_test.py

示例14: test_simple_hessenberg_trafo

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def test_simple_hessenberg_trafo():
    # Made up discrete time TF
    G = Transfer([1., -8., 28., -58., 67., -30.],
                 poly([1, 2, 3., 2, 3., 4, 1 + 1j, 1 - 1j]), dt=0.1)
    H, _ = hessenberg_realization(G, compute_T=1, form='c', invert=1)
    assert_(not np.any(H.a[triu_indices_from(H.a, k=2)]))
    assert_(not np.any(H.b[:-1, 0]))
    H = hessenberg_realization(G, form='o', invert=1)
    assert_(not np.any(H.c[0, :-1]))
    assert_(not np.any(H.a.T[triu_indices_from(H.a, k=2)])) 
开发者ID:ilayn,项目名称:harold,代码行数:12,代码来源:test_system_funcs.py

示例15: lowertosymmetric

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices_from [as 别名]
def lowertosymmetric(a, copy=False):
	a = np.copy(a) if copy else a
	idxs = np.triu_indices_from(a)
	a[idxs] = a[(idxs[1], idxs[0])] 
开发者ID:thalesians,项目名称:bayestsa,代码行数:6,代码来源:numpyutils.py


注:本文中的numpy.triu_indices_from方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。