ZTWHHH commited on
Commit
0c20e07
·
verified ·
1 Parent(s): 4b28474

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. .gitattributes +1 -0
  2. janus/lib/libtinfow.so.6 +3 -0
  3. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc +0 -0
  5. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc +0 -0
  6. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc +0 -0
  7. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc +0 -0
  8. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc +0 -0
  9. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc +0 -0
  10. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc +0 -0
  11. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc +0 -0
  12. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc +0 -0
  13. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc +0 -0
  14. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc +0 -0
  15. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc +0 -0
  16. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc +0 -0
  17. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc +0 -0
  18. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc +0 -0
  19. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc +0 -0
  20. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc +0 -0
  21. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc +0 -0
  22. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc +0 -0
  23. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc +0 -0
  24. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc +0 -0
  25. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc +0 -0
  26. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc +0 -0
  27. janus/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz +3 -0
  28. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc +0 -0
  29. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc +0 -0
  30. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc +0 -0
  31. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc +0 -0
  32. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc +0 -0
  33. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-310.pyc +0 -0
  34. janus/lib/python3.10/site-packages/networkx/generators/tests/test_classic.py +640 -0
  35. janus/lib/python3.10/site-packages/networkx/generators/tests/test_community.py +362 -0
  36. janus/lib/python3.10/site-packages/networkx/generators/tests/test_directed.py +163 -0
  37. janus/lib/python3.10/site-packages/networkx/generators/tests/test_lattice.py +246 -0
  38. janus/lib/python3.10/site-packages/networkx/generators/tests/test_spectral_graph_forge.py +49 -0
  39. janus/lib/python3.10/site-packages/networkx/generators/tests/test_time_series.py +64 -0
  40. janus/lib/python3.10/site-packages/networkx/linalg/__init__.py +13 -0
  41. janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc +0 -0
  42. janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py +657 -0
  46. janus/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py +465 -0
  47. janus/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py +79 -0
  48. janus/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py +168 -0
  49. janus/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py +617 -0
  50. janus/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py +166 -0
.gitattributes CHANGED
@@ -438,3 +438,4 @@ deepseek/lib/python3.10/site-packages/timm/models/__pycache__/vision_transformer
438
  deepseek/lib/python3.10/site-packages/pyarrow/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
439
  deepseek/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
440
  janus/lib/libtinfow.so filter=lfs diff=lfs merge=lfs -text
 
 
438
  deepseek/lib/python3.10/site-packages/pyarrow/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
439
  deepseek/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
440
  janus/lib/libtinfow.so filter=lfs diff=lfs merge=lfs -text
441
+ janus/lib/libtinfow.so.6 filter=lfs diff=lfs merge=lfs -text
janus/lib/libtinfow.so.6 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ce4e329189b38682e806046f803063f032d007c68737923b8362ce10570c653
3
+ size 287080
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc ADDED
Binary file (4.32 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc ADDED
Binary file (29.8 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc ADDED
Binary file (2.22 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc ADDED
Binary file (31.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc ADDED
Binary file (25.6 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc ADDED
Binary file (5.06 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc ADDED
Binary file (4.79 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc ADDED
Binary file (4.25 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc ADDED
Binary file (5.64 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc ADDED
Binary file (40.2 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc ADDED
Binary file (4.22 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc ADDED
Binary file (1.99 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc ADDED
Binary file (34.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73fc416df0164923607751cb759f4ae81deb5f6550bf25be59c86de3b747e41d
3
+ size 8887
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc ADDED
Binary file (3.57 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc ADDED
Binary file (8.63 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc ADDED
Binary file (7.41 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-310.pyc ADDED
Binary file (5.69 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/test_classic.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ====================
3
+ Generators - Classic
4
+ ====================
5
+
6
+ Unit tests for various classic graph generators in generators/classic.py
7
+ """
8
+
9
+ import itertools
10
+ import typing
11
+
12
+ import pytest
13
+
14
+ import networkx as nx
15
+ from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic
16
+ from networkx.utils import edges_equal, nodes_equal
17
+
18
+ is_isomorphic = graph_could_be_isomorphic
19
+
20
+
21
+ class TestGeneratorClassic:
22
+ def test_balanced_tree(self):
23
+ # balanced_tree(r,h) is a tree with (r**(h+1)-1)/(r-1) edges
24
+ for r, h in [(2, 2), (3, 3), (6, 2)]:
25
+ t = nx.balanced_tree(r, h)
26
+ order = t.order()
27
+ assert order == (r ** (h + 1) - 1) / (r - 1)
28
+ assert nx.is_connected(t)
29
+ assert t.size() == order - 1
30
+ dh = nx.degree_histogram(t)
31
+ assert dh[0] == 0 # no nodes of 0
32
+ assert dh[1] == r**h # nodes of degree 1 are leaves
33
+ assert dh[r] == 1 # root is degree r
34
+ assert dh[r + 1] == order - r**h - 1 # everyone else is degree r+1
35
+ assert len(dh) == r + 2
36
+
37
+ def test_balanced_tree_star(self):
38
+ # balanced_tree(r,1) is the r-star
39
+ t = nx.balanced_tree(r=2, h=1)
40
+ assert is_isomorphic(t, nx.star_graph(2))
41
+ t = nx.balanced_tree(r=5, h=1)
42
+ assert is_isomorphic(t, nx.star_graph(5))
43
+ t = nx.balanced_tree(r=10, h=1)
44
+ assert is_isomorphic(t, nx.star_graph(10))
45
+
46
+ def test_balanced_tree_path(self):
47
+ """Tests that the balanced tree with branching factor one is the
48
+ path graph.
49
+
50
+ """
51
+ # A tree of height four has five levels.
52
+ T = nx.balanced_tree(1, 4)
53
+ P = nx.path_graph(5)
54
+ assert is_isomorphic(T, P)
55
+
56
+ def test_full_rary_tree(self):
57
+ r = 2
58
+ n = 9
59
+ t = nx.full_rary_tree(r, n)
60
+ assert t.order() == n
61
+ assert nx.is_connected(t)
62
+ dh = nx.degree_histogram(t)
63
+ assert dh[0] == 0 # no nodes of 0
64
+ assert dh[1] == 5 # nodes of degree 1 are leaves
65
+ assert dh[r] == 1 # root is degree r
66
+ assert dh[r + 1] == 9 - 5 - 1 # everyone else is degree r+1
67
+ assert len(dh) == r + 2
68
+
69
+ def test_full_rary_tree_balanced(self):
70
+ t = nx.full_rary_tree(2, 15)
71
+ th = nx.balanced_tree(2, 3)
72
+ assert is_isomorphic(t, th)
73
+
74
+ def test_full_rary_tree_path(self):
75
+ t = nx.full_rary_tree(1, 10)
76
+ assert is_isomorphic(t, nx.path_graph(10))
77
+
78
+ def test_full_rary_tree_empty(self):
79
+ t = nx.full_rary_tree(0, 10)
80
+ assert is_isomorphic(t, nx.empty_graph(10))
81
+ t = nx.full_rary_tree(3, 0)
82
+ assert is_isomorphic(t, nx.empty_graph(0))
83
+
84
+ def test_full_rary_tree_3_20(self):
85
+ t = nx.full_rary_tree(3, 20)
86
+ assert t.order() == 20
87
+
88
+ def test_barbell_graph(self):
89
+ # number of nodes = 2*m1 + m2 (2 m1-complete graphs + m2-path + 2 edges)
90
+ # number of edges = 2*(nx.number_of_edges(m1-complete graph) + m2 + 1
91
+ m1 = 3
92
+ m2 = 5
93
+ b = nx.barbell_graph(m1, m2)
94
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
95
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
96
+
97
+ m1 = 4
98
+ m2 = 10
99
+ b = nx.barbell_graph(m1, m2)
100
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
101
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
102
+
103
+ m1 = 3
104
+ m2 = 20
105
+ b = nx.barbell_graph(m1, m2)
106
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
107
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
108
+
109
+ # Raise NetworkXError if m1<2
110
+ m1 = 1
111
+ m2 = 20
112
+ pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
113
+
114
+ # Raise NetworkXError if m2<0
115
+ m1 = 5
116
+ m2 = -2
117
+ pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
118
+
119
+ # nx.barbell_graph(2,m) = nx.path_graph(m+4)
120
+ m1 = 2
121
+ m2 = 5
122
+ b = nx.barbell_graph(m1, m2)
123
+ assert is_isomorphic(b, nx.path_graph(m2 + 4))
124
+
125
+ m1 = 2
126
+ m2 = 10
127
+ b = nx.barbell_graph(m1, m2)
128
+ assert is_isomorphic(b, nx.path_graph(m2 + 4))
129
+
130
+ m1 = 2
131
+ m2 = 20
132
+ b = nx.barbell_graph(m1, m2)
133
+ assert is_isomorphic(b, nx.path_graph(m2 + 4))
134
+
135
+ pytest.raises(
136
+ nx.NetworkXError, nx.barbell_graph, m1, m2, create_using=nx.DiGraph()
137
+ )
138
+
139
+ mb = nx.barbell_graph(m1, m2, create_using=nx.MultiGraph())
140
+ assert edges_equal(mb.edges(), b.edges())
141
+
142
+ def test_binomial_tree(self):
143
+ graphs = (None, nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
144
+ for create_using in graphs:
145
+ for n in range(4):
146
+ b = nx.binomial_tree(n, create_using)
147
+ assert nx.number_of_nodes(b) == 2**n
148
+ assert nx.number_of_edges(b) == (2**n - 1)
149
+
150
+ def test_complete_graph(self):
151
+ # complete_graph(m) is a connected graph with
152
+ # m nodes and m*(m+1)/2 edges
153
+ for m in [0, 1, 3, 5]:
154
+ g = nx.complete_graph(m)
155
+ assert nx.number_of_nodes(g) == m
156
+ assert nx.number_of_edges(g) == m * (m - 1) // 2
157
+
158
+ mg = nx.complete_graph(m, create_using=nx.MultiGraph)
159
+ assert edges_equal(mg.edges(), g.edges())
160
+
161
+ g = nx.complete_graph("abc")
162
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
163
+ assert g.size() == 3
164
+
165
+ # creates a self-loop... should it? <backward compatible says yes>
166
+ g = nx.complete_graph("abcb")
167
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
168
+ assert g.size() == 4
169
+
170
+ g = nx.complete_graph("abcb", create_using=nx.MultiGraph)
171
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
172
+ assert g.size() == 6
173
+
174
+ def test_complete_digraph(self):
175
+ # complete_graph(m) is a connected graph with
176
+ # m nodes and m*(m+1)/2 edges
177
+ for m in [0, 1, 3, 5]:
178
+ g = nx.complete_graph(m, create_using=nx.DiGraph)
179
+ assert nx.number_of_nodes(g) == m
180
+ assert nx.number_of_edges(g) == m * (m - 1)
181
+
182
+ g = nx.complete_graph("abc", create_using=nx.DiGraph)
183
+ assert len(g) == 3
184
+ assert g.size() == 6
185
+ assert g.is_directed()
186
+
187
+ def test_circular_ladder_graph(self):
188
+ G = nx.circular_ladder_graph(5)
189
+ pytest.raises(
190
+ nx.NetworkXError, nx.circular_ladder_graph, 5, create_using=nx.DiGraph
191
+ )
192
+ mG = nx.circular_ladder_graph(5, create_using=nx.MultiGraph)
193
+ assert edges_equal(mG.edges(), G.edges())
194
+
195
+ def test_circulant_graph(self):
196
+ # Ci_n(1) is the cycle graph for all n
197
+ Ci6_1 = nx.circulant_graph(6, [1])
198
+ C6 = nx.cycle_graph(6)
199
+ assert edges_equal(Ci6_1.edges(), C6.edges())
200
+
201
+ # Ci_n(1, 2, ..., n div 2) is the complete graph for all n
202
+ Ci7 = nx.circulant_graph(7, [1, 2, 3])
203
+ K7 = nx.complete_graph(7)
204
+ assert edges_equal(Ci7.edges(), K7.edges())
205
+
206
+ # Ci_6(1, 3) is K_3,3 i.e. the utility graph
207
+ Ci6_1_3 = nx.circulant_graph(6, [1, 3])
208
+ K3_3 = nx.complete_bipartite_graph(3, 3)
209
+ assert is_isomorphic(Ci6_1_3, K3_3)
210
+
211
+ def test_cycle_graph(self):
212
+ G = nx.cycle_graph(4)
213
+ assert edges_equal(G.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
214
+ mG = nx.cycle_graph(4, create_using=nx.MultiGraph)
215
+ assert edges_equal(mG.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
216
+ G = nx.cycle_graph(4, create_using=nx.DiGraph)
217
+ assert not G.has_edge(2, 1)
218
+ assert G.has_edge(1, 2)
219
+ assert G.is_directed()
220
+
221
+ G = nx.cycle_graph("abc")
222
+ assert len(G) == 3
223
+ assert G.size() == 3
224
+ G = nx.cycle_graph("abcb")
225
+ assert len(G) == 3
226
+ assert G.size() == 2
227
+ g = nx.cycle_graph("abc", nx.DiGraph)
228
+ assert len(g) == 3
229
+ assert g.size() == 3
230
+ assert g.is_directed()
231
+ g = nx.cycle_graph("abcb", nx.DiGraph)
232
+ assert len(g) == 3
233
+ assert g.size() == 4
234
+
235
+ def test_dorogovtsev_goltsev_mendes_graph(self):
236
+ G = nx.dorogovtsev_goltsev_mendes_graph(0)
237
+ assert edges_equal(G.edges(), [(0, 1)])
238
+ assert nodes_equal(list(G), [0, 1])
239
+ G = nx.dorogovtsev_goltsev_mendes_graph(1)
240
+ assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
241
+ assert nx.average_clustering(G) == 1.0
242
+ assert nx.average_shortest_path_length(G) == 1.0
243
+ assert sorted(nx.triangles(G).values()) == [1, 1, 1]
244
+ assert nx.is_planar(G)
245
+ G = nx.dorogovtsev_goltsev_mendes_graph(2)
246
+ assert nx.number_of_nodes(G) == 6
247
+ assert nx.number_of_edges(G) == 9
248
+ assert nx.average_clustering(G) == 0.75
249
+ assert nx.average_shortest_path_length(G) == 1.4
250
+ assert nx.is_planar(G)
251
+ G = nx.dorogovtsev_goltsev_mendes_graph(10)
252
+ assert nx.number_of_nodes(G) == 29526
253
+ assert nx.number_of_edges(G) == 59049
254
+ assert G.degree(0) == 1024
255
+ assert G.degree(1) == 1024
256
+ assert G.degree(2) == 1024
257
+
258
+ with pytest.raises(nx.NetworkXError, match=r"n must be greater than"):
259
+ nx.dorogovtsev_goltsev_mendes_graph(-1)
260
+ with pytest.raises(nx.NetworkXError, match=r"directed graph not supported"):
261
+ nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.DiGraph)
262
+ with pytest.raises(nx.NetworkXError, match=r"multigraph not supported"):
263
+ nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.MultiGraph)
264
+ with pytest.raises(nx.NetworkXError):
265
+ nx.dorogovtsev_goltsev_mendes_graph(7, create_using=nx.MultiDiGraph)
266
+
267
+ def test_create_using(self):
268
+ G = nx.empty_graph()
269
+ assert isinstance(G, nx.Graph)
270
+ pytest.raises(TypeError, nx.empty_graph, create_using=0.0)
271
+ pytest.raises(TypeError, nx.empty_graph, create_using="Graph")
272
+
273
+ G = nx.empty_graph(create_using=nx.MultiGraph)
274
+ assert isinstance(G, nx.MultiGraph)
275
+ G = nx.empty_graph(create_using=nx.DiGraph)
276
+ assert isinstance(G, nx.DiGraph)
277
+
278
+ G = nx.empty_graph(create_using=nx.DiGraph, default=nx.MultiGraph)
279
+ assert isinstance(G, nx.DiGraph)
280
+ G = nx.empty_graph(create_using=None, default=nx.MultiGraph)
281
+ assert isinstance(G, nx.MultiGraph)
282
+ G = nx.empty_graph(default=nx.MultiGraph)
283
+ assert isinstance(G, nx.MultiGraph)
284
+
285
+ G = nx.path_graph(5)
286
+ H = nx.empty_graph(create_using=G)
287
+ assert not H.is_multigraph()
288
+ assert not H.is_directed()
289
+ assert len(H) == 0
290
+ assert G is H
291
+
292
+ H = nx.empty_graph(create_using=nx.MultiGraph())
293
+ assert H.is_multigraph()
294
+ assert not H.is_directed()
295
+ assert G is not H
296
+
297
+ # test for subclasses that also use typing.Protocol. See gh-6243
298
+ class Mixin(typing.Protocol):
299
+ pass
300
+
301
+ class MyGraph(Mixin, nx.DiGraph):
302
+ pass
303
+
304
+ G = nx.empty_graph(create_using=MyGraph)
305
+
306
+ def test_empty_graph(self):
307
+ G = nx.empty_graph()
308
+ assert nx.number_of_nodes(G) == 0
309
+ G = nx.empty_graph(42)
310
+ assert nx.number_of_nodes(G) == 42
311
+ assert nx.number_of_edges(G) == 0
312
+
313
+ G = nx.empty_graph("abc")
314
+ assert len(G) == 3
315
+ assert G.size() == 0
316
+
317
+ # create empty digraph
318
+ G = nx.empty_graph(42, create_using=nx.DiGraph(name="duh"))
319
+ assert nx.number_of_nodes(G) == 42
320
+ assert nx.number_of_edges(G) == 0
321
+ assert isinstance(G, nx.DiGraph)
322
+
323
+ # create empty multigraph
324
+ G = nx.empty_graph(42, create_using=nx.MultiGraph(name="duh"))
325
+ assert nx.number_of_nodes(G) == 42
326
+ assert nx.number_of_edges(G) == 0
327
+ assert isinstance(G, nx.MultiGraph)
328
+
329
+ # create empty graph from another
330
+ pete = nx.petersen_graph()
331
+ G = nx.empty_graph(42, create_using=pete)
332
+ assert nx.number_of_nodes(G) == 42
333
+ assert nx.number_of_edges(G) == 0
334
+ assert isinstance(G, nx.Graph)
335
+
336
+ def test_ladder_graph(self):
337
+ for i, G in [
338
+ (0, nx.empty_graph(0)),
339
+ (1, nx.path_graph(2)),
340
+ (2, nx.hypercube_graph(2)),
341
+ (10, nx.grid_graph([2, 10])),
342
+ ]:
343
+ assert is_isomorphic(nx.ladder_graph(i), G)
344
+
345
+ pytest.raises(nx.NetworkXError, nx.ladder_graph, 2, create_using=nx.DiGraph)
346
+
347
+ g = nx.ladder_graph(2)
348
+ mg = nx.ladder_graph(2, create_using=nx.MultiGraph)
349
+ assert edges_equal(mg.edges(), g.edges())
350
+
351
+ @pytest.mark.parametrize(("m", "n"), [(3, 5), (4, 10), (3, 20)])
352
+ def test_lollipop_graph_right_sizes(self, m, n):
353
+ G = nx.lollipop_graph(m, n)
354
+ assert nx.number_of_nodes(G) == m + n
355
+ assert nx.number_of_edges(G) == m * (m - 1) / 2 + n
356
+
357
+ @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("abc", "defg")])
358
+ def test_lollipop_graph_size_node_sequence(self, m, n):
359
+ G = nx.lollipop_graph(m, n)
360
+ assert nx.number_of_nodes(G) == len(m) + len(n)
361
+ assert nx.number_of_edges(G) == len(m) * (len(m) - 1) / 2 + len(n)
362
+
363
+ def test_lollipop_graph_exceptions(self):
364
+ # Raise NetworkXError if m<2
365
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, -1, 2)
366
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, 1, 20)
367
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, "", 20)
368
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, "a", 20)
369
+
370
+ # Raise NetworkXError if n<0
371
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, 5, -2)
372
+
373
+ # raise NetworkXError if create_using is directed
374
+ with pytest.raises(nx.NetworkXError):
375
+ nx.lollipop_graph(2, 20, create_using=nx.DiGraph)
376
+ with pytest.raises(nx.NetworkXError):
377
+ nx.lollipop_graph(2, 20, create_using=nx.MultiDiGraph)
378
+
379
+ @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
380
+ def test_lollipop_graph_same_as_path_when_m1_is_2(self, m, n):
381
+ G = nx.lollipop_graph(m, n)
382
+ assert is_isomorphic(G, nx.path_graph(n + 2))
383
+
384
+ def test_lollipop_graph_for_multigraph(self):
385
+ G = nx.lollipop_graph(5, 20)
386
+ MG = nx.lollipop_graph(5, 20, create_using=nx.MultiGraph)
387
+ assert edges_equal(MG.edges(), G.edges())
388
+
389
+ @pytest.mark.parametrize(
390
+ ("m", "n"),
391
+ [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
392
+ )
393
+ def test_lollipop_graph_mixing_input_types(self, m, n):
394
+ expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
395
+ expected.add_edge(0, 100) # Connect complete graph and path graph
396
+ assert is_isomorphic(nx.lollipop_graph(m, n), expected)
397
+
398
+ def test_lollipop_graph_non_builtin_ints(self):
399
+ np = pytest.importorskip("numpy")
400
+ G = nx.lollipop_graph(np.int32(4), np.int64(3))
401
+ expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
402
+ expected.add_edge(0, 100) # Connect complete graph and path graph
403
+ assert is_isomorphic(G, expected)
404
+
405
+ def test_null_graph(self):
406
+ assert nx.number_of_nodes(nx.null_graph()) == 0
407
+
408
+ def test_path_graph(self):
409
+ p = nx.path_graph(0)
410
+ assert is_isomorphic(p, nx.null_graph())
411
+
412
+ p = nx.path_graph(1)
413
+ assert is_isomorphic(p, nx.empty_graph(1))
414
+
415
+ p = nx.path_graph(10)
416
+ assert nx.is_connected(p)
417
+ assert sorted(d for n, d in p.degree()) == [1, 1, 2, 2, 2, 2, 2, 2, 2, 2]
418
+ assert p.order() - 1 == p.size()
419
+
420
+ dp = nx.path_graph(3, create_using=nx.DiGraph)
421
+ assert dp.has_edge(0, 1)
422
+ assert not dp.has_edge(1, 0)
423
+
424
+ mp = nx.path_graph(10, create_using=nx.MultiGraph)
425
+ assert edges_equal(mp.edges(), p.edges())
426
+
427
+ G = nx.path_graph("abc")
428
+ assert len(G) == 3
429
+ assert G.size() == 2
430
+ G = nx.path_graph("abcb")
431
+ assert len(G) == 3
432
+ assert G.size() == 2
433
+ g = nx.path_graph("abc", nx.DiGraph)
434
+ assert len(g) == 3
435
+ assert g.size() == 2
436
+ assert g.is_directed()
437
+ g = nx.path_graph("abcb", nx.DiGraph)
438
+ assert len(g) == 3
439
+ assert g.size() == 3
440
+
441
+ G = nx.path_graph((1, 2, 3, 2, 4))
442
+ assert G.has_edge(2, 4)
443
+
444
+ def test_star_graph(self):
445
+ assert is_isomorphic(nx.star_graph(""), nx.empty_graph(0))
446
+ assert is_isomorphic(nx.star_graph([]), nx.empty_graph(0))
447
+ assert is_isomorphic(nx.star_graph(0), nx.empty_graph(1))
448
+ assert is_isomorphic(nx.star_graph(1), nx.path_graph(2))
449
+ assert is_isomorphic(nx.star_graph(2), nx.path_graph(3))
450
+ assert is_isomorphic(nx.star_graph(5), nx.complete_bipartite_graph(1, 5))
451
+
452
+ s = nx.star_graph(10)
453
+ assert sorted(d for n, d in s.degree()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10]
454
+
455
+ pytest.raises(nx.NetworkXError, nx.star_graph, 10, create_using=nx.DiGraph)
456
+
457
+ ms = nx.star_graph(10, create_using=nx.MultiGraph)
458
+ assert edges_equal(ms.edges(), s.edges())
459
+
460
+ G = nx.star_graph("abc")
461
+ assert len(G) == 3
462
+ assert G.size() == 2
463
+
464
+ G = nx.star_graph("abcb")
465
+ assert len(G) == 3
466
+ assert G.size() == 2
467
+ G = nx.star_graph("abcb", create_using=nx.MultiGraph)
468
+ assert len(G) == 3
469
+ assert G.size() == 3
470
+
471
+ G = nx.star_graph("abcdefg")
472
+ assert len(G) == 7
473
+ assert G.size() == 6
474
+
475
+ def test_non_int_integers_for_star_graph(self):
476
+ np = pytest.importorskip("numpy")
477
+ G = nx.star_graph(np.int32(3))
478
+ assert len(G) == 4
479
+ assert G.size() == 3
480
+
481
+ @pytest.mark.parametrize(("m", "n"), [(3, 0), (3, 5), (4, 10), (3, 20)])
482
+ def test_tadpole_graph_right_sizes(self, m, n):
483
+ G = nx.tadpole_graph(m, n)
484
+ assert nx.number_of_nodes(G) == m + n
485
+ assert nx.number_of_edges(G) == m + n - (m == 2)
486
+
487
+ @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("ab", "c"), ("abc", "defg")])
488
+ def test_tadpole_graph_size_node_sequences(self, m, n):
489
+ G = nx.tadpole_graph(m, n)
490
+ assert nx.number_of_nodes(G) == len(m) + len(n)
491
+ assert nx.number_of_edges(G) == len(m) + len(n) - (len(m) == 2)
492
+
493
+ def test_tadpole_graph_exceptions(self):
494
+ # Raise NetworkXError if m<2
495
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, -1, 3)
496
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 0, 3)
497
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 1, 3)
498
+
499
+ # Raise NetworkXError if n<0
500
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 5, -2)
501
+
502
+ # Raise NetworkXError for digraphs
503
+ with pytest.raises(nx.NetworkXError):
504
+ nx.tadpole_graph(2, 20, create_using=nx.DiGraph)
505
+ with pytest.raises(nx.NetworkXError):
506
+ nx.tadpole_graph(2, 20, create_using=nx.MultiDiGraph)
507
+
508
+ @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
509
+ def test_tadpole_graph_same_as_path_when_m_is_2(self, m, n):
510
+ G = nx.tadpole_graph(m, n)
511
+ assert is_isomorphic(G, nx.path_graph(n + 2))
512
+
513
+ @pytest.mark.parametrize("m", [4, 7])
514
+ def test_tadpole_graph_same_as_cycle_when_m2_is_0(self, m):
515
+ G = nx.tadpole_graph(m, 0)
516
+ assert is_isomorphic(G, nx.cycle_graph(m))
517
+
518
+ def test_tadpole_graph_for_multigraph(self):
519
+ G = nx.tadpole_graph(5, 20)
520
+ MG = nx.tadpole_graph(5, 20, create_using=nx.MultiGraph)
521
+ assert edges_equal(MG.edges(), G.edges())
522
+
523
+ @pytest.mark.parametrize(
524
+ ("m", "n"),
525
+ [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
526
+ )
527
+ def test_tadpole_graph_mixing_input_types(self, m, n):
528
+ expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
529
+ expected.add_edge(0, 100) # Connect cycle and path
530
+ assert is_isomorphic(nx.tadpole_graph(m, n), expected)
531
+
532
+ def test_tadpole_graph_non_builtin_integers(self):
533
+ np = pytest.importorskip("numpy")
534
+ G = nx.tadpole_graph(np.int32(4), np.int64(3))
535
+ expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
536
+ expected.add_edge(0, 100) # Connect cycle and path
537
+ assert is_isomorphic(G, expected)
538
+
539
+ def test_trivial_graph(self):
540
+ assert nx.number_of_nodes(nx.trivial_graph()) == 1
541
+
542
+ def test_turan_graph(self):
543
+ assert nx.number_of_edges(nx.turan_graph(13, 4)) == 63
544
+ assert is_isomorphic(
545
+ nx.turan_graph(13, 4), nx.complete_multipartite_graph(3, 4, 3, 3)
546
+ )
547
+
548
+ def test_wheel_graph(self):
549
+ for n, G in [
550
+ ("", nx.null_graph()),
551
+ (0, nx.null_graph()),
552
+ (1, nx.empty_graph(1)),
553
+ (2, nx.path_graph(2)),
554
+ (3, nx.complete_graph(3)),
555
+ (4, nx.complete_graph(4)),
556
+ ]:
557
+ g = nx.wheel_graph(n)
558
+ assert is_isomorphic(g, G)
559
+
560
+ g = nx.wheel_graph(10)
561
+ assert sorted(d for n, d in g.degree()) == [3, 3, 3, 3, 3, 3, 3, 3, 3, 9]
562
+
563
+ pytest.raises(nx.NetworkXError, nx.wheel_graph, 10, create_using=nx.DiGraph)
564
+
565
+ mg = nx.wheel_graph(10, create_using=nx.MultiGraph())
566
+ assert edges_equal(mg.edges(), g.edges())
567
+
568
+ G = nx.wheel_graph("abc")
569
+ assert len(G) == 3
570
+ assert G.size() == 3
571
+
572
+ G = nx.wheel_graph("abcb")
573
+ assert len(G) == 3
574
+ assert G.size() == 4
575
+ G = nx.wheel_graph("abcb", nx.MultiGraph)
576
+ assert len(G) == 3
577
+ assert G.size() == 6
578
+
579
+ def test_non_int_integers_for_wheel_graph(self):
580
+ np = pytest.importorskip("numpy")
581
+ G = nx.wheel_graph(np.int32(3))
582
+ assert len(G) == 3
583
+ assert G.size() == 3
584
+
585
+ def test_complete_0_partite_graph(self):
586
+ """Tests that the complete 0-partite graph is the null graph."""
587
+ G = nx.complete_multipartite_graph()
588
+ H = nx.null_graph()
589
+ assert nodes_equal(G, H)
590
+ assert edges_equal(G.edges(), H.edges())
591
+
592
+ def test_complete_1_partite_graph(self):
593
+ """Tests that the complete 1-partite graph is the empty graph."""
594
+ G = nx.complete_multipartite_graph(3)
595
+ H = nx.empty_graph(3)
596
+ assert nodes_equal(G, H)
597
+ assert edges_equal(G.edges(), H.edges())
598
+
599
+ def test_complete_2_partite_graph(self):
600
+ """Tests that the complete 2-partite graph is the complete bipartite
601
+ graph.
602
+
603
+ """
604
+ G = nx.complete_multipartite_graph(2, 3)
605
+ H = nx.complete_bipartite_graph(2, 3)
606
+ assert nodes_equal(G, H)
607
+ assert edges_equal(G.edges(), H.edges())
608
+
609
+ def test_complete_multipartite_graph(self):
610
+ """Tests for generating the complete multipartite graph."""
611
+ G = nx.complete_multipartite_graph(2, 3, 4)
612
+ blocks = [(0, 1), (2, 3, 4), (5, 6, 7, 8)]
613
+ # Within each block, no two vertices should be adjacent.
614
+ for block in blocks:
615
+ for u, v in itertools.combinations_with_replacement(block, 2):
616
+ assert v not in G[u]
617
+ assert G.nodes[u] == G.nodes[v]
618
+ # Across blocks, all vertices should be adjacent.
619
+ for block1, block2 in itertools.combinations(blocks, 2):
620
+ for u, v in itertools.product(block1, block2):
621
+ assert v in G[u]
622
+ assert G.nodes[u] != G.nodes[v]
623
+ with pytest.raises(nx.NetworkXError, match="Negative number of nodes"):
624
+ nx.complete_multipartite_graph(2, -3, 4)
625
+
626
+ def test_kneser_graph(self):
627
+ # the petersen graph is a special case of the kneser graph when n=5 and k=2
628
+ assert is_isomorphic(nx.kneser_graph(5, 2), nx.petersen_graph())
629
+
630
+ # when k is 1, the kneser graph returns a complete graph with n vertices
631
+ for i in range(1, 7):
632
+ assert is_isomorphic(nx.kneser_graph(i, 1), nx.complete_graph(i))
633
+
634
+ # the kneser graph of n and n-1 is the empty graph with n vertices
635
+ for j in range(3, 7):
636
+ assert is_isomorphic(nx.kneser_graph(j, j - 1), nx.empty_graph(j))
637
+
638
+ # in general the number of edges of the kneser graph is equal to
639
+ # (n choose k) times (n-k choose k) divided by 2
640
+ assert nx.number_of_edges(nx.kneser_graph(8, 3)) == 280
janus/lib/python3.10/site-packages/networkx/generators/tests/test_community.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_random_partition_graph():
7
+ G = nx.random_partition_graph([3, 3, 3], 1, 0, seed=42)
8
+ C = G.graph["partition"]
9
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
10
+ assert len(G) == 9
11
+ assert len(list(G.edges())) == 9
12
+
13
+ G = nx.random_partition_graph([3, 3, 3], 0, 1)
14
+ C = G.graph["partition"]
15
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
16
+ assert len(G) == 9
17
+ assert len(list(G.edges())) == 27
18
+
19
+ G = nx.random_partition_graph([3, 3, 3], 1, 0, directed=True)
20
+ C = G.graph["partition"]
21
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
22
+ assert len(G) == 9
23
+ assert len(list(G.edges())) == 18
24
+
25
+ G = nx.random_partition_graph([3, 3, 3], 0, 1, directed=True)
26
+ C = G.graph["partition"]
27
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
28
+ assert len(G) == 9
29
+ assert len(list(G.edges())) == 54
30
+
31
+ G = nx.random_partition_graph([1, 2, 3, 4, 5], 0.5, 0.1)
32
+ C = G.graph["partition"]
33
+ assert C == [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {10, 11, 12, 13, 14}]
34
+ assert len(G) == 15
35
+
36
+ rpg = nx.random_partition_graph
37
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 1.1, 0.1)
38
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], -0.1, 0.1)
39
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, 1.1)
40
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, -0.1)
41
+
42
+
43
+ def test_planted_partition_graph():
44
+ G = nx.planted_partition_graph(4, 3, 1, 0, seed=42)
45
+ C = G.graph["partition"]
46
+ assert len(C) == 4
47
+ assert len(G) == 12
48
+ assert len(list(G.edges())) == 12
49
+
50
+ G = nx.planted_partition_graph(4, 3, 0, 1)
51
+ C = G.graph["partition"]
52
+ assert len(C) == 4
53
+ assert len(G) == 12
54
+ assert len(list(G.edges())) == 54
55
+
56
+ G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42)
57
+ C = G.graph["partition"]
58
+ assert len(C) == 10
59
+ assert len(G) == 40
60
+
61
+ G = nx.planted_partition_graph(4, 3, 1, 0, directed=True)
62
+ C = G.graph["partition"]
63
+ assert len(C) == 4
64
+ assert len(G) == 12
65
+ assert len(list(G.edges())) == 24
66
+
67
+ G = nx.planted_partition_graph(4, 3, 0, 1, directed=True)
68
+ C = G.graph["partition"]
69
+ assert len(C) == 4
70
+ assert len(G) == 12
71
+ assert len(list(G.edges())) == 108
72
+
73
+ G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42, directed=True)
74
+ C = G.graph["partition"]
75
+ assert len(C) == 10
76
+ assert len(G) == 40
77
+
78
+ ppg = nx.planted_partition_graph
79
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 1.1, 0.1)
80
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, -0.1, 0.1)
81
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, 1.1)
82
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, -0.1)
83
+
84
+
85
+ def test_relaxed_caveman_graph():
86
+ G = nx.relaxed_caveman_graph(4, 3, 0)
87
+ assert len(G) == 12
88
+ G = nx.relaxed_caveman_graph(4, 3, 1)
89
+ assert len(G) == 12
90
+ G = nx.relaxed_caveman_graph(4, 3, 0.5)
91
+ assert len(G) == 12
92
+ G = nx.relaxed_caveman_graph(4, 3, 0.5, seed=42)
93
+ assert len(G) == 12
94
+
95
+
96
+ def test_connected_caveman_graph():
97
+ G = nx.connected_caveman_graph(4, 3)
98
+ assert len(G) == 12
99
+
100
+ G = nx.connected_caveman_graph(1, 5)
101
+ K5 = nx.complete_graph(5)
102
+ K5.remove_edge(3, 4)
103
+ assert nx.is_isomorphic(G, K5)
104
+
105
+ # need at least 2 nodes in each clique
106
+ pytest.raises(nx.NetworkXError, nx.connected_caveman_graph, 4, 1)
107
+
108
+
109
+ def test_caveman_graph():
110
+ G = nx.caveman_graph(4, 3)
111
+ assert len(G) == 12
112
+
113
+ G = nx.caveman_graph(5, 1)
114
+ E5 = nx.empty_graph(5)
115
+ assert nx.is_isomorphic(G, E5)
116
+
117
+ G = nx.caveman_graph(1, 5)
118
+ K5 = nx.complete_graph(5)
119
+ assert nx.is_isomorphic(G, K5)
120
+
121
+
122
+ def test_gaussian_random_partition_graph():
123
+ G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01)
124
+ assert len(G) == 100
125
+ G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True)
126
+ assert len(G) == 100
127
+ G = nx.gaussian_random_partition_graph(
128
+ 100, 10, 10, 0.3, 0.01, directed=False, seed=42
129
+ )
130
+ assert len(G) == 100
131
+ assert not isinstance(G, nx.DiGraph)
132
+ G = nx.gaussian_random_partition_graph(
133
+ 100, 10, 10, 0.3, 0.01, directed=True, seed=42
134
+ )
135
+ assert len(G) == 100
136
+ assert isinstance(G, nx.DiGraph)
137
+ pytest.raises(
138
+ nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0
139
+ )
140
+ # Test when clusters are likely less than 1
141
+ G = nx.gaussian_random_partition_graph(10, 0.5, 0.5, 0.5, 0.5, seed=1)
142
+ assert len(G) == 10
143
+
144
+
145
+ def test_ring_of_cliques():
146
+ for i in range(2, 20, 3):
147
+ for j in range(2, 20, 3):
148
+ G = nx.ring_of_cliques(i, j)
149
+ assert G.number_of_nodes() == i * j
150
+ if i != 2 or j != 1:
151
+ expected_num_edges = i * (((j * (j - 1)) // 2) + 1)
152
+ else:
153
+ # the edge that already exists cannot be duplicated
154
+ expected_num_edges = i * (((j * (j - 1)) // 2) + 1) - 1
155
+ assert G.number_of_edges() == expected_num_edges
156
+ with pytest.raises(
157
+ nx.NetworkXError, match="A ring of cliques must have at least two cliques"
158
+ ):
159
+ nx.ring_of_cliques(1, 5)
160
+ with pytest.raises(
161
+ nx.NetworkXError, match="The cliques must have at least two nodes"
162
+ ):
163
+ nx.ring_of_cliques(3, 0)
164
+
165
+
166
+ def test_windmill_graph():
167
+ for n in range(2, 20, 3):
168
+ for k in range(2, 20, 3):
169
+ G = nx.windmill_graph(n, k)
170
+ assert G.number_of_nodes() == (k - 1) * n + 1
171
+ assert G.number_of_edges() == n * k * (k - 1) / 2
172
+ assert G.degree(0) == G.number_of_nodes() - 1
173
+ for i in range(1, G.number_of_nodes()):
174
+ assert G.degree(i) == k - 1
175
+ with pytest.raises(
176
+ nx.NetworkXError, match="A windmill graph must have at least two cliques"
177
+ ):
178
+ nx.windmill_graph(1, 3)
179
+ with pytest.raises(
180
+ nx.NetworkXError, match="The cliques must have at least two nodes"
181
+ ):
182
+ nx.windmill_graph(3, 0)
183
+
184
+
185
+ def test_stochastic_block_model():
186
+ sizes = [75, 75, 300]
187
+ probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
188
+ G = nx.stochastic_block_model(sizes, probs, seed=0)
189
+ C = G.graph["partition"]
190
+ assert len(C) == 3
191
+ assert len(G) == 450
192
+ assert G.size() == 22160
193
+
194
+ GG = nx.stochastic_block_model(sizes, probs, range(450), seed=0)
195
+ assert G.nodes == GG.nodes
196
+
197
+ # Test Exceptions
198
+ sbm = nx.stochastic_block_model
199
+ badnodelist = list(range(400)) # not enough nodes to match sizes
200
+ badprobs1 = [[0.25, 0.05, 1.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
201
+ badprobs2 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
202
+ probs_rect1 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07]]
203
+ probs_rect2 = [[0.25, 0.05], [0.05, -0.35], [0.02, 0.07]]
204
+ asymprobs = [[0.25, 0.05, 0.01], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
205
+ pytest.raises(nx.NetworkXException, sbm, sizes, badprobs1)
206
+ pytest.raises(nx.NetworkXException, sbm, sizes, badprobs2)
207
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect1, directed=True)
208
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect2, directed=True)
209
+ pytest.raises(nx.NetworkXException, sbm, sizes, asymprobs, directed=False)
210
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs, badnodelist)
211
+ nodelist = [0] + list(range(449)) # repeated node name in nodelist
212
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs, nodelist)
213
+
214
+ # Extra keyword arguments test
215
+ GG = nx.stochastic_block_model(sizes, probs, seed=0, selfloops=True)
216
+ assert G.nodes == GG.nodes
217
+ GG = nx.stochastic_block_model(sizes, probs, selfloops=True, directed=True)
218
+ assert G.nodes == GG.nodes
219
+ GG = nx.stochastic_block_model(sizes, probs, seed=0, sparse=False)
220
+ assert G.nodes == GG.nodes
221
+
222
+
223
+ def test_generator():
224
+ n = 250
225
+ tau1 = 3
226
+ tau2 = 1.5
227
+ mu = 0.1
228
+ G = nx.LFR_benchmark_graph(
229
+ n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
230
+ )
231
+ assert len(G) == 250
232
+ C = {frozenset(G.nodes[v]["community"]) for v in G}
233
+ assert nx.community.is_partition(G.nodes(), C)
234
+
235
+
236
+ def test_invalid_tau1():
237
+ with pytest.raises(nx.NetworkXError, match="tau2 must be greater than one"):
238
+ n = 100
239
+ tau1 = 2
240
+ tau2 = 1
241
+ mu = 0.1
242
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
243
+
244
+
245
+ def test_invalid_tau2():
246
+ with pytest.raises(nx.NetworkXError, match="tau1 must be greater than one"):
247
+ n = 100
248
+ tau1 = 1
249
+ tau2 = 2
250
+ mu = 0.1
251
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
252
+
253
+
254
+ def test_mu_too_large():
255
+ with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
256
+ n = 100
257
+ tau1 = 2
258
+ tau2 = 2
259
+ mu = 1.1
260
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
261
+
262
+
263
+ def test_mu_too_small():
264
+ with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
265
+ n = 100
266
+ tau1 = 2
267
+ tau2 = 2
268
+ mu = -1
269
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
270
+
271
+
272
+ def test_both_degrees_none():
273
+ with pytest.raises(
274
+ nx.NetworkXError,
275
+ match="Must assign exactly one of min_degree and average_degree",
276
+ ):
277
+ n = 100
278
+ tau1 = 2
279
+ tau2 = 2
280
+ mu = 1
281
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu)
282
+
283
+
284
+ def test_neither_degrees_none():
285
+ with pytest.raises(
286
+ nx.NetworkXError,
287
+ match="Must assign exactly one of min_degree and average_degree",
288
+ ):
289
+ n = 100
290
+ tau1 = 2
291
+ tau2 = 2
292
+ mu = 1
293
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, average_degree=5)
294
+
295
+
296
+ def test_max_iters_exceeded():
297
+ with pytest.raises(
298
+ nx.ExceededMaxIterations,
299
+ match="Could not assign communities; try increasing min_community",
300
+ ):
301
+ n = 10
302
+ tau1 = 2
303
+ tau2 = 2
304
+ mu = 0.1
305
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=10, seed=1)
306
+
307
+
308
+ def test_max_deg_out_of_range():
309
+ with pytest.raises(
310
+ nx.NetworkXError, match="max_degree must be in the interval \\(0, n\\]"
311
+ ):
312
+ n = 10
313
+ tau1 = 2
314
+ tau2 = 2
315
+ mu = 0.1
316
+ nx.LFR_benchmark_graph(
317
+ n, tau1, tau2, mu, max_degree=n + 1, max_iters=10, seed=1
318
+ )
319
+
320
+
321
+ def test_max_community():
322
+ n = 250
323
+ tau1 = 3
324
+ tau2 = 1.5
325
+ mu = 0.1
326
+ G = nx.LFR_benchmark_graph(
327
+ n,
328
+ tau1,
329
+ tau2,
330
+ mu,
331
+ average_degree=5,
332
+ max_degree=100,
333
+ min_community=50,
334
+ max_community=200,
335
+ seed=10,
336
+ )
337
+ assert len(G) == 250
338
+ C = {frozenset(G.nodes[v]["community"]) for v in G}
339
+ assert nx.community.is_partition(G.nodes(), C)
340
+
341
+
342
+ def test_powerlaw_iterations_exceeded():
343
+ with pytest.raises(
344
+ nx.ExceededMaxIterations, match="Could not create power law sequence"
345
+ ):
346
+ n = 100
347
+ tau1 = 2
348
+ tau2 = 2
349
+ mu = 1
350
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=0)
351
+
352
+
353
+ def test_no_scipy_zeta():
354
+ zeta2 = 1.6449340668482264
355
+ assert abs(zeta2 - nx.generators.community._hurwitz_zeta(2, 1, 0.0001)) < 0.01
356
+
357
+
358
+ def test_generate_min_degree_itr():
359
+ with pytest.raises(
360
+ nx.ExceededMaxIterations, match="Could not match average_degree"
361
+ ):
362
+ nx.generators.community._generate_min_degree(2, 2, 1, 0.01, 0)
janus/lib/python3.10/site-packages/networkx/generators/tests/test_directed.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators - Directed Graphs
2
+ ----------------------------
3
+ """
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.classes import Graph, MultiDiGraph
9
+ from networkx.generators.directed import (
10
+ gn_graph,
11
+ gnc_graph,
12
+ gnr_graph,
13
+ random_k_out_graph,
14
+ random_uniform_k_out_graph,
15
+ scale_free_graph,
16
+ )
17
+
18
+
19
+ class TestGeneratorsDirected:
20
+ def test_smoke_test_random_graphs(self):
21
+ gn_graph(100)
22
+ gnr_graph(100, 0.5)
23
+ gnc_graph(100)
24
+ scale_free_graph(100)
25
+
26
+ gn_graph(100, seed=42)
27
+ gnr_graph(100, 0.5, seed=42)
28
+ gnc_graph(100, seed=42)
29
+ scale_free_graph(100, seed=42)
30
+
31
+ def test_create_using_keyword_arguments(self):
32
+ pytest.raises(nx.NetworkXError, gn_graph, 100, create_using=Graph())
33
+ pytest.raises(nx.NetworkXError, gnr_graph, 100, 0.5, create_using=Graph())
34
+ pytest.raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph())
35
+ G = gn_graph(100, seed=1)
36
+ MG = gn_graph(100, create_using=MultiDiGraph(), seed=1)
37
+ assert sorted(G.edges()) == sorted(MG.edges())
38
+ G = gnr_graph(100, 0.5, seed=1)
39
+ MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1)
40
+ assert sorted(G.edges()) == sorted(MG.edges())
41
+ G = gnc_graph(100, seed=1)
42
+ MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1)
43
+ assert sorted(G.edges()) == sorted(MG.edges())
44
+
45
+ G = scale_free_graph(
46
+ 100,
47
+ alpha=0.3,
48
+ beta=0.4,
49
+ gamma=0.3,
50
+ delta_in=0.3,
51
+ delta_out=0.1,
52
+ initial_graph=nx.cycle_graph(4, create_using=MultiDiGraph),
53
+ seed=1,
54
+ )
55
+ pytest.raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3)
56
+ pytest.raises(ValueError, scale_free_graph, 100, alpha=-0.3)
57
+ pytest.raises(ValueError, scale_free_graph, 100, beta=-0.3)
58
+ pytest.raises(ValueError, scale_free_graph, 100, gamma=-0.3)
59
+
60
+ def test_parameters(self):
61
+ G = nx.DiGraph()
62
+ G.add_node(0)
63
+
64
+ def kernel(x):
65
+ return x
66
+
67
+ assert nx.is_isomorphic(gn_graph(1), G)
68
+ assert nx.is_isomorphic(gn_graph(1, kernel=kernel), G)
69
+ assert nx.is_isomorphic(gnc_graph(1), G)
70
+ assert nx.is_isomorphic(gnr_graph(1, 0.5), G)
71
+
72
+
73
+ def test_scale_free_graph_negative_delta():
74
+ with pytest.raises(ValueError, match="delta_in must be >= 0."):
75
+ scale_free_graph(10, delta_in=-1)
76
+ with pytest.raises(ValueError, match="delta_out must be >= 0."):
77
+ scale_free_graph(10, delta_out=-1)
78
+
79
+
80
+ def test_non_numeric_ordering():
81
+ G = MultiDiGraph([("a", "b"), ("b", "c"), ("c", "a")])
82
+ s = scale_free_graph(3, initial_graph=G)
83
+ assert len(s) == 3
84
+ assert len(s.edges) == 3
85
+
86
+
87
+ @pytest.mark.parametrize("ig", (nx.Graph(), nx.DiGraph([(0, 1)])))
88
+ def test_scale_free_graph_initial_graph_kwarg(ig):
89
+ with pytest.raises(nx.NetworkXError):
90
+ scale_free_graph(100, initial_graph=ig)
91
+
92
+
93
+ class TestRandomKOutGraph:
94
+ """Unit tests for the
95
+ :func:`~networkx.generators.directed.random_k_out_graph` function.
96
+
97
+ """
98
+
99
+ def test_regularity(self):
100
+ """Tests that the generated graph is `k`-out-regular."""
101
+ n = 10
102
+ k = 3
103
+ alpha = 1
104
+ G = random_k_out_graph(n, k, alpha)
105
+ assert all(d == k for v, d in G.out_degree())
106
+ G = random_k_out_graph(n, k, alpha, seed=42)
107
+ assert all(d == k for v, d in G.out_degree())
108
+
109
+ def test_no_self_loops(self):
110
+ """Tests for forbidding self-loops."""
111
+ n = 10
112
+ k = 3
113
+ alpha = 1
114
+ G = random_k_out_graph(n, k, alpha, self_loops=False)
115
+ assert nx.number_of_selfloops(G) == 0
116
+
117
+ def test_negative_alpha(self):
118
+ with pytest.raises(ValueError, match="alpha must be positive"):
119
+ random_k_out_graph(10, 3, -1)
120
+
121
+
122
+ class TestUniformRandomKOutGraph:
123
+ """Unit tests for the
124
+ :func:`~networkx.generators.directed.random_uniform_k_out_graph`
125
+ function.
126
+
127
+ """
128
+
129
+ def test_regularity(self):
130
+ """Tests that the generated graph is `k`-out-regular."""
131
+ n = 10
132
+ k = 3
133
+ G = random_uniform_k_out_graph(n, k)
134
+ assert all(d == k for v, d in G.out_degree())
135
+ G = random_uniform_k_out_graph(n, k, seed=42)
136
+ assert all(d == k for v, d in G.out_degree())
137
+
138
+ def test_no_self_loops(self):
139
+ """Tests for forbidding self-loops."""
140
+ n = 10
141
+ k = 3
142
+ G = random_uniform_k_out_graph(n, k, self_loops=False)
143
+ assert nx.number_of_selfloops(G) == 0
144
+ assert all(d == k for v, d in G.out_degree())
145
+
146
+ def test_with_replacement(self):
147
+ n = 10
148
+ k = 3
149
+ G = random_uniform_k_out_graph(n, k, with_replacement=True)
150
+ assert G.is_multigraph()
151
+ assert all(d == k for v, d in G.out_degree())
152
+ n = 10
153
+ k = 9
154
+ G = random_uniform_k_out_graph(n, k, with_replacement=False, self_loops=False)
155
+ assert nx.number_of_selfloops(G) == 0
156
+ assert all(d == k for v, d in G.out_degree())
157
+
158
+ def test_without_replacement(self):
159
+ n = 10
160
+ k = 3
161
+ G = random_uniform_k_out_graph(n, k, with_replacement=False)
162
+ assert not G.is_multigraph()
163
+ assert all(d == k for v, d in G.out_degree())
janus/lib/python3.10/site-packages/networkx/generators/tests/test_lattice.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.lattice` module."""
2
+
3
+ from itertools import product
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.utils import edges_equal
9
+
10
+
11
+ class TestGrid2DGraph:
12
+ """Unit tests for :func:`networkx.generators.lattice.grid_2d_graph`"""
13
+
14
+ def test_number_of_vertices(self):
15
+ m, n = 5, 6
16
+ G = nx.grid_2d_graph(m, n)
17
+ assert len(G) == m * n
18
+
19
+ def test_degree_distribution(self):
20
+ m, n = 5, 6
21
+ G = nx.grid_2d_graph(m, n)
22
+ expected_histogram = [0, 0, 4, 2 * (m + n) - 8, (m - 2) * (n - 2)]
23
+ assert nx.degree_histogram(G) == expected_histogram
24
+
25
+ def test_directed(self):
26
+ m, n = 5, 6
27
+ G = nx.grid_2d_graph(m, n)
28
+ H = nx.grid_2d_graph(m, n, create_using=nx.DiGraph())
29
+ assert H.succ == G.adj
30
+ assert H.pred == G.adj
31
+
32
+ def test_multigraph(self):
33
+ m, n = 5, 6
34
+ G = nx.grid_2d_graph(m, n)
35
+ H = nx.grid_2d_graph(m, n, create_using=nx.MultiGraph())
36
+ assert list(H.edges()) == list(G.edges())
37
+
38
+ def test_periodic(self):
39
+ G = nx.grid_2d_graph(0, 0, periodic=True)
40
+ assert dict(G.degree()) == {}
41
+
42
+ for m, n, H in [
43
+ (2, 2, nx.cycle_graph(4)),
44
+ (1, 7, nx.cycle_graph(7)),
45
+ (7, 1, nx.cycle_graph(7)),
46
+ (2, 5, nx.circular_ladder_graph(5)),
47
+ (5, 2, nx.circular_ladder_graph(5)),
48
+ (2, 4, nx.cubical_graph()),
49
+ (4, 2, nx.cubical_graph()),
50
+ ]:
51
+ G = nx.grid_2d_graph(m, n, periodic=True)
52
+ assert nx.could_be_isomorphic(G, H)
53
+
54
+ def test_periodic_iterable(self):
55
+ m, n = 3, 7
56
+ for a, b in product([0, 1], [0, 1]):
57
+ G = nx.grid_2d_graph(m, n, periodic=(a, b))
58
+ assert G.number_of_nodes() == m * n
59
+ assert G.number_of_edges() == (m + a - 1) * n + (n + b - 1) * m
60
+
61
+ def test_periodic_directed(self):
62
+ G = nx.grid_2d_graph(4, 2, periodic=True)
63
+ H = nx.grid_2d_graph(4, 2, periodic=True, create_using=nx.DiGraph())
64
+ assert H.succ == G.adj
65
+ assert H.pred == G.adj
66
+
67
+ def test_periodic_multigraph(self):
68
+ G = nx.grid_2d_graph(4, 2, periodic=True)
69
+ H = nx.grid_2d_graph(4, 2, periodic=True, create_using=nx.MultiGraph())
70
+ assert list(G.edges()) == list(H.edges())
71
+
72
+ def test_exceptions(self):
73
+ pytest.raises(nx.NetworkXError, nx.grid_2d_graph, -3, 2)
74
+ pytest.raises(nx.NetworkXError, nx.grid_2d_graph, 3, -2)
75
+ pytest.raises(TypeError, nx.grid_2d_graph, 3.3, 2)
76
+ pytest.raises(TypeError, nx.grid_2d_graph, 3, 2.2)
77
+
78
+ def test_node_input(self):
79
+ G = nx.grid_2d_graph(4, 2, periodic=True)
80
+ H = nx.grid_2d_graph(range(4), range(2), periodic=True)
81
+ assert nx.is_isomorphic(H, G)
82
+ H = nx.grid_2d_graph("abcd", "ef", periodic=True)
83
+ assert nx.is_isomorphic(H, G)
84
+ G = nx.grid_2d_graph(5, 6)
85
+ H = nx.grid_2d_graph(range(5), range(6))
86
+ assert edges_equal(H, G)
87
+
88
+
89
+ class TestGridGraph:
90
+ """Unit tests for :func:`networkx.generators.lattice.grid_graph`"""
91
+
92
+ def test_grid_graph(self):
93
+ """grid_graph([n,m]) is a connected simple graph with the
94
+ following properties:
95
+ number_of_nodes = n*m
96
+ degree_histogram = [0,0,4,2*(n+m)-8,(n-2)*(m-2)]
97
+ """
98
+ for n, m in [(3, 5), (5, 3), (4, 5), (5, 4)]:
99
+ dim = [n, m]
100
+ g = nx.grid_graph(dim)
101
+ assert len(g) == n * m
102
+ assert nx.degree_histogram(g) == [
103
+ 0,
104
+ 0,
105
+ 4,
106
+ 2 * (n + m) - 8,
107
+ (n - 2) * (m - 2),
108
+ ]
109
+
110
+ for n, m in [(1, 5), (5, 1)]:
111
+ dim = [n, m]
112
+ g = nx.grid_graph(dim)
113
+ assert len(g) == n * m
114
+ assert nx.is_isomorphic(g, nx.path_graph(5))
115
+
116
+ # mg = nx.grid_graph([n,m], create_using=MultiGraph())
117
+ # assert_equal(mg.edges(), g.edges())
118
+
119
+ def test_node_input(self):
120
+ G = nx.grid_graph([range(7, 9), range(3, 6)])
121
+ assert len(G) == 2 * 3
122
+ assert nx.is_isomorphic(G, nx.grid_graph([2, 3]))
123
+
124
+ def test_periodic_iterable(self):
125
+ m, n, k = 3, 7, 5
126
+ for a, b, c in product([0, 1], [0, 1], [0, 1]):
127
+ G = nx.grid_graph([m, n, k], periodic=(a, b, c))
128
+ num_e = (m + a - 1) * n * k + (n + b - 1) * m * k + (k + c - 1) * m * n
129
+ assert G.number_of_nodes() == m * n * k
130
+ assert G.number_of_edges() == num_e
131
+
132
+
133
+ class TestHypercubeGraph:
134
+ """Unit tests for :func:`networkx.generators.lattice.hypercube_graph`"""
135
+
136
+ def test_special_cases(self):
137
+ for n, H in [
138
+ (0, nx.null_graph()),
139
+ (1, nx.path_graph(2)),
140
+ (2, nx.cycle_graph(4)),
141
+ (3, nx.cubical_graph()),
142
+ ]:
143
+ G = nx.hypercube_graph(n)
144
+ assert nx.could_be_isomorphic(G, H)
145
+
146
+ def test_degree_distribution(self):
147
+ for n in range(1, 10):
148
+ G = nx.hypercube_graph(n)
149
+ expected_histogram = [0] * n + [2**n]
150
+ assert nx.degree_histogram(G) == expected_histogram
151
+
152
+
153
+ class TestTriangularLatticeGraph:
154
+ "Tests for :func:`networkx.generators.lattice.triangular_lattice_graph`"
155
+
156
+ def test_lattice_points(self):
157
+ """Tests that the graph is really a triangular lattice."""
158
+ for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
159
+ G = nx.triangular_lattice_graph(m, n)
160
+ N = (n + 1) // 2
161
+ assert len(G) == (m + 1) * (1 + N) - (n % 2) * ((m + 1) // 2)
162
+ for i, j in G.nodes():
163
+ nbrs = G[(i, j)]
164
+ if i < N:
165
+ assert (i + 1, j) in nbrs
166
+ if j < m:
167
+ assert (i, j + 1) in nbrs
168
+ if j < m and (i > 0 or j % 2) and (i < N or (j + 1) % 2):
169
+ assert (i + 1, j + 1) in nbrs or (i - 1, j + 1) in nbrs
170
+
171
+ def test_directed(self):
172
+ """Tests for creating a directed triangular lattice."""
173
+ G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
174
+ H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
175
+ assert H.is_directed()
176
+ for u, v in H.edges():
177
+ assert v[1] >= u[1]
178
+ if v[1] == u[1]:
179
+ assert v[0] > u[0]
180
+
181
+ def test_multigraph(self):
182
+ """Tests for creating a triangular lattice multigraph."""
183
+ G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
184
+ H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
185
+ assert list(H.edges()) == list(G.edges())
186
+
187
+ def test_periodic(self):
188
+ G = nx.triangular_lattice_graph(4, 6, periodic=True)
189
+ assert len(G) == 12
190
+ assert G.size() == 36
191
+ # all degrees are 6
192
+ assert len([n for n, d in G.degree() if d != 6]) == 0
193
+ G = nx.triangular_lattice_graph(5, 7, periodic=True)
194
+ TLG = nx.triangular_lattice_graph
195
+ pytest.raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
196
+ pytest.raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
197
+ pytest.raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
198
+
199
+
200
+ class TestHexagonalLatticeGraph:
201
+ "Tests for :func:`networkx.generators.lattice.hexagonal_lattice_graph`"
202
+
203
+ def test_lattice_points(self):
204
+ """Tests that the graph is really a hexagonal lattice."""
205
+ for m, n in [(4, 5), (4, 4), (4, 3), (3, 2), (3, 3), (3, 5)]:
206
+ G = nx.hexagonal_lattice_graph(m, n)
207
+ assert len(G) == 2 * (m + 1) * (n + 1) - 2
208
+ C_6 = nx.cycle_graph(6)
209
+ hexagons = [
210
+ [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)],
211
+ [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)],
212
+ [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)],
213
+ [(2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)],
214
+ [(2, 2), (2, 3), (2, 4), (3, 2), (3, 3), (3, 4)],
215
+ ]
216
+ for hexagon in hexagons:
217
+ assert nx.is_isomorphic(G.subgraph(hexagon), C_6)
218
+
219
+ def test_directed(self):
220
+ """Tests for creating a directed hexagonal lattice."""
221
+ G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
222
+ H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.DiGraph())
223
+ assert H.is_directed()
224
+ pos = nx.get_node_attributes(H, "pos")
225
+ for u, v in H.edges():
226
+ assert pos[v][1] >= pos[u][1]
227
+ if pos[v][1] == pos[u][1]:
228
+ assert pos[v][0] > pos[u][0]
229
+
230
+ def test_multigraph(self):
231
+ """Tests for creating a hexagonal lattice multigraph."""
232
+ G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
233
+ H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.MultiGraph())
234
+ assert list(H.edges()) == list(G.edges())
235
+
236
+ def test_periodic(self):
237
+ G = nx.hexagonal_lattice_graph(4, 6, periodic=True)
238
+ assert len(G) == 48
239
+ assert G.size() == 72
240
+ # all degrees are 3
241
+ assert len([n for n, d in G.degree() if d != 3]) == 0
242
+ G = nx.hexagonal_lattice_graph(5, 8, periodic=True)
243
+ HLG = nx.hexagonal_lattice_graph
244
+ pytest.raises(nx.NetworkXError, HLG, 2, 7, periodic=True)
245
+ pytest.raises(nx.NetworkXError, HLG, 1, 4, periodic=True)
246
+ pytest.raises(nx.NetworkXError, HLG, 2, 1, periodic=True)
janus/lib/python3.10/site-packages/networkx/generators/tests/test_spectral_graph_forge.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ pytest.importorskip("numpy")
4
+ pytest.importorskip("scipy")
5
+
6
+
7
+ from networkx import is_isomorphic
8
+ from networkx.exception import NetworkXError
9
+ from networkx.generators import karate_club_graph
10
+ from networkx.generators.spectral_graph_forge import spectral_graph_forge
11
+ from networkx.utils import nodes_equal
12
+
13
+
14
+ def test_spectral_graph_forge():
15
+ G = karate_club_graph()
16
+
17
+ seed = 54321
18
+
19
+ # common cases, just checking node number preserving and difference
20
+ # between identity and modularity cases
21
+ H = spectral_graph_forge(G, 0.1, transformation="identity", seed=seed)
22
+ assert nodes_equal(G, H)
23
+
24
+ I = spectral_graph_forge(G, 0.1, transformation="identity", seed=seed)
25
+ assert nodes_equal(G, H)
26
+ assert is_isomorphic(I, H)
27
+
28
+ I = spectral_graph_forge(G, 0.1, transformation="modularity", seed=seed)
29
+ assert nodes_equal(G, I)
30
+
31
+ assert not is_isomorphic(I, H)
32
+
33
+ # with all the eigenvectors, output graph is identical to the input one
34
+ H = spectral_graph_forge(G, 1, transformation="modularity", seed=seed)
35
+ assert nodes_equal(G, H)
36
+ assert is_isomorphic(G, H)
37
+
38
+ # invalid alpha input value, it is silently truncated in [0,1]
39
+ H = spectral_graph_forge(G, -1, transformation="identity", seed=seed)
40
+ assert nodes_equal(G, H)
41
+
42
+ H = spectral_graph_forge(G, 10, transformation="identity", seed=seed)
43
+ assert nodes_equal(G, H)
44
+ assert is_isomorphic(G, H)
45
+
46
+ # invalid transformation mode, checking the error raising
47
+ pytest.raises(
48
+ NetworkXError, spectral_graph_forge, G, 0.1, transformation="unknown", seed=seed
49
+ )
janus/lib/python3.10/site-packages/networkx/generators/tests/test_time_series.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.time_series` module."""
2
+
3
+ import itertools
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def test_visibility_graph__empty_series__empty_graph():
9
+ null_graph = nx.visibility_graph([]) # move along nothing to see here
10
+ assert nx.is_empty(null_graph)
11
+
12
+
13
+ def test_visibility_graph__single_value_ts__single_node_graph():
14
+ node_graph = nx.visibility_graph([10]) # So Lonely
15
+ assert node_graph.number_of_nodes() == 1
16
+ assert node_graph.number_of_edges() == 0
17
+
18
+
19
+ def test_visibility_graph__two_values_ts__single_edge_graph():
20
+ edge_graph = nx.visibility_graph([10, 20]) # Two of Us
21
+ assert list(edge_graph.edges) == [(0, 1)]
22
+
23
+
24
+ def test_visibility_graph__convex_series__complete_graph():
25
+ series = [i**2 for i in range(10)] # no obstructions
26
+ expected_series_length = len(series)
27
+
28
+ actual_graph = nx.visibility_graph(series)
29
+
30
+ assert actual_graph.number_of_nodes() == expected_series_length
31
+ assert actual_graph.number_of_edges() == 45
32
+ assert nx.is_isomorphic(actual_graph, nx.complete_graph(expected_series_length))
33
+
34
+
35
+ def test_visibility_graph__concave_series__path_graph():
36
+ series = [-(i**2) for i in range(10)] # Slip Slidin' Away
37
+ expected_node_count = len(series)
38
+
39
+ actual_graph = nx.visibility_graph(series)
40
+
41
+ assert actual_graph.number_of_nodes() == expected_node_count
42
+ assert actual_graph.number_of_edges() == expected_node_count - 1
43
+ assert nx.is_isomorphic(actual_graph, nx.path_graph(expected_node_count))
44
+
45
+
46
+ def test_visibility_graph__flat_series__path_graph():
47
+ series = [0] * 10 # living in 1D flatland
48
+ expected_node_count = len(series)
49
+
50
+ actual_graph = nx.visibility_graph(series)
51
+
52
+ assert actual_graph.number_of_nodes() == expected_node_count
53
+ assert actual_graph.number_of_edges() == expected_node_count - 1
54
+ assert nx.is_isomorphic(actual_graph, nx.path_graph(expected_node_count))
55
+
56
+
57
+ def test_visibility_graph_cyclic_series():
58
+ series = list(itertools.islice(itertools.cycle((2, 1, 3)), 17)) # It's so bumpy!
59
+ expected_node_count = len(series)
60
+
61
+ actual_graph = nx.visibility_graph(series)
62
+
63
+ assert actual_graph.number_of_nodes() == expected_node_count
64
+ assert actual_graph.number_of_edges() == 25
janus/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
janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
janus/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc ADDED
Binary file (4.41 kB). View file
 
janus/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())
janus/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
janus/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
janus/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)
janus/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
janus/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modularity matrix of graphs."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for
5
+
6
+ __all__ = ["modularity_matrix", "directed_modularity_matrix"]
7
+
8
+
9
+ @not_implemented_for("directed")
10
+ @not_implemented_for("multigraph")
11
+ @nx._dispatchable(edge_attrs="weight")
12
+ def modularity_matrix(G, nodelist=None, weight=None):
13
+ r"""Returns the modularity matrix of G.
14
+
15
+ The modularity matrix is the matrix B = A - <A>, where A is the adjacency
16
+ matrix and <A> is the average adjacency matrix, assuming that the graph
17
+ is described by the configuration model.
18
+
19
+ More specifically, the element B_ij of B is defined as
20
+
21
+ .. math::
22
+ A_{ij} - {k_i k_j \over 2 m}
23
+
24
+ where k_i is the degree of node i, and where m is the number of edges
25
+ in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
26
+ k_j and m are computed using its value.
27
+
28
+ Parameters
29
+ ----------
30
+ G : Graph
31
+ A NetworkX graph
32
+
33
+ nodelist : list, optional
34
+ The rows and columns are ordered according to the nodes in nodelist.
35
+ If nodelist is None, then the ordering is produced by G.nodes().
36
+
37
+ weight : string or None, optional (default=None)
38
+ The edge attribute that holds the numerical value used for
39
+ the edge weight. If None then all edge weights are 1.
40
+
41
+ Returns
42
+ -------
43
+ B : Numpy array
44
+ The modularity matrix of G.
45
+
46
+ Examples
47
+ --------
48
+ >>> k = [3, 2, 2, 1, 0]
49
+ >>> G = nx.havel_hakimi_graph(k)
50
+ >>> B = nx.modularity_matrix(G)
51
+
52
+
53
+ See Also
54
+ --------
55
+ to_numpy_array
56
+ modularity_spectrum
57
+ adjacency_matrix
58
+ directed_modularity_matrix
59
+
60
+ References
61
+ ----------
62
+ .. [1] M. E. J. Newman, "Modularity and community structure in networks",
63
+ Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
64
+ """
65
+ import numpy as np
66
+
67
+ if nodelist is None:
68
+ nodelist = list(G)
69
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
70
+ k = A.sum(axis=1)
71
+ m = k.sum() * 0.5
72
+ # Expected adjacency matrix
73
+ X = np.outer(k, k) / (2 * m)
74
+
75
+ return A - X
76
+
77
+
78
+ @not_implemented_for("undirected")
79
+ @not_implemented_for("multigraph")
80
+ @nx._dispatchable(edge_attrs="weight")
81
+ def directed_modularity_matrix(G, nodelist=None, weight=None):
82
+ """Returns the directed modularity matrix of G.
83
+
84
+ The modularity matrix is the matrix B = A - <A>, where A is the adjacency
85
+ matrix and <A> is the expected adjacency matrix, assuming that the graph
86
+ is described by the configuration model.
87
+
88
+ More specifically, the element B_ij of B is defined as
89
+
90
+ .. math::
91
+ B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
92
+
93
+ where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree
94
+ of node j, with m the number of edges in the graph. When weight is set
95
+ to a name of an attribute edge, Aij, k_i, k_j and m are computed using
96
+ its value.
97
+
98
+ Parameters
99
+ ----------
100
+ G : DiGraph
101
+ A NetworkX DiGraph
102
+
103
+ nodelist : list, optional
104
+ The rows and columns are ordered according to the nodes in nodelist.
105
+ If nodelist is None, then the ordering is produced by G.nodes().
106
+
107
+ weight : string or None, optional (default=None)
108
+ The edge attribute that holds the numerical value used for
109
+ the edge weight. If None then all edge weights are 1.
110
+
111
+ Returns
112
+ -------
113
+ B : Numpy array
114
+ The modularity matrix of G.
115
+
116
+ Examples
117
+ --------
118
+ >>> G = nx.DiGraph()
119
+ >>> G.add_edges_from(
120
+ ... (
121
+ ... (1, 2),
122
+ ... (1, 3),
123
+ ... (3, 1),
124
+ ... (3, 2),
125
+ ... (3, 5),
126
+ ... (4, 5),
127
+ ... (4, 6),
128
+ ... (5, 4),
129
+ ... (5, 6),
130
+ ... (6, 4),
131
+ ... )
132
+ ... )
133
+ >>> B = nx.directed_modularity_matrix(G)
134
+
135
+
136
+ Notes
137
+ -----
138
+ NetworkX defines the element A_ij of the adjacency matrix as 1 if there
139
+ is a link going from node i to node j. Leicht and Newman use the opposite
140
+ definition. This explains the different expression for B_ij.
141
+
142
+ See Also
143
+ --------
144
+ to_numpy_array
145
+ modularity_spectrum
146
+ adjacency_matrix
147
+ modularity_matrix
148
+
149
+ References
150
+ ----------
151
+ .. [1] E. A. Leicht, M. E. J. Newman,
152
+ "Community structure in directed networks",
153
+ Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
154
+ """
155
+ import numpy as np
156
+
157
+ if nodelist is None:
158
+ nodelist = list(G)
159
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
160
+ k_in = A.sum(axis=0)
161
+ k_out = A.sum(axis=1)
162
+ m = k_in.sum()
163
+ # Expected adjacency matrix
164
+ X = np.outer(k_out, k_in) / m
165
+
166
+ return A - X