Python networkx.to_scipy_sparse_matrix() Examples

The following are 30 code examples of networkx.to_scipy_sparse_matrix(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: lle.py    From OpenNE with MIT License 6 votes vote down vote up
def learn_embedding(self):
        graph = self.g.G
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        # print(np.sum(A.todense(), axis=0))
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(graph.number_of_nodes())
        I_min_A = I_n - A
        print(I_min_A)
        u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X, (t2 - t1)
        # I_n = sp.eye(graph.number_of_nodes()) 
Example #2
Source File: modularitymatrix.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def modularity_matrix(G, nodelist=None):
    """Return the modularity matrix of G.

    The modularity matrix is the matrix B = A - <A>, where A is the adjacency
    matrix and <A> is the average adjacency matrix, assuming that the graph
    is described by the configuration model.

    More specifically, the element B_ij of B is defined as
        A_ij - k_i k_j/m
    where k_i(in) is the degree of node i, and were m is the number of edges
    in the graph.

    Parameters
    ----------
    G : Graph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    Returns
    -------
    B : Numpy matrix
      The modularity matrix of G.

    Examples
    --------
    >>> import networkx as nx
    >>> k =[3, 2, 2, 1, 0]
    >>> G = nx.havel_hakimi_graph(k)
    >>> B = nx.modularity_matrix(G)


    See Also
    --------
    to_numpy_matrix
    adjacency_matrix
    laplacian_matrix
    directed_modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    if nodelist is None:
        nodelist = G.nodes()
    A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, format='csr')
    k = A.sum(axis=1)
    m = G.number_of_edges()
    # Expected adjacency matrix
    X = k * k.transpose() / (2 * m)
    return A - X 
Example #3
Source File: lle.py    From GEM with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def learn_embedding(self, graph=None, edge_f=None,
                        is_weighted=False, no_python=False):
        if not graph and not edge_f:
            raise Exception('graph/edge_f needed')
        if not graph:
            graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(len(graph.nodes))
        I_min_A = I_n - A
        u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X.real, (t2 - t1) 
Example #4
Source File: util.py    From region with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def convert_from_geodataframe(gdf):
    """
    Convert a GeoDataFrame to other types representing the contiguity relation
    of the GeoDataFrame's areas.

    Parameters
    ----------
    gdf : GeoDataFrame

    Returns
    -------
    other_formats : tuple
        The 1st entry is a sparse adjacency matrix of type
        :class:`scipy.sparse.csr_matrix`.
        The 2nd entry is a networkx graph.
        The 3rd entry is a dict. Each key is an area and each value is an
        iterable of the key area's neighbors.
        The 4th entry is a PySAL W object.
    """
    w = weights.Rook.from_dataframe(gdf)
    graph = w.to_networkx()
    adj = nx.to_scipy_sparse_matrix(graph)
    neighbor_dict = w.neighbors
    return adj, graph, neighbor_dict, w 
Example #5
Source File: lle.py    From GPF with MIT License 6 votes vote down vote up
def learn_embedding(self):
        graph = self.g.G
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        # print(np.sum(A.todense(), axis=0))
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(graph.number_of_nodes())
        I_min_A = I_n - A
        print(I_min_A)
        u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X, (t2 - t1)
        # I_n = sp.eye(graph.number_of_nodes()) 
Example #6
Source File: data.py    From dcnn with MIT License 6 votes vote down vote up
def parse_cora_sparse():
    path = "%s/../data/cora/" % (current_dir,)

    features, labels, id2index = _parse_cora_features_labels()

    n_papers = len(id2index)
    graph = nx.Graph()

    with open(path + 'cora.cites', 'r') as f:
        for line in f.xreadlines():
            items = line.strip().split('\t')

            tail = id2index[items[0]]
            head = id2index[items[1]]

            graph.add_edge(head, tail)

    adj = nx.to_scipy_sparse_matrix(graph, format='csr')

    return adj.astype('float32'), features.astype('float32'), labels.astype('int32') 
Example #7
Source File: forceatlas2.py    From forceatlas2 with GNU General Public License v3.0 6 votes vote down vote up
def forceatlas2_networkx_layout(self, G, pos=None, iterations=100, weight_attr=None):
        import networkx
        try:
            import cynetworkx
        except ImportError:
            cynetworkx = None

        assert (
            isinstance(G, networkx.classes.graph.Graph)
            or (cynetworkx and isinstance(G, cynetworkx.classes.graph.Graph))
        ), "Not a networkx graph"
        assert isinstance(pos, dict) or (pos is None), "pos must be specified as a dictionary, as in networkx"
        M = networkx.to_scipy_sparse_matrix(G, dtype='f', format='lil', weight=weight_attr)
        if pos is None:
            l = self.forceatlas2(M, pos=None, iterations=iterations)
        else:
            poslist = numpy.asarray([pos[i] for i in G.nodes()])
            l = self.forceatlas2(M, pos=poslist, iterations=iterations)
        return dict(zip(G.nodes(), l))

    # A layout for igraph.
    #
    # This function returns an igraph layout 
Example #8
Source File: lle.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def learn_embedding(self, graph=None, edge_f=None,
                        is_weighted=False, no_python=False):
        if not graph and not edge_f:
            raise Exception('graph/edge_f needed')
        if not graph:
            graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(graph.number_of_nodes())
        I_min_A = I_n - A
        try:
            u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        except:
            u = np.random.randn(A.shape[0], self._d + 1)
            s = np.random.randn(self._d + 1, self._d + 1)
            vt = np.random.randn(self._d + 1, A.shape[0])
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X, (t2 - t1) 
Example #9
Source File: build_gcn.py    From incubator-tvm with Apache License 2.0 6 votes vote down vote up
def prepare_params(g, data):
    params = {}
    params['infeats'] = data.features.astype('float32') # Only support float32 as feature for now

    # Generate adjacency matrix
    adjacency = nx.to_scipy_sparse_matrix(g)
    params['g_data'] = adjacency.data.astype('float32')
    params['indices'] = adjacency.indices.astype('int32')
    params['indptr'] = adjacency.indptr.astype('int32')

    # Normalization w.r.t. node degrees
    degs = [g.in_degree[i] for i in range(g.number_of_nodes())]
    params['norm'] = np.power(degs, -0.5).astype('float32')
    params['norm'] = params['norm'].reshape((params['norm'].shape[0], 1))

    return params 
Example #10
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identity_weighted_graph_matrix(self):
        """Conversion from weighted graph to sparse matrix to weighted graph."""
        A = nx.to_scipy_sparse_matrix(self.G3)
        self.identity_conversion(self.G3, A, nx.Graph()) 
Example #11
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_identity_weighted_digraph_matrix(self):
        """Conversion from weighted digraph to sparse matrix to weighted digraph."""
        A = nx.to_scipy_sparse_matrix(self.G4)
        self.identity_conversion(self.G4, A, nx.DiGraph()) 
Example #12
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_null_raise(self):
        nx.to_scipy_sparse_matrix(nx.Graph()) 
Example #13
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_empty(self):
        G = nx.Graph()
        G.add_node(1)
        M = nx.to_scipy_sparse_matrix(G)
        np_assert_equal(M.todense(), np.matrix([[0]])) 
Example #14
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_ordering(self):
        G = nx.DiGraph()
        G.add_edge(1, 2)
        G.add_edge(2, 3)
        G.add_edge(3, 1)
        M = nx.to_scipy_sparse_matrix(G, nodelist=[3, 2, 1])
        np_assert_equal(M.todense(), np.matrix([[0, 0, 1], [1, 0, 0], [0, 1, 0]])) 
Example #15
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_selfloop_digraph(self):
        G = nx.DiGraph([(1, 1)])
        M = nx.to_scipy_sparse_matrix(G)
        np_assert_equal(M.todense(), np.matrix([[1]])) 
Example #16
Source File: test_layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_adjacency_interface_scipy(self):
        try:
            import scipy
        except ImportError:
            raise SkipTest('scipy not available.')
        A = nx.to_scipy_sparse_matrix(self.Gs, dtype='d')
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
        assert_equal(pos.shape, (6, 2))
        pos = nx.drawing.layout._sparse_spectral(A)
        assert_equal(pos.shape, (6, 2))
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
        assert_equal(pos.shape, (6, 3)) 
Example #17
Source File: modularitymatrix.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def modularity_matrix(G, nodelist=None, weight=None):
    """Return the modularity matrix of G.

    The modularity matrix is the matrix B = A - <A>, where A is the adjacency
    matrix and <A> is the average adjacency matrix, assuming that the graph
    is described by the configuration model.

    More specifically, the element B_ij of B is defined as
        A_ij - k_i k_j / 2 * m
    where k_i(in) is the degree of node i, and were m is the number of edges
    in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
    k_j and m are computed using its value.

    Parameters
    ----------
    G : Graph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used for
       the edge weight.  If None then all edge weights are 1.

    Returns
    -------
    B : Numpy matrix
      The modularity matrix of G.

    Examples
    --------
    >>> import networkx as nx
    >>> k =[3, 2, 2, 1, 0]
    >>> G = nx.havel_hakimi_graph(k)
    >>> B = nx.modularity_matrix(G)


    See Also
    --------
    to_numpy_matrix
    adjacency_matrix
    laplacian_matrix
    directed_modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    if nodelist is None:
        nodelist = list(G)
    A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
                                  format='csr')
    k = A.sum(axis=1)
    m = k.sum() * 0.5
    # Expected adjacency matrix
    X = k * k.transpose() / (2 * m)
    return A - X 
Example #18
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_format_keyword_raise(self):
        WP4 = nx.Graph()
        WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3))
                           for n in range(3))
        P4 = path_graph(4)
        nx.to_scipy_sparse_matrix(P4, format='any_other') 
Example #19
Source File: test_convert_scipy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_identity_digraph_matrix(self):
        "Conversion from digraph to sparse matrix to digraph."
        A = nx.to_scipy_sparse_matrix(self.G2)
        self.identity_conversion(self.G2, A, nx.DiGraph()) 
Example #20
Source File: flow_matrix.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def laplacian_sparse_matrix(G, nodelist=None, weight=None, dtype=None,
                            format='csr'):
    import numpy as np
    import scipy.sparse
    A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
                                  dtype=dtype, format=format)
    (n, n) = A.shape
    data = np.asarray(A.sum(axis=1).T)
    D = scipy.sparse.spdiags(data, 0, n, n, format=format)
    return D - A 
Example #21
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_adjacency_interface_scipy(self):
        try:
            import scipy
        except ImportError:
            raise SkipTest('scipy not available.')
        A = nx.to_scipy_sparse_matrix(self.Gs, dtype='d')
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
        assert_equal(pos.shape, (6, 2))
        pos = nx.drawing.layout._sparse_spectral(A)
        assert_equal(pos.shape, (6, 2))
        pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
        assert_equal(pos.shape, (6, 3)) 
Example #22
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_selfloop_digraph(self):
        G = nx.DiGraph([(1, 1)])
        M = nx.to_scipy_sparse_matrix(G)
        np_assert_equal(M.todense(), np.matrix([[1]])) 
Example #23
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ordering(self):
        G = nx.DiGraph()
        G.add_edge(1, 2)
        G.add_edge(2, 3)
        G.add_edge(3, 1)
        M = nx.to_scipy_sparse_matrix(G, nodelist=[3, 2, 1])
        np_assert_equal(M.todense(), np.matrix([[0, 0, 1], [1, 0, 0], [0, 1, 0]])) 
Example #24
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty(self):
        G = nx.Graph()
        G.add_node(1)
        M = nx.to_scipy_sparse_matrix(G)
        np_assert_equal(M.todense(), np.matrix([[0]])) 
Example #25
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_null_raise(self):
        nx.to_scipy_sparse_matrix(nx.Graph()) 
Example #26
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_format_keyword_raise(self):
        WP4 = nx.Graph()
        WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3))
                           for n in range(3))
        P4 = path_graph(4)
        nx.to_scipy_sparse_matrix(P4, format='any_other') 
Example #27
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_format_keyword(self):
        WP4 = nx.Graph()
        WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3))
                           for n in range(3))
        P4 = path_graph(4)
        A = nx.to_scipy_sparse_matrix(P4, format='csr')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='csc')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='coo')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='bsr')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='lil')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='dia')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='dok')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense()) 
Example #28
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_nodelist(self):
        """Conversion from graph to sparse matrix to graph with nodelist."""
        P4 = path_graph(4)
        P3 = path_graph(3)
        nodelist = list(P3.nodes())
        A = nx.to_scipy_sparse_matrix(P4, nodelist=nodelist)
        GA = nx.Graph(A)
        self.assert_isomorphic(GA, P3)

        # Make nodelist ambiguous by containing duplicates.
        nodelist += [nodelist[0]]
        assert_raises(nx.NetworkXError, nx.to_numpy_matrix, P3,
                      nodelist=nodelist) 
Example #29
Source File: test_convert_scipy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identity_weighted_digraph_matrix(self):
        """Conversion from weighted digraph to sparse matrix to weighted digraph."""
        A = nx.to_scipy_sparse_matrix(self.G4)
        self.identity_conversion(self.G4, A, nx.DiGraph()) 
Example #30
Source File: karate.py    From pytorch_geometric with MIT License 5 votes vote down vote up
def __init__(self, transform=None):
        super(KarateClub, self).__init__('.', transform, None, None)

        G = nx.karate_club_graph()

        adj = nx.to_scipy_sparse_matrix(G).tocoo()
        row = torch.from_numpy(adj.row.astype(np.int64)).to(torch.long)
        col = torch.from_numpy(adj.col.astype(np.int64)).to(torch.long)
        edge_index = torch.stack([row, col], dim=0)
        data = Data(edge_index=edge_index)
        data.num_nodes = edge_index.max().item() + 1
        data.x = torch.eye(data.num_nodes, dtype=torch.float)
        y = [0 if G.nodes[i]['club'] == 'Mr. Hi' else 1 for i in G.nodes]
        data.y = torch.tensor(y)
        self.data, self.slices = self.collate([data])