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


Python sparse.triu方法代码示例

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


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

示例1: test_upper_triangular_P

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def test_upper_triangular_P(self):
        res_default = self.model.solve()

        # Get upper triangular P
        P_triu = sparse.triu(self.P, format='csc')

        # Setup and solve with upper triangular part only
        m = osqp.OSQP()
        m.setup(P=P_triu, q=self.q, A=self.A, l=self.l, u=self.u,
                **self.opts)
        res_triu = m.solve()

        # Assert equal
        nptest.assert_array_almost_equal(res_default.x, res_triu.x)
        nptest.assert_array_almost_equal(res_default.y, res_triu.y)
        nptest.assert_array_almost_equal(res_default.info.obj_val, 
                                         res_triu.info.obj_val) 
开发者ID:oxfordcontrol,项目名称:osqp-python,代码行数:19,代码来源:basic_test.py

示例2: test_hicConvertFormat_hicpro_to_cool

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def test_hicConvertFormat_hicpro_to_cool():

    outfile = NamedTemporaryFile(suffix='.cool', delete=False)
    outfile.close()
    hicprofile = ROOT + '/test_matrix.hicpro'
    bedfile = ROOT + '/test_matrix.bed'
    args = "--matrices {} --outFileName {} --inputFormat hicpro --outputFormat cool --bedFileHicpro {}".format(hicprofile, outfile.name, bedfile).split()
    hicConvertFormat.main(args)

    # test = hm.hiCMatrix(original_matrix_cool)
    # print(outfile.name)
    new = hm.hiCMatrix(outfile.name)

    matrixFileHandlerInput = MatrixFileHandler(pFileType='hicpro', pMatrixFile=hicprofile,
                                               pBedFileHicPro=bedfile)

    _matrix, cut_intervals, nan_bins, \
        distance_counts, correction_factors = matrixFileHandlerInput.load()

    new.matrix = triu(new.matrix)
    nt.assert_array_almost_equal(new.matrix.data, _matrix.data, decimal=0) 
开发者ID:deeptools,项目名称:HiCExplorer,代码行数:23,代码来源:test_hicConvertFormat.py

示例3: get_data

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def get_data(self, region):
        """Get sparse data for a region

        Parameters
        ----------
        region : tuple or str
            Region for which to load the data. Either tuple of (chr, start, end), or
            string with chromosome name.

        Returns
        -------
        data : csr
            Sparse csr matrix for the corresponding region.

        """
        logging.debug("Loading data")
        data = self.clr.matrix(sparse=True, balance=self.balance).fetch(region)
        data = sparse.triu(data)
        return data.tocsr() 
开发者ID:Phlya,项目名称:coolpuppy,代码行数:21,代码来源:coolpup.py

示例4: baseline_eigencentrality_top_flips

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def baseline_eigencentrality_top_flips(adj_matrix, candidates, n_flips):
    """Selects the top (n_flips) number of flips using eigencentrality score of the edges.
    Applicable only when removing edges.

    :param adj_matrix: sp.spmatrix
        The graph represented as a sparse scipy matrix
    :param candidates: np.ndarray, shape [?, 2]
        Candidate set of edge flips
    :param n_flips: int
        Number of flips to select
    :return: np.ndarray, shape [?, 2]
        The top edge flips from the candidate set
    """
    edges = np.column_stack(sp.triu(adj_matrix, 1).nonzero())
    line_graph = construct_line_graph(adj_matrix)
    eigcentrality_scores = nx.eigenvector_centrality_numpy(nx.Graph(line_graph))
    eigcentrality_scores = {tuple(edges[k]): eigcentrality_scores[k] for k, v in eigcentrality_scores.items()}
    eigcentrality_scores = np.array([eigcentrality_scores[tuple(cnd)] for cnd in candidates])

    scores_argsrt = eigcentrality_scores.argsort()

    return candidates[scores_argsrt[-n_flips:]] 
开发者ID:abojchevski,项目名称:node_embedding_attack,代码行数:24,代码来源:perturbation_attack.py

示例5: construct_line_graph

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def construct_line_graph(adj_matrix):
    """Construct a line graph from an undirected original graph.

    Parameters
    ----------
    adj_matrix : sp.spmatrix [n_samples ,n_samples]
        Symmetric binary adjacency matrix.

    Returns
    -------
    L : sp.spmatrix, shape [A.nnz/2, A.nnz/2]
        Symmetric binary adjacency matrix of the line graph.
    """
    N = adj_matrix.shape[0]
    edges = np.column_stack(sp.triu(adj_matrix, 1).nonzero())
    e1, e2 = edges[:, 0], edges[:, 1]

    I = sp.eye(N).tocsr()
    E1 = I[e1]
    E2 = I[e2]

    L = E1.dot(E1.T) + E1.dot(E2.T) + E2.dot(E1.T) + E2.dot(E2.T)

    return L - 2 * sp.eye(L.shape[0]) 
开发者ID:abojchevski,项目名称:node_embedding_attack,代码行数:26,代码来源:utils.py

示例6: hamming

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def hamming(bkps1, bkps2):
    """Modified Hamming distance for partitions.
    For all pair of points (x, y), x != y, the functions computes the
    number of times the two partitions disagree.
    The result is scaled to be within 0 and 1.

    Args:
        bkps1 (list): list of the last index of each regime.
        bkps2 (list): list of the last index of each regime.

    Returns:
        float: Hamming distance.
    """
    sanity_check(bkps1, bkps2)
    n_samples = max(bkps1)

    disagreement = abs(membership_mat(bkps1) - membership_mat(bkps2))
    disagreement = triu(disagreement, k=1).sum() * 1.
    disagreement /= n_samples * n_samples / 2  # scaling
    return disagreement 
开发者ID:deepcharles,项目名称:ruptures,代码行数:22,代码来源:hamming.py

示例7: test_warm_start

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def test_warm_start(self):

        # Big problem
        sp.random.seed(2)
        self.n = 100
        self.m = 200
        self.A = sparse.random(self.m, self.n, density=0.9, format='csc')
        self.l = -sp.rand(self.m) * 2.
        self.u = sp.rand(self.m) * 2.

        P = sparse.random(self.n, self.n, density=0.9)
        self.P = sparse.triu(P.dot(P.T), format='csc')
        self.q = sp.randn(self.n)

        # Setup solver
        self.model = osqp.OSQP()
        self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
                         **self.opts)

        # Solve problem with OSQP
        res = self.model.solve()

        # Store optimal values
        x_opt = res.x
        y_opt = res.y
        tot_iter = res.info.iter

        # Warm start with zeros and check if number of iterations is the same
        self.model.warm_start(x=np.zeros(self.n), y=np.zeros(self.m))
        res = self.model.solve()
        self.assertEqual(res.info.iter, tot_iter)

        # Warm start with optimal values and check that number of iter < 10
        self.model.warm_start(x=x_opt, y=y_opt)
        res = self.model.solve()
        self.assertLess(res.info.iter, 10) 
开发者ID:oxfordcontrol,项目名称:osqp-python,代码行数:38,代码来源:warm_start_test.py

示例8: setUp

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def setUp(self):
        # Simple QP problem
        sp.random.seed(1)

        self.n = 5
        self.m = 8
        p = 0.7

        Pt = sparse.random(self.n, self.n, density=p)
        Pt_new = Pt.copy()
        Pt_new.data += 0.1 * np.random.randn(Pt.nnz)

        self.P = sparse.triu(Pt.T.dot(Pt) + sparse.eye(self.n), format='csc')
        self.P_new = sparse.triu(Pt_new.T.dot(Pt_new) + sparse.eye(self.n), format='csc')
        self.q = np.random.randn(self.n)
        self.A = sparse.random(self.m, self.n, density=p, format='csc')
        self.A_new = self.A.copy()
        self.A_new.data += np.random.randn(self.A_new.nnz)
        self.l = np.zeros(self.m)
        self.u = 30 + np.random.randn(self.m)
        self.opts = {'eps_abs': 1e-08,
                     'eps_rel': 1e-08,
                     'verbose': False}
        self.model = osqp.OSQP()
        self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
                         **self.opts) 
开发者ID:oxfordcontrol,项目名称:osqp-python,代码行数:28,代码来源:update_matrices_test.py

示例9: setUp

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def setUp(self):

        # Simple QP problem
        self.P = sparse.triu([[2., 5.], [5., 1.]], format='csc')
        self.q = np.array([3, 4])
        self.A = sparse.csc_matrix([[-1.0, 0.], [0., -1.],
                                    [-1., 3.], [2., 5.], [3., 4]])
        self.u = np.array([0., 0., -15, 100, 80])
        self.l = -np.inf * np.ones(len(self.u))
        self.model = osqp.OSQP() 
开发者ID:oxfordcontrol,项目名称:osqp-python,代码行数:12,代码来源:non_convex_test.py

示例10: test_polish_random

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def test_polish_random(self):

        # Random QP problem
        sp.random.seed(6)

        self.n = 30
        self.m = 50
        Pt = sp.randn(self.n, self.n)
        self.P = sparse.triu(np.dot(Pt.T, Pt), format='csc')
        self.q = sp.randn(self.n)
        self.A = sparse.csc_matrix(sp.randn(self.m, self.n))
        self.l = -3 + sp.randn(self.m)
        self.u = 3 + sp.randn(self.m)
        self.model = osqp.OSQP()
        self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
                         **self.opts)

        # Solve problem
        res = self.model.solve()

        # Assert close
        nptest.assert_array_almost_equal(
            res.x, np.array([
                -0.58549607, 0.0030388, -0.07154039, -0.0406463, -0.13349925,
                -0.1354755, -0.17417362, 0.0165324, -0.12213118, -0.10477034,
                -0.51748662, -0.05310921, 0.07862616, 0.53663003, -0.01459859,
                0.40678716, -0.03496123, 0.25722838, 0.06335071, 0.29908295,
                -0.6223218, -0.07614658, -0.3892153, -0.18111635, 0.56301768,
                0.10429917, 0.09821862, -0.30881928, 0.24430531, 0.06597486]))
        nptest.assert_array_almost_equal(
            res.y, np.array([
                0., -2.11407101e-01, 0., 0., 0., 0., 0., 0., 0.,
                0., -3.78854588e-02, 0., -1.58346998e-02, 0., 0.,
                -6.88711599e-02, 0., 0., 0., 0., 0., 0., 0., 0.,
                6.04385132e-01, 0., 0., 0., 0., 0., 0., 0., 0.,
                0., 1.37995470e-01, 0., 0., 0.,  -2.04427802e-02,
                0., -1.32983915e-01, 0., 2.94425952e-02, 0., 0.,
                0., 0., 0., -6.53409219e-02, 0.]))
        nptest.assert_array_almost_equal(res.info.obj_val, -3.262280663471232) 
开发者ID:oxfordcontrol,项目名称:osqp-python,代码行数:41,代码来源:polishing_test.py

示例11: get_edges

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def get_edges(surf, mask=None):
    """Get surface edges.

    Parameters
    ----------
    surf : vtkDataSet or BSDataSet
        Input surface.
    mask : 1D ndarray, optional
        Binary mask. If specified, only use points within the mask.
        Default is None.

    Returns
    -------
    edges : ndarray, shape (n_edges, 2)
        Array of edges. Each element is a point id.

    See Also
    --------
    :func:`get_edge_length`
    :func:`get_points`
    :func:`get_cells`

    """

    adj = get_immediate_adjacency(surf, include_self=False, mask=mask,
                                  dtype=np.bool)
    adj.sort_indices()
    adj_ud = ssp.triu(adj, k=1, format='coo')
    edges = np.column_stack([adj_ud.row, adj_ud.col])
    return edges 
开发者ID:MICA-MNI,项目名称:BrainSpace,代码行数:32,代码来源:mesh_elements.py

示例12: _symmetric_matrix

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def _symmetric_matrix(mat: dok_matrix) -> dok_matrix:
        upper = triu(mat, 1, format='dok') / 2
        # `todok` is necessary because subtraction results in other format
        return (mat + upper.transpose() - upper).todok() 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:6,代码来源:quadratic_expression.py

示例13: omega_index

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def omega_index(clustering1, clustering2):
    '''
    This function calculates the omega index between two clusterings.

    See :cite:`Collins1988omega` for a detailed derivation and explanation of the measure.

    :param Clustering clustering1:
        The first clustering.

    :param Clustering clustering2:
        The second clustering.

    :returns: the omega index
    '''
    if clustering1.n_elements != clustering2.n_elements:
        raise ClusteringSimilarityError

    elif any(e1 != e2 for e1, e2 in zip(clustering1.elements, clustering2.elements)):
        raise ClusteringSimilarityError

    A1 = make_overlapping_membership_matrix(clustering1)
    A2 = make_overlapping_membership_matrix(clustering2)

    M = clustering1.n_elements * (clustering1.n_elements - 1) / 2.0

    maxNover = max(max(A1.diagonal()), max(A2.diagonal())) + 1

    Anot = spsparse.triu((A1 != A2), k=1).sum()

    omega_u = 1.0 - Anot.sum() / M

    t_0_1 = M - spsparse.triu((A1 != 0), k=1).sum()
    t_0_2 = M - spsparse.triu((A2 != 0), k=1).sum()

    t_k_1 = [spsparse.triu((A1 == i), k=1).sum() for i in range(1, maxNover)]
    t_k_2 = [spsparse.triu((A2 == i), k=1).sum() for i in range(1, maxNover)]

    omega_e = (t_0_1*t_0_2 + np.dot(t_k_1, t_k_2)) / M**2

    return (omega_u - omega_e) / (1.0 - omega_e) 
开发者ID:Hoosier-Clusters,项目名称:clusim,代码行数:42,代码来源:sim.py

示例14: test_triul

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def test_triul(shape, k):
    s = sparse.random(shape, density=0.5)
    x = s.todense()

    assert_eq(np.triu(x, k), sparse.triu(s, k))
    assert_eq(np.tril(x, k), sparse.tril(s, k)) 
开发者ID:pydata,项目名称:sparse,代码行数:8,代码来源:test_coo.py

示例15: triu

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import triu [as 别名]
def triu(x, k=0):
    """
    Returns an array with all elements below the k-th diagonal set to zero.

    Parameters
    ----------
    x : COO
        The input array.
    k : int, optional
        The diagonal below which elements are set to zero. The default is
        zero, which corresponds to the main diagonal.

    Returns
    -------
    COO
        The output upper-triangular matrix.

    Raises
    ------
    ValueError
        If :code:`x` doesn't have zero fill-values.

    See Also
    --------
    numpy.triu : NumPy equivalent function
    """
    from .core import COO

    check_zero_fill_value(x)

    if not x.ndim >= 2:
        raise NotImplementedError(
            "sparse.triu is not implemented for scalars or 1-D arrays."
        )

    mask = x.coords[-2] + k <= x.coords[-1]

    coords = x.coords[:, mask]
    data = x.data[mask]

    return COO(coords, data, shape=x.shape, has_duplicates=False, sorted=True) 
开发者ID:pydata,项目名称:sparse,代码行数:43,代码来源:common.py


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