MCPcopy Create free account
hub / github.com/easy-graph/Easy-Graph / to_scipy_sparse_array

Function to_scipy_sparse_array

easygraph/utils/convert_to_matrix.py:18–143  ·  view source on GitHub ↗

Returns the graph adjacency matrix as a SciPy sparse array. Parameters ---------- G : graph The EasyGraph graph used to construct the sparse matrix. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist`

(G, nodelist=None, dtype=None, weight="weight", format="csr")

Source from the content-addressed store, hash-verified

16
17
18def to_scipy_sparse_array(G, nodelist=None, dtype=None, weight="weight", format="csr"):
19 """Returns the graph adjacency matrix as a SciPy sparse array.
20
21 Parameters
22 ----------
23 G : graph
24 The EasyGraph graph used to construct the sparse matrix.
25
26 nodelist : list, optional
27 The rows and columns are ordered according to the nodes in `nodelist`.
28 If `nodelist` is None, then the ordering is produced by G.nodes().
29
30 dtype : NumPy data-type, optional
31 A valid NumPy dtype used to initialize the array. If None, then the
32 NumPy default is used.
33
34 weight : string or None optional (default='weight')
35 The edge attribute that holds the numerical value used for
36 the edge weight. If None then all edge weights are 1.
37
38 format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
39 The type of the matrix to be returned (default 'csr'). For
40 some algorithms different implementations of sparse matrices
41 can perform better. See [1]_ for details.
42
43 Returns
44 -------
45 A : SciPy sparse array
46 Graph adjacency matrix.
47
48 Notes
49 -----
50 For directed graphs, matrix entry i,j corresponds to an edge from i to j.
51
52 The matrix entries are populated using the edge attribute held in
53 parameter weight. When an edge does not have that attribute, the
54 value of the entry is 1.
55
56 For multiple edges the matrix values are the sums of the edge weights.
57
58 When `nodelist` does not contain every node in `G`, the adjacency matrix
59 is built from the subgraph of `G` that is induced by the nodes in
60 `nodelist`.
61
62 The convention used for self-loop edges in graphs is to assign the
63 diagonal matrix entry value to the weight attribute of the edge
64 (or the number 1 if the edge has no weight attribute). If the
65 alternate convention of doubling the edge weight is desired the
66 resulting Scipy sparse matrix can be modified as follows:
67
68 >>> G = eg.Graph([(1, 1)])
69 >>> A = eg.to_scipy_sparse_array(G)
70 >>> print(A.todense())
71 [[1]]
72 >>> A.setdiag(A.diagonal() * 2)
73 >>> print(A.toarray())
74 [[2]]
75

Callers 1

to_scipy_sparse_matrixFunction · 0.85

Calls 2

nbunch_iterMethod · 0.45
is_directedMethod · 0.45

Tested by

no test coverage detected