ZTWHHH commited on
Commit
ab4fc75
·
verified ·
1 Parent(s): afeefb6

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. wemm/lib/python3.10/site-packages/botocore/data/schemas/2019-12-02/endpoint-rule-set-1.json.gz +3 -0
  2. wemm/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/gomory_hu.cpython-310.pyc +0 -0
  3. wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/breadth_first_search.cpython-310.pyc +0 -0
  4. wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/tests/__pycache__/test_beamsearch.cpython-310.pyc +0 -0
  5. wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/tests/__pycache__/test_edgebfs.cpython-310.pyc +0 -0
  6. wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/tests/test_dfs.py +305 -0
  7. wemm/lib/python3.10/site-packages/networkx/algorithms/tree/__pycache__/mst.cpython-310.pyc +0 -0
  8. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc +0 -0
  9. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc +0 -0
  10. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc +0 -0
  11. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc +0 -0
  12. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc +0 -0
  13. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc +0 -0
  14. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc +0 -0
  15. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc +0 -0
  16. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc +0 -0
  17. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc +0 -0
  18. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc +0 -0
  19. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc +0 -0
  20. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc +0 -0
  21. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc +0 -0
  22. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc +0 -0
  23. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc +0 -0
  24. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc +0 -0
  25. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc +0 -0
  26. wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc +0 -0
  27. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  28. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc +0 -0
  29. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc +0 -0
  30. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc +0 -0
  31. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc +0 -0
  32. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc +0 -0
  33. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-310.pyc +0 -0
  34. wemm/lib/python3.10/site-packages/networkx/generators/tests/test_triads.py +15 -0
  35. wemm/lib/python3.10/site-packages/networkx/linalg/__init__.py +13 -0
  36. wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
  37. wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc +0 -0
  38. wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc +0 -0
  39. wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc +0 -0
  40. wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc +0 -0
  41. wemm/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py +657 -0
  42. wemm/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py +465 -0
  43. wemm/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py +79 -0
  44. wemm/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py +168 -0
  45. wemm/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py +617 -0
  46. wemm/lib/python3.10/site-packages/networkx/linalg/spectrum.py +186 -0
  47. wemm/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py +0 -0
  48. wemm/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  49. wemm/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc +0 -0
  50. wemm/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc +0 -0
wemm/lib/python3.10/site-packages/botocore/data/schemas/2019-12-02/endpoint-rule-set-1.json.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af42a70c3fed77a8cdfc96011b2830a6bacf903b8315b72adeda63d5a953ea72
3
+ size 1146
wemm/lib/python3.10/site-packages/networkx/algorithms/flow/__pycache__/gomory_hu.cpython-310.pyc ADDED
Binary file (5.87 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/__pycache__/breadth_first_search.cpython-310.pyc ADDED
Binary file (17 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/tests/__pycache__/test_beamsearch.cpython-310.pyc ADDED
Binary file (1.16 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/tests/__pycache__/test_edgebfs.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/traversal/tests/test_dfs.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+
4
+ class TestDFS:
5
+ @classmethod
6
+ def setup_class(cls):
7
+ # simple graph
8
+ G = nx.Graph()
9
+ G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 0), (0, 4)])
10
+ cls.G = G
11
+ # simple graph, disconnected
12
+ D = nx.Graph()
13
+ D.add_edges_from([(0, 1), (2, 3)])
14
+ cls.D = D
15
+
16
+ def test_preorder_nodes(self):
17
+ assert list(nx.dfs_preorder_nodes(self.G, source=0)) == [0, 1, 2, 4, 3]
18
+ assert list(nx.dfs_preorder_nodes(self.D)) == [0, 1, 2, 3]
19
+ assert list(nx.dfs_preorder_nodes(self.D, source=2)) == [2, 3]
20
+
21
+ def test_postorder_nodes(self):
22
+ assert list(nx.dfs_postorder_nodes(self.G, source=0)) == [4, 2, 3, 1, 0]
23
+ assert list(nx.dfs_postorder_nodes(self.D)) == [1, 0, 3, 2]
24
+ assert list(nx.dfs_postorder_nodes(self.D, source=0)) == [1, 0]
25
+
26
+ def test_successor(self):
27
+ assert nx.dfs_successors(self.G, source=0) == {0: [1], 1: [2, 3], 2: [4]}
28
+ assert nx.dfs_successors(self.G, source=1) == {0: [3, 4], 1: [0], 4: [2]}
29
+ assert nx.dfs_successors(self.D) == {0: [1], 2: [3]}
30
+ assert nx.dfs_successors(self.D, source=1) == {1: [0]}
31
+
32
+ def test_predecessor(self):
33
+ assert nx.dfs_predecessors(self.G, source=0) == {1: 0, 2: 1, 3: 1, 4: 2}
34
+ assert nx.dfs_predecessors(self.D) == {1: 0, 3: 2}
35
+
36
+ def test_dfs_tree(self):
37
+ exp_nodes = sorted(self.G.nodes())
38
+ exp_edges = [(0, 1), (1, 2), (1, 3), (2, 4)]
39
+ # Search from first node
40
+ T = nx.dfs_tree(self.G, source=0)
41
+ assert sorted(T.nodes()) == exp_nodes
42
+ assert sorted(T.edges()) == exp_edges
43
+ # Check source=None
44
+ T = nx.dfs_tree(self.G, source=None)
45
+ assert sorted(T.nodes()) == exp_nodes
46
+ assert sorted(T.edges()) == exp_edges
47
+ # Check source=None is the default
48
+ T = nx.dfs_tree(self.G)
49
+ assert sorted(T.nodes()) == exp_nodes
50
+ assert sorted(T.edges()) == exp_edges
51
+
52
+ def test_dfs_edges(self):
53
+ edges = nx.dfs_edges(self.G, source=0)
54
+ assert list(edges) == [(0, 1), (1, 2), (2, 4), (1, 3)]
55
+ edges = nx.dfs_edges(self.D)
56
+ assert list(edges) == [(0, 1), (2, 3)]
57
+
58
+ def test_dfs_edges_sorting(self):
59
+ G = nx.Graph([(0, 1), (1, 2), (1, 3), (2, 4), (3, 0), (0, 4)])
60
+ edges_asc = nx.dfs_edges(G, source=0, sort_neighbors=sorted)
61
+ sorted_desc = lambda x: sorted(x, reverse=True)
62
+ edges_desc = nx.dfs_edges(G, source=0, sort_neighbors=sorted_desc)
63
+ assert list(edges_asc) == [(0, 1), (1, 2), (2, 4), (1, 3)]
64
+ assert list(edges_desc) == [(0, 4), (4, 2), (2, 1), (1, 3)]
65
+
66
+ def test_dfs_labeled_edges(self):
67
+ edges = list(nx.dfs_labeled_edges(self.G, source=0))
68
+ forward = [(u, v) for (u, v, d) in edges if d == "forward"]
69
+ assert forward == [(0, 0), (0, 1), (1, 2), (2, 4), (1, 3)]
70
+ assert edges == [
71
+ (0, 0, "forward"),
72
+ (0, 1, "forward"),
73
+ (1, 0, "nontree"),
74
+ (1, 2, "forward"),
75
+ (2, 1, "nontree"),
76
+ (2, 4, "forward"),
77
+ (4, 2, "nontree"),
78
+ (4, 0, "nontree"),
79
+ (2, 4, "reverse"),
80
+ (1, 2, "reverse"),
81
+ (1, 3, "forward"),
82
+ (3, 1, "nontree"),
83
+ (3, 0, "nontree"),
84
+ (1, 3, "reverse"),
85
+ (0, 1, "reverse"),
86
+ (0, 3, "nontree"),
87
+ (0, 4, "nontree"),
88
+ (0, 0, "reverse"),
89
+ ]
90
+
91
+ def test_dfs_labeled_edges_sorting(self):
92
+ G = nx.Graph([(0, 1), (1, 2), (1, 3), (2, 4), (3, 0), (0, 4)])
93
+ edges_asc = nx.dfs_labeled_edges(G, source=0, sort_neighbors=sorted)
94
+ sorted_desc = lambda x: sorted(x, reverse=True)
95
+ edges_desc = nx.dfs_labeled_edges(G, source=0, sort_neighbors=sorted_desc)
96
+ assert list(edges_asc) == [
97
+ (0, 0, "forward"),
98
+ (0, 1, "forward"),
99
+ (1, 0, "nontree"),
100
+ (1, 2, "forward"),
101
+ (2, 1, "nontree"),
102
+ (2, 4, "forward"),
103
+ (4, 0, "nontree"),
104
+ (4, 2, "nontree"),
105
+ (2, 4, "reverse"),
106
+ (1, 2, "reverse"),
107
+ (1, 3, "forward"),
108
+ (3, 0, "nontree"),
109
+ (3, 1, "nontree"),
110
+ (1, 3, "reverse"),
111
+ (0, 1, "reverse"),
112
+ (0, 3, "nontree"),
113
+ (0, 4, "nontree"),
114
+ (0, 0, "reverse"),
115
+ ]
116
+ assert list(edges_desc) == [
117
+ (0, 0, "forward"),
118
+ (0, 4, "forward"),
119
+ (4, 2, "forward"),
120
+ (2, 4, "nontree"),
121
+ (2, 1, "forward"),
122
+ (1, 3, "forward"),
123
+ (3, 1, "nontree"),
124
+ (3, 0, "nontree"),
125
+ (1, 3, "reverse"),
126
+ (1, 2, "nontree"),
127
+ (1, 0, "nontree"),
128
+ (2, 1, "reverse"),
129
+ (4, 2, "reverse"),
130
+ (4, 0, "nontree"),
131
+ (0, 4, "reverse"),
132
+ (0, 3, "nontree"),
133
+ (0, 1, "nontree"),
134
+ (0, 0, "reverse"),
135
+ ]
136
+
137
+ def test_dfs_labeled_disconnected_edges(self):
138
+ edges = list(nx.dfs_labeled_edges(self.D))
139
+ forward = [(u, v) for (u, v, d) in edges if d == "forward"]
140
+ assert forward == [(0, 0), (0, 1), (2, 2), (2, 3)]
141
+ assert edges == [
142
+ (0, 0, "forward"),
143
+ (0, 1, "forward"),
144
+ (1, 0, "nontree"),
145
+ (0, 1, "reverse"),
146
+ (0, 0, "reverse"),
147
+ (2, 2, "forward"),
148
+ (2, 3, "forward"),
149
+ (3, 2, "nontree"),
150
+ (2, 3, "reverse"),
151
+ (2, 2, "reverse"),
152
+ ]
153
+
154
+ def test_dfs_tree_isolates(self):
155
+ G = nx.Graph()
156
+ G.add_node(1)
157
+ G.add_node(2)
158
+ T = nx.dfs_tree(G, source=1)
159
+ assert sorted(T.nodes()) == [1]
160
+ assert sorted(T.edges()) == []
161
+ T = nx.dfs_tree(G, source=None)
162
+ assert sorted(T.nodes()) == [1, 2]
163
+ assert sorted(T.edges()) == []
164
+
165
+
166
+ class TestDepthLimitedSearch:
167
+ @classmethod
168
+ def setup_class(cls):
169
+ # a tree
170
+ G = nx.Graph()
171
+ nx.add_path(G, [0, 1, 2, 3, 4, 5, 6])
172
+ nx.add_path(G, [2, 7, 8, 9, 10])
173
+ cls.G = G
174
+ # a disconnected graph
175
+ D = nx.Graph()
176
+ D.add_edges_from([(0, 1), (2, 3)])
177
+ nx.add_path(D, [2, 7, 8, 9, 10])
178
+ cls.D = D
179
+
180
+ def test_dls_preorder_nodes(self):
181
+ assert list(nx.dfs_preorder_nodes(self.G, source=0, depth_limit=2)) == [0, 1, 2]
182
+ assert list(nx.dfs_preorder_nodes(self.D, source=1, depth_limit=2)) == ([1, 0])
183
+
184
+ def test_dls_postorder_nodes(self):
185
+ assert list(nx.dfs_postorder_nodes(self.G, source=3, depth_limit=3)) == [
186
+ 1,
187
+ 7,
188
+ 2,
189
+ 5,
190
+ 4,
191
+ 3,
192
+ ]
193
+ assert list(nx.dfs_postorder_nodes(self.D, source=2, depth_limit=2)) == (
194
+ [3, 7, 2]
195
+ )
196
+
197
+ def test_dls_successor(self):
198
+ result = nx.dfs_successors(self.G, source=4, depth_limit=3)
199
+ assert {n: set(v) for n, v in result.items()} == {
200
+ 2: {1, 7},
201
+ 3: {2},
202
+ 4: {3, 5},
203
+ 5: {6},
204
+ }
205
+ result = nx.dfs_successors(self.D, source=7, depth_limit=2)
206
+ assert {n: set(v) for n, v in result.items()} == {8: {9}, 2: {3}, 7: {8, 2}}
207
+
208
+ def test_dls_predecessor(self):
209
+ assert nx.dfs_predecessors(self.G, source=0, depth_limit=3) == {
210
+ 1: 0,
211
+ 2: 1,
212
+ 3: 2,
213
+ 7: 2,
214
+ }
215
+ assert nx.dfs_predecessors(self.D, source=2, depth_limit=3) == {
216
+ 8: 7,
217
+ 9: 8,
218
+ 3: 2,
219
+ 7: 2,
220
+ }
221
+
222
+ def test_dls_tree(self):
223
+ T = nx.dfs_tree(self.G, source=3, depth_limit=1)
224
+ assert sorted(T.edges()) == [(3, 2), (3, 4)]
225
+
226
+ def test_dls_edges(self):
227
+ edges = nx.dfs_edges(self.G, source=9, depth_limit=4)
228
+ assert list(edges) == [(9, 8), (8, 7), (7, 2), (2, 1), (2, 3), (9, 10)]
229
+
230
+ def test_dls_labeled_edges_depth_1(self):
231
+ edges = list(nx.dfs_labeled_edges(self.G, source=5, depth_limit=1))
232
+ forward = [(u, v) for (u, v, d) in edges if d == "forward"]
233
+ assert forward == [(5, 5), (5, 4), (5, 6)]
234
+ # Note: reverse-depth_limit edge types were not reported before gh-6240
235
+ assert edges == [
236
+ (5, 5, "forward"),
237
+ (5, 4, "forward"),
238
+ (5, 4, "reverse-depth_limit"),
239
+ (5, 6, "forward"),
240
+ (5, 6, "reverse-depth_limit"),
241
+ (5, 5, "reverse"),
242
+ ]
243
+
244
+ def test_dls_labeled_edges_depth_2(self):
245
+ edges = list(nx.dfs_labeled_edges(self.G, source=6, depth_limit=2))
246
+ forward = [(u, v) for (u, v, d) in edges if d == "forward"]
247
+ assert forward == [(6, 6), (6, 5), (5, 4)]
248
+ assert edges == [
249
+ (6, 6, "forward"),
250
+ (6, 5, "forward"),
251
+ (5, 4, "forward"),
252
+ (5, 4, "reverse-depth_limit"),
253
+ (5, 6, "nontree"),
254
+ (6, 5, "reverse"),
255
+ (6, 6, "reverse"),
256
+ ]
257
+
258
+ def test_dls_labeled_disconnected_edges(self):
259
+ edges = list(nx.dfs_labeled_edges(self.D, depth_limit=1))
260
+ assert edges == [
261
+ (0, 0, "forward"),
262
+ (0, 1, "forward"),
263
+ (0, 1, "reverse-depth_limit"),
264
+ (0, 0, "reverse"),
265
+ (2, 2, "forward"),
266
+ (2, 3, "forward"),
267
+ (2, 3, "reverse-depth_limit"),
268
+ (2, 7, "forward"),
269
+ (2, 7, "reverse-depth_limit"),
270
+ (2, 2, "reverse"),
271
+ (8, 8, "forward"),
272
+ (8, 7, "nontree"),
273
+ (8, 9, "forward"),
274
+ (8, 9, "reverse-depth_limit"),
275
+ (8, 8, "reverse"),
276
+ (10, 10, "forward"),
277
+ (10, 9, "nontree"),
278
+ (10, 10, "reverse"),
279
+ ]
280
+ # large depth_limit has no impact
281
+ edges = list(nx.dfs_labeled_edges(self.D, depth_limit=19))
282
+ assert edges == [
283
+ (0, 0, "forward"),
284
+ (0, 1, "forward"),
285
+ (1, 0, "nontree"),
286
+ (0, 1, "reverse"),
287
+ (0, 0, "reverse"),
288
+ (2, 2, "forward"),
289
+ (2, 3, "forward"),
290
+ (3, 2, "nontree"),
291
+ (2, 3, "reverse"),
292
+ (2, 7, "forward"),
293
+ (7, 2, "nontree"),
294
+ (7, 8, "forward"),
295
+ (8, 7, "nontree"),
296
+ (8, 9, "forward"),
297
+ (9, 8, "nontree"),
298
+ (9, 10, "forward"),
299
+ (10, 9, "nontree"),
300
+ (9, 10, "reverse"),
301
+ (8, 9, "reverse"),
302
+ (7, 8, "reverse"),
303
+ (2, 7, "reverse"),
304
+ (2, 2, "reverse"),
305
+ ]
wemm/lib/python3.10/site-packages/networkx/algorithms/tree/__pycache__/mst.cpython-310.pyc ADDED
Binary file (36.9 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc ADDED
Binary file (2.22 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc ADDED
Binary file (31.2 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc ADDED
Binary file (5.06 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc ADDED
Binary file (4.25 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc ADDED
Binary file (5.64 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc ADDED
Binary file (1.99 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc ADDED
Binary file (34.3 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (175 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc ADDED
Binary file (7 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc ADDED
Binary file (3.25 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-310.pyc ADDED
Binary file (856 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/test_triads.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.triads` module."""
2
+
3
+ import pytest
4
+
5
+ from networkx import triad_graph
6
+
7
+
8
+ def test_triad_graph():
9
+ G = triad_graph("030T")
10
+ assert [tuple(e) for e in ("ab", "ac", "cb")] == sorted(G.edges())
11
+
12
+
13
+ def test_invalid_name():
14
+ with pytest.raises(ValueError):
15
+ triad_graph("bogus")
wemm/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
wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (698 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc ADDED
Binary file (4.71 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc ADDED
Binary file (4.41 kB). View file
 
wemm/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())
wemm/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
wemm/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
wemm/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)
wemm/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
wemm/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())
wemm/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (171 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc ADDED
Binary file (3.1 kB). View file