ZTWHHH commited on
Commit
4246f2e
·
verified ·
1 Parent(s): 7187212

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc +0 -0
  2. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc +0 -0
  3. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc +0 -0
  4. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc +0 -0
  5. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc +0 -0
  6. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc +0 -0
  7. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc +0 -0
  8. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc +0 -0
  9. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc +0 -0
  10. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc +0 -0
  11. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc +0 -0
  12. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc +0 -0
  13. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc +0 -0
  14. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc +0 -0
  15. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc +0 -0
  16. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc +0 -0
  17. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc +0 -0
  18. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc +0 -0
  19. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc +0 -0
  20. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc +0 -0
  21. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc +0 -0
  22. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc +0 -0
  23. minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc +0 -0
  24. minigpt2/lib/python3.10/site-packages/networkx/linalg/__init__.py +13 -0
  25. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
  26. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc +0 -0
  27. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc +0 -0
  28. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/bethehessianmatrix.cpython-310.pyc +0 -0
  29. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/graphmatrix.cpython-310.pyc +0 -0
  30. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc +0 -0
  31. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc +0 -0
  32. minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc +0 -0
  33. minigpt2/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py +657 -0
  34. minigpt2/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py +465 -0
  35. minigpt2/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py +79 -0
  36. minigpt2/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py +168 -0
  37. minigpt2/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py +617 -0
  38. minigpt2/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py +166 -0
  39. minigpt2/lib/python3.10/site-packages/networkx/linalg/spectrum.py +186 -0
  40. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py +0 -0
  41. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  42. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc +0 -0
  43. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc +0 -0
  44. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_bethehessian.cpython-310.pyc +0 -0
  45. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_graphmatrix.cpython-310.pyc +0 -0
  46. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_laplacian.cpython-310.pyc +0 -0
  47. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_modularity.cpython-310.pyc +0 -0
  48. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_spectrum.cpython-310.pyc +0 -0
  49. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/test_algebraic_connectivity.py +402 -0
  50. minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/test_attrmatrix.py +108 -0
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc ADDED
Binary file (4.32 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc ADDED
Binary file (29.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc ADDED
Binary file (2.23 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc ADDED
Binary file (31.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc ADDED
Binary file (25.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc ADDED
Binary file (5.06 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc ADDED
Binary file (4.79 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc ADDED
Binary file (2.32 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc ADDED
Binary file (5.64 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc ADDED
Binary file (4.22 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc ADDED
Binary file (1.99 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc ADDED
Binary file (4.04 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc ADDED
Binary file (34.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networkx.linalg.attrmatrix import *
2
+ from networkx.linalg import attrmatrix
3
+ from networkx.linalg.spectrum import *
4
+ from networkx.linalg import spectrum
5
+ from networkx.linalg.graphmatrix import *
6
+ from networkx.linalg import graphmatrix
7
+ from networkx.linalg.laplacianmatrix import *
8
+ from networkx.linalg import laplacianmatrix
9
+ from networkx.linalg.algebraicconnectivity import *
10
+ from networkx.linalg.modularitymatrix import *
11
+ from networkx.linalg import modularitymatrix
12
+ from networkx.linalg.bethehessianmatrix import *
13
+ from networkx.linalg import bethehessianmatrix
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (702 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/bethehessianmatrix.cpython-310.pyc ADDED
Binary file (2.96 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/graphmatrix.cpython-310.pyc ADDED
Binary file (5.56 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc ADDED
Binary file (4.71 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc ADDED
Binary file (4.41 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Algebraic connectivity and Fiedler vectors of undirected graphs.
3
+ """
4
+
5
+ from functools import partial
6
+
7
+ import networkx as nx
8
+ from networkx.utils import (
9
+ not_implemented_for,
10
+ np_random_state,
11
+ reverse_cuthill_mckee_ordering,
12
+ )
13
+
14
+ __all__ = [
15
+ "algebraic_connectivity",
16
+ "fiedler_vector",
17
+ "spectral_ordering",
18
+ "spectral_bisection",
19
+ ]
20
+
21
+
22
+ class _PCGSolver:
23
+ """Preconditioned conjugate gradient method.
24
+
25
+ To solve Ax = b:
26
+ M = A.diagonal() # or some other preconditioner
27
+ solver = _PCGSolver(lambda x: A * x, lambda x: M * x)
28
+ x = solver.solve(b)
29
+
30
+ The inputs A and M are functions which compute
31
+ matrix multiplication on the argument.
32
+ A - multiply by the matrix A in Ax=b
33
+ M - multiply by M, the preconditioner surrogate for A
34
+
35
+ Warning: There is no limit on number of iterations.
36
+ """
37
+
38
+ def __init__(self, A, M):
39
+ self._A = A
40
+ self._M = M
41
+
42
+ def solve(self, B, tol):
43
+ import numpy as np
44
+
45
+ # Densifying step - can this be kept sparse?
46
+ B = np.asarray(B)
47
+ X = np.ndarray(B.shape, order="F")
48
+ for j in range(B.shape[1]):
49
+ X[:, j] = self._solve(B[:, j], tol)
50
+ return X
51
+
52
+ def _solve(self, b, tol):
53
+ import numpy as np
54
+ import scipy as sp
55
+
56
+ A = self._A
57
+ M = self._M
58
+ tol *= sp.linalg.blas.dasum(b)
59
+ # Initialize.
60
+ x = np.zeros(b.shape)
61
+ r = b.copy()
62
+ z = M(r)
63
+ rz = sp.linalg.blas.ddot(r, z)
64
+ p = z.copy()
65
+ # Iterate.
66
+ while True:
67
+ Ap = A(p)
68
+ alpha = rz / sp.linalg.blas.ddot(p, Ap)
69
+ x = sp.linalg.blas.daxpy(p, x, a=alpha)
70
+ r = sp.linalg.blas.daxpy(Ap, r, a=-alpha)
71
+ if sp.linalg.blas.dasum(r) < tol:
72
+ return x
73
+ z = M(r)
74
+ beta = sp.linalg.blas.ddot(r, z)
75
+ beta, rz = beta / rz, beta
76
+ p = sp.linalg.blas.daxpy(p, z, a=beta)
77
+
78
+
79
+ class _LUSolver:
80
+ """LU factorization.
81
+
82
+ To solve Ax = b:
83
+ solver = _LUSolver(A)
84
+ x = solver.solve(b)
85
+
86
+ optional argument `tol` on solve method is ignored but included
87
+ to match _PCGsolver API.
88
+ """
89
+
90
+ def __init__(self, A):
91
+ import scipy as sp
92
+
93
+ self._LU = sp.sparse.linalg.splu(
94
+ A,
95
+ permc_spec="MMD_AT_PLUS_A",
96
+ diag_pivot_thresh=0.0,
97
+ options={"Equil": True, "SymmetricMode": True},
98
+ )
99
+
100
+ def solve(self, B, tol=None):
101
+ import numpy as np
102
+
103
+ B = np.asarray(B)
104
+ X = np.ndarray(B.shape, order="F")
105
+ for j in range(B.shape[1]):
106
+ X[:, j] = self._LU.solve(B[:, j])
107
+ return X
108
+
109
+
110
+ def _preprocess_graph(G, weight):
111
+ """Compute edge weights and eliminate zero-weight edges."""
112
+ if G.is_directed():
113
+ H = nx.MultiGraph()
114
+ H.add_nodes_from(G)
115
+ H.add_weighted_edges_from(
116
+ ((u, v, e.get(weight, 1.0)) for u, v, e in G.edges(data=True) if u != v),
117
+ weight=weight,
118
+ )
119
+ G = H
120
+ if not G.is_multigraph():
121
+ edges = (
122
+ (u, v, abs(e.get(weight, 1.0))) for u, v, e in G.edges(data=True) if u != v
123
+ )
124
+ else:
125
+ edges = (
126
+ (u, v, sum(abs(e.get(weight, 1.0)) for e in G[u][v].values()))
127
+ for u, v in G.edges()
128
+ if u != v
129
+ )
130
+ H = nx.Graph()
131
+ H.add_nodes_from(G)
132
+ H.add_weighted_edges_from((u, v, e) for u, v, e in edges if e != 0)
133
+ return H
134
+
135
+
136
+ def _rcm_estimate(G, nodelist):
137
+ """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering."""
138
+ import numpy as np
139
+
140
+ G = G.subgraph(nodelist)
141
+ order = reverse_cuthill_mckee_ordering(G)
142
+ n = len(nodelist)
143
+ index = dict(zip(nodelist, range(n)))
144
+ x = np.ndarray(n, dtype=float)
145
+ for i, u in enumerate(order):
146
+ x[index[u]] = i
147
+ x -= (n - 1) / 2.0
148
+ return x
149
+
150
+
151
+ def _tracemin_fiedler(L, X, normalized, tol, method):
152
+ """Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
153
+
154
+ The Fiedler vector of a connected undirected graph is the eigenvector
155
+ corresponding to the second smallest eigenvalue of the Laplacian matrix
156
+ of the graph. This function starts with the Laplacian L, not the Graph.
157
+
158
+ Parameters
159
+ ----------
160
+ L : Laplacian of a possibly weighted or normalized, but undirected graph
161
+
162
+ X : Initial guess for a solution. Usually a matrix of random numbers.
163
+ This function allows more than one column in X to identify more than
164
+ one eigenvector if desired.
165
+
166
+ normalized : bool
167
+ Whether the normalized Laplacian matrix is used.
168
+
169
+ tol : float
170
+ Tolerance of relative residual in eigenvalue computation.
171
+ Warning: There is no limit on number of iterations.
172
+
173
+ method : string
174
+ Should be 'tracemin_pcg' or 'tracemin_lu'.
175
+ Otherwise exception is raised.
176
+
177
+ Returns
178
+ -------
179
+ sigma, X : Two NumPy arrays of floats.
180
+ The lowest eigenvalues and corresponding eigenvectors of L.
181
+ The size of input X determines the size of these outputs.
182
+ As this is for Fiedler vectors, the zero eigenvalue (and
183
+ constant eigenvector) are avoided.
184
+ """
185
+ import numpy as np
186
+ import scipy as sp
187
+
188
+ n = X.shape[0]
189
+
190
+ if normalized:
191
+ # Form the normalized Laplacian matrix and determine the eigenvector of
192
+ # its nullspace.
193
+ e = np.sqrt(L.diagonal())
194
+ # TODO: rm csr_array wrapper when spdiags array creation becomes available
195
+ D = sp.sparse.csr_array(sp.sparse.spdiags(1 / e, 0, n, n, format="csr"))
196
+ L = D @ L @ D
197
+ e *= 1.0 / np.linalg.norm(e, 2)
198
+
199
+ if normalized:
200
+
201
+ def project(X):
202
+ """Make X orthogonal to the nullspace of L."""
203
+ X = np.asarray(X)
204
+ for j in range(X.shape[1]):
205
+ X[:, j] -= (X[:, j] @ e) * e
206
+
207
+ else:
208
+
209
+ def project(X):
210
+ """Make X orthogonal to the nullspace of L."""
211
+ X = np.asarray(X)
212
+ for j in range(X.shape[1]):
213
+ X[:, j] -= X[:, j].sum() / n
214
+
215
+ if method == "tracemin_pcg":
216
+ D = L.diagonal().astype(float)
217
+ solver = _PCGSolver(lambda x: L @ x, lambda x: D * x)
218
+ elif method == "tracemin_lu":
219
+ # Convert A to CSC to suppress SparseEfficiencyWarning.
220
+ A = sp.sparse.csc_array(L, dtype=float, copy=True)
221
+ # Force A to be nonsingular. Since A is the Laplacian matrix of a
222
+ # connected graph, its rank deficiency is one, and thus one diagonal
223
+ # element needs to modified. Changing to infinity forces a zero in the
224
+ # corresponding element in the solution.
225
+ i = (A.indptr[1:] - A.indptr[:-1]).argmax()
226
+ A[i, i] = np.inf
227
+ solver = _LUSolver(A)
228
+ else:
229
+ raise nx.NetworkXError(f"Unknown linear system solver: {method}")
230
+
231
+ # Initialize.
232
+ Lnorm = abs(L).sum(axis=1).flatten().max()
233
+ project(X)
234
+ W = np.ndarray(X.shape, order="F")
235
+
236
+ while True:
237
+ # Orthonormalize X.
238
+ X = np.linalg.qr(X)[0]
239
+ # Compute iteration matrix H.
240
+ W[:, :] = L @ X
241
+ H = X.T @ W
242
+ sigma, Y = sp.linalg.eigh(H, overwrite_a=True)
243
+ # Compute the Ritz vectors.
244
+ X = X @ Y
245
+ # Test for convergence exploiting the fact that L * X == W * Y.
246
+ res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm
247
+ if res < tol:
248
+ break
249
+ # Compute X = L \ X / (X' * (L \ X)).
250
+ # L \ X can have an arbitrary projection on the nullspace of L,
251
+ # which will be eliminated.
252
+ W[:, :] = solver.solve(X, tol)
253
+ X = (sp.linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order.
254
+ project(X)
255
+
256
+ return sigma, np.asarray(X)
257
+
258
+
259
+ def _get_fiedler_func(method):
260
+ """Returns a function that solves the Fiedler eigenvalue problem."""
261
+ import numpy as np
262
+
263
+ if method == "tracemin": # old style keyword <v2.1
264
+ method = "tracemin_pcg"
265
+ if method in ("tracemin_pcg", "tracemin_lu"):
266
+
267
+ def find_fiedler(L, x, normalized, tol, seed):
268
+ q = 1 if method == "tracemin_pcg" else min(4, L.shape[0] - 1)
269
+ X = np.asarray(seed.normal(size=(q, L.shape[0]))).T
270
+ sigma, X = _tracemin_fiedler(L, X, normalized, tol, method)
271
+ return sigma[0], X[:, 0]
272
+
273
+ elif method == "lanczos" or method == "lobpcg":
274
+
275
+ def find_fiedler(L, x, normalized, tol, seed):
276
+ import scipy as sp
277
+
278
+ L = sp.sparse.csc_array(L, dtype=float)
279
+ n = L.shape[0]
280
+ if normalized:
281
+ # TODO: rm csc_array wrapping when spdiags array becomes available
282
+ D = sp.sparse.csc_array(
283
+ sp.sparse.spdiags(
284
+ 1.0 / np.sqrt(L.diagonal()), [0], n, n, format="csc"
285
+ )
286
+ )
287
+ L = D @ L @ D
288
+ if method == "lanczos" or n < 10:
289
+ # Avoid LOBPCG when n < 10 due to
290
+ # https://github.com/scipy/scipy/issues/3592
291
+ # https://github.com/scipy/scipy/pull/3594
292
+ sigma, X = sp.sparse.linalg.eigsh(
293
+ L, 2, which="SM", tol=tol, return_eigenvectors=True
294
+ )
295
+ return sigma[1], X[:, 1]
296
+ else:
297
+ X = np.asarray(np.atleast_2d(x).T)
298
+ # TODO: rm csr_array wrapping when spdiags array becomes available
299
+ M = sp.sparse.csr_array(sp.sparse.spdiags(1.0 / L.diagonal(), 0, n, n))
300
+ Y = np.ones(n)
301
+ if normalized:
302
+ Y /= D.diagonal()
303
+ sigma, X = sp.sparse.linalg.lobpcg(
304
+ L, X, M=M, Y=np.atleast_2d(Y).T, tol=tol, maxiter=n, largest=False
305
+ )
306
+ return sigma[0], X[:, 0]
307
+
308
+ else:
309
+ raise nx.NetworkXError(f"unknown method {method!r}.")
310
+
311
+ return find_fiedler
312
+
313
+
314
+ @not_implemented_for("directed")
315
+ @np_random_state(5)
316
+ @nx._dispatchable(edge_attrs="weight")
317
+ def algebraic_connectivity(
318
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
319
+ ):
320
+ r"""Returns the algebraic connectivity of an undirected graph.
321
+
322
+ The algebraic connectivity of a connected undirected graph is the second
323
+ smallest eigenvalue of its Laplacian matrix.
324
+
325
+ Parameters
326
+ ----------
327
+ G : NetworkX graph
328
+ An undirected graph.
329
+
330
+ weight : object, optional (default: None)
331
+ The data key used to determine the weight of each edge. If None, then
332
+ each edge has unit weight.
333
+
334
+ normalized : bool, optional (default: False)
335
+ Whether the normalized Laplacian matrix is used.
336
+
337
+ tol : float, optional (default: 1e-8)
338
+ Tolerance of relative residual in eigenvalue computation.
339
+
340
+ method : string, optional (default: 'tracemin_pcg')
341
+ Method of eigenvalue computation. It must be one of the tracemin
342
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
343
+ or 'lobpcg' (LOBPCG).
344
+
345
+ The TraceMIN algorithm uses a linear system solver. The following
346
+ values allow specifying the solver to be used.
347
+
348
+ =============== ========================================
349
+ Value Solver
350
+ =============== ========================================
351
+ 'tracemin_pcg' Preconditioned conjugate gradient method
352
+ 'tracemin_lu' LU factorization
353
+ =============== ========================================
354
+
355
+ seed : integer, random_state, or None (default)
356
+ Indicator of random number generation state.
357
+ See :ref:`Randomness<randomness>`.
358
+
359
+ Returns
360
+ -------
361
+ algebraic_connectivity : float
362
+ Algebraic connectivity.
363
+
364
+ Raises
365
+ ------
366
+ NetworkXNotImplemented
367
+ If G is directed.
368
+
369
+ NetworkXError
370
+ If G has less than two nodes.
371
+
372
+ Notes
373
+ -----
374
+ Edge weights are interpreted by their absolute values. For MultiGraph's,
375
+ weights of parallel edges are summed. Zero-weighted edges are ignored.
376
+
377
+ See Also
378
+ --------
379
+ laplacian_matrix
380
+
381
+ Examples
382
+ --------
383
+ For undirected graphs algebraic connectivity can tell us if a graph is connected or not
384
+ `G` is connected iff ``algebraic_connectivity(G) > 0``:
385
+
386
+ >>> G = nx.complete_graph(5)
387
+ >>> nx.algebraic_connectivity(G) > 0
388
+ True
389
+ >>> G.add_node(10) # G is no longer connected
390
+ >>> nx.algebraic_connectivity(G) > 0
391
+ False
392
+
393
+ """
394
+ if len(G) < 2:
395
+ raise nx.NetworkXError("graph has less than two nodes.")
396
+ G = _preprocess_graph(G, weight)
397
+ if not nx.is_connected(G):
398
+ return 0.0
399
+
400
+ L = nx.laplacian_matrix(G)
401
+ if L.shape[0] == 2:
402
+ return 2.0 * float(L[0, 0]) if not normalized else 2.0
403
+
404
+ find_fiedler = _get_fiedler_func(method)
405
+ x = None if method != "lobpcg" else _rcm_estimate(G, G)
406
+ sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
407
+ return float(sigma)
408
+
409
+
410
+ @not_implemented_for("directed")
411
+ @np_random_state(5)
412
+ @nx._dispatchable(edge_attrs="weight")
413
+ def fiedler_vector(
414
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
415
+ ):
416
+ """Returns the Fiedler vector of a connected undirected graph.
417
+
418
+ The Fiedler vector of a connected undirected graph is the eigenvector
419
+ corresponding to the second smallest eigenvalue of the Laplacian matrix
420
+ of the graph.
421
+
422
+ Parameters
423
+ ----------
424
+ G : NetworkX graph
425
+ An undirected graph.
426
+
427
+ weight : object, optional (default: None)
428
+ The data key used to determine the weight of each edge. If None, then
429
+ each edge has unit weight.
430
+
431
+ normalized : bool, optional (default: False)
432
+ Whether the normalized Laplacian matrix is used.
433
+
434
+ tol : float, optional (default: 1e-8)
435
+ Tolerance of relative residual in eigenvalue computation.
436
+
437
+ method : string, optional (default: 'tracemin_pcg')
438
+ Method of eigenvalue computation. It must be one of the tracemin
439
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
440
+ or 'lobpcg' (LOBPCG).
441
+
442
+ The TraceMIN algorithm uses a linear system solver. The following
443
+ values allow specifying the solver to be used.
444
+
445
+ =============== ========================================
446
+ Value Solver
447
+ =============== ========================================
448
+ 'tracemin_pcg' Preconditioned conjugate gradient method
449
+ 'tracemin_lu' LU factorization
450
+ =============== ========================================
451
+
452
+ seed : integer, random_state, or None (default)
453
+ Indicator of random number generation state.
454
+ See :ref:`Randomness<randomness>`.
455
+
456
+ Returns
457
+ -------
458
+ fiedler_vector : NumPy array of floats.
459
+ Fiedler vector.
460
+
461
+ Raises
462
+ ------
463
+ NetworkXNotImplemented
464
+ If G is directed.
465
+
466
+ NetworkXError
467
+ If G has less than two nodes or is not connected.
468
+
469
+ Notes
470
+ -----
471
+ Edge weights are interpreted by their absolute values. For MultiGraph's,
472
+ weights of parallel edges are summed. Zero-weighted edges are ignored.
473
+
474
+ See Also
475
+ --------
476
+ laplacian_matrix
477
+
478
+ Examples
479
+ --------
480
+ Given a connected graph the signs of the values in the Fiedler vector can be
481
+ used to partition the graph into two components.
482
+
483
+ >>> G = nx.barbell_graph(5, 0)
484
+ >>> nx.fiedler_vector(G, normalized=True, seed=1)
485
+ array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899,
486
+ 0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129])
487
+
488
+ The connected components are the two 5-node cliques of the barbell graph.
489
+ """
490
+ import numpy as np
491
+
492
+ if len(G) < 2:
493
+ raise nx.NetworkXError("graph has less than two nodes.")
494
+ G = _preprocess_graph(G, weight)
495
+ if not nx.is_connected(G):
496
+ raise nx.NetworkXError("graph is not connected.")
497
+
498
+ if len(G) == 2:
499
+ return np.array([1.0, -1.0])
500
+
501
+ find_fiedler = _get_fiedler_func(method)
502
+ L = nx.laplacian_matrix(G)
503
+ x = None if method != "lobpcg" else _rcm_estimate(G, G)
504
+ sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
505
+ return fiedler
506
+
507
+
508
+ @np_random_state(5)
509
+ @nx._dispatchable(edge_attrs="weight")
510
+ def spectral_ordering(
511
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
512
+ ):
513
+ """Compute the spectral_ordering of a graph.
514
+
515
+ The spectral ordering of a graph is an ordering of its nodes where nodes
516
+ in the same weakly connected components appear contiguous and ordered by
517
+ their corresponding elements in the Fiedler vector of the component.
518
+
519
+ Parameters
520
+ ----------
521
+ G : NetworkX graph
522
+ A graph.
523
+
524
+ weight : object, optional (default: None)
525
+ The data key used to determine the weight of each edge. If None, then
526
+ each edge has unit weight.
527
+
528
+ normalized : bool, optional (default: False)
529
+ Whether the normalized Laplacian matrix is used.
530
+
531
+ tol : float, optional (default: 1e-8)
532
+ Tolerance of relative residual in eigenvalue computation.
533
+
534
+ method : string, optional (default: 'tracemin_pcg')
535
+ Method of eigenvalue computation. It must be one of the tracemin
536
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
537
+ or 'lobpcg' (LOBPCG).
538
+
539
+ The TraceMIN algorithm uses a linear system solver. The following
540
+ values allow specifying the solver to be used.
541
+
542
+ =============== ========================================
543
+ Value Solver
544
+ =============== ========================================
545
+ 'tracemin_pcg' Preconditioned conjugate gradient method
546
+ 'tracemin_lu' LU factorization
547
+ =============== ========================================
548
+
549
+ seed : integer, random_state, or None (default)
550
+ Indicator of random number generation state.
551
+ See :ref:`Randomness<randomness>`.
552
+
553
+ Returns
554
+ -------
555
+ spectral_ordering : NumPy array of floats.
556
+ Spectral ordering of nodes.
557
+
558
+ Raises
559
+ ------
560
+ NetworkXError
561
+ If G is empty.
562
+
563
+ Notes
564
+ -----
565
+ Edge weights are interpreted by their absolute values. For MultiGraph's,
566
+ weights of parallel edges are summed. Zero-weighted edges are ignored.
567
+
568
+ See Also
569
+ --------
570
+ laplacian_matrix
571
+ """
572
+ if len(G) == 0:
573
+ raise nx.NetworkXError("graph is empty.")
574
+ G = _preprocess_graph(G, weight)
575
+
576
+ find_fiedler = _get_fiedler_func(method)
577
+ order = []
578
+ for component in nx.connected_components(G):
579
+ size = len(component)
580
+ if size > 2:
581
+ L = nx.laplacian_matrix(G, component)
582
+ x = None if method != "lobpcg" else _rcm_estimate(G, component)
583
+ sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
584
+ sort_info = zip(fiedler, range(size), component)
585
+ order.extend(u for x, c, u in sorted(sort_info))
586
+ else:
587
+ order.extend(component)
588
+
589
+ return order
590
+
591
+
592
+ @nx._dispatchable(edge_attrs="weight")
593
+ def spectral_bisection(
594
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
595
+ ):
596
+ """Bisect the graph using the Fiedler vector.
597
+
598
+ This method uses the Fiedler vector to bisect a graph.
599
+ The partition is defined by the nodes which are associated with
600
+ either positive or negative values in the vector.
601
+
602
+ Parameters
603
+ ----------
604
+ G : NetworkX Graph
605
+
606
+ weight : str, optional (default: weight)
607
+ The data key used to determine the weight of each edge. If None, then
608
+ each edge has unit weight.
609
+
610
+ normalized : bool, optional (default: False)
611
+ Whether the normalized Laplacian matrix is used.
612
+
613
+ tol : float, optional (default: 1e-8)
614
+ Tolerance of relative residual in eigenvalue computation.
615
+
616
+ method : string, optional (default: 'tracemin_pcg')
617
+ Method of eigenvalue computation. It must be one of the tracemin
618
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
619
+ or 'lobpcg' (LOBPCG).
620
+
621
+ The TraceMIN algorithm uses a linear system solver. The following
622
+ values allow specifying the solver to be used.
623
+
624
+ =============== ========================================
625
+ Value Solver
626
+ =============== ========================================
627
+ 'tracemin_pcg' Preconditioned conjugate gradient method
628
+ 'tracemin_lu' LU factorization
629
+ =============== ========================================
630
+
631
+ seed : integer, random_state, or None (default)
632
+ Indicator of random number generation state.
633
+ See :ref:`Randomness<randomness>`.
634
+
635
+ Returns
636
+ -------
637
+ bisection : tuple of sets
638
+ Sets with the bisection of nodes
639
+
640
+ Examples
641
+ --------
642
+ >>> G = nx.barbell_graph(3, 0)
643
+ >>> nx.spectral_bisection(G)
644
+ ({0, 1, 2}, {3, 4, 5})
645
+
646
+ References
647
+ ----------
648
+ .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370
649
+ Oxford University Press 2011.
650
+ """
651
+ import numpy as np
652
+
653
+ v = nx.fiedler_vector(G, weight, normalized, tol, method, seed)
654
+ nodes = np.array(list(G))
655
+ pos_vals = v >= 0
656
+
657
+ return set(nodes[~pos_vals].tolist()), set(nodes[pos_vals].tolist())
minigpt2/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions for constructing matrix-like objects from graph attributes.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["attr_matrix", "attr_sparse_matrix"]
8
+
9
+
10
+ def _node_value(G, node_attr):
11
+ """Returns a function that returns a value from G.nodes[u].
12
+
13
+ We return a function expecting a node as its sole argument. Then, in the
14
+ simplest scenario, the returned function will return G.nodes[u][node_attr].
15
+ However, we also handle the case when `node_attr` is None or when it is a
16
+ function itself.
17
+
18
+ Parameters
19
+ ----------
20
+ G : graph
21
+ A NetworkX graph
22
+
23
+ node_attr : {None, str, callable}
24
+ Specification of how the value of the node attribute should be obtained
25
+ from the node attribute dictionary.
26
+
27
+ Returns
28
+ -------
29
+ value : function
30
+ A function expecting a node as its sole argument. The function will
31
+ returns a value from G.nodes[u] that depends on `edge_attr`.
32
+
33
+ """
34
+ if node_attr is None:
35
+
36
+ def value(u):
37
+ return u
38
+
39
+ elif not callable(node_attr):
40
+ # assume it is a key for the node attribute dictionary
41
+ def value(u):
42
+ return G.nodes[u][node_attr]
43
+
44
+ else:
45
+ # Advanced: Allow users to specify something else.
46
+ #
47
+ # For example,
48
+ # node_attr = lambda u: G.nodes[u].get('size', .5) * 3
49
+ #
50
+ value = node_attr
51
+
52
+ return value
53
+
54
+
55
+ def _edge_value(G, edge_attr):
56
+ """Returns a function that returns a value from G[u][v].
57
+
58
+ Suppose there exists an edge between u and v. Then we return a function
59
+ expecting u and v as arguments. For Graph and DiGraph, G[u][v] is
60
+ the edge attribute dictionary, and the function (essentially) returns
61
+ G[u][v][edge_attr]. However, we also handle cases when `edge_attr` is None
62
+ and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v]
63
+ is a dictionary of all edges between u and v. In this case, the returned
64
+ function sums the value of `edge_attr` for every edge between u and v.
65
+
66
+ Parameters
67
+ ----------
68
+ G : graph
69
+ A NetworkX graph
70
+
71
+ edge_attr : {None, str, callable}
72
+ Specification of how the value of the edge attribute should be obtained
73
+ from the edge attribute dictionary, G[u][v]. For multigraphs, G[u][v]
74
+ is a dictionary of all the edges between u and v. This allows for
75
+ special treatment of multiedges.
76
+
77
+ Returns
78
+ -------
79
+ value : function
80
+ A function expecting two nodes as parameters. The nodes should
81
+ represent the from- and to- node of an edge. The function will
82
+ return a value from G[u][v] that depends on `edge_attr`.
83
+
84
+ """
85
+
86
+ if edge_attr is None:
87
+ # topological count of edges
88
+
89
+ if G.is_multigraph():
90
+
91
+ def value(u, v):
92
+ return len(G[u][v])
93
+
94
+ else:
95
+
96
+ def value(u, v):
97
+ return 1
98
+
99
+ elif not callable(edge_attr):
100
+ # assume it is a key for the edge attribute dictionary
101
+
102
+ if edge_attr == "weight":
103
+ # provide a default value
104
+ if G.is_multigraph():
105
+
106
+ def value(u, v):
107
+ return sum(d.get(edge_attr, 1) for d in G[u][v].values())
108
+
109
+ else:
110
+
111
+ def value(u, v):
112
+ return G[u][v].get(edge_attr, 1)
113
+
114
+ else:
115
+ # otherwise, the edge attribute MUST exist for each edge
116
+ if G.is_multigraph():
117
+
118
+ def value(u, v):
119
+ return sum(d[edge_attr] for d in G[u][v].values())
120
+
121
+ else:
122
+
123
+ def value(u, v):
124
+ return G[u][v][edge_attr]
125
+
126
+ else:
127
+ # Advanced: Allow users to specify something else.
128
+ #
129
+ # Alternative default value:
130
+ # edge_attr = lambda u,v: G[u][v].get('thickness', .5)
131
+ #
132
+ # Function on an attribute:
133
+ # edge_attr = lambda u,v: abs(G[u][v]['weight'])
134
+ #
135
+ # Handle Multi(Di)Graphs differently:
136
+ # edge_attr = lambda u,v: numpy.prod([d['size'] for d in G[u][v].values()])
137
+ #
138
+ # Ignore multiple edges
139
+ # edge_attr = lambda u,v: 1 if len(G[u][v]) else 0
140
+ #
141
+ value = edge_attr
142
+
143
+ return value
144
+
145
+
146
+ @nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
147
+ def attr_matrix(
148
+ G,
149
+ edge_attr=None,
150
+ node_attr=None,
151
+ normalized=False,
152
+ rc_order=None,
153
+ dtype=None,
154
+ order=None,
155
+ ):
156
+ """Returns the attribute matrix using attributes from `G` as a numpy array.
157
+
158
+ If only `G` is passed in, then the adjacency matrix is constructed.
159
+
160
+ Let A be a discrete set of values for the node attribute `node_attr`. Then
161
+ the elements of A represent the rows and columns of the constructed matrix.
162
+ Now, iterate through every edge e=(u,v) in `G` and consider the value
163
+ of the edge attribute `edge_attr`. If ua and va are the values of the
164
+ node attribute `node_attr` for u and v, respectively, then the value of
165
+ the edge attribute is added to the matrix element at (ua, va).
166
+
167
+ Parameters
168
+ ----------
169
+ G : graph
170
+ The NetworkX graph used to construct the attribute matrix.
171
+
172
+ edge_attr : str, optional
173
+ Each element of the matrix represents a running total of the
174
+ specified edge attribute for edges whose node attributes correspond
175
+ to the rows/cols of the matrix. The attribute must be present for
176
+ all edges in the graph. If no attribute is specified, then we
177
+ just count the number of edges whose node attributes correspond
178
+ to the matrix element.
179
+
180
+ node_attr : str, optional
181
+ Each row and column in the matrix represents a particular value
182
+ of the node attribute. The attribute must be present for all nodes
183
+ in the graph. Note, the values of this attribute should be reliably
184
+ hashable. So, float values are not recommended. If no attribute is
185
+ specified, then the rows and columns will be the nodes of the graph.
186
+
187
+ normalized : bool, optional
188
+ If True, then each row is normalized by the summation of its values.
189
+
190
+ rc_order : list, optional
191
+ A list of the node attribute values. This list specifies the ordering
192
+ of rows and columns of the array. If no ordering is provided, then
193
+ the ordering will be random (and also, a return value).
194
+
195
+ Other Parameters
196
+ ----------------
197
+ dtype : NumPy data-type, optional
198
+ A valid NumPy dtype used to initialize the array. Keep in mind certain
199
+ dtypes can yield unexpected results if the array is to be normalized.
200
+ The parameter is passed to numpy.zeros(). If unspecified, the NumPy
201
+ default is used.
202
+
203
+ order : {'C', 'F'}, optional
204
+ Whether to store multidimensional data in C- or Fortran-contiguous
205
+ (row- or column-wise) order in memory. This parameter is passed to
206
+ numpy.zeros(). If unspecified, the NumPy default is used.
207
+
208
+ Returns
209
+ -------
210
+ M : 2D NumPy ndarray
211
+ The attribute matrix.
212
+
213
+ ordering : list
214
+ If `rc_order` was specified, then only the attribute matrix is returned.
215
+ However, if `rc_order` was None, then the ordering used to construct
216
+ the matrix is returned as well.
217
+
218
+ Examples
219
+ --------
220
+ Construct an adjacency matrix:
221
+
222
+ >>> G = nx.Graph()
223
+ >>> G.add_edge(0, 1, thickness=1, weight=3)
224
+ >>> G.add_edge(0, 2, thickness=2)
225
+ >>> G.add_edge(1, 2, thickness=3)
226
+ >>> nx.attr_matrix(G, rc_order=[0, 1, 2])
227
+ array([[0., 1., 1.],
228
+ [1., 0., 1.],
229
+ [1., 1., 0.]])
230
+
231
+ Alternatively, we can obtain the matrix describing edge thickness.
232
+
233
+ >>> nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
234
+ array([[0., 1., 2.],
235
+ [1., 0., 3.],
236
+ [2., 3., 0.]])
237
+
238
+ We can also color the nodes and ask for the probability distribution over
239
+ all edges (u,v) describing:
240
+
241
+ Pr(v has color Y | u has color X)
242
+
243
+ >>> G.nodes[0]["color"] = "red"
244
+ >>> G.nodes[1]["color"] = "red"
245
+ >>> G.nodes[2]["color"] = "blue"
246
+ >>> rc = ["red", "blue"]
247
+ >>> nx.attr_matrix(G, node_attr="color", normalized=True, rc_order=rc)
248
+ array([[0.33333333, 0.66666667],
249
+ [1. , 0. ]])
250
+
251
+ For example, the above tells us that for all edges (u,v):
252
+
253
+ Pr( v is red | u is red) = 1/3
254
+ Pr( v is blue | u is red) = 2/3
255
+
256
+ Pr( v is red | u is blue) = 1
257
+ Pr( v is blue | u is blue) = 0
258
+
259
+ Finally, we can obtain the total weights listed by the node colors.
260
+
261
+ >>> nx.attr_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
262
+ array([[3., 2.],
263
+ [2., 0.]])
264
+
265
+ Thus, the total weight over all edges (u,v) with u and v having colors:
266
+
267
+ (red, red) is 3 # the sole contribution is from edge (0,1)
268
+ (red, blue) is 2 # contributions from edges (0,2) and (1,2)
269
+ (blue, red) is 2 # same as (red, blue) since graph is undirected
270
+ (blue, blue) is 0 # there are no edges with blue endpoints
271
+
272
+ """
273
+ import numpy as np
274
+
275
+ edge_value = _edge_value(G, edge_attr)
276
+ node_value = _node_value(G, node_attr)
277
+
278
+ if rc_order is None:
279
+ ordering = list({node_value(n) for n in G})
280
+ else:
281
+ ordering = rc_order
282
+
283
+ N = len(ordering)
284
+ undirected = not G.is_directed()
285
+ index = dict(zip(ordering, range(N)))
286
+ M = np.zeros((N, N), dtype=dtype, order=order)
287
+
288
+ seen = set()
289
+ for u, nbrdict in G.adjacency():
290
+ for v in nbrdict:
291
+ # Obtain the node attribute values.
292
+ i, j = index[node_value(u)], index[node_value(v)]
293
+ if v not in seen:
294
+ M[i, j] += edge_value(u, v)
295
+ if undirected:
296
+ M[j, i] = M[i, j]
297
+
298
+ if undirected:
299
+ seen.add(u)
300
+
301
+ if normalized:
302
+ M /= M.sum(axis=1).reshape((N, 1))
303
+
304
+ if rc_order is None:
305
+ return M, ordering
306
+ else:
307
+ return M
308
+
309
+
310
+ @nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
311
+ def attr_sparse_matrix(
312
+ G, edge_attr=None, node_attr=None, normalized=False, rc_order=None, dtype=None
313
+ ):
314
+ """Returns a SciPy sparse array using attributes from G.
315
+
316
+ If only `G` is passed in, then the adjacency matrix is constructed.
317
+
318
+ Let A be a discrete set of values for the node attribute `node_attr`. Then
319
+ the elements of A represent the rows and columns of the constructed matrix.
320
+ Now, iterate through every edge e=(u,v) in `G` and consider the value
321
+ of the edge attribute `edge_attr`. If ua and va are the values of the
322
+ node attribute `node_attr` for u and v, respectively, then the value of
323
+ the edge attribute is added to the matrix element at (ua, va).
324
+
325
+ Parameters
326
+ ----------
327
+ G : graph
328
+ The NetworkX graph used to construct the NumPy matrix.
329
+
330
+ edge_attr : str, optional
331
+ Each element of the matrix represents a running total of the
332
+ specified edge attribute for edges whose node attributes correspond
333
+ to the rows/cols of the matrix. The attribute must be present for
334
+ all edges in the graph. If no attribute is specified, then we
335
+ just count the number of edges whose node attributes correspond
336
+ to the matrix element.
337
+
338
+ node_attr : str, optional
339
+ Each row and column in the matrix represents a particular value
340
+ of the node attribute. The attribute must be present for all nodes
341
+ in the graph. Note, the values of this attribute should be reliably
342
+ hashable. So, float values are not recommended. If no attribute is
343
+ specified, then the rows and columns will be the nodes of the graph.
344
+
345
+ normalized : bool, optional
346
+ If True, then each row is normalized by the summation of its values.
347
+
348
+ rc_order : list, optional
349
+ A list of the node attribute values. This list specifies the ordering
350
+ of rows and columns of the array. If no ordering is provided, then
351
+ the ordering will be random (and also, a return value).
352
+
353
+ Other Parameters
354
+ ----------------
355
+ dtype : NumPy data-type, optional
356
+ A valid NumPy dtype used to initialize the array. Keep in mind certain
357
+ dtypes can yield unexpected results if the array is to be normalized.
358
+ The parameter is passed to numpy.zeros(). If unspecified, the NumPy
359
+ default is used.
360
+
361
+ Returns
362
+ -------
363
+ M : SciPy sparse array
364
+ The attribute matrix.
365
+
366
+ ordering : list
367
+ If `rc_order` was specified, then only the matrix is returned.
368
+ However, if `rc_order` was None, then the ordering used to construct
369
+ the matrix is returned as well.
370
+
371
+ Examples
372
+ --------
373
+ Construct an adjacency matrix:
374
+
375
+ >>> G = nx.Graph()
376
+ >>> G.add_edge(0, 1, thickness=1, weight=3)
377
+ >>> G.add_edge(0, 2, thickness=2)
378
+ >>> G.add_edge(1, 2, thickness=3)
379
+ >>> M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2])
380
+ >>> M.toarray()
381
+ array([[0., 1., 1.],
382
+ [1., 0., 1.],
383
+ [1., 1., 0.]])
384
+
385
+ Alternatively, we can obtain the matrix describing edge thickness.
386
+
387
+ >>> M = nx.attr_sparse_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
388
+ >>> M.toarray()
389
+ array([[0., 1., 2.],
390
+ [1., 0., 3.],
391
+ [2., 3., 0.]])
392
+
393
+ We can also color the nodes and ask for the probability distribution over
394
+ all edges (u,v) describing:
395
+
396
+ Pr(v has color Y | u has color X)
397
+
398
+ >>> G.nodes[0]["color"] = "red"
399
+ >>> G.nodes[1]["color"] = "red"
400
+ >>> G.nodes[2]["color"] = "blue"
401
+ >>> rc = ["red", "blue"]
402
+ >>> M = nx.attr_sparse_matrix(G, node_attr="color", normalized=True, rc_order=rc)
403
+ >>> M.toarray()
404
+ array([[0.33333333, 0.66666667],
405
+ [1. , 0. ]])
406
+
407
+ For example, the above tells us that for all edges (u,v):
408
+
409
+ Pr( v is red | u is red) = 1/3
410
+ Pr( v is blue | u is red) = 2/3
411
+
412
+ Pr( v is red | u is blue) = 1
413
+ Pr( v is blue | u is blue) = 0
414
+
415
+ Finally, we can obtain the total weights listed by the node colors.
416
+
417
+ >>> M = nx.attr_sparse_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
418
+ >>> M.toarray()
419
+ array([[3., 2.],
420
+ [2., 0.]])
421
+
422
+ Thus, the total weight over all edges (u,v) with u and v having colors:
423
+
424
+ (red, red) is 3 # the sole contribution is from edge (0,1)
425
+ (red, blue) is 2 # contributions from edges (0,2) and (1,2)
426
+ (blue, red) is 2 # same as (red, blue) since graph is undirected
427
+ (blue, blue) is 0 # there are no edges with blue endpoints
428
+
429
+ """
430
+ import numpy as np
431
+ import scipy as sp
432
+
433
+ edge_value = _edge_value(G, edge_attr)
434
+ node_value = _node_value(G, node_attr)
435
+
436
+ if rc_order is None:
437
+ ordering = list({node_value(n) for n in G})
438
+ else:
439
+ ordering = rc_order
440
+
441
+ N = len(ordering)
442
+ undirected = not G.is_directed()
443
+ index = dict(zip(ordering, range(N)))
444
+ M = sp.sparse.lil_array((N, N), dtype=dtype)
445
+
446
+ seen = set()
447
+ for u, nbrdict in G.adjacency():
448
+ for v in nbrdict:
449
+ # Obtain the node attribute values.
450
+ i, j = index[node_value(u)], index[node_value(v)]
451
+ if v not in seen:
452
+ M[i, j] += edge_value(u, v)
453
+ if undirected:
454
+ M[j, i] = M[i, j]
455
+
456
+ if undirected:
457
+ seen.add(u)
458
+
459
+ if normalized:
460
+ M *= 1 / M.sum(axis=1)[:, np.newaxis] # in-place mult preserves sparse
461
+
462
+ if rc_order is None:
463
+ return M, ordering
464
+ else:
465
+ return M
minigpt2/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bethe Hessian or deformed Laplacian matrix of graphs."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for
5
+
6
+ __all__ = ["bethe_hessian_matrix"]
7
+
8
+
9
+ @not_implemented_for("directed")
10
+ @not_implemented_for("multigraph")
11
+ @nx._dispatchable
12
+ def bethe_hessian_matrix(G, r=None, nodelist=None):
13
+ r"""Returns the Bethe Hessian matrix of G.
14
+
15
+ The Bethe Hessian is a family of matrices parametrized by r, defined as
16
+ H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the
17
+ diagonal matrix of node degrees, and I is the identify matrix. It is equal
18
+ to the graph laplacian when the regularizer r = 1.
19
+
20
+ The default choice of regularizer should be the ratio [2]_
21
+
22
+ .. math::
23
+ r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1
24
+
25
+ Parameters
26
+ ----------
27
+ G : Graph
28
+ A NetworkX graph
29
+ r : float
30
+ Regularizer parameter
31
+ nodelist : list, optional
32
+ The rows and columns are ordered according to the nodes in nodelist.
33
+ If nodelist is None, then the ordering is produced by ``G.nodes()``.
34
+
35
+ Returns
36
+ -------
37
+ H : scipy.sparse.csr_array
38
+ The Bethe Hessian matrix of `G`, with parameter `r`.
39
+
40
+ Examples
41
+ --------
42
+ >>> k = [3, 2, 2, 1, 0]
43
+ >>> G = nx.havel_hakimi_graph(k)
44
+ >>> H = nx.bethe_hessian_matrix(G)
45
+ >>> H.toarray()
46
+ array([[ 3.5625, -1.25 , -1.25 , -1.25 , 0. ],
47
+ [-1.25 , 2.5625, -1.25 , 0. , 0. ],
48
+ [-1.25 , -1.25 , 2.5625, 0. , 0. ],
49
+ [-1.25 , 0. , 0. , 1.5625, 0. ],
50
+ [ 0. , 0. , 0. , 0. , 0.5625]])
51
+
52
+ See Also
53
+ --------
54
+ bethe_hessian_spectrum
55
+ adjacency_matrix
56
+ laplacian_matrix
57
+
58
+ References
59
+ ----------
60
+ .. [1] A. Saade, F. Krzakala and L. Zdeborová
61
+ "Spectral Clustering of Graphs with the Bethe Hessian",
62
+ Advances in Neural Information Processing Systems, 2014.
63
+ .. [2] C. M. Le, E. Levina
64
+ "Estimating the number of communities in networks by spectral methods"
65
+ arXiv:1507.00827, 2015.
66
+ """
67
+ import scipy as sp
68
+
69
+ if nodelist is None:
70
+ nodelist = list(G)
71
+ if r is None:
72
+ r = sum(d**2 for v, d in nx.degree(G)) / sum(d for v, d in nx.degree(G)) - 1
73
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, format="csr")
74
+ n, m = A.shape
75
+ # TODO: Rm csr_array wrapper when spdiags array creation becomes available
76
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, m, n, format="csr"))
77
+ # TODO: Rm csr_array wrapper when eye array creation becomes available
78
+ I = sp.sparse.csr_array(sp.sparse.eye(m, n, format="csr"))
79
+ return (r**2 - 1) * I - r * A + D
minigpt2/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adjacency matrix and incidence matrix of graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["incidence_matrix", "adjacency_matrix"]
8
+
9
+
10
+ @nx._dispatchable(edge_attrs="weight")
11
+ def incidence_matrix(
12
+ G, nodelist=None, edgelist=None, oriented=False, weight=None, *, dtype=None
13
+ ):
14
+ """Returns incidence matrix of G.
15
+
16
+ The incidence matrix assigns each row to a node and each column to an edge.
17
+ For a standard incidence matrix a 1 appears wherever a row's node is
18
+ incident on the column's edge. For an oriented incidence matrix each
19
+ edge is assigned an orientation (arbitrarily for undirected and aligning to
20
+ direction for directed). A -1 appears for the source (tail) of an edge and
21
+ 1 for the destination (head) of the edge. The elements are zero otherwise.
22
+
23
+ Parameters
24
+ ----------
25
+ G : graph
26
+ A NetworkX graph
27
+
28
+ nodelist : list, optional (default= all nodes in G)
29
+ The rows are ordered according to the nodes in nodelist.
30
+ If nodelist is None, then the ordering is produced by G.nodes().
31
+
32
+ edgelist : list, optional (default= all edges in G)
33
+ The columns are ordered according to the edges in edgelist.
34
+ If edgelist is None, then the ordering is produced by G.edges().
35
+
36
+ oriented: bool, optional (default=False)
37
+ If True, matrix elements are +1 or -1 for the head or tail node
38
+ respectively of each edge. If False, +1 occurs at both nodes.
39
+
40
+ weight : string or None, optional (default=None)
41
+ The edge data key used to provide each value in the matrix.
42
+ If None, then each edge has weight 1. Edge weights, if used,
43
+ should be positive so that the orientation can provide the sign.
44
+
45
+ dtype : a NumPy dtype or None (default=None)
46
+ The dtype of the output sparse array. This type should be a compatible
47
+ type of the weight argument, eg. if weight would return a float this
48
+ argument should also be a float.
49
+ If None, then the default for SciPy is used.
50
+
51
+ Returns
52
+ -------
53
+ A : SciPy sparse array
54
+ The incidence matrix of G.
55
+
56
+ Notes
57
+ -----
58
+ For MultiGraph/MultiDiGraph, the edges in edgelist should be
59
+ (u,v,key) 3-tuples.
60
+
61
+ "Networks are the best discrete model for so many problems in
62
+ applied mathematics" [1]_.
63
+
64
+ References
65
+ ----------
66
+ .. [1] Gil Strang, Network applications: A = incidence matrix,
67
+ http://videolectures.net/mit18085f07_strang_lec03/
68
+ """
69
+ import scipy as sp
70
+
71
+ if nodelist is None:
72
+ nodelist = list(G)
73
+ if edgelist is None:
74
+ if G.is_multigraph():
75
+ edgelist = list(G.edges(keys=True))
76
+ else:
77
+ edgelist = list(G.edges())
78
+ A = sp.sparse.lil_array((len(nodelist), len(edgelist)), dtype=dtype)
79
+ node_index = {node: i for i, node in enumerate(nodelist)}
80
+ for ei, e in enumerate(edgelist):
81
+ (u, v) = e[:2]
82
+ if u == v:
83
+ continue # self loops give zero column
84
+ try:
85
+ ui = node_index[u]
86
+ vi = node_index[v]
87
+ except KeyError as err:
88
+ raise nx.NetworkXError(
89
+ f"node {u} or {v} in edgelist but not in nodelist"
90
+ ) from err
91
+ if weight is None:
92
+ wt = 1
93
+ else:
94
+ if G.is_multigraph():
95
+ ekey = e[2]
96
+ wt = G[u][v][ekey].get(weight, 1)
97
+ else:
98
+ wt = G[u][v].get(weight, 1)
99
+ if oriented:
100
+ A[ui, ei] = -wt
101
+ A[vi, ei] = wt
102
+ else:
103
+ A[ui, ei] = wt
104
+ A[vi, ei] = wt
105
+ return A.asformat("csc")
106
+
107
+
108
+ @nx._dispatchable(edge_attrs="weight")
109
+ def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"):
110
+ """Returns adjacency matrix of `G`.
111
+
112
+ Parameters
113
+ ----------
114
+ G : graph
115
+ A NetworkX graph
116
+
117
+ nodelist : list, optional
118
+ The rows and columns are ordered according to the nodes in `nodelist`.
119
+ If ``nodelist=None`` (the default), then the ordering is produced by
120
+ ``G.nodes()``.
121
+
122
+ dtype : NumPy data-type, optional
123
+ The desired data-type for the array.
124
+ If `None`, then the NumPy default is used.
125
+
126
+ weight : string or None, optional (default='weight')
127
+ The edge data key used to provide each value in the matrix.
128
+ If None, then each edge has weight 1.
129
+
130
+ Returns
131
+ -------
132
+ A : SciPy sparse array
133
+ Adjacency matrix representation of G.
134
+
135
+ Notes
136
+ -----
137
+ For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
138
+
139
+ If you want a pure Python adjacency matrix representation try
140
+ :func:`~networkx.convert.to_dict_of_dicts` which will return a
141
+ dictionary-of-dictionaries format that can be addressed as a
142
+ sparse matrix.
143
+
144
+ For multigraphs with parallel edges the weights are summed.
145
+ See :func:`networkx.convert_matrix.to_numpy_array` for other options.
146
+
147
+ The convention used for self-loop edges in graphs is to assign the
148
+ diagonal matrix entry value to the edge weight attribute
149
+ (or the number 1 if the edge has no weight attribute). If the
150
+ alternate convention of doubling the edge weight is desired the
151
+ resulting SciPy sparse array can be modified as follows::
152
+
153
+ >>> G = nx.Graph([(1, 1)])
154
+ >>> A = nx.adjacency_matrix(G)
155
+ >>> A.toarray()
156
+ array([[1]])
157
+ >>> A.setdiag(A.diagonal() * 2)
158
+ >>> A.toarray()
159
+ array([[2]])
160
+
161
+ See Also
162
+ --------
163
+ to_numpy_array
164
+ to_scipy_sparse_array
165
+ to_dict_of_dicts
166
+ adjacency_spectrum
167
+ """
168
+ return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight)
minigpt2/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py ADDED
@@ -0,0 +1,617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Laplacian matrix of graphs.
2
+
3
+ All calculations here are done using the out-degree. For Laplacians using
4
+ in-degree, use `G.reverse(copy=False)` instead of `G` and take the transpose.
5
+
6
+ The `laplacian_matrix` function provides an unnormalized matrix,
7
+ while `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
8
+ and `directed_combinatorial_laplacian_matrix` are all normalized.
9
+ """
10
+
11
+ import networkx as nx
12
+ from networkx.utils import not_implemented_for
13
+
14
+ __all__ = [
15
+ "laplacian_matrix",
16
+ "normalized_laplacian_matrix",
17
+ "total_spanning_tree_weight",
18
+ "directed_laplacian_matrix",
19
+ "directed_combinatorial_laplacian_matrix",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(edge_attrs="weight")
24
+ def laplacian_matrix(G, nodelist=None, weight="weight"):
25
+ """Returns the Laplacian matrix of G.
26
+
27
+ The graph Laplacian is the matrix L = D - A, where
28
+ A is the adjacency matrix and D is the diagonal matrix of node degrees.
29
+
30
+ Parameters
31
+ ----------
32
+ G : graph
33
+ A NetworkX graph
34
+
35
+ nodelist : list, optional
36
+ The rows and columns are ordered according to the nodes in nodelist.
37
+ If nodelist is None, then the ordering is produced by G.nodes().
38
+
39
+ weight : string or None, optional (default='weight')
40
+ The edge data key used to compute each value in the matrix.
41
+ If None, then each edge has weight 1.
42
+
43
+ Returns
44
+ -------
45
+ L : SciPy sparse array
46
+ The Laplacian matrix of G.
47
+
48
+ Notes
49
+ -----
50
+ For MultiGraph, the edges weights are summed.
51
+
52
+ This returns an unnormalized matrix. For a normalized output,
53
+ use `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
54
+ or `directed_combinatorial_laplacian_matrix`.
55
+
56
+ This calculation uses the out-degree of the graph `G`. To use the
57
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
58
+ take the transpose.
59
+
60
+ See Also
61
+ --------
62
+ :func:`~networkx.convert_matrix.to_numpy_array`
63
+ normalized_laplacian_matrix
64
+ directed_laplacian_matrix
65
+ directed_combinatorial_laplacian_matrix
66
+ :func:`~networkx.linalg.spectrum.laplacian_spectrum`
67
+
68
+ Examples
69
+ --------
70
+ For graphs with multiple connected components, L is permutation-similar
71
+ to a block diagonal matrix where each block is the respective Laplacian
72
+ matrix for each component.
73
+
74
+ >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
75
+ >>> print(nx.laplacian_matrix(G).toarray())
76
+ [[ 1 -1 0 0 0]
77
+ [-1 2 -1 0 0]
78
+ [ 0 -1 1 0 0]
79
+ [ 0 0 0 1 -1]
80
+ [ 0 0 0 -1 1]]
81
+
82
+ >>> edges = [
83
+ ... (1, 2),
84
+ ... (2, 1),
85
+ ... (2, 4),
86
+ ... (4, 3),
87
+ ... (3, 4),
88
+ ... ]
89
+ >>> DiG = nx.DiGraph(edges)
90
+ >>> print(nx.laplacian_matrix(DiG).toarray())
91
+ [[ 1 -1 0 0]
92
+ [-1 2 -1 0]
93
+ [ 0 0 1 -1]
94
+ [ 0 0 -1 1]]
95
+
96
+ Notice that node 4 is represented by the third column and row. This is because
97
+ by default the row/column order is the order of `G.nodes` (i.e. the node added
98
+ order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
99
+ To control the node order of the matrix, use the `nodelist` argument.
100
+
101
+ >>> print(nx.laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
102
+ [[ 1 -1 0 0]
103
+ [-1 2 0 -1]
104
+ [ 0 0 1 -1]
105
+ [ 0 0 -1 1]]
106
+
107
+ This calculation uses the out-degree of the graph `G`. To use the
108
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
109
+ take the transpose.
110
+
111
+ >>> print(nx.laplacian_matrix(DiG.reverse(copy=False)).toarray().T)
112
+ [[ 1 -1 0 0]
113
+ [-1 1 -1 0]
114
+ [ 0 0 2 -1]
115
+ [ 0 0 -1 1]]
116
+
117
+ References
118
+ ----------
119
+ .. [1] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
120
+ The Science of Search Engine Rankings. Princeton University Press, 2006.
121
+
122
+ """
123
+ import scipy as sp
124
+
125
+ if nodelist is None:
126
+ nodelist = list(G)
127
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
128
+ n, m = A.shape
129
+ # TODO: rm csr_array wrapper when spdiags can produce arrays
130
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, m, n, format="csr"))
131
+ return D - A
132
+
133
+
134
+ @nx._dispatchable(edge_attrs="weight")
135
+ def normalized_laplacian_matrix(G, nodelist=None, weight="weight"):
136
+ r"""Returns the normalized Laplacian matrix of G.
137
+
138
+ The normalized graph Laplacian is the matrix
139
+
140
+ .. math::
141
+
142
+ N = D^{-1/2} L D^{-1/2}
143
+
144
+ where `L` is the graph Laplacian and `D` is the diagonal matrix of
145
+ node degrees [1]_.
146
+
147
+ Parameters
148
+ ----------
149
+ G : graph
150
+ A NetworkX graph
151
+
152
+ nodelist : list, optional
153
+ The rows and columns are ordered according to the nodes in nodelist.
154
+ If nodelist is None, then the ordering is produced by G.nodes().
155
+
156
+ weight : string or None, optional (default='weight')
157
+ The edge data key used to compute each value in the matrix.
158
+ If None, then each edge has weight 1.
159
+
160
+ Returns
161
+ -------
162
+ N : SciPy sparse array
163
+ The normalized Laplacian matrix of G.
164
+
165
+ Notes
166
+ -----
167
+ For MultiGraph, the edges weights are summed.
168
+ See :func:`to_numpy_array` for other options.
169
+
170
+ If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is
171
+ the adjacency matrix [2]_.
172
+
173
+ This calculation uses the out-degree of the graph `G`. To use the
174
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
175
+ take the transpose.
176
+
177
+ For an unnormalized output, use `laplacian_matrix`.
178
+
179
+ Examples
180
+ --------
181
+
182
+ >>> import numpy as np
183
+ >>> edges = [
184
+ ... (1, 2),
185
+ ... (2, 1),
186
+ ... (2, 4),
187
+ ... (4, 3),
188
+ ... (3, 4),
189
+ ... ]
190
+ >>> DiG = nx.DiGraph(edges)
191
+ >>> print(nx.normalized_laplacian_matrix(DiG).toarray())
192
+ [[ 1. -0.70710678 0. 0. ]
193
+ [-0.70710678 1. -0.70710678 0. ]
194
+ [ 0. 0. 1. -1. ]
195
+ [ 0. 0. -1. 1. ]]
196
+
197
+ Notice that node 4 is represented by the third column and row. This is because
198
+ by default the row/column order is the order of `G.nodes` (i.e. the node added
199
+ order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
200
+ To control the node order of the matrix, use the `nodelist` argument.
201
+
202
+ >>> print(nx.normalized_laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
203
+ [[ 1. -0.70710678 0. 0. ]
204
+ [-0.70710678 1. 0. -0.70710678]
205
+ [ 0. 0. 1. -1. ]
206
+ [ 0. 0. -1. 1. ]]
207
+ >>> G = nx.Graph(edges)
208
+ >>> print(nx.normalized_laplacian_matrix(G).toarray())
209
+ [[ 1. -0.70710678 0. 0. ]
210
+ [-0.70710678 1. -0.5 0. ]
211
+ [ 0. -0.5 1. -0.70710678]
212
+ [ 0. 0. -0.70710678 1. ]]
213
+
214
+ See Also
215
+ --------
216
+ laplacian_matrix
217
+ normalized_laplacian_spectrum
218
+ directed_laplacian_matrix
219
+ directed_combinatorial_laplacian_matrix
220
+
221
+ References
222
+ ----------
223
+ .. [1] Fan Chung-Graham, Spectral Graph Theory,
224
+ CBMS Regional Conference Series in Mathematics, Number 92, 1997.
225
+ .. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized
226
+ Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98,
227
+ March 2007.
228
+ .. [3] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
229
+ The Science of Search Engine Rankings. Princeton University Press, 2006.
230
+ """
231
+ import numpy as np
232
+ import scipy as sp
233
+
234
+ if nodelist is None:
235
+ nodelist = list(G)
236
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
237
+ n, _ = A.shape
238
+ diags = A.sum(axis=1)
239
+ # TODO: rm csr_array wrapper when spdiags can produce arrays
240
+ D = sp.sparse.csr_array(sp.sparse.spdiags(diags, 0, n, n, format="csr"))
241
+ L = D - A
242
+ with np.errstate(divide="ignore"):
243
+ diags_sqrt = 1.0 / np.sqrt(diags)
244
+ diags_sqrt[np.isinf(diags_sqrt)] = 0
245
+ # TODO: rm csr_array wrapper when spdiags can produce arrays
246
+ DH = sp.sparse.csr_array(sp.sparse.spdiags(diags_sqrt, 0, n, n, format="csr"))
247
+ return DH @ (L @ DH)
248
+
249
+
250
+ @nx._dispatchable(edge_attrs="weight")
251
+ def total_spanning_tree_weight(G, weight=None, root=None):
252
+ """
253
+ Returns the total weight of all spanning trees of `G`.
254
+
255
+ Kirchoff's Tree Matrix Theorem [1]_, [2]_ states that the determinant of any
256
+ cofactor of the Laplacian matrix of a graph is the number of spanning trees
257
+ in the graph. For a weighted Laplacian matrix, it is the sum across all
258
+ spanning trees of the multiplicative weight of each tree. That is, the
259
+ weight of each tree is the product of its edge weights.
260
+
261
+ For unweighted graphs, the total weight equals the number of spanning trees in `G`.
262
+
263
+ For directed graphs, the total weight follows by summing over all directed
264
+ spanning trees in `G` that start in the `root` node [3]_.
265
+
266
+ .. deprecated:: 3.3
267
+
268
+ ``total_spanning_tree_weight`` is deprecated and will be removed in v3.5.
269
+ Use ``nx.number_of_spanning_trees(G)`` instead.
270
+
271
+ Parameters
272
+ ----------
273
+ G : NetworkX Graph
274
+
275
+ weight : string or None, optional (default=None)
276
+ The key for the edge attribute holding the edge weight.
277
+ If None, then each edge has weight 1.
278
+
279
+ root : node (only required for directed graphs)
280
+ A node in the directed graph `G`.
281
+
282
+ Returns
283
+ -------
284
+ total_weight : float
285
+ Undirected graphs:
286
+ The sum of the total multiplicative weights for all spanning trees in `G`.
287
+ Directed graphs:
288
+ The sum of the total multiplicative weights for all spanning trees of `G`,
289
+ rooted at node `root`.
290
+
291
+ Raises
292
+ ------
293
+ NetworkXPointlessConcept
294
+ If `G` does not contain any nodes.
295
+
296
+ NetworkXError
297
+ If the graph `G` is not (weakly) connected,
298
+ or if `G` is directed and the root node is not specified or not in G.
299
+
300
+ Examples
301
+ --------
302
+ >>> G = nx.complete_graph(5)
303
+ >>> round(nx.total_spanning_tree_weight(G))
304
+ 125
305
+
306
+ >>> G = nx.Graph()
307
+ >>> G.add_edge(1, 2, weight=2)
308
+ >>> G.add_edge(1, 3, weight=1)
309
+ >>> G.add_edge(2, 3, weight=1)
310
+ >>> round(nx.total_spanning_tree_weight(G, "weight"))
311
+ 5
312
+
313
+ Notes
314
+ -----
315
+ Self-loops are excluded. Multi-edges are contracted in one edge
316
+ equal to the sum of the weights.
317
+
318
+ References
319
+ ----------
320
+ .. [1] Wikipedia
321
+ "Kirchhoff's theorem."
322
+ https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem
323
+ .. [2] Kirchhoff, G. R.
324
+ Über die Auflösung der Gleichungen, auf welche man
325
+ bei der Untersuchung der linearen Vertheilung
326
+ Galvanischer Ströme geführt wird
327
+ Annalen der Physik und Chemie, vol. 72, pp. 497-508, 1847.
328
+ .. [3] Margoliash, J.
329
+ "Matrix-Tree Theorem for Directed Graphs"
330
+ https://www.math.uchicago.edu/~may/VIGRE/VIGRE2010/REUPapers/Margoliash.pdf
331
+ """
332
+ import warnings
333
+
334
+ warnings.warn(
335
+ (
336
+ "\n\ntotal_spanning_tree_weight is deprecated and will be removed in v3.5.\n"
337
+ "Use `nx.number_of_spanning_trees(G)` instead."
338
+ ),
339
+ category=DeprecationWarning,
340
+ stacklevel=3,
341
+ )
342
+
343
+ return nx.number_of_spanning_trees(G, weight=weight, root=root)
344
+
345
+
346
+ ###############################################################################
347
+ # Code based on work from https://github.com/bjedwards
348
+
349
+
350
+ @not_implemented_for("undirected")
351
+ @not_implemented_for("multigraph")
352
+ @nx._dispatchable(edge_attrs="weight")
353
+ def directed_laplacian_matrix(
354
+ G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
355
+ ):
356
+ r"""Returns the directed Laplacian matrix of G.
357
+
358
+ The graph directed Laplacian is the matrix
359
+
360
+ .. math::
361
+
362
+ L = I - \frac{1}{2} \left (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} \right )
363
+
364
+ where `I` is the identity matrix, `P` is the transition matrix of the
365
+ graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
366
+ zeros elsewhere [1]_.
367
+
368
+ Depending on the value of walk_type, `P` can be the transition matrix
369
+ induced by a random walk, a lazy random walk, or a random walk with
370
+ teleportation (PageRank).
371
+
372
+ Parameters
373
+ ----------
374
+ G : DiGraph
375
+ A NetworkX graph
376
+
377
+ nodelist : list, optional
378
+ The rows and columns are ordered according to the nodes in nodelist.
379
+ If nodelist is None, then the ordering is produced by G.nodes().
380
+
381
+ weight : string or None, optional (default='weight')
382
+ The edge data key used to compute each value in the matrix.
383
+ If None, then each edge has weight 1.
384
+
385
+ walk_type : string or None, optional (default=None)
386
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
387
+ (the default), then a value is selected according to the properties of `G`:
388
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
389
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
390
+ - ``walk_type="pagerank"`` for all other cases.
391
+
392
+ alpha : real
393
+ (1 - alpha) is the teleportation probability used with pagerank
394
+
395
+ Returns
396
+ -------
397
+ L : NumPy matrix
398
+ Normalized Laplacian of G.
399
+
400
+ Notes
401
+ -----
402
+ Only implemented for DiGraphs
403
+
404
+ The result is always a symmetric matrix.
405
+
406
+ This calculation uses the out-degree of the graph `G`. To use the
407
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
408
+ take the transpose.
409
+
410
+ See Also
411
+ --------
412
+ laplacian_matrix
413
+ normalized_laplacian_matrix
414
+ directed_combinatorial_laplacian_matrix
415
+
416
+ References
417
+ ----------
418
+ .. [1] Fan Chung (2005).
419
+ Laplacians and the Cheeger inequality for directed graphs.
420
+ Annals of Combinatorics, 9(1), 2005
421
+ """
422
+ import numpy as np
423
+ import scipy as sp
424
+
425
+ # NOTE: P has type ndarray if walk_type=="pagerank", else csr_array
426
+ P = _transition_matrix(
427
+ G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
428
+ )
429
+
430
+ n, m = P.shape
431
+
432
+ evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
433
+ v = evecs.flatten().real
434
+ p = v / v.sum()
435
+ # p>=0 by Perron-Frobenius Thm. Use abs() to fix roundoff across zero gh-6865
436
+ sqrtp = np.sqrt(np.abs(p))
437
+ Q = (
438
+ # TODO: rm csr_array wrapper when spdiags creates arrays
439
+ sp.sparse.csr_array(sp.sparse.spdiags(sqrtp, 0, n, n))
440
+ @ P
441
+ # TODO: rm csr_array wrapper when spdiags creates arrays
442
+ @ sp.sparse.csr_array(sp.sparse.spdiags(1.0 / sqrtp, 0, n, n))
443
+ )
444
+ # NOTE: This could be sparsified for the non-pagerank cases
445
+ I = np.identity(len(G))
446
+
447
+ return I - (Q + Q.T) / 2.0
448
+
449
+
450
+ @not_implemented_for("undirected")
451
+ @not_implemented_for("multigraph")
452
+ @nx._dispatchable(edge_attrs="weight")
453
+ def directed_combinatorial_laplacian_matrix(
454
+ G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
455
+ ):
456
+ r"""Return the directed combinatorial Laplacian matrix of G.
457
+
458
+ The graph directed combinatorial Laplacian is the matrix
459
+
460
+ .. math::
461
+
462
+ L = \Phi - \frac{1}{2} \left (\Phi P + P^T \Phi \right)
463
+
464
+ where `P` is the transition matrix of the graph and `\Phi` a matrix
465
+ with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
466
+
467
+ Depending on the value of walk_type, `P` can be the transition matrix
468
+ induced by a random walk, a lazy random walk, or a random walk with
469
+ teleportation (PageRank).
470
+
471
+ Parameters
472
+ ----------
473
+ G : DiGraph
474
+ A NetworkX graph
475
+
476
+ nodelist : list, optional
477
+ The rows and columns are ordered according to the nodes in nodelist.
478
+ If nodelist is None, then the ordering is produced by G.nodes().
479
+
480
+ weight : string or None, optional (default='weight')
481
+ The edge data key used to compute each value in the matrix.
482
+ If None, then each edge has weight 1.
483
+
484
+ walk_type : string or None, optional (default=None)
485
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
486
+ (the default), then a value is selected according to the properties of `G`:
487
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
488
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
489
+ - ``walk_type="pagerank"`` for all other cases.
490
+
491
+ alpha : real
492
+ (1 - alpha) is the teleportation probability used with pagerank
493
+
494
+ Returns
495
+ -------
496
+ L : NumPy matrix
497
+ Combinatorial Laplacian of G.
498
+
499
+ Notes
500
+ -----
501
+ Only implemented for DiGraphs
502
+
503
+ The result is always a symmetric matrix.
504
+
505
+ This calculation uses the out-degree of the graph `G`. To use the
506
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
507
+ take the transpose.
508
+
509
+ See Also
510
+ --------
511
+ laplacian_matrix
512
+ normalized_laplacian_matrix
513
+ directed_laplacian_matrix
514
+
515
+ References
516
+ ----------
517
+ .. [1] Fan Chung (2005).
518
+ Laplacians and the Cheeger inequality for directed graphs.
519
+ Annals of Combinatorics, 9(1), 2005
520
+ """
521
+ import scipy as sp
522
+
523
+ P = _transition_matrix(
524
+ G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
525
+ )
526
+
527
+ n, m = P.shape
528
+
529
+ evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
530
+ v = evecs.flatten().real
531
+ p = v / v.sum()
532
+ # NOTE: could be improved by not densifying
533
+ # TODO: Rm csr_array wrapper when spdiags array creation becomes available
534
+ Phi = sp.sparse.csr_array(sp.sparse.spdiags(p, 0, n, n)).toarray()
535
+
536
+ return Phi - (Phi @ P + P.T @ Phi) / 2.0
537
+
538
+
539
+ def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha=0.95):
540
+ """Returns the transition matrix of G.
541
+
542
+ This is a row stochastic giving the transition probabilities while
543
+ performing a random walk on the graph. Depending on the value of walk_type,
544
+ P can be the transition matrix induced by a random walk, a lazy random walk,
545
+ or a random walk with teleportation (PageRank).
546
+
547
+ Parameters
548
+ ----------
549
+ G : DiGraph
550
+ A NetworkX graph
551
+
552
+ nodelist : list, optional
553
+ The rows and columns are ordered according to the nodes in nodelist.
554
+ If nodelist is None, then the ordering is produced by G.nodes().
555
+
556
+ weight : string or None, optional (default='weight')
557
+ The edge data key used to compute each value in the matrix.
558
+ If None, then each edge has weight 1.
559
+
560
+ walk_type : string or None, optional (default=None)
561
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
562
+ (the default), then a value is selected according to the properties of `G`:
563
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
564
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
565
+ - ``walk_type="pagerank"`` for all other cases.
566
+
567
+ alpha : real
568
+ (1 - alpha) is the teleportation probability used with pagerank
569
+
570
+ Returns
571
+ -------
572
+ P : numpy.ndarray
573
+ transition matrix of G.
574
+
575
+ Raises
576
+ ------
577
+ NetworkXError
578
+ If walk_type not specified or alpha not in valid range
579
+ """
580
+ import numpy as np
581
+ import scipy as sp
582
+
583
+ if walk_type is None:
584
+ if nx.is_strongly_connected(G):
585
+ if nx.is_aperiodic(G):
586
+ walk_type = "random"
587
+ else:
588
+ walk_type = "lazy"
589
+ else:
590
+ walk_type = "pagerank"
591
+
592
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
593
+ n, m = A.shape
594
+ if walk_type in ["random", "lazy"]:
595
+ # TODO: Rm csr_array wrapper when spdiags array creation becomes available
596
+ DI = sp.sparse.csr_array(sp.sparse.spdiags(1.0 / A.sum(axis=1), 0, n, n))
597
+ if walk_type == "random":
598
+ P = DI @ A
599
+ else:
600
+ # TODO: Rm csr_array wrapper when identity array creation becomes available
601
+ I = sp.sparse.csr_array(sp.sparse.identity(n))
602
+ P = (I + DI @ A) / 2.0
603
+
604
+ elif walk_type == "pagerank":
605
+ if not (0 < alpha < 1):
606
+ raise nx.NetworkXError("alpha must be between 0 and 1")
607
+ # this is using a dense representation. NOTE: This should be sparsified!
608
+ A = A.toarray()
609
+ # add constant to dangling nodes' row
610
+ A[A.sum(axis=1) == 0, :] = 1 / n
611
+ # normalize
612
+ A = A / A.sum(axis=1)[np.newaxis, :].T
613
+ P = alpha * A + (1 - alpha) / n
614
+ else:
615
+ raise nx.NetworkXError("walk_type must be random, lazy, or pagerank")
616
+
617
+ return P
minigpt2/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modularity matrix of graphs."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for
5
+
6
+ __all__ = ["modularity_matrix", "directed_modularity_matrix"]
7
+
8
+
9
+ @not_implemented_for("directed")
10
+ @not_implemented_for("multigraph")
11
+ @nx._dispatchable(edge_attrs="weight")
12
+ def modularity_matrix(G, nodelist=None, weight=None):
13
+ r"""Returns the modularity matrix of G.
14
+
15
+ The modularity matrix is the matrix B = A - <A>, where A is the adjacency
16
+ matrix and <A> is the average adjacency matrix, assuming that the graph
17
+ is described by the configuration model.
18
+
19
+ More specifically, the element B_ij of B is defined as
20
+
21
+ .. math::
22
+ A_{ij} - {k_i k_j \over 2 m}
23
+
24
+ where k_i is the degree of node i, and where m is the number of edges
25
+ in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
26
+ k_j and m are computed using its value.
27
+
28
+ Parameters
29
+ ----------
30
+ G : Graph
31
+ A NetworkX graph
32
+
33
+ nodelist : list, optional
34
+ The rows and columns are ordered according to the nodes in nodelist.
35
+ If nodelist is None, then the ordering is produced by G.nodes().
36
+
37
+ weight : string or None, optional (default=None)
38
+ The edge attribute that holds the numerical value used for
39
+ the edge weight. If None then all edge weights are 1.
40
+
41
+ Returns
42
+ -------
43
+ B : Numpy array
44
+ The modularity matrix of G.
45
+
46
+ Examples
47
+ --------
48
+ >>> k = [3, 2, 2, 1, 0]
49
+ >>> G = nx.havel_hakimi_graph(k)
50
+ >>> B = nx.modularity_matrix(G)
51
+
52
+
53
+ See Also
54
+ --------
55
+ to_numpy_array
56
+ modularity_spectrum
57
+ adjacency_matrix
58
+ directed_modularity_matrix
59
+
60
+ References
61
+ ----------
62
+ .. [1] M. E. J. Newman, "Modularity and community structure in networks",
63
+ Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
64
+ """
65
+ import numpy as np
66
+
67
+ if nodelist is None:
68
+ nodelist = list(G)
69
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
70
+ k = A.sum(axis=1)
71
+ m = k.sum() * 0.5
72
+ # Expected adjacency matrix
73
+ X = np.outer(k, k) / (2 * m)
74
+
75
+ return A - X
76
+
77
+
78
+ @not_implemented_for("undirected")
79
+ @not_implemented_for("multigraph")
80
+ @nx._dispatchable(edge_attrs="weight")
81
+ def directed_modularity_matrix(G, nodelist=None, weight=None):
82
+ """Returns the directed modularity matrix of G.
83
+
84
+ The modularity matrix is the matrix B = A - <A>, where A is the adjacency
85
+ matrix and <A> is the expected adjacency matrix, assuming that the graph
86
+ is described by the configuration model.
87
+
88
+ More specifically, the element B_ij of B is defined as
89
+
90
+ .. math::
91
+ B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
92
+
93
+ where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree
94
+ of node j, with m the number of edges in the graph. When weight is set
95
+ to a name of an attribute edge, Aij, k_i, k_j and m are computed using
96
+ its value.
97
+
98
+ Parameters
99
+ ----------
100
+ G : DiGraph
101
+ A NetworkX DiGraph
102
+
103
+ nodelist : list, optional
104
+ The rows and columns are ordered according to the nodes in nodelist.
105
+ If nodelist is None, then the ordering is produced by G.nodes().
106
+
107
+ weight : string or None, optional (default=None)
108
+ The edge attribute that holds the numerical value used for
109
+ the edge weight. If None then all edge weights are 1.
110
+
111
+ Returns
112
+ -------
113
+ B : Numpy array
114
+ The modularity matrix of G.
115
+
116
+ Examples
117
+ --------
118
+ >>> G = nx.DiGraph()
119
+ >>> G.add_edges_from(
120
+ ... (
121
+ ... (1, 2),
122
+ ... (1, 3),
123
+ ... (3, 1),
124
+ ... (3, 2),
125
+ ... (3, 5),
126
+ ... (4, 5),
127
+ ... (4, 6),
128
+ ... (5, 4),
129
+ ... (5, 6),
130
+ ... (6, 4),
131
+ ... )
132
+ ... )
133
+ >>> B = nx.directed_modularity_matrix(G)
134
+
135
+
136
+ Notes
137
+ -----
138
+ NetworkX defines the element A_ij of the adjacency matrix as 1 if there
139
+ is a link going from node i to node j. Leicht and Newman use the opposite
140
+ definition. This explains the different expression for B_ij.
141
+
142
+ See Also
143
+ --------
144
+ to_numpy_array
145
+ modularity_spectrum
146
+ adjacency_matrix
147
+ modularity_matrix
148
+
149
+ References
150
+ ----------
151
+ .. [1] E. A. Leicht, M. E. J. Newman,
152
+ "Community structure in directed networks",
153
+ Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
154
+ """
155
+ import numpy as np
156
+
157
+ if nodelist is None:
158
+ nodelist = list(G)
159
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
160
+ k_in = A.sum(axis=0)
161
+ k_out = A.sum(axis=1)
162
+ m = k_in.sum()
163
+ # Expected adjacency matrix
164
+ X = np.outer(k_out, k_in) / m
165
+
166
+ return A - X
minigpt2/lib/python3.10/site-packages/networkx/linalg/spectrum.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Eigenvalue spectrum of graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "laplacian_spectrum",
9
+ "adjacency_spectrum",
10
+ "modularity_spectrum",
11
+ "normalized_laplacian_spectrum",
12
+ "bethe_hessian_spectrum",
13
+ ]
14
+
15
+
16
+ @nx._dispatchable(edge_attrs="weight")
17
+ def laplacian_spectrum(G, weight="weight"):
18
+ """Returns eigenvalues of the Laplacian of G
19
+
20
+ Parameters
21
+ ----------
22
+ G : graph
23
+ A NetworkX graph
24
+
25
+ weight : string or None, optional (default='weight')
26
+ The edge data key used to compute each value in the matrix.
27
+ If None, then each edge has weight 1.
28
+
29
+ Returns
30
+ -------
31
+ evals : NumPy array
32
+ Eigenvalues
33
+
34
+ Notes
35
+ -----
36
+ For MultiGraph/MultiDiGraph, the edges weights are summed.
37
+ See :func:`~networkx.convert_matrix.to_numpy_array` for other options.
38
+
39
+ See Also
40
+ --------
41
+ laplacian_matrix
42
+
43
+ Examples
44
+ --------
45
+ The multiplicity of 0 as an eigenvalue of the laplacian matrix is equal
46
+ to the number of connected components of G.
47
+
48
+ >>> G = nx.Graph() # Create a graph with 5 nodes and 3 connected components
49
+ >>> G.add_nodes_from(range(5))
50
+ >>> G.add_edges_from([(0, 2), (3, 4)])
51
+ >>> nx.laplacian_spectrum(G)
52
+ array([0., 0., 0., 2., 2.])
53
+
54
+ """
55
+ import scipy as sp
56
+
57
+ return sp.linalg.eigvalsh(nx.laplacian_matrix(G, weight=weight).todense())
58
+
59
+
60
+ @nx._dispatchable(edge_attrs="weight")
61
+ def normalized_laplacian_spectrum(G, weight="weight"):
62
+ """Return eigenvalues of the normalized Laplacian of G
63
+
64
+ Parameters
65
+ ----------
66
+ G : graph
67
+ A NetworkX graph
68
+
69
+ weight : string or None, optional (default='weight')
70
+ The edge data key used to compute each value in the matrix.
71
+ If None, then each edge has weight 1.
72
+
73
+ Returns
74
+ -------
75
+ evals : NumPy array
76
+ Eigenvalues
77
+
78
+ Notes
79
+ -----
80
+ For MultiGraph/MultiDiGraph, the edges weights are summed.
81
+ See to_numpy_array for other options.
82
+
83
+ See Also
84
+ --------
85
+ normalized_laplacian_matrix
86
+ """
87
+ import scipy as sp
88
+
89
+ return sp.linalg.eigvalsh(
90
+ nx.normalized_laplacian_matrix(G, weight=weight).todense()
91
+ )
92
+
93
+
94
+ @nx._dispatchable(edge_attrs="weight")
95
+ def adjacency_spectrum(G, weight="weight"):
96
+ """Returns eigenvalues of the adjacency matrix of G.
97
+
98
+ Parameters
99
+ ----------
100
+ G : graph
101
+ A NetworkX graph
102
+
103
+ weight : string or None, optional (default='weight')
104
+ The edge data key used to compute each value in the matrix.
105
+ If None, then each edge has weight 1.
106
+
107
+ Returns
108
+ -------
109
+ evals : NumPy array
110
+ Eigenvalues
111
+
112
+ Notes
113
+ -----
114
+ For MultiGraph/MultiDiGraph, the edges weights are summed.
115
+ See to_numpy_array for other options.
116
+
117
+ See Also
118
+ --------
119
+ adjacency_matrix
120
+ """
121
+ import scipy as sp
122
+
123
+ return sp.linalg.eigvals(nx.adjacency_matrix(G, weight=weight).todense())
124
+
125
+
126
+ @nx._dispatchable
127
+ def modularity_spectrum(G):
128
+ """Returns eigenvalues of the modularity matrix of G.
129
+
130
+ Parameters
131
+ ----------
132
+ G : Graph
133
+ A NetworkX Graph or DiGraph
134
+
135
+ Returns
136
+ -------
137
+ evals : NumPy array
138
+ Eigenvalues
139
+
140
+ See Also
141
+ --------
142
+ modularity_matrix
143
+
144
+ References
145
+ ----------
146
+ .. [1] M. E. J. Newman, "Modularity and community structure in networks",
147
+ Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
148
+ """
149
+ import scipy as sp
150
+
151
+ if G.is_directed():
152
+ return sp.linalg.eigvals(nx.directed_modularity_matrix(G))
153
+ else:
154
+ return sp.linalg.eigvals(nx.modularity_matrix(G))
155
+
156
+
157
+ @nx._dispatchable
158
+ def bethe_hessian_spectrum(G, r=None):
159
+ """Returns eigenvalues of the Bethe Hessian matrix of G.
160
+
161
+ Parameters
162
+ ----------
163
+ G : Graph
164
+ A NetworkX Graph or DiGraph
165
+
166
+ r : float
167
+ Regularizer parameter
168
+
169
+ Returns
170
+ -------
171
+ evals : NumPy array
172
+ Eigenvalues
173
+
174
+ See Also
175
+ --------
176
+ bethe_hessian_matrix
177
+
178
+ References
179
+ ----------
180
+ .. [1] A. Saade, F. Krzakala and L. Zdeborová
181
+ "Spectral clustering of graphs with the bethe hessian",
182
+ Advances in Neural Information Processing Systems. 2014.
183
+ """
184
+ import scipy as sp
185
+
186
+ return sp.linalg.eigvalsh(nx.bethe_hessian_matrix(G, r).todense())
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py ADDED
File without changes
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (175 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc ADDED
Binary file (3.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_bethehessian.cpython-310.pyc ADDED
Binary file (1.39 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_graphmatrix.cpython-310.pyc ADDED
Binary file (5.61 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_laplacian.cpython-310.pyc ADDED
Binary file (8.15 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_modularity.cpython-310.pyc ADDED
Binary file (2.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_spectrum.cpython-310.pyc ADDED
Binary file (3.21 kB). View file
 
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/test_algebraic_connectivity.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import sqrt
2
+
3
+ import pytest
4
+
5
+ np = pytest.importorskip("numpy")
6
+
7
+
8
+ import networkx as nx
9
+
10
+ methods = ("tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg")
11
+
12
+
13
+ def test_algebraic_connectivity_tracemin_chol():
14
+ """Test that "tracemin_chol" raises an exception."""
15
+ pytest.importorskip("scipy")
16
+ G = nx.barbell_graph(5, 4)
17
+ with pytest.raises(nx.NetworkXError):
18
+ nx.algebraic_connectivity(G, method="tracemin_chol")
19
+
20
+
21
+ def test_fiedler_vector_tracemin_chol():
22
+ """Test that "tracemin_chol" raises an exception."""
23
+ pytest.importorskip("scipy")
24
+ G = nx.barbell_graph(5, 4)
25
+ with pytest.raises(nx.NetworkXError):
26
+ nx.fiedler_vector(G, method="tracemin_chol")
27
+
28
+
29
+ def test_spectral_ordering_tracemin_chol():
30
+ """Test that "tracemin_chol" raises an exception."""
31
+ pytest.importorskip("scipy")
32
+ G = nx.barbell_graph(5, 4)
33
+ with pytest.raises(nx.NetworkXError):
34
+ nx.spectral_ordering(G, method="tracemin_chol")
35
+
36
+
37
+ def test_fiedler_vector_tracemin_unknown():
38
+ """Test that "tracemin_unknown" raises an exception."""
39
+ pytest.importorskip("scipy")
40
+ G = nx.barbell_graph(5, 4)
41
+ L = nx.laplacian_matrix(G)
42
+ X = np.asarray(np.random.normal(size=(1, L.shape[0]))).T
43
+ with pytest.raises(nx.NetworkXError, match="Unknown linear system solver"):
44
+ nx.linalg.algebraicconnectivity._tracemin_fiedler(
45
+ L, X, normalized=False, tol=1e-8, method="tracemin_unknown"
46
+ )
47
+
48
+
49
+ def test_spectral_bisection():
50
+ pytest.importorskip("scipy")
51
+ G = nx.barbell_graph(3, 0)
52
+ C = nx.spectral_bisection(G)
53
+ assert C == ({0, 1, 2}, {3, 4, 5})
54
+
55
+ mapping = dict(enumerate("badfec"))
56
+ G = nx.relabel_nodes(G, mapping)
57
+ C = nx.spectral_bisection(G)
58
+ assert C == (
59
+ {mapping[0], mapping[1], mapping[2]},
60
+ {mapping[3], mapping[4], mapping[5]},
61
+ )
62
+
63
+
64
+ def check_eigenvector(A, l, x):
65
+ nx = np.linalg.norm(x)
66
+ # Check zeroness.
67
+ assert nx != pytest.approx(0, abs=1e-07)
68
+ y = A @ x
69
+ ny = np.linalg.norm(y)
70
+ # Check collinearity.
71
+ assert x @ y == pytest.approx(nx * ny, abs=1e-7)
72
+ # Check eigenvalue.
73
+ assert ny == pytest.approx(l * nx, abs=1e-7)
74
+
75
+
76
+ class TestAlgebraicConnectivity:
77
+ @pytest.mark.parametrize("method", methods)
78
+ def test_directed(self, method):
79
+ G = nx.DiGraph()
80
+ pytest.raises(
81
+ nx.NetworkXNotImplemented, nx.algebraic_connectivity, G, method=method
82
+ )
83
+ pytest.raises(nx.NetworkXNotImplemented, nx.fiedler_vector, G, method=method)
84
+
85
+ @pytest.mark.parametrize("method", methods)
86
+ def test_null_and_singleton(self, method):
87
+ G = nx.Graph()
88
+ pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method=method)
89
+ pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
90
+ G.add_edge(0, 0)
91
+ pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method=method)
92
+ pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
93
+
94
+ @pytest.mark.parametrize("method", methods)
95
+ def test_disconnected(self, method):
96
+ G = nx.Graph()
97
+ G.add_nodes_from(range(2))
98
+ assert nx.algebraic_connectivity(G) == 0
99
+ pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
100
+ G.add_edge(0, 1, weight=0)
101
+ assert nx.algebraic_connectivity(G) == 0
102
+ pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
103
+
104
+ def test_unrecognized_method(self):
105
+ pytest.importorskip("scipy")
106
+ G = nx.path_graph(4)
107
+ pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method="unknown")
108
+ pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method="unknown")
109
+
110
+ @pytest.mark.parametrize("method", methods)
111
+ def test_two_nodes(self, method):
112
+ pytest.importorskip("scipy")
113
+ G = nx.Graph()
114
+ G.add_edge(0, 1, weight=1)
115
+ A = nx.laplacian_matrix(G)
116
+ assert nx.algebraic_connectivity(G, tol=1e-12, method=method) == pytest.approx(
117
+ 2, abs=1e-7
118
+ )
119
+ x = nx.fiedler_vector(G, tol=1e-12, method=method)
120
+ check_eigenvector(A, 2, x)
121
+
122
+ @pytest.mark.parametrize("method", methods)
123
+ def test_two_nodes_multigraph(self, method):
124
+ pytest.importorskip("scipy")
125
+ G = nx.MultiGraph()
126
+ G.add_edge(0, 0, spam=1e8)
127
+ G.add_edge(0, 1, spam=1)
128
+ G.add_edge(0, 1, spam=-2)
129
+ A = -3 * nx.laplacian_matrix(G, weight="spam")
130
+ assert nx.algebraic_connectivity(
131
+ G, weight="spam", tol=1e-12, method=method
132
+ ) == pytest.approx(6, abs=1e-7)
133
+ x = nx.fiedler_vector(G, weight="spam", tol=1e-12, method=method)
134
+ check_eigenvector(A, 6, x)
135
+
136
+ def test_abbreviation_of_method(self):
137
+ pytest.importorskip("scipy")
138
+ G = nx.path_graph(8)
139
+ A = nx.laplacian_matrix(G)
140
+ sigma = 2 - sqrt(2 + sqrt(2))
141
+ ac = nx.algebraic_connectivity(G, tol=1e-12, method="tracemin")
142
+ assert ac == pytest.approx(sigma, abs=1e-7)
143
+ x = nx.fiedler_vector(G, tol=1e-12, method="tracemin")
144
+ check_eigenvector(A, sigma, x)
145
+
146
+ @pytest.mark.parametrize("method", methods)
147
+ def test_path(self, method):
148
+ pytest.importorskip("scipy")
149
+ G = nx.path_graph(8)
150
+ A = nx.laplacian_matrix(G)
151
+ sigma = 2 - sqrt(2 + sqrt(2))
152
+ ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
153
+ assert ac == pytest.approx(sigma, abs=1e-7)
154
+ x = nx.fiedler_vector(G, tol=1e-12, method=method)
155
+ check_eigenvector(A, sigma, x)
156
+
157
+ @pytest.mark.parametrize("method", methods)
158
+ def test_problematic_graph_issue_2381(self, method):
159
+ pytest.importorskip("scipy")
160
+ G = nx.path_graph(4)
161
+ G.add_edges_from([(4, 2), (5, 1)])
162
+ A = nx.laplacian_matrix(G)
163
+ sigma = 0.438447187191
164
+ ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
165
+ assert ac == pytest.approx(sigma, abs=1e-7)
166
+ x = nx.fiedler_vector(G, tol=1e-12, method=method)
167
+ check_eigenvector(A, sigma, x)
168
+
169
+ @pytest.mark.parametrize("method", methods)
170
+ def test_cycle(self, method):
171
+ pytest.importorskip("scipy")
172
+ G = nx.cycle_graph(8)
173
+ A = nx.laplacian_matrix(G)
174
+ sigma = 2 - sqrt(2)
175
+ ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
176
+ assert ac == pytest.approx(sigma, abs=1e-7)
177
+ x = nx.fiedler_vector(G, tol=1e-12, method=method)
178
+ check_eigenvector(A, sigma, x)
179
+
180
+ @pytest.mark.parametrize("method", methods)
181
+ def test_seed_argument(self, method):
182
+ pytest.importorskip("scipy")
183
+ G = nx.cycle_graph(8)
184
+ A = nx.laplacian_matrix(G)
185
+ sigma = 2 - sqrt(2)
186
+ ac = nx.algebraic_connectivity(G, tol=1e-12, method=method, seed=1)
187
+ assert ac == pytest.approx(sigma, abs=1e-7)
188
+ x = nx.fiedler_vector(G, tol=1e-12, method=method, seed=1)
189
+ check_eigenvector(A, sigma, x)
190
+
191
+ @pytest.mark.parametrize(
192
+ ("normalized", "sigma", "laplacian_fn"),
193
+ (
194
+ (False, 0.2434017461399311, nx.laplacian_matrix),
195
+ (True, 0.08113391537997749, nx.normalized_laplacian_matrix),
196
+ ),
197
+ )
198
+ @pytest.mark.parametrize("method", methods)
199
+ def test_buckminsterfullerene(self, normalized, sigma, laplacian_fn, method):
200
+ pytest.importorskip("scipy")
201
+ G = nx.Graph(
202
+ [
203
+ (1, 10),
204
+ (1, 41),
205
+ (1, 59),
206
+ (2, 12),
207
+ (2, 42),
208
+ (2, 60),
209
+ (3, 6),
210
+ (3, 43),
211
+ (3, 57),
212
+ (4, 8),
213
+ (4, 44),
214
+ (4, 58),
215
+ (5, 13),
216
+ (5, 56),
217
+ (5, 57),
218
+ (6, 10),
219
+ (6, 31),
220
+ (7, 14),
221
+ (7, 56),
222
+ (7, 58),
223
+ (8, 12),
224
+ (8, 32),
225
+ (9, 23),
226
+ (9, 53),
227
+ (9, 59),
228
+ (10, 15),
229
+ (11, 24),
230
+ (11, 53),
231
+ (11, 60),
232
+ (12, 16),
233
+ (13, 14),
234
+ (13, 25),
235
+ (14, 26),
236
+ (15, 27),
237
+ (15, 49),
238
+ (16, 28),
239
+ (16, 50),
240
+ (17, 18),
241
+ (17, 19),
242
+ (17, 54),
243
+ (18, 20),
244
+ (18, 55),
245
+ (19, 23),
246
+ (19, 41),
247
+ (20, 24),
248
+ (20, 42),
249
+ (21, 31),
250
+ (21, 33),
251
+ (21, 57),
252
+ (22, 32),
253
+ (22, 34),
254
+ (22, 58),
255
+ (23, 24),
256
+ (25, 35),
257
+ (25, 43),
258
+ (26, 36),
259
+ (26, 44),
260
+ (27, 51),
261
+ (27, 59),
262
+ (28, 52),
263
+ (28, 60),
264
+ (29, 33),
265
+ (29, 34),
266
+ (29, 56),
267
+ (30, 51),
268
+ (30, 52),
269
+ (30, 53),
270
+ (31, 47),
271
+ (32, 48),
272
+ (33, 45),
273
+ (34, 46),
274
+ (35, 36),
275
+ (35, 37),
276
+ (36, 38),
277
+ (37, 39),
278
+ (37, 49),
279
+ (38, 40),
280
+ (38, 50),
281
+ (39, 40),
282
+ (39, 51),
283
+ (40, 52),
284
+ (41, 47),
285
+ (42, 48),
286
+ (43, 49),
287
+ (44, 50),
288
+ (45, 46),
289
+ (45, 54),
290
+ (46, 55),
291
+ (47, 54),
292
+ (48, 55),
293
+ ]
294
+ )
295
+ A = laplacian_fn(G)
296
+ try:
297
+ assert nx.algebraic_connectivity(
298
+ G, normalized=normalized, tol=1e-12, method=method
299
+ ) == pytest.approx(sigma, abs=1e-7)
300
+ x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method)
301
+ check_eigenvector(A, sigma, x)
302
+ except nx.NetworkXError as err:
303
+ if err.args not in (
304
+ ("Cholesky solver unavailable.",),
305
+ ("LU solver unavailable.",),
306
+ ):
307
+ raise
308
+
309
+
310
+ class TestSpectralOrdering:
311
+ _graphs = (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
312
+
313
+ @pytest.mark.parametrize("graph", _graphs)
314
+ def test_nullgraph(self, graph):
315
+ G = graph()
316
+ pytest.raises(nx.NetworkXError, nx.spectral_ordering, G)
317
+
318
+ @pytest.mark.parametrize("graph", _graphs)
319
+ def test_singleton(self, graph):
320
+ G = graph()
321
+ G.add_node("x")
322
+ assert nx.spectral_ordering(G) == ["x"]
323
+ G.add_edge("x", "x", weight=33)
324
+ G.add_edge("x", "x", weight=33)
325
+ assert nx.spectral_ordering(G) == ["x"]
326
+
327
+ def test_unrecognized_method(self):
328
+ G = nx.path_graph(4)
329
+ pytest.raises(nx.NetworkXError, nx.spectral_ordering, G, method="unknown")
330
+
331
+ @pytest.mark.parametrize("method", methods)
332
+ def test_three_nodes(self, method):
333
+ pytest.importorskip("scipy")
334
+ G = nx.Graph()
335
+ G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1)], weight="spam")
336
+ order = nx.spectral_ordering(G, weight="spam", method=method)
337
+ assert set(order) == set(G)
338
+ assert {1, 3} in (set(order[:-1]), set(order[1:]))
339
+
340
+ @pytest.mark.parametrize("method", methods)
341
+ def test_three_nodes_multigraph(self, method):
342
+ pytest.importorskip("scipy")
343
+ G = nx.MultiDiGraph()
344
+ G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1), (2, 3, 2)])
345
+ order = nx.spectral_ordering(G, method=method)
346
+ assert set(order) == set(G)
347
+ assert {2, 3} in (set(order[:-1]), set(order[1:]))
348
+
349
+ @pytest.mark.parametrize("method", methods)
350
+ def test_path(self, method):
351
+ pytest.importorskip("scipy")
352
+ path = list(range(10))
353
+ np.random.shuffle(path)
354
+ G = nx.Graph()
355
+ nx.add_path(G, path)
356
+ order = nx.spectral_ordering(G, method=method)
357
+ assert order in [path, list(reversed(path))]
358
+
359
+ @pytest.mark.parametrize("method", methods)
360
+ def test_seed_argument(self, method):
361
+ pytest.importorskip("scipy")
362
+ path = list(range(10))
363
+ np.random.shuffle(path)
364
+ G = nx.Graph()
365
+ nx.add_path(G, path)
366
+ order = nx.spectral_ordering(G, method=method, seed=1)
367
+ assert order in [path, list(reversed(path))]
368
+
369
+ @pytest.mark.parametrize("method", methods)
370
+ def test_disconnected(self, method):
371
+ pytest.importorskip("scipy")
372
+ G = nx.Graph()
373
+ nx.add_path(G, range(0, 10, 2))
374
+ nx.add_path(G, range(1, 10, 2))
375
+ order = nx.spectral_ordering(G, method=method)
376
+ assert set(order) == set(G)
377
+ seqs = [
378
+ list(range(0, 10, 2)),
379
+ list(range(8, -1, -2)),
380
+ list(range(1, 10, 2)),
381
+ list(range(9, -1, -2)),
382
+ ]
383
+ assert order[:5] in seqs
384
+ assert order[5:] in seqs
385
+
386
+ @pytest.mark.parametrize(
387
+ ("normalized", "expected_order"),
388
+ (
389
+ (False, [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8], [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]]),
390
+ (True, [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8], [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]),
391
+ ),
392
+ )
393
+ @pytest.mark.parametrize("method", methods)
394
+ def test_cycle(self, normalized, expected_order, method):
395
+ pytest.importorskip("scipy")
396
+ path = list(range(10))
397
+ G = nx.Graph()
398
+ nx.add_path(G, path, weight=5)
399
+ G.add_edge(path[-1], path[0], weight=1)
400
+ A = nx.laplacian_matrix(G).todense()
401
+ order = nx.spectral_ordering(G, normalized=normalized, method=method)
402
+ assert order in expected_order
minigpt2/lib/python3.10/site-packages/networkx/linalg/tests/test_attrmatrix.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def test_attr_matrix():
9
+ G = nx.Graph()
10
+ G.add_edge(0, 1, thickness=1, weight=3)
11
+ G.add_edge(0, 1, thickness=1, weight=3)
12
+ G.add_edge(0, 2, thickness=2)
13
+ G.add_edge(1, 2, thickness=3)
14
+
15
+ def node_attr(u):
16
+ return G.nodes[u].get("size", 0.5) * 3
17
+
18
+ def edge_attr(u, v):
19
+ return G[u][v].get("thickness", 0.5)
20
+
21
+ M = nx.attr_matrix(G, edge_attr=edge_attr, node_attr=node_attr)
22
+ np.testing.assert_equal(M[0], np.array([[6.0]]))
23
+ assert M[1] == [1.5]
24
+
25
+
26
+ def test_attr_matrix_directed():
27
+ G = nx.DiGraph()
28
+ G.add_edge(0, 1, thickness=1, weight=3)
29
+ G.add_edge(0, 1, thickness=1, weight=3)
30
+ G.add_edge(0, 2, thickness=2)
31
+ G.add_edge(1, 2, thickness=3)
32
+ M = nx.attr_matrix(G, rc_order=[0, 1, 2])
33
+ # fmt: off
34
+ data = np.array(
35
+ [[0., 1., 1.],
36
+ [0., 0., 1.],
37
+ [0., 0., 0.]]
38
+ )
39
+ # fmt: on
40
+ np.testing.assert_equal(M, np.array(data))
41
+
42
+
43
+ def test_attr_matrix_multigraph():
44
+ G = nx.MultiGraph()
45
+ G.add_edge(0, 1, thickness=1, weight=3)
46
+ G.add_edge(0, 1, thickness=1, weight=3)
47
+ G.add_edge(0, 1, thickness=1, weight=3)
48
+ G.add_edge(0, 2, thickness=2)
49
+ G.add_edge(1, 2, thickness=3)
50
+ M = nx.attr_matrix(G, rc_order=[0, 1, 2])
51
+ # fmt: off
52
+ data = np.array(
53
+ [[0., 3., 1.],
54
+ [3., 0., 1.],
55
+ [1., 1., 0.]]
56
+ )
57
+ # fmt: on
58
+ np.testing.assert_equal(M, np.array(data))
59
+ M = nx.attr_matrix(G, edge_attr="weight", rc_order=[0, 1, 2])
60
+ # fmt: off
61
+ data = np.array(
62
+ [[0., 9., 1.],
63
+ [9., 0., 1.],
64
+ [1., 1., 0.]]
65
+ )
66
+ # fmt: on
67
+ np.testing.assert_equal(M, np.array(data))
68
+ M = nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
69
+ # fmt: off
70
+ data = np.array(
71
+ [[0., 3., 2.],
72
+ [3., 0., 3.],
73
+ [2., 3., 0.]]
74
+ )
75
+ # fmt: on
76
+ np.testing.assert_equal(M, np.array(data))
77
+
78
+
79
+ def test_attr_sparse_matrix():
80
+ pytest.importorskip("scipy")
81
+ G = nx.Graph()
82
+ G.add_edge(0, 1, thickness=1, weight=3)
83
+ G.add_edge(0, 2, thickness=2)
84
+ G.add_edge(1, 2, thickness=3)
85
+ M = nx.attr_sparse_matrix(G)
86
+ mtx = M[0]
87
+ data = np.ones((3, 3), float)
88
+ np.fill_diagonal(data, 0)
89
+ np.testing.assert_equal(mtx.todense(), np.array(data))
90
+ assert M[1] == [0, 1, 2]
91
+
92
+
93
+ def test_attr_sparse_matrix_directed():
94
+ pytest.importorskip("scipy")
95
+ G = nx.DiGraph()
96
+ G.add_edge(0, 1, thickness=1, weight=3)
97
+ G.add_edge(0, 1, thickness=1, weight=3)
98
+ G.add_edge(0, 2, thickness=2)
99
+ G.add_edge(1, 2, thickness=3)
100
+ M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2])
101
+ # fmt: off
102
+ data = np.array(
103
+ [[0., 1., 1.],
104
+ [0., 0., 1.],
105
+ [0., 0., 0.]]
106
+ )
107
+ # fmt: on
108
+ np.testing.assert_equal(M.todense(), np.array(data))