ZTWHHH commited on
Commit
725897d
·
verified ·
1 Parent(s): 6afcd7e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. wemm/lib/python3.10/site-packages/botocore/data/cloudfront/2014-10-21/endpoint-rule-set-1.json.gz +3 -0
  2. wemm/lib/python3.10/site-packages/networkx/algorithms/__pycache__/simple_paths.cpython-310.pyc +0 -0
  3. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-310.pyc +0 -0
  4. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-310.pyc +0 -0
  5. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-310.pyc +0 -0
  6. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/correlation.py +302 -0
  7. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/pairs.py +127 -0
  8. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__init__.py +0 -0
  9. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  10. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-310.pyc +0 -0
  11. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-310.pyc +0 -0
  12. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py +176 -0
  13. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py +108 -0
  14. wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py +4 -0
  15. wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc +0 -0
  16. wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py +0 -0
  17. wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py +863 -0
  18. wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc +0 -0
  19. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py +0 -0
  20. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc +0 -0
  21. wemm/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc +0 -0
  22. wemm/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc +0 -0
  23. wemm/lib/python3.10/site-packages/networkx/algorithms/connectivity/tests/test_edge_kcomponents.py +488 -0
  24. wemm/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2 +3 -0
  25. wemm/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 +3 -0
  26. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/all.cpython-310.pyc +0 -0
  27. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc +0 -0
  28. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_all.py +328 -0
  29. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_binary.py +453 -0
  30. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_product.py +491 -0
  31. wemm/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chordal.cpython-310.pyc +0 -0
  32. wemm/lib/python3.10/site-packages/networkx/algorithms/tree/tests/test_coding.py +114 -0
  33. wemm/lib/python3.10/site-packages/networkx/algorithms/tree/tests/test_recognition.py +174 -0
  34. wemm/lib/python3.10/site-packages/networkx/drawing/__init__.py +7 -0
  35. wemm/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py +464 -0
  36. wemm/lib/python3.10/site-packages/networkx/drawing/nx_latex.py +572 -0
  37. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py +0 -0
  38. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
  39. wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py +292 -0
  40. wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py +538 -0
  41. wemm/lib/python3.10/site-packages/networkx/generators/atlas.py +180 -0
  42. wemm/lib/python3.10/site-packages/networkx/generators/community.py +1070 -0
  43. wemm/lib/python3.10/site-packages/networkx/generators/directed.py +501 -0
  44. wemm/lib/python3.10/site-packages/networkx/generators/geometric.py +1048 -0
  45. wemm/lib/python3.10/site-packages/networkx/generators/harary_graph.py +199 -0
  46. wemm/lib/python3.10/site-packages/networkx/generators/intersection.py +125 -0
  47. wemm/lib/python3.10/site-packages/networkx/generators/joint_degree_seq.py +664 -0
  48. wemm/lib/python3.10/site-packages/networkx/generators/line.py +500 -0
  49. wemm/lib/python3.10/site-packages/networkx/generators/random_graphs.py +1400 -0
  50. wemm/lib/python3.10/site-packages/networkx/generators/small.py +993 -0
wemm/lib/python3.10/site-packages/botocore/data/cloudfront/2014-10-21/endpoint-rule-set-1.json.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a06b3ceba5eaeb6c6f1759e44ec4eb1d041492dbeb669d033a0f92a05fe513a2
3
+ size 1839
wemm/lib/python3.10/site-packages/networkx/algorithms/__pycache__/simple_paths.cpython-310.pyc ADDED
Binary file (25.8 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (467 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-310.pyc ADDED
Binary file (4.01 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-310.pyc ADDED
Binary file (9.26 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/correlation.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Node assortativity coefficients and correlation measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.assortativity.mixing import (
5
+ attribute_mixing_matrix,
6
+ degree_mixing_matrix,
7
+ )
8
+ from networkx.algorithms.assortativity.pairs import node_degree_xy
9
+
10
+ __all__ = [
11
+ "degree_pearson_correlation_coefficient",
12
+ "degree_assortativity_coefficient",
13
+ "attribute_assortativity_coefficient",
14
+ "numeric_assortativity_coefficient",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable(edge_attrs="weight")
19
+ def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
20
+ """Compute degree assortativity of graph.
21
+
22
+ Assortativity measures the similarity of connections
23
+ in the graph with respect to the node degree.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ x: string ('in','out')
30
+ The degree type for source node (directed graphs only).
31
+
32
+ y: string ('in','out')
33
+ The degree type for target node (directed graphs only).
34
+
35
+ weight: string or None, optional (default=None)
36
+ The edge attribute that holds the numerical value used
37
+ as a weight. If None, then each edge has weight 1.
38
+ The degree is the sum of the edge weights adjacent to the node.
39
+
40
+ nodes: list or iterable (optional)
41
+ Compute degree assortativity only for nodes in container.
42
+ The default is all nodes.
43
+
44
+ Returns
45
+ -------
46
+ r : float
47
+ Assortativity of graph by degree.
48
+
49
+ Examples
50
+ --------
51
+ >>> G = nx.path_graph(4)
52
+ >>> r = nx.degree_assortativity_coefficient(G)
53
+ >>> print(f"{r:3.1f}")
54
+ -0.5
55
+
56
+ See Also
57
+ --------
58
+ attribute_assortativity_coefficient
59
+ numeric_assortativity_coefficient
60
+ degree_mixing_dict
61
+ degree_mixing_matrix
62
+
63
+ Notes
64
+ -----
65
+ This computes Eq. (21) in Ref. [1]_ , where e is the joint
66
+ probability distribution (mixing matrix) of the degrees. If G is
67
+ directed than the matrix e is the joint probability of the
68
+ user-specified degree type for the source and target.
69
+
70
+ References
71
+ ----------
72
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
73
+ Physical Review E, 67 026126, 2003
74
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
75
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
76
+ """
77
+ if nodes is None:
78
+ nodes = G.nodes
79
+
80
+ degrees = None
81
+
82
+ if G.is_directed():
83
+ indeg = (
84
+ {d for _, d in G.in_degree(nodes, weight=weight)}
85
+ if "in" in (x, y)
86
+ else set()
87
+ )
88
+ outdeg = (
89
+ {d for _, d in G.out_degree(nodes, weight=weight)}
90
+ if "out" in (x, y)
91
+ else set()
92
+ )
93
+ degrees = set.union(indeg, outdeg)
94
+ else:
95
+ degrees = {d for _, d in G.degree(nodes, weight=weight)}
96
+
97
+ mapping = {d: i for i, d in enumerate(degrees)}
98
+ M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
99
+
100
+ return _numeric_ac(M, mapping=mapping)
101
+
102
+
103
+ @nx._dispatchable(edge_attrs="weight")
104
+ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
105
+ """Compute degree assortativity of graph.
106
+
107
+ Assortativity measures the similarity of connections
108
+ in the graph with respect to the node degree.
109
+
110
+ This is the same as degree_assortativity_coefficient but uses the
111
+ potentially faster scipy.stats.pearsonr function.
112
+
113
+ Parameters
114
+ ----------
115
+ G : NetworkX graph
116
+
117
+ x: string ('in','out')
118
+ The degree type for source node (directed graphs only).
119
+
120
+ y: string ('in','out')
121
+ The degree type for target node (directed graphs only).
122
+
123
+ weight: string or None, optional (default=None)
124
+ The edge attribute that holds the numerical value used
125
+ as a weight. If None, then each edge has weight 1.
126
+ The degree is the sum of the edge weights adjacent to the node.
127
+
128
+ nodes: list or iterable (optional)
129
+ Compute pearson correlation of degrees only for specified nodes.
130
+ The default is all nodes.
131
+
132
+ Returns
133
+ -------
134
+ r : float
135
+ Assortativity of graph by degree.
136
+
137
+ Examples
138
+ --------
139
+ >>> G = nx.path_graph(4)
140
+ >>> r = nx.degree_pearson_correlation_coefficient(G)
141
+ >>> print(f"{r:3.1f}")
142
+ -0.5
143
+
144
+ Notes
145
+ -----
146
+ This calls scipy.stats.pearsonr.
147
+
148
+ References
149
+ ----------
150
+ .. [1] M. E. J. Newman, Mixing patterns in networks
151
+ Physical Review E, 67 026126, 2003
152
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
153
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
154
+ """
155
+ import scipy as sp
156
+
157
+ xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
158
+ x, y = zip(*xy)
159
+ return float(sp.stats.pearsonr(x, y)[0])
160
+
161
+
162
+ @nx._dispatchable(node_attrs="attribute")
163
+ def attribute_assortativity_coefficient(G, attribute, nodes=None):
164
+ """Compute assortativity for node attributes.
165
+
166
+ Assortativity measures the similarity of connections
167
+ in the graph with respect to the given attribute.
168
+
169
+ Parameters
170
+ ----------
171
+ G : NetworkX graph
172
+
173
+ attribute : string
174
+ Node attribute key
175
+
176
+ nodes: list or iterable (optional)
177
+ Compute attribute assortativity for nodes in container.
178
+ The default is all nodes.
179
+
180
+ Returns
181
+ -------
182
+ r: float
183
+ Assortativity of graph for given attribute
184
+
185
+ Examples
186
+ --------
187
+ >>> G = nx.Graph()
188
+ >>> G.add_nodes_from([0, 1], color="red")
189
+ >>> G.add_nodes_from([2, 3], color="blue")
190
+ >>> G.add_edges_from([(0, 1), (2, 3)])
191
+ >>> print(nx.attribute_assortativity_coefficient(G, "color"))
192
+ 1.0
193
+
194
+ Notes
195
+ -----
196
+ This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
197
+ where M is the joint probability distribution (mixing matrix)
198
+ of the specified attribute.
199
+
200
+ References
201
+ ----------
202
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
203
+ Physical Review E, 67 026126, 2003
204
+ """
205
+ M = attribute_mixing_matrix(G, attribute, nodes)
206
+ return attribute_ac(M)
207
+
208
+
209
+ @nx._dispatchable(node_attrs="attribute")
210
+ def numeric_assortativity_coefficient(G, attribute, nodes=None):
211
+ """Compute assortativity for numerical node attributes.
212
+
213
+ Assortativity measures the similarity of connections
214
+ in the graph with respect to the given numeric attribute.
215
+
216
+ Parameters
217
+ ----------
218
+ G : NetworkX graph
219
+
220
+ attribute : string
221
+ Node attribute key.
222
+
223
+ nodes: list or iterable (optional)
224
+ Compute numeric assortativity only for attributes of nodes in
225
+ container. The default is all nodes.
226
+
227
+ Returns
228
+ -------
229
+ r: float
230
+ Assortativity of graph for given attribute
231
+
232
+ Examples
233
+ --------
234
+ >>> G = nx.Graph()
235
+ >>> G.add_nodes_from([0, 1], size=2)
236
+ >>> G.add_nodes_from([2, 3], size=3)
237
+ >>> G.add_edges_from([(0, 1), (2, 3)])
238
+ >>> print(nx.numeric_assortativity_coefficient(G, "size"))
239
+ 1.0
240
+
241
+ Notes
242
+ -----
243
+ This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
244
+ coefficient of the specified (scalar valued) attribute across edges.
245
+
246
+ References
247
+ ----------
248
+ .. [1] M. E. J. Newman, Mixing patterns in networks
249
+ Physical Review E, 67 026126, 2003
250
+ """
251
+ if nodes is None:
252
+ nodes = G.nodes
253
+ vals = {G.nodes[n][attribute] for n in nodes}
254
+ mapping = {d: i for i, d in enumerate(vals)}
255
+ M = attribute_mixing_matrix(G, attribute, nodes, mapping)
256
+ return _numeric_ac(M, mapping)
257
+
258
+
259
+ def attribute_ac(M):
260
+ """Compute assortativity for attribute matrix M.
261
+
262
+ Parameters
263
+ ----------
264
+ M : numpy.ndarray
265
+ 2D ndarray representing the attribute mixing matrix.
266
+
267
+ Notes
268
+ -----
269
+ This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
270
+ where e is the joint probability distribution (mixing matrix)
271
+ of the specified attribute.
272
+
273
+ References
274
+ ----------
275
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
276
+ Physical Review E, 67 026126, 2003
277
+ """
278
+ if M.sum() != 1.0:
279
+ M = M / M.sum()
280
+ s = (M @ M).sum()
281
+ t = M.trace()
282
+ r = (t - s) / (1 - s)
283
+ return float(r)
284
+
285
+
286
+ def _numeric_ac(M, mapping):
287
+ # M is a 2D numpy array
288
+ # numeric assortativity coefficient, pearsonr
289
+ import numpy as np
290
+
291
+ if M.sum() != 1.0:
292
+ M = M / M.sum()
293
+ x = np.array(list(mapping.keys()))
294
+ y = x # x and y have the same support
295
+ idx = list(mapping.values())
296
+ a = M.sum(axis=0)
297
+ b = M.sum(axis=1)
298
+ vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
299
+ varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
300
+ xy = np.outer(x, y)
301
+ ab = np.outer(a[idx], b[idx])
302
+ return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/pairs.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators of x-y pairs of node data."""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["node_attribute_xy", "node_degree_xy"]
6
+
7
+
8
+ @nx._dispatchable(node_attrs="attribute")
9
+ def node_attribute_xy(G, attribute, nodes=None):
10
+ """Yields 2-tuples of node attribute values for all edges in `G`.
11
+
12
+ This generator yields, for each edge in `G` incident to a node in `nodes`,
13
+ a 2-tuple of form ``(attribute value, attribute value)`` for the parameter
14
+ specified node-attribute.
15
+
16
+ Parameters
17
+ ----------
18
+ G: NetworkX graph
19
+
20
+ attribute: key
21
+ The node attribute key.
22
+
23
+ nodes: list or iterable (optional)
24
+ Use only edges that are incident to specified nodes.
25
+ The default is all nodes.
26
+
27
+ Yields
28
+ ------
29
+ (x, y): 2-tuple
30
+ Generates 2-tuple of (attribute, attribute) values.
31
+
32
+ Examples
33
+ --------
34
+ >>> G = nx.DiGraph()
35
+ >>> G.add_node(1, color="red")
36
+ >>> G.add_node(2, color="blue")
37
+ >>> G.add_node(3, color="green")
38
+ >>> G.add_edge(1, 2)
39
+ >>> list(nx.node_attribute_xy(G, "color"))
40
+ [('red', 'blue')]
41
+
42
+ Notes
43
+ -----
44
+ For undirected graphs, each edge is produced twice, once for each edge
45
+ representation (u, v) and (v, u), with the exception of self-loop edges
46
+ which only appear once.
47
+ """
48
+ if nodes is None:
49
+ nodes = set(G)
50
+ else:
51
+ nodes = set(nodes)
52
+ Gnodes = G.nodes
53
+ for u, nbrsdict in G.adjacency():
54
+ if u not in nodes:
55
+ continue
56
+ uattr = Gnodes[u].get(attribute, None)
57
+ if G.is_multigraph():
58
+ for v, keys in nbrsdict.items():
59
+ vattr = Gnodes[v].get(attribute, None)
60
+ for _ in keys:
61
+ yield (uattr, vattr)
62
+ else:
63
+ for v in nbrsdict:
64
+ vattr = Gnodes[v].get(attribute, None)
65
+ yield (uattr, vattr)
66
+
67
+
68
+ @nx._dispatchable(edge_attrs="weight")
69
+ def node_degree_xy(G, x="out", y="in", weight=None, nodes=None):
70
+ """Yields 2-tuples of ``(degree, degree)`` values for edges in `G`.
71
+
72
+ This generator yields, for each edge in `G` incident to a node in `nodes`,
73
+ a 2-tuple of form ``(degree, degree)``. The node degrees are weighted
74
+ when a `weight` attribute is specified.
75
+
76
+ Parameters
77
+ ----------
78
+ G: NetworkX graph
79
+
80
+ x: string ('in','out')
81
+ The degree type for source node (directed graphs only).
82
+
83
+ y: string ('in','out')
84
+ The degree type for target node (directed graphs only).
85
+
86
+ weight: string or None, optional (default=None)
87
+ The edge attribute that holds the numerical value used
88
+ as a weight. If None, then each edge has weight 1.
89
+ The degree is the sum of the edge weights adjacent to the node.
90
+
91
+ nodes: list or iterable (optional)
92
+ Use only edges that are adjacency to specified nodes.
93
+ The default is all nodes.
94
+
95
+ Yields
96
+ ------
97
+ (x, y): 2-tuple
98
+ Generates 2-tuple of (degree, degree) values.
99
+
100
+ Examples
101
+ --------
102
+ >>> G = nx.DiGraph()
103
+ >>> G.add_edge(1, 2)
104
+ >>> list(nx.node_degree_xy(G, x="out", y="in"))
105
+ [(1, 1)]
106
+ >>> list(nx.node_degree_xy(G, x="in", y="out"))
107
+ [(0, 0)]
108
+
109
+ Notes
110
+ -----
111
+ For undirected graphs, each edge is produced twice, once for each edge
112
+ representation (u, v) and (v, u), with the exception of self-loop edges
113
+ which only appear once.
114
+ """
115
+ nodes = set(G) if nodes is None else set(nodes)
116
+ if G.is_directed():
117
+ direction = {"out": G.out_degree, "in": G.in_degree}
118
+ xdeg = direction[x]
119
+ ydeg = direction[y]
120
+ else:
121
+ xdeg = ydeg = G.degree
122
+
123
+ for u, degu in xdeg(nodes, weight=weight):
124
+ # use G.edges to treat multigraphs correctly
125
+ neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes)
126
+ for _, degv in ydeg(neighbors, weight=weight):
127
+ yield degu, degv
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (189 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-310.pyc ADDED
Binary file (3.67 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+
6
+ import networkx as nx
7
+
8
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
9
+
10
+
11
+ class TestDegreeMixingDict(BaseTestDegreeMixing):
12
+ def test_degree_mixing_dict_undirected(self):
13
+ d = nx.degree_mixing_dict(self.P4)
14
+ d_result = {1: {2: 2}, 2: {1: 2, 2: 2}}
15
+ assert d == d_result
16
+
17
+ def test_degree_mixing_dict_undirected_normalized(self):
18
+ d = nx.degree_mixing_dict(self.P4, normalized=True)
19
+ d_result = {1: {2: 1.0 / 3}, 2: {1: 1.0 / 3, 2: 1.0 / 3}}
20
+ assert d == d_result
21
+
22
+ def test_degree_mixing_dict_directed(self):
23
+ d = nx.degree_mixing_dict(self.D)
24
+ print(d)
25
+ d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}}
26
+ assert d == d_result
27
+
28
+ def test_degree_mixing_dict_multigraph(self):
29
+ d = nx.degree_mixing_dict(self.M)
30
+ d_result = {1: {2: 1}, 2: {1: 1, 3: 3}, 3: {2: 3}}
31
+ assert d == d_result
32
+
33
+ def test_degree_mixing_dict_weighted(self):
34
+ d = nx.degree_mixing_dict(self.W, weight="weight")
35
+ d_result = {0.5: {1.5: 1}, 1.5: {1.5: 6, 0.5: 1}}
36
+ assert d == d_result
37
+
38
+
39
+ class TestDegreeMixingMatrix(BaseTestDegreeMixing):
40
+ def test_degree_mixing_matrix_undirected(self):
41
+ # fmt: off
42
+ a_result = np.array([[0, 2],
43
+ [2, 2]]
44
+ )
45
+ # fmt: on
46
+ a = nx.degree_mixing_matrix(self.P4, normalized=False)
47
+ np.testing.assert_equal(a, a_result)
48
+ a = nx.degree_mixing_matrix(self.P4)
49
+ np.testing.assert_equal(a, a_result / a_result.sum())
50
+
51
+ def test_degree_mixing_matrix_directed(self):
52
+ # fmt: off
53
+ a_result = np.array([[0, 0, 2],
54
+ [1, 0, 1],
55
+ [0, 0, 0]]
56
+ )
57
+ # fmt: on
58
+ a = nx.degree_mixing_matrix(self.D, normalized=False)
59
+ np.testing.assert_equal(a, a_result)
60
+ a = nx.degree_mixing_matrix(self.D)
61
+ np.testing.assert_equal(a, a_result / a_result.sum())
62
+
63
+ def test_degree_mixing_matrix_multigraph(self):
64
+ # fmt: off
65
+ a_result = np.array([[0, 1, 0],
66
+ [1, 0, 3],
67
+ [0, 3, 0]]
68
+ )
69
+ # fmt: on
70
+ a = nx.degree_mixing_matrix(self.M, normalized=False)
71
+ np.testing.assert_equal(a, a_result)
72
+ a = nx.degree_mixing_matrix(self.M)
73
+ np.testing.assert_equal(a, a_result / a_result.sum())
74
+
75
+ def test_degree_mixing_matrix_selfloop(self):
76
+ # fmt: off
77
+ a_result = np.array([[2]])
78
+ # fmt: on
79
+ a = nx.degree_mixing_matrix(self.S, normalized=False)
80
+ np.testing.assert_equal(a, a_result)
81
+ a = nx.degree_mixing_matrix(self.S)
82
+ np.testing.assert_equal(a, a_result / a_result.sum())
83
+
84
+ def test_degree_mixing_matrix_weighted(self):
85
+ a_result = np.array([[0.0, 1.0], [1.0, 6.0]])
86
+ a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False)
87
+ np.testing.assert_equal(a, a_result)
88
+ a = nx.degree_mixing_matrix(self.W, weight="weight")
89
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
90
+
91
+ def test_degree_mixing_matrix_mapping(self):
92
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
93
+ mapping = {0.5: 1, 1.5: 0}
94
+ a = nx.degree_mixing_matrix(
95
+ self.W, weight="weight", normalized=False, mapping=mapping
96
+ )
97
+ np.testing.assert_equal(a, a_result)
98
+
99
+
100
+ class TestAttributeMixingDict(BaseTestAttributeMixing):
101
+ def test_attribute_mixing_dict_undirected(self):
102
+ d = nx.attribute_mixing_dict(self.G, "fish")
103
+ d_result = {
104
+ "one": {"one": 2, "red": 1},
105
+ "two": {"two": 2, "blue": 1},
106
+ "red": {"one": 1},
107
+ "blue": {"two": 1},
108
+ }
109
+ assert d == d_result
110
+
111
+ def test_attribute_mixing_dict_directed(self):
112
+ d = nx.attribute_mixing_dict(self.D, "fish")
113
+ d_result = {
114
+ "one": {"one": 1, "red": 1},
115
+ "two": {"two": 1, "blue": 1},
116
+ "red": {},
117
+ "blue": {},
118
+ }
119
+ assert d == d_result
120
+
121
+ def test_attribute_mixing_dict_multigraph(self):
122
+ d = nx.attribute_mixing_dict(self.M, "fish")
123
+ d_result = {"one": {"one": 4}, "two": {"two": 2}}
124
+ assert d == d_result
125
+
126
+
127
+ class TestAttributeMixingMatrix(BaseTestAttributeMixing):
128
+ def test_attribute_mixing_matrix_undirected(self):
129
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
130
+ a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])
131
+ a = nx.attribute_mixing_matrix(
132
+ self.G, "fish", mapping=mapping, normalized=False
133
+ )
134
+ np.testing.assert_equal(a, a_result)
135
+ a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping)
136
+ np.testing.assert_equal(a, a_result / a_result.sum())
137
+
138
+ def test_attribute_mixing_matrix_directed(self):
139
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
140
+ a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
141
+ a = nx.attribute_mixing_matrix(
142
+ self.D, "fish", mapping=mapping, normalized=False
143
+ )
144
+ np.testing.assert_equal(a, a_result)
145
+ a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping)
146
+ np.testing.assert_equal(a, a_result / a_result.sum())
147
+
148
+ def test_attribute_mixing_matrix_multigraph(self):
149
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
150
+ a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
151
+ a = nx.attribute_mixing_matrix(
152
+ self.M, "fish", mapping=mapping, normalized=False
153
+ )
154
+ np.testing.assert_equal(a, a_result)
155
+ a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping)
156
+ np.testing.assert_equal(a, a_result / a_result.sum())
157
+
158
+ def test_attribute_mixing_matrix_negative(self):
159
+ mapping = {-2: 0, -3: 1, -4: 2}
160
+ a_result = np.array([[4.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
161
+ a = nx.attribute_mixing_matrix(
162
+ self.N, "margin", mapping=mapping, normalized=False
163
+ )
164
+ np.testing.assert_equal(a, a_result)
165
+ a = nx.attribute_mixing_matrix(self.N, "margin", mapping=mapping)
166
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
167
+
168
+ def test_attribute_mixing_matrix_float(self):
169
+ mapping = {0.5: 1, 1.5: 0}
170
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
171
+ a = nx.attribute_mixing_matrix(
172
+ self.F, "margin", mapping=mapping, normalized=False
173
+ )
174
+ np.testing.assert_equal(a, a_result)
175
+ a = nx.attribute_mixing_matrix(self.F, "margin", mapping=mapping)
176
+ np.testing.assert_equal(a, a_result / a_result.sum())
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestAverageNeighbor:
7
+ def test_degree_p4(self):
8
+ G = nx.path_graph(4)
9
+ answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2}
10
+ nd = nx.average_neighbor_degree(G)
11
+ assert nd == answer
12
+
13
+ D = G.to_directed()
14
+ nd = nx.average_neighbor_degree(D)
15
+ assert nd == answer
16
+
17
+ D = nx.DiGraph(G.edges(data=True))
18
+ nd = nx.average_neighbor_degree(D)
19
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
20
+ nd = nx.average_neighbor_degree(D, "in", "out")
21
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
22
+ nd = nx.average_neighbor_degree(D, "out", "in")
23
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
24
+ nd = nx.average_neighbor_degree(D, "in", "in")
25
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
26
+
27
+ def test_degree_p4_weighted(self):
28
+ G = nx.path_graph(4)
29
+ G[1][2]["weight"] = 4
30
+ answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2}
31
+ nd = nx.average_neighbor_degree(G, weight="weight")
32
+ assert nd == answer
33
+
34
+ D = G.to_directed()
35
+ nd = nx.average_neighbor_degree(D, weight="weight")
36
+ assert nd == answer
37
+
38
+ D = nx.DiGraph(G.edges(data=True))
39
+ print(D.edges(data=True))
40
+ nd = nx.average_neighbor_degree(D, weight="weight")
41
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
42
+ nd = nx.average_neighbor_degree(D, "out", "out", weight="weight")
43
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
44
+ nd = nx.average_neighbor_degree(D, "in", "in", weight="weight")
45
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
46
+ nd = nx.average_neighbor_degree(D, "in", "out", weight="weight")
47
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
48
+ nd = nx.average_neighbor_degree(D, "out", "in", weight="weight")
49
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
50
+ nd = nx.average_neighbor_degree(D, source="in+out", weight="weight")
51
+ assert nd == {0: 1.0, 1: 1.0, 2: 0.8, 3: 1.0}
52
+ nd = nx.average_neighbor_degree(D, target="in+out", weight="weight")
53
+ assert nd == {0: 2.0, 1: 2.0, 2: 1.0, 3: 0.0}
54
+
55
+ D = G.to_directed()
56
+ nd = nx.average_neighbor_degree(D, weight="weight")
57
+ assert nd == answer
58
+ nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight")
59
+ assert nd == answer
60
+
61
+ D = G.to_directed()
62
+ nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight")
63
+ assert nd == answer
64
+
65
+ def test_degree_k4(self):
66
+ G = nx.complete_graph(4)
67
+ answer = {0: 3, 1: 3, 2: 3, 3: 3}
68
+ nd = nx.average_neighbor_degree(G)
69
+ assert nd == answer
70
+
71
+ D = G.to_directed()
72
+ nd = nx.average_neighbor_degree(D)
73
+ assert nd == answer
74
+
75
+ D = G.to_directed()
76
+ nd = nx.average_neighbor_degree(D)
77
+ assert nd == answer
78
+
79
+ D = G.to_directed()
80
+ nd = nx.average_neighbor_degree(D, source="in", target="in")
81
+ assert nd == answer
82
+
83
+ def test_degree_k4_nodes(self):
84
+ G = nx.complete_graph(4)
85
+ answer = {1: 3.0, 2: 3.0}
86
+ nd = nx.average_neighbor_degree(G, nodes=[1, 2])
87
+ assert nd == answer
88
+
89
+ def test_degree_barrat(self):
90
+ G = nx.star_graph(5)
91
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
92
+ G[0][5]["weight"] = 5
93
+ nd = nx.average_neighbor_degree(G)[5]
94
+ assert nd == 1.8
95
+ nd = nx.average_neighbor_degree(G, weight="weight")[5]
96
+ assert nd == pytest.approx(3.222222, abs=1e-5)
97
+
98
+ def test_error_invalid_source_target(self):
99
+ G = nx.path_graph(4)
100
+ with pytest.raises(nx.NetworkXError):
101
+ nx.average_neighbor_degree(G, "error")
102
+ with pytest.raises(nx.NetworkXError):
103
+ nx.average_neighbor_degree(G, "in", "error")
104
+ G = G.to_directed()
105
+ with pytest.raises(nx.NetworkXError):
106
+ nx.average_neighbor_degree(G, "error")
107
+ with pytest.raises(nx.NetworkXError):
108
+ nx.average_neighbor_degree(G, "in", "error")
wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from networkx.algorithms.coloring.greedy_coloring import *
2
+ from networkx.algorithms.coloring.equitable_coloring import equitable_color
3
+
4
+ __all__ = ["greedy_color", "equitable_color"]
wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/__pycache__/equitable_coloring.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/test_coloring.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Greedy coloring test suite."""
2
+
3
+ import itertools
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+
9
+ is_coloring = nx.algorithms.coloring.equitable_coloring.is_coloring
10
+ is_equitable = nx.algorithms.coloring.equitable_coloring.is_equitable
11
+
12
+
13
+ ALL_STRATEGIES = [
14
+ "largest_first",
15
+ "random_sequential",
16
+ "smallest_last",
17
+ "independent_set",
18
+ "connected_sequential_bfs",
19
+ "connected_sequential_dfs",
20
+ "connected_sequential",
21
+ "saturation_largest_first",
22
+ "DSATUR",
23
+ ]
24
+
25
+ # List of strategies where interchange=True results in an error
26
+ INTERCHANGE_INVALID = ["independent_set", "saturation_largest_first", "DSATUR"]
27
+
28
+
29
+ class TestColoring:
30
+ def test_basic_cases(self):
31
+ def check_basic_case(graph_func, n_nodes, strategy, interchange):
32
+ graph = graph_func()
33
+ coloring = nx.coloring.greedy_color(
34
+ graph, strategy=strategy, interchange=interchange
35
+ )
36
+ assert verify_length(coloring, n_nodes)
37
+ assert verify_coloring(graph, coloring)
38
+
39
+ for graph_func, n_nodes in BASIC_TEST_CASES.items():
40
+ for interchange in [True, False]:
41
+ for strategy in ALL_STRATEGIES:
42
+ check_basic_case(graph_func, n_nodes, strategy, False)
43
+ if strategy not in INTERCHANGE_INVALID:
44
+ check_basic_case(graph_func, n_nodes, strategy, True)
45
+
46
+ def test_special_cases(self):
47
+ def check_special_case(strategy, graph_func, interchange, colors):
48
+ graph = graph_func()
49
+ coloring = nx.coloring.greedy_color(
50
+ graph, strategy=strategy, interchange=interchange
51
+ )
52
+ if not hasattr(colors, "__len__"):
53
+ colors = [colors]
54
+ assert any(verify_length(coloring, n_colors) for n_colors in colors)
55
+ assert verify_coloring(graph, coloring)
56
+
57
+ for strategy, arglist in SPECIAL_TEST_CASES.items():
58
+ for args in arglist:
59
+ check_special_case(strategy, args[0], args[1], args[2])
60
+
61
+ def test_interchange_invalid(self):
62
+ graph = one_node_graph()
63
+ for strategy in INTERCHANGE_INVALID:
64
+ pytest.raises(
65
+ nx.NetworkXPointlessConcept,
66
+ nx.coloring.greedy_color,
67
+ graph,
68
+ strategy=strategy,
69
+ interchange=True,
70
+ )
71
+
72
+ def test_bad_inputs(self):
73
+ graph = one_node_graph()
74
+ pytest.raises(
75
+ nx.NetworkXError,
76
+ nx.coloring.greedy_color,
77
+ graph,
78
+ strategy="invalid strategy",
79
+ )
80
+
81
+ def test_strategy_as_function(self):
82
+ graph = lf_shc()
83
+ colors_1 = nx.coloring.greedy_color(graph, "largest_first")
84
+ colors_2 = nx.coloring.greedy_color(graph, nx.coloring.strategy_largest_first)
85
+ assert colors_1 == colors_2
86
+
87
+ def test_seed_argument(self):
88
+ graph = lf_shc()
89
+ rs = nx.coloring.strategy_random_sequential
90
+ c1 = nx.coloring.greedy_color(graph, lambda g, c: rs(g, c, seed=1))
91
+ for u, v in graph.edges:
92
+ assert c1[u] != c1[v]
93
+
94
+ def test_is_coloring(self):
95
+ G = nx.Graph()
96
+ G.add_edges_from([(0, 1), (1, 2)])
97
+ coloring = {0: 0, 1: 1, 2: 0}
98
+ assert is_coloring(G, coloring)
99
+
100
+ coloring[0] = 1
101
+ assert not is_coloring(G, coloring)
102
+ assert not is_equitable(G, coloring)
103
+
104
+ def test_is_equitable(self):
105
+ G = nx.Graph()
106
+ G.add_edges_from([(0, 1), (1, 2)])
107
+ coloring = {0: 0, 1: 1, 2: 0}
108
+ assert is_equitable(G, coloring)
109
+
110
+ G.add_edges_from([(2, 3), (2, 4), (2, 5)])
111
+ coloring[3] = 1
112
+ coloring[4] = 1
113
+ coloring[5] = 1
114
+ assert is_coloring(G, coloring)
115
+ assert not is_equitable(G, coloring)
116
+
117
+ def test_num_colors(self):
118
+ G = nx.Graph()
119
+ G.add_edges_from([(0, 1), (0, 2), (0, 3)])
120
+ pytest.raises(nx.NetworkXAlgorithmError, nx.coloring.equitable_color, G, 2)
121
+
122
+ def test_equitable_color(self):
123
+ G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
124
+ coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
125
+ assert is_equitable(G, coloring)
126
+
127
+ def test_equitable_color_empty(self):
128
+ G = nx.empty_graph()
129
+ coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
130
+ assert is_equitable(G, coloring)
131
+
132
+ def test_equitable_color_large(self):
133
+ G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
134
+ coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
135
+ assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
136
+
137
+ def test_case_V_plus_not_in_A_cal(self):
138
+ # Hand crafted case to avoid the easy case.
139
+ L = {
140
+ 0: [2, 5],
141
+ 1: [3, 4],
142
+ 2: [0, 8],
143
+ 3: [1, 7],
144
+ 4: [1, 6],
145
+ 5: [0, 6],
146
+ 6: [4, 5],
147
+ 7: [3],
148
+ 8: [2],
149
+ }
150
+
151
+ F = {
152
+ # Color 0
153
+ 0: 0,
154
+ 1: 0,
155
+ # Color 1
156
+ 2: 1,
157
+ 3: 1,
158
+ 4: 1,
159
+ 5: 1,
160
+ # Color 2
161
+ 6: 2,
162
+ 7: 2,
163
+ 8: 2,
164
+ }
165
+
166
+ C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
167
+ N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
168
+ H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
169
+
170
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
171
+ V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
172
+ )
173
+ check_state(L=L, N=N, H=H, F=F, C=C)
174
+
175
+ def test_cast_no_solo(self):
176
+ L = {
177
+ 0: [8, 9],
178
+ 1: [10, 11],
179
+ 2: [8],
180
+ 3: [9],
181
+ 4: [10, 11],
182
+ 5: [8],
183
+ 6: [9],
184
+ 7: [10, 11],
185
+ 8: [0, 2, 5],
186
+ 9: [0, 3, 6],
187
+ 10: [1, 4, 7],
188
+ 11: [1, 4, 7],
189
+ }
190
+
191
+ F = {0: 0, 1: 0, 2: 2, 3: 2, 4: 2, 5: 3, 6: 3, 7: 3, 8: 1, 9: 1, 10: 1, 11: 1}
192
+
193
+ C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
194
+ N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
195
+ H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
196
+
197
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
198
+ V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
199
+ )
200
+ check_state(L=L, N=N, H=H, F=F, C=C)
201
+
202
+ def test_hard_prob(self):
203
+ # Tests for two levels of recursion.
204
+ num_colors, s = 5, 5
205
+
206
+ G = nx.Graph()
207
+ G.add_edges_from(
208
+ [
209
+ (0, 10),
210
+ (0, 11),
211
+ (0, 12),
212
+ (0, 23),
213
+ (10, 4),
214
+ (10, 9),
215
+ (10, 20),
216
+ (11, 4),
217
+ (11, 8),
218
+ (11, 16),
219
+ (12, 9),
220
+ (12, 22),
221
+ (12, 23),
222
+ (23, 7),
223
+ (1, 17),
224
+ (1, 18),
225
+ (1, 19),
226
+ (1, 24),
227
+ (17, 5),
228
+ (17, 13),
229
+ (17, 22),
230
+ (18, 5),
231
+ (19, 5),
232
+ (19, 6),
233
+ (19, 8),
234
+ (24, 7),
235
+ (24, 16),
236
+ (2, 4),
237
+ (2, 13),
238
+ (2, 14),
239
+ (2, 15),
240
+ (4, 6),
241
+ (13, 5),
242
+ (13, 21),
243
+ (14, 6),
244
+ (14, 15),
245
+ (15, 6),
246
+ (15, 21),
247
+ (3, 16),
248
+ (3, 20),
249
+ (3, 21),
250
+ (3, 22),
251
+ (16, 8),
252
+ (20, 8),
253
+ (21, 9),
254
+ (22, 7),
255
+ ]
256
+ )
257
+ F = {node: node // s for node in range(num_colors * s)}
258
+ F[s - 1] = num_colors - 1
259
+
260
+ params = make_params_from_graph(G=G, F=F)
261
+
262
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
263
+ V_minus=0, V_plus=num_colors - 1, **params
264
+ )
265
+ check_state(**params)
266
+
267
+ def test_hardest_prob(self):
268
+ # Tests for two levels of recursion.
269
+ num_colors, s = 10, 4
270
+
271
+ G = nx.Graph()
272
+ G.add_edges_from(
273
+ [
274
+ (0, 19),
275
+ (0, 24),
276
+ (0, 29),
277
+ (0, 30),
278
+ (0, 35),
279
+ (19, 3),
280
+ (19, 7),
281
+ (19, 9),
282
+ (19, 15),
283
+ (19, 21),
284
+ (19, 24),
285
+ (19, 30),
286
+ (19, 38),
287
+ (24, 5),
288
+ (24, 11),
289
+ (24, 13),
290
+ (24, 20),
291
+ (24, 30),
292
+ (24, 37),
293
+ (24, 38),
294
+ (29, 6),
295
+ (29, 10),
296
+ (29, 13),
297
+ (29, 15),
298
+ (29, 16),
299
+ (29, 17),
300
+ (29, 20),
301
+ (29, 26),
302
+ (30, 6),
303
+ (30, 10),
304
+ (30, 15),
305
+ (30, 22),
306
+ (30, 23),
307
+ (30, 39),
308
+ (35, 6),
309
+ (35, 9),
310
+ (35, 14),
311
+ (35, 18),
312
+ (35, 22),
313
+ (35, 23),
314
+ (35, 25),
315
+ (35, 27),
316
+ (1, 20),
317
+ (1, 26),
318
+ (1, 31),
319
+ (1, 34),
320
+ (1, 38),
321
+ (20, 4),
322
+ (20, 8),
323
+ (20, 14),
324
+ (20, 18),
325
+ (20, 28),
326
+ (20, 33),
327
+ (26, 7),
328
+ (26, 10),
329
+ (26, 14),
330
+ (26, 18),
331
+ (26, 21),
332
+ (26, 32),
333
+ (26, 39),
334
+ (31, 5),
335
+ (31, 8),
336
+ (31, 13),
337
+ (31, 16),
338
+ (31, 17),
339
+ (31, 21),
340
+ (31, 25),
341
+ (31, 27),
342
+ (34, 7),
343
+ (34, 8),
344
+ (34, 13),
345
+ (34, 18),
346
+ (34, 22),
347
+ (34, 23),
348
+ (34, 25),
349
+ (34, 27),
350
+ (38, 4),
351
+ (38, 9),
352
+ (38, 12),
353
+ (38, 14),
354
+ (38, 21),
355
+ (38, 27),
356
+ (2, 3),
357
+ (2, 18),
358
+ (2, 21),
359
+ (2, 28),
360
+ (2, 32),
361
+ (2, 33),
362
+ (2, 36),
363
+ (2, 37),
364
+ (2, 39),
365
+ (3, 5),
366
+ (3, 9),
367
+ (3, 13),
368
+ (3, 22),
369
+ (3, 23),
370
+ (3, 25),
371
+ (3, 27),
372
+ (18, 6),
373
+ (18, 11),
374
+ (18, 15),
375
+ (18, 39),
376
+ (21, 4),
377
+ (21, 10),
378
+ (21, 14),
379
+ (21, 36),
380
+ (28, 6),
381
+ (28, 10),
382
+ (28, 14),
383
+ (28, 16),
384
+ (28, 17),
385
+ (28, 25),
386
+ (28, 27),
387
+ (32, 5),
388
+ (32, 10),
389
+ (32, 12),
390
+ (32, 16),
391
+ (32, 17),
392
+ (32, 22),
393
+ (32, 23),
394
+ (33, 7),
395
+ (33, 10),
396
+ (33, 12),
397
+ (33, 16),
398
+ (33, 17),
399
+ (33, 25),
400
+ (33, 27),
401
+ (36, 5),
402
+ (36, 8),
403
+ (36, 15),
404
+ (36, 16),
405
+ (36, 17),
406
+ (36, 25),
407
+ (36, 27),
408
+ (37, 5),
409
+ (37, 11),
410
+ (37, 15),
411
+ (37, 16),
412
+ (37, 17),
413
+ (37, 22),
414
+ (37, 23),
415
+ (39, 7),
416
+ (39, 8),
417
+ (39, 15),
418
+ (39, 22),
419
+ (39, 23),
420
+ ]
421
+ )
422
+ F = {node: node // s for node in range(num_colors * s)}
423
+ F[s - 1] = num_colors - 1 # V- = 0, V+ = num_colors - 1
424
+
425
+ params = make_params_from_graph(G=G, F=F)
426
+
427
+ nx.algorithms.coloring.equitable_coloring.procedure_P(
428
+ V_minus=0, V_plus=num_colors - 1, **params
429
+ )
430
+ check_state(**params)
431
+
432
+ def test_strategy_saturation_largest_first(self):
433
+ def color_remaining_nodes(
434
+ G,
435
+ colored_nodes,
436
+ full_color_assignment=None,
437
+ nodes_to_add_between_calls=1,
438
+ ):
439
+ color_assignments = []
440
+ aux_colored_nodes = colored_nodes.copy()
441
+
442
+ node_iterator = nx.algorithms.coloring.greedy_coloring.strategy_saturation_largest_first(
443
+ G, aux_colored_nodes
444
+ )
445
+
446
+ for u in node_iterator:
447
+ # Set to keep track of colors of neighbors
448
+ nbr_colors = {
449
+ aux_colored_nodes[v] for v in G[u] if v in aux_colored_nodes
450
+ }
451
+ # Find the first unused color.
452
+ for color in itertools.count():
453
+ if color not in nbr_colors:
454
+ break
455
+ aux_colored_nodes[u] = color
456
+ color_assignments.append((u, color))
457
+
458
+ # Color nodes between iterations
459
+ for i in range(nodes_to_add_between_calls - 1):
460
+ if not len(color_assignments) + len(colored_nodes) >= len(
461
+ full_color_assignment
462
+ ):
463
+ full_color_assignment_node, color = full_color_assignment[
464
+ len(color_assignments) + len(colored_nodes)
465
+ ]
466
+
467
+ # Assign the new color to the current node.
468
+ aux_colored_nodes[full_color_assignment_node] = color
469
+ color_assignments.append((full_color_assignment_node, color))
470
+
471
+ return color_assignments, aux_colored_nodes
472
+
473
+ for G, _, _ in SPECIAL_TEST_CASES["saturation_largest_first"]:
474
+ G = G()
475
+
476
+ # Check that function still works when nodes are colored between iterations
477
+ for nodes_to_add_between_calls in range(1, 5):
478
+ # Get a full color assignment, (including the order in which nodes were colored)
479
+ colored_nodes = {}
480
+ full_color_assignment, full_colored_nodes = color_remaining_nodes(
481
+ G, colored_nodes
482
+ )
483
+
484
+ # For each node in the color assignment, add it to colored_nodes and re-run the function
485
+ for ind, (node, color) in enumerate(full_color_assignment):
486
+ colored_nodes[node] = color
487
+
488
+ (
489
+ partial_color_assignment,
490
+ partial_colored_nodes,
491
+ ) = color_remaining_nodes(
492
+ G,
493
+ colored_nodes,
494
+ full_color_assignment=full_color_assignment,
495
+ nodes_to_add_between_calls=nodes_to_add_between_calls,
496
+ )
497
+
498
+ # Check that the color assignment and order of remaining nodes are the same
499
+ assert full_color_assignment[ind + 1 :] == partial_color_assignment
500
+ assert full_colored_nodes == partial_colored_nodes
501
+
502
+
503
+ # ############################ Utility functions ############################
504
+ def verify_coloring(graph, coloring):
505
+ for node in graph.nodes():
506
+ if node not in coloring:
507
+ return False
508
+
509
+ color = coloring[node]
510
+ for neighbor in graph.neighbors(node):
511
+ if coloring[neighbor] == color:
512
+ return False
513
+
514
+ return True
515
+
516
+
517
+ def verify_length(coloring, expected):
518
+ coloring = dict_to_sets(coloring)
519
+ return len(coloring) == expected
520
+
521
+
522
+ def dict_to_sets(colors):
523
+ if len(colors) == 0:
524
+ return []
525
+
526
+ k = max(colors.values()) + 1
527
+ sets = [set() for _ in range(k)]
528
+
529
+ for node, color in colors.items():
530
+ sets[color].add(node)
531
+
532
+ return sets
533
+
534
+
535
+ # ############################ Graph Generation ############################
536
+
537
+
538
+ def empty_graph():
539
+ return nx.Graph()
540
+
541
+
542
+ def one_node_graph():
543
+ graph = nx.Graph()
544
+ graph.add_nodes_from([1])
545
+ return graph
546
+
547
+
548
+ def two_node_graph():
549
+ graph = nx.Graph()
550
+ graph.add_nodes_from([1, 2])
551
+ graph.add_edges_from([(1, 2)])
552
+ return graph
553
+
554
+
555
+ def three_node_clique():
556
+ graph = nx.Graph()
557
+ graph.add_nodes_from([1, 2, 3])
558
+ graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
559
+ return graph
560
+
561
+
562
+ def disconnected():
563
+ graph = nx.Graph()
564
+ graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
565
+ return graph
566
+
567
+
568
+ def rs_shc():
569
+ graph = nx.Graph()
570
+ graph.add_nodes_from([1, 2, 3, 4])
571
+ graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
572
+ return graph
573
+
574
+
575
+ def slf_shc():
576
+ graph = nx.Graph()
577
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
578
+ graph.add_edges_from(
579
+ [(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
580
+ )
581
+ return graph
582
+
583
+
584
+ def slf_hc():
585
+ graph = nx.Graph()
586
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
587
+ graph.add_edges_from(
588
+ [
589
+ (1, 2),
590
+ (1, 3),
591
+ (1, 4),
592
+ (1, 5),
593
+ (2, 3),
594
+ (2, 4),
595
+ (2, 6),
596
+ (5, 7),
597
+ (5, 8),
598
+ (6, 7),
599
+ (6, 8),
600
+ (7, 8),
601
+ ]
602
+ )
603
+ return graph
604
+
605
+
606
+ def lf_shc():
607
+ graph = nx.Graph()
608
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
609
+ graph.add_edges_from([(6, 1), (1, 4), (4, 3), (3, 2), (2, 5)])
610
+ return graph
611
+
612
+
613
+ def lf_hc():
614
+ graph = nx.Graph()
615
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
616
+ graph.add_edges_from(
617
+ [
618
+ (1, 7),
619
+ (1, 6),
620
+ (1, 3),
621
+ (1, 4),
622
+ (7, 2),
623
+ (2, 6),
624
+ (2, 3),
625
+ (2, 5),
626
+ (5, 3),
627
+ (5, 4),
628
+ (4, 3),
629
+ ]
630
+ )
631
+ return graph
632
+
633
+
634
+ def sl_shc():
635
+ graph = nx.Graph()
636
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
637
+ graph.add_edges_from(
638
+ [(1, 2), (1, 3), (2, 3), (1, 4), (2, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
639
+ )
640
+ return graph
641
+
642
+
643
+ def sl_hc():
644
+ graph = nx.Graph()
645
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
646
+ graph.add_edges_from(
647
+ [
648
+ (1, 2),
649
+ (1, 3),
650
+ (1, 5),
651
+ (1, 7),
652
+ (2, 3),
653
+ (2, 4),
654
+ (2, 8),
655
+ (8, 4),
656
+ (8, 6),
657
+ (8, 7),
658
+ (7, 5),
659
+ (7, 6),
660
+ (3, 4),
661
+ (4, 6),
662
+ (6, 5),
663
+ (5, 3),
664
+ ]
665
+ )
666
+ return graph
667
+
668
+
669
+ def gis_shc():
670
+ graph = nx.Graph()
671
+ graph.add_nodes_from([1, 2, 3, 4])
672
+ graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
673
+ return graph
674
+
675
+
676
+ def gis_hc():
677
+ graph = nx.Graph()
678
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
679
+ graph.add_edges_from([(1, 5), (2, 5), (3, 6), (4, 6), (5, 6)])
680
+ return graph
681
+
682
+
683
+ def cs_shc():
684
+ graph = nx.Graph()
685
+ graph.add_nodes_from([1, 2, 3, 4, 5])
686
+ graph.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)])
687
+ return graph
688
+
689
+
690
+ def rsi_shc():
691
+ graph = nx.Graph()
692
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6])
693
+ graph.add_edges_from(
694
+ [(1, 2), (1, 5), (1, 6), (2, 3), (3, 4), (4, 5), (4, 6), (5, 6)]
695
+ )
696
+ return graph
697
+
698
+
699
+ def lfi_shc():
700
+ graph = nx.Graph()
701
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
702
+ graph.add_edges_from(
703
+ [(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
704
+ )
705
+ return graph
706
+
707
+
708
+ def lfi_hc():
709
+ graph = nx.Graph()
710
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
711
+ graph.add_edges_from(
712
+ [
713
+ (1, 2),
714
+ (1, 5),
715
+ (1, 6),
716
+ (1, 7),
717
+ (2, 3),
718
+ (2, 8),
719
+ (2, 9),
720
+ (3, 4),
721
+ (3, 8),
722
+ (3, 9),
723
+ (4, 5),
724
+ (4, 6),
725
+ (4, 7),
726
+ (5, 6),
727
+ ]
728
+ )
729
+ return graph
730
+
731
+
732
+ def sli_shc():
733
+ graph = nx.Graph()
734
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
735
+ graph.add_edges_from(
736
+ [
737
+ (1, 2),
738
+ (1, 3),
739
+ (1, 5),
740
+ (1, 7),
741
+ (2, 3),
742
+ (2, 6),
743
+ (3, 4),
744
+ (4, 5),
745
+ (4, 6),
746
+ (5, 7),
747
+ (6, 7),
748
+ ]
749
+ )
750
+ return graph
751
+
752
+
753
+ def sli_hc():
754
+ graph = nx.Graph()
755
+ graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
756
+ graph.add_edges_from(
757
+ [
758
+ (1, 2),
759
+ (1, 3),
760
+ (1, 4),
761
+ (1, 5),
762
+ (2, 3),
763
+ (2, 7),
764
+ (2, 8),
765
+ (2, 9),
766
+ (3, 6),
767
+ (3, 7),
768
+ (3, 9),
769
+ (4, 5),
770
+ (4, 6),
771
+ (4, 8),
772
+ (4, 9),
773
+ (5, 6),
774
+ (5, 7),
775
+ (5, 8),
776
+ (6, 7),
777
+ (6, 9),
778
+ (7, 8),
779
+ (8, 9),
780
+ ]
781
+ )
782
+ return graph
783
+
784
+
785
+ # --------------------------------------------------------------------------
786
+ # Basic tests for all strategies
787
+ # For each basic graph function, specify the number of expected colors.
788
+ BASIC_TEST_CASES = {
789
+ empty_graph: 0,
790
+ one_node_graph: 1,
791
+ two_node_graph: 2,
792
+ disconnected: 2,
793
+ three_node_clique: 3,
794
+ }
795
+
796
+
797
+ # --------------------------------------------------------------------------
798
+ # Special test cases. Each strategy has a list of tuples of the form
799
+ # (graph function, interchange, valid # of colors)
800
+ SPECIAL_TEST_CASES = {
801
+ "random_sequential": [
802
+ (rs_shc, False, (2, 3)),
803
+ (rs_shc, True, 2),
804
+ (rsi_shc, True, (3, 4)),
805
+ ],
806
+ "saturation_largest_first": [(slf_shc, False, (3, 4)), (slf_hc, False, 4)],
807
+ "largest_first": [
808
+ (lf_shc, False, (2, 3)),
809
+ (lf_hc, False, 4),
810
+ (lf_shc, True, 2),
811
+ (lf_hc, True, 3),
812
+ (lfi_shc, True, (3, 4)),
813
+ (lfi_hc, True, 4),
814
+ ],
815
+ "smallest_last": [
816
+ (sl_shc, False, (3, 4)),
817
+ (sl_hc, False, 5),
818
+ (sl_shc, True, 3),
819
+ (sl_hc, True, 4),
820
+ (sli_shc, True, (3, 4)),
821
+ (sli_hc, True, 5),
822
+ ],
823
+ "independent_set": [(gis_shc, False, (2, 3)), (gis_hc, False, 3)],
824
+ "connected_sequential": [(cs_shc, False, (3, 4)), (cs_shc, True, 3)],
825
+ "connected_sequential_dfs": [(cs_shc, False, (3, 4))],
826
+ }
827
+
828
+
829
+ # --------------------------------------------------------------------------
830
+ # Helper functions to test
831
+ # (graph function, interchange, valid # of colors)
832
+
833
+
834
+ def check_state(L, N, H, F, C):
835
+ s = len(C[0])
836
+ num_colors = len(C.keys())
837
+
838
+ assert all(u in L[v] for u in L for v in L[u])
839
+ assert all(F[u] != F[v] for u in L for v in L[u])
840
+ assert all(len(L[u]) < num_colors for u in L)
841
+ assert all(len(C[x]) == s for x in C)
842
+ assert all(H[(c1, c2)] >= 0 for c1 in C for c2 in C)
843
+ assert all(N[(u, F[u])] == 0 for u in F)
844
+
845
+
846
+ def max_degree(G):
847
+ """Get the maximum degree of any node in G."""
848
+ return max(G.degree(node) for node in G.nodes) if len(G.nodes) > 0 else 0
849
+
850
+
851
+ def make_params_from_graph(G, F):
852
+ """Returns {N, L, H, C} from the given graph."""
853
+ num_nodes = len(G)
854
+ L = {u: [] for u in range(num_nodes)}
855
+ for u, v in G.edges:
856
+ L[u].append(v)
857
+ L[v].append(u)
858
+
859
+ C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
860
+ N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
861
+ H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
862
+
863
+ return {"N": N, "F": F, "C": C, "H": H, "L": L}
wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (441 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/connectivity/tests/test_edge_kcomponents.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools as it
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.connectivity import EdgeComponentAuxGraph, bridge_components
7
+ from networkx.algorithms.connectivity.edge_kcomponents import general_k_edge_subgraphs
8
+ from networkx.utils import pairwise
9
+
10
+ # ----------------
11
+ # Helper functions
12
+ # ----------------
13
+
14
+
15
+ def fset(list_of_sets):
16
+ """allows == to be used for list of sets"""
17
+ return set(map(frozenset, list_of_sets))
18
+
19
+
20
+ def _assert_subgraph_edge_connectivity(G, ccs_subgraph, k):
21
+ """
22
+ tests properties of k-edge-connected subgraphs
23
+
24
+ the actual edge connectivity should be no less than k unless the cc is a
25
+ single node.
26
+ """
27
+ for cc in ccs_subgraph:
28
+ C = G.subgraph(cc)
29
+ if len(cc) > 1:
30
+ connectivity = nx.edge_connectivity(C)
31
+ assert connectivity >= k
32
+
33
+
34
+ def _memo_connectivity(G, u, v, memo):
35
+ edge = (u, v)
36
+ if edge in memo:
37
+ return memo[edge]
38
+ if not G.is_directed():
39
+ redge = (v, u)
40
+ if redge in memo:
41
+ return memo[redge]
42
+ memo[edge] = nx.edge_connectivity(G, *edge)
43
+ return memo[edge]
44
+
45
+
46
+ def _all_pairs_connectivity(G, cc, k, memo):
47
+ # Brute force check
48
+ for u, v in it.combinations(cc, 2):
49
+ # Use a memoization dict to save on computation
50
+ connectivity = _memo_connectivity(G, u, v, memo)
51
+ if G.is_directed():
52
+ connectivity = min(connectivity, _memo_connectivity(G, v, u, memo))
53
+ assert connectivity >= k
54
+
55
+
56
+ def _assert_local_cc_edge_connectivity(G, ccs_local, k, memo):
57
+ """
58
+ tests properties of k-edge-connected components
59
+
60
+ the local edge connectivity between each pair of nodes in the original
61
+ graph should be no less than k unless the cc is a single node.
62
+ """
63
+ for cc in ccs_local:
64
+ if len(cc) > 1:
65
+ # Strategy for testing a bit faster: If the subgraph has high edge
66
+ # connectivity then it must have local connectivity
67
+ C = G.subgraph(cc)
68
+ connectivity = nx.edge_connectivity(C)
69
+ if connectivity < k:
70
+ # Otherwise do the brute force (with memoization) check
71
+ _all_pairs_connectivity(G, cc, k, memo)
72
+
73
+
74
+ # Helper function
75
+ def _check_edge_connectivity(G):
76
+ """
77
+ Helper - generates all k-edge-components using the aux graph. Checks the
78
+ both local and subgraph edge connectivity of each cc. Also checks that
79
+ alternate methods of computing the k-edge-ccs generate the same result.
80
+ """
81
+ # Construct the auxiliary graph that can be used to make each k-cc or k-sub
82
+ aux_graph = EdgeComponentAuxGraph.construct(G)
83
+
84
+ # memoize the local connectivity in this graph
85
+ memo = {}
86
+
87
+ for k in it.count(1):
88
+ # Test "local" k-edge-components and k-edge-subgraphs
89
+ ccs_local = fset(aux_graph.k_edge_components(k))
90
+ ccs_subgraph = fset(aux_graph.k_edge_subgraphs(k))
91
+
92
+ # Check connectivity properties that should be guaranteed by the
93
+ # algorithms.
94
+ _assert_local_cc_edge_connectivity(G, ccs_local, k, memo)
95
+ _assert_subgraph_edge_connectivity(G, ccs_subgraph, k)
96
+
97
+ if k == 1 or k == 2 and not G.is_directed():
98
+ assert (
99
+ ccs_local == ccs_subgraph
100
+ ), "Subgraphs and components should be the same when k == 1 or (k == 2 and not G.directed())"
101
+
102
+ if G.is_directed():
103
+ # Test special case methods are the same as the aux graph
104
+ if k == 1:
105
+ alt_sccs = fset(nx.strongly_connected_components(G))
106
+ assert alt_sccs == ccs_local, "k=1 failed alt"
107
+ assert alt_sccs == ccs_subgraph, "k=1 failed alt"
108
+ else:
109
+ # Test special case methods are the same as the aux graph
110
+ if k == 1:
111
+ alt_ccs = fset(nx.connected_components(G))
112
+ assert alt_ccs == ccs_local, "k=1 failed alt"
113
+ assert alt_ccs == ccs_subgraph, "k=1 failed alt"
114
+ elif k == 2:
115
+ alt_bridge_ccs = fset(bridge_components(G))
116
+ assert alt_bridge_ccs == ccs_local, "k=2 failed alt"
117
+ assert alt_bridge_ccs == ccs_subgraph, "k=2 failed alt"
118
+ # if new methods for k == 3 or k == 4 are implemented add them here
119
+
120
+ # Check the general subgraph method works by itself
121
+ alt_subgraph_ccs = fset(
122
+ [set(C.nodes()) for C in general_k_edge_subgraphs(G, k=k)]
123
+ )
124
+ assert alt_subgraph_ccs == ccs_subgraph, "alt subgraph method failed"
125
+
126
+ # Stop once k is larger than all special case methods
127
+ # and we cannot break down ccs any further.
128
+ if k > 2 and all(len(cc) == 1 for cc in ccs_local):
129
+ break
130
+
131
+
132
+ # ----------------
133
+ # Misc tests
134
+ # ----------------
135
+
136
+
137
+ def test_zero_k_exception():
138
+ G = nx.Graph()
139
+ # functions that return generators error immediately
140
+ pytest.raises(ValueError, nx.k_edge_components, G, k=0)
141
+ pytest.raises(ValueError, nx.k_edge_subgraphs, G, k=0)
142
+
143
+ # actual generators only error when you get the first item
144
+ aux_graph = EdgeComponentAuxGraph.construct(G)
145
+ pytest.raises(ValueError, list, aux_graph.k_edge_components(k=0))
146
+ pytest.raises(ValueError, list, aux_graph.k_edge_subgraphs(k=0))
147
+
148
+ pytest.raises(ValueError, list, general_k_edge_subgraphs(G, k=0))
149
+
150
+
151
+ def test_empty_input():
152
+ G = nx.Graph()
153
+ assert [] == list(nx.k_edge_components(G, k=5))
154
+ assert [] == list(nx.k_edge_subgraphs(G, k=5))
155
+
156
+ G = nx.DiGraph()
157
+ assert [] == list(nx.k_edge_components(G, k=5))
158
+ assert [] == list(nx.k_edge_subgraphs(G, k=5))
159
+
160
+
161
+ def test_not_implemented():
162
+ G = nx.MultiGraph()
163
+ pytest.raises(nx.NetworkXNotImplemented, EdgeComponentAuxGraph.construct, G)
164
+ pytest.raises(nx.NetworkXNotImplemented, nx.k_edge_components, G, k=2)
165
+ pytest.raises(nx.NetworkXNotImplemented, nx.k_edge_subgraphs, G, k=2)
166
+ with pytest.raises(nx.NetworkXNotImplemented):
167
+ next(bridge_components(G))
168
+ with pytest.raises(nx.NetworkXNotImplemented):
169
+ next(bridge_components(nx.DiGraph()))
170
+
171
+
172
+ def test_general_k_edge_subgraph_quick_return():
173
+ # tests quick return optimization
174
+ G = nx.Graph()
175
+ G.add_node(0)
176
+ subgraphs = list(general_k_edge_subgraphs(G, k=1))
177
+ assert len(subgraphs) == 1
178
+ for subgraph in subgraphs:
179
+ assert subgraph.number_of_nodes() == 1
180
+
181
+ G.add_node(1)
182
+ subgraphs = list(general_k_edge_subgraphs(G, k=1))
183
+ assert len(subgraphs) == 2
184
+ for subgraph in subgraphs:
185
+ assert subgraph.number_of_nodes() == 1
186
+
187
+
188
+ # ----------------
189
+ # Undirected tests
190
+ # ----------------
191
+
192
+
193
+ def test_random_gnp():
194
+ # seeds = [1550709854, 1309423156, 4208992358, 2785630813, 1915069929]
195
+ seeds = [12, 13]
196
+
197
+ for seed in seeds:
198
+ G = nx.gnp_random_graph(20, 0.2, seed=seed)
199
+ _check_edge_connectivity(G)
200
+
201
+
202
+ def test_configuration():
203
+ # seeds = [2718183590, 2470619828, 1694705158, 3001036531, 2401251497]
204
+ seeds = [14, 15]
205
+ for seed in seeds:
206
+ deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
207
+ G = nx.Graph(nx.configuration_model(deg_seq, seed=seed))
208
+ G.remove_edges_from(nx.selfloop_edges(G))
209
+ _check_edge_connectivity(G)
210
+
211
+
212
+ def test_shell():
213
+ # seeds = [2057382236, 3331169846, 1840105863, 476020778, 2247498425]
214
+ seeds = [20]
215
+ for seed in seeds:
216
+ constructor = [(12, 70, 0.8), (15, 40, 0.6)]
217
+ G = nx.random_shell_graph(constructor, seed=seed)
218
+ _check_edge_connectivity(G)
219
+
220
+
221
+ def test_karate():
222
+ G = nx.karate_club_graph()
223
+ _check_edge_connectivity(G)
224
+
225
+
226
+ def test_tarjan_bridge():
227
+ # graph from tarjan paper
228
+ # RE Tarjan - "A note on finding the bridges of a graph"
229
+ # Information Processing Letters, 1974 - Elsevier
230
+ # doi:10.1016/0020-0190(74)90003-9.
231
+ # define 2-connected components and bridges
232
+ ccs = [
233
+ (1, 2, 4, 3, 1, 4),
234
+ (5, 6, 7, 5),
235
+ (8, 9, 10, 8),
236
+ (17, 18, 16, 15, 17),
237
+ (11, 12, 14, 13, 11, 14),
238
+ ]
239
+ bridges = [(4, 8), (3, 5), (3, 17)]
240
+ G = nx.Graph(it.chain(*(pairwise(path) for path in ccs + bridges)))
241
+ _check_edge_connectivity(G)
242
+
243
+
244
+ def test_bridge_cc():
245
+ # define 2-connected components and bridges
246
+ cc2 = [(1, 2, 4, 3, 1, 4), (8, 9, 10, 8), (11, 12, 13, 11)]
247
+ bridges = [(4, 8), (3, 5), (20, 21), (22, 23, 24)]
248
+ G = nx.Graph(it.chain(*(pairwise(path) for path in cc2 + bridges)))
249
+ bridge_ccs = fset(bridge_components(G))
250
+ target_ccs = fset(
251
+ [{1, 2, 3, 4}, {5}, {8, 9, 10}, {11, 12, 13}, {20}, {21}, {22}, {23}, {24}]
252
+ )
253
+ assert bridge_ccs == target_ccs
254
+ _check_edge_connectivity(G)
255
+
256
+
257
+ def test_undirected_aux_graph():
258
+ # Graph similar to the one in
259
+ # http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
260
+ a, b, c, d, e, f, g, h, i = "abcdefghi"
261
+ paths = [
262
+ (a, d, b, f, c),
263
+ (a, e, b),
264
+ (a, e, b, c, g, b, a),
265
+ (c, b),
266
+ (f, g, f),
267
+ (h, i),
268
+ ]
269
+ G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
270
+ aux_graph = EdgeComponentAuxGraph.construct(G)
271
+
272
+ components_1 = fset(aux_graph.k_edge_subgraphs(k=1))
273
+ target_1 = fset([{a, b, c, d, e, f, g}, {h, i}])
274
+ assert target_1 == components_1
275
+
276
+ # Check that the undirected case for k=1 agrees with CCs
277
+ alt_1 = fset(nx.k_edge_subgraphs(G, k=1))
278
+ assert alt_1 == components_1
279
+
280
+ components_2 = fset(aux_graph.k_edge_subgraphs(k=2))
281
+ target_2 = fset([{a, b, c, d, e, f, g}, {h}, {i}])
282
+ assert target_2 == components_2
283
+
284
+ # Check that the undirected case for k=2 agrees with bridge components
285
+ alt_2 = fset(nx.k_edge_subgraphs(G, k=2))
286
+ assert alt_2 == components_2
287
+
288
+ components_3 = fset(aux_graph.k_edge_subgraphs(k=3))
289
+ target_3 = fset([{a}, {b, c, f, g}, {d}, {e}, {h}, {i}])
290
+ assert target_3 == components_3
291
+
292
+ components_4 = fset(aux_graph.k_edge_subgraphs(k=4))
293
+ target_4 = fset([{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}, {i}])
294
+ assert target_4 == components_4
295
+
296
+ _check_edge_connectivity(G)
297
+
298
+
299
+ def test_local_subgraph_difference():
300
+ paths = [
301
+ (11, 12, 13, 14, 11, 13, 14, 12), # first 4-clique
302
+ (21, 22, 23, 24, 21, 23, 24, 22), # second 4-clique
303
+ # paths connecting each node of the 4 cliques
304
+ (11, 101, 21),
305
+ (12, 102, 22),
306
+ (13, 103, 23),
307
+ (14, 104, 24),
308
+ ]
309
+ G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
310
+ aux_graph = EdgeComponentAuxGraph.construct(G)
311
+
312
+ # Each clique is returned separately in k-edge-subgraphs
313
+ subgraph_ccs = fset(aux_graph.k_edge_subgraphs(3))
314
+ subgraph_target = fset(
315
+ [{101}, {102}, {103}, {104}, {21, 22, 23, 24}, {11, 12, 13, 14}]
316
+ )
317
+ assert subgraph_ccs == subgraph_target
318
+
319
+ # But in k-edge-ccs they are returned together
320
+ # because they are locally 3-edge-connected
321
+ local_ccs = fset(aux_graph.k_edge_components(3))
322
+ local_target = fset([{101}, {102}, {103}, {104}, {11, 12, 13, 14, 21, 22, 23, 24}])
323
+ assert local_ccs == local_target
324
+
325
+
326
+ def test_local_subgraph_difference_directed():
327
+ dipaths = [(1, 2, 3, 4, 1), (1, 3, 1)]
328
+ G = nx.DiGraph(it.chain(*[pairwise(path) for path in dipaths]))
329
+
330
+ assert fset(nx.k_edge_components(G, k=1)) == fset(nx.k_edge_subgraphs(G, k=1))
331
+
332
+ # Unlike undirected graphs, when k=2, for directed graphs there is a case
333
+ # where the k-edge-ccs are not the same as the k-edge-subgraphs.
334
+ # (in directed graphs ccs and subgraphs are the same when k=2)
335
+ assert fset(nx.k_edge_components(G, k=2)) != fset(nx.k_edge_subgraphs(G, k=2))
336
+
337
+ assert fset(nx.k_edge_components(G, k=3)) == fset(nx.k_edge_subgraphs(G, k=3))
338
+
339
+ _check_edge_connectivity(G)
340
+
341
+
342
+ def test_triangles():
343
+ paths = [
344
+ (11, 12, 13, 11), # first 3-clique
345
+ (21, 22, 23, 21), # second 3-clique
346
+ (11, 21), # connected by an edge
347
+ ]
348
+ G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
349
+
350
+ # subgraph and ccs are the same in all cases here
351
+ assert fset(nx.k_edge_components(G, k=1)) == fset(nx.k_edge_subgraphs(G, k=1))
352
+
353
+ assert fset(nx.k_edge_components(G, k=2)) == fset(nx.k_edge_subgraphs(G, k=2))
354
+
355
+ assert fset(nx.k_edge_components(G, k=3)) == fset(nx.k_edge_subgraphs(G, k=3))
356
+
357
+ _check_edge_connectivity(G)
358
+
359
+
360
+ def test_four_clique():
361
+ paths = [
362
+ (11, 12, 13, 14, 11, 13, 14, 12), # first 4-clique
363
+ (21, 22, 23, 24, 21, 23, 24, 22), # second 4-clique
364
+ # paths connecting the 4 cliques such that they are
365
+ # 3-connected in G, but not in the subgraph.
366
+ # Case where the nodes bridging them do not have degree less than 3.
367
+ (100, 13),
368
+ (12, 100, 22),
369
+ (13, 200, 23),
370
+ (14, 300, 24),
371
+ ]
372
+ G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
373
+
374
+ # The subgraphs and ccs are different for k=3
375
+ local_ccs = fset(nx.k_edge_components(G, k=3))
376
+ subgraphs = fset(nx.k_edge_subgraphs(G, k=3))
377
+ assert local_ccs != subgraphs
378
+
379
+ # The cliques ares in the same cc
380
+ clique1 = frozenset(paths[0])
381
+ clique2 = frozenset(paths[1])
382
+ assert clique1.union(clique2).union({100}) in local_ccs
383
+
384
+ # but different subgraphs
385
+ assert clique1 in subgraphs
386
+ assert clique2 in subgraphs
387
+
388
+ assert G.degree(100) == 3
389
+
390
+ _check_edge_connectivity(G)
391
+
392
+
393
+ def test_five_clique():
394
+ # Make a graph that can be disconnected less than 4 edges, but no node has
395
+ # degree less than 4.
396
+ G = nx.disjoint_union(nx.complete_graph(5), nx.complete_graph(5))
397
+ paths = [
398
+ # add aux-connections
399
+ (1, 100, 6),
400
+ (2, 100, 7),
401
+ (3, 200, 8),
402
+ (4, 200, 100),
403
+ ]
404
+ G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
405
+ assert min(dict(nx.degree(G)).values()) == 4
406
+
407
+ # For k=3 they are the same
408
+ assert fset(nx.k_edge_components(G, k=3)) == fset(nx.k_edge_subgraphs(G, k=3))
409
+
410
+ # For k=4 they are the different
411
+ # the aux nodes are in the same CC as clique 1 but no the same subgraph
412
+ assert fset(nx.k_edge_components(G, k=4)) != fset(nx.k_edge_subgraphs(G, k=4))
413
+
414
+ # For k=5 they are not the same
415
+ assert fset(nx.k_edge_components(G, k=5)) != fset(nx.k_edge_subgraphs(G, k=5))
416
+
417
+ # For k=6 they are the same
418
+ assert fset(nx.k_edge_components(G, k=6)) == fset(nx.k_edge_subgraphs(G, k=6))
419
+ _check_edge_connectivity(G)
420
+
421
+
422
+ # ----------------
423
+ # Undirected tests
424
+ # ----------------
425
+
426
+
427
+ def test_directed_aux_graph():
428
+ # Graph similar to the one in
429
+ # http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
430
+ a, b, c, d, e, f, g, h, i = "abcdefghi"
431
+ dipaths = [
432
+ (a, d, b, f, c),
433
+ (a, e, b),
434
+ (a, e, b, c, g, b, a),
435
+ (c, b),
436
+ (f, g, f),
437
+ (h, i),
438
+ ]
439
+ G = nx.DiGraph(it.chain(*[pairwise(path) for path in dipaths]))
440
+ aux_graph = EdgeComponentAuxGraph.construct(G)
441
+
442
+ components_1 = fset(aux_graph.k_edge_subgraphs(k=1))
443
+ target_1 = fset([{a, b, c, d, e, f, g}, {h}, {i}])
444
+ assert target_1 == components_1
445
+
446
+ # Check that the directed case for k=1 agrees with SCCs
447
+ alt_1 = fset(nx.strongly_connected_components(G))
448
+ assert alt_1 == components_1
449
+
450
+ components_2 = fset(aux_graph.k_edge_subgraphs(k=2))
451
+ target_2 = fset([{i}, {e}, {d}, {b, c, f, g}, {h}, {a}])
452
+ assert target_2 == components_2
453
+
454
+ components_3 = fset(aux_graph.k_edge_subgraphs(k=3))
455
+ target_3 = fset([{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}, {i}])
456
+ assert target_3 == components_3
457
+
458
+
459
+ def test_random_gnp_directed():
460
+ # seeds = [3894723670, 500186844, 267231174, 2181982262, 1116750056]
461
+ seeds = [21]
462
+ for seed in seeds:
463
+ G = nx.gnp_random_graph(20, 0.2, directed=True, seed=seed)
464
+ _check_edge_connectivity(G)
465
+
466
+
467
+ def test_configuration_directed():
468
+ # seeds = [671221681, 2403749451, 124433910, 672335939, 1193127215]
469
+ seeds = [67]
470
+ for seed in seeds:
471
+ deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
472
+ G = nx.DiGraph(nx.configuration_model(deg_seq, seed=seed))
473
+ G.remove_edges_from(nx.selfloop_edges(G))
474
+ _check_edge_connectivity(G)
475
+
476
+
477
+ def test_shell_directed():
478
+ # seeds = [3134027055, 4079264063, 1350769518, 1405643020, 530038094]
479
+ seeds = [31]
480
+ for seed in seeds:
481
+ constructor = [(12, 70, 0.8), (15, 40, 0.6)]
482
+ G = nx.random_shell_graph(constructor, seed=seed).to_directed()
483
+ _check_edge_connectivity(G)
484
+
485
+
486
+ def test_karate_directed():
487
+ G = nx.karate_club_graph().to_directed()
488
+ _check_edge_connectivity(G)
wemm/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f79f0e90fa4c51ec79165f15963e1ed89477576e06bcaa67ae622c260411931
3
+ size 42248
wemm/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b17e66cdeda8edb8d1dec72626c77f1f65dd4675e3f76dc2fc4fd84aa038e30
3
+ size 18972
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/all.cpython-310.pyc ADDED
Binary file (9.12 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_all.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ def test_union_all_attributes():
8
+ g = nx.Graph()
9
+ g.add_node(0, x=4)
10
+ g.add_node(1, x=5)
11
+ g.add_edge(0, 1, size=5)
12
+ g.graph["name"] = "g"
13
+
14
+ h = g.copy()
15
+ h.graph["name"] = "h"
16
+ h.graph["attr"] = "attr"
17
+ h.nodes[0]["x"] = 7
18
+
19
+ j = g.copy()
20
+ j.graph["name"] = "j"
21
+ j.graph["attr"] = "attr"
22
+ j.nodes[0]["x"] = 7
23
+
24
+ ghj = nx.union_all([g, h, j], rename=("g", "h", "j"))
25
+ assert set(ghj.nodes()) == {"h0", "h1", "g0", "g1", "j0", "j1"}
26
+ for n in ghj:
27
+ graph, node = n
28
+ assert ghj.nodes[n] == eval(graph).nodes[int(node)]
29
+
30
+ assert ghj.graph["attr"] == "attr"
31
+ assert ghj.graph["name"] == "j" # j graph attributes take precedent
32
+
33
+
34
+ def test_intersection_all():
35
+ G = nx.Graph()
36
+ H = nx.Graph()
37
+ R = nx.Graph(awesome=True)
38
+ G.add_nodes_from([1, 2, 3, 4])
39
+ G.add_edge(1, 2)
40
+ G.add_edge(2, 3)
41
+ H.add_nodes_from([1, 2, 3, 4])
42
+ H.add_edge(2, 3)
43
+ H.add_edge(3, 4)
44
+ R.add_nodes_from([1, 2, 3, 4])
45
+ R.add_edge(2, 3)
46
+ R.add_edge(4, 1)
47
+ I = nx.intersection_all([G, H, R])
48
+ assert set(I.nodes()) == {1, 2, 3, 4}
49
+ assert sorted(I.edges()) == [(2, 3)]
50
+ assert I.graph == {}
51
+
52
+
53
+ def test_intersection_all_different_node_sets():
54
+ G = nx.Graph()
55
+ H = nx.Graph()
56
+ R = nx.Graph()
57
+ G.add_nodes_from([1, 2, 3, 4, 6, 7])
58
+ G.add_edge(1, 2)
59
+ G.add_edge(2, 3)
60
+ G.add_edge(6, 7)
61
+ H.add_nodes_from([1, 2, 3, 4])
62
+ H.add_edge(2, 3)
63
+ H.add_edge(3, 4)
64
+ R.add_nodes_from([1, 2, 3, 4, 8, 9])
65
+ R.add_edge(2, 3)
66
+ R.add_edge(4, 1)
67
+ R.add_edge(8, 9)
68
+ I = nx.intersection_all([G, H, R])
69
+ assert set(I.nodes()) == {1, 2, 3, 4}
70
+ assert sorted(I.edges()) == [(2, 3)]
71
+
72
+
73
+ def test_intersection_all_attributes():
74
+ g = nx.Graph()
75
+ g.add_node(0, x=4)
76
+ g.add_node(1, x=5)
77
+ g.add_edge(0, 1, size=5)
78
+ g.graph["name"] = "g"
79
+
80
+ h = g.copy()
81
+ h.graph["name"] = "h"
82
+ h.graph["attr"] = "attr"
83
+ h.nodes[0]["x"] = 7
84
+
85
+ gh = nx.intersection_all([g, h])
86
+ assert set(gh.nodes()) == set(g.nodes())
87
+ assert set(gh.nodes()) == set(h.nodes())
88
+ assert sorted(gh.edges()) == sorted(g.edges())
89
+
90
+
91
+ def test_intersection_all_attributes_different_node_sets():
92
+ g = nx.Graph()
93
+ g.add_node(0, x=4)
94
+ g.add_node(1, x=5)
95
+ g.add_edge(0, 1, size=5)
96
+ g.graph["name"] = "g"
97
+
98
+ h = g.copy()
99
+ g.add_node(2)
100
+ h.graph["name"] = "h"
101
+ h.graph["attr"] = "attr"
102
+ h.nodes[0]["x"] = 7
103
+
104
+ gh = nx.intersection_all([g, h])
105
+ assert set(gh.nodes()) == set(h.nodes())
106
+ assert sorted(gh.edges()) == sorted(g.edges())
107
+
108
+
109
+ def test_intersection_all_multigraph_attributes():
110
+ g = nx.MultiGraph()
111
+ g.add_edge(0, 1, key=0)
112
+ g.add_edge(0, 1, key=1)
113
+ g.add_edge(0, 1, key=2)
114
+ h = nx.MultiGraph()
115
+ h.add_edge(0, 1, key=0)
116
+ h.add_edge(0, 1, key=3)
117
+ gh = nx.intersection_all([g, h])
118
+ assert set(gh.nodes()) == set(g.nodes())
119
+ assert set(gh.nodes()) == set(h.nodes())
120
+ assert sorted(gh.edges()) == [(0, 1)]
121
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
122
+
123
+
124
+ def test_intersection_all_multigraph_attributes_different_node_sets():
125
+ g = nx.MultiGraph()
126
+ g.add_edge(0, 1, key=0)
127
+ g.add_edge(0, 1, key=1)
128
+ g.add_edge(0, 1, key=2)
129
+ g.add_edge(1, 2, key=1)
130
+ g.add_edge(1, 2, key=2)
131
+ h = nx.MultiGraph()
132
+ h.add_edge(0, 1, key=0)
133
+ h.add_edge(0, 1, key=2)
134
+ h.add_edge(0, 1, key=3)
135
+ gh = nx.intersection_all([g, h])
136
+ assert set(gh.nodes()) == set(h.nodes())
137
+ assert sorted(gh.edges()) == [(0, 1), (0, 1)]
138
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0), (0, 1, 2)]
139
+
140
+
141
+ def test_intersection_all_digraph():
142
+ g = nx.DiGraph()
143
+ g.add_edges_from([(1, 2), (2, 3)])
144
+ h = nx.DiGraph()
145
+ h.add_edges_from([(2, 1), (2, 3)])
146
+ gh = nx.intersection_all([g, h])
147
+ assert sorted(gh.edges()) == [(2, 3)]
148
+
149
+
150
+ def test_union_all_and_compose_all():
151
+ K3 = nx.complete_graph(3)
152
+ P3 = nx.path_graph(3)
153
+
154
+ G1 = nx.DiGraph()
155
+ G1.add_edge("A", "B")
156
+ G1.add_edge("A", "C")
157
+ G1.add_edge("A", "D")
158
+ G2 = nx.DiGraph()
159
+ G2.add_edge("1", "2")
160
+ G2.add_edge("1", "3")
161
+ G2.add_edge("1", "4")
162
+
163
+ G = nx.union_all([G1, G2])
164
+ H = nx.compose_all([G1, G2])
165
+ assert edges_equal(G.edges(), H.edges())
166
+ assert not G.has_edge("A", "1")
167
+ pytest.raises(nx.NetworkXError, nx.union, K3, P3)
168
+ H1 = nx.union_all([H, G1], rename=("H", "G1"))
169
+ assert sorted(H1.nodes()) == [
170
+ "G1A",
171
+ "G1B",
172
+ "G1C",
173
+ "G1D",
174
+ "H1",
175
+ "H2",
176
+ "H3",
177
+ "H4",
178
+ "HA",
179
+ "HB",
180
+ "HC",
181
+ "HD",
182
+ ]
183
+
184
+ H2 = nx.union_all([H, G2], rename=("H", ""))
185
+ assert sorted(H2.nodes()) == [
186
+ "1",
187
+ "2",
188
+ "3",
189
+ "4",
190
+ "H1",
191
+ "H2",
192
+ "H3",
193
+ "H4",
194
+ "HA",
195
+ "HB",
196
+ "HC",
197
+ "HD",
198
+ ]
199
+
200
+ assert not H1.has_edge("NB", "NA")
201
+
202
+ G = nx.compose_all([G, G])
203
+ assert edges_equal(G.edges(), H.edges())
204
+
205
+ G2 = nx.union_all([G2, G2], rename=("", "copy"))
206
+ assert sorted(G2.nodes()) == [
207
+ "1",
208
+ "2",
209
+ "3",
210
+ "4",
211
+ "copy1",
212
+ "copy2",
213
+ "copy3",
214
+ "copy4",
215
+ ]
216
+
217
+ assert sorted(G2.neighbors("copy4")) == []
218
+ assert sorted(G2.neighbors("copy1")) == ["copy2", "copy3", "copy4"]
219
+ assert len(G) == 8
220
+ assert nx.number_of_edges(G) == 6
221
+
222
+ E = nx.disjoint_union_all([G, G])
223
+ assert len(E) == 16
224
+ assert nx.number_of_edges(E) == 12
225
+
226
+ E = nx.disjoint_union_all([G1, G2])
227
+ assert sorted(E.nodes()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
228
+
229
+ G1 = nx.DiGraph()
230
+ G1.add_edge("A", "B")
231
+ G2 = nx.DiGraph()
232
+ G2.add_edge(1, 2)
233
+ G3 = nx.DiGraph()
234
+ G3.add_edge(11, 22)
235
+ G4 = nx.union_all([G1, G2, G3], rename=("G1", "G2", "G3"))
236
+ assert sorted(G4.nodes()) == ["G1A", "G1B", "G21", "G22", "G311", "G322"]
237
+
238
+
239
+ def test_union_all_multigraph():
240
+ G = nx.MultiGraph()
241
+ G.add_edge(1, 2, key=0)
242
+ G.add_edge(1, 2, key=1)
243
+ H = nx.MultiGraph()
244
+ H.add_edge(3, 4, key=0)
245
+ H.add_edge(3, 4, key=1)
246
+ GH = nx.union_all([G, H])
247
+ assert set(GH) == set(G) | set(H)
248
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
249
+
250
+
251
+ def test_input_output():
252
+ l = [nx.Graph([(1, 2)]), nx.Graph([(3, 4)], awesome=True)]
253
+ U = nx.disjoint_union_all(l)
254
+ assert len(l) == 2
255
+ assert U.graph["awesome"]
256
+ C = nx.compose_all(l)
257
+ assert len(l) == 2
258
+ l = [nx.Graph([(1, 2)]), nx.Graph([(1, 2)])]
259
+ R = nx.intersection_all(l)
260
+ assert len(l) == 2
261
+
262
+
263
+ def test_mixed_type_union():
264
+ with pytest.raises(nx.NetworkXError):
265
+ G = nx.Graph()
266
+ H = nx.MultiGraph()
267
+ I = nx.Graph()
268
+ U = nx.union_all([G, H, I])
269
+ with pytest.raises(nx.NetworkXError):
270
+ X = nx.Graph()
271
+ Y = nx.DiGraph()
272
+ XY = nx.union_all([X, Y])
273
+
274
+
275
+ def test_mixed_type_disjoint_union():
276
+ with pytest.raises(nx.NetworkXError):
277
+ G = nx.Graph()
278
+ H = nx.MultiGraph()
279
+ I = nx.Graph()
280
+ U = nx.disjoint_union_all([G, H, I])
281
+ with pytest.raises(nx.NetworkXError):
282
+ X = nx.Graph()
283
+ Y = nx.DiGraph()
284
+ XY = nx.disjoint_union_all([X, Y])
285
+
286
+
287
+ def test_mixed_type_intersection():
288
+ with pytest.raises(nx.NetworkXError):
289
+ G = nx.Graph()
290
+ H = nx.MultiGraph()
291
+ I = nx.Graph()
292
+ U = nx.intersection_all([G, H, I])
293
+ with pytest.raises(nx.NetworkXError):
294
+ X = nx.Graph()
295
+ Y = nx.DiGraph()
296
+ XY = nx.intersection_all([X, Y])
297
+
298
+
299
+ def test_mixed_type_compose():
300
+ with pytest.raises(nx.NetworkXError):
301
+ G = nx.Graph()
302
+ H = nx.MultiGraph()
303
+ I = nx.Graph()
304
+ U = nx.compose_all([G, H, I])
305
+ with pytest.raises(nx.NetworkXError):
306
+ X = nx.Graph()
307
+ Y = nx.DiGraph()
308
+ XY = nx.compose_all([X, Y])
309
+
310
+
311
+ def test_empty_union():
312
+ with pytest.raises(ValueError):
313
+ nx.union_all([])
314
+
315
+
316
+ def test_empty_disjoint_union():
317
+ with pytest.raises(ValueError):
318
+ nx.disjoint_union_all([])
319
+
320
+
321
+ def test_empty_compose_all():
322
+ with pytest.raises(ValueError):
323
+ nx.compose_all([])
324
+
325
+
326
+ def test_empty_intersection_all():
327
+ with pytest.raises(ValueError):
328
+ nx.intersection_all([])
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_binary.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal
7
+
8
+
9
+ def test_union_attributes():
10
+ g = nx.Graph()
11
+ g.add_node(0, x=4)
12
+ g.add_node(1, x=5)
13
+ g.add_edge(0, 1, size=5)
14
+ g.graph["name"] = "g"
15
+
16
+ h = g.copy()
17
+ h.graph["name"] = "h"
18
+ h.graph["attr"] = "attr"
19
+ h.nodes[0]["x"] = 7
20
+
21
+ gh = nx.union(g, h, rename=("g", "h"))
22
+ assert set(gh.nodes()) == {"h0", "h1", "g0", "g1"}
23
+ for n in gh:
24
+ graph, node = n
25
+ assert gh.nodes[n] == eval(graph).nodes[int(node)]
26
+
27
+ assert gh.graph["attr"] == "attr"
28
+ assert gh.graph["name"] == "h" # h graph attributes take precedent
29
+
30
+
31
+ def test_intersection():
32
+ G = nx.Graph()
33
+ H = nx.Graph()
34
+ G.add_nodes_from([1, 2, 3, 4])
35
+ G.add_edge(1, 2)
36
+ G.add_edge(2, 3)
37
+ H.add_nodes_from([1, 2, 3, 4])
38
+ H.add_edge(2, 3)
39
+ H.add_edge(3, 4)
40
+ I = nx.intersection(G, H)
41
+ assert set(I.nodes()) == {1, 2, 3, 4}
42
+ assert sorted(I.edges()) == [(2, 3)]
43
+
44
+
45
+ def test_intersection_node_sets_different():
46
+ G = nx.Graph()
47
+ H = nx.Graph()
48
+ G.add_nodes_from([1, 2, 3, 4, 7])
49
+ G.add_edge(1, 2)
50
+ G.add_edge(2, 3)
51
+ H.add_nodes_from([1, 2, 3, 4, 5, 6])
52
+ H.add_edge(2, 3)
53
+ H.add_edge(3, 4)
54
+ H.add_edge(5, 6)
55
+ I = nx.intersection(G, H)
56
+ assert set(I.nodes()) == {1, 2, 3, 4}
57
+ assert sorted(I.edges()) == [(2, 3)]
58
+
59
+
60
+ def test_intersection_attributes():
61
+ g = nx.Graph()
62
+ g.add_node(0, x=4)
63
+ g.add_node(1, x=5)
64
+ g.add_edge(0, 1, size=5)
65
+ g.graph["name"] = "g"
66
+
67
+ h = g.copy()
68
+ h.graph["name"] = "h"
69
+ h.graph["attr"] = "attr"
70
+ h.nodes[0]["x"] = 7
71
+ gh = nx.intersection(g, h)
72
+
73
+ assert set(gh.nodes()) == set(g.nodes())
74
+ assert set(gh.nodes()) == set(h.nodes())
75
+ assert sorted(gh.edges()) == sorted(g.edges())
76
+
77
+
78
+ def test_intersection_attributes_node_sets_different():
79
+ g = nx.Graph()
80
+ g.add_node(0, x=4)
81
+ g.add_node(1, x=5)
82
+ g.add_node(2, x=3)
83
+ g.add_edge(0, 1, size=5)
84
+ g.graph["name"] = "g"
85
+
86
+ h = g.copy()
87
+ h.graph["name"] = "h"
88
+ h.graph["attr"] = "attr"
89
+ h.nodes[0]["x"] = 7
90
+ h.remove_node(2)
91
+
92
+ gh = nx.intersection(g, h)
93
+ assert set(gh.nodes()) == set(h.nodes())
94
+ assert sorted(gh.edges()) == sorted(g.edges())
95
+
96
+
97
+ def test_intersection_multigraph_attributes():
98
+ g = nx.MultiGraph()
99
+ g.add_edge(0, 1, key=0)
100
+ g.add_edge(0, 1, key=1)
101
+ g.add_edge(0, 1, key=2)
102
+ h = nx.MultiGraph()
103
+ h.add_edge(0, 1, key=0)
104
+ h.add_edge(0, 1, key=3)
105
+ gh = nx.intersection(g, h)
106
+ assert set(gh.nodes()) == set(g.nodes())
107
+ assert set(gh.nodes()) == set(h.nodes())
108
+ assert sorted(gh.edges()) == [(0, 1)]
109
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
110
+
111
+
112
+ def test_intersection_multigraph_attributes_node_set_different():
113
+ g = nx.MultiGraph()
114
+ g.add_edge(0, 1, key=0)
115
+ g.add_edge(0, 1, key=1)
116
+ g.add_edge(0, 1, key=2)
117
+ g.add_edge(0, 2, key=2)
118
+ g.add_edge(0, 2, key=1)
119
+ h = nx.MultiGraph()
120
+ h.add_edge(0, 1, key=0)
121
+ h.add_edge(0, 1, key=3)
122
+ gh = nx.intersection(g, h)
123
+ assert set(gh.nodes()) == set(h.nodes())
124
+ assert sorted(gh.edges()) == [(0, 1)]
125
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 0)]
126
+
127
+
128
+ def test_difference():
129
+ G = nx.Graph()
130
+ H = nx.Graph()
131
+ G.add_nodes_from([1, 2, 3, 4])
132
+ G.add_edge(1, 2)
133
+ G.add_edge(2, 3)
134
+ H.add_nodes_from([1, 2, 3, 4])
135
+ H.add_edge(2, 3)
136
+ H.add_edge(3, 4)
137
+ D = nx.difference(G, H)
138
+ assert set(D.nodes()) == {1, 2, 3, 4}
139
+ assert sorted(D.edges()) == [(1, 2)]
140
+ D = nx.difference(H, G)
141
+ assert set(D.nodes()) == {1, 2, 3, 4}
142
+ assert sorted(D.edges()) == [(3, 4)]
143
+ D = nx.symmetric_difference(G, H)
144
+ assert set(D.nodes()) == {1, 2, 3, 4}
145
+ assert sorted(D.edges()) == [(1, 2), (3, 4)]
146
+
147
+
148
+ def test_difference2():
149
+ G = nx.Graph()
150
+ H = nx.Graph()
151
+ G.add_nodes_from([1, 2, 3, 4])
152
+ H.add_nodes_from([1, 2, 3, 4])
153
+ G.add_edge(1, 2)
154
+ H.add_edge(1, 2)
155
+ G.add_edge(2, 3)
156
+ D = nx.difference(G, H)
157
+ assert set(D.nodes()) == {1, 2, 3, 4}
158
+ assert sorted(D.edges()) == [(2, 3)]
159
+ D = nx.difference(H, G)
160
+ assert set(D.nodes()) == {1, 2, 3, 4}
161
+ assert sorted(D.edges()) == []
162
+ H.add_edge(3, 4)
163
+ D = nx.difference(H, G)
164
+ assert set(D.nodes()) == {1, 2, 3, 4}
165
+ assert sorted(D.edges()) == [(3, 4)]
166
+
167
+
168
+ def test_difference_attributes():
169
+ g = nx.Graph()
170
+ g.add_node(0, x=4)
171
+ g.add_node(1, x=5)
172
+ g.add_edge(0, 1, size=5)
173
+ g.graph["name"] = "g"
174
+
175
+ h = g.copy()
176
+ h.graph["name"] = "h"
177
+ h.graph["attr"] = "attr"
178
+ h.nodes[0]["x"] = 7
179
+
180
+ gh = nx.difference(g, h)
181
+ assert set(gh.nodes()) == set(g.nodes())
182
+ assert set(gh.nodes()) == set(h.nodes())
183
+ assert sorted(gh.edges()) == []
184
+ # node and graph data should not be copied over
185
+ assert gh.nodes.data() != g.nodes.data()
186
+ assert gh.graph != g.graph
187
+
188
+
189
+ def test_difference_multigraph_attributes():
190
+ g = nx.MultiGraph()
191
+ g.add_edge(0, 1, key=0)
192
+ g.add_edge(0, 1, key=1)
193
+ g.add_edge(0, 1, key=2)
194
+ h = nx.MultiGraph()
195
+ h.add_edge(0, 1, key=0)
196
+ h.add_edge(0, 1, key=3)
197
+ gh = nx.difference(g, h)
198
+ assert set(gh.nodes()) == set(g.nodes())
199
+ assert set(gh.nodes()) == set(h.nodes())
200
+ assert sorted(gh.edges()) == [(0, 1), (0, 1)]
201
+ assert sorted(gh.edges(keys=True)) == [(0, 1, 1), (0, 1, 2)]
202
+
203
+
204
+ def test_difference_raise():
205
+ G = nx.path_graph(4)
206
+ H = nx.path_graph(3)
207
+ pytest.raises(nx.NetworkXError, nx.difference, G, H)
208
+ pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H)
209
+
210
+
211
+ def test_symmetric_difference_multigraph():
212
+ g = nx.MultiGraph()
213
+ g.add_edge(0, 1, key=0)
214
+ g.add_edge(0, 1, key=1)
215
+ g.add_edge(0, 1, key=2)
216
+ h = nx.MultiGraph()
217
+ h.add_edge(0, 1, key=0)
218
+ h.add_edge(0, 1, key=3)
219
+ gh = nx.symmetric_difference(g, h)
220
+ assert set(gh.nodes()) == set(g.nodes())
221
+ assert set(gh.nodes()) == set(h.nodes())
222
+ assert sorted(gh.edges()) == 3 * [(0, 1)]
223
+ assert sorted(sorted(e) for e in gh.edges(keys=True)) == [
224
+ [0, 1, 1],
225
+ [0, 1, 2],
226
+ [0, 1, 3],
227
+ ]
228
+
229
+
230
+ def test_union_and_compose():
231
+ K3 = nx.complete_graph(3)
232
+ P3 = nx.path_graph(3)
233
+
234
+ G1 = nx.DiGraph()
235
+ G1.add_edge("A", "B")
236
+ G1.add_edge("A", "C")
237
+ G1.add_edge("A", "D")
238
+ G2 = nx.DiGraph()
239
+ G2.add_edge("1", "2")
240
+ G2.add_edge("1", "3")
241
+ G2.add_edge("1", "4")
242
+
243
+ G = nx.union(G1, G2)
244
+ H = nx.compose(G1, G2)
245
+ assert edges_equal(G.edges(), H.edges())
246
+ assert not G.has_edge("A", 1)
247
+ pytest.raises(nx.NetworkXError, nx.union, K3, P3)
248
+ H1 = nx.union(H, G1, rename=("H", "G1"))
249
+ assert sorted(H1.nodes()) == [
250
+ "G1A",
251
+ "G1B",
252
+ "G1C",
253
+ "G1D",
254
+ "H1",
255
+ "H2",
256
+ "H3",
257
+ "H4",
258
+ "HA",
259
+ "HB",
260
+ "HC",
261
+ "HD",
262
+ ]
263
+
264
+ H2 = nx.union(H, G2, rename=("H", ""))
265
+ assert sorted(H2.nodes()) == [
266
+ "1",
267
+ "2",
268
+ "3",
269
+ "4",
270
+ "H1",
271
+ "H2",
272
+ "H3",
273
+ "H4",
274
+ "HA",
275
+ "HB",
276
+ "HC",
277
+ "HD",
278
+ ]
279
+
280
+ assert not H1.has_edge("NB", "NA")
281
+
282
+ G = nx.compose(G, G)
283
+ assert edges_equal(G.edges(), H.edges())
284
+
285
+ G2 = nx.union(G2, G2, rename=("", "copy"))
286
+ assert sorted(G2.nodes()) == [
287
+ "1",
288
+ "2",
289
+ "3",
290
+ "4",
291
+ "copy1",
292
+ "copy2",
293
+ "copy3",
294
+ "copy4",
295
+ ]
296
+
297
+ assert sorted(G2.neighbors("copy4")) == []
298
+ assert sorted(G2.neighbors("copy1")) == ["copy2", "copy3", "copy4"]
299
+ assert len(G) == 8
300
+ assert nx.number_of_edges(G) == 6
301
+
302
+ E = nx.disjoint_union(G, G)
303
+ assert len(E) == 16
304
+ assert nx.number_of_edges(E) == 12
305
+
306
+ E = nx.disjoint_union(G1, G2)
307
+ assert sorted(E.nodes()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
308
+
309
+ G = nx.Graph()
310
+ H = nx.Graph()
311
+ G.add_nodes_from([(1, {"a1": 1})])
312
+ H.add_nodes_from([(1, {"b1": 1})])
313
+ R = nx.compose(G, H)
314
+ assert R.nodes == {1: {"a1": 1, "b1": 1}}
315
+
316
+
317
+ def test_union_multigraph():
318
+ G = nx.MultiGraph()
319
+ G.add_edge(1, 2, key=0)
320
+ G.add_edge(1, 2, key=1)
321
+ H = nx.MultiGraph()
322
+ H.add_edge(3, 4, key=0)
323
+ H.add_edge(3, 4, key=1)
324
+ GH = nx.union(G, H)
325
+ assert set(GH) == set(G) | set(H)
326
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
327
+
328
+
329
+ def test_disjoint_union_multigraph():
330
+ G = nx.MultiGraph()
331
+ G.add_edge(0, 1, key=0)
332
+ G.add_edge(0, 1, key=1)
333
+ H = nx.MultiGraph()
334
+ H.add_edge(2, 3, key=0)
335
+ H.add_edge(2, 3, key=1)
336
+ GH = nx.disjoint_union(G, H)
337
+ assert set(GH) == set(G) | set(H)
338
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
339
+
340
+
341
+ def test_compose_multigraph():
342
+ G = nx.MultiGraph()
343
+ G.add_edge(1, 2, key=0)
344
+ G.add_edge(1, 2, key=1)
345
+ H = nx.MultiGraph()
346
+ H.add_edge(3, 4, key=0)
347
+ H.add_edge(3, 4, key=1)
348
+ GH = nx.compose(G, H)
349
+ assert set(GH) == set(G) | set(H)
350
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
351
+ H.add_edge(1, 2, key=2)
352
+ GH = nx.compose(G, H)
353
+ assert set(GH) == set(G) | set(H)
354
+ assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True))
355
+
356
+
357
+ def test_full_join_graph():
358
+ # Simple Graphs
359
+ G = nx.Graph()
360
+ G.add_node(0)
361
+ G.add_edge(1, 2)
362
+ H = nx.Graph()
363
+ H.add_edge(3, 4)
364
+
365
+ U = nx.full_join(G, H)
366
+ assert set(U) == set(G) | set(H)
367
+ assert len(U) == len(G) + len(H)
368
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
369
+
370
+ # Rename
371
+ U = nx.full_join(G, H, rename=("g", "h"))
372
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
373
+ assert len(U) == len(G) + len(H)
374
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
375
+
376
+ # Rename graphs with string-like nodes
377
+ G = nx.Graph()
378
+ G.add_node("a")
379
+ G.add_edge("b", "c")
380
+ H = nx.Graph()
381
+ H.add_edge("d", "e")
382
+
383
+ U = nx.full_join(G, H, rename=("g", "h"))
384
+ assert set(U) == {"ga", "gb", "gc", "hd", "he"}
385
+ assert len(U) == len(G) + len(H)
386
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
387
+
388
+ # DiGraphs
389
+ G = nx.DiGraph()
390
+ G.add_node(0)
391
+ G.add_edge(1, 2)
392
+ H = nx.DiGraph()
393
+ H.add_edge(3, 4)
394
+
395
+ U = nx.full_join(G, H)
396
+ assert set(U) == set(G) | set(H)
397
+ assert len(U) == len(G) + len(H)
398
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
399
+
400
+ # DiGraphs Rename
401
+ U = nx.full_join(G, H, rename=("g", "h"))
402
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
403
+ assert len(U) == len(G) + len(H)
404
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
405
+
406
+
407
+ def test_full_join_multigraph():
408
+ # MultiGraphs
409
+ G = nx.MultiGraph()
410
+ G.add_node(0)
411
+ G.add_edge(1, 2)
412
+ H = nx.MultiGraph()
413
+ H.add_edge(3, 4)
414
+
415
+ U = nx.full_join(G, H)
416
+ assert set(U) == set(G) | set(H)
417
+ assert len(U) == len(G) + len(H)
418
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
419
+
420
+ # MultiGraphs rename
421
+ U = nx.full_join(G, H, rename=("g", "h"))
422
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
423
+ assert len(U) == len(G) + len(H)
424
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H)
425
+
426
+ # MultiDiGraphs
427
+ G = nx.MultiDiGraph()
428
+ G.add_node(0)
429
+ G.add_edge(1, 2)
430
+ H = nx.MultiDiGraph()
431
+ H.add_edge(3, 4)
432
+
433
+ U = nx.full_join(G, H)
434
+ assert set(U) == set(G) | set(H)
435
+ assert len(U) == len(G) + len(H)
436
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
437
+
438
+ # MultiDiGraphs rename
439
+ U = nx.full_join(G, H, rename=("g", "h"))
440
+ assert set(U) == {"g0", "g1", "g2", "h3", "h4"}
441
+ assert len(U) == len(G) + len(H)
442
+ assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2
443
+
444
+
445
+ def test_mixed_type_union():
446
+ G = nx.Graph()
447
+ H = nx.MultiGraph()
448
+ pytest.raises(nx.NetworkXError, nx.union, G, H)
449
+ pytest.raises(nx.NetworkXError, nx.disjoint_union, G, H)
450
+ pytest.raises(nx.NetworkXError, nx.intersection, G, H)
451
+ pytest.raises(nx.NetworkXError, nx.difference, G, H)
452
+ pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H)
453
+ pytest.raises(nx.NetworkXError, nx.compose, G, H)
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/test_product.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ def test_tensor_product_raises():
8
+ with pytest.raises(nx.NetworkXError):
9
+ P = nx.tensor_product(nx.DiGraph(), nx.Graph())
10
+
11
+
12
+ def test_tensor_product_null():
13
+ null = nx.null_graph()
14
+ empty10 = nx.empty_graph(10)
15
+ K3 = nx.complete_graph(3)
16
+ K10 = nx.complete_graph(10)
17
+ P3 = nx.path_graph(3)
18
+ P10 = nx.path_graph(10)
19
+ # null graph
20
+ G = nx.tensor_product(null, null)
21
+ assert nx.is_isomorphic(G, null)
22
+ # null_graph X anything = null_graph and v.v.
23
+ G = nx.tensor_product(null, empty10)
24
+ assert nx.is_isomorphic(G, null)
25
+ G = nx.tensor_product(null, K3)
26
+ assert nx.is_isomorphic(G, null)
27
+ G = nx.tensor_product(null, K10)
28
+ assert nx.is_isomorphic(G, null)
29
+ G = nx.tensor_product(null, P3)
30
+ assert nx.is_isomorphic(G, null)
31
+ G = nx.tensor_product(null, P10)
32
+ assert nx.is_isomorphic(G, null)
33
+ G = nx.tensor_product(empty10, null)
34
+ assert nx.is_isomorphic(G, null)
35
+ G = nx.tensor_product(K3, null)
36
+ assert nx.is_isomorphic(G, null)
37
+ G = nx.tensor_product(K10, null)
38
+ assert nx.is_isomorphic(G, null)
39
+ G = nx.tensor_product(P3, null)
40
+ assert nx.is_isomorphic(G, null)
41
+ G = nx.tensor_product(P10, null)
42
+ assert nx.is_isomorphic(G, null)
43
+
44
+
45
+ def test_tensor_product_size():
46
+ P5 = nx.path_graph(5)
47
+ K3 = nx.complete_graph(3)
48
+ K5 = nx.complete_graph(5)
49
+
50
+ G = nx.tensor_product(P5, K3)
51
+ assert nx.number_of_nodes(G) == 5 * 3
52
+ G = nx.tensor_product(K3, K5)
53
+ assert nx.number_of_nodes(G) == 3 * 5
54
+
55
+
56
+ def test_tensor_product_combinations():
57
+ # basic smoke test, more realistic tests would be useful
58
+ P5 = nx.path_graph(5)
59
+ K3 = nx.complete_graph(3)
60
+ G = nx.tensor_product(P5, K3)
61
+ assert nx.number_of_nodes(G) == 5 * 3
62
+ G = nx.tensor_product(P5, nx.MultiGraph(K3))
63
+ assert nx.number_of_nodes(G) == 5 * 3
64
+ G = nx.tensor_product(nx.MultiGraph(P5), K3)
65
+ assert nx.number_of_nodes(G) == 5 * 3
66
+ G = nx.tensor_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
67
+ assert nx.number_of_nodes(G) == 5 * 3
68
+
69
+ G = nx.tensor_product(nx.DiGraph(P5), nx.DiGraph(K3))
70
+ assert nx.number_of_nodes(G) == 5 * 3
71
+
72
+
73
+ def test_tensor_product_classic_result():
74
+ K2 = nx.complete_graph(2)
75
+ G = nx.petersen_graph()
76
+ G = nx.tensor_product(G, K2)
77
+ assert nx.is_isomorphic(G, nx.desargues_graph())
78
+
79
+ G = nx.cycle_graph(5)
80
+ G = nx.tensor_product(G, K2)
81
+ assert nx.is_isomorphic(G, nx.cycle_graph(10))
82
+
83
+ G = nx.tetrahedral_graph()
84
+ G = nx.tensor_product(G, K2)
85
+ assert nx.is_isomorphic(G, nx.cubical_graph())
86
+
87
+
88
+ def test_tensor_product_random():
89
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
90
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
91
+ GH = nx.tensor_product(G, H)
92
+
93
+ for u_G, u_H in GH.nodes():
94
+ for v_G, v_H in GH.nodes():
95
+ if H.has_edge(u_H, v_H) and G.has_edge(u_G, v_G):
96
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
97
+ else:
98
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
99
+
100
+
101
+ def test_cartesian_product_multigraph():
102
+ G = nx.MultiGraph()
103
+ G.add_edge(1, 2, key=0)
104
+ G.add_edge(1, 2, key=1)
105
+ H = nx.MultiGraph()
106
+ H.add_edge(3, 4, key=0)
107
+ H.add_edge(3, 4, key=1)
108
+ GH = nx.cartesian_product(G, H)
109
+ assert set(GH) == {(1, 3), (2, 3), (2, 4), (1, 4)}
110
+ assert {(frozenset([u, v]), k) for u, v, k in GH.edges(keys=True)} == {
111
+ (frozenset([u, v]), k)
112
+ for u, v, k in [
113
+ ((1, 3), (2, 3), 0),
114
+ ((1, 3), (2, 3), 1),
115
+ ((1, 3), (1, 4), 0),
116
+ ((1, 3), (1, 4), 1),
117
+ ((2, 3), (2, 4), 0),
118
+ ((2, 3), (2, 4), 1),
119
+ ((2, 4), (1, 4), 0),
120
+ ((2, 4), (1, 4), 1),
121
+ ]
122
+ }
123
+
124
+
125
+ def test_cartesian_product_raises():
126
+ with pytest.raises(nx.NetworkXError):
127
+ P = nx.cartesian_product(nx.DiGraph(), nx.Graph())
128
+
129
+
130
+ def test_cartesian_product_null():
131
+ null = nx.null_graph()
132
+ empty10 = nx.empty_graph(10)
133
+ K3 = nx.complete_graph(3)
134
+ K10 = nx.complete_graph(10)
135
+ P3 = nx.path_graph(3)
136
+ P10 = nx.path_graph(10)
137
+ # null graph
138
+ G = nx.cartesian_product(null, null)
139
+ assert nx.is_isomorphic(G, null)
140
+ # null_graph X anything = null_graph and v.v.
141
+ G = nx.cartesian_product(null, empty10)
142
+ assert nx.is_isomorphic(G, null)
143
+ G = nx.cartesian_product(null, K3)
144
+ assert nx.is_isomorphic(G, null)
145
+ G = nx.cartesian_product(null, K10)
146
+ assert nx.is_isomorphic(G, null)
147
+ G = nx.cartesian_product(null, P3)
148
+ assert nx.is_isomorphic(G, null)
149
+ G = nx.cartesian_product(null, P10)
150
+ assert nx.is_isomorphic(G, null)
151
+ G = nx.cartesian_product(empty10, null)
152
+ assert nx.is_isomorphic(G, null)
153
+ G = nx.cartesian_product(K3, null)
154
+ assert nx.is_isomorphic(G, null)
155
+ G = nx.cartesian_product(K10, null)
156
+ assert nx.is_isomorphic(G, null)
157
+ G = nx.cartesian_product(P3, null)
158
+ assert nx.is_isomorphic(G, null)
159
+ G = nx.cartesian_product(P10, null)
160
+ assert nx.is_isomorphic(G, null)
161
+
162
+
163
+ def test_cartesian_product_size():
164
+ # order(GXH)=order(G)*order(H)
165
+ K5 = nx.complete_graph(5)
166
+ P5 = nx.path_graph(5)
167
+ K3 = nx.complete_graph(3)
168
+ G = nx.cartesian_product(P5, K3)
169
+ assert nx.number_of_nodes(G) == 5 * 3
170
+ assert nx.number_of_edges(G) == nx.number_of_edges(P5) * nx.number_of_nodes(
171
+ K3
172
+ ) + nx.number_of_edges(K3) * nx.number_of_nodes(P5)
173
+ G = nx.cartesian_product(K3, K5)
174
+ assert nx.number_of_nodes(G) == 3 * 5
175
+ assert nx.number_of_edges(G) == nx.number_of_edges(K5) * nx.number_of_nodes(
176
+ K3
177
+ ) + nx.number_of_edges(K3) * nx.number_of_nodes(K5)
178
+
179
+
180
+ def test_cartesian_product_classic():
181
+ # test some classic product graphs
182
+ P2 = nx.path_graph(2)
183
+ P3 = nx.path_graph(3)
184
+ # cube = 2-path X 2-path
185
+ G = nx.cartesian_product(P2, P2)
186
+ G = nx.cartesian_product(P2, G)
187
+ assert nx.is_isomorphic(G, nx.cubical_graph())
188
+
189
+ # 3x3 grid
190
+ G = nx.cartesian_product(P3, P3)
191
+ assert nx.is_isomorphic(G, nx.grid_2d_graph(3, 3))
192
+
193
+
194
+ def test_cartesian_product_random():
195
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
196
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
197
+ GH = nx.cartesian_product(G, H)
198
+
199
+ for u_G, u_H in GH.nodes():
200
+ for v_G, v_H in GH.nodes():
201
+ if (u_G == v_G and H.has_edge(u_H, v_H)) or (
202
+ u_H == v_H and G.has_edge(u_G, v_G)
203
+ ):
204
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
205
+ else:
206
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
207
+
208
+
209
+ def test_lexicographic_product_raises():
210
+ with pytest.raises(nx.NetworkXError):
211
+ P = nx.lexicographic_product(nx.DiGraph(), nx.Graph())
212
+
213
+
214
+ def test_lexicographic_product_null():
215
+ null = nx.null_graph()
216
+ empty10 = nx.empty_graph(10)
217
+ K3 = nx.complete_graph(3)
218
+ K10 = nx.complete_graph(10)
219
+ P3 = nx.path_graph(3)
220
+ P10 = nx.path_graph(10)
221
+ # null graph
222
+ G = nx.lexicographic_product(null, null)
223
+ assert nx.is_isomorphic(G, null)
224
+ # null_graph X anything = null_graph and v.v.
225
+ G = nx.lexicographic_product(null, empty10)
226
+ assert nx.is_isomorphic(G, null)
227
+ G = nx.lexicographic_product(null, K3)
228
+ assert nx.is_isomorphic(G, null)
229
+ G = nx.lexicographic_product(null, K10)
230
+ assert nx.is_isomorphic(G, null)
231
+ G = nx.lexicographic_product(null, P3)
232
+ assert nx.is_isomorphic(G, null)
233
+ G = nx.lexicographic_product(null, P10)
234
+ assert nx.is_isomorphic(G, null)
235
+ G = nx.lexicographic_product(empty10, null)
236
+ assert nx.is_isomorphic(G, null)
237
+ G = nx.lexicographic_product(K3, null)
238
+ assert nx.is_isomorphic(G, null)
239
+ G = nx.lexicographic_product(K10, null)
240
+ assert nx.is_isomorphic(G, null)
241
+ G = nx.lexicographic_product(P3, null)
242
+ assert nx.is_isomorphic(G, null)
243
+ G = nx.lexicographic_product(P10, null)
244
+ assert nx.is_isomorphic(G, null)
245
+
246
+
247
+ def test_lexicographic_product_size():
248
+ K5 = nx.complete_graph(5)
249
+ P5 = nx.path_graph(5)
250
+ K3 = nx.complete_graph(3)
251
+ G = nx.lexicographic_product(P5, K3)
252
+ assert nx.number_of_nodes(G) == 5 * 3
253
+ G = nx.lexicographic_product(K3, K5)
254
+ assert nx.number_of_nodes(G) == 3 * 5
255
+
256
+
257
+ def test_lexicographic_product_combinations():
258
+ P5 = nx.path_graph(5)
259
+ K3 = nx.complete_graph(3)
260
+ G = nx.lexicographic_product(P5, K3)
261
+ assert nx.number_of_nodes(G) == 5 * 3
262
+ G = nx.lexicographic_product(nx.MultiGraph(P5), K3)
263
+ assert nx.number_of_nodes(G) == 5 * 3
264
+ G = nx.lexicographic_product(P5, nx.MultiGraph(K3))
265
+ assert nx.number_of_nodes(G) == 5 * 3
266
+ G = nx.lexicographic_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
267
+ assert nx.number_of_nodes(G) == 5 * 3
268
+
269
+ # No classic easily found classic results for lexicographic product
270
+
271
+
272
+ def test_lexicographic_product_random():
273
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
274
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
275
+ GH = nx.lexicographic_product(G, H)
276
+
277
+ for u_G, u_H in GH.nodes():
278
+ for v_G, v_H in GH.nodes():
279
+ if G.has_edge(u_G, v_G) or (u_G == v_G and H.has_edge(u_H, v_H)):
280
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
281
+ else:
282
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
283
+
284
+
285
+ def test_strong_product_raises():
286
+ with pytest.raises(nx.NetworkXError):
287
+ P = nx.strong_product(nx.DiGraph(), nx.Graph())
288
+
289
+
290
+ def test_strong_product_null():
291
+ null = nx.null_graph()
292
+ empty10 = nx.empty_graph(10)
293
+ K3 = nx.complete_graph(3)
294
+ K10 = nx.complete_graph(10)
295
+ P3 = nx.path_graph(3)
296
+ P10 = nx.path_graph(10)
297
+ # null graph
298
+ G = nx.strong_product(null, null)
299
+ assert nx.is_isomorphic(G, null)
300
+ # null_graph X anything = null_graph and v.v.
301
+ G = nx.strong_product(null, empty10)
302
+ assert nx.is_isomorphic(G, null)
303
+ G = nx.strong_product(null, K3)
304
+ assert nx.is_isomorphic(G, null)
305
+ G = nx.strong_product(null, K10)
306
+ assert nx.is_isomorphic(G, null)
307
+ G = nx.strong_product(null, P3)
308
+ assert nx.is_isomorphic(G, null)
309
+ G = nx.strong_product(null, P10)
310
+ assert nx.is_isomorphic(G, null)
311
+ G = nx.strong_product(empty10, null)
312
+ assert nx.is_isomorphic(G, null)
313
+ G = nx.strong_product(K3, null)
314
+ assert nx.is_isomorphic(G, null)
315
+ G = nx.strong_product(K10, null)
316
+ assert nx.is_isomorphic(G, null)
317
+ G = nx.strong_product(P3, null)
318
+ assert nx.is_isomorphic(G, null)
319
+ G = nx.strong_product(P10, null)
320
+ assert nx.is_isomorphic(G, null)
321
+
322
+
323
+ def test_strong_product_size():
324
+ K5 = nx.complete_graph(5)
325
+ P5 = nx.path_graph(5)
326
+ K3 = nx.complete_graph(3)
327
+ G = nx.strong_product(P5, K3)
328
+ assert nx.number_of_nodes(G) == 5 * 3
329
+ G = nx.strong_product(K3, K5)
330
+ assert nx.number_of_nodes(G) == 3 * 5
331
+
332
+
333
+ def test_strong_product_combinations():
334
+ P5 = nx.path_graph(5)
335
+ K3 = nx.complete_graph(3)
336
+ G = nx.strong_product(P5, K3)
337
+ assert nx.number_of_nodes(G) == 5 * 3
338
+ G = nx.strong_product(nx.MultiGraph(P5), K3)
339
+ assert nx.number_of_nodes(G) == 5 * 3
340
+ G = nx.strong_product(P5, nx.MultiGraph(K3))
341
+ assert nx.number_of_nodes(G) == 5 * 3
342
+ G = nx.strong_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
343
+ assert nx.number_of_nodes(G) == 5 * 3
344
+
345
+ # No classic easily found classic results for strong product
346
+
347
+
348
+ def test_strong_product_random():
349
+ G = nx.erdos_renyi_graph(10, 2 / 10.0)
350
+ H = nx.erdos_renyi_graph(10, 2 / 10.0)
351
+ GH = nx.strong_product(G, H)
352
+
353
+ for u_G, u_H in GH.nodes():
354
+ for v_G, v_H in GH.nodes():
355
+ if (
356
+ (u_G == v_G and H.has_edge(u_H, v_H))
357
+ or (u_H == v_H and G.has_edge(u_G, v_G))
358
+ or (G.has_edge(u_G, v_G) and H.has_edge(u_H, v_H))
359
+ ):
360
+ assert GH.has_edge((u_G, u_H), (v_G, v_H))
361
+ else:
362
+ assert not GH.has_edge((u_G, u_H), (v_G, v_H))
363
+
364
+
365
+ def test_graph_power_raises():
366
+ with pytest.raises(nx.NetworkXNotImplemented):
367
+ nx.power(nx.MultiDiGraph(), 2)
368
+
369
+
370
+ def test_graph_power():
371
+ # wikipedia example for graph power
372
+ G = nx.cycle_graph(7)
373
+ G.add_edge(6, 7)
374
+ G.add_edge(7, 8)
375
+ G.add_edge(8, 9)
376
+ G.add_edge(9, 2)
377
+ H = nx.power(G, 2)
378
+
379
+ assert edges_equal(
380
+ list(H.edges()),
381
+ [
382
+ (0, 1),
383
+ (0, 2),
384
+ (0, 5),
385
+ (0, 6),
386
+ (0, 7),
387
+ (1, 9),
388
+ (1, 2),
389
+ (1, 3),
390
+ (1, 6),
391
+ (2, 3),
392
+ (2, 4),
393
+ (2, 8),
394
+ (2, 9),
395
+ (3, 4),
396
+ (3, 5),
397
+ (3, 9),
398
+ (4, 5),
399
+ (4, 6),
400
+ (5, 6),
401
+ (5, 7),
402
+ (6, 7),
403
+ (6, 8),
404
+ (7, 8),
405
+ (7, 9),
406
+ (8, 9),
407
+ ],
408
+ )
409
+
410
+
411
+ def test_graph_power_negative():
412
+ with pytest.raises(ValueError):
413
+ nx.power(nx.Graph(), -1)
414
+
415
+
416
+ def test_rooted_product_raises():
417
+ with pytest.raises(nx.NodeNotFound):
418
+ nx.rooted_product(nx.Graph(), nx.path_graph(2), 10)
419
+
420
+
421
+ def test_rooted_product():
422
+ G = nx.cycle_graph(5)
423
+ H = nx.Graph()
424
+ H.add_edges_from([("a", "b"), ("b", "c"), ("b", "d")])
425
+ R = nx.rooted_product(G, H, "a")
426
+ assert len(R) == len(G) * len(H)
427
+ assert R.size() == G.size() + len(G) * H.size()
428
+
429
+
430
+ def test_corona_product():
431
+ G = nx.cycle_graph(3)
432
+ H = nx.path_graph(2)
433
+ C = nx.corona_product(G, H)
434
+ assert len(C) == (len(G) * len(H)) + len(G)
435
+ assert C.size() == G.size() + len(G) * H.size() + len(G) * len(H)
436
+
437
+
438
+ def test_modular_product():
439
+ G = nx.path_graph(3)
440
+ H = nx.path_graph(4)
441
+ M = nx.modular_product(G, H)
442
+ assert len(M) == len(G) * len(H)
443
+
444
+ assert edges_equal(
445
+ list(M.edges()),
446
+ [
447
+ ((0, 0), (1, 1)),
448
+ ((0, 0), (2, 2)),
449
+ ((0, 0), (2, 3)),
450
+ ((0, 1), (1, 0)),
451
+ ((0, 1), (1, 2)),
452
+ ((0, 1), (2, 3)),
453
+ ((0, 2), (1, 1)),
454
+ ((0, 2), (1, 3)),
455
+ ((0, 2), (2, 0)),
456
+ ((0, 3), (1, 2)),
457
+ ((0, 3), (2, 0)),
458
+ ((0, 3), (2, 1)),
459
+ ((1, 0), (2, 1)),
460
+ ((1, 1), (2, 0)),
461
+ ((1, 1), (2, 2)),
462
+ ((1, 2), (2, 1)),
463
+ ((1, 2), (2, 3)),
464
+ ((1, 3), (2, 2)),
465
+ ],
466
+ )
467
+
468
+
469
+ def test_modular_product_raises():
470
+ G = nx.Graph([(0, 1), (1, 2), (2, 0)])
471
+ H = nx.Graph([(0, 1), (1, 2), (2, 0)])
472
+ DG = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
473
+ DH = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
474
+ with pytest.raises(nx.NetworkXNotImplemented):
475
+ nx.modular_product(G, DH)
476
+ with pytest.raises(nx.NetworkXNotImplemented):
477
+ nx.modular_product(DG, H)
478
+ with pytest.raises(nx.NetworkXNotImplemented):
479
+ nx.modular_product(DG, DH)
480
+
481
+ MG = nx.MultiGraph([(0, 1), (1, 2), (2, 0), (0, 1)])
482
+ MH = nx.MultiGraph([(0, 1), (1, 2), (2, 0), (0, 1)])
483
+ with pytest.raises(nx.NetworkXNotImplemented):
484
+ nx.modular_product(G, MH)
485
+ with pytest.raises(nx.NetworkXNotImplemented):
486
+ nx.modular_product(MG, H)
487
+ with pytest.raises(nx.NetworkXNotImplemented):
488
+ nx.modular_product(MG, MH)
489
+ with pytest.raises(nx.NetworkXNotImplemented):
490
+ # check multigraph with no multiedges
491
+ nx.modular_product(nx.MultiGraph(G), H)
wemm/lib/python3.10/site-packages/networkx/algorithms/tests/__pycache__/test_chordal.cpython-310.pyc ADDED
Binary file (4.4 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/tree/tests/test_coding.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`~networkx.algorithms.tree.coding` module."""
2
+
3
+ from itertools import product
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.utils import edges_equal, nodes_equal
9
+
10
+
11
+ class TestPruferSequence:
12
+ """Unit tests for the Prüfer sequence encoding and decoding
13
+ functions.
14
+
15
+ """
16
+
17
+ def test_nontree(self):
18
+ with pytest.raises(nx.NotATree):
19
+ G = nx.cycle_graph(3)
20
+ nx.to_prufer_sequence(G)
21
+
22
+ def test_null_graph(self):
23
+ with pytest.raises(nx.NetworkXPointlessConcept):
24
+ nx.to_prufer_sequence(nx.null_graph())
25
+
26
+ def test_trivial_graph(self):
27
+ with pytest.raises(nx.NetworkXPointlessConcept):
28
+ nx.to_prufer_sequence(nx.trivial_graph())
29
+
30
+ def test_bad_integer_labels(self):
31
+ with pytest.raises(KeyError):
32
+ T = nx.Graph(nx.utils.pairwise("abc"))
33
+ nx.to_prufer_sequence(T)
34
+
35
+ def test_encoding(self):
36
+ """Tests for encoding a tree as a Prüfer sequence using the
37
+ iterative strategy.
38
+
39
+ """
40
+ # Example from Wikipedia.
41
+ tree = nx.Graph([(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)])
42
+ sequence = nx.to_prufer_sequence(tree)
43
+ assert sequence == [3, 3, 3, 4]
44
+
45
+ def test_decoding(self):
46
+ """Tests for decoding a tree from a Prüfer sequence."""
47
+ # Example from Wikipedia.
48
+ sequence = [3, 3, 3, 4]
49
+ tree = nx.from_prufer_sequence(sequence)
50
+ assert nodes_equal(list(tree), list(range(6)))
51
+ edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]
52
+ assert edges_equal(list(tree.edges()), edges)
53
+
54
+ def test_decoding2(self):
55
+ # Example from "An Optimal Algorithm for Prufer Codes".
56
+ sequence = [2, 4, 0, 1, 3, 3]
57
+ tree = nx.from_prufer_sequence(sequence)
58
+ assert nodes_equal(list(tree), list(range(8)))
59
+ edges = [(0, 1), (0, 4), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7)]
60
+ assert edges_equal(list(tree.edges()), edges)
61
+
62
+ def test_inverse(self):
63
+ """Tests that the encoding and decoding functions are inverses."""
64
+ for T in nx.nonisomorphic_trees(4):
65
+ T2 = nx.from_prufer_sequence(nx.to_prufer_sequence(T))
66
+ assert nodes_equal(list(T), list(T2))
67
+ assert edges_equal(list(T.edges()), list(T2.edges()))
68
+
69
+ for seq in product(range(4), repeat=2):
70
+ seq2 = nx.to_prufer_sequence(nx.from_prufer_sequence(seq))
71
+ assert list(seq) == seq2
72
+
73
+
74
+ class TestNestedTuple:
75
+ """Unit tests for the nested tuple encoding and decoding functions."""
76
+
77
+ def test_nontree(self):
78
+ with pytest.raises(nx.NotATree):
79
+ G = nx.cycle_graph(3)
80
+ nx.to_nested_tuple(G, 0)
81
+
82
+ def test_unknown_root(self):
83
+ with pytest.raises(nx.NodeNotFound):
84
+ G = nx.path_graph(2)
85
+ nx.to_nested_tuple(G, "bogus")
86
+
87
+ def test_encoding(self):
88
+ T = nx.full_rary_tree(2, 2**3 - 1)
89
+ expected = (((), ()), ((), ()))
90
+ actual = nx.to_nested_tuple(T, 0)
91
+ assert nodes_equal(expected, actual)
92
+
93
+ def test_canonical_form(self):
94
+ T = nx.Graph()
95
+ T.add_edges_from([(0, 1), (0, 2), (0, 3)])
96
+ T.add_edges_from([(1, 4), (1, 5)])
97
+ T.add_edges_from([(3, 6), (3, 7)])
98
+ root = 0
99
+ actual = nx.to_nested_tuple(T, root, canonical_form=True)
100
+ expected = ((), ((), ()), ((), ()))
101
+ assert actual == expected
102
+
103
+ def test_decoding(self):
104
+ balanced = (((), ()), ((), ()))
105
+ expected = nx.full_rary_tree(2, 2**3 - 1)
106
+ actual = nx.from_nested_tuple(balanced)
107
+ assert nx.is_isomorphic(expected, actual)
108
+
109
+ def test_sensible_relabeling(self):
110
+ balanced = (((), ()), ((), ()))
111
+ T = nx.from_nested_tuple(balanced, sensible_relabeling=True)
112
+ edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
113
+ assert nodes_equal(list(T), list(range(2**3 - 1)))
114
+ assert edges_equal(list(T.edges()), edges)
wemm/lib/python3.10/site-packages/networkx/algorithms/tree/tests/test_recognition.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestTreeRecognition:
7
+ graph = nx.Graph
8
+ multigraph = nx.MultiGraph
9
+
10
+ @classmethod
11
+ def setup_class(cls):
12
+ cls.T1 = cls.graph()
13
+
14
+ cls.T2 = cls.graph()
15
+ cls.T2.add_node(1)
16
+
17
+ cls.T3 = cls.graph()
18
+ cls.T3.add_nodes_from(range(5))
19
+ edges = [(i, i + 1) for i in range(4)]
20
+ cls.T3.add_edges_from(edges)
21
+
22
+ cls.T5 = cls.multigraph()
23
+ cls.T5.add_nodes_from(range(5))
24
+ edges = [(i, i + 1) for i in range(4)]
25
+ cls.T5.add_edges_from(edges)
26
+
27
+ cls.T6 = cls.graph()
28
+ cls.T6.add_nodes_from([6, 7])
29
+ cls.T6.add_edge(6, 7)
30
+
31
+ cls.F1 = nx.compose(cls.T6, cls.T3)
32
+
33
+ cls.N4 = cls.graph()
34
+ cls.N4.add_node(1)
35
+ cls.N4.add_edge(1, 1)
36
+
37
+ cls.N5 = cls.graph()
38
+ cls.N5.add_nodes_from(range(5))
39
+
40
+ cls.N6 = cls.graph()
41
+ cls.N6.add_nodes_from(range(3))
42
+ cls.N6.add_edges_from([(0, 1), (1, 2), (2, 0)])
43
+
44
+ cls.NF1 = nx.compose(cls.T6, cls.N6)
45
+
46
+ def test_null_tree(self):
47
+ with pytest.raises(nx.NetworkXPointlessConcept):
48
+ nx.is_tree(self.graph())
49
+
50
+ def test_null_tree2(self):
51
+ with pytest.raises(nx.NetworkXPointlessConcept):
52
+ nx.is_tree(self.multigraph())
53
+
54
+ def test_null_forest(self):
55
+ with pytest.raises(nx.NetworkXPointlessConcept):
56
+ nx.is_forest(self.graph())
57
+
58
+ def test_null_forest2(self):
59
+ with pytest.raises(nx.NetworkXPointlessConcept):
60
+ nx.is_forest(self.multigraph())
61
+
62
+ def test_is_tree(self):
63
+ assert nx.is_tree(self.T2)
64
+ assert nx.is_tree(self.T3)
65
+ assert nx.is_tree(self.T5)
66
+
67
+ def test_is_not_tree(self):
68
+ assert not nx.is_tree(self.N4)
69
+ assert not nx.is_tree(self.N5)
70
+ assert not nx.is_tree(self.N6)
71
+
72
+ def test_is_forest(self):
73
+ assert nx.is_forest(self.T2)
74
+ assert nx.is_forest(self.T3)
75
+ assert nx.is_forest(self.T5)
76
+ assert nx.is_forest(self.F1)
77
+ assert nx.is_forest(self.N5)
78
+
79
+ def test_is_not_forest(self):
80
+ assert not nx.is_forest(self.N4)
81
+ assert not nx.is_forest(self.N6)
82
+ assert not nx.is_forest(self.NF1)
83
+
84
+
85
+ class TestDirectedTreeRecognition(TestTreeRecognition):
86
+ graph = nx.DiGraph
87
+ multigraph = nx.MultiDiGraph
88
+
89
+
90
+ def test_disconnected_graph():
91
+ # https://github.com/networkx/networkx/issues/1144
92
+ G = nx.Graph()
93
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)])
94
+ assert not nx.is_tree(G)
95
+
96
+ G = nx.DiGraph()
97
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)])
98
+ assert not nx.is_tree(G)
99
+
100
+
101
+ def test_dag_nontree():
102
+ G = nx.DiGraph()
103
+ G.add_edges_from([(0, 1), (0, 2), (1, 2)])
104
+ assert not nx.is_tree(G)
105
+ assert nx.is_directed_acyclic_graph(G)
106
+
107
+
108
+ def test_multicycle():
109
+ G = nx.MultiDiGraph()
110
+ G.add_edges_from([(0, 1), (0, 1)])
111
+ assert not nx.is_tree(G)
112
+ assert nx.is_directed_acyclic_graph(G)
113
+
114
+
115
+ def test_emptybranch():
116
+ G = nx.DiGraph()
117
+ G.add_nodes_from(range(10))
118
+ assert nx.is_branching(G)
119
+ assert not nx.is_arborescence(G)
120
+
121
+
122
+ def test_is_branching_empty_graph_raises():
123
+ G = nx.DiGraph()
124
+ with pytest.raises(nx.NetworkXPointlessConcept, match="G has no nodes."):
125
+ nx.is_branching(G)
126
+
127
+
128
+ def test_path():
129
+ G = nx.DiGraph()
130
+ nx.add_path(G, range(5))
131
+ assert nx.is_branching(G)
132
+ assert nx.is_arborescence(G)
133
+
134
+
135
+ def test_notbranching1():
136
+ # Acyclic violation.
137
+ G = nx.MultiDiGraph()
138
+ G.add_nodes_from(range(10))
139
+ G.add_edges_from([(0, 1), (1, 0)])
140
+ assert not nx.is_branching(G)
141
+ assert not nx.is_arborescence(G)
142
+
143
+
144
+ def test_notbranching2():
145
+ # In-degree violation.
146
+ G = nx.MultiDiGraph()
147
+ G.add_nodes_from(range(10))
148
+ G.add_edges_from([(0, 1), (0, 2), (3, 2)])
149
+ assert not nx.is_branching(G)
150
+ assert not nx.is_arborescence(G)
151
+
152
+
153
+ def test_notarborescence1():
154
+ # Not an arborescence due to not spanning.
155
+ G = nx.MultiDiGraph()
156
+ G.add_nodes_from(range(10))
157
+ G.add_edges_from([(0, 1), (0, 2), (1, 3), (5, 6)])
158
+ assert nx.is_branching(G)
159
+ assert not nx.is_arborescence(G)
160
+
161
+
162
+ def test_notarborescence2():
163
+ # Not an arborescence due to in-degree violation.
164
+ G = nx.MultiDiGraph()
165
+ nx.add_path(G, range(5))
166
+ G.add_edge(6, 4)
167
+ assert not nx.is_branching(G)
168
+ assert not nx.is_arborescence(G)
169
+
170
+
171
+ def test_is_arborescense_empty_graph_raises():
172
+ G = nx.DiGraph()
173
+ with pytest.raises(nx.NetworkXPointlessConcept, match="G has no nodes."):
174
+ nx.is_arborescence(G)
wemm/lib/python3.10/site-packages/networkx/drawing/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # graph drawing and interface to graphviz
2
+
3
+ from .layout import *
4
+ from .nx_latex import *
5
+ from .nx_pylab import *
6
+ from . import nx_agraph
7
+ from . import nx_pydot
wemm/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ***************
3
+ Graphviz AGraph
4
+ ***************
5
+
6
+ Interface to pygraphviz AGraph class.
7
+
8
+ Examples
9
+ --------
10
+ >>> G = nx.complete_graph(5)
11
+ >>> A = nx.nx_agraph.to_agraph(G)
12
+ >>> H = nx.nx_agraph.from_agraph(A)
13
+
14
+ See Also
15
+ --------
16
+ - Pygraphviz: http://pygraphviz.github.io/
17
+ - Graphviz: https://www.graphviz.org
18
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
19
+ """
20
+
21
+ import os
22
+ import tempfile
23
+
24
+ import networkx as nx
25
+
26
+ __all__ = [
27
+ "from_agraph",
28
+ "to_agraph",
29
+ "write_dot",
30
+ "read_dot",
31
+ "graphviz_layout",
32
+ "pygraphviz_layout",
33
+ "view_pygraphviz",
34
+ ]
35
+
36
+
37
+ @nx._dispatchable(graphs=None, returns_graph=True)
38
+ def from_agraph(A, create_using=None):
39
+ """Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
40
+
41
+ Parameters
42
+ ----------
43
+ A : PyGraphviz AGraph
44
+ A graph created with PyGraphviz
45
+
46
+ create_using : NetworkX graph constructor, optional (default=None)
47
+ Graph type to create. If graph instance, then cleared before populated.
48
+ If `None`, then the appropriate Graph type is inferred from `A`.
49
+
50
+ Examples
51
+ --------
52
+ >>> K5 = nx.complete_graph(5)
53
+ >>> A = nx.nx_agraph.to_agraph(K5)
54
+ >>> G = nx.nx_agraph.from_agraph(A)
55
+
56
+ Notes
57
+ -----
58
+ The Graph G will have a dictionary G.graph_attr containing
59
+ the default graphviz attributes for graphs, nodes and edges.
60
+
61
+ Default node attributes will be in the dictionary G.node_attr
62
+ which is keyed by node.
63
+
64
+ Edge attributes will be returned as edge data in G. With
65
+ edge_attr=False the edge data will be the Graphviz edge weight
66
+ attribute or the value 1 if no edge weight attribute is found.
67
+
68
+ """
69
+ if create_using is None:
70
+ if A.is_directed():
71
+ if A.is_strict():
72
+ create_using = nx.DiGraph
73
+ else:
74
+ create_using = nx.MultiDiGraph
75
+ else:
76
+ if A.is_strict():
77
+ create_using = nx.Graph
78
+ else:
79
+ create_using = nx.MultiGraph
80
+
81
+ # assign defaults
82
+ N = nx.empty_graph(0, create_using)
83
+ if A.name is not None:
84
+ N.name = A.name
85
+
86
+ # add graph attributes
87
+ N.graph.update(A.graph_attr)
88
+
89
+ # add nodes, attributes to N.node_attr
90
+ for n in A.nodes():
91
+ str_attr = {str(k): v for k, v in n.attr.items()}
92
+ N.add_node(str(n), **str_attr)
93
+
94
+ # add edges, assign edge data as dictionary of attributes
95
+ for e in A.edges():
96
+ u, v = str(e[0]), str(e[1])
97
+ attr = dict(e.attr)
98
+ str_attr = {str(k): v for k, v in attr.items()}
99
+ if not N.is_multigraph():
100
+ if e.name is not None:
101
+ str_attr["key"] = e.name
102
+ N.add_edge(u, v, **str_attr)
103
+ else:
104
+ N.add_edge(u, v, key=e.name, **str_attr)
105
+
106
+ # add default attributes for graph, nodes, and edges
107
+ # hang them on N.graph_attr
108
+ N.graph["graph"] = dict(A.graph_attr)
109
+ N.graph["node"] = dict(A.node_attr)
110
+ N.graph["edge"] = dict(A.edge_attr)
111
+ return N
112
+
113
+
114
+ def to_agraph(N):
115
+ """Returns a pygraphviz graph from a NetworkX graph N.
116
+
117
+ Parameters
118
+ ----------
119
+ N : NetworkX graph
120
+ A graph created with NetworkX
121
+
122
+ Examples
123
+ --------
124
+ >>> K5 = nx.complete_graph(5)
125
+ >>> A = nx.nx_agraph.to_agraph(K5)
126
+
127
+ Notes
128
+ -----
129
+ If N has an dict N.graph_attr an attempt will be made first
130
+ to copy properties attached to the graph (see from_agraph)
131
+ and then updated with the calling arguments if any.
132
+
133
+ """
134
+ try:
135
+ import pygraphviz
136
+ except ImportError as err:
137
+ raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
138
+ directed = N.is_directed()
139
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
140
+
141
+ A = pygraphviz.AGraph(name=N.name, strict=strict, directed=directed)
142
+
143
+ # default graph attributes
144
+ A.graph_attr.update(N.graph.get("graph", {}))
145
+ A.node_attr.update(N.graph.get("node", {}))
146
+ A.edge_attr.update(N.graph.get("edge", {}))
147
+
148
+ A.graph_attr.update(
149
+ (k, v) for k, v in N.graph.items() if k not in ("graph", "node", "edge")
150
+ )
151
+
152
+ # add nodes
153
+ for n, nodedata in N.nodes(data=True):
154
+ A.add_node(n)
155
+ # Add node data
156
+ a = A.get_node(n)
157
+ for key, val in nodedata.items():
158
+ if key == "pos":
159
+ a.attr["pos"] = f"{val[0]},{val[1]}!"
160
+ else:
161
+ a.attr[key] = str(val)
162
+
163
+ # loop over edges
164
+ if N.is_multigraph():
165
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
166
+ str_edgedata = {k: str(v) for k, v in edgedata.items() if k != "key"}
167
+ A.add_edge(u, v, key=str(key))
168
+ # Add edge data
169
+ a = A.get_edge(u, v)
170
+ a.attr.update(str_edgedata)
171
+
172
+ else:
173
+ for u, v, edgedata in N.edges(data=True):
174
+ str_edgedata = {k: str(v) for k, v in edgedata.items()}
175
+ A.add_edge(u, v)
176
+ # Add edge data
177
+ a = A.get_edge(u, v)
178
+ a.attr.update(str_edgedata)
179
+
180
+ return A
181
+
182
+
183
+ def write_dot(G, path):
184
+ """Write NetworkX graph G to Graphviz dot format on path.
185
+
186
+ Parameters
187
+ ----------
188
+ G : graph
189
+ A networkx graph
190
+ path : filename
191
+ Filename or file handle to write
192
+
193
+ Notes
194
+ -----
195
+ To use a specific graph layout, call ``A.layout`` prior to `write_dot`.
196
+ Note that some graphviz layouts are not guaranteed to be deterministic,
197
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
198
+ """
199
+ A = to_agraph(G)
200
+ A.write(path)
201
+ A.clear()
202
+ return
203
+
204
+
205
+ @nx._dispatchable(name="agraph_read_dot", graphs=None, returns_graph=True)
206
+ def read_dot(path):
207
+ """Returns a NetworkX graph from a dot file on path.
208
+
209
+ Parameters
210
+ ----------
211
+ path : file or string
212
+ File name or file handle to read.
213
+ """
214
+ try:
215
+ import pygraphviz
216
+ except ImportError as err:
217
+ raise ImportError(
218
+ "read_dot() requires pygraphviz http://pygraphviz.github.io/"
219
+ ) from err
220
+ A = pygraphviz.AGraph(file=path)
221
+ gr = from_agraph(A)
222
+ A.clear()
223
+ return gr
224
+
225
+
226
+ def graphviz_layout(G, prog="neato", root=None, args=""):
227
+ """Create node positions for G using Graphviz.
228
+
229
+ Parameters
230
+ ----------
231
+ G : NetworkX graph
232
+ A graph created with NetworkX
233
+ prog : string
234
+ Name of Graphviz layout program
235
+ root : string, optional
236
+ Root node for twopi layout
237
+ args : string, optional
238
+ Extra arguments to Graphviz layout program
239
+
240
+ Returns
241
+ -------
242
+ Dictionary of x, y, positions keyed by node.
243
+
244
+ Examples
245
+ --------
246
+ >>> G = nx.petersen_graph()
247
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
248
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
249
+
250
+ Notes
251
+ -----
252
+ This is a wrapper for pygraphviz_layout.
253
+
254
+ Note that some graphviz layouts are not guaranteed to be deterministic,
255
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
256
+ """
257
+ return pygraphviz_layout(G, prog=prog, root=root, args=args)
258
+
259
+
260
+ def pygraphviz_layout(G, prog="neato", root=None, args=""):
261
+ """Create node positions for G using Graphviz.
262
+
263
+ Parameters
264
+ ----------
265
+ G : NetworkX graph
266
+ A graph created with NetworkX
267
+ prog : string
268
+ Name of Graphviz layout program
269
+ root : string, optional
270
+ Root node for twopi layout
271
+ args : string, optional
272
+ Extra arguments to Graphviz layout program
273
+
274
+ Returns
275
+ -------
276
+ node_pos : dict
277
+ Dictionary of x, y, positions keyed by node.
278
+
279
+ Examples
280
+ --------
281
+ >>> G = nx.petersen_graph()
282
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
283
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
284
+
285
+ Notes
286
+ -----
287
+ If you use complex node objects, they may have the same string
288
+ representation and GraphViz could treat them as the same node.
289
+ The layout may assign both nodes a single location. See Issue #1568
290
+ If this occurs in your case, consider relabeling the nodes just
291
+ for the layout computation using something similar to::
292
+
293
+ >>> H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
294
+ >>> H_layout = nx.nx_agraph.pygraphviz_layout(G, prog="dot")
295
+ >>> G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
296
+
297
+ Note that some graphviz layouts are not guaranteed to be deterministic,
298
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
299
+ """
300
+ try:
301
+ import pygraphviz
302
+ except ImportError as err:
303
+ raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
304
+ if root is not None:
305
+ args += f"-Groot={root}"
306
+ A = to_agraph(G)
307
+ A.layout(prog=prog, args=args)
308
+ node_pos = {}
309
+ for n in G:
310
+ node = pygraphviz.Node(A, n)
311
+ try:
312
+ xs = node.attr["pos"].split(",")
313
+ node_pos[n] = tuple(float(x) for x in xs)
314
+ except:
315
+ print("no position for node", n)
316
+ node_pos[n] = (0.0, 0.0)
317
+ return node_pos
318
+
319
+
320
+ @nx.utils.open_file(5, "w+b")
321
+ def view_pygraphviz(
322
+ G, edgelabel=None, prog="dot", args="", suffix="", path=None, show=True
323
+ ):
324
+ """Views the graph G using the specified layout algorithm.
325
+
326
+ Parameters
327
+ ----------
328
+ G : NetworkX graph
329
+ The machine to draw.
330
+ edgelabel : str, callable, None
331
+ If a string, then it specifies the edge attribute to be displayed
332
+ on the edge labels. If a callable, then it is called for each
333
+ edge and it should return the string to be displayed on the edges.
334
+ The function signature of `edgelabel` should be edgelabel(data),
335
+ where `data` is the edge attribute dictionary.
336
+ prog : string
337
+ Name of Graphviz layout program.
338
+ args : str
339
+ Additional arguments to pass to the Graphviz layout program.
340
+ suffix : str
341
+ If `filename` is None, we save to a temporary file. The value of
342
+ `suffix` will appear at the tail end of the temporary filename.
343
+ path : str, None
344
+ The filename used to save the image. If None, save to a temporary
345
+ file. File formats are the same as those from pygraphviz.agraph.draw.
346
+ show : bool, default = True
347
+ Whether to display the graph with :mod:`PIL.Image.show`,
348
+ default is `True`. If `False`, the rendered graph is still available
349
+ at `path`.
350
+
351
+ Returns
352
+ -------
353
+ path : str
354
+ The filename of the generated image.
355
+ A : PyGraphviz graph
356
+ The PyGraphviz graph instance used to generate the image.
357
+
358
+ Notes
359
+ -----
360
+ If this function is called in succession too quickly, sometimes the
361
+ image is not displayed. So you might consider time.sleep(.5) between
362
+ calls if you experience problems.
363
+
364
+ Note that some graphviz layouts are not guaranteed to be deterministic,
365
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
366
+
367
+ """
368
+ if not len(G):
369
+ raise nx.NetworkXException("An empty graph cannot be drawn.")
370
+
371
+ # If we are providing default values for graphviz, these must be set
372
+ # before any nodes or edges are added to the PyGraphviz graph object.
373
+ # The reason for this is that default values only affect incoming objects.
374
+ # If you change the default values after the objects have been added,
375
+ # then they inherit no value and are set only if explicitly set.
376
+
377
+ # to_agraph() uses these values.
378
+ attrs = ["edge", "node", "graph"]
379
+ for attr in attrs:
380
+ if attr not in G.graph:
381
+ G.graph[attr] = {}
382
+
383
+ # These are the default values.
384
+ edge_attrs = {"fontsize": "10"}
385
+ node_attrs = {
386
+ "style": "filled",
387
+ "fillcolor": "#0000FF40",
388
+ "height": "0.75",
389
+ "width": "0.75",
390
+ "shape": "circle",
391
+ }
392
+ graph_attrs = {}
393
+
394
+ def update_attrs(which, attrs):
395
+ # Update graph attributes. Return list of those which were added.
396
+ added = []
397
+ for k, v in attrs.items():
398
+ if k not in G.graph[which]:
399
+ G.graph[which][k] = v
400
+ added.append(k)
401
+
402
+ def clean_attrs(which, added):
403
+ # Remove added attributes
404
+ for attr in added:
405
+ del G.graph[which][attr]
406
+ if not G.graph[which]:
407
+ del G.graph[which]
408
+
409
+ # Update all default values
410
+ update_attrs("edge", edge_attrs)
411
+ update_attrs("node", node_attrs)
412
+ update_attrs("graph", graph_attrs)
413
+
414
+ # Convert to agraph, so we inherit default values
415
+ A = to_agraph(G)
416
+
417
+ # Remove the default values we added to the original graph.
418
+ clean_attrs("edge", edge_attrs)
419
+ clean_attrs("node", node_attrs)
420
+ clean_attrs("graph", graph_attrs)
421
+
422
+ # If the user passed in an edgelabel, we update the labels for all edges.
423
+ if edgelabel is not None:
424
+ if not callable(edgelabel):
425
+
426
+ def func(data):
427
+ return "".join([" ", str(data[edgelabel]), " "])
428
+
429
+ else:
430
+ func = edgelabel
431
+
432
+ # update all the edge labels
433
+ if G.is_multigraph():
434
+ for u, v, key, data in G.edges(keys=True, data=True):
435
+ # PyGraphviz doesn't convert the key to a string. See #339
436
+ edge = A.get_edge(u, v, str(key))
437
+ edge.attr["label"] = str(func(data))
438
+ else:
439
+ for u, v, data in G.edges(data=True):
440
+ edge = A.get_edge(u, v)
441
+ edge.attr["label"] = str(func(data))
442
+
443
+ if path is None:
444
+ ext = "png"
445
+ if suffix:
446
+ suffix = f"_{suffix}.{ext}"
447
+ else:
448
+ suffix = f".{ext}"
449
+ path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
450
+ else:
451
+ # Assume the decorator worked and it is a file-object.
452
+ pass
453
+
454
+ # Write graph to file
455
+ A.draw(path=path, format=None, prog=prog, args=args)
456
+ path.close()
457
+
458
+ # Show graph in a new window (depends on platform configuration)
459
+ if show:
460
+ from PIL import Image
461
+
462
+ Image.open(path.name).show()
463
+
464
+ return path.name, A
wemm/lib/python3.10/site-packages/networkx/drawing/nx_latex.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ *****
3
+ LaTeX
4
+ *****
5
+
6
+ Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
7
+ Usually, you will want the drawing to appear in a figure environment so
8
+ you use ``to_latex(G, caption="A caption")``. If you want the raw
9
+ drawing commands without a figure environment use :func:`to_latex_raw`.
10
+ And if you want to write to a file instead of just returning the latex
11
+ code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
12
+
13
+ To construct a figure with subfigures for each graph to be shown, provide
14
+ ``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
15
+ and a number of rows of subfigures inside the figure.
16
+
17
+ To be able to refer to the figures or subfigures in latex using ``\\ref``,
18
+ the keyword ``latex_label`` is available for figures and `sub_labels` for
19
+ a list of labels, one for each subfigure.
20
+
21
+ We intend to eventually provide an interface to the TikZ Graph
22
+ features which include e.g. layout algorithms.
23
+
24
+ Let us know via github what you'd like to see available, or better yet
25
+ give us some code to do it, or even better make a github pull request
26
+ to add the feature.
27
+
28
+ The TikZ approach
29
+ =================
30
+ Drawing options can be stored on the graph as node/edge attributes, or
31
+ can be provided as dicts keyed by node/edge to a string of the options
32
+ for that node/edge. Similarly a label can be shown for each node/edge
33
+ by specifying the labels as graph node/edge attributes or by providing
34
+ a dict keyed by node/edge to the text to be written for that node/edge.
35
+
36
+ Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
37
+ via a keyword argument. Similarly default node and edge options can be
38
+ provided through keywords arguments. The default node options are applied
39
+ to the single TikZ "path" that draws all nodes (and no edges). The default edge
40
+ options are applied to a TikZ "scope" which contains a path for each edge.
41
+
42
+ Examples
43
+ ========
44
+ >>> G = nx.path_graph(3)
45
+ >>> nx.write_latex(G, "just_my_figure.tex", as_document=True)
46
+ >>> nx.write_latex(G, "my_figure.tex", caption="A path graph", latex_label="fig1")
47
+ >>> latex_code = nx.to_latex(G) # a string rather than a file
48
+
49
+ You can change many features of the nodes and edges.
50
+
51
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph)
52
+ >>> pos = {n: (n, n) for n in G} # nodes set on a line
53
+
54
+ >>> G.nodes[0]["style"] = "blue"
55
+ >>> G.nodes[2]["style"] = "line width=3,draw"
56
+ >>> G.nodes[3]["label"] = "Stop"
57
+ >>> G.edges[(0, 1)]["label"] = "1st Step"
58
+ >>> G.edges[(0, 1)]["label_opts"] = "near start"
59
+ >>> G.edges[(1, 2)]["style"] = "line width=3"
60
+ >>> G.edges[(1, 2)]["label"] = "2nd Step"
61
+ >>> G.edges[(2, 3)]["style"] = "green"
62
+ >>> G.edges[(2, 3)]["label"] = "3rd Step"
63
+ >>> G.edges[(2, 3)]["label_opts"] = "near end"
64
+
65
+ >>> nx.write_latex(G, "latex_graph.tex", pos=pos, as_document=True)
66
+
67
+ Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
68
+ and view the pdf file created: ``latex_graph.pdf``.
69
+
70
+ If you want **subfigures** each containing one graph, you can input a list of graphs.
71
+
72
+ >>> H1 = nx.path_graph(4)
73
+ >>> H2 = nx.complete_graph(4)
74
+ >>> H3 = nx.path_graph(8)
75
+ >>> H4 = nx.complete_graph(8)
76
+ >>> graphs = [H1, H2, H3, H4]
77
+ >>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
78
+ >>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
79
+ >>> nx.write_latex(graphs, "subfigs.tex", n_rows=2, sub_captions=caps, sub_labels=lbls)
80
+ >>> latex_code = nx.to_latex(graphs, n_rows=2, sub_captions=caps, sub_labels=lbls)
81
+
82
+ >>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
83
+ >>> edge_width = {e: "line width=1.5" for e in H3.edges}
84
+ >>> pos = nx.circular_layout(H3)
85
+ >>> latex_code = nx.to_latex(H3, pos, node_options=node_color, edge_options=edge_width)
86
+ >>> print(latex_code)
87
+ \documentclass{report}
88
+ \usepackage{tikz}
89
+ \usepackage{subcaption}
90
+ <BLANKLINE>
91
+ \begin{document}
92
+ \begin{figure}
93
+ \begin{tikzpicture}
94
+ \draw
95
+ (1.0, 0.0) node[red] (0){0}
96
+ (0.707, 0.707) node[orange] (1){1}
97
+ (-0.0, 1.0) node[blue] (2){2}
98
+ (-0.707, 0.707) node[gray!90] (3){3}
99
+ (-1.0, -0.0) node (4){4}
100
+ (-0.707, -0.707) node (5){5}
101
+ (0.0, -1.0) node (6){6}
102
+ (0.707, -0.707) node (7){7};
103
+ \begin{scope}[-]
104
+ \draw[line width=1.5] (0) to (1);
105
+ \draw[line width=1.5] (1) to (2);
106
+ \draw[line width=1.5] (2) to (3);
107
+ \draw[line width=1.5] (3) to (4);
108
+ \draw[line width=1.5] (4) to (5);
109
+ \draw[line width=1.5] (5) to (6);
110
+ \draw[line width=1.5] (6) to (7);
111
+ \end{scope}
112
+ \end{tikzpicture}
113
+ \end{figure}
114
+ \end{document}
115
+
116
+ Notes
117
+ -----
118
+ If you want to change the preamble/postamble of the figure/document/subfigure
119
+ environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
120
+ `subfigure_wrapper`. The default values are stored in private variables
121
+ e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
122
+
123
+ References
124
+ ----------
125
+ TikZ: https://tikz.dev/
126
+
127
+ TikZ options details: https://tikz.dev/tikz-actions
128
+ """
129
+
130
+ import numbers
131
+ import os
132
+
133
+ import networkx as nx
134
+
135
+ __all__ = [
136
+ "to_latex_raw",
137
+ "to_latex",
138
+ "write_latex",
139
+ ]
140
+
141
+
142
+ @nx.utils.not_implemented_for("multigraph")
143
+ def to_latex_raw(
144
+ G,
145
+ pos="pos",
146
+ tikz_options="",
147
+ default_node_options="",
148
+ node_options="node_options",
149
+ node_label="label",
150
+ default_edge_options="",
151
+ edge_options="edge_options",
152
+ edge_label="label",
153
+ edge_label_options="edge_label_options",
154
+ ):
155
+ """Return a string of the LaTeX/TikZ code to draw `G`
156
+
157
+ This function produces just the code for the tikzpicture
158
+ without any enclosing environment.
159
+
160
+ Parameters
161
+ ==========
162
+ G : NetworkX graph
163
+ The NetworkX graph to be drawn
164
+ pos : string or dict (default "pos")
165
+ The name of the node attribute on `G` that holds the position of each node.
166
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
167
+ They can also be strings to denote positions in TikZ style, such as (x, y)
168
+ or (angle:radius).
169
+ If a dict, it should be keyed by node to a position.
170
+ If an empty dict, a circular layout is computed by TikZ.
171
+ tikz_options : string
172
+ The tikzpicture options description defining the options for the picture.
173
+ Often large scale options like `[scale=2]`.
174
+ default_node_options : string
175
+ The draw options for a path of nodes. Individual node options override these.
176
+ node_options : string or dict
177
+ The name of the node attribute on `G` that holds the options for each node.
178
+ Or a dict keyed by node to a string holding the options for that node.
179
+ node_label : string or dict
180
+ The name of the node attribute on `G` that holds the node label (text)
181
+ displayed for each node. If the attribute is "" or not present, the node
182
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
183
+ Or a dict keyed by node to a string holding the label for that node.
184
+ default_edge_options : string
185
+ The options for the scope drawing all edges. The default is "[-]" for
186
+ undirected graphs and "[->]" for directed graphs.
187
+ edge_options : string or dict
188
+ The name of the edge attribute on `G` that holds the options for each edge.
189
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
190
+ "loop," is added to the options for the self-loop edge. Hence you can
191
+ use "[loop above]" explicitly, but the default is "[loop]".
192
+ Or a dict keyed by edge to a string holding the options for that edge.
193
+ edge_label : string or dict
194
+ The name of the edge attribute on `G` that holds the edge label (text)
195
+ displayed for each edge. If the attribute is "" or not present, no edge
196
+ label is drawn.
197
+ Or a dict keyed by edge to a string holding the label for that edge.
198
+ edge_label_options : string or dict
199
+ The name of the edge attribute on `G` that holds the label options for
200
+ each edge. For example, "[sloped,above,blue]". The default is no options.
201
+ Or a dict keyed by edge to a string holding the label options for that edge.
202
+
203
+ Returns
204
+ =======
205
+ latex_code : string
206
+ The text string which draws the desired graph(s) when compiled by LaTeX.
207
+
208
+ See Also
209
+ ========
210
+ to_latex
211
+ write_latex
212
+ """
213
+ i4 = "\n "
214
+ i8 = "\n "
215
+
216
+ # set up position dict
217
+ # TODO allow pos to be None and use a nice TikZ default
218
+ if not isinstance(pos, dict):
219
+ pos = nx.get_node_attributes(G, pos)
220
+ if not pos:
221
+ # circular layout with radius 2
222
+ pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
223
+ for node in G:
224
+ if node not in pos:
225
+ raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
226
+ posnode = pos[node]
227
+ if not isinstance(posnode, str):
228
+ try:
229
+ posx, posy = posnode
230
+ pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
231
+ except (TypeError, ValueError):
232
+ msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
233
+ raise nx.NetworkXError(msg)
234
+
235
+ # set up all the dicts
236
+ if not isinstance(node_options, dict):
237
+ node_options = nx.get_node_attributes(G, node_options)
238
+ if not isinstance(node_label, dict):
239
+ node_label = nx.get_node_attributes(G, node_label)
240
+ if not isinstance(edge_options, dict):
241
+ edge_options = nx.get_edge_attributes(G, edge_options)
242
+ if not isinstance(edge_label, dict):
243
+ edge_label = nx.get_edge_attributes(G, edge_label)
244
+ if not isinstance(edge_label_options, dict):
245
+ edge_label_options = nx.get_edge_attributes(G, edge_label_options)
246
+
247
+ # process default options (add brackets or not)
248
+ topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
249
+ defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
250
+ linestyle = f"{'->' if G.is_directed() else '-'}"
251
+ if default_edge_options == "":
252
+ defe = "[" + linestyle + "]"
253
+ elif "-" in default_edge_options:
254
+ defe = default_edge_options
255
+ else:
256
+ defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
257
+
258
+ # Construct the string line by line
259
+ result = " \\begin{tikzpicture}" + topts
260
+ result += i4 + " \\draw" + defn
261
+ # load the nodes
262
+ for n in G:
263
+ # node options goes inside square brackets
264
+ nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
265
+ # node text goes inside curly brackets {}
266
+ ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
267
+
268
+ result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
269
+ result += ";\n"
270
+
271
+ # load the edges
272
+ result += " \\begin{scope}" + defe
273
+ for edge in G.edges:
274
+ u, v = edge[:2]
275
+ e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
276
+ # add loop options for selfloops if not present
277
+ if u == v and "loop" not in e_opts:
278
+ e_opts = "loop," + e_opts
279
+ e_opts = f"[{e_opts}]" if e_opts != "" else ""
280
+ # TODO -- handle bending of multiedges
281
+
282
+ els = edge_label_options[edge] if edge in edge_label_options else ""
283
+ # edge label options goes inside square brackets []
284
+ els = f"[{els.strip('[]')}]"
285
+ # edge text is drawn using the TikZ node command inside curly brackets {}
286
+ e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
287
+
288
+ result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
289
+
290
+ result += "\n \\end{scope}\n \\end{tikzpicture}\n"
291
+ return result
292
+
293
+
294
+ _DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
295
+ \usepackage{{tikz}}
296
+ \usepackage{{subcaption}}
297
+
298
+ \begin{{document}}
299
+ {content}
300
+ \end{{document}}"""
301
+
302
+
303
+ _FIG_WRAPPER = r"""\begin{{figure}}
304
+ {content}{caption}{label}
305
+ \end{{figure}}"""
306
+
307
+
308
+ _SUBFIG_WRAPPER = r""" \begin{{subfigure}}{{{size}\textwidth}}
309
+ {content}{caption}{label}
310
+ \end{{subfigure}}"""
311
+
312
+
313
+ def to_latex(
314
+ Gbunch,
315
+ pos="pos",
316
+ tikz_options="",
317
+ default_node_options="",
318
+ node_options="node_options",
319
+ node_label="node_label",
320
+ default_edge_options="",
321
+ edge_options="edge_options",
322
+ edge_label="edge_label",
323
+ edge_label_options="edge_label_options",
324
+ caption="",
325
+ latex_label="",
326
+ sub_captions=None,
327
+ sub_labels=None,
328
+ n_rows=1,
329
+ as_document=True,
330
+ document_wrapper=_DOC_WRAPPER_TIKZ,
331
+ figure_wrapper=_FIG_WRAPPER,
332
+ subfigure_wrapper=_SUBFIG_WRAPPER,
333
+ ):
334
+ """Return latex code to draw the graph(s) in `Gbunch`
335
+
336
+ The TikZ drawing utility in LaTeX is used to draw the graph(s).
337
+ If `Gbunch` is a graph, it is drawn in a figure environment.
338
+ If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
339
+ within a single figure environment.
340
+
341
+ If `as_document` is True, the figure is wrapped inside a document environment
342
+ so that the resulting string is ready to be compiled by LaTeX. Otherwise,
343
+ the string is ready for inclusion in a larger tex document using ``\\include``
344
+ or ``\\input`` statements.
345
+
346
+ Parameters
347
+ ==========
348
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
349
+ The NetworkX graph to be drawn or an iterable of graphs
350
+ to be drawn inside subfigures of a single figure.
351
+ pos : string or list of strings
352
+ The name of the node attribute on `G` that holds the position of each node.
353
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
354
+ They can also be strings to denote positions in TikZ style, such as (x, y)
355
+ or (angle:radius).
356
+ If a dict, it should be keyed by node to a position.
357
+ If an empty dict, a circular layout is computed by TikZ.
358
+ If you are drawing many graphs in subfigures, use a list of position dicts.
359
+ tikz_options : string
360
+ The tikzpicture options description defining the options for the picture.
361
+ Often large scale options like `[scale=2]`.
362
+ default_node_options : string
363
+ The draw options for a path of nodes. Individual node options override these.
364
+ node_options : string or dict
365
+ The name of the node attribute on `G` that holds the options for each node.
366
+ Or a dict keyed by node to a string holding the options for that node.
367
+ node_label : string or dict
368
+ The name of the node attribute on `G` that holds the node label (text)
369
+ displayed for each node. If the attribute is "" or not present, the node
370
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
371
+ Or a dict keyed by node to a string holding the label for that node.
372
+ default_edge_options : string
373
+ The options for the scope drawing all edges. The default is "[-]" for
374
+ undirected graphs and "[->]" for directed graphs.
375
+ edge_options : string or dict
376
+ The name of the edge attribute on `G` that holds the options for each edge.
377
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
378
+ "loop," is added to the options for the self-loop edge. Hence you can
379
+ use "[loop above]" explicitly, but the default is "[loop]".
380
+ Or a dict keyed by edge to a string holding the options for that edge.
381
+ edge_label : string or dict
382
+ The name of the edge attribute on `G` that holds the edge label (text)
383
+ displayed for each edge. If the attribute is "" or not present, no edge
384
+ label is drawn.
385
+ Or a dict keyed by edge to a string holding the label for that edge.
386
+ edge_label_options : string or dict
387
+ The name of the edge attribute on `G` that holds the label options for
388
+ each edge. For example, "[sloped,above,blue]". The default is no options.
389
+ Or a dict keyed by edge to a string holding the label options for that edge.
390
+ caption : string
391
+ The caption string for the figure environment
392
+ latex_label : string
393
+ The latex label used for the figure for easy referral from the main text
394
+ sub_captions : list of strings
395
+ The sub_caption string for each subfigure in the figure
396
+ sub_latex_labels : list of strings
397
+ The latex label for each subfigure in the figure
398
+ n_rows : int
399
+ The number of rows of subfigures to arrange for multiple graphs
400
+ as_document : bool
401
+ Whether to wrap the latex code in a document environment for compiling
402
+ document_wrapper : formatted text string with variable ``content``.
403
+ This text is called to evaluate the content embedded in a document
404
+ environment with a preamble setting up TikZ.
405
+ figure_wrapper : formatted text string
406
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
407
+ It wraps the content and if a caption is provided, adds the latex code for
408
+ that caption, and if a label is provided, adds the latex code for a label.
409
+ subfigure_wrapper : formatted text string
410
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
411
+ It wraps the content and if a caption is provided, adds the latex code for
412
+ that caption, and if a label is provided, adds the latex code for a label.
413
+ The size is the vertical size of each row of subfigures as a fraction.
414
+
415
+ Returns
416
+ =======
417
+ latex_code : string
418
+ The text string which draws the desired graph(s) when compiled by LaTeX.
419
+
420
+ See Also
421
+ ========
422
+ write_latex
423
+ to_latex_raw
424
+ """
425
+ if hasattr(Gbunch, "adj"):
426
+ raw = to_latex_raw(
427
+ Gbunch,
428
+ pos,
429
+ tikz_options,
430
+ default_node_options,
431
+ node_options,
432
+ node_label,
433
+ default_edge_options,
434
+ edge_options,
435
+ edge_label,
436
+ edge_label_options,
437
+ )
438
+ else: # iterator of graphs
439
+ sbf = subfigure_wrapper
440
+ size = 1 / n_rows
441
+
442
+ N = len(Gbunch)
443
+ if isinstance(pos, str | dict):
444
+ pos = [pos] * N
445
+ if sub_captions is None:
446
+ sub_captions = [""] * N
447
+ if sub_labels is None:
448
+ sub_labels = [""] * N
449
+ if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
450
+ raise nx.NetworkXError(
451
+ "length of Gbunch, sub_captions and sub_figures must agree"
452
+ )
453
+
454
+ raw = ""
455
+ for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
456
+ subraw = to_latex_raw(
457
+ G,
458
+ pos,
459
+ tikz_options,
460
+ default_node_options,
461
+ node_options,
462
+ node_label,
463
+ default_edge_options,
464
+ edge_options,
465
+ edge_label,
466
+ edge_label_options,
467
+ )
468
+ cap = f" \\caption{{{subcap}}}" if subcap else ""
469
+ lbl = f"\\label{{{sublbl}}}" if sublbl else ""
470
+ raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
471
+ raw += "\n"
472
+
473
+ # put raw latex code into a figure environment and optionally into a document
474
+ raw = raw[:-1]
475
+ cap = f"\n \\caption{{{caption}}}" if caption else ""
476
+ lbl = f"\\label{{{latex_label}}}" if latex_label else ""
477
+ fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
478
+ if as_document:
479
+ return document_wrapper.format(content=fig)
480
+ return fig
481
+
482
+
483
+ @nx.utils.open_file(1, mode="w")
484
+ def write_latex(Gbunch, path, **options):
485
+ """Write the latex code to draw the graph(s) onto `path`.
486
+
487
+ This convenience function creates the latex drawing code as a string
488
+ and writes that to a file ready to be compiled when `as_document` is True
489
+ or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
490
+
491
+ The `path` argument can be a string filename or a file handle to write to.
492
+
493
+ Parameters
494
+ ----------
495
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
496
+ If Gbunch is a graph, it is drawn in a figure environment.
497
+ If Gbunch is an iterable of graphs, each is drawn in a subfigure
498
+ environment within a single figure environment.
499
+ path : filename
500
+ Filename or file handle to write to
501
+ options : dict
502
+ By default, TikZ is used with options: (others are ignored)::
503
+
504
+ pos : string or dict or list
505
+ The name of the node attribute on `G` that holds the position of each node.
506
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
507
+ They can also be strings to denote positions in TikZ style, such as (x, y)
508
+ or (angle:radius).
509
+ If a dict, it should be keyed by node to a position.
510
+ If an empty dict, a circular layout is computed by TikZ.
511
+ If you are drawing many graphs in subfigures, use a list of position dicts.
512
+ tikz_options : string
513
+ The tikzpicture options description defining the options for the picture.
514
+ Often large scale options like `[scale=2]`.
515
+ default_node_options : string
516
+ The draw options for a path of nodes. Individual node options override these.
517
+ node_options : string or dict
518
+ The name of the node attribute on `G` that holds the options for each node.
519
+ Or a dict keyed by node to a string holding the options for that node.
520
+ node_label : string or dict
521
+ The name of the node attribute on `G` that holds the node label (text)
522
+ displayed for each node. If the attribute is "" or not present, the node
523
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
524
+ Or a dict keyed by node to a string holding the label for that node.
525
+ default_edge_options : string
526
+ The options for the scope drawing all edges. The default is "[-]" for
527
+ undirected graphs and "[->]" for directed graphs.
528
+ edge_options : string or dict
529
+ The name of the edge attribute on `G` that holds the options for each edge.
530
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
531
+ "loop," is added to the options for the self-loop edge. Hence you can
532
+ use "[loop above]" explicitly, but the default is "[loop]".
533
+ Or a dict keyed by edge to a string holding the options for that edge.
534
+ edge_label : string or dict
535
+ The name of the edge attribute on `G` that holds the edge label (text)
536
+ displayed for each edge. If the attribute is "" or not present, no edge
537
+ label is drawn.
538
+ Or a dict keyed by edge to a string holding the label for that edge.
539
+ edge_label_options : string or dict
540
+ The name of the edge attribute on `G` that holds the label options for
541
+ each edge. For example, "[sloped,above,blue]". The default is no options.
542
+ Or a dict keyed by edge to a string holding the label options for that edge.
543
+ caption : string
544
+ The caption string for the figure environment
545
+ latex_label : string
546
+ The latex label used for the figure for easy referral from the main text
547
+ sub_captions : list of strings
548
+ The sub_caption string for each subfigure in the figure
549
+ sub_latex_labels : list of strings
550
+ The latex label for each subfigure in the figure
551
+ n_rows : int
552
+ The number of rows of subfigures to arrange for multiple graphs
553
+ as_document : bool
554
+ Whether to wrap the latex code in a document environment for compiling
555
+ document_wrapper : formatted text string with variable ``content``.
556
+ This text is called to evaluate the content embedded in a document
557
+ environment with a preamble setting up the TikZ syntax.
558
+ figure_wrapper : formatted text string
559
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
560
+ It wraps the content and if a caption is provided, adds the latex code for
561
+ that caption, and if a label is provided, adds the latex code for a label.
562
+ subfigure_wrapper : formatted text string
563
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
564
+ It wraps the content and if a caption is provided, adds the latex code for
565
+ that caption, and if a label is provided, adds the latex code for a label.
566
+ The size is the vertical size of each row of subfigures as a fraction.
567
+
568
+ See Also
569
+ ========
570
+ to_latex
571
+ """
572
+ path.write(to_latex(Gbunch, **options))
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc ADDED
Binary file (7.36 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_tikz_attributes():
7
+ G = nx.path_graph(4, create_using=nx.DiGraph)
8
+ pos = {n: (n, n) for n in G}
9
+
10
+ G.add_edge(0, 0)
11
+ G.edges[(0, 0)]["label"] = "Loop"
12
+ G.edges[(0, 0)]["label_options"] = "midway"
13
+
14
+ G.nodes[0]["style"] = "blue"
15
+ G.nodes[1]["style"] = "line width=3,draw"
16
+ G.nodes[2]["style"] = "circle,draw,blue!50"
17
+ G.nodes[3]["label"] = "Stop"
18
+ G.edges[(0, 1)]["label"] = "1st Step"
19
+ G.edges[(0, 1)]["label_options"] = "near end"
20
+ G.edges[(2, 3)]["label"] = "3rd Step"
21
+ G.edges[(2, 3)]["label_options"] = "near start"
22
+ G.edges[(2, 3)]["style"] = "bend left,green"
23
+ G.edges[(1, 2)]["label"] = "2nd"
24
+ G.edges[(1, 2)]["label_options"] = "pos=0.5"
25
+ G.edges[(1, 2)]["style"] = ">->,bend right,line width=3,green!90"
26
+
27
+ output_tex = nx.to_latex(
28
+ G,
29
+ pos=pos,
30
+ as_document=False,
31
+ tikz_options="[scale=3]",
32
+ node_options="style",
33
+ edge_options="style",
34
+ node_label="label",
35
+ edge_label="label",
36
+ edge_label_options="label_options",
37
+ )
38
+ expected_tex = r"""\begin{figure}
39
+ \begin{tikzpicture}[scale=3]
40
+ \draw
41
+ (0, 0) node[blue] (0){0}
42
+ (1, 1) node[line width=3,draw] (1){1}
43
+ (2, 2) node[circle,draw,blue!50] (2){2}
44
+ (3, 3) node (3){Stop};
45
+ \begin{scope}[->]
46
+ \draw (0) to node[near end] {1st Step} (1);
47
+ \draw[loop,] (0) to node[midway] {Loop} (0);
48
+ \draw[>->,bend right,line width=3,green!90] (1) to node[pos=0.5] {2nd} (2);
49
+ \draw[bend left,green] (2) to node[near start] {3rd Step} (3);
50
+ \end{scope}
51
+ \end{tikzpicture}
52
+ \end{figure}"""
53
+
54
+ assert output_tex == expected_tex
55
+ # print(output_tex)
56
+ # # Pretty way to assert that A.to_document() == expected_tex
57
+ # content_same = True
58
+ # for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
59
+ # if aa != bb:
60
+ # content_same = False
61
+ # print(f"-{aa}|\n+{bb}|")
62
+ # assert content_same
63
+
64
+
65
+ def test_basic_multiple_graphs():
66
+ H1 = nx.path_graph(4)
67
+ H2 = nx.complete_graph(4)
68
+ H3 = nx.path_graph(8)
69
+ H4 = nx.complete_graph(8)
70
+ captions = [
71
+ "Path on 4 nodes",
72
+ "Complete graph on 4 nodes",
73
+ "Path on 8 nodes",
74
+ "Complete graph on 8 nodes",
75
+ ]
76
+ labels = ["fig2a", "fig2b", "fig2c", "fig2d"]
77
+ latex_code = nx.to_latex(
78
+ [H1, H2, H3, H4],
79
+ n_rows=2,
80
+ sub_captions=captions,
81
+ sub_labels=labels,
82
+ )
83
+ # print(latex_code)
84
+ assert "begin{document}" in latex_code
85
+ assert "begin{figure}" in latex_code
86
+ assert latex_code.count("begin{subfigure}") == 4
87
+ assert latex_code.count("tikzpicture") == 8
88
+ assert latex_code.count("[-]") == 4
89
+
90
+
91
+ def test_basic_tikz():
92
+ expected_tex = r"""\documentclass{report}
93
+ \usepackage{tikz}
94
+ \usepackage{subcaption}
95
+
96
+ \begin{document}
97
+ \begin{figure}
98
+ \begin{subfigure}{0.5\textwidth}
99
+ \begin{tikzpicture}[scale=2]
100
+ \draw[gray!90]
101
+ (0.749, 0.702) node[red!90] (0){0}
102
+ (1.0, -0.014) node[red!90] (1){1}
103
+ (-0.777, -0.705) node (2){2}
104
+ (-0.984, 0.042) node (3){3}
105
+ (-0.028, 0.375) node[cyan!90] (4){4}
106
+ (-0.412, 0.888) node (5){5}
107
+ (0.448, -0.856) node (6){6}
108
+ (0.003, -0.431) node[cyan!90] (7){7};
109
+ \begin{scope}[->,gray!90]
110
+ \draw (0) to (4);
111
+ \draw (0) to (5);
112
+ \draw (0) to (6);
113
+ \draw (0) to (7);
114
+ \draw (1) to (4);
115
+ \draw (1) to (5);
116
+ \draw (1) to (6);
117
+ \draw (1) to (7);
118
+ \draw (2) to (4);
119
+ \draw (2) to (5);
120
+ \draw (2) to (6);
121
+ \draw (2) to (7);
122
+ \draw (3) to (4);
123
+ \draw (3) to (5);
124
+ \draw (3) to (6);
125
+ \draw (3) to (7);
126
+ \end{scope}
127
+ \end{tikzpicture}
128
+ \caption{My tikz number 1 of 2}\label{tikz_1_2}
129
+ \end{subfigure}
130
+ \begin{subfigure}{0.5\textwidth}
131
+ \begin{tikzpicture}[scale=2]
132
+ \draw[gray!90]
133
+ (0.749, 0.702) node[green!90] (0){0}
134
+ (1.0, -0.014) node[green!90] (1){1}
135
+ (-0.777, -0.705) node (2){2}
136
+ (-0.984, 0.042) node (3){3}
137
+ (-0.028, 0.375) node[purple!90] (4){4}
138
+ (-0.412, 0.888) node (5){5}
139
+ (0.448, -0.856) node (6){6}
140
+ (0.003, -0.431) node[purple!90] (7){7};
141
+ \begin{scope}[->,gray!90]
142
+ \draw (0) to (4);
143
+ \draw (0) to (5);
144
+ \draw (0) to (6);
145
+ \draw (0) to (7);
146
+ \draw (1) to (4);
147
+ \draw (1) to (5);
148
+ \draw (1) to (6);
149
+ \draw (1) to (7);
150
+ \draw (2) to (4);
151
+ \draw (2) to (5);
152
+ \draw (2) to (6);
153
+ \draw (2) to (7);
154
+ \draw (3) to (4);
155
+ \draw (3) to (5);
156
+ \draw (3) to (6);
157
+ \draw (3) to (7);
158
+ \end{scope}
159
+ \end{tikzpicture}
160
+ \caption{My tikz number 2 of 2}\label{tikz_2_2}
161
+ \end{subfigure}
162
+ \caption{A graph generated with python and latex.}
163
+ \end{figure}
164
+ \end{document}"""
165
+
166
+ edges = [
167
+ (0, 4),
168
+ (0, 5),
169
+ (0, 6),
170
+ (0, 7),
171
+ (1, 4),
172
+ (1, 5),
173
+ (1, 6),
174
+ (1, 7),
175
+ (2, 4),
176
+ (2, 5),
177
+ (2, 6),
178
+ (2, 7),
179
+ (3, 4),
180
+ (3, 5),
181
+ (3, 6),
182
+ (3, 7),
183
+ ]
184
+ G = nx.DiGraph()
185
+ G.add_nodes_from(range(8))
186
+ G.add_edges_from(edges)
187
+ pos = {
188
+ 0: (0.7490296171687696, 0.702353520257394),
189
+ 1: (1.0, -0.014221357723796535),
190
+ 2: (-0.7765783344161441, -0.7054170966808919),
191
+ 3: (-0.9842690223417624, 0.04177547602465483),
192
+ 4: (-0.02768523817180917, 0.3745724439551441),
193
+ 5: (-0.41154855146767433, 0.8880106515525136),
194
+ 6: (0.44780153389148264, -0.8561492709269164),
195
+ 7: (0.0032499953371383505, -0.43092436645809945),
196
+ }
197
+
198
+ rc_node_color = {0: "red!90", 1: "red!90", 4: "cyan!90", 7: "cyan!90"}
199
+ gp_node_color = {0: "green!90", 1: "green!90", 4: "purple!90", 7: "purple!90"}
200
+
201
+ H = G.copy()
202
+ nx.set_node_attributes(G, rc_node_color, "color")
203
+ nx.set_node_attributes(H, gp_node_color, "color")
204
+
205
+ sub_captions = ["My tikz number 1 of 2", "My tikz number 2 of 2"]
206
+ sub_labels = ["tikz_1_2", "tikz_2_2"]
207
+
208
+ output_tex = nx.to_latex(
209
+ [G, H],
210
+ [pos, pos],
211
+ tikz_options="[scale=2]",
212
+ default_node_options="gray!90",
213
+ default_edge_options="gray!90",
214
+ node_options="color",
215
+ sub_captions=sub_captions,
216
+ sub_labels=sub_labels,
217
+ caption="A graph generated with python and latex.",
218
+ n_rows=2,
219
+ as_document=True,
220
+ )
221
+
222
+ assert output_tex == expected_tex
223
+ # print(output_tex)
224
+ # # Pretty way to assert that A.to_document() == expected_tex
225
+ # content_same = True
226
+ # for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
227
+ # if aa != bb:
228
+ # content_same = False
229
+ # print(f"-{aa}|\n+{bb}|")
230
+ # assert content_same
231
+
232
+
233
+ def test_exception_pos_single_graph(to_latex=nx.to_latex):
234
+ # smoke test that pos can be a string
235
+ G = nx.path_graph(4)
236
+ to_latex(G, pos="pos")
237
+
238
+ # must include all nodes
239
+ pos = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
240
+ with pytest.raises(nx.NetworkXError):
241
+ to_latex(G, pos)
242
+
243
+ # must have 2 values
244
+ pos[3] = (1, 2, 3)
245
+ with pytest.raises(nx.NetworkXError):
246
+ to_latex(G, pos)
247
+ pos[3] = 2
248
+ with pytest.raises(nx.NetworkXError):
249
+ to_latex(G, pos)
250
+
251
+ # check that passes with 2 values
252
+ pos[3] = (3, 2)
253
+ to_latex(G, pos)
254
+
255
+
256
+ def test_exception_multiple_graphs(to_latex=nx.to_latex):
257
+ G = nx.path_graph(3)
258
+ pos_bad = {0: (1, 2), 1: (0, 1)}
259
+ pos_OK = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
260
+ fourG = [G, G, G, G]
261
+ fourpos = [pos_OK, pos_OK, pos_OK, pos_OK]
262
+
263
+ # input single dict to use for all graphs
264
+ to_latex(fourG, pos_OK)
265
+ with pytest.raises(nx.NetworkXError):
266
+ to_latex(fourG, pos_bad)
267
+
268
+ # input list of dicts to use for all graphs
269
+ to_latex(fourG, fourpos)
270
+ with pytest.raises(nx.NetworkXError):
271
+ to_latex(fourG, [pos_bad, pos_bad, pos_bad, pos_bad])
272
+
273
+ # every pos dict must include all nodes
274
+ with pytest.raises(nx.NetworkXError):
275
+ to_latex(fourG, [pos_OK, pos_OK, pos_bad, pos_OK])
276
+
277
+ # test sub_captions and sub_labels (len must match Gbunch)
278
+ with pytest.raises(nx.NetworkXError):
279
+ to_latex(fourG, fourpos, sub_captions=["hi", "hi"])
280
+
281
+ with pytest.raises(nx.NetworkXError):
282
+ to_latex(fourG, fourpos, sub_labels=["hi", "hi"])
283
+
284
+ # all pass
285
+ to_latex(fourG, fourpos, sub_captions=["hi"] * 4, sub_labels=["lbl"] * 4)
286
+
287
+
288
+ def test_exception_multigraph():
289
+ G = nx.path_graph(4, create_using=nx.MultiGraph)
290
+ G.add_edge(1, 2)
291
+ with pytest.raises(nx.NetworkXNotImplemented):
292
+ nx.to_latex(G)
wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for layout functions."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+ np = pytest.importorskip("numpy")
8
+ pytest.importorskip("scipy")
9
+
10
+
11
+ class TestLayout:
12
+ @classmethod
13
+ def setup_class(cls):
14
+ cls.Gi = nx.grid_2d_graph(5, 5)
15
+ cls.Gs = nx.Graph()
16
+ nx.add_path(cls.Gs, "abcdef")
17
+ cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse
18
+
19
+ def test_spring_fixed_without_pos(self):
20
+ G = nx.path_graph(4)
21
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
22
+ pos = {0: (1, 1), 2: (0, 0)}
23
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
24
+ nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError
25
+
26
+ def test_spring_init_pos(self):
27
+ # Tests GH #2448
28
+ import math
29
+
30
+ G = nx.Graph()
31
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)])
32
+
33
+ init_pos = {0: (0.0, 0.0)}
34
+ fixed_pos = [0]
35
+ pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos)
36
+ has_nan = any(math.isnan(c) for coords in pos.values() for c in coords)
37
+ assert not has_nan, "values should not be nan"
38
+
39
+ def test_smoke_empty_graph(self):
40
+ G = []
41
+ nx.random_layout(G)
42
+ nx.circular_layout(G)
43
+ nx.planar_layout(G)
44
+ nx.spring_layout(G)
45
+ nx.fruchterman_reingold_layout(G)
46
+ nx.spectral_layout(G)
47
+ nx.shell_layout(G)
48
+ nx.bipartite_layout(G, G)
49
+ nx.spiral_layout(G)
50
+ nx.multipartite_layout(G)
51
+ nx.kamada_kawai_layout(G)
52
+
53
+ def test_smoke_int(self):
54
+ G = self.Gi
55
+ nx.random_layout(G)
56
+ nx.circular_layout(G)
57
+ nx.planar_layout(G)
58
+ nx.spring_layout(G)
59
+ nx.forceatlas2_layout(G)
60
+ nx.fruchterman_reingold_layout(G)
61
+ nx.fruchterman_reingold_layout(self.bigG)
62
+ nx.spectral_layout(G)
63
+ nx.spectral_layout(G.to_directed())
64
+ nx.spectral_layout(self.bigG)
65
+ nx.spectral_layout(self.bigG.to_directed())
66
+ nx.shell_layout(G)
67
+ nx.spiral_layout(G)
68
+ nx.kamada_kawai_layout(G)
69
+ nx.kamada_kawai_layout(G, dim=1)
70
+ nx.kamada_kawai_layout(G, dim=3)
71
+ nx.arf_layout(G)
72
+
73
+ def test_smoke_string(self):
74
+ G = self.Gs
75
+ nx.random_layout(G)
76
+ nx.circular_layout(G)
77
+ nx.planar_layout(G)
78
+ nx.spring_layout(G)
79
+ nx.forceatlas2_layout(G)
80
+ nx.fruchterman_reingold_layout(G)
81
+ nx.spectral_layout(G)
82
+ nx.shell_layout(G)
83
+ nx.spiral_layout(G)
84
+ nx.kamada_kawai_layout(G)
85
+ nx.kamada_kawai_layout(G, dim=1)
86
+ nx.kamada_kawai_layout(G, dim=3)
87
+ nx.arf_layout(G)
88
+
89
+ def check_scale_and_center(self, pos, scale, center):
90
+ center = np.array(center)
91
+ low = center - scale
92
+ hi = center + scale
93
+ vpos = np.array(list(pos.values()))
94
+ length = vpos.max(0) - vpos.min(0)
95
+ assert (length <= 2 * scale).all()
96
+ assert (vpos >= low).all()
97
+ assert (vpos <= hi).all()
98
+
99
+ def test_scale_and_center_arg(self):
100
+ sc = self.check_scale_and_center
101
+ c = (4, 5)
102
+ G = nx.complete_graph(9)
103
+ G.add_node(9)
104
+ sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
105
+ # rest can have 2*scale length: [-scale, scale]
106
+ sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
107
+ sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
108
+ sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
109
+ sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
110
+ sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
111
+ sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
112
+
113
+ c = (2, 3, 5)
114
+ sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c)
115
+
116
+ def test_planar_layout_non_planar_input(self):
117
+ G = nx.complete_graph(9)
118
+ pytest.raises(nx.NetworkXException, nx.planar_layout, G)
119
+
120
+ def test_smoke_planar_layout_embedding_input(self):
121
+ embedding = nx.PlanarEmbedding()
122
+ embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]})
123
+ nx.planar_layout(embedding)
124
+
125
+ def test_default_scale_and_center(self):
126
+ sc = self.check_scale_and_center
127
+ c = (0, 0)
128
+ G = nx.complete_graph(9)
129
+ G.add_node(9)
130
+ sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
131
+ sc(nx.spring_layout(G), scale=1, center=c)
132
+ sc(nx.spectral_layout(G), scale=1, center=c)
133
+ sc(nx.circular_layout(G), scale=1, center=c)
134
+ sc(nx.shell_layout(G), scale=1, center=c)
135
+ sc(nx.spiral_layout(G), scale=1, center=c)
136
+ sc(nx.kamada_kawai_layout(G), scale=1, center=c)
137
+
138
+ c = (0, 0, 0)
139
+ sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c)
140
+
141
+ def test_circular_planar_and_shell_dim_error(self):
142
+ G = nx.path_graph(4)
143
+ pytest.raises(ValueError, nx.circular_layout, G, dim=1)
144
+ pytest.raises(ValueError, nx.shell_layout, G, dim=1)
145
+ pytest.raises(ValueError, nx.shell_layout, G, dim=3)
146
+ pytest.raises(ValueError, nx.planar_layout, G, dim=1)
147
+ pytest.raises(ValueError, nx.planar_layout, G, dim=3)
148
+
149
+ def test_adjacency_interface_numpy(self):
150
+ A = nx.to_numpy_array(self.Gs)
151
+ pos = nx.drawing.layout._fruchterman_reingold(A)
152
+ assert pos.shape == (6, 2)
153
+ pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
154
+ assert pos.shape == (6, 3)
155
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
156
+ assert pos.shape == (6, 2)
157
+
158
+ def test_adjacency_interface_scipy(self):
159
+ A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
160
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
161
+ assert pos.shape == (6, 2)
162
+ pos = nx.drawing.layout._sparse_spectral(A)
163
+ assert pos.shape == (6, 2)
164
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
165
+ assert pos.shape == (6, 3)
166
+
167
+ def test_single_nodes(self):
168
+ G = nx.path_graph(1)
169
+ vpos = nx.shell_layout(G)
170
+ assert not vpos[0].any()
171
+ G = nx.path_graph(4)
172
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]])
173
+ assert not vpos[0].any()
174
+ assert vpos[3].any() # ensure node 3 not at origin (#3188)
175
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
176
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0)
177
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
178
+
179
+ def test_smoke_initial_pos_forceatlas2(self):
180
+ pos = nx.circular_layout(self.Gi)
181
+ npos = nx.forceatlas2_layout(self.Gi, pos=pos)
182
+
183
+ def test_smoke_initial_pos_fruchterman_reingold(self):
184
+ pos = nx.circular_layout(self.Gi)
185
+ npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
186
+
187
+ def test_smoke_initial_pos_arf(self):
188
+ pos = nx.circular_layout(self.Gi)
189
+ npos = nx.arf_layout(self.Gi, pos=pos)
190
+
191
+ def test_fixed_node_fruchterman_reingold(self):
192
+ # Dense version (numpy based)
193
+ pos = nx.circular_layout(self.Gi)
194
+ npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)])
195
+ assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)])
196
+ # Sparse version (scipy based)
197
+ pos = nx.circular_layout(self.bigG)
198
+ npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)])
199
+ for axis in range(2):
200
+ assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7)
201
+
202
+ def test_center_parameter(self):
203
+ G = nx.path_graph(1)
204
+ nx.random_layout(G, center=(1, 1))
205
+ vpos = nx.circular_layout(G, center=(1, 1))
206
+ assert tuple(vpos[0]) == (1, 1)
207
+ vpos = nx.planar_layout(G, center=(1, 1))
208
+ assert tuple(vpos[0]) == (1, 1)
209
+ vpos = nx.spring_layout(G, center=(1, 1))
210
+ assert tuple(vpos[0]) == (1, 1)
211
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
212
+ assert tuple(vpos[0]) == (1, 1)
213
+ vpos = nx.spectral_layout(G, center=(1, 1))
214
+ assert tuple(vpos[0]) == (1, 1)
215
+ vpos = nx.shell_layout(G, center=(1, 1))
216
+ assert tuple(vpos[0]) == (1, 1)
217
+ vpos = nx.spiral_layout(G, center=(1, 1))
218
+ assert tuple(vpos[0]) == (1, 1)
219
+
220
+ def test_center_wrong_dimensions(self):
221
+ G = nx.path_graph(1)
222
+ assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout)
223
+ pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1))
224
+ pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1))
225
+ pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1))
226
+ pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1))
227
+ pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1))
228
+ pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1))
229
+ pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1))
230
+ pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
231
+ pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1))
232
+ pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1))
233
+
234
+ def test_empty_graph(self):
235
+ G = nx.empty_graph()
236
+ vpos = nx.random_layout(G, center=(1, 1))
237
+ assert vpos == {}
238
+ vpos = nx.circular_layout(G, center=(1, 1))
239
+ assert vpos == {}
240
+ vpos = nx.planar_layout(G, center=(1, 1))
241
+ assert vpos == {}
242
+ vpos = nx.bipartite_layout(G, G)
243
+ assert vpos == {}
244
+ vpos = nx.spring_layout(G, center=(1, 1))
245
+ assert vpos == {}
246
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
247
+ assert vpos == {}
248
+ vpos = nx.spectral_layout(G, center=(1, 1))
249
+ assert vpos == {}
250
+ vpos = nx.shell_layout(G, center=(1, 1))
251
+ assert vpos == {}
252
+ vpos = nx.spiral_layout(G, center=(1, 1))
253
+ assert vpos == {}
254
+ vpos = nx.multipartite_layout(G, center=(1, 1))
255
+ assert vpos == {}
256
+ vpos = nx.kamada_kawai_layout(G, center=(1, 1))
257
+ assert vpos == {}
258
+ vpos = nx.forceatlas2_layout(G)
259
+ assert vpos == {}
260
+ vpos = nx.arf_layout(G)
261
+ assert vpos == {}
262
+
263
+ def test_bipartite_layout(self):
264
+ G = nx.complete_bipartite_graph(3, 5)
265
+ top, bottom = nx.bipartite.sets(G)
266
+
267
+ vpos = nx.bipartite_layout(G, top)
268
+ assert len(vpos) == len(G)
269
+
270
+ top_x = vpos[list(top)[0]][0]
271
+ bottom_x = vpos[list(bottom)[0]][0]
272
+ for node in top:
273
+ assert vpos[node][0] == top_x
274
+ for node in bottom:
275
+ assert vpos[node][0] == bottom_x
276
+
277
+ vpos = nx.bipartite_layout(
278
+ G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1
279
+ )
280
+ assert len(vpos) == len(G)
281
+
282
+ top_y = vpos[list(top)[0]][1]
283
+ bottom_y = vpos[list(bottom)[0]][1]
284
+ for node in top:
285
+ assert vpos[node][1] == top_y
286
+ for node in bottom:
287
+ assert vpos[node][1] == bottom_y
288
+
289
+ pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo")
290
+
291
+ def test_multipartite_layout(self):
292
+ sizes = (0, 5, 7, 2, 8)
293
+ G = nx.complete_multipartite_graph(*sizes)
294
+
295
+ vpos = nx.multipartite_layout(G)
296
+ assert len(vpos) == len(G)
297
+
298
+ start = 0
299
+ for n in sizes:
300
+ end = start + n
301
+ assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end))
302
+ start += n
303
+
304
+ vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2))
305
+ assert len(vpos) == len(G)
306
+
307
+ start = 0
308
+ for n in sizes:
309
+ end = start + n
310
+ assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end))
311
+ start += n
312
+
313
+ pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
314
+
315
+ def test_kamada_kawai_costfn_1d(self):
316
+ costfn = nx.drawing.layout._kamada_kawai_costfn
317
+
318
+ pos = np.array([4.0, 7.0])
319
+ invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]])
320
+
321
+ cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1)
322
+
323
+ assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7)
324
+ assert grad[0] == pytest.approx((-0.5), abs=1e-7)
325
+ assert grad[1] == pytest.approx(0.5, abs=1e-7)
326
+
327
+ def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim):
328
+ costfn = nx.drawing.layout._kamada_kawai_costfn
329
+
330
+ cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim)
331
+
332
+ expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2)
333
+ for i in range(pos.shape[0]):
334
+ for j in range(i + 1, pos.shape[0]):
335
+ diff = np.linalg.norm(pos[i] - pos[j])
336
+ expected_cost += (diff * invdist[i][j] - 1.0) ** 2
337
+
338
+ assert cost == pytest.approx(expected_cost, abs=1e-7)
339
+
340
+ dx = 1e-4
341
+ for nd in range(pos.shape[0]):
342
+ for dm in range(pos.shape[1]):
343
+ idx = nd * pos.shape[1] + dm
344
+ ps = pos.flatten()
345
+
346
+ ps[idx] += dx
347
+ cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
348
+
349
+ ps[idx] -= 2 * dx
350
+ cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
351
+
352
+ assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5)
353
+
354
+ def test_kamada_kawai_costfn(self):
355
+ invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]])
356
+ meanwt = 0.3
357
+
358
+ # 2d
359
+ pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]])
360
+
361
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2)
362
+
363
+ # 3d
364
+ pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]])
365
+
366
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3)
367
+
368
+ def test_spiral_layout(self):
369
+ G = self.Gs
370
+
371
+ # a lower value of resolution should result in a more compact layout
372
+ # intuitively, the total distance from the start and end nodes
373
+ # via each node in between (transiting through each) will be less,
374
+ # assuming rescaling does not occur on the computed node positions
375
+ pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values()))
376
+ pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values()))
377
+ distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1)
378
+ distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1)
379
+ assert sum(distances) > sum(distances_tighter)
380
+
381
+ # return near-equidistant points after the first value if set to true
382
+ pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values()))
383
+ distances_equidistant = np.linalg.norm(
384
+ pos_equidistant[:-1] - pos_equidistant[1:], axis=1
385
+ )
386
+ assert np.allclose(
387
+ distances_equidistant[1:], distances_equidistant[-1], atol=0.01
388
+ )
389
+
390
+ def test_spiral_layout_equidistant(self):
391
+ G = nx.path_graph(10)
392
+ pos = nx.spiral_layout(G, equidistant=True)
393
+ # Extract individual node positions as an array
394
+ p = np.array(list(pos.values()))
395
+ # Elementwise-distance between node positions
396
+ dist = np.linalg.norm(p[1:] - p[:-1], axis=1)
397
+ assert np.allclose(np.diff(dist), 0, atol=1e-3)
398
+
399
+ def test_forceatlas2_layout_partial_input_test(self):
400
+ # check whether partial pos input still returns a full proper position
401
+ G = self.Gs
402
+ node = nx.utils.arbitrary_element(G)
403
+ pos = nx.circular_layout(G)
404
+ del pos[node]
405
+ pos = nx.forceatlas2_layout(G, pos=pos)
406
+ assert len(pos) == len(G)
407
+
408
+ def test_rescale_layout_dict(self):
409
+ G = nx.empty_graph()
410
+ vpos = nx.random_layout(G, center=(1, 1))
411
+ assert nx.rescale_layout_dict(vpos) == {}
412
+
413
+ G = nx.empty_graph(2)
414
+ vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)}
415
+ s_vpos = nx.rescale_layout_dict(vpos)
416
+ assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6
417
+
418
+ G = nx.empty_graph(3)
419
+ vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)}
420
+ s_vpos = nx.rescale_layout_dict(vpos)
421
+
422
+ expectation = {
423
+ 0: np.array((-1, -1)),
424
+ 1: np.array((1, 1)),
425
+ 2: np.array((0, 0)),
426
+ }
427
+ for k, v in expectation.items():
428
+ assert (s_vpos[k] == v).all()
429
+ s_vpos = nx.rescale_layout_dict(vpos, scale=2)
430
+ expectation = {
431
+ 0: np.array((-2, -2)),
432
+ 1: np.array((2, 2)),
433
+ 2: np.array((0, 0)),
434
+ }
435
+ for k, v in expectation.items():
436
+ assert (s_vpos[k] == v).all()
437
+
438
+ def test_arf_layout_partial_input_test(self):
439
+ # Checks whether partial pos input still returns a proper position.
440
+ G = self.Gs
441
+ node = nx.utils.arbitrary_element(G)
442
+ pos = nx.circular_layout(G)
443
+ del pos[node]
444
+ pos = nx.arf_layout(G, pos=pos)
445
+ assert len(pos) == len(G)
446
+
447
+ def test_arf_layout_negative_a_check(self):
448
+ """
449
+ Checks input parameters correctly raises errors. For example, `a` should be larger than 1
450
+ """
451
+ G = self.Gs
452
+ pytest.raises(ValueError, nx.arf_layout, G=G, a=-1)
453
+
454
+ def test_smoke_seed_input(self):
455
+ G = self.Gs
456
+ nx.random_layout(G, seed=42)
457
+ nx.spring_layout(G, seed=42)
458
+ nx.arf_layout(G, seed=42)
459
+ nx.forceatlas2_layout(G, seed=42)
460
+
461
+
462
+ def test_multipartite_layout_nonnumeric_partition_labels():
463
+ """See gh-5123."""
464
+ G = nx.Graph()
465
+ G.add_node(0, subset="s0")
466
+ G.add_node(1, subset="s0")
467
+ G.add_node(2, subset="s1")
468
+ G.add_node(3, subset="s1")
469
+ G.add_edges_from([(0, 2), (0, 3), (1, 2)])
470
+ pos = nx.multipartite_layout(G)
471
+ assert len(pos) == len(G)
472
+
473
+
474
+ def test_multipartite_layout_layer_order():
475
+ """Return the layers in sorted order if the layers of the multipartite
476
+ graph are sortable. See gh-5691"""
477
+ G = nx.Graph()
478
+ node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4)))
479
+ for node, layer in node_group.items():
480
+ G.add_node(node, subset=layer)
481
+
482
+ # Horizontal alignment, therefore y-coord determines layers
483
+ pos = nx.multipartite_layout(G, align="horizontal")
484
+
485
+ layers = nx.utils.groups(node_group)
486
+ pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers)
487
+ for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()):
488
+ assert n1 == n2 and (p1 == p2).all()
489
+
490
+ # Nodes "a" and "d" are in the same layer
491
+ assert pos["a"][-1] == pos["d"][-1]
492
+ # positions should be sorted according to layer
493
+ assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1]
494
+
495
+ # Make sure that multipartite_layout still works when layers are not sortable
496
+ G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints
497
+ pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise
498
+ assert pos_nosort.keys() == pos.keys()
499
+
500
+
501
+ def _num_nodes_per_bfs_layer(pos):
502
+ """Helper function to extract the number of nodes in each layer of bfs_layout"""
503
+ x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension
504
+ _, layer_count = np.unique(x, return_counts=True)
505
+ return layer_count
506
+
507
+
508
+ @pytest.mark.parametrize("n", range(2, 7))
509
+ def test_bfs_layout_complete_graph(n):
510
+ """The complete graph should result in two layers: the starting node and
511
+ a second layer containing all neighbors."""
512
+ G = nx.complete_graph(n)
513
+ pos = nx.bfs_layout(G, start=0)
514
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1])
515
+
516
+
517
+ def test_bfs_layout_barbell():
518
+ G = nx.barbell_graph(5, 3)
519
+ # Start in one of the "bells"
520
+ pos = nx.bfs_layout(G, start=0)
521
+ # start, bell-1, [1] * len(bar)+1, bell-1
522
+ expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4]
523
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
524
+ # Start in the other "bell" - expect same layer pattern
525
+ pos = nx.bfs_layout(G, start=12)
526
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
527
+ # Starting in the center of the bar, expect layers to be symmetric
528
+ pos = nx.bfs_layout(G, start=6)
529
+ # Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells}
530
+ expected_nodes_per_layer = [1, 2, 2, 8]
531
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
532
+
533
+
534
+ def test_bfs_layout_disconnected():
535
+ G = nx.complete_graph(5)
536
+ G.add_edges_from([(10, 11), (11, 12)])
537
+ with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"):
538
+ nx.bfs_layout(G, start=0)
wemm/lib/python3.10/site-packages/networkx/generators/atlas.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for the small graph atlas.
3
+ """
4
+
5
+ import gzip
6
+ import importlib.resources
7
+ import os
8
+ import os.path
9
+ from itertools import islice
10
+
11
+ import networkx as nx
12
+
13
+ __all__ = ["graph_atlas", "graph_atlas_g"]
14
+
15
+ #: The total number of graphs in the atlas.
16
+ #:
17
+ #: The graphs are labeled starting from 0 and extending to (but not
18
+ #: including) this number.
19
+ NUM_GRAPHS = 1253
20
+
21
+ #: The path to the data file containing the graph edge lists.
22
+ #:
23
+ #: This is the absolute path of the gzipped text file containing the
24
+ #: edge list for each graph in the atlas. The file contains one entry
25
+ #: per graph in the atlas, in sequential order, starting from graph
26
+ #: number 0 and extending through graph number 1252 (see
27
+ #: :data:`NUM_GRAPHS`). Each entry looks like
28
+ #:
29
+ #: .. sourcecode:: text
30
+ #:
31
+ #: GRAPH 6
32
+ #: NODES 3
33
+ #: 0 1
34
+ #: 0 2
35
+ #:
36
+ #: where the first two lines are the graph's index in the atlas and the
37
+ #: number of nodes in the graph, and the remaining lines are the edge
38
+ #: list.
39
+ #:
40
+ #: This file was generated from a Python list of graphs via code like
41
+ #: the following::
42
+ #:
43
+ #: import gzip
44
+ #: from networkx.generators.atlas import graph_atlas_g
45
+ #: from networkx.readwrite.edgelist import write_edgelist
46
+ #:
47
+ #: with gzip.open('atlas.dat.gz', 'wb') as f:
48
+ #: for i, G in enumerate(graph_atlas_g()):
49
+ #: f.write(bytes(f'GRAPH {i}\n', encoding='utf-8'))
50
+ #: f.write(bytes(f'NODES {len(G)}\n', encoding='utf-8'))
51
+ #: write_edgelist(G, f, data=False)
52
+ #:
53
+
54
+ # Path to the atlas file
55
+ ATLAS_FILE = importlib.resources.files("networkx.generators") / "atlas.dat.gz"
56
+
57
+
58
+ def _generate_graphs():
59
+ """Sequentially read the file containing the edge list data for the
60
+ graphs in the atlas and generate the graphs one at a time.
61
+
62
+ This function reads the file given in :data:`.ATLAS_FILE`.
63
+
64
+ """
65
+ with gzip.open(ATLAS_FILE, "rb") as f:
66
+ line = f.readline()
67
+ while line and line.startswith(b"GRAPH"):
68
+ # The first two lines of each entry tell us the index of the
69
+ # graph in the list and the number of nodes in the graph.
70
+ # They look like this:
71
+ #
72
+ # GRAPH 3
73
+ # NODES 2
74
+ #
75
+ graph_index = int(line[6:].rstrip())
76
+ line = f.readline()
77
+ num_nodes = int(line[6:].rstrip())
78
+ # The remaining lines contain the edge list, until the next
79
+ # GRAPH line (or until the end of the file).
80
+ edgelist = []
81
+ line = f.readline()
82
+ while line and not line.startswith(b"GRAPH"):
83
+ edgelist.append(line.rstrip())
84
+ line = f.readline()
85
+ G = nx.Graph()
86
+ G.name = f"G{graph_index}"
87
+ G.add_nodes_from(range(num_nodes))
88
+ G.add_edges_from(tuple(map(int, e.split())) for e in edgelist)
89
+ yield G
90
+
91
+
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def graph_atlas(i):
94
+ """Returns graph number `i` from the Graph Atlas.
95
+
96
+ For more information, see :func:`.graph_atlas_g`.
97
+
98
+ Parameters
99
+ ----------
100
+ i : int
101
+ The index of the graph from the atlas to get. The graph at index
102
+ 0 is assumed to be the null graph.
103
+
104
+ Returns
105
+ -------
106
+ list
107
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
108
+ corresponding to the graph *i* in the Graph Atlas.
109
+
110
+ See also
111
+ --------
112
+ graph_atlas_g
113
+
114
+ Notes
115
+ -----
116
+ The time required by this function increases linearly with the
117
+ argument `i`, since it reads a large file sequentially in order to
118
+ generate the graph [1]_.
119
+
120
+ References
121
+ ----------
122
+ .. [1] Ronald C. Read and Robin J. Wilson, *An Atlas of Graphs*.
123
+ Oxford University Press, 1998.
124
+
125
+ """
126
+ if not (0 <= i < NUM_GRAPHS):
127
+ raise ValueError(f"index must be between 0 and {NUM_GRAPHS}")
128
+ return next(islice(_generate_graphs(), i, None))
129
+
130
+
131
+ @nx._dispatchable(graphs=None, returns_graph=True)
132
+ def graph_atlas_g():
133
+ """Returns the list of all graphs with up to seven nodes named in the
134
+ Graph Atlas.
135
+
136
+ The graphs are listed in increasing order by
137
+
138
+ 1. number of nodes,
139
+ 2. number of edges,
140
+ 3. degree sequence (for example 111223 < 112222),
141
+ 4. number of automorphisms,
142
+
143
+ in that order, with three exceptions as described in the *Notes*
144
+ section below. This causes the list to correspond with the index of
145
+ the graphs in the Graph Atlas [atlas]_, with the first graph,
146
+ ``G[0]``, being the null graph.
147
+
148
+ Returns
149
+ -------
150
+ list
151
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
152
+ corresponding to the graph *i* in the Graph Atlas.
153
+
154
+ See also
155
+ --------
156
+ graph_atlas
157
+
158
+ Notes
159
+ -----
160
+ This function may be expensive in both time and space, since it
161
+ reads a large file sequentially in order to populate the list.
162
+
163
+ Although the NetworkX atlas functions match the order of graphs
164
+ given in the "Atlas of Graphs" book, there are (at least) three
165
+ errors in the ordering described in the book. The following three
166
+ pairs of nodes violate the lexicographically nondecreasing sorted
167
+ degree sequence rule:
168
+
169
+ - graphs 55 and 56 with degree sequences 001111 and 000112,
170
+ - graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
171
+ - graphs 1012 and 1213 with degree sequences 1244555 and 1244456.
172
+
173
+ References
174
+ ----------
175
+ .. [atlas] Ronald C. Read and Robin J. Wilson,
176
+ *An Atlas of Graphs*.
177
+ Oxford University Press, 1998.
178
+
179
+ """
180
+ return list(_generate_graphs())
wemm/lib/python3.10/site-packages/networkx/generators/community.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for classes of graphs used in studying social networks."""
2
+
3
+ import itertools
4
+ import math
5
+
6
+ import networkx as nx
7
+ from networkx.utils import py_random_state
8
+
9
+ __all__ = [
10
+ "caveman_graph",
11
+ "connected_caveman_graph",
12
+ "relaxed_caveman_graph",
13
+ "random_partition_graph",
14
+ "planted_partition_graph",
15
+ "gaussian_random_partition_graph",
16
+ "ring_of_cliques",
17
+ "windmill_graph",
18
+ "stochastic_block_model",
19
+ "LFR_benchmark_graph",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(graphs=None, returns_graph=True)
24
+ def caveman_graph(l, k):
25
+ """Returns a caveman graph of `l` cliques of size `k`.
26
+
27
+ Parameters
28
+ ----------
29
+ l : int
30
+ Number of cliques
31
+ k : int
32
+ Size of cliques
33
+
34
+ Returns
35
+ -------
36
+ G : NetworkX Graph
37
+ caveman graph
38
+
39
+ Notes
40
+ -----
41
+ This returns an undirected graph, it can be converted to a directed
42
+ graph using :func:`nx.to_directed`, or a multigraph using
43
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
44
+ described in [1]_ and it is unclear which of the directed
45
+ generalizations is most useful.
46
+
47
+ Examples
48
+ --------
49
+ >>> G = nx.caveman_graph(3, 3)
50
+
51
+ See also
52
+ --------
53
+
54
+ connected_caveman_graph
55
+
56
+ References
57
+ ----------
58
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
59
+ Amer. J. Soc. 105, 493-527, 1999.
60
+ """
61
+ # l disjoint cliques of size k
62
+ G = nx.empty_graph(l * k)
63
+ if k > 1:
64
+ for start in range(0, l * k, k):
65
+ edges = itertools.combinations(range(start, start + k), 2)
66
+ G.add_edges_from(edges)
67
+ return G
68
+
69
+
70
+ @nx._dispatchable(graphs=None, returns_graph=True)
71
+ def connected_caveman_graph(l, k):
72
+ """Returns a connected caveman graph of `l` cliques of size `k`.
73
+
74
+ The connected caveman graph is formed by creating `n` cliques of size
75
+ `k`, then a single edge in each clique is rewired to a node in an
76
+ adjacent clique.
77
+
78
+ Parameters
79
+ ----------
80
+ l : int
81
+ number of cliques
82
+ k : int
83
+ size of cliques (k at least 2 or NetworkXError is raised)
84
+
85
+ Returns
86
+ -------
87
+ G : NetworkX Graph
88
+ connected caveman graph
89
+
90
+ Raises
91
+ ------
92
+ NetworkXError
93
+ If the size of cliques `k` is smaller than 2.
94
+
95
+ Notes
96
+ -----
97
+ This returns an undirected graph, it can be converted to a directed
98
+ graph using :func:`nx.to_directed`, or a multigraph using
99
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
100
+ described in [1]_ and it is unclear which of the directed
101
+ generalizations is most useful.
102
+
103
+ Examples
104
+ --------
105
+ >>> G = nx.connected_caveman_graph(3, 3)
106
+
107
+ References
108
+ ----------
109
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
110
+ Amer. J. Soc. 105, 493-527, 1999.
111
+ """
112
+ if k < 2:
113
+ raise nx.NetworkXError(
114
+ "The size of cliques in a connected caveman graph must be at least 2."
115
+ )
116
+
117
+ G = nx.caveman_graph(l, k)
118
+ for start in range(0, l * k, k):
119
+ G.remove_edge(start, start + 1)
120
+ G.add_edge(start, (start - 1) % (l * k))
121
+ return G
122
+
123
+
124
+ @py_random_state(3)
125
+ @nx._dispatchable(graphs=None, returns_graph=True)
126
+ def relaxed_caveman_graph(l, k, p, seed=None):
127
+ """Returns a relaxed caveman graph.
128
+
129
+ A relaxed caveman graph starts with `l` cliques of size `k`. Edges are
130
+ then randomly rewired with probability `p` to link different cliques.
131
+
132
+ Parameters
133
+ ----------
134
+ l : int
135
+ Number of groups
136
+ k : int
137
+ Size of cliques
138
+ p : float
139
+ Probability of rewiring each edge.
140
+ seed : integer, random_state, or None (default)
141
+ Indicator of random number generation state.
142
+ See :ref:`Randomness<randomness>`.
143
+
144
+ Returns
145
+ -------
146
+ G : NetworkX Graph
147
+ Relaxed Caveman Graph
148
+
149
+ Raises
150
+ ------
151
+ NetworkXError
152
+ If p is not in [0,1]
153
+
154
+ Examples
155
+ --------
156
+ >>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42)
157
+
158
+ References
159
+ ----------
160
+ .. [1] Santo Fortunato, Community Detection in Graphs,
161
+ Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174.
162
+ https://arxiv.org/abs/0906.0612
163
+ """
164
+ G = nx.caveman_graph(l, k)
165
+ nodes = list(G)
166
+ for u, v in G.edges():
167
+ if seed.random() < p: # rewire the edge
168
+ x = seed.choice(nodes)
169
+ if G.has_edge(u, x):
170
+ continue
171
+ G.remove_edge(u, v)
172
+ G.add_edge(u, x)
173
+ return G
174
+
175
+
176
+ @py_random_state(3)
177
+ @nx._dispatchable(graphs=None, returns_graph=True)
178
+ def random_partition_graph(sizes, p_in, p_out, seed=None, directed=False):
179
+ """Returns the random partition graph with a partition of sizes.
180
+
181
+ A partition graph is a graph of communities with sizes defined by
182
+ s in sizes. Nodes in the same group are connected with probability
183
+ p_in and nodes of different groups are connected with probability
184
+ p_out.
185
+
186
+ Parameters
187
+ ----------
188
+ sizes : list of ints
189
+ Sizes of groups
190
+ p_in : float
191
+ probability of edges with in groups
192
+ p_out : float
193
+ probability of edges between groups
194
+ directed : boolean optional, default=False
195
+ Whether to create a directed graph
196
+ seed : integer, random_state, or None (default)
197
+ Indicator of random number generation state.
198
+ See :ref:`Randomness<randomness>`.
199
+
200
+ Returns
201
+ -------
202
+ G : NetworkX Graph or DiGraph
203
+ random partition graph of size sum(gs)
204
+
205
+ Raises
206
+ ------
207
+ NetworkXError
208
+ If p_in or p_out is not in [0,1]
209
+
210
+ Examples
211
+ --------
212
+ >>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
213
+ >>> len(G)
214
+ 30
215
+ >>> partition = G.graph["partition"]
216
+ >>> len(partition)
217
+ 3
218
+
219
+ Notes
220
+ -----
221
+ This is a generalization of the planted-l-partition described in
222
+ [1]_. It allows for the creation of groups of any size.
223
+
224
+ The partition is store as a graph attribute 'partition'.
225
+
226
+ References
227
+ ----------
228
+ .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
229
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
230
+ """
231
+ # Use geometric method for O(n+m) complexity algorithm
232
+ # partition = nx.community_sets(nx.get_node_attributes(G, 'affiliation'))
233
+ if not 0.0 <= p_in <= 1.0:
234
+ raise nx.NetworkXError("p_in must be in [0,1]")
235
+ if not 0.0 <= p_out <= 1.0:
236
+ raise nx.NetworkXError("p_out must be in [0,1]")
237
+
238
+ # create connection matrix
239
+ num_blocks = len(sizes)
240
+ p = [[p_out for s in range(num_blocks)] for r in range(num_blocks)]
241
+ for r in range(num_blocks):
242
+ p[r][r] = p_in
243
+
244
+ return stochastic_block_model(
245
+ sizes,
246
+ p,
247
+ nodelist=None,
248
+ seed=seed,
249
+ directed=directed,
250
+ selfloops=False,
251
+ sparse=True,
252
+ )
253
+
254
+
255
+ @py_random_state(4)
256
+ @nx._dispatchable(graphs=None, returns_graph=True)
257
+ def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
258
+ """Returns the planted l-partition graph.
259
+
260
+ This model partitions a graph with n=l*k vertices in
261
+ l groups with k vertices each. Vertices of the same
262
+ group are linked with a probability p_in, and vertices
263
+ of different groups are linked with probability p_out.
264
+
265
+ Parameters
266
+ ----------
267
+ l : int
268
+ Number of groups
269
+ k : int
270
+ Number of vertices in each group
271
+ p_in : float
272
+ probability of connecting vertices within a group
273
+ p_out : float
274
+ probability of connected vertices between groups
275
+ seed : integer, random_state, or None (default)
276
+ Indicator of random number generation state.
277
+ See :ref:`Randomness<randomness>`.
278
+ directed : bool,optional (default=False)
279
+ If True return a directed graph
280
+
281
+ Returns
282
+ -------
283
+ G : NetworkX Graph or DiGraph
284
+ planted l-partition graph
285
+
286
+ Raises
287
+ ------
288
+ NetworkXError
289
+ If `p_in`, `p_out` are not in `[0, 1]`
290
+
291
+ Examples
292
+ --------
293
+ >>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)
294
+
295
+ See Also
296
+ --------
297
+ random_partition_model
298
+
299
+ References
300
+ ----------
301
+ .. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
302
+ on the planted partition model,
303
+ Random Struct. Algor. 18 (2001) 116-140.
304
+
305
+ .. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
306
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
307
+ """
308
+ return random_partition_graph([k] * l, p_in, p_out, seed=seed, directed=directed)
309
+
310
+
311
+ @py_random_state(6)
312
+ @nx._dispatchable(graphs=None, returns_graph=True)
313
+ def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
314
+ """Generate a Gaussian random partition graph.
315
+
316
+ A Gaussian random partition graph is created by creating k partitions
317
+ each with a size drawn from a normal distribution with mean s and variance
318
+ s/v. Nodes are connected within clusters with probability p_in and
319
+ between clusters with probability p_out[1]
320
+
321
+ Parameters
322
+ ----------
323
+ n : int
324
+ Number of nodes in the graph
325
+ s : float
326
+ Mean cluster size
327
+ v : float
328
+ Shape parameter. The variance of cluster size distribution is s/v.
329
+ p_in : float
330
+ Probability of intra cluster connection.
331
+ p_out : float
332
+ Probability of inter cluster connection.
333
+ directed : boolean, optional default=False
334
+ Whether to create a directed graph or not
335
+ seed : integer, random_state, or None (default)
336
+ Indicator of random number generation state.
337
+ See :ref:`Randomness<randomness>`.
338
+
339
+ Returns
340
+ -------
341
+ G : NetworkX Graph or DiGraph
342
+ gaussian random partition graph
343
+
344
+ Raises
345
+ ------
346
+ NetworkXError
347
+ If s is > n
348
+ If p_in or p_out is not in [0,1]
349
+
350
+ Notes
351
+ -----
352
+ Note the number of partitions is dependent on s,v and n, and that the
353
+ last partition may be considerably smaller, as it is sized to simply
354
+ fill out the nodes [1]
355
+
356
+ See Also
357
+ --------
358
+ random_partition_graph
359
+
360
+ Examples
361
+ --------
362
+ >>> G = nx.gaussian_random_partition_graph(100, 10, 10, 0.25, 0.1)
363
+ >>> len(G)
364
+ 100
365
+
366
+ References
367
+ ----------
368
+ .. [1] Ulrik Brandes, Marco Gaertler, Dorothea Wagner,
369
+ Experiments on Graph Clustering Algorithms,
370
+ In the proceedings of the 11th Europ. Symp. Algorithms, 2003.
371
+ """
372
+ if s > n:
373
+ raise nx.NetworkXError("s must be <= n")
374
+ assigned = 0
375
+ sizes = []
376
+ while True:
377
+ size = int(seed.gauss(s, s / v + 0.5))
378
+ if size < 1: # how to handle 0 or negative sizes?
379
+ continue
380
+ if assigned + size >= n:
381
+ sizes.append(n - assigned)
382
+ break
383
+ assigned += size
384
+ sizes.append(size)
385
+ return random_partition_graph(sizes, p_in, p_out, seed=seed, directed=directed)
386
+
387
+
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def ring_of_cliques(num_cliques, clique_size):
390
+ """Defines a "ring of cliques" graph.
391
+
392
+ A ring of cliques graph is consisting of cliques, connected through single
393
+ links. Each clique is a complete graph.
394
+
395
+ Parameters
396
+ ----------
397
+ num_cliques : int
398
+ Number of cliques
399
+ clique_size : int
400
+ Size of cliques
401
+
402
+ Returns
403
+ -------
404
+ G : NetworkX Graph
405
+ ring of cliques graph
406
+
407
+ Raises
408
+ ------
409
+ NetworkXError
410
+ If the number of cliques is lower than 2 or
411
+ if the size of cliques is smaller than 2.
412
+
413
+ Examples
414
+ --------
415
+ >>> G = nx.ring_of_cliques(8, 4)
416
+
417
+ See Also
418
+ --------
419
+ connected_caveman_graph
420
+
421
+ Notes
422
+ -----
423
+ The `connected_caveman_graph` graph removes a link from each clique to
424
+ connect it with the next clique. Instead, the `ring_of_cliques` graph
425
+ simply adds the link without removing any link from the cliques.
426
+ """
427
+ if num_cliques < 2:
428
+ raise nx.NetworkXError("A ring of cliques must have at least two cliques")
429
+ if clique_size < 2:
430
+ raise nx.NetworkXError("The cliques must have at least two nodes")
431
+
432
+ G = nx.Graph()
433
+ for i in range(num_cliques):
434
+ edges = itertools.combinations(
435
+ range(i * clique_size, i * clique_size + clique_size), 2
436
+ )
437
+ G.add_edges_from(edges)
438
+ G.add_edge(
439
+ i * clique_size + 1, (i + 1) * clique_size % (num_cliques * clique_size)
440
+ )
441
+ return G
442
+
443
+
444
+ @nx._dispatchable(graphs=None, returns_graph=True)
445
+ def windmill_graph(n, k):
446
+ """Generate a windmill graph.
447
+ A windmill graph is a graph of `n` cliques each of size `k` that are all
448
+ joined at one node.
449
+ It can be thought of as taking a disjoint union of `n` cliques of size `k`,
450
+ selecting one point from each, and contracting all of the selected points.
451
+ Alternatively, one could generate `n` cliques of size `k-1` and one node
452
+ that is connected to all other nodes in the graph.
453
+
454
+ Parameters
455
+ ----------
456
+ n : int
457
+ Number of cliques
458
+ k : int
459
+ Size of cliques
460
+
461
+ Returns
462
+ -------
463
+ G : NetworkX Graph
464
+ windmill graph with n cliques of size k
465
+
466
+ Raises
467
+ ------
468
+ NetworkXError
469
+ If the number of cliques is less than two
470
+ If the size of the cliques are less than two
471
+
472
+ Examples
473
+ --------
474
+ >>> G = nx.windmill_graph(4, 5)
475
+
476
+ Notes
477
+ -----
478
+ The node labeled `0` will be the node connected to all other nodes.
479
+ Note that windmill graphs are usually denoted `Wd(k,n)`, so the parameters
480
+ are in the opposite order as the parameters of this method.
481
+ """
482
+ if n < 2:
483
+ msg = "A windmill graph must have at least two cliques"
484
+ raise nx.NetworkXError(msg)
485
+ if k < 2:
486
+ raise nx.NetworkXError("The cliques must have at least two nodes")
487
+
488
+ G = nx.disjoint_union_all(
489
+ itertools.chain(
490
+ [nx.complete_graph(k)], (nx.complete_graph(k - 1) for _ in range(n - 1))
491
+ )
492
+ )
493
+ G.add_edges_from((0, i) for i in range(k, G.number_of_nodes()))
494
+ return G
495
+
496
+
497
+ @py_random_state(3)
498
+ @nx._dispatchable(graphs=None, returns_graph=True)
499
+ def stochastic_block_model(
500
+ sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True
501
+ ):
502
+ """Returns a stochastic block model graph.
503
+
504
+ This model partitions the nodes in blocks of arbitrary sizes, and places
505
+ edges between pairs of nodes independently, with a probability that depends
506
+ on the blocks.
507
+
508
+ Parameters
509
+ ----------
510
+ sizes : list of ints
511
+ Sizes of blocks
512
+ p : list of list of floats
513
+ Element (r,s) gives the density of edges going from the nodes
514
+ of group r to nodes of group s.
515
+ p must match the number of groups (len(sizes) == len(p)),
516
+ and it must be symmetric if the graph is undirected.
517
+ nodelist : list, optional
518
+ The block tags are assigned according to the node identifiers
519
+ in nodelist. If nodelist is None, then the ordering is the
520
+ range [0,sum(sizes)-1].
521
+ seed : integer, random_state, or None (default)
522
+ Indicator of random number generation state.
523
+ See :ref:`Randomness<randomness>`.
524
+ directed : boolean optional, default=False
525
+ Whether to create a directed graph or not.
526
+ selfloops : boolean optional, default=False
527
+ Whether to include self-loops or not.
528
+ sparse: boolean optional, default=True
529
+ Use the sparse heuristic to speed up the generator.
530
+
531
+ Returns
532
+ -------
533
+ g : NetworkX Graph or DiGraph
534
+ Stochastic block model graph of size sum(sizes)
535
+
536
+ Raises
537
+ ------
538
+ NetworkXError
539
+ If probabilities are not in [0,1].
540
+ If the probability matrix is not square (directed case).
541
+ If the probability matrix is not symmetric (undirected case).
542
+ If the sizes list does not match nodelist or the probability matrix.
543
+ If nodelist contains duplicate.
544
+
545
+ Examples
546
+ --------
547
+ >>> sizes = [75, 75, 300]
548
+ >>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
549
+ >>> g = nx.stochastic_block_model(sizes, probs, seed=0)
550
+ >>> len(g)
551
+ 450
552
+ >>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True)
553
+ >>> for v in H.nodes(data=True):
554
+ ... print(round(v[1]["density"], 3))
555
+ 0.245
556
+ 0.348
557
+ 0.405
558
+ >>> for v in H.edges(data=True):
559
+ ... print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3))
560
+ 0.051
561
+ 0.022
562
+ 0.07
563
+
564
+ See Also
565
+ --------
566
+ random_partition_graph
567
+ planted_partition_graph
568
+ gaussian_random_partition_graph
569
+ gnp_random_graph
570
+
571
+ References
572
+ ----------
573
+ .. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S.,
574
+ "Stochastic blockmodels: First steps",
575
+ Social networks, 5(2), 109-137, 1983.
576
+ """
577
+ # Check if dimensions match
578
+ if len(sizes) != len(p):
579
+ raise nx.NetworkXException("'sizes' and 'p' do not match.")
580
+ # Check for probability symmetry (undirected) and shape (directed)
581
+ for row in p:
582
+ if len(p) != len(row):
583
+ raise nx.NetworkXException("'p' must be a square matrix.")
584
+ if not directed:
585
+ p_transpose = [list(i) for i in zip(*p)]
586
+ for i in zip(p, p_transpose):
587
+ for j in zip(i[0], i[1]):
588
+ if abs(j[0] - j[1]) > 1e-08:
589
+ raise nx.NetworkXException("'p' must be symmetric.")
590
+ # Check for probability range
591
+ for row in p:
592
+ for prob in row:
593
+ if prob < 0 or prob > 1:
594
+ raise nx.NetworkXException("Entries of 'p' not in [0,1].")
595
+ # Check for nodelist consistency
596
+ if nodelist is not None:
597
+ if len(nodelist) != sum(sizes):
598
+ raise nx.NetworkXException("'nodelist' and 'sizes' do not match.")
599
+ if len(nodelist) != len(set(nodelist)):
600
+ raise nx.NetworkXException("nodelist contains duplicate.")
601
+ else:
602
+ nodelist = range(sum(sizes))
603
+
604
+ # Setup the graph conditionally to the directed switch.
605
+ block_range = range(len(sizes))
606
+ if directed:
607
+ g = nx.DiGraph()
608
+ block_iter = itertools.product(block_range, block_range)
609
+ else:
610
+ g = nx.Graph()
611
+ block_iter = itertools.combinations_with_replacement(block_range, 2)
612
+ # Split nodelist in a partition (list of sets).
613
+ size_cumsum = [sum(sizes[0:x]) for x in range(len(sizes) + 1)]
614
+ g.graph["partition"] = [
615
+ set(nodelist[size_cumsum[x] : size_cumsum[x + 1]])
616
+ for x in range(len(size_cumsum) - 1)
617
+ ]
618
+ # Setup nodes and graph name
619
+ for block_id, nodes in enumerate(g.graph["partition"]):
620
+ for node in nodes:
621
+ g.add_node(node, block=block_id)
622
+
623
+ g.name = "stochastic_block_model"
624
+
625
+ # Test for edge existence
626
+ parts = g.graph["partition"]
627
+ for i, j in block_iter:
628
+ if i == j:
629
+ if directed:
630
+ if selfloops:
631
+ edges = itertools.product(parts[i], parts[i])
632
+ else:
633
+ edges = itertools.permutations(parts[i], 2)
634
+ else:
635
+ edges = itertools.combinations(parts[i], 2)
636
+ if selfloops:
637
+ edges = itertools.chain(edges, zip(parts[i], parts[i]))
638
+ for e in edges:
639
+ if seed.random() < p[i][j]:
640
+ g.add_edge(*e)
641
+ else:
642
+ edges = itertools.product(parts[i], parts[j])
643
+ if sparse:
644
+ if p[i][j] == 1: # Test edges cases p_ij = 0 or 1
645
+ for e in edges:
646
+ g.add_edge(*e)
647
+ elif p[i][j] > 0:
648
+ while True:
649
+ try:
650
+ logrand = math.log(seed.random())
651
+ skip = math.floor(logrand / math.log(1 - p[i][j]))
652
+ # consume "skip" edges
653
+ next(itertools.islice(edges, skip, skip), None)
654
+ e = next(edges)
655
+ g.add_edge(*e) # __safe
656
+ except StopIteration:
657
+ break
658
+ else:
659
+ for e in edges:
660
+ if seed.random() < p[i][j]:
661
+ g.add_edge(*e) # __safe
662
+ return g
663
+
664
+
665
+ def _zipf_rv_below(gamma, xmin, threshold, seed):
666
+ """Returns a random value chosen from the bounded Zipf distribution.
667
+
668
+ Repeatedly draws values from the Zipf distribution until the
669
+ threshold is met, then returns that value.
670
+ """
671
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
672
+ while result > threshold:
673
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
674
+ return result
675
+
676
+
677
+ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters, seed):
678
+ """Returns a list of numbers obeying a constrained power law distribution.
679
+
680
+ ``gamma`` and ``low`` are the parameters for the Zipf distribution.
681
+
682
+ ``high`` is the maximum allowed value for values draw from the Zipf
683
+ distribution. For more information, see :func:`_zipf_rv_below`.
684
+
685
+ ``condition`` and ``length`` are Boolean-valued functions on
686
+ lists. While generating the list, random values are drawn and
687
+ appended to the list until ``length`` is satisfied by the created
688
+ list. Once ``condition`` is satisfied, the sequence generated in
689
+ this way is returned.
690
+
691
+ ``max_iters`` indicates the number of times to generate a list
692
+ satisfying ``length``. If the number of iterations exceeds this
693
+ value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.
694
+
695
+ seed : integer, random_state, or None (default)
696
+ Indicator of random number generation state.
697
+ See :ref:`Randomness<randomness>`.
698
+ """
699
+ for i in range(max_iters):
700
+ seq = []
701
+ while not length(seq):
702
+ seq.append(_zipf_rv_below(gamma, low, high, seed))
703
+ if condition(seq):
704
+ return seq
705
+ raise nx.ExceededMaxIterations("Could not create power law sequence")
706
+
707
+
708
+ def _hurwitz_zeta(x, q, tolerance):
709
+ """The Hurwitz zeta function, or the Riemann zeta function of two arguments.
710
+
711
+ ``x`` must be greater than one and ``q`` must be positive.
712
+
713
+ This function repeatedly computes subsequent partial sums until
714
+ convergence, as decided by ``tolerance``.
715
+ """
716
+ z = 0
717
+ z_prev = -float("inf")
718
+ k = 0
719
+ while abs(z - z_prev) > tolerance:
720
+ z_prev = z
721
+ z += 1 / ((k + q) ** x)
722
+ k += 1
723
+ return z
724
+
725
+
726
+ def _generate_min_degree(gamma, average_degree, max_degree, tolerance, max_iters):
727
+ """Returns a minimum degree from the given average degree."""
728
+ # Defines zeta function whether or not Scipy is available
729
+ try:
730
+ from scipy.special import zeta
731
+ except ImportError:
732
+
733
+ def zeta(x, q):
734
+ return _hurwitz_zeta(x, q, tolerance)
735
+
736
+ min_deg_top = max_degree
737
+ min_deg_bot = 1
738
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
739
+ itrs = 0
740
+ mid_avg_deg = 0
741
+ while abs(mid_avg_deg - average_degree) > tolerance:
742
+ if itrs > max_iters:
743
+ raise nx.ExceededMaxIterations("Could not match average_degree")
744
+ mid_avg_deg = 0
745
+ for x in range(int(min_deg_mid), max_degree + 1):
746
+ mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid)
747
+ if mid_avg_deg > average_degree:
748
+ min_deg_top = min_deg_mid
749
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
750
+ else:
751
+ min_deg_bot = min_deg_mid
752
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
753
+ itrs += 1
754
+ # return int(min_deg_mid + 0.5)
755
+ return round(min_deg_mid)
756
+
757
+
758
+ def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed):
759
+ """Returns a list of sets, each of which represents a community.
760
+
761
+ ``degree_seq`` is the degree sequence that must be met by the
762
+ graph.
763
+
764
+ ``community_sizes`` is the community size distribution that must be
765
+ met by the generated list of sets.
766
+
767
+ ``mu`` is a float in the interval [0, 1] indicating the fraction of
768
+ intra-community edges incident to each node.
769
+
770
+ ``max_iters`` is the number of times to try to add a node to a
771
+ community. This must be greater than the length of
772
+ ``degree_seq``, otherwise this function will always fail. If
773
+ the number of iterations exceeds this value,
774
+ :exc:`~networkx.exception.ExceededMaxIterations` is raised.
775
+
776
+ seed : integer, random_state, or None (default)
777
+ Indicator of random number generation state.
778
+ See :ref:`Randomness<randomness>`.
779
+
780
+ The communities returned by this are sets of integers in the set {0,
781
+ ..., *n* - 1}, where *n* is the length of ``degree_seq``.
782
+
783
+ """
784
+ # This assumes the nodes in the graph will be natural numbers.
785
+ result = [set() for _ in community_sizes]
786
+ n = len(degree_seq)
787
+ free = list(range(n))
788
+ for i in range(max_iters):
789
+ v = free.pop()
790
+ c = seed.choice(range(len(community_sizes)))
791
+ # s = int(degree_seq[v] * (1 - mu) + 0.5)
792
+ s = round(degree_seq[v] * (1 - mu))
793
+ # If the community is large enough, add the node to the chosen
794
+ # community. Otherwise, return it to the list of unaffiliated
795
+ # nodes.
796
+ if s < community_sizes[c]:
797
+ result[c].add(v)
798
+ else:
799
+ free.append(v)
800
+ # If the community is too big, remove a node from it.
801
+ if len(result[c]) > community_sizes[c]:
802
+ free.append(result[c].pop())
803
+ if not free:
804
+ return result
805
+ msg = "Could not assign communities; try increasing min_community"
806
+ raise nx.ExceededMaxIterations(msg)
807
+
808
+
809
+ @py_random_state(11)
810
+ @nx._dispatchable(graphs=None, returns_graph=True)
811
+ def LFR_benchmark_graph(
812
+ n,
813
+ tau1,
814
+ tau2,
815
+ mu,
816
+ average_degree=None,
817
+ min_degree=None,
818
+ max_degree=None,
819
+ min_community=None,
820
+ max_community=None,
821
+ tol=1.0e-7,
822
+ max_iters=500,
823
+ seed=None,
824
+ ):
825
+ r"""Returns the LFR benchmark graph.
826
+
827
+ This algorithm proceeds as follows:
828
+
829
+ 1) Find a degree sequence with a power law distribution, and minimum
830
+ value ``min_degree``, which has approximate average degree
831
+ ``average_degree``. This is accomplished by either
832
+
833
+ a) specifying ``min_degree`` and not ``average_degree``,
834
+ b) specifying ``average_degree`` and not ``min_degree``, in which
835
+ case a suitable minimum degree will be found.
836
+
837
+ ``max_degree`` can also be specified, otherwise it will be set to
838
+ ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
839
+ joining it to nodes in communities other than its own and $(1 -
840
+ \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
841
+ community.
842
+ 2) Generate community sizes according to a power law distribution
843
+ with exponent ``tau2``. If ``min_community`` and
844
+ ``max_community`` are not specified they will be selected to be
845
+ ``min_degree`` and ``max_degree``, respectively. Community sizes
846
+ are generated until the sum of their sizes equals ``n``.
847
+ 3) Each node will be randomly assigned a community with the
848
+ condition that the community is large enough for the node's
849
+ intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
850
+ described in step 2. If a community grows too large, a random node
851
+ will be selected for reassignment to a new community, until all
852
+ nodes have been assigned a community.
853
+ 4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
854
+ intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
855
+ edges.
856
+
857
+ Parameters
858
+ ----------
859
+ n : int
860
+ Number of nodes in the created graph.
861
+
862
+ tau1 : float
863
+ Power law exponent for the degree distribution of the created
864
+ graph. This value must be strictly greater than one.
865
+
866
+ tau2 : float
867
+ Power law exponent for the community size distribution in the
868
+ created graph. This value must be strictly greater than one.
869
+
870
+ mu : float
871
+ Fraction of inter-community edges incident to each node. This
872
+ value must be in the interval [0, 1].
873
+
874
+ average_degree : float
875
+ Desired average degree of nodes in the created graph. This value
876
+ must be in the interval [0, *n*]. Exactly one of this and
877
+ ``min_degree`` must be specified, otherwise a
878
+ :exc:`NetworkXError` is raised.
879
+
880
+ min_degree : int
881
+ Minimum degree of nodes in the created graph. This value must be
882
+ in the interval [0, *n*]. Exactly one of this and
883
+ ``average_degree`` must be specified, otherwise a
884
+ :exc:`NetworkXError` is raised.
885
+
886
+ max_degree : int
887
+ Maximum degree of nodes in the created graph. If not specified,
888
+ this is set to ``n``, the total number of nodes in the graph.
889
+
890
+ min_community : int
891
+ Minimum size of communities in the graph. If not specified, this
892
+ is set to ``min_degree``.
893
+
894
+ max_community : int
895
+ Maximum size of communities in the graph. If not specified, this
896
+ is set to ``n``, the total number of nodes in the graph.
897
+
898
+ tol : float
899
+ Tolerance when comparing floats, specifically when comparing
900
+ average degree values.
901
+
902
+ max_iters : int
903
+ Maximum number of iterations to try to create the community sizes,
904
+ degree distribution, and community affiliations.
905
+
906
+ seed : integer, random_state, or None (default)
907
+ Indicator of random number generation state.
908
+ See :ref:`Randomness<randomness>`.
909
+
910
+ Returns
911
+ -------
912
+ G : NetworkX graph
913
+ The LFR benchmark graph generated according to the specified
914
+ parameters.
915
+
916
+ Each node in the graph has a node attribute ``'community'`` that
917
+ stores the community (that is, the set of nodes) that includes
918
+ it.
919
+
920
+ Raises
921
+ ------
922
+ NetworkXError
923
+ If any of the parameters do not meet their upper and lower bounds:
924
+
925
+ - ``tau1`` and ``tau2`` must be strictly greater than 1.
926
+ - ``mu`` must be in [0, 1].
927
+ - ``max_degree`` must be in {1, ..., *n*}.
928
+ - ``min_community`` and ``max_community`` must be in {0, ...,
929
+ *n*}.
930
+
931
+ If not exactly one of ``average_degree`` and ``min_degree`` is
932
+ specified.
933
+
934
+ If ``min_degree`` is not specified and a suitable ``min_degree``
935
+ cannot be found.
936
+
937
+ ExceededMaxIterations
938
+ If a valid degree sequence cannot be created within
939
+ ``max_iters`` number of iterations.
940
+
941
+ If a valid set of community sizes cannot be created within
942
+ ``max_iters`` number of iterations.
943
+
944
+ If a valid community assignment cannot be created within ``10 *
945
+ n * max_iters`` number of iterations.
946
+
947
+ Examples
948
+ --------
949
+ Basic usage::
950
+
951
+ >>> from networkx.generators.community import LFR_benchmark_graph
952
+ >>> n = 250
953
+ >>> tau1 = 3
954
+ >>> tau2 = 1.5
955
+ >>> mu = 0.1
956
+ >>> G = LFR_benchmark_graph(
957
+ ... n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
958
+ ... )
959
+
960
+ Continuing the example above, you can get the communities from the
961
+ node attributes of the graph::
962
+
963
+ >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}
964
+
965
+ Notes
966
+ -----
967
+ This algorithm differs slightly from the original way it was
968
+ presented in [1].
969
+
970
+ 1) Rather than connecting the graph via a configuration model then
971
+ rewiring to match the intra-community and inter-community
972
+ degrees, we do this wiring explicitly at the end, which should be
973
+ equivalent.
974
+ 2) The code posted on the author's website [2] calculates the random
975
+ power law distributed variables and their average using
976
+ continuous approximations, whereas we use the discrete
977
+ distributions here as both degree and community size are
978
+ discrete.
979
+
980
+ Though the authors describe the algorithm as quite robust, testing
981
+ during development indicates that a somewhat narrower parameter set
982
+ is likely to successfully produce a graph. Some suggestions have
983
+ been provided in the event of exceptions.
984
+
985
+ References
986
+ ----------
987
+ .. [1] "Benchmark graphs for testing community detection algorithms",
988
+ Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
989
+ Phys. Rev. E 78, 046110 2008
990
+ .. [2] https://www.santofortunato.net/resources
991
+
992
+ """
993
+ # Perform some basic parameter validation.
994
+ if not tau1 > 1:
995
+ raise nx.NetworkXError("tau1 must be greater than one")
996
+ if not tau2 > 1:
997
+ raise nx.NetworkXError("tau2 must be greater than one")
998
+ if not 0 <= mu <= 1:
999
+ raise nx.NetworkXError("mu must be in the interval [0, 1]")
1000
+
1001
+ # Validate parameters for generating the degree sequence.
1002
+ if max_degree is None:
1003
+ max_degree = n
1004
+ elif not 0 < max_degree <= n:
1005
+ raise nx.NetworkXError("max_degree must be in the interval (0, n]")
1006
+ if not ((min_degree is None) ^ (average_degree is None)):
1007
+ raise nx.NetworkXError(
1008
+ "Must assign exactly one of min_degree and average_degree"
1009
+ )
1010
+ if min_degree is None:
1011
+ min_degree = _generate_min_degree(
1012
+ tau1, average_degree, max_degree, tol, max_iters
1013
+ )
1014
+
1015
+ # Generate a degree sequence with a power law distribution.
1016
+ low, high = min_degree, max_degree
1017
+
1018
+ def condition(seq):
1019
+ return sum(seq) % 2 == 0
1020
+
1021
+ def length(seq):
1022
+ return len(seq) >= n
1023
+
1024
+ deg_seq = _powerlaw_sequence(tau1, low, high, condition, length, max_iters, seed)
1025
+
1026
+ # Validate parameters for generating the community size sequence.
1027
+ if min_community is None:
1028
+ min_community = min(deg_seq)
1029
+ if max_community is None:
1030
+ max_community = max(deg_seq)
1031
+
1032
+ # Generate a community size sequence with a power law distribution.
1033
+ #
1034
+ # TODO The original code incremented the number of iterations each
1035
+ # time a new Zipf random value was drawn from the distribution. This
1036
+ # differed from the way the number of iterations was incremented in
1037
+ # `_powerlaw_degree_sequence`, so this code was changed to match
1038
+ # that one. As a result, this code is allowed many more chances to
1039
+ # generate a valid community size sequence.
1040
+ low, high = min_community, max_community
1041
+
1042
+ def condition(seq):
1043
+ return sum(seq) == n
1044
+
1045
+ def length(seq):
1046
+ return sum(seq) >= n
1047
+
1048
+ comms = _powerlaw_sequence(tau2, low, high, condition, length, max_iters, seed)
1049
+
1050
+ # Generate the communities based on the given degree sequence and
1051
+ # community sizes.
1052
+ max_iters *= 10 * n
1053
+ communities = _generate_communities(deg_seq, comms, mu, max_iters, seed)
1054
+
1055
+ # Finally, generate the benchmark graph based on the given
1056
+ # communities, joining nodes according to the intra- and
1057
+ # inter-community degrees.
1058
+ G = nx.Graph()
1059
+ G.add_nodes_from(range(n))
1060
+ for c in communities:
1061
+ for u in c:
1062
+ while G.degree(u) < round(deg_seq[u] * (1 - mu)):
1063
+ v = seed.choice(list(c))
1064
+ G.add_edge(u, v)
1065
+ while G.degree(u) < deg_seq[u]:
1066
+ v = seed.choice(range(n))
1067
+ if v not in c:
1068
+ G.add_edge(u, v)
1069
+ G.nodes[u]["community"] = c
1070
+ return G
wemm/lib/python3.10/site-packages/networkx/generators/directed.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for some directed graphs, including growing network (GN) graphs and
3
+ scale-free graphs.
4
+
5
+ """
6
+
7
+ import numbers
8
+ from collections import Counter
9
+
10
+ import networkx as nx
11
+ from networkx.generators.classic import empty_graph
12
+ from networkx.utils import discrete_sequence, py_random_state, weighted_choice
13
+
14
+ __all__ = [
15
+ "gn_graph",
16
+ "gnc_graph",
17
+ "gnr_graph",
18
+ "random_k_out_graph",
19
+ "scale_free_graph",
20
+ ]
21
+
22
+
23
+ @py_random_state(3)
24
+ @nx._dispatchable(graphs=None, returns_graph=True)
25
+ def gn_graph(n, kernel=None, create_using=None, seed=None):
26
+ """Returns the growing network (GN) digraph with `n` nodes.
27
+
28
+ The GN graph is built by adding nodes one at a time with a link to one
29
+ previously added node. The target node for the link is chosen with
30
+ probability based on degree. The default attachment kernel is a linear
31
+ function of the degree of a node.
32
+
33
+ The graph is always a (directed) tree.
34
+
35
+ Parameters
36
+ ----------
37
+ n : int
38
+ The number of nodes for the generated graph.
39
+ kernel : function
40
+ The attachment kernel.
41
+ create_using : NetworkX graph constructor, optional (default DiGraph)
42
+ Graph type to create. If graph instance, then cleared before populated.
43
+ seed : integer, random_state, or None (default)
44
+ Indicator of random number generation state.
45
+ See :ref:`Randomness<randomness>`.
46
+
47
+ Examples
48
+ --------
49
+ To create the undirected GN graph, use the :meth:`~DiGraph.to_directed`
50
+ method::
51
+
52
+ >>> D = nx.gn_graph(10) # the GN graph
53
+ >>> G = D.to_undirected() # the undirected version
54
+
55
+ To specify an attachment kernel, use the `kernel` keyword argument::
56
+
57
+ >>> D = nx.gn_graph(10, kernel=lambda x: x**1.5) # A_k = k^1.5
58
+
59
+ References
60
+ ----------
61
+ .. [1] P. L. Krapivsky and S. Redner,
62
+ Organization of Growing Random Networks,
63
+ Phys. Rev. E, 63, 066123, 2001.
64
+ """
65
+ G = empty_graph(1, create_using, default=nx.DiGraph)
66
+ if not G.is_directed():
67
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
68
+
69
+ if kernel is None:
70
+
71
+ def kernel(x):
72
+ return x
73
+
74
+ if n == 1:
75
+ return G
76
+
77
+ G.add_edge(1, 0) # get started
78
+ ds = [1, 1] # degree sequence
79
+
80
+ for source in range(2, n):
81
+ # compute distribution from kernel and degree
82
+ dist = [kernel(d) for d in ds]
83
+ # choose target from discrete distribution
84
+ target = discrete_sequence(1, distribution=dist, seed=seed)[0]
85
+ G.add_edge(source, target)
86
+ ds.append(1) # the source has only one link (degree one)
87
+ ds[target] += 1 # add one to the target link degree
88
+ return G
89
+
90
+
91
+ @py_random_state(3)
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def gnr_graph(n, p, create_using=None, seed=None):
94
+ """Returns the growing network with redirection (GNR) digraph with `n`
95
+ nodes and redirection probability `p`.
96
+
97
+ The GNR graph is built by adding nodes one at a time with a link to one
98
+ previously added node. The previous target node is chosen uniformly at
99
+ random. With probability `p` the link is instead "redirected" to the
100
+ successor node of the target.
101
+
102
+ The graph is always a (directed) tree.
103
+
104
+ Parameters
105
+ ----------
106
+ n : int
107
+ The number of nodes for the generated graph.
108
+ p : float
109
+ The redirection probability.
110
+ create_using : NetworkX graph constructor, optional (default DiGraph)
111
+ Graph type to create. If graph instance, then cleared before populated.
112
+ seed : integer, random_state, or None (default)
113
+ Indicator of random number generation state.
114
+ See :ref:`Randomness<randomness>`.
115
+
116
+ Examples
117
+ --------
118
+ To create the undirected GNR graph, use the :meth:`~DiGraph.to_directed`
119
+ method::
120
+
121
+ >>> D = nx.gnr_graph(10, 0.5) # the GNR graph
122
+ >>> G = D.to_undirected() # the undirected version
123
+
124
+ References
125
+ ----------
126
+ .. [1] P. L. Krapivsky and S. Redner,
127
+ Organization of Growing Random Networks,
128
+ Phys. Rev. E, 63, 066123, 2001.
129
+ """
130
+ G = empty_graph(1, create_using, default=nx.DiGraph)
131
+ if not G.is_directed():
132
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
133
+
134
+ if n == 1:
135
+ return G
136
+
137
+ for source in range(1, n):
138
+ target = seed.randrange(0, source)
139
+ if seed.random() < p and target != 0:
140
+ target = next(G.successors(target))
141
+ G.add_edge(source, target)
142
+ return G
143
+
144
+
145
+ @py_random_state(2)
146
+ @nx._dispatchable(graphs=None, returns_graph=True)
147
+ def gnc_graph(n, create_using=None, seed=None):
148
+ """Returns the growing network with copying (GNC) digraph with `n` nodes.
149
+
150
+ The GNC graph is built by adding nodes one at a time with a link to one
151
+ previously added node (chosen uniformly at random) and to all of that
152
+ node's successors.
153
+
154
+ Parameters
155
+ ----------
156
+ n : int
157
+ The number of nodes for the generated graph.
158
+ create_using : NetworkX graph constructor, optional (default DiGraph)
159
+ Graph type to create. If graph instance, then cleared before populated.
160
+ seed : integer, random_state, or None (default)
161
+ Indicator of random number generation state.
162
+ See :ref:`Randomness<randomness>`.
163
+
164
+ References
165
+ ----------
166
+ .. [1] P. L. Krapivsky and S. Redner,
167
+ Network Growth by Copying,
168
+ Phys. Rev. E, 71, 036118, 2005k.},
169
+ """
170
+ G = empty_graph(1, create_using, default=nx.DiGraph)
171
+ if not G.is_directed():
172
+ raise nx.NetworkXError("create_using must indicate a Directed Graph")
173
+
174
+ if n == 1:
175
+ return G
176
+
177
+ for source in range(1, n):
178
+ target = seed.randrange(0, source)
179
+ for succ in G.successors(target):
180
+ G.add_edge(source, succ)
181
+ G.add_edge(source, target)
182
+ return G
183
+
184
+
185
+ @py_random_state(6)
186
+ @nx._dispatchable(graphs=None, returns_graph=True)
187
+ def scale_free_graph(
188
+ n,
189
+ alpha=0.41,
190
+ beta=0.54,
191
+ gamma=0.05,
192
+ delta_in=0.2,
193
+ delta_out=0,
194
+ seed=None,
195
+ initial_graph=None,
196
+ ):
197
+ """Returns a scale-free directed graph.
198
+
199
+ Parameters
200
+ ----------
201
+ n : integer
202
+ Number of nodes in graph
203
+ alpha : float
204
+ Probability for adding a new node connected to an existing node
205
+ chosen randomly according to the in-degree distribution.
206
+ beta : float
207
+ Probability for adding an edge between two existing nodes.
208
+ One existing node is chosen randomly according the in-degree
209
+ distribution and the other chosen randomly according to the out-degree
210
+ distribution.
211
+ gamma : float
212
+ Probability for adding a new node connected to an existing node
213
+ chosen randomly according to the out-degree distribution.
214
+ delta_in : float
215
+ Bias for choosing nodes from in-degree distribution.
216
+ delta_out : float
217
+ Bias for choosing nodes from out-degree distribution.
218
+ seed : integer, random_state, or None (default)
219
+ Indicator of random number generation state.
220
+ See :ref:`Randomness<randomness>`.
221
+ initial_graph : MultiDiGraph instance, optional
222
+ Build the scale-free graph starting from this initial MultiDiGraph,
223
+ if provided.
224
+
225
+ Returns
226
+ -------
227
+ MultiDiGraph
228
+
229
+ Examples
230
+ --------
231
+ Create a scale-free graph on one hundred nodes::
232
+
233
+ >>> G = nx.scale_free_graph(100)
234
+
235
+ Notes
236
+ -----
237
+ The sum of `alpha`, `beta`, and `gamma` must be 1.
238
+
239
+ References
240
+ ----------
241
+ .. [1] B. Bollobás, C. Borgs, J. Chayes, and O. Riordan,
242
+ Directed scale-free graphs,
243
+ Proceedings of the fourteenth annual ACM-SIAM Symposium on
244
+ Discrete Algorithms, 132--139, 2003.
245
+ """
246
+
247
+ def _choose_node(candidates, node_list, delta):
248
+ if delta > 0:
249
+ bias_sum = len(node_list) * delta
250
+ p_delta = bias_sum / (bias_sum + len(candidates))
251
+ if seed.random() < p_delta:
252
+ return seed.choice(node_list)
253
+ return seed.choice(candidates)
254
+
255
+ if initial_graph is not None and hasattr(initial_graph, "_adj"):
256
+ if not isinstance(initial_graph, nx.MultiDiGraph):
257
+ raise nx.NetworkXError("initial_graph must be a MultiDiGraph.")
258
+ G = initial_graph
259
+ else:
260
+ # Start with 3-cycle
261
+ G = nx.MultiDiGraph([(0, 1), (1, 2), (2, 0)])
262
+
263
+ if alpha <= 0:
264
+ raise ValueError("alpha must be > 0.")
265
+ if beta <= 0:
266
+ raise ValueError("beta must be > 0.")
267
+ if gamma <= 0:
268
+ raise ValueError("gamma must be > 0.")
269
+
270
+ if abs(alpha + beta + gamma - 1.0) >= 1e-9:
271
+ raise ValueError("alpha+beta+gamma must equal 1.")
272
+
273
+ if delta_in < 0:
274
+ raise ValueError("delta_in must be >= 0.")
275
+
276
+ if delta_out < 0:
277
+ raise ValueError("delta_out must be >= 0.")
278
+
279
+ # pre-populate degree states
280
+ vs = sum((count * [idx] for idx, count in G.out_degree()), [])
281
+ ws = sum((count * [idx] for idx, count in G.in_degree()), [])
282
+
283
+ # pre-populate node state
284
+ node_list = list(G.nodes())
285
+
286
+ # see if there already are number-based nodes
287
+ numeric_nodes = [n for n in node_list if isinstance(n, numbers.Number)]
288
+ if len(numeric_nodes) > 0:
289
+ # set cursor for new nodes appropriately
290
+ cursor = max(int(n.real) for n in numeric_nodes) + 1
291
+ else:
292
+ # or start at zero
293
+ cursor = 0
294
+
295
+ while len(G) < n:
296
+ r = seed.random()
297
+
298
+ # random choice in alpha,beta,gamma ranges
299
+ if r < alpha:
300
+ # alpha
301
+ # add new node v
302
+ v = cursor
303
+ cursor += 1
304
+ # also add to node state
305
+ node_list.append(v)
306
+ # choose w according to in-degree and delta_in
307
+ w = _choose_node(ws, node_list, delta_in)
308
+
309
+ elif r < alpha + beta:
310
+ # beta
311
+ # choose v according to out-degree and delta_out
312
+ v = _choose_node(vs, node_list, delta_out)
313
+ # choose w according to in-degree and delta_in
314
+ w = _choose_node(ws, node_list, delta_in)
315
+
316
+ else:
317
+ # gamma
318
+ # choose v according to out-degree and delta_out
319
+ v = _choose_node(vs, node_list, delta_out)
320
+ # add new node w
321
+ w = cursor
322
+ cursor += 1
323
+ # also add to node state
324
+ node_list.append(w)
325
+
326
+ # add edge to graph
327
+ G.add_edge(v, w)
328
+
329
+ # update degree states
330
+ vs.append(v)
331
+ ws.append(w)
332
+
333
+ return G
334
+
335
+
336
+ @py_random_state(4)
337
+ @nx._dispatchable(graphs=None, returns_graph=True)
338
+ def random_uniform_k_out_graph(n, k, self_loops=True, with_replacement=True, seed=None):
339
+ """Returns a random `k`-out graph with uniform attachment.
340
+
341
+ A random `k`-out graph with uniform attachment is a multidigraph
342
+ generated by the following algorithm. For each node *u*, choose
343
+ `k` nodes *v* uniformly at random (with replacement). Add a
344
+ directed edge joining *u* to *v*.
345
+
346
+ Parameters
347
+ ----------
348
+ n : int
349
+ The number of nodes in the returned graph.
350
+
351
+ k : int
352
+ The out-degree of each node in the returned graph.
353
+
354
+ self_loops : bool
355
+ If True, self-loops are allowed when generating the graph.
356
+
357
+ with_replacement : bool
358
+ If True, neighbors are chosen with replacement and the
359
+ returned graph will be a directed multigraph. Otherwise,
360
+ neighbors are chosen without replacement and the returned graph
361
+ will be a directed graph.
362
+
363
+ seed : integer, random_state, or None (default)
364
+ Indicator of random number generation state.
365
+ See :ref:`Randomness<randomness>`.
366
+
367
+ Returns
368
+ -------
369
+ NetworkX graph
370
+ A `k`-out-regular directed graph generated according to the
371
+ above algorithm. It will be a multigraph if and only if
372
+ `with_replacement` is True.
373
+
374
+ Raises
375
+ ------
376
+ ValueError
377
+ If `with_replacement` is False and `k` is greater than
378
+ `n`.
379
+
380
+ See also
381
+ --------
382
+ random_k_out_graph
383
+
384
+ Notes
385
+ -----
386
+ The return digraph or multidigraph may not be strongly connected, or
387
+ even weakly connected.
388
+
389
+ If `with_replacement` is True, this function is similar to
390
+ :func:`random_k_out_graph`, if that function had parameter `alpha`
391
+ set to positive infinity.
392
+
393
+ """
394
+ if with_replacement:
395
+ create_using = nx.MultiDiGraph()
396
+
397
+ def sample(v, nodes):
398
+ if not self_loops:
399
+ nodes = nodes - {v}
400
+ return (seed.choice(list(nodes)) for i in range(k))
401
+
402
+ else:
403
+ create_using = nx.DiGraph()
404
+
405
+ def sample(v, nodes):
406
+ if not self_loops:
407
+ nodes = nodes - {v}
408
+ return seed.sample(list(nodes), k)
409
+
410
+ G = nx.empty_graph(n, create_using)
411
+ nodes = set(G)
412
+ for u in G:
413
+ G.add_edges_from((u, v) for v in sample(u, nodes))
414
+ return G
415
+
416
+
417
+ @py_random_state(4)
418
+ @nx._dispatchable(graphs=None, returns_graph=True)
419
+ def random_k_out_graph(n, k, alpha, self_loops=True, seed=None):
420
+ """Returns a random `k`-out graph with preferential attachment.
421
+
422
+ A random `k`-out graph with preferential attachment is a
423
+ multidigraph generated by the following algorithm.
424
+
425
+ 1. Begin with an empty digraph, and initially set each node to have
426
+ weight `alpha`.
427
+ 2. Choose a node `u` with out-degree less than `k` uniformly at
428
+ random.
429
+ 3. Choose a node `v` from with probability proportional to its
430
+ weight.
431
+ 4. Add a directed edge from `u` to `v`, and increase the weight
432
+ of `v` by one.
433
+ 5. If each node has out-degree `k`, halt, otherwise repeat from
434
+ step 2.
435
+
436
+ For more information on this model of random graph, see [1].
437
+
438
+ Parameters
439
+ ----------
440
+ n : int
441
+ The number of nodes in the returned graph.
442
+
443
+ k : int
444
+ The out-degree of each node in the returned graph.
445
+
446
+ alpha : float
447
+ A positive :class:`float` representing the initial weight of
448
+ each vertex. A higher number means that in step 3 above, nodes
449
+ will be chosen more like a true uniformly random sample, and a
450
+ lower number means that nodes are more likely to be chosen as
451
+ their in-degree increases. If this parameter is not positive, a
452
+ :exc:`ValueError` is raised.
453
+
454
+ self_loops : bool
455
+ If True, self-loops are allowed when generating the graph.
456
+
457
+ seed : integer, random_state, or None (default)
458
+ Indicator of random number generation state.
459
+ See :ref:`Randomness<randomness>`.
460
+
461
+ Returns
462
+ -------
463
+ :class:`~networkx.classes.MultiDiGraph`
464
+ A `k`-out-regular multidigraph generated according to the above
465
+ algorithm.
466
+
467
+ Raises
468
+ ------
469
+ ValueError
470
+ If `alpha` is not positive.
471
+
472
+ Notes
473
+ -----
474
+ The returned multidigraph may not be strongly connected, or even
475
+ weakly connected.
476
+
477
+ References
478
+ ----------
479
+ [1]: Peterson, Nicholas R., and Boris Pittel.
480
+ "Distance between two random `k`-out digraphs, with and without
481
+ preferential attachment."
482
+ arXiv preprint arXiv:1311.5961 (2013).
483
+ <https://arxiv.org/abs/1311.5961>
484
+
485
+ """
486
+ if alpha < 0:
487
+ raise ValueError("alpha must be positive")
488
+ G = nx.empty_graph(n, create_using=nx.MultiDiGraph)
489
+ weights = Counter({v: alpha for v in G})
490
+ for i in range(k * n):
491
+ u = seed.choice([v for v, d in G.out_degree() if d < k])
492
+ # If self-loops are not allowed, make the source node `u` have
493
+ # weight zero.
494
+ if not self_loops:
495
+ adjustment = Counter({u: weights[u]})
496
+ else:
497
+ adjustment = Counter()
498
+ v = weighted_choice(weights - adjustment, seed=seed)
499
+ G.add_edge(u, v)
500
+ weights[v] += 1
501
+ return G
wemm/lib/python3.10/site-packages/networkx/generators/geometric.py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for geometric graphs."""
2
+
3
+ import math
4
+ from bisect import bisect_left
5
+ from itertools import accumulate, combinations, product
6
+
7
+ import networkx as nx
8
+ from networkx.utils import py_random_state
9
+
10
+ __all__ = [
11
+ "geometric_edges",
12
+ "geographical_threshold_graph",
13
+ "navigable_small_world_graph",
14
+ "random_geometric_graph",
15
+ "soft_random_geometric_graph",
16
+ "thresholded_random_geometric_graph",
17
+ "waxman_graph",
18
+ "geometric_soft_configuration_graph",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable(node_attrs="pos_name")
23
+ def geometric_edges(G, radius, p=2, *, pos_name="pos"):
24
+ """Returns edge list of node pairs within `radius` of each other.
25
+
26
+ Parameters
27
+ ----------
28
+ G : networkx graph
29
+ The graph from which to generate the edge list. The nodes in `G` should
30
+ have an attribute ``pos`` corresponding to the node position, which is
31
+ used to compute the distance to other nodes.
32
+ radius : scalar
33
+ The distance threshold. Edges are included in the edge list if the
34
+ distance between the two nodes is less than `radius`.
35
+ pos_name : string, default="pos"
36
+ The name of the node attribute which represents the position of each
37
+ node in 2D coordinates. Every node in the Graph must have this attribute.
38
+ p : scalar, default=2
39
+ The `Minkowski distance metric
40
+ <https://en.wikipedia.org/wiki/Minkowski_distance>`_ used to compute
41
+ distances. The default value is 2, i.e. Euclidean distance.
42
+
43
+ Returns
44
+ -------
45
+ edges : list
46
+ List of edges whose distances are less than `radius`
47
+
48
+ Notes
49
+ -----
50
+ Radius uses Minkowski distance metric `p`.
51
+ If scipy is available, `scipy.spatial.cKDTree` is used to speed computation.
52
+
53
+ Examples
54
+ --------
55
+ Create a graph with nodes that have a "pos" attribute representing 2D
56
+ coordinates.
57
+
58
+ >>> G = nx.Graph()
59
+ >>> G.add_nodes_from(
60
+ ... [
61
+ ... (0, {"pos": (0, 0)}),
62
+ ... (1, {"pos": (3, 0)}),
63
+ ... (2, {"pos": (8, 0)}),
64
+ ... ]
65
+ ... )
66
+ >>> nx.geometric_edges(G, radius=1)
67
+ []
68
+ >>> nx.geometric_edges(G, radius=4)
69
+ [(0, 1)]
70
+ >>> nx.geometric_edges(G, radius=6)
71
+ [(0, 1), (1, 2)]
72
+ >>> nx.geometric_edges(G, radius=9)
73
+ [(0, 1), (0, 2), (1, 2)]
74
+ """
75
+ # Input validation - every node must have a "pos" attribute
76
+ for n, pos in G.nodes(data=pos_name):
77
+ if pos is None:
78
+ raise nx.NetworkXError(
79
+ f"Node {n} (and all nodes) must have a '{pos_name}' attribute."
80
+ )
81
+
82
+ # NOTE: See _geometric_edges for the actual implementation. The reason this
83
+ # is split into two functions is to avoid the overhead of input validation
84
+ # every time the function is called internally in one of the other
85
+ # geometric generators
86
+ return _geometric_edges(G, radius, p, pos_name)
87
+
88
+
89
+ def _geometric_edges(G, radius, p, pos_name):
90
+ """
91
+ Implements `geometric_edges` without input validation. See `geometric_edges`
92
+ for complete docstring.
93
+ """
94
+ nodes_pos = G.nodes(data=pos_name)
95
+ try:
96
+ import scipy as sp
97
+ except ImportError:
98
+ # no scipy KDTree so compute by for-loop
99
+ radius_p = radius**p
100
+ edges = [
101
+ (u, v)
102
+ for (u, pu), (v, pv) in combinations(nodes_pos, 2)
103
+ if sum(abs(a - b) ** p for a, b in zip(pu, pv)) <= radius_p
104
+ ]
105
+ return edges
106
+ # scipy KDTree is available
107
+ nodes, coords = list(zip(*nodes_pos))
108
+ kdtree = sp.spatial.cKDTree(coords) # Cannot provide generator.
109
+ edge_indexes = kdtree.query_pairs(radius, p)
110
+ edges = [(nodes[u], nodes[v]) for u, v in sorted(edge_indexes)]
111
+ return edges
112
+
113
+
114
+ @py_random_state(5)
115
+ @nx._dispatchable(graphs=None, returns_graph=True)
116
+ def random_geometric_graph(
117
+ n, radius, dim=2, pos=None, p=2, seed=None, *, pos_name="pos"
118
+ ):
119
+ """Returns a random geometric graph in the unit cube of dimensions `dim`.
120
+
121
+ The random geometric graph model places `n` nodes uniformly at
122
+ random in the unit cube. Two nodes are joined by an edge if the
123
+ distance between the nodes is at most `radius`.
124
+
125
+ Edges are determined using a KDTree when SciPy is available.
126
+ This reduces the time complexity from $O(n^2)$ to $O(n)$.
127
+
128
+ Parameters
129
+ ----------
130
+ n : int or iterable
131
+ Number of nodes or iterable of nodes
132
+ radius: float
133
+ Distance threshold value
134
+ dim : int, optional
135
+ Dimension of graph
136
+ pos : dict, optional
137
+ A dictionary keyed by node with node positions as values.
138
+ p : float, optional
139
+ Which Minkowski distance metric to use. `p` has to meet the condition
140
+ ``1 <= p <= infinity``.
141
+
142
+ If this argument is not specified, the :math:`L^2` metric
143
+ (the Euclidean distance metric), p = 2 is used.
144
+ This should not be confused with the `p` of an Erdős-Rényi random
145
+ graph, which represents probability.
146
+ seed : integer, random_state, or None (default)
147
+ Indicator of random number generation state.
148
+ See :ref:`Randomness<randomness>`.
149
+ pos_name : string, default="pos"
150
+ The name of the node attribute which represents the position
151
+ in 2D coordinates of the node in the returned graph.
152
+
153
+ Returns
154
+ -------
155
+ Graph
156
+ A random geometric graph, undirected and without self-loops.
157
+ Each node has a node attribute ``'pos'`` that stores the
158
+ position of that node in Euclidean space as provided by the
159
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
160
+ generated by this function.
161
+
162
+ Examples
163
+ --------
164
+ Create a random geometric graph on twenty nodes where nodes are joined by
165
+ an edge if their distance is at most 0.1::
166
+
167
+ >>> G = nx.random_geometric_graph(20, 0.1)
168
+
169
+ Notes
170
+ -----
171
+ This uses a *k*-d tree to build the graph.
172
+
173
+ The `pos` keyword argument can be used to specify node positions so you
174
+ can create an arbitrary distribution and domain for positions.
175
+
176
+ For example, to use a 2D Gaussian distribution of node positions with mean
177
+ (0, 0) and standard deviation 2::
178
+
179
+ >>> import random
180
+ >>> n = 20
181
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
182
+ >>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
183
+
184
+ References
185
+ ----------
186
+ .. [1] Penrose, Mathew, *Random Geometric Graphs*,
187
+ Oxford Studies in Probability, 5, 2003.
188
+
189
+ """
190
+ # TODO Is this function just a special case of the geographical
191
+ # threshold graph?
192
+ #
193
+ # half_radius = {v: radius / 2 for v in n}
194
+ # return geographical_threshold_graph(nodes, theta=1, alpha=1,
195
+ # weight=half_radius)
196
+ #
197
+ G = nx.empty_graph(n)
198
+ # If no positions are provided, choose uniformly random vectors in
199
+ # Euclidean space of the specified dimension.
200
+ if pos is None:
201
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
202
+ nx.set_node_attributes(G, pos, pos_name)
203
+
204
+ G.add_edges_from(_geometric_edges(G, radius, p, pos_name))
205
+ return G
206
+
207
+
208
+ @py_random_state(6)
209
+ @nx._dispatchable(graphs=None, returns_graph=True)
210
+ def soft_random_geometric_graph(
211
+ n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name="pos"
212
+ ):
213
+ r"""Returns a soft random geometric graph in the unit cube.
214
+
215
+ The soft random geometric graph [1] model places `n` nodes uniformly at
216
+ random in the unit cube in dimension `dim`. Two nodes of distance, `dist`,
217
+ computed by the `p`-Minkowski distance metric are joined by an edge with
218
+ probability `p_dist` if the computed distance metric value of the nodes
219
+ is at most `radius`, otherwise they are not joined.
220
+
221
+ Edges within `radius` of each other are determined using a KDTree when
222
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
223
+ to :math:`O(n)`.
224
+
225
+ Parameters
226
+ ----------
227
+ n : int or iterable
228
+ Number of nodes or iterable of nodes
229
+ radius: float
230
+ Distance threshold value
231
+ dim : int, optional
232
+ Dimension of graph
233
+ pos : dict, optional
234
+ A dictionary keyed by node with node positions as values.
235
+ p : float, optional
236
+ Which Minkowski distance metric to use.
237
+ `p` has to meet the condition ``1 <= p <= infinity``.
238
+
239
+ If this argument is not specified, the :math:`L^2` metric
240
+ (the Euclidean distance metric), p = 2 is used.
241
+
242
+ This should not be confused with the `p` of an Erdős-Rényi random
243
+ graph, which represents probability.
244
+ p_dist : function, optional
245
+ A probability density function computing the probability of
246
+ connecting two nodes that are of distance, dist, computed by the
247
+ Minkowski distance metric. The probability density function, `p_dist`,
248
+ must be any function that takes the metric value as input
249
+ and outputs a single probability value between 0-1. The scipy.stats
250
+ package has many probability distribution functions implemented and
251
+ tools for custom probability distribution definitions [2], and passing
252
+ the .pdf method of scipy.stats distributions can be used here. If the
253
+ probability function, `p_dist`, is not supplied, the default function
254
+ is an exponential distribution with rate parameter :math:`\lambda=1`.
255
+ seed : integer, random_state, or None (default)
256
+ Indicator of random number generation state.
257
+ See :ref:`Randomness<randomness>`.
258
+ pos_name : string, default="pos"
259
+ The name of the node attribute which represents the position
260
+ in 2D coordinates of the node in the returned graph.
261
+
262
+ Returns
263
+ -------
264
+ Graph
265
+ A soft random geometric graph, undirected and without self-loops.
266
+ Each node has a node attribute ``'pos'`` that stores the
267
+ position of that node in Euclidean space as provided by the
268
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
269
+ generated by this function.
270
+
271
+ Examples
272
+ --------
273
+ Default Graph:
274
+
275
+ G = nx.soft_random_geometric_graph(50, 0.2)
276
+
277
+ Custom Graph:
278
+
279
+ Create a soft random geometric graph on 100 uniformly distributed nodes
280
+ where nodes are joined by an edge with probability computed from an
281
+ exponential distribution with rate parameter :math:`\lambda=1` if their
282
+ Euclidean distance is at most 0.2.
283
+
284
+ Notes
285
+ -----
286
+ This uses a *k*-d tree to build the graph.
287
+
288
+ The `pos` keyword argument can be used to specify node positions so you
289
+ can create an arbitrary distribution and domain for positions.
290
+
291
+ For example, to use a 2D Gaussian distribution of node positions with mean
292
+ (0, 0) and standard deviation 2
293
+
294
+ The scipy.stats package can be used to define the probability distribution
295
+ with the .pdf method used as `p_dist`.
296
+
297
+ ::
298
+
299
+ >>> import random
300
+ >>> import math
301
+ >>> n = 100
302
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
303
+ >>> p_dist = lambda dist: math.exp(-dist)
304
+ >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist)
305
+
306
+ References
307
+ ----------
308
+ .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs."
309
+ The Annals of Applied Probability 26.2 (2016): 986-1028.
310
+ .. [2] scipy.stats -
311
+ https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
312
+
313
+ """
314
+ G = nx.empty_graph(n)
315
+ G.name = f"soft_random_geometric_graph({n}, {radius}, {dim})"
316
+ # If no positions are provided, choose uniformly random vectors in
317
+ # Euclidean space of the specified dimension.
318
+ if pos is None:
319
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
320
+ nx.set_node_attributes(G, pos, pos_name)
321
+
322
+ # if p_dist function not supplied the default function is an exponential
323
+ # distribution with rate parameter :math:`\lambda=1`.
324
+ if p_dist is None:
325
+
326
+ def p_dist(dist):
327
+ return math.exp(-dist)
328
+
329
+ def should_join(edge):
330
+ u, v = edge
331
+ dist = (sum(abs(a - b) ** p for a, b in zip(pos[u], pos[v]))) ** (1 / p)
332
+ return seed.random() < p_dist(dist)
333
+
334
+ G.add_edges_from(filter(should_join, _geometric_edges(G, radius, p, pos_name)))
335
+ return G
336
+
337
+
338
+ @py_random_state(7)
339
+ @nx._dispatchable(graphs=None, returns_graph=True)
340
+ def geographical_threshold_graph(
341
+ n,
342
+ theta,
343
+ dim=2,
344
+ pos=None,
345
+ weight=None,
346
+ metric=None,
347
+ p_dist=None,
348
+ seed=None,
349
+ *,
350
+ pos_name="pos",
351
+ weight_name="weight",
352
+ ):
353
+ r"""Returns a geographical threshold graph.
354
+
355
+ The geographical threshold graph model places $n$ nodes uniformly at
356
+ random in a rectangular domain. Each node $u$ is assigned a weight
357
+ $w_u$. Two nodes $u$ and $v$ are joined by an edge if
358
+
359
+ .. math::
360
+
361
+ (w_u + w_v)p_{dist}(r) \ge \theta
362
+
363
+ where `r` is the distance between `u` and `v`, `p_dist` is any function of
364
+ `r`, and :math:`\theta` as the threshold parameter. `p_dist` is used to
365
+ give weight to the distance between nodes when deciding whether or not
366
+ they should be connected. The larger `p_dist` is, the more prone nodes
367
+ separated by `r` are to be connected, and vice versa.
368
+
369
+ Parameters
370
+ ----------
371
+ n : int or iterable
372
+ Number of nodes or iterable of nodes
373
+ theta: float
374
+ Threshold value
375
+ dim : int, optional
376
+ Dimension of graph
377
+ pos : dict
378
+ Node positions as a dictionary of tuples keyed by node.
379
+ weight : dict
380
+ Node weights as a dictionary of numbers keyed by node.
381
+ metric : function
382
+ A metric on vectors of numbers (represented as lists or
383
+ tuples). This must be a function that accepts two lists (or
384
+ tuples) as input and yields a number as output. The function
385
+ must also satisfy the four requirements of a `metric`_.
386
+ Specifically, if $d$ is the function and $x$, $y$,
387
+ and $z$ are vectors in the graph, then $d$ must satisfy
388
+
389
+ 1. $d(x, y) \ge 0$,
390
+ 2. $d(x, y) = 0$ if and only if $x = y$,
391
+ 3. $d(x, y) = d(y, x)$,
392
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
393
+
394
+ If this argument is not specified, the Euclidean distance metric is
395
+ used.
396
+
397
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
398
+ p_dist : function, optional
399
+ Any function used to give weight to the distance between nodes when
400
+ deciding whether or not they should be connected. `p_dist` was
401
+ originally conceived as a probability density function giving the
402
+ probability of connecting two nodes that are of metric distance `r`
403
+ apart. The implementation here allows for more arbitrary definitions
404
+ of `p_dist` that do not need to correspond to valid probability
405
+ density functions. The :mod:`scipy.stats` package has many
406
+ probability density functions implemented and tools for custom
407
+ probability density definitions, and passing the ``.pdf`` method of
408
+ scipy.stats distributions can be used here. If ``p_dist=None``
409
+ (the default), the exponential function :math:`r^{-2}` is used.
410
+ seed : integer, random_state, or None (default)
411
+ Indicator of random number generation state.
412
+ See :ref:`Randomness<randomness>`.
413
+ pos_name : string, default="pos"
414
+ The name of the node attribute which represents the position
415
+ in 2D coordinates of the node in the returned graph.
416
+ weight_name : string, default="weight"
417
+ The name of the node attribute which represents the weight
418
+ of the node in the returned graph.
419
+
420
+ Returns
421
+ -------
422
+ Graph
423
+ A random geographic threshold graph, undirected and without
424
+ self-loops.
425
+
426
+ Each node has a node attribute ``pos`` that stores the
427
+ position of that node in Euclidean space as provided by the
428
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
429
+ generated by this function. Similarly, each node has a node
430
+ attribute ``weight`` that stores the weight of that node as
431
+ provided or as generated.
432
+
433
+ Examples
434
+ --------
435
+ Specify an alternate distance metric using the ``metric`` keyword
436
+ argument. For example, to use the `taxicab metric`_ instead of the
437
+ default `Euclidean metric`_::
438
+
439
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
440
+ >>> G = nx.geographical_threshold_graph(10, 0.1, metric=dist)
441
+
442
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
443
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
444
+
445
+ Notes
446
+ -----
447
+ If weights are not specified they are assigned to nodes by drawing randomly
448
+ from the exponential distribution with rate parameter $\lambda=1$.
449
+ To specify weights from a different distribution, use the `weight` keyword
450
+ argument::
451
+
452
+ >>> import random
453
+ >>> n = 20
454
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
455
+ >>> G = nx.geographical_threshold_graph(20, 50, weight=w)
456
+
457
+ If node positions are not specified they are randomly assigned from the
458
+ uniform distribution.
459
+
460
+ References
461
+ ----------
462
+ .. [1] Masuda, N., Miwa, H., Konno, N.:
463
+ Geographical threshold graphs with small-world and scale-free
464
+ properties.
465
+ Physical Review E 71, 036108 (2005)
466
+ .. [2] Milan Bradonjić, Aric Hagberg and Allon G. Percus,
467
+ Giant component and connectivity in geographical threshold graphs,
468
+ in Algorithms and Models for the Web-Graph (WAW 2007),
469
+ Antony Bonato and Fan Chung (Eds), pp. 209--216, 2007
470
+ """
471
+ G = nx.empty_graph(n)
472
+ # If no weights are provided, choose them from an exponential
473
+ # distribution.
474
+ if weight is None:
475
+ weight = {v: seed.expovariate(1) for v in G}
476
+ # If no positions are provided, choose uniformly random vectors in
477
+ # Euclidean space of the specified dimension.
478
+ if pos is None:
479
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
480
+ # If no distance metric is provided, use Euclidean distance.
481
+ if metric is None:
482
+ metric = math.dist
483
+ nx.set_node_attributes(G, weight, weight_name)
484
+ nx.set_node_attributes(G, pos, pos_name)
485
+
486
+ # if p_dist is not supplied, use default r^-2
487
+ if p_dist is None:
488
+
489
+ def p_dist(r):
490
+ return r**-2
491
+
492
+ # Returns ``True`` if and only if the nodes whose attributes are
493
+ # ``du`` and ``dv`` should be joined, according to the threshold
494
+ # condition.
495
+ def should_join(pair):
496
+ u, v = pair
497
+ u_pos, v_pos = pos[u], pos[v]
498
+ u_weight, v_weight = weight[u], weight[v]
499
+ return (u_weight + v_weight) * p_dist(metric(u_pos, v_pos)) >= theta
500
+
501
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
502
+ return G
503
+
504
+
505
+ @py_random_state(6)
506
+ @nx._dispatchable(graphs=None, returns_graph=True)
507
+ def waxman_graph(
508
+ n,
509
+ beta=0.4,
510
+ alpha=0.1,
511
+ L=None,
512
+ domain=(0, 0, 1, 1),
513
+ metric=None,
514
+ seed=None,
515
+ *,
516
+ pos_name="pos",
517
+ ):
518
+ r"""Returns a Waxman random graph.
519
+
520
+ The Waxman random graph model places `n` nodes uniformly at random
521
+ in a rectangular domain. Each pair of nodes at distance `d` is
522
+ joined by an edge with probability
523
+
524
+ .. math::
525
+ p = \beta \exp(-d / \alpha L).
526
+
527
+ This function implements both Waxman models, using the `L` keyword
528
+ argument.
529
+
530
+ * Waxman-1: if `L` is not specified, it is set to be the maximum distance
531
+ between any pair of nodes.
532
+ * Waxman-2: if `L` is specified, the distance between a pair of nodes is
533
+ chosen uniformly at random from the interval `[0, L]`.
534
+
535
+ Parameters
536
+ ----------
537
+ n : int or iterable
538
+ Number of nodes or iterable of nodes
539
+ beta: float
540
+ Model parameter
541
+ alpha: float
542
+ Model parameter
543
+ L : float, optional
544
+ Maximum distance between nodes. If not specified, the actual distance
545
+ is calculated.
546
+ domain : four-tuple of numbers, optional
547
+ Domain size, given as a tuple of the form `(x_min, y_min, x_max,
548
+ y_max)`.
549
+ metric : function
550
+ A metric on vectors of numbers (represented as lists or
551
+ tuples). This must be a function that accepts two lists (or
552
+ tuples) as input and yields a number as output. The function
553
+ must also satisfy the four requirements of a `metric`_.
554
+ Specifically, if $d$ is the function and $x$, $y$,
555
+ and $z$ are vectors in the graph, then $d$ must satisfy
556
+
557
+ 1. $d(x, y) \ge 0$,
558
+ 2. $d(x, y) = 0$ if and only if $x = y$,
559
+ 3. $d(x, y) = d(y, x)$,
560
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
561
+
562
+ If this argument is not specified, the Euclidean distance metric is
563
+ used.
564
+
565
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
566
+
567
+ seed : integer, random_state, or None (default)
568
+ Indicator of random number generation state.
569
+ See :ref:`Randomness<randomness>`.
570
+ pos_name : string, default="pos"
571
+ The name of the node attribute which represents the position
572
+ in 2D coordinates of the node in the returned graph.
573
+
574
+ Returns
575
+ -------
576
+ Graph
577
+ A random Waxman graph, undirected and without self-loops. Each
578
+ node has a node attribute ``'pos'`` that stores the position of
579
+ that node in Euclidean space as generated by this function.
580
+
581
+ Examples
582
+ --------
583
+ Specify an alternate distance metric using the ``metric`` keyword
584
+ argument. For example, to use the "`taxicab metric`_" instead of the
585
+ default `Euclidean metric`_::
586
+
587
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
588
+ >>> G = nx.waxman_graph(10, 0.5, 0.1, metric=dist)
589
+
590
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
591
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
592
+
593
+ Notes
594
+ -----
595
+ Starting in NetworkX 2.0 the parameters alpha and beta align with their
596
+ usual roles in the probability distribution. In earlier versions their
597
+ positions in the expression were reversed. Their position in the calling
598
+ sequence reversed as well to minimize backward incompatibility.
599
+
600
+ References
601
+ ----------
602
+ .. [1] B. M. Waxman, *Routing of multipoint connections*.
603
+ IEEE J. Select. Areas Commun. 6(9),(1988) 1617--1622.
604
+ """
605
+ G = nx.empty_graph(n)
606
+ (xmin, ymin, xmax, ymax) = domain
607
+ # Each node gets a uniformly random position in the given rectangle.
608
+ pos = {v: (seed.uniform(xmin, xmax), seed.uniform(ymin, ymax)) for v in G}
609
+ nx.set_node_attributes(G, pos, pos_name)
610
+ # If no distance metric is provided, use Euclidean distance.
611
+ if metric is None:
612
+ metric = math.dist
613
+ # If the maximum distance L is not specified (that is, we are in the
614
+ # Waxman-1 model), then find the maximum distance between any pair
615
+ # of nodes.
616
+ #
617
+ # In the Waxman-1 model, join nodes randomly based on distance. In
618
+ # the Waxman-2 model, join randomly based on random l.
619
+ if L is None:
620
+ L = max(metric(x, y) for x, y in combinations(pos.values(), 2))
621
+
622
+ def dist(u, v):
623
+ return metric(pos[u], pos[v])
624
+
625
+ else:
626
+
627
+ def dist(u, v):
628
+ return seed.random() * L
629
+
630
+ # `pair` is the pair of nodes to decide whether to join.
631
+ def should_join(pair):
632
+ return seed.random() < beta * math.exp(-dist(*pair) / (alpha * L))
633
+
634
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
635
+ return G
636
+
637
+
638
+ @py_random_state(5)
639
+ @nx._dispatchable(graphs=None, returns_graph=True)
640
+ def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None):
641
+ r"""Returns a navigable small-world graph.
642
+
643
+ A navigable small-world graph is a directed grid with additional long-range
644
+ connections that are chosen randomly.
645
+
646
+ [...] we begin with a set of nodes [...] that are identified with the set
647
+ of lattice points in an $n \times n$ square,
648
+ $\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
649
+ and we define the *lattice distance* between two nodes $(i, j)$ and
650
+ $(k, l)$ to be the number of "lattice steps" separating them:
651
+ $d((i, j), (k, l)) = |k - i| + |l - j|$.
652
+
653
+ For a universal constant $p >= 1$, the node $u$ has a directed edge to
654
+ every other node within lattice distance $p$---these are its *local
655
+ contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
656
+ construct directed edges from $u$ to $q$ other nodes (the *long-range
657
+ contacts*) using independent random trials; the $i$th directed edge from
658
+ $u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
659
+
660
+ -- [1]_
661
+
662
+ Parameters
663
+ ----------
664
+ n : int
665
+ The length of one side of the lattice; the number of nodes in
666
+ the graph is therefore $n^2$.
667
+ p : int
668
+ The diameter of short range connections. Each node is joined with every
669
+ other node within this lattice distance.
670
+ q : int
671
+ The number of long-range connections for each node.
672
+ r : float
673
+ Exponent for decaying probability of connections. The probability of
674
+ connecting to a node at lattice distance $d$ is $1/d^r$.
675
+ dim : int
676
+ Dimension of grid
677
+ seed : integer, random_state, or None (default)
678
+ Indicator of random number generation state.
679
+ See :ref:`Randomness<randomness>`.
680
+
681
+ References
682
+ ----------
683
+ .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
684
+ perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
685
+ """
686
+ if p < 1:
687
+ raise nx.NetworkXException("p must be >= 1")
688
+ if q < 0:
689
+ raise nx.NetworkXException("q must be >= 0")
690
+ if r < 0:
691
+ raise nx.NetworkXException("r must be >= 0")
692
+
693
+ G = nx.DiGraph()
694
+ nodes = list(product(range(n), repeat=dim))
695
+ for p1 in nodes:
696
+ probs = [0]
697
+ for p2 in nodes:
698
+ if p1 == p2:
699
+ continue
700
+ d = sum((abs(b - a) for a, b in zip(p1, p2)))
701
+ if d <= p:
702
+ G.add_edge(p1, p2)
703
+ probs.append(d**-r)
704
+ cdf = list(accumulate(probs))
705
+ for _ in range(q):
706
+ target = nodes[bisect_left(cdf, seed.uniform(0, cdf[-1]))]
707
+ G.add_edge(p1, target)
708
+ return G
709
+
710
+
711
+ @py_random_state(7)
712
+ @nx._dispatchable(graphs=None, returns_graph=True)
713
+ def thresholded_random_geometric_graph(
714
+ n,
715
+ radius,
716
+ theta,
717
+ dim=2,
718
+ pos=None,
719
+ weight=None,
720
+ p=2,
721
+ seed=None,
722
+ *,
723
+ pos_name="pos",
724
+ weight_name="weight",
725
+ ):
726
+ r"""Returns a thresholded random geometric graph in the unit cube.
727
+
728
+ The thresholded random geometric graph [1] model places `n` nodes
729
+ uniformly at random in the unit cube of dimensions `dim`. Each node
730
+ `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are
731
+ joined by an edge if they are within the maximum connection distance,
732
+ `radius` computed by the `p`-Minkowski distance and the summation of
733
+ weights :math:`w_u` + :math:`w_v` is greater than or equal
734
+ to the threshold parameter `theta`.
735
+
736
+ Edges within `radius` of each other are determined using a KDTree when
737
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
738
+ to :math:`O(n)`.
739
+
740
+ Parameters
741
+ ----------
742
+ n : int or iterable
743
+ Number of nodes or iterable of nodes
744
+ radius: float
745
+ Distance threshold value
746
+ theta: float
747
+ Threshold value
748
+ dim : int, optional
749
+ Dimension of graph
750
+ pos : dict, optional
751
+ A dictionary keyed by node with node positions as values.
752
+ weight : dict, optional
753
+ Node weights as a dictionary of numbers keyed by node.
754
+ p : float, optional (default 2)
755
+ Which Minkowski distance metric to use. `p` has to meet the condition
756
+ ``1 <= p <= infinity``.
757
+
758
+ If this argument is not specified, the :math:`L^2` metric
759
+ (the Euclidean distance metric), p = 2 is used.
760
+
761
+ This should not be confused with the `p` of an Erdős-Rényi random
762
+ graph, which represents probability.
763
+ seed : integer, random_state, or None (default)
764
+ Indicator of random number generation state.
765
+ See :ref:`Randomness<randomness>`.
766
+ pos_name : string, default="pos"
767
+ The name of the node attribute which represents the position
768
+ in 2D coordinates of the node in the returned graph.
769
+ weight_name : string, default="weight"
770
+ The name of the node attribute which represents the weight
771
+ of the node in the returned graph.
772
+
773
+ Returns
774
+ -------
775
+ Graph
776
+ A thresholded random geographic graph, undirected and without
777
+ self-loops.
778
+
779
+ Each node has a node attribute ``'pos'`` that stores the
780
+ position of that node in Euclidean space as provided by the
781
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
782
+ generated by this function. Similarly, each node has a nodethre
783
+ attribute ``'weight'`` that stores the weight of that node as
784
+ provided or as generated.
785
+
786
+ Examples
787
+ --------
788
+ Default Graph:
789
+
790
+ G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
791
+
792
+ Custom Graph:
793
+
794
+ Create a thresholded random geometric graph on 50 uniformly distributed
795
+ nodes where nodes are joined by an edge if their sum weights drawn from
796
+ a exponential distribution with rate = 5 are >= theta = 0.1 and their
797
+ Euclidean distance is at most 0.2.
798
+
799
+ Notes
800
+ -----
801
+ This uses a *k*-d tree to build the graph.
802
+
803
+ The `pos` keyword argument can be used to specify node positions so you
804
+ can create an arbitrary distribution and domain for positions.
805
+
806
+ For example, to use a 2D Gaussian distribution of node positions with mean
807
+ (0, 0) and standard deviation 2
808
+
809
+ If weights are not specified they are assigned to nodes by drawing randomly
810
+ from the exponential distribution with rate parameter :math:`\lambda=1`.
811
+ To specify weights from a different distribution, use the `weight` keyword
812
+ argument::
813
+
814
+ ::
815
+
816
+ >>> import random
817
+ >>> import math
818
+ >>> n = 50
819
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
820
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
821
+ >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w)
822
+
823
+ References
824
+ ----------
825
+ .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
826
+
827
+ """
828
+ G = nx.empty_graph(n)
829
+ G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})"
830
+ # If no weights are provided, choose them from an exponential
831
+ # distribution.
832
+ if weight is None:
833
+ weight = {v: seed.expovariate(1) for v in G}
834
+ # If no positions are provided, choose uniformly random vectors in
835
+ # Euclidean space of the specified dimension.
836
+ if pos is None:
837
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
838
+ # If no distance metric is provided, use Euclidean distance.
839
+ nx.set_node_attributes(G, weight, weight_name)
840
+ nx.set_node_attributes(G, pos, pos_name)
841
+
842
+ edges = (
843
+ (u, v)
844
+ for u, v in _geometric_edges(G, radius, p, pos_name)
845
+ if weight[u] + weight[v] >= theta
846
+ )
847
+ G.add_edges_from(edges)
848
+ return G
849
+
850
+
851
+ @py_random_state(5)
852
+ @nx._dispatchable(graphs=None, returns_graph=True)
853
+ def geometric_soft_configuration_graph(
854
+ *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None
855
+ ):
856
+ r"""Returns a random graph from the geometric soft configuration model.
857
+
858
+ The $\mathbb{S}^1$ model [1]_ is the geometric soft configuration model
859
+ which is able to explain many fundamental features of real networks such as
860
+ small-world property, heteregenous degree distributions, high level of
861
+ clustering, and self-similarity.
862
+
863
+ In the geometric soft configuration model, a node $i$ is assigned two hidden
864
+ variables: a hidden degree $\kappa_i$, quantifying its popularity, influence,
865
+ or importance, and an angular position $\theta_i$ in a circle abstracting the
866
+ similarity space, where angular distances between nodes are a proxy for their
867
+ similarity. Focusing on the angular position, this model is often called
868
+ the $\mathbb{S}^1$ model (a one-dimensional sphere). The circle's radius is
869
+ adjusted to $R = N/2\pi$, where $N$ is the number of nodes, so that the density
870
+ is set to 1 without loss of generality.
871
+
872
+ The connection probability between any pair of nodes increases with
873
+ the product of their hidden degrees (i.e., their combined popularities),
874
+ and decreases with the angular distance between the two nodes.
875
+ Specifically, nodes $i$ and $j$ are connected with the probability
876
+
877
+ $p_{ij} = \frac{1}{1 + \frac{d_{ij}^\beta}{\left(\mu \kappa_i \kappa_j\right)^{\max(1, \beta)}}}$
878
+
879
+ where $d_{ij} = R\Delta\theta_{ij}$ is the arc length of the circle between
880
+ nodes $i$ and $j$ separated by an angular distance $\Delta\theta_{ij}$.
881
+ Parameters $\mu$ and $\beta$ (also called inverse temperature) control the
882
+ average degree and the clustering coefficient, respectively.
883
+
884
+ It can be shown [2]_ that the model undergoes a structural phase transition
885
+ at $\beta=1$ so that for $\beta<1$ networks are unclustered in the thermodynamic
886
+ limit (when $N\to \infty$) whereas for $\beta>1$ the ensemble generates
887
+ networks with finite clustering coefficient.
888
+
889
+ The $\mathbb{S}^1$ model can be expressed as a purely geometric model
890
+ $\mathbb{H}^2$ in the hyperbolic plane [3]_ by mapping the hidden degree of
891
+ each node into a radial coordinate as
892
+
893
+ $r_i = \hat{R} - \frac{2 \max(1, \beta)}{\beta \zeta} \ln \left(\frac{\kappa_i}{\kappa_0}\right)$
894
+
895
+ where $\hat{R}$ is the radius of the hyperbolic disk and $\zeta$ is the curvature,
896
+
897
+ $\hat{R} = \frac{2}{\zeta} \ln \left(\frac{N}{\pi}\right)
898
+ - \frac{2\max(1, \beta)}{\beta \zeta} \ln (\mu \kappa_0^2)$
899
+
900
+ The connection probability then reads
901
+
902
+ $p_{ij} = \frac{1}{1 + \exp\left({\frac{\beta\zeta}{2} (x_{ij} - \hat{R})}\right)}$
903
+
904
+ where
905
+
906
+ $x_{ij} = r_i + r_j + \frac{2}{\zeta} \ln \frac{\Delta\theta_{ij}}{2}$
907
+
908
+ is a good approximation of the hyperbolic distance between two nodes separated
909
+ by an angular distance $\Delta\theta_{ij}$ with radial coordinates $r_i$ and $r_j$.
910
+ For $\beta > 1$, the curvature $\zeta = 1$, for $\beta < 1$, $\zeta = \beta^{-1}$.
911
+
912
+
913
+ Parameters
914
+ ----------
915
+ Either `n`, `gamma`, `mean_degree` are provided or `kappas`. The values of
916
+ `n`, `gamma`, `mean_degree` (if provided) are used to construct a random
917
+ kappa-dict keyed by node with values sampled from a power-law distribution.
918
+
919
+ beta : positive number
920
+ Inverse temperature, controlling the clustering coefficient.
921
+ n : int (default: None)
922
+ Size of the network (number of nodes).
923
+ If not provided, `kappas` must be provided and holds the nodes.
924
+ gamma : float (default: None)
925
+ Exponent of the power-law distribution for hidden degrees `kappas`.
926
+ If not provided, `kappas` must be provided directly.
927
+ mean_degree : float (default: None)
928
+ The mean degree in the network.
929
+ If not provided, `kappas` must be provided directly.
930
+ kappas : dict (default: None)
931
+ A dict keyed by node to its hidden degree value.
932
+ If not provided, random values are computed based on a power-law
933
+ distribution using `n`, `gamma` and `mean_degree`.
934
+ seed : int, random_state, or None (default)
935
+ Indicator of random number generation state.
936
+ See :ref:`Randomness<randomness>`.
937
+
938
+ Returns
939
+ -------
940
+ Graph
941
+ A random geometric soft configuration graph (undirected with no self-loops).
942
+ Each node has three node-attributes:
943
+
944
+ - ``kappa`` that represents the hidden degree.
945
+
946
+ - ``theta`` the position in the similarity space ($\mathbb{S}^1$) which is
947
+ also the angular position in the hyperbolic plane.
948
+
949
+ - ``radius`` the radial position in the hyperbolic plane
950
+ (based on the hidden degree).
951
+
952
+
953
+ Examples
954
+ --------
955
+ Generate a network with specified parameters:
956
+
957
+ >>> G = nx.geometric_soft_configuration_graph(
958
+ ... beta=1.5, n=100, gamma=2.7, mean_degree=5
959
+ ... )
960
+
961
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
962
+ is set to 1.5 and the exponent of the powerlaw distribution of the hidden
963
+ degrees is 2.7 with mean value of 5.
964
+
965
+ Generate a network with predefined hidden degrees:
966
+
967
+ >>> kappas = {i: 10 for i in range(100)}
968
+ >>> G = nx.geometric_soft_configuration_graph(beta=2.5, kappas=kappas)
969
+
970
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
971
+ is set to 2.5 and all nodes with hidden degree $\kappa=10$.
972
+
973
+
974
+ References
975
+ ----------
976
+ .. [1] Serrano, M. Á., Krioukov, D., & Boguñá, M. (2008). Self-similarity
977
+ of complex networks and hidden metric spaces. Physical review letters, 100(7), 078701.
978
+
979
+ .. [2] van der Kolk, J., Serrano, M. Á., & Boguñá, M. (2022). An anomalous
980
+ topological phase transition in spatial random graphs. Communications Physics, 5(1), 245.
981
+
982
+ .. [3] Krioukov, D., Papadopoulos, F., Kitsak, M., Vahdat, A., & Boguná, M. (2010).
983
+ Hyperbolic geometry of complex networks. Physical Review E, 82(3), 036106.
984
+
985
+ """
986
+ if beta <= 0:
987
+ raise nx.NetworkXError("The parameter beta cannot be smaller or equal to 0.")
988
+
989
+ if kappas is not None:
990
+ if not all((n is None, gamma is None, mean_degree is None)):
991
+ raise nx.NetworkXError(
992
+ "When kappas is input, n, gamma and mean_degree must not be."
993
+ )
994
+
995
+ n = len(kappas)
996
+ mean_degree = sum(kappas) / len(kappas)
997
+ else:
998
+ if any((n is None, gamma is None, mean_degree is None)):
999
+ raise nx.NetworkXError(
1000
+ "Please provide either kappas, or all 3 of: n, gamma and mean_degree."
1001
+ )
1002
+
1003
+ # Generate `n` hidden degrees from a powerlaw distribution
1004
+ # with given exponent `gamma` and mean value `mean_degree`
1005
+ gam_ratio = (gamma - 2) / (gamma - 1)
1006
+ kappa_0 = mean_degree * gam_ratio * (1 - 1 / n) / (1 - 1 / n**gam_ratio)
1007
+ base = 1 - 1 / n
1008
+ power = 1 / (1 - gamma)
1009
+ kappas = {i: kappa_0 * (1 - seed.random() * base) ** power for i in range(n)}
1010
+
1011
+ G = nx.Graph()
1012
+ R = n / (2 * math.pi)
1013
+
1014
+ # Approximate values for mu in the thermodynamic limit (when n -> infinity)
1015
+ if beta > 1:
1016
+ mu = beta * math.sin(math.pi / beta) / (2 * math.pi * mean_degree)
1017
+ elif beta == 1:
1018
+ mu = 1 / (2 * mean_degree * math.log(n))
1019
+ else:
1020
+ mu = (1 - beta) / (2**beta * mean_degree * n ** (1 - beta))
1021
+
1022
+ # Generate random positions on a circle
1023
+ thetas = {k: seed.uniform(0, 2 * math.pi) for k in kappas}
1024
+
1025
+ for u in kappas:
1026
+ for v in list(G):
1027
+ angle = math.pi - math.fabs(math.pi - math.fabs(thetas[u] - thetas[v]))
1028
+ dij = math.pow(R * angle, beta)
1029
+ mu_kappas = math.pow(mu * kappas[u] * kappas[v], max(1, beta))
1030
+ p_ij = 1 / (1 + dij / mu_kappas)
1031
+
1032
+ # Create an edge with a certain connection probability
1033
+ if seed.random() < p_ij:
1034
+ G.add_edge(u, v)
1035
+ G.add_node(u)
1036
+
1037
+ nx.set_node_attributes(G, thetas, "theta")
1038
+ nx.set_node_attributes(G, kappas, "kappa")
1039
+
1040
+ # Map hidden degrees into the radial coordinates
1041
+ zeta = 1 if beta > 1 else 1 / beta
1042
+ kappa_min = min(kappas.values())
1043
+ R_c = 2 * max(1, beta) / (beta * zeta)
1044
+ R_hat = (2 / zeta) * math.log(n / math.pi) - R_c * math.log(mu * kappa_min)
1045
+ radii = {node: R_hat - R_c * math.log(kappa) for node, kappa in kappas.items()}
1046
+ nx.set_node_attributes(G, radii, "radius")
1047
+
1048
+ return G
wemm/lib/python3.10/site-packages/networkx/generators/harary_graph.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for Harary graphs
2
+
3
+ This module gives two generators for the Harary graph, which was
4
+ introduced by the famous mathematician Frank Harary in his 1962 work [H]_.
5
+ The first generator gives the Harary graph that maximizes the node
6
+ connectivity with given number of nodes and given number of edges.
7
+ The second generator gives the Harary graph that minimizes
8
+ the number of edges in the graph with given node connectivity and
9
+ number of nodes.
10
+
11
+ References
12
+ ----------
13
+ .. [H] Harary, F. "The Maximum Connectivity of a Graph."
14
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
15
+
16
+ """
17
+
18
+ import networkx as nx
19
+ from networkx.exception import NetworkXError
20
+
21
+ __all__ = ["hnm_harary_graph", "hkn_harary_graph"]
22
+
23
+
24
+ @nx._dispatchable(graphs=None, returns_graph=True)
25
+ def hnm_harary_graph(n, m, create_using=None):
26
+ """Returns the Harary graph with given numbers of nodes and edges.
27
+
28
+ The Harary graph $H_{n,m}$ is the graph that maximizes node connectivity
29
+ with $n$ nodes and $m$ edges.
30
+
31
+ This maximum node connectivity is known to be floor($2m/n$). [1]_
32
+
33
+ Parameters
34
+ ----------
35
+ n: integer
36
+ The number of nodes the generated graph is to contain
37
+
38
+ m: integer
39
+ The number of edges the generated graph is to contain
40
+
41
+ create_using : NetworkX graph constructor, optional Graph type
42
+ to create (default=nx.Graph). If graph instance, then cleared
43
+ before populated.
44
+
45
+ Returns
46
+ -------
47
+ NetworkX graph
48
+ The Harary graph $H_{n,m}$.
49
+
50
+ See Also
51
+ --------
52
+ hkn_harary_graph
53
+
54
+ Notes
55
+ -----
56
+ This algorithm runs in $O(m)$ time.
57
+ It is implemented by following the Reference [2]_.
58
+
59
+ References
60
+ ----------
61
+ .. [1] F. T. Boesch, A. Satyanarayana, and C. L. Suffel,
62
+ "A Survey of Some Network Reliability Analysis and Synthesis Results,"
63
+ Networks, pp. 99-107, 2009.
64
+
65
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
66
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
67
+ """
68
+
69
+ if n < 1:
70
+ raise NetworkXError("The number of nodes must be >= 1!")
71
+ if m < n - 1:
72
+ raise NetworkXError("The number of edges must be >= n - 1 !")
73
+ if m > n * (n - 1) // 2:
74
+ raise NetworkXError("The number of edges must be <= n(n-1)/2")
75
+
76
+ # Construct an empty graph with n nodes first
77
+ H = nx.empty_graph(n, create_using)
78
+ # Get the floor of average node degree
79
+ d = 2 * m // n
80
+
81
+ # Test the parity of n and d
82
+ if (n % 2 == 0) or (d % 2 == 0):
83
+ # Start with a regular graph of d degrees
84
+ offset = d // 2
85
+ for i in range(n):
86
+ for j in range(1, offset + 1):
87
+ H.add_edge(i, (i - j) % n)
88
+ H.add_edge(i, (i + j) % n)
89
+ if d & 1:
90
+ # in case d is odd; n must be even in this case
91
+ half = n // 2
92
+ for i in range(half):
93
+ # add edges diagonally
94
+ H.add_edge(i, i + half)
95
+ # Get the remainder of 2*m modulo n
96
+ r = 2 * m % n
97
+ if r > 0:
98
+ # add remaining edges at offset+1
99
+ for i in range(r // 2):
100
+ H.add_edge(i, i + offset + 1)
101
+ else:
102
+ # Start with a regular graph of (d - 1) degrees
103
+ offset = (d - 1) // 2
104
+ for i in range(n):
105
+ for j in range(1, offset + 1):
106
+ H.add_edge(i, (i - j) % n)
107
+ H.add_edge(i, (i + j) % n)
108
+ half = n // 2
109
+ for i in range(m - n * offset):
110
+ # add the remaining m - n*offset edges between i and i+half
111
+ H.add_edge(i, (i + half) % n)
112
+
113
+ return H
114
+
115
+
116
+ @nx._dispatchable(graphs=None, returns_graph=True)
117
+ def hkn_harary_graph(k, n, create_using=None):
118
+ """Returns the Harary graph with given node connectivity and node number.
119
+
120
+ The Harary graph $H_{k,n}$ is the graph that minimizes the number of
121
+ edges needed with given node connectivity $k$ and node number $n$.
122
+
123
+ This smallest number of edges is known to be ceil($kn/2$) [1]_.
124
+
125
+ Parameters
126
+ ----------
127
+ k: integer
128
+ The node connectivity of the generated graph
129
+
130
+ n: integer
131
+ The number of nodes the generated graph is to contain
132
+
133
+ create_using : NetworkX graph constructor, optional Graph type
134
+ to create (default=nx.Graph). If graph instance, then cleared
135
+ before populated.
136
+
137
+ Returns
138
+ -------
139
+ NetworkX graph
140
+ The Harary graph $H_{k,n}$.
141
+
142
+ See Also
143
+ --------
144
+ hnm_harary_graph
145
+
146
+ Notes
147
+ -----
148
+ This algorithm runs in $O(kn)$ time.
149
+ It is implemented by following the Reference [2]_.
150
+
151
+ References
152
+ ----------
153
+ .. [1] Weisstein, Eric W. "Harary Graph." From MathWorld--A Wolfram Web
154
+ Resource. http://mathworld.wolfram.com/HararyGraph.html.
155
+
156
+ .. [2] Harary, F. "The Maximum Connectivity of a Graph."
157
+ Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
158
+ """
159
+
160
+ if k < 1:
161
+ raise NetworkXError("The node connectivity must be >= 1!")
162
+ if n < k + 1:
163
+ raise NetworkXError("The number of nodes must be >= k+1 !")
164
+
165
+ # in case of connectivity 1, simply return the path graph
166
+ if k == 1:
167
+ H = nx.path_graph(n, create_using)
168
+ return H
169
+
170
+ # Construct an empty graph with n nodes first
171
+ H = nx.empty_graph(n, create_using)
172
+
173
+ # Test the parity of k and n
174
+ if (k % 2 == 0) or (n % 2 == 0):
175
+ # Construct a regular graph with k degrees
176
+ offset = k // 2
177
+ for i in range(n):
178
+ for j in range(1, offset + 1):
179
+ H.add_edge(i, (i - j) % n)
180
+ H.add_edge(i, (i + j) % n)
181
+ if k & 1:
182
+ # odd degree; n must be even in this case
183
+ half = n // 2
184
+ for i in range(half):
185
+ # add edges diagonally
186
+ H.add_edge(i, i + half)
187
+ else:
188
+ # Construct a regular graph with (k - 1) degrees
189
+ offset = (k - 1) // 2
190
+ for i in range(n):
191
+ for j in range(1, offset + 1):
192
+ H.add_edge(i, (i - j) % n)
193
+ H.add_edge(i, (i + j) % n)
194
+ half = n // 2
195
+ for i in range(half + 1):
196
+ # add half+1 edges between i and i+half
197
+ H.add_edge(i, (i + half) % n)
198
+
199
+ return H
wemm/lib/python3.10/site-packages/networkx/generators/intersection.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random intersection graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.utils import py_random_state
7
+
8
+ __all__ = [
9
+ "uniform_random_intersection_graph",
10
+ "k_random_intersection_graph",
11
+ "general_random_intersection_graph",
12
+ ]
13
+
14
+
15
+ @py_random_state(3)
16
+ @nx._dispatchable(graphs=None, returns_graph=True)
17
+ def uniform_random_intersection_graph(n, m, p, seed=None):
18
+ """Returns a uniform random intersection graph.
19
+
20
+ Parameters
21
+ ----------
22
+ n : int
23
+ The number of nodes in the first bipartite set (nodes)
24
+ m : int
25
+ The number of nodes in the second bipartite set (attributes)
26
+ p : float
27
+ Probability of connecting nodes between bipartite sets
28
+ seed : integer, random_state, or None (default)
29
+ Indicator of random number generation state.
30
+ See :ref:`Randomness<randomness>`.
31
+
32
+ See Also
33
+ --------
34
+ gnp_random_graph
35
+
36
+ References
37
+ ----------
38
+ .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995,
39
+ PhD thesis, Johns Hopkins University
40
+ .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B.,
41
+ Random intersection graphs when m = !(n):
42
+ An equivalence theorem relating the evolution of the g(n, m, p)
43
+ and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176.
44
+ """
45
+ from networkx.algorithms import bipartite
46
+
47
+ G = bipartite.random_graph(n, m, p, seed)
48
+ return nx.projected_graph(G, range(n))
49
+
50
+
51
+ @py_random_state(3)
52
+ @nx._dispatchable(graphs=None, returns_graph=True)
53
+ def k_random_intersection_graph(n, m, k, seed=None):
54
+ """Returns a intersection graph with randomly chosen attribute sets for
55
+ each node that are of equal size (k).
56
+
57
+ Parameters
58
+ ----------
59
+ n : int
60
+ The number of nodes in the first bipartite set (nodes)
61
+ m : int
62
+ The number of nodes in the second bipartite set (attributes)
63
+ k : float
64
+ Size of attribute set to assign to each node.
65
+ seed : integer, random_state, or None (default)
66
+ Indicator of random number generation state.
67
+ See :ref:`Randomness<randomness>`.
68
+
69
+ See Also
70
+ --------
71
+ gnp_random_graph, uniform_random_intersection_graph
72
+
73
+ References
74
+ ----------
75
+ .. [1] Godehardt, E., and Jaworski, J.
76
+ Two models of random intersection graphs and their applications.
77
+ Electronic Notes in Discrete Mathematics 10 (2001), 129--132.
78
+ """
79
+ G = nx.empty_graph(n + m)
80
+ mset = range(n, n + m)
81
+ for v in range(n):
82
+ targets = seed.sample(mset, k)
83
+ G.add_edges_from(zip([v] * len(targets), targets))
84
+ return nx.projected_graph(G, range(n))
85
+
86
+
87
+ @py_random_state(3)
88
+ @nx._dispatchable(graphs=None, returns_graph=True)
89
+ def general_random_intersection_graph(n, m, p, seed=None):
90
+ """Returns a random intersection graph with independent probabilities
91
+ for connections between node and attribute sets.
92
+
93
+ Parameters
94
+ ----------
95
+ n : int
96
+ The number of nodes in the first bipartite set (nodes)
97
+ m : int
98
+ The number of nodes in the second bipartite set (attributes)
99
+ p : list of floats of length m
100
+ Probabilities for connecting nodes to each attribute
101
+ seed : integer, random_state, or None (default)
102
+ Indicator of random number generation state.
103
+ See :ref:`Randomness<randomness>`.
104
+
105
+ See Also
106
+ --------
107
+ gnp_random_graph, uniform_random_intersection_graph
108
+
109
+ References
110
+ ----------
111
+ .. [1] Nikoletseas, S. E., Raptopoulos, C., and Spirakis, P. G.
112
+ The existence and efficient construction of large independent sets
113
+ in general random intersection graphs. In ICALP (2004), J. D´ıaz,
114
+ J. Karhum¨aki, A. Lepist¨o, and D. Sannella, Eds., vol. 3142
115
+ of Lecture Notes in Computer Science, Springer, pp. 1029–1040.
116
+ """
117
+ if len(p) != m:
118
+ raise ValueError("Probability list p must have m elements.")
119
+ G = nx.empty_graph(n + m)
120
+ mset = range(n, n + m)
121
+ for u in range(n):
122
+ for v, q in zip(mset, p):
123
+ if seed.random() < q:
124
+ G.add_edge(u, v)
125
+ return nx.projected_graph(G, range(n))
wemm/lib/python3.10/site-packages/networkx/generators/joint_degree_seq.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given joint degree and directed joint degree"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = [
7
+ "is_valid_joint_degree",
8
+ "is_valid_directed_joint_degree",
9
+ "joint_degree_graph",
10
+ "directed_joint_degree_graph",
11
+ ]
12
+
13
+
14
+ @nx._dispatchable(graphs=None)
15
+ def is_valid_joint_degree(joint_degrees):
16
+ """Checks whether the given joint degree dictionary is realizable.
17
+
18
+ A *joint degree dictionary* is a dictionary of dictionaries, in
19
+ which entry ``joint_degrees[k][l]`` is an integer representing the
20
+ number of edges joining nodes of degree *k* with nodes of degree
21
+ *l*. Such a dictionary is realizable as a simple graph if and only
22
+ if the following conditions are satisfied.
23
+
24
+ - each entry must be an integer,
25
+ - the total number of nodes of degree *k*, computed by
26
+ ``sum(joint_degrees[k].values()) / k``, must be an integer,
27
+ - the total number of edges joining nodes of degree *k* with
28
+ nodes of degree *l* cannot exceed the total number of possible edges,
29
+ - each diagonal entry ``joint_degrees[k][k]`` must be even (this is
30
+ a convention assumed by the :func:`joint_degree_graph` function).
31
+
32
+
33
+ Parameters
34
+ ----------
35
+ joint_degrees : dictionary of dictionary of integers
36
+ A joint degree dictionary in which entry ``joint_degrees[k][l]``
37
+ is the number of edges joining nodes of degree *k* with nodes of
38
+ degree *l*.
39
+
40
+ Returns
41
+ -------
42
+ bool
43
+ Whether the given joint degree dictionary is realizable as a
44
+ simple graph.
45
+
46
+ References
47
+ ----------
48
+ .. [1] M. Gjoka, M. Kurant, A. Markopoulou, "2.5K Graphs: from Sampling
49
+ to Generation", IEEE Infocom, 2013.
50
+ .. [2] I. Stanton, A. Pinar, "Constructing and sampling graphs with a
51
+ prescribed joint degree distribution", Journal of Experimental
52
+ Algorithmics, 2012.
53
+ """
54
+
55
+ degree_count = {}
56
+ for k in joint_degrees:
57
+ if k > 0:
58
+ k_size = sum(joint_degrees[k].values()) / k
59
+ if not k_size.is_integer():
60
+ return False
61
+ degree_count[k] = k_size
62
+
63
+ for k in joint_degrees:
64
+ for l in joint_degrees[k]:
65
+ if not float(joint_degrees[k][l]).is_integer():
66
+ return False
67
+
68
+ if (k != l) and (joint_degrees[k][l] > degree_count[k] * degree_count[l]):
69
+ return False
70
+ elif k == l:
71
+ if joint_degrees[k][k] > degree_count[k] * (degree_count[k] - 1):
72
+ return False
73
+ if joint_degrees[k][k] % 2 != 0:
74
+ return False
75
+
76
+ # if all above conditions have been satisfied then the input
77
+ # joint degree is realizable as a simple graph.
78
+ return True
79
+
80
+
81
+ def _neighbor_switch(G, w, unsat, h_node_residual, avoid_node_id=None):
82
+ """Releases one free stub for ``w``, while preserving joint degree in G.
83
+
84
+ Parameters
85
+ ----------
86
+ G : NetworkX graph
87
+ Graph in which the neighbor switch will take place.
88
+ w : integer
89
+ Node id for which we will execute this neighbor switch.
90
+ unsat : set of integers
91
+ Set of unsaturated node ids that have the same degree as w.
92
+ h_node_residual: dictionary of integers
93
+ Keeps track of the remaining stubs for a given node.
94
+ avoid_node_id: integer
95
+ Node id to avoid when selecting w_prime.
96
+
97
+ Notes
98
+ -----
99
+ First, it selects *w_prime*, an unsaturated node that has the same degree
100
+ as ``w``. Second, it selects *switch_node*, a neighbor node of ``w`` that
101
+ is not connected to *w_prime*. Then it executes an edge swap i.e. removes
102
+ (``w``,*switch_node*) and adds (*w_prime*,*switch_node*). Gjoka et. al. [1]
103
+ prove that such an edge swap is always possible.
104
+
105
+ References
106
+ ----------
107
+ .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
108
+ Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
109
+ """
110
+
111
+ if (avoid_node_id is None) or (h_node_residual[avoid_node_id] > 1):
112
+ # select unsaturated node w_prime that has the same degree as w
113
+ w_prime = next(iter(unsat))
114
+ else:
115
+ # assume that the node pair (v,w) has been selected for connection. if
116
+ # - neighbor_switch is called for node w,
117
+ # - nodes v and w have the same degree,
118
+ # - node v=avoid_node_id has only one stub left,
119
+ # then prevent v=avoid_node_id from being selected as w_prime.
120
+
121
+ iter_var = iter(unsat)
122
+ while True:
123
+ w_prime = next(iter_var)
124
+ if w_prime != avoid_node_id:
125
+ break
126
+
127
+ # select switch_node, a neighbor of w, that is not connected to w_prime
128
+ w_prime_neighbs = G[w_prime] # slightly faster declaring this variable
129
+ for v in G[w]:
130
+ if (v not in w_prime_neighbs) and (v != w_prime):
131
+ switch_node = v
132
+ break
133
+
134
+ # remove edge (w,switch_node), add edge (w_prime,switch_node) and update
135
+ # data structures
136
+ G.remove_edge(w, switch_node)
137
+ G.add_edge(w_prime, switch_node)
138
+ h_node_residual[w] += 1
139
+ h_node_residual[w_prime] -= 1
140
+ if h_node_residual[w_prime] == 0:
141
+ unsat.remove(w_prime)
142
+
143
+
144
+ @py_random_state(1)
145
+ @nx._dispatchable(graphs=None, returns_graph=True)
146
+ def joint_degree_graph(joint_degrees, seed=None):
147
+ """Generates a random simple graph with the given joint degree dictionary.
148
+
149
+ Parameters
150
+ ----------
151
+ joint_degrees : dictionary of dictionary of integers
152
+ A joint degree dictionary in which entry ``joint_degrees[k][l]`` is the
153
+ number of edges joining nodes of degree *k* with nodes of degree *l*.
154
+ seed : integer, random_state, or None (default)
155
+ Indicator of random number generation state.
156
+ See :ref:`Randomness<randomness>`.
157
+
158
+ Returns
159
+ -------
160
+ G : Graph
161
+ A graph with the specified joint degree dictionary.
162
+
163
+ Raises
164
+ ------
165
+ NetworkXError
166
+ If *joint_degrees* dictionary is not realizable.
167
+
168
+ Notes
169
+ -----
170
+ In each iteration of the "while loop" the algorithm picks two disconnected
171
+ nodes *v* and *w*, of degree *k* and *l* correspondingly, for which
172
+ ``joint_degrees[k][l]`` has not reached its target yet. It then adds
173
+ edge (*v*, *w*) and increases the number of edges in graph G by one.
174
+
175
+ The intelligence of the algorithm lies in the fact that it is always
176
+ possible to add an edge between such disconnected nodes *v* and *w*,
177
+ even if one or both nodes do not have free stubs. That is made possible by
178
+ executing a "neighbor switch", an edge rewiring move that releases
179
+ a free stub while keeping the joint degree of G the same.
180
+
181
+ The algorithm continues for E (number of edges) iterations of
182
+ the "while loop", at the which point all entries of the given
183
+ ``joint_degrees[k][l]`` have reached their target values and the
184
+ construction is complete.
185
+
186
+ References
187
+ ----------
188
+ .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
189
+ Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
190
+
191
+ Examples
192
+ --------
193
+ >>> joint_degrees = {
194
+ ... 1: {4: 1},
195
+ ... 2: {2: 2, 3: 2, 4: 2},
196
+ ... 3: {2: 2, 4: 1},
197
+ ... 4: {1: 1, 2: 2, 3: 1},
198
+ ... }
199
+ >>> G = nx.joint_degree_graph(joint_degrees)
200
+ >>>
201
+ """
202
+
203
+ if not is_valid_joint_degree(joint_degrees):
204
+ msg = "Input joint degree dict not realizable as a simple graph"
205
+ raise nx.NetworkXError(msg)
206
+
207
+ # compute degree count from joint_degrees
208
+ degree_count = {k: sum(l.values()) // k for k, l in joint_degrees.items() if k > 0}
209
+
210
+ # start with empty N-node graph
211
+ N = sum(degree_count.values())
212
+ G = nx.empty_graph(N)
213
+
214
+ # for a given degree group, keep the list of all node ids
215
+ h_degree_nodelist = {}
216
+
217
+ # for a given node, keep track of the remaining stubs
218
+ h_node_residual = {}
219
+
220
+ # populate h_degree_nodelist and h_node_residual
221
+ nodeid = 0
222
+ for degree, num_nodes in degree_count.items():
223
+ h_degree_nodelist[degree] = range(nodeid, nodeid + num_nodes)
224
+ for v in h_degree_nodelist[degree]:
225
+ h_node_residual[v] = degree
226
+ nodeid += int(num_nodes)
227
+
228
+ # iterate over every degree pair (k,l) and add the number of edges given
229
+ # for each pair
230
+ for k in joint_degrees:
231
+ for l in joint_degrees[k]:
232
+ # n_edges_add is the number of edges to add for the
233
+ # degree pair (k,l)
234
+ n_edges_add = joint_degrees[k][l]
235
+
236
+ if (n_edges_add > 0) and (k >= l):
237
+ # number of nodes with degree k and l
238
+ k_size = degree_count[k]
239
+ l_size = degree_count[l]
240
+
241
+ # k_nodes and l_nodes consist of all nodes of degree k and l
242
+ k_nodes = h_degree_nodelist[k]
243
+ l_nodes = h_degree_nodelist[l]
244
+
245
+ # k_unsat and l_unsat consist of nodes of degree k and l that
246
+ # are unsaturated (nodes that have at least 1 available stub)
247
+ k_unsat = {v for v in k_nodes if h_node_residual[v] > 0}
248
+
249
+ if k != l:
250
+ l_unsat = {w for w in l_nodes if h_node_residual[w] > 0}
251
+ else:
252
+ l_unsat = k_unsat
253
+ n_edges_add = joint_degrees[k][l] // 2
254
+
255
+ while n_edges_add > 0:
256
+ # randomly pick nodes v and w that have degrees k and l
257
+ v = k_nodes[seed.randrange(k_size)]
258
+ w = l_nodes[seed.randrange(l_size)]
259
+
260
+ # if nodes v and w are disconnected then attempt to connect
261
+ if not G.has_edge(v, w) and (v != w):
262
+ # if node v has no free stubs then do neighbor switch
263
+ if h_node_residual[v] == 0:
264
+ _neighbor_switch(G, v, k_unsat, h_node_residual)
265
+
266
+ # if node w has no free stubs then do neighbor switch
267
+ if h_node_residual[w] == 0:
268
+ if k != l:
269
+ _neighbor_switch(G, w, l_unsat, h_node_residual)
270
+ else:
271
+ _neighbor_switch(
272
+ G, w, l_unsat, h_node_residual, avoid_node_id=v
273
+ )
274
+
275
+ # add edge (v, w) and update data structures
276
+ G.add_edge(v, w)
277
+ h_node_residual[v] -= 1
278
+ h_node_residual[w] -= 1
279
+ n_edges_add -= 1
280
+
281
+ if h_node_residual[v] == 0:
282
+ k_unsat.discard(v)
283
+ if h_node_residual[w] == 0:
284
+ l_unsat.discard(w)
285
+ return G
286
+
287
+
288
+ @nx._dispatchable(graphs=None)
289
+ def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
290
+ """Checks whether the given directed joint degree input is realizable
291
+
292
+ Parameters
293
+ ----------
294
+ in_degrees : list of integers
295
+ in degree sequence contains the in degrees of nodes.
296
+ out_degrees : list of integers
297
+ out degree sequence contains the out degrees of nodes.
298
+ nkk : dictionary of dictionary of integers
299
+ directed joint degree dictionary. for nodes of out degree k (first
300
+ level of dict) and nodes of in degree l (second level of dict)
301
+ describes the number of edges.
302
+
303
+ Returns
304
+ -------
305
+ boolean
306
+ returns true if given input is realizable, else returns false.
307
+
308
+ Notes
309
+ -----
310
+ Here is the list of conditions that the inputs (in/out degree sequences,
311
+ nkk) need to satisfy for simple directed graph realizability:
312
+
313
+ - Condition 0: in_degrees and out_degrees have the same length
314
+ - Condition 1: nkk[k][l] is integer for all k,l
315
+ - Condition 2: sum(nkk[k])/k = number of nodes with partition id k, is an
316
+ integer and matching degree sequence
317
+ - Condition 3: number of edges and non-chords between k and l cannot exceed
318
+ maximum possible number of edges
319
+
320
+
321
+ References
322
+ ----------
323
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
324
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
325
+ """
326
+ V = {} # number of nodes with in/out degree.
327
+ forbidden = {}
328
+ if len(in_degrees) != len(out_degrees):
329
+ return False
330
+
331
+ for idx in range(len(in_degrees)):
332
+ i = in_degrees[idx]
333
+ o = out_degrees[idx]
334
+ V[(i, 0)] = V.get((i, 0), 0) + 1
335
+ V[(o, 1)] = V.get((o, 1), 0) + 1
336
+
337
+ forbidden[(o, i)] = forbidden.get((o, i), 0) + 1
338
+
339
+ S = {} # number of edges going from in/out degree nodes.
340
+ for k in nkk:
341
+ for l in nkk[k]:
342
+ val = nkk[k][l]
343
+ if not float(val).is_integer(): # condition 1
344
+ return False
345
+
346
+ if val > 0:
347
+ S[(k, 1)] = S.get((k, 1), 0) + val
348
+ S[(l, 0)] = S.get((l, 0), 0) + val
349
+ # condition 3
350
+ if val + forbidden.get((k, l), 0) > V[(k, 1)] * V[(l, 0)]:
351
+ return False
352
+
353
+ return all(S[s] / s[0] == V[s] for s in S)
354
+
355
+
356
+ def _directed_neighbor_switch(
357
+ G, w, unsat, h_node_residual_out, chords, h_partition_in, partition
358
+ ):
359
+ """Releases one free stub for node w, while preserving joint degree in G.
360
+
361
+ Parameters
362
+ ----------
363
+ G : networkx directed graph
364
+ graph within which the edge swap will take place.
365
+ w : integer
366
+ node id for which we need to perform a neighbor switch.
367
+ unsat: set of integers
368
+ set of node ids that have the same degree as w and are unsaturated.
369
+ h_node_residual_out: dict of integers
370
+ for a given node, keeps track of the remaining stubs to be added.
371
+ chords: set of tuples
372
+ keeps track of available positions to add edges.
373
+ h_partition_in: dict of integers
374
+ for a given node, keeps track of its partition id (in degree).
375
+ partition: integer
376
+ partition id to check if chords have to be updated.
377
+
378
+ Notes
379
+ -----
380
+ First, it selects node w_prime that (1) has the same degree as w and
381
+ (2) is unsaturated. Then, it selects node v, a neighbor of w, that is
382
+ not connected to w_prime and does an edge swap i.e. removes (w,v) and
383
+ adds (w_prime,v). If neighbor switch is not possible for w using
384
+ w_prime and v, then return w_prime; in [1] it's proven that
385
+ such unsaturated nodes can be used.
386
+
387
+ References
388
+ ----------
389
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
390
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
391
+ """
392
+ w_prime = unsat.pop()
393
+ unsat.add(w_prime)
394
+ # select node t, a neighbor of w, that is not connected to w_prime
395
+ w_neighbs = list(G.successors(w))
396
+ # slightly faster declaring this variable
397
+ w_prime_neighbs = list(G.successors(w_prime))
398
+
399
+ for v in w_neighbs:
400
+ if (v not in w_prime_neighbs) and w_prime != v:
401
+ # removes (w,v), add (w_prime,v) and update data structures
402
+ G.remove_edge(w, v)
403
+ G.add_edge(w_prime, v)
404
+
405
+ if h_partition_in[v] == partition:
406
+ chords.add((w, v))
407
+ chords.discard((w_prime, v))
408
+
409
+ h_node_residual_out[w] += 1
410
+ h_node_residual_out[w_prime] -= 1
411
+ if h_node_residual_out[w_prime] == 0:
412
+ unsat.remove(w_prime)
413
+ return None
414
+
415
+ # If neighbor switch didn't work, use unsaturated node
416
+ return w_prime
417
+
418
+
419
+ def _directed_neighbor_switch_rev(
420
+ G, w, unsat, h_node_residual_in, chords, h_partition_out, partition
421
+ ):
422
+ """The reverse of directed_neighbor_switch.
423
+
424
+ Parameters
425
+ ----------
426
+ G : networkx directed graph
427
+ graph within which the edge swap will take place.
428
+ w : integer
429
+ node id for which we need to perform a neighbor switch.
430
+ unsat: set of integers
431
+ set of node ids that have the same degree as w and are unsaturated.
432
+ h_node_residual_in: dict of integers
433
+ for a given node, keeps track of the remaining stubs to be added.
434
+ chords: set of tuples
435
+ keeps track of available positions to add edges.
436
+ h_partition_out: dict of integers
437
+ for a given node, keeps track of its partition id (out degree).
438
+ partition: integer
439
+ partition id to check if chords have to be updated.
440
+
441
+ Notes
442
+ -----
443
+ Same operation as directed_neighbor_switch except it handles this operation
444
+ for incoming edges instead of outgoing.
445
+ """
446
+ w_prime = unsat.pop()
447
+ unsat.add(w_prime)
448
+ # slightly faster declaring these as variables.
449
+ w_neighbs = list(G.predecessors(w))
450
+ w_prime_neighbs = list(G.predecessors(w_prime))
451
+ # select node v, a neighbor of w, that is not connected to w_prime.
452
+ for v in w_neighbs:
453
+ if (v not in w_prime_neighbs) and w_prime != v:
454
+ # removes (v,w), add (v,w_prime) and update data structures.
455
+ G.remove_edge(v, w)
456
+ G.add_edge(v, w_prime)
457
+ if h_partition_out[v] == partition:
458
+ chords.add((v, w))
459
+ chords.discard((v, w_prime))
460
+
461
+ h_node_residual_in[w] += 1
462
+ h_node_residual_in[w_prime] -= 1
463
+ if h_node_residual_in[w_prime] == 0:
464
+ unsat.remove(w_prime)
465
+ return None
466
+
467
+ # If neighbor switch didn't work, use the unsaturated node.
468
+ return w_prime
469
+
470
+
471
+ @py_random_state(3)
472
+ @nx._dispatchable(graphs=None, returns_graph=True)
473
+ def directed_joint_degree_graph(in_degrees, out_degrees, nkk, seed=None):
474
+ """Generates a random simple directed graph with the joint degree.
475
+
476
+ Parameters
477
+ ----------
478
+ degree_seq : list of tuples (of size 3)
479
+ degree sequence contains tuples of nodes with node id, in degree and
480
+ out degree.
481
+ nkk : dictionary of dictionary of integers
482
+ directed joint degree dictionary, for nodes of out degree k (first
483
+ level of dict) and nodes of in degree l (second level of dict)
484
+ describes the number of edges.
485
+ seed : hashable object, optional
486
+ Seed for random number generator.
487
+
488
+ Returns
489
+ -------
490
+ G : Graph
491
+ A directed graph with the specified inputs.
492
+
493
+ Raises
494
+ ------
495
+ NetworkXError
496
+ If degree_seq and nkk are not realizable as a simple directed graph.
497
+
498
+
499
+ Notes
500
+ -----
501
+ Similarly to the undirected version:
502
+ In each iteration of the "while loop" the algorithm picks two disconnected
503
+ nodes v and w, of degree k and l correspondingly, for which nkk[k][l] has
504
+ not reached its target yet i.e. (for given k,l): n_edges_add < nkk[k][l].
505
+ It then adds edge (v,w) and always increases the number of edges in graph G
506
+ by one.
507
+
508
+ The intelligence of the algorithm lies in the fact that it is always
509
+ possible to add an edge between disconnected nodes v and w, for which
510
+ nkk[degree(v)][degree(w)] has not reached its target, even if one or both
511
+ nodes do not have free stubs. If either node v or w does not have a free
512
+ stub, we perform a "neighbor switch", an edge rewiring move that releases a
513
+ free stub while keeping nkk the same.
514
+
515
+ The difference for the directed version lies in the fact that neighbor
516
+ switches might not be able to rewire, but in these cases unsaturated nodes
517
+ can be reassigned to use instead, see [1] for detailed description and
518
+ proofs.
519
+
520
+ The algorithm continues for E (number of edges in the graph) iterations of
521
+ the "while loop", at which point all entries of the given nkk[k][l] have
522
+ reached their target values and the construction is complete.
523
+
524
+ References
525
+ ----------
526
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
527
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
528
+
529
+ Examples
530
+ --------
531
+ >>> in_degrees = [0, 1, 1, 2]
532
+ >>> out_degrees = [1, 1, 1, 1]
533
+ >>> nkk = {1: {1: 2, 2: 2}}
534
+ >>> G = nx.directed_joint_degree_graph(in_degrees, out_degrees, nkk)
535
+ >>>
536
+ """
537
+ if not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
538
+ msg = "Input is not realizable as a simple graph"
539
+ raise nx.NetworkXError(msg)
540
+
541
+ # start with an empty directed graph.
542
+ G = nx.DiGraph()
543
+
544
+ # for a given group, keep the list of all node ids.
545
+ h_degree_nodelist_in = {}
546
+ h_degree_nodelist_out = {}
547
+ # for a given group, keep the list of all unsaturated node ids.
548
+ h_degree_nodelist_in_unsat = {}
549
+ h_degree_nodelist_out_unsat = {}
550
+ # for a given node, keep track of the remaining stubs to be added.
551
+ h_node_residual_out = {}
552
+ h_node_residual_in = {}
553
+ # for a given node, keep track of the partition id.
554
+ h_partition_out = {}
555
+ h_partition_in = {}
556
+ # keep track of non-chords between pairs of partition ids.
557
+ non_chords = {}
558
+
559
+ # populate data structures
560
+ for idx, i in enumerate(in_degrees):
561
+ idx = int(idx)
562
+ if i > 0:
563
+ h_degree_nodelist_in.setdefault(i, [])
564
+ h_degree_nodelist_in_unsat.setdefault(i, set())
565
+ h_degree_nodelist_in[i].append(idx)
566
+ h_degree_nodelist_in_unsat[i].add(idx)
567
+ h_node_residual_in[idx] = i
568
+ h_partition_in[idx] = i
569
+
570
+ for idx, o in enumerate(out_degrees):
571
+ o = out_degrees[idx]
572
+ non_chords[(o, in_degrees[idx])] = non_chords.get((o, in_degrees[idx]), 0) + 1
573
+ idx = int(idx)
574
+ if o > 0:
575
+ h_degree_nodelist_out.setdefault(o, [])
576
+ h_degree_nodelist_out_unsat.setdefault(o, set())
577
+ h_degree_nodelist_out[o].append(idx)
578
+ h_degree_nodelist_out_unsat[o].add(idx)
579
+ h_node_residual_out[idx] = o
580
+ h_partition_out[idx] = o
581
+
582
+ G.add_node(idx)
583
+
584
+ nk_in = {}
585
+ nk_out = {}
586
+ for p in h_degree_nodelist_in:
587
+ nk_in[p] = len(h_degree_nodelist_in[p])
588
+ for p in h_degree_nodelist_out:
589
+ nk_out[p] = len(h_degree_nodelist_out[p])
590
+
591
+ # iterate over every degree pair (k,l) and add the number of edges given
592
+ # for each pair.
593
+ for k in nkk:
594
+ for l in nkk[k]:
595
+ n_edges_add = nkk[k][l]
596
+
597
+ if n_edges_add > 0:
598
+ # chords contains a random set of potential edges.
599
+ chords = set()
600
+
601
+ k_len = nk_out[k]
602
+ l_len = nk_in[l]
603
+ chords_sample = seed.sample(
604
+ range(k_len * l_len), n_edges_add + non_chords.get((k, l), 0)
605
+ )
606
+
607
+ num = 0
608
+ while len(chords) < n_edges_add:
609
+ i = h_degree_nodelist_out[k][chords_sample[num] % k_len]
610
+ j = h_degree_nodelist_in[l][chords_sample[num] // k_len]
611
+ num += 1
612
+ if i != j:
613
+ chords.add((i, j))
614
+
615
+ # k_unsat and l_unsat consist of nodes of in/out degree k and l
616
+ # that are unsaturated i.e. those nodes that have at least one
617
+ # available stub
618
+ k_unsat = h_degree_nodelist_out_unsat[k]
619
+ l_unsat = h_degree_nodelist_in_unsat[l]
620
+
621
+ while n_edges_add > 0:
622
+ v, w = chords.pop()
623
+ chords.add((v, w))
624
+
625
+ # if node v has no free stubs then do neighbor switch.
626
+ if h_node_residual_out[v] == 0:
627
+ _v = _directed_neighbor_switch(
628
+ G,
629
+ v,
630
+ k_unsat,
631
+ h_node_residual_out,
632
+ chords,
633
+ h_partition_in,
634
+ l,
635
+ )
636
+ if _v is not None:
637
+ v = _v
638
+
639
+ # if node w has no free stubs then do neighbor switch.
640
+ if h_node_residual_in[w] == 0:
641
+ _w = _directed_neighbor_switch_rev(
642
+ G,
643
+ w,
644
+ l_unsat,
645
+ h_node_residual_in,
646
+ chords,
647
+ h_partition_out,
648
+ k,
649
+ )
650
+ if _w is not None:
651
+ w = _w
652
+
653
+ # add edge (v,w) and update data structures.
654
+ G.add_edge(v, w)
655
+ h_node_residual_out[v] -= 1
656
+ h_node_residual_in[w] -= 1
657
+ n_edges_add -= 1
658
+ chords.discard((v, w))
659
+
660
+ if h_node_residual_out[v] == 0:
661
+ k_unsat.discard(v)
662
+ if h_node_residual_in[w] == 0:
663
+ l_unsat.discard(w)
664
+ return G
wemm/lib/python3.10/site-packages/networkx/generators/line.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating line graphs."""
2
+
3
+ from collections import defaultdict
4
+ from functools import partial
5
+ from itertools import combinations
6
+
7
+ import networkx as nx
8
+ from networkx.utils import arbitrary_element
9
+ from networkx.utils.decorators import not_implemented_for
10
+
11
+ __all__ = ["line_graph", "inverse_line_graph"]
12
+
13
+
14
+ @nx._dispatchable(returns_graph=True)
15
+ def line_graph(G, create_using=None):
16
+ r"""Returns the line graph of the graph or digraph `G`.
17
+
18
+ The line graph of a graph `G` has a node for each edge in `G` and an
19
+ edge joining those nodes if the two edges in `G` share a common node. For
20
+ directed graphs, nodes are adjacent exactly when the edges they represent
21
+ form a directed path of length two.
22
+
23
+ The nodes of the line graph are 2-tuples of nodes in the original graph (or
24
+ 3-tuples for multigraphs, with the key of the edge as the third element).
25
+
26
+ For information about self-loops and more discussion, see the **Notes**
27
+ section below.
28
+
29
+ Parameters
30
+ ----------
31
+ G : graph
32
+ A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
33
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
34
+ Graph type to create. If graph instance, then cleared before populated.
35
+
36
+ Returns
37
+ -------
38
+ L : graph
39
+ The line graph of G.
40
+
41
+ Examples
42
+ --------
43
+ >>> G = nx.star_graph(3)
44
+ >>> L = nx.line_graph(G)
45
+ >>> print(sorted(map(sorted, L.edges()))) # makes a 3-clique, K3
46
+ [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
47
+
48
+ Edge attributes from `G` are not copied over as node attributes in `L`, but
49
+ attributes can be copied manually:
50
+
51
+ >>> G = nx.path_graph(4)
52
+ >>> G.add_edges_from((u, v, {"tot": u + v}) for u, v in G.edges)
53
+ >>> G.edges(data=True)
54
+ EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
55
+ >>> H = nx.line_graph(G)
56
+ >>> H.add_nodes_from((node, G.edges[node]) for node in H)
57
+ >>> H.nodes(data=True)
58
+ NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
59
+
60
+ Notes
61
+ -----
62
+ Graph, node, and edge data are not propagated to the new graph. For
63
+ undirected graphs, the nodes in G must be sortable, otherwise the
64
+ constructed line graph may not be correct.
65
+
66
+ *Self-loops in undirected graphs*
67
+
68
+ For an undirected graph `G` without multiple edges, each edge can be
69
+ written as a set `\{u, v\}`. Its line graph `L` has the edges of `G` as
70
+ its nodes. If `x` and `y` are two nodes in `L`, then `\{x, y\}` is an edge
71
+ in `L` if and only if the intersection of `x` and `y` is nonempty. Thus,
72
+ the set of all edges is determined by the set of all pairwise intersections
73
+ of edges in `G`.
74
+
75
+ Trivially, every edge in G would have a nonzero intersection with itself,
76
+ and so every node in `L` should have a self-loop. This is not so
77
+ interesting, and the original context of line graphs was with simple
78
+ graphs, which had no self-loops or multiple edges. The line graph was also
79
+ meant to be a simple graph and thus, self-loops in `L` are not part of the
80
+ standard definition of a line graph. In a pairwise intersection matrix,
81
+ this is analogous to excluding the diagonal entries from the line graph
82
+ definition.
83
+
84
+ Self-loops and multiple edges in `G` add nodes to `L` in a natural way, and
85
+ do not require any fundamental changes to the definition. It might be
86
+ argued that the self-loops we excluded before should now be included.
87
+ However, the self-loops are still "trivial" in some sense and thus, are
88
+ usually excluded.
89
+
90
+ *Self-loops in directed graphs*
91
+
92
+ For a directed graph `G` without multiple edges, each edge can be written
93
+ as a tuple `(u, v)`. Its line graph `L` has the edges of `G` as its
94
+ nodes. If `x` and `y` are two nodes in `L`, then `(x, y)` is an edge in `L`
95
+ if and only if the tail of `x` matches the head of `y`, for example, if `x
96
+ = (a, b)` and `y = (b, c)` for some vertices `a`, `b`, and `c` in `G`.
97
+
98
+ Due to the directed nature of the edges, it is no longer the case that
99
+ every edge in `G` should have a self-loop in `L`. Now, the only time
100
+ self-loops arise is if a node in `G` itself has a self-loop. So such
101
+ self-loops are no longer "trivial" but instead, represent essential
102
+ features of the topology of `G`. For this reason, the historical
103
+ development of line digraphs is such that self-loops are included. When the
104
+ graph `G` has multiple edges, once again only superficial changes are
105
+ required to the definition.
106
+
107
+ References
108
+ ----------
109
+ * Harary, Frank, and Norman, Robert Z., "Some properties of line digraphs",
110
+ Rend. Circ. Mat. Palermo, II. Ser. 9 (1960), 161--168.
111
+ * Hemminger, R. L.; Beineke, L. W. (1978), "Line graphs and line digraphs",
112
+ in Beineke, L. W.; Wilson, R. J., Selected Topics in Graph Theory,
113
+ Academic Press Inc., pp. 271--305.
114
+
115
+ """
116
+ if G.is_directed():
117
+ L = _lg_directed(G, create_using=create_using)
118
+ else:
119
+ L = _lg_undirected(G, selfloops=False, create_using=create_using)
120
+ return L
121
+
122
+
123
+ def _lg_directed(G, create_using=None):
124
+ """Returns the line graph L of the (multi)digraph G.
125
+
126
+ Edges in G appear as nodes in L, represented as tuples of the form (u,v)
127
+ or (u,v,key) if G is a multidigraph. A node in L corresponding to the edge
128
+ (u,v) is connected to every node corresponding to an edge (v,w).
129
+
130
+ Parameters
131
+ ----------
132
+ G : digraph
133
+ A directed graph or directed multigraph.
134
+ create_using : NetworkX graph constructor, optional
135
+ Graph type to create. If graph instance, then cleared before populated.
136
+ Default is to use the same graph class as `G`.
137
+
138
+ """
139
+ L = nx.empty_graph(0, create_using, default=G.__class__)
140
+
141
+ # Create a graph specific edge function.
142
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
143
+
144
+ for from_node in get_edges():
145
+ # from_node is: (u,v) or (u,v,key)
146
+ L.add_node(from_node)
147
+ for to_node in get_edges(from_node[1]):
148
+ L.add_edge(from_node, to_node)
149
+
150
+ return L
151
+
152
+
153
+ def _lg_undirected(G, selfloops=False, create_using=None):
154
+ """Returns the line graph L of the (multi)graph G.
155
+
156
+ Edges in G appear as nodes in L, represented as sorted tuples of the form
157
+ (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
158
+ the edge {u,v} is connected to every node corresponding to an edge that
159
+ involves u or v.
160
+
161
+ Parameters
162
+ ----------
163
+ G : graph
164
+ An undirected graph or multigraph.
165
+ selfloops : bool
166
+ If `True`, then self-loops are included in the line graph. If `False`,
167
+ they are excluded.
168
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
169
+ Graph type to create. If graph instance, then cleared before populated.
170
+
171
+ Notes
172
+ -----
173
+ The standard algorithm for line graphs of undirected graphs does not
174
+ produce self-loops.
175
+
176
+ """
177
+ L = nx.empty_graph(0, create_using, default=G.__class__)
178
+
179
+ # Graph specific functions for edges.
180
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
181
+
182
+ # Determine if we include self-loops or not.
183
+ shift = 0 if selfloops else 1
184
+
185
+ # Introduce numbering of nodes
186
+ node_index = {n: i for i, n in enumerate(G)}
187
+
188
+ # Lift canonical representation of nodes to edges in line graph
189
+ edge_key_function = lambda edge: (node_index[edge[0]], node_index[edge[1]])
190
+
191
+ edges = set()
192
+ for u in G:
193
+ # Label nodes as a sorted tuple of nodes in original graph.
194
+ # Decide on representation of {u, v} as (u, v) or (v, u) depending on node_index.
195
+ # -> This ensures a canonical representation and avoids comparing values of different types.
196
+ nodes = [tuple(sorted(x[:2], key=node_index.get)) + x[2:] for x in get_edges(u)]
197
+
198
+ if len(nodes) == 1:
199
+ # Then the edge will be an isolated node in L.
200
+ L.add_node(nodes[0])
201
+
202
+ # Add a clique of `nodes` to graph. To prevent double adding edges,
203
+ # especially important for multigraphs, we store the edges in
204
+ # canonical form in a set.
205
+ for i, a in enumerate(nodes):
206
+ edges.update(
207
+ [
208
+ tuple(sorted((a, b), key=edge_key_function))
209
+ for b in nodes[i + shift :]
210
+ ]
211
+ )
212
+
213
+ L.add_edges_from(edges)
214
+ return L
215
+
216
+
217
+ @not_implemented_for("directed")
218
+ @not_implemented_for("multigraph")
219
+ @nx._dispatchable(returns_graph=True)
220
+ def inverse_line_graph(G):
221
+ """Returns the inverse line graph of graph G.
222
+
223
+ If H is a graph, and G is the line graph of H, such that G = L(H).
224
+ Then H is the inverse line graph of G.
225
+
226
+ Not all graphs are line graphs and these do not have an inverse line graph.
227
+ In these cases this function raises a NetworkXError.
228
+
229
+ Parameters
230
+ ----------
231
+ G : graph
232
+ A NetworkX Graph
233
+
234
+ Returns
235
+ -------
236
+ H : graph
237
+ The inverse line graph of G.
238
+
239
+ Raises
240
+ ------
241
+ NetworkXNotImplemented
242
+ If G is directed or a multigraph
243
+
244
+ NetworkXError
245
+ If G is not a line graph
246
+
247
+ Notes
248
+ -----
249
+ This is an implementation of the Roussopoulos algorithm[1]_.
250
+
251
+ If G consists of multiple components, then the algorithm doesn't work.
252
+ You should invert every component separately:
253
+
254
+ >>> K5 = nx.complete_graph(5)
255
+ >>> P4 = nx.Graph([("a", "b"), ("b", "c"), ("c", "d")])
256
+ >>> G = nx.union(K5, P4)
257
+ >>> root_graphs = []
258
+ >>> for comp in nx.connected_components(G):
259
+ ... root_graphs.append(nx.inverse_line_graph(G.subgraph(comp)))
260
+ >>> len(root_graphs)
261
+ 2
262
+
263
+ References
264
+ ----------
265
+ .. [1] Roussopoulos, N.D. , "A max {m, n} algorithm for determining the graph H from
266
+ its line graph G", Information Processing Letters 2, (1973), 108--112, ISSN 0020-0190,
267
+ `DOI link <https://doi.org/10.1016/0020-0190(73)90029-X>`_
268
+
269
+ """
270
+ if G.number_of_nodes() == 0:
271
+ return nx.empty_graph(1)
272
+ elif G.number_of_nodes() == 1:
273
+ v = arbitrary_element(G)
274
+ a = (v, 0)
275
+ b = (v, 1)
276
+ H = nx.Graph([(a, b)])
277
+ return H
278
+ elif G.number_of_nodes() > 1 and G.number_of_edges() == 0:
279
+ msg = (
280
+ "inverse_line_graph() doesn't work on an edgeless graph. "
281
+ "Please use this function on each component separately."
282
+ )
283
+ raise nx.NetworkXError(msg)
284
+
285
+ if nx.number_of_selfloops(G) != 0:
286
+ msg = (
287
+ "A line graph as generated by NetworkX has no selfloops, so G has no "
288
+ "inverse line graph. Please remove the selfloops from G and try again."
289
+ )
290
+ raise nx.NetworkXError(msg)
291
+
292
+ starting_cell = _select_starting_cell(G)
293
+ P = _find_partition(G, starting_cell)
294
+ # count how many times each vertex appears in the partition set
295
+ P_count = {u: 0 for u in G.nodes}
296
+ for p in P:
297
+ for u in p:
298
+ P_count[u] += 1
299
+
300
+ if max(P_count.values()) > 2:
301
+ msg = "G is not a line graph (vertex found in more than two partition cells)"
302
+ raise nx.NetworkXError(msg)
303
+ W = tuple((u,) for u in P_count if P_count[u] == 1)
304
+ H = nx.Graph()
305
+ H.add_nodes_from(P)
306
+ H.add_nodes_from(W)
307
+ for a, b in combinations(H.nodes, 2):
308
+ if any(a_bit in b for a_bit in a):
309
+ H.add_edge(a, b)
310
+ return H
311
+
312
+
313
+ def _triangles(G, e):
314
+ """Return list of all triangles containing edge e"""
315
+ u, v = e
316
+ if u not in G:
317
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
318
+ if v not in G[u]:
319
+ raise nx.NetworkXError(f"Edge ({u}, {v}) not in graph")
320
+ triangle_list = []
321
+ for x in G[u]:
322
+ if x in G[v]:
323
+ triangle_list.append((u, v, x))
324
+ return triangle_list
325
+
326
+
327
+ def _odd_triangle(G, T):
328
+ """Test whether T is an odd triangle in G
329
+
330
+ Parameters
331
+ ----------
332
+ G : NetworkX Graph
333
+ T : 3-tuple of vertices forming triangle in G
334
+
335
+ Returns
336
+ -------
337
+ True is T is an odd triangle
338
+ False otherwise
339
+
340
+ Raises
341
+ ------
342
+ NetworkXError
343
+ T is not a triangle in G
344
+
345
+ Notes
346
+ -----
347
+ An odd triangle is one in which there exists another vertex in G which is
348
+ adjacent to either exactly one or exactly all three of the vertices in the
349
+ triangle.
350
+
351
+ """
352
+ for u in T:
353
+ if u not in G.nodes():
354
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
355
+ for e in list(combinations(T, 2)):
356
+ if e[0] not in G[e[1]]:
357
+ raise nx.NetworkXError(f"Edge ({e[0]}, {e[1]}) not in graph")
358
+
359
+ T_nbrs = defaultdict(int)
360
+ for t in T:
361
+ for v in G[t]:
362
+ if v not in T:
363
+ T_nbrs[v] += 1
364
+ return any(T_nbrs[v] in [1, 3] for v in T_nbrs)
365
+
366
+
367
+ def _find_partition(G, starting_cell):
368
+ """Find a partition of the vertices of G into cells of complete graphs
369
+
370
+ Parameters
371
+ ----------
372
+ G : NetworkX Graph
373
+ starting_cell : tuple of vertices in G which form a cell
374
+
375
+ Returns
376
+ -------
377
+ List of tuples of vertices of G
378
+
379
+ Raises
380
+ ------
381
+ NetworkXError
382
+ If a cell is not a complete subgraph then G is not a line graph
383
+ """
384
+ G_partition = G.copy()
385
+ P = [starting_cell] # partition set
386
+ G_partition.remove_edges_from(list(combinations(starting_cell, 2)))
387
+ # keep list of partitioned nodes which might have an edge in G_partition
388
+ partitioned_vertices = list(starting_cell)
389
+ while G_partition.number_of_edges() > 0:
390
+ # there are still edges left and so more cells to be made
391
+ u = partitioned_vertices.pop()
392
+ deg_u = len(G_partition[u])
393
+ if deg_u != 0:
394
+ # if u still has edges then we need to find its other cell
395
+ # this other cell must be a complete subgraph or else G is
396
+ # not a line graph
397
+ new_cell = [u] + list(G_partition[u])
398
+ for u in new_cell:
399
+ for v in new_cell:
400
+ if (u != v) and (v not in G_partition[u]):
401
+ msg = (
402
+ "G is not a line graph "
403
+ "(partition cell not a complete subgraph)"
404
+ )
405
+ raise nx.NetworkXError(msg)
406
+ P.append(tuple(new_cell))
407
+ G_partition.remove_edges_from(list(combinations(new_cell, 2)))
408
+ partitioned_vertices += new_cell
409
+ return P
410
+
411
+
412
+ def _select_starting_cell(G, starting_edge=None):
413
+ """Select a cell to initiate _find_partition
414
+
415
+ Parameters
416
+ ----------
417
+ G : NetworkX Graph
418
+ starting_edge: an edge to build the starting cell from
419
+
420
+ Returns
421
+ -------
422
+ Tuple of vertices in G
423
+
424
+ Raises
425
+ ------
426
+ NetworkXError
427
+ If it is determined that G is not a line graph
428
+
429
+ Notes
430
+ -----
431
+ If starting edge not specified then pick an arbitrary edge - doesn't
432
+ matter which. However, this function may call itself requiring a
433
+ specific starting edge. Note that the r, s notation for counting
434
+ triangles is the same as in the Roussopoulos paper cited above.
435
+ """
436
+ if starting_edge is None:
437
+ e = arbitrary_element(G.edges())
438
+ else:
439
+ e = starting_edge
440
+ if e[0] not in G.nodes():
441
+ raise nx.NetworkXError(f"Vertex {e[0]} not in graph")
442
+ if e[1] not in G[e[0]]:
443
+ msg = f"starting_edge ({e[0]}, {e[1]}) is not in the Graph"
444
+ raise nx.NetworkXError(msg)
445
+ e_triangles = _triangles(G, e)
446
+ r = len(e_triangles)
447
+ if r == 0:
448
+ # there are no triangles containing e, so the starting cell is just e
449
+ starting_cell = e
450
+ elif r == 1:
451
+ # there is exactly one triangle, T, containing e. If other 2 edges
452
+ # of T belong only to this triangle then T is starting cell
453
+ T = e_triangles[0]
454
+ a, b, c = T
455
+ # ab was original edge so check the other 2 edges
456
+ ac_edges = len(_triangles(G, (a, c)))
457
+ bc_edges = len(_triangles(G, (b, c)))
458
+ if ac_edges == 1:
459
+ if bc_edges == 1:
460
+ starting_cell = T
461
+ else:
462
+ return _select_starting_cell(G, starting_edge=(b, c))
463
+ else:
464
+ return _select_starting_cell(G, starting_edge=(a, c))
465
+ else:
466
+ # r >= 2 so we need to count the number of odd triangles, s
467
+ s = 0
468
+ odd_triangles = []
469
+ for T in e_triangles:
470
+ if _odd_triangle(G, T):
471
+ s += 1
472
+ odd_triangles.append(T)
473
+ if r == 2 and s == 0:
474
+ # in this case either triangle works, so just use T
475
+ starting_cell = T
476
+ elif r - 1 <= s <= r:
477
+ # check if odd triangles containing e form complete subgraph
478
+ triangle_nodes = set()
479
+ for T in odd_triangles:
480
+ for x in T:
481
+ triangle_nodes.add(x)
482
+
483
+ for u in triangle_nodes:
484
+ for v in triangle_nodes:
485
+ if u != v and (v not in G[u]):
486
+ msg = (
487
+ "G is not a line graph (odd triangles "
488
+ "do not form complete subgraph)"
489
+ )
490
+ raise nx.NetworkXError(msg)
491
+ # otherwise then we can use this as the starting cell
492
+ starting_cell = tuple(triangle_nodes)
493
+
494
+ else:
495
+ msg = (
496
+ "G is not a line graph (incorrect number of "
497
+ "odd triangles around starting edge)"
498
+ )
499
+ raise nx.NetworkXError(msg)
500
+ return starting_cell
wemm/lib/python3.10/site-packages/networkx/generators/random_graphs.py ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random graphs.
3
+
4
+ """
5
+
6
+ import itertools
7
+ import math
8
+ from collections import defaultdict
9
+
10
+ import networkx as nx
11
+ from networkx.utils import py_random_state
12
+
13
+ from ..utils.misc import check_create_using
14
+ from .classic import complete_graph, empty_graph, path_graph, star_graph
15
+ from .degree_seq import degree_sequence_tree
16
+
17
+ __all__ = [
18
+ "fast_gnp_random_graph",
19
+ "gnp_random_graph",
20
+ "dense_gnm_random_graph",
21
+ "gnm_random_graph",
22
+ "erdos_renyi_graph",
23
+ "binomial_graph",
24
+ "newman_watts_strogatz_graph",
25
+ "watts_strogatz_graph",
26
+ "connected_watts_strogatz_graph",
27
+ "random_regular_graph",
28
+ "barabasi_albert_graph",
29
+ "dual_barabasi_albert_graph",
30
+ "extended_barabasi_albert_graph",
31
+ "powerlaw_cluster_graph",
32
+ "random_lobster",
33
+ "random_shell_graph",
34
+ "random_powerlaw_tree",
35
+ "random_powerlaw_tree_sequence",
36
+ "random_kernel_graph",
37
+ ]
38
+
39
+
40
+ @py_random_state(2)
41
+ @nx._dispatchable(graphs=None, returns_graph=True)
42
+ def fast_gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
43
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
44
+ a binomial graph.
45
+
46
+ Parameters
47
+ ----------
48
+ n : int
49
+ The number of nodes.
50
+ p : float
51
+ Probability for edge creation.
52
+ seed : integer, random_state, or None (default)
53
+ Indicator of random number generation state.
54
+ See :ref:`Randomness<randomness>`.
55
+ directed : bool, optional (default=False)
56
+ If True, this function returns a directed graph.
57
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
58
+ Graph type to create. If graph instance, then cleared before populated.
59
+ Multigraph types are not supported and raise a ``NetworkXError``.
60
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
61
+
62
+ Notes
63
+ -----
64
+ The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
65
+ (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
66
+
67
+ This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
68
+ edges, which equals $p n (n - 1) / 2$. This should be faster than
69
+ :func:`gnp_random_graph` when $p$ is small and the expected number of edges
70
+ is small (that is, the graph is sparse).
71
+
72
+ See Also
73
+ --------
74
+ gnp_random_graph
75
+
76
+ References
77
+ ----------
78
+ .. [1] Vladimir Batagelj and Ulrik Brandes,
79
+ "Efficient generation of large random networks",
80
+ Phys. Rev. E, 71, 036113, 2005.
81
+ """
82
+ default = nx.DiGraph if directed else nx.Graph
83
+ create_using = check_create_using(
84
+ create_using, directed=directed, multigraph=False, default=default
85
+ )
86
+ if p <= 0 or p >= 1:
87
+ return nx.gnp_random_graph(
88
+ n, p, seed=seed, directed=directed, create_using=create_using
89
+ )
90
+
91
+ G = empty_graph(n, create_using=create_using)
92
+
93
+ lp = math.log(1.0 - p)
94
+
95
+ if directed:
96
+ v = 1
97
+ w = -1
98
+ while v < n:
99
+ lr = math.log(1.0 - seed.random())
100
+ w = w + 1 + int(lr / lp)
101
+ while w >= v and v < n:
102
+ w = w - v
103
+ v = v + 1
104
+ if v < n:
105
+ G.add_edge(w, v)
106
+
107
+ # Nodes in graph are from 0,n-1 (start with v as the second node index).
108
+ v = 1
109
+ w = -1
110
+ while v < n:
111
+ lr = math.log(1.0 - seed.random())
112
+ w = w + 1 + int(lr / lp)
113
+ while w >= v and v < n:
114
+ w = w - v
115
+ v = v + 1
116
+ if v < n:
117
+ G.add_edge(v, w)
118
+ return G
119
+
120
+
121
+ @py_random_state(2)
122
+ @nx._dispatchable(graphs=None, returns_graph=True)
123
+ def gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
124
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
125
+ or a binomial graph.
126
+
127
+ The $G_{n,p}$ model chooses each of the possible edges with probability $p$.
128
+
129
+ Parameters
130
+ ----------
131
+ n : int
132
+ The number of nodes.
133
+ p : float
134
+ Probability for edge creation.
135
+ seed : integer, random_state, or None (default)
136
+ Indicator of random number generation state.
137
+ See :ref:`Randomness<randomness>`.
138
+ directed : bool, optional (default=False)
139
+ If True, this function returns a directed graph.
140
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
141
+ Graph type to create. If graph instance, then cleared before populated.
142
+ Multigraph types are not supported and raise a ``NetworkXError``.
143
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
144
+
145
+ See Also
146
+ --------
147
+ fast_gnp_random_graph
148
+
149
+ Notes
150
+ -----
151
+ This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for
152
+ small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm.
153
+
154
+ :func:`binomial_graph` and :func:`erdos_renyi_graph` are
155
+ aliases for :func:`gnp_random_graph`.
156
+
157
+ >>> nx.binomial_graph is nx.gnp_random_graph
158
+ True
159
+ >>> nx.erdos_renyi_graph is nx.gnp_random_graph
160
+ True
161
+
162
+ References
163
+ ----------
164
+ .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
165
+ .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
166
+ """
167
+ default = nx.DiGraph if directed else nx.Graph
168
+ create_using = check_create_using(
169
+ create_using, directed=directed, multigraph=False, default=default
170
+ )
171
+ if p >= 1:
172
+ return complete_graph(n, create_using=create_using)
173
+
174
+ G = nx.empty_graph(n, create_using=create_using)
175
+ if p <= 0:
176
+ return G
177
+
178
+ edgetool = itertools.permutations if directed else itertools.combinations
179
+ for e in edgetool(range(n), 2):
180
+ if seed.random() < p:
181
+ G.add_edge(*e)
182
+ return G
183
+
184
+
185
+ # add some aliases to common names
186
+ binomial_graph = gnp_random_graph
187
+ erdos_renyi_graph = gnp_random_graph
188
+
189
+
190
+ @py_random_state(2)
191
+ @nx._dispatchable(graphs=None, returns_graph=True)
192
+ def dense_gnm_random_graph(n, m, seed=None, *, create_using=None):
193
+ """Returns a $G_{n,m}$ random graph.
194
+
195
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
196
+ of all graphs with $n$ nodes and $m$ edges.
197
+
198
+ This algorithm should be faster than :func:`gnm_random_graph` for dense
199
+ graphs.
200
+
201
+ Parameters
202
+ ----------
203
+ n : int
204
+ The number of nodes.
205
+ m : int
206
+ The number of edges.
207
+ seed : integer, random_state, or None (default)
208
+ Indicator of random number generation state.
209
+ See :ref:`Randomness<randomness>`.
210
+ create_using : Graph constructor, optional (default=nx.Graph)
211
+ Graph type to create. If graph instance, then cleared before populated.
212
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
213
+
214
+ See Also
215
+ --------
216
+ gnm_random_graph
217
+
218
+ Notes
219
+ -----
220
+ Algorithm by Keith M. Briggs Mar 31, 2006.
221
+ Inspired by Knuth's Algorithm S (Selection sampling technique),
222
+ in section 3.4.2 of [1]_.
223
+
224
+ References
225
+ ----------
226
+ .. [1] Donald E. Knuth, The Art of Computer Programming,
227
+ Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
228
+ """
229
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
230
+ mmax = n * (n - 1) // 2
231
+ if m >= mmax:
232
+ return complete_graph(n, create_using)
233
+ G = empty_graph(n, create_using)
234
+
235
+ if n == 1:
236
+ return G
237
+
238
+ u = 0
239
+ v = 1
240
+ t = 0
241
+ k = 0
242
+ while True:
243
+ if seed.randrange(mmax - t) < m - k:
244
+ G.add_edge(u, v)
245
+ k += 1
246
+ if k == m:
247
+ return G
248
+ t += 1
249
+ v += 1
250
+ if v == n: # go to next row of adjacency matrix
251
+ u += 1
252
+ v = u + 1
253
+
254
+
255
+ @py_random_state(2)
256
+ @nx._dispatchable(graphs=None, returns_graph=True)
257
+ def gnm_random_graph(n, m, seed=None, directed=False, *, create_using=None):
258
+ """Returns a $G_{n,m}$ random graph.
259
+
260
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
261
+ of all graphs with $n$ nodes and $m$ edges.
262
+
263
+ This algorithm should be faster than :func:`dense_gnm_random_graph` for
264
+ sparse graphs.
265
+
266
+ Parameters
267
+ ----------
268
+ n : int
269
+ The number of nodes.
270
+ m : int
271
+ The number of edges.
272
+ seed : integer, random_state, or None (default)
273
+ Indicator of random number generation state.
274
+ See :ref:`Randomness<randomness>`.
275
+ directed : bool, optional (default=False)
276
+ If True return a directed graph
277
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
278
+ Graph type to create. If graph instance, then cleared before populated.
279
+ Multigraph types are not supported and raise a ``NetworkXError``.
280
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
281
+
282
+ See also
283
+ --------
284
+ dense_gnm_random_graph
285
+
286
+ """
287
+ default = nx.DiGraph if directed else nx.Graph
288
+ create_using = check_create_using(
289
+ create_using, directed=directed, multigraph=False, default=default
290
+ )
291
+ if n == 1:
292
+ return nx.empty_graph(n, create_using=create_using)
293
+ max_edges = n * (n - 1) if directed else n * (n - 1) / 2.0
294
+ if m >= max_edges:
295
+ return complete_graph(n, create_using=create_using)
296
+
297
+ G = nx.empty_graph(n, create_using=create_using)
298
+ nlist = list(G)
299
+ edge_count = 0
300
+ while edge_count < m:
301
+ # generate random edge,u,v
302
+ u = seed.choice(nlist)
303
+ v = seed.choice(nlist)
304
+ if u == v or G.has_edge(u, v):
305
+ continue
306
+ else:
307
+ G.add_edge(u, v)
308
+ edge_count = edge_count + 1
309
+ return G
310
+
311
+
312
+ @py_random_state(3)
313
+ @nx._dispatchable(graphs=None, returns_graph=True)
314
+ def newman_watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
315
+ """Returns a Newman–Watts–Strogatz small-world graph.
316
+
317
+ Parameters
318
+ ----------
319
+ n : int
320
+ The number of nodes.
321
+ k : int
322
+ Each node is joined with its `k` nearest neighbors in a ring
323
+ topology.
324
+ p : float
325
+ The probability of adding a new edge for each edge.
326
+ seed : integer, random_state, or None (default)
327
+ Indicator of random number generation state.
328
+ See :ref:`Randomness<randomness>`.
329
+ create_using : Graph constructor, optional (default=nx.Graph)
330
+ Graph type to create. If graph instance, then cleared before populated.
331
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
332
+
333
+ Notes
334
+ -----
335
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is
336
+ connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
337
+ is odd). Then shortcuts are created by adding new edges as follows: for
338
+ each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
339
+ neighbors" with probability $p$ add a new edge $(u, w)$ with
340
+ randomly-chosen existing node $w$. In contrast with
341
+ :func:`watts_strogatz_graph`, no edges are removed.
342
+
343
+ See Also
344
+ --------
345
+ watts_strogatz_graph
346
+
347
+ References
348
+ ----------
349
+ .. [1] M. E. J. Newman and D. J. Watts,
350
+ Renormalization group analysis of the small-world network model,
351
+ Physics Letters A, 263, 341, 1999.
352
+ https://doi.org/10.1016/S0375-9601(99)00757-4
353
+ """
354
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
355
+ if k > n:
356
+ raise nx.NetworkXError("k>=n, choose smaller k or larger n")
357
+
358
+ # If k == n the graph return is a complete graph
359
+ if k == n:
360
+ return nx.complete_graph(n, create_using)
361
+
362
+ G = empty_graph(n, create_using)
363
+ nlist = list(G.nodes())
364
+ fromv = nlist
365
+ # connect the k/2 neighbors
366
+ for j in range(1, k // 2 + 1):
367
+ tov = fromv[j:] + fromv[0:j] # the first j are now last
368
+ for i in range(len(fromv)):
369
+ G.add_edge(fromv[i], tov[i])
370
+ # for each edge u-v, with probability p, randomly select existing
371
+ # node w and add new edge u-w
372
+ e = list(G.edges())
373
+ for u, v in e:
374
+ if seed.random() < p:
375
+ w = seed.choice(nlist)
376
+ # no self-loops and reject if edge u-w exists
377
+ # is that the correct NWS model?
378
+ while w == u or G.has_edge(u, w):
379
+ w = seed.choice(nlist)
380
+ if G.degree(u) >= n - 1:
381
+ break # skip this rewiring
382
+ else:
383
+ G.add_edge(u, w)
384
+ return G
385
+
386
+
387
+ @py_random_state(3)
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
390
+ """Returns a Watts–Strogatz small-world graph.
391
+
392
+ Parameters
393
+ ----------
394
+ n : int
395
+ The number of nodes
396
+ k : int
397
+ Each node is joined with its `k` nearest neighbors in a ring
398
+ topology.
399
+ p : float
400
+ The probability of rewiring each edge
401
+ seed : integer, random_state, or None (default)
402
+ Indicator of random number generation state.
403
+ See :ref:`Randomness<randomness>`.
404
+ create_using : Graph constructor, optional (default=nx.Graph)
405
+ Graph type to create. If graph instance, then cleared before populated.
406
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
407
+
408
+ See Also
409
+ --------
410
+ newman_watts_strogatz_graph
411
+ connected_watts_strogatz_graph
412
+
413
+ Notes
414
+ -----
415
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
416
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
417
+ Then shortcuts are created by replacing some edges as follows: for each
418
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
419
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
420
+ random choice of existing node $w$.
421
+
422
+ In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring
423
+ does not increase the number of edges. The rewired graph is not guaranteed
424
+ to be connected as in :func:`connected_watts_strogatz_graph`.
425
+
426
+ References
427
+ ----------
428
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
429
+ Collective dynamics of small-world networks,
430
+ Nature, 393, pp. 440--442, 1998.
431
+ """
432
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
433
+ if k > n:
434
+ raise nx.NetworkXError("k>n, choose smaller k or larger n")
435
+
436
+ # If k == n, the graph is complete not Watts-Strogatz
437
+ if k == n:
438
+ G = nx.complete_graph(n, create_using)
439
+ return G
440
+
441
+ G = nx.empty_graph(n, create_using=create_using)
442
+ nodes = list(range(n)) # nodes are labeled 0 to n-1
443
+ # connect each node to k/2 neighbors
444
+ for j in range(1, k // 2 + 1):
445
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
446
+ G.add_edges_from(zip(nodes, targets))
447
+ # rewire edges from each node
448
+ # loop over all nodes in order (label) and neighbors in order (distance)
449
+ # no self loops or multiple edges allowed
450
+ for j in range(1, k // 2 + 1): # outer loop is neighbors
451
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
452
+ # inner loop in node order
453
+ for u, v in zip(nodes, targets):
454
+ if seed.random() < p:
455
+ w = seed.choice(nodes)
456
+ # Enforce no self-loops or multiple edges
457
+ while w == u or G.has_edge(u, w):
458
+ w = seed.choice(nodes)
459
+ if G.degree(u) >= n - 1:
460
+ break # skip this rewiring
461
+ else:
462
+ G.remove_edge(u, v)
463
+ G.add_edge(u, w)
464
+ return G
465
+
466
+
467
+ @py_random_state(4)
468
+ @nx._dispatchable(graphs=None, returns_graph=True)
469
+ def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None, *, create_using=None):
470
+ """Returns a connected Watts–Strogatz small-world graph.
471
+
472
+ Attempts to generate a connected graph by repeated generation of
473
+ Watts–Strogatz small-world graphs. An exception is raised if the maximum
474
+ number of tries is exceeded.
475
+
476
+ Parameters
477
+ ----------
478
+ n : int
479
+ The number of nodes
480
+ k : int
481
+ Each node is joined with its `k` nearest neighbors in a ring
482
+ topology.
483
+ p : float
484
+ The probability of rewiring each edge
485
+ tries : int
486
+ Number of attempts to generate a connected graph.
487
+ seed : integer, random_state, or None (default)
488
+ Indicator of random number generation state.
489
+ See :ref:`Randomness<randomness>`.
490
+ create_using : Graph constructor, optional (default=nx.Graph)
491
+ Graph type to create. If graph instance, then cleared before populated.
492
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
493
+
494
+ Notes
495
+ -----
496
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
497
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
498
+ Then shortcuts are created by replacing some edges as follows: for each
499
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
500
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
501
+ random choice of existing node $w$.
502
+ The entire process is repeated until a connected graph results.
503
+
504
+ See Also
505
+ --------
506
+ newman_watts_strogatz_graph
507
+ watts_strogatz_graph
508
+
509
+ References
510
+ ----------
511
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
512
+ Collective dynamics of small-world networks,
513
+ Nature, 393, pp. 440--442, 1998.
514
+ """
515
+ for i in range(tries):
516
+ # seed is an RNG so should change sequence each call
517
+ G = watts_strogatz_graph(n, k, p, seed, create_using=create_using)
518
+ if nx.is_connected(G):
519
+ return G
520
+ raise nx.NetworkXError("Maximum number of tries exceeded")
521
+
522
+
523
+ @py_random_state(2)
524
+ @nx._dispatchable(graphs=None, returns_graph=True)
525
+ def random_regular_graph(d, n, seed=None, *, create_using=None):
526
+ r"""Returns a random $d$-regular graph on $n$ nodes.
527
+
528
+ A regular graph is a graph where each node has the same number of neighbors.
529
+
530
+ The resulting graph has no self-loops or parallel edges.
531
+
532
+ Parameters
533
+ ----------
534
+ d : int
535
+ The degree of each node.
536
+ n : integer
537
+ The number of nodes. The value of $n \times d$ must be even.
538
+ seed : integer, random_state, or None (default)
539
+ Indicator of random number generation state.
540
+ See :ref:`Randomness<randomness>`.
541
+ create_using : Graph constructor, optional (default=nx.Graph)
542
+ Graph type to create. If graph instance, then cleared before populated.
543
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
544
+
545
+ Notes
546
+ -----
547
+ The nodes are numbered from $0$ to $n - 1$.
548
+
549
+ Kim and Vu's paper [2]_ shows that this algorithm samples in an
550
+ asymptotically uniform way from the space of random graphs when
551
+ $d = O(n^{1 / 3 - \epsilon})$.
552
+
553
+ Raises
554
+ ------
555
+
556
+ NetworkXError
557
+ If $n \times d$ is odd or $d$ is greater than or equal to $n$.
558
+
559
+ References
560
+ ----------
561
+ .. [1] A. Steger and N. Wormald,
562
+ Generating random regular graphs quickly,
563
+ Probability and Computing 8 (1999), 377-396, 1999.
564
+ https://doi.org/10.1017/S0963548399003867
565
+
566
+ .. [2] Jeong Han Kim and Van H. Vu,
567
+ Generating random regular graphs,
568
+ Proceedings of the thirty-fifth ACM symposium on Theory of computing,
569
+ San Diego, CA, USA, pp 213--222, 2003.
570
+ http://portal.acm.org/citation.cfm?id=780542.780576
571
+ """
572
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
573
+ if (n * d) % 2 != 0:
574
+ raise nx.NetworkXError("n * d must be even")
575
+
576
+ if not 0 <= d < n:
577
+ raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
578
+
579
+ G = nx.empty_graph(n, create_using=create_using)
580
+
581
+ if d == 0:
582
+ return G
583
+
584
+ def _suitable(edges, potential_edges):
585
+ # Helper subroutine to check if there are suitable edges remaining
586
+ # If False, the generation of the graph has failed
587
+ if not potential_edges:
588
+ return True
589
+ for s1 in potential_edges:
590
+ for s2 in potential_edges:
591
+ # Two iterators on the same dictionary are guaranteed
592
+ # to visit it in the same order if there are no
593
+ # intervening modifications.
594
+ if s1 == s2:
595
+ # Only need to consider s1-s2 pair one time
596
+ break
597
+ if s1 > s2:
598
+ s1, s2 = s2, s1
599
+ if (s1, s2) not in edges:
600
+ return True
601
+ return False
602
+
603
+ def _try_creation():
604
+ # Attempt to create an edge set
605
+
606
+ edges = set()
607
+ stubs = list(range(n)) * d
608
+
609
+ while stubs:
610
+ potential_edges = defaultdict(lambda: 0)
611
+ seed.shuffle(stubs)
612
+ stubiter = iter(stubs)
613
+ for s1, s2 in zip(stubiter, stubiter):
614
+ if s1 > s2:
615
+ s1, s2 = s2, s1
616
+ if s1 != s2 and ((s1, s2) not in edges):
617
+ edges.add((s1, s2))
618
+ else:
619
+ potential_edges[s1] += 1
620
+ potential_edges[s2] += 1
621
+
622
+ if not _suitable(edges, potential_edges):
623
+ return None # failed to find suitable edge set
624
+
625
+ stubs = [
626
+ node
627
+ for node, potential in potential_edges.items()
628
+ for _ in range(potential)
629
+ ]
630
+ return edges
631
+
632
+ # Even though a suitable edge set exists,
633
+ # the generation of such a set is not guaranteed.
634
+ # Try repeatedly to find one.
635
+ edges = _try_creation()
636
+ while edges is None:
637
+ edges = _try_creation()
638
+ G.add_edges_from(edges)
639
+
640
+ return G
641
+
642
+
643
+ def _random_subset(seq, m, rng):
644
+ """Return m unique elements from seq.
645
+
646
+ This differs from random.sample which can return repeated
647
+ elements if seq holds repeated elements.
648
+
649
+ Note: rng is a random.Random or numpy.random.RandomState instance.
650
+ """
651
+ targets = set()
652
+ while len(targets) < m:
653
+ x = rng.choice(seq)
654
+ targets.add(x)
655
+ return targets
656
+
657
+
658
+ @py_random_state(2)
659
+ @nx._dispatchable(graphs=None, returns_graph=True)
660
+ def barabasi_albert_graph(n, m, seed=None, initial_graph=None, *, create_using=None):
661
+ """Returns a random graph using Barabási–Albert preferential attachment
662
+
663
+ A graph of $n$ nodes is grown by attaching new nodes each with $m$
664
+ edges that are preferentially attached to existing nodes with high degree.
665
+
666
+ Parameters
667
+ ----------
668
+ n : int
669
+ Number of nodes
670
+ m : int
671
+ Number of edges to attach from a new node to existing nodes
672
+ seed : integer, random_state, or None (default)
673
+ Indicator of random number generation state.
674
+ See :ref:`Randomness<randomness>`.
675
+ initial_graph : Graph or None (default)
676
+ Initial network for Barabási–Albert algorithm.
677
+ It should be a connected graph for most use cases.
678
+ A copy of `initial_graph` is used.
679
+ If None, starts from a star graph on (m+1) nodes.
680
+ create_using : Graph constructor, optional (default=nx.Graph)
681
+ Graph type to create. If graph instance, then cleared before populated.
682
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
683
+
684
+ Returns
685
+ -------
686
+ G : Graph
687
+
688
+ Raises
689
+ ------
690
+ NetworkXError
691
+ If `m` does not satisfy ``1 <= m < n``, or
692
+ the initial graph number of nodes m0 does not satisfy ``m <= m0 <= n``.
693
+
694
+ References
695
+ ----------
696
+ .. [1] A. L. Barabási and R. Albert "Emergence of scaling in
697
+ random networks", Science 286, pp 509-512, 1999.
698
+ """
699
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
700
+ if m < 1 or m >= n:
701
+ raise nx.NetworkXError(
702
+ f"Barabási–Albert network must have m >= 1 and m < n, m = {m}, n = {n}"
703
+ )
704
+
705
+ if initial_graph is None:
706
+ # Default initial graph : star graph on (m + 1) nodes
707
+ G = star_graph(m, create_using)
708
+ else:
709
+ if len(initial_graph) < m or len(initial_graph) > n:
710
+ raise nx.NetworkXError(
711
+ f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
712
+ )
713
+ G = initial_graph.copy()
714
+
715
+ # List of existing nodes, with nodes repeated once for each adjacent edge
716
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
717
+ # Start adding the other n - m0 nodes.
718
+ source = len(G)
719
+ while source < n:
720
+ # Now choose m unique nodes from the existing nodes
721
+ # Pick uniformly from repeated_nodes (preferential attachment)
722
+ targets = _random_subset(repeated_nodes, m, seed)
723
+ # Add edges to m nodes from the source.
724
+ G.add_edges_from(zip([source] * m, targets))
725
+ # Add one node to the list for each new edge just created.
726
+ repeated_nodes.extend(targets)
727
+ # And the new node "source" has m edges to add to the list.
728
+ repeated_nodes.extend([source] * m)
729
+
730
+ source += 1
731
+ return G
732
+
733
+
734
+ @py_random_state(4)
735
+ @nx._dispatchable(graphs=None, returns_graph=True)
736
+ def dual_barabasi_albert_graph(
737
+ n, m1, m2, p, seed=None, initial_graph=None, *, create_using=None
738
+ ):
739
+ """Returns a random graph using dual Barabási–Albert preferential attachment
740
+
741
+ A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
742
+ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
743
+ are preferentially attached to existing nodes with high degree.
744
+
745
+ Parameters
746
+ ----------
747
+ n : int
748
+ Number of nodes
749
+ m1 : int
750
+ Number of edges to link each new node to existing nodes with probability $p$
751
+ m2 : int
752
+ Number of edges to link each new node to existing nodes with probability $1-p$
753
+ p : float
754
+ The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
755
+ seed : integer, random_state, or None (default)
756
+ Indicator of random number generation state.
757
+ See :ref:`Randomness<randomness>`.
758
+ initial_graph : Graph or None (default)
759
+ Initial network for Barabási–Albert algorithm.
760
+ A copy of `initial_graph` is used.
761
+ It should be connected for most use cases.
762
+ If None, starts from an star graph on max(m1, m2) + 1 nodes.
763
+ create_using : Graph constructor, optional (default=nx.Graph)
764
+ Graph type to create. If graph instance, then cleared before populated.
765
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
766
+
767
+ Returns
768
+ -------
769
+ G : Graph
770
+
771
+ Raises
772
+ ------
773
+ NetworkXError
774
+ If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
775
+ `p` does not satisfy ``0 <= p <= 1``, or
776
+ the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
777
+
778
+ References
779
+ ----------
780
+ .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
781
+ """
782
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
783
+ if m1 < 1 or m1 >= n:
784
+ raise nx.NetworkXError(
785
+ f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
786
+ )
787
+ if m2 < 1 or m2 >= n:
788
+ raise nx.NetworkXError(
789
+ f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
790
+ )
791
+ if p < 0 or p > 1:
792
+ raise nx.NetworkXError(
793
+ f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
794
+ )
795
+
796
+ # For simplicity, if p == 0 or 1, just return BA
797
+ if p == 1:
798
+ return barabasi_albert_graph(n, m1, seed, create_using=create_using)
799
+ elif p == 0:
800
+ return barabasi_albert_graph(n, m2, seed, create_using=create_using)
801
+
802
+ if initial_graph is None:
803
+ # Default initial graph : star graph on max(m1, m2) nodes
804
+ G = star_graph(max(m1, m2), create_using)
805
+ else:
806
+ if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
807
+ raise nx.NetworkXError(
808
+ f"Barabási–Albert initial graph must have between "
809
+ f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
810
+ )
811
+ G = initial_graph.copy()
812
+
813
+ # Target nodes for new edges
814
+ targets = list(G)
815
+ # List of existing nodes, with nodes repeated once for each adjacent edge
816
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
817
+ # Start adding the remaining nodes.
818
+ source = len(G)
819
+ while source < n:
820
+ # Pick which m to use (m1 or m2)
821
+ if seed.random() < p:
822
+ m = m1
823
+ else:
824
+ m = m2
825
+ # Now choose m unique nodes from the existing nodes
826
+ # Pick uniformly from repeated_nodes (preferential attachment)
827
+ targets = _random_subset(repeated_nodes, m, seed)
828
+ # Add edges to m nodes from the source.
829
+ G.add_edges_from(zip([source] * m, targets))
830
+ # Add one node to the list for each new edge just created.
831
+ repeated_nodes.extend(targets)
832
+ # And the new node "source" has m edges to add to the list.
833
+ repeated_nodes.extend([source] * m)
834
+
835
+ source += 1
836
+ return G
837
+
838
+
839
+ @py_random_state(4)
840
+ @nx._dispatchable(graphs=None, returns_graph=True)
841
+ def extended_barabasi_albert_graph(n, m, p, q, seed=None, *, create_using=None):
842
+ """Returns an extended Barabási–Albert model graph.
843
+
844
+ An extended Barabási–Albert model graph is a random graph constructed
845
+ using preferential attachment. The extended model allows new edges,
846
+ rewired edges or new nodes. Based on the probabilities $p$ and $q$
847
+ with $p + q < 1$, the growing behavior of the graph is determined as:
848
+
849
+ 1) With $p$ probability, $m$ new edges are added to the graph,
850
+ starting from randomly chosen existing nodes and attached preferentially at the
851
+ other end.
852
+
853
+ 2) With $q$ probability, $m$ existing edges are rewired
854
+ by randomly choosing an edge and rewiring one end to a preferentially chosen node.
855
+
856
+ 3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
857
+ with edges attached preferentially.
858
+
859
+ When $p = q = 0$, the model behaves just like the Barabási–Alber model.
860
+
861
+ Parameters
862
+ ----------
863
+ n : int
864
+ Number of nodes
865
+ m : int
866
+ Number of edges with which a new node attaches to existing nodes
867
+ p : float
868
+ Probability value for adding an edge between existing nodes. p + q < 1
869
+ q : float
870
+ Probability value of rewiring of existing edges. p + q < 1
871
+ seed : integer, random_state, or None (default)
872
+ Indicator of random number generation state.
873
+ See :ref:`Randomness<randomness>`.
874
+ create_using : Graph constructor, optional (default=nx.Graph)
875
+ Graph type to create. If graph instance, then cleared before populated.
876
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
877
+
878
+ Returns
879
+ -------
880
+ G : Graph
881
+
882
+ Raises
883
+ ------
884
+ NetworkXError
885
+ If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
886
+
887
+ References
888
+ ----------
889
+ .. [1] Albert, R., & Barabási, A. L. (2000)
890
+ Topology of evolving networks: local events and universality
891
+ Physical review letters, 85(24), 5234.
892
+ """
893
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
894
+ if m < 1 or m >= n:
895
+ msg = f"Extended Barabasi-Albert network needs m>=1 and m<n, m={m}, n={n}"
896
+ raise nx.NetworkXError(msg)
897
+ if p + q >= 1:
898
+ msg = f"Extended Barabasi-Albert network needs p + q <= 1, p={p}, q={q}"
899
+ raise nx.NetworkXError(msg)
900
+
901
+ # Add m initial nodes (m0 in barabasi-speak)
902
+ G = empty_graph(m, create_using)
903
+
904
+ # List of nodes to represent the preferential attachment random selection.
905
+ # At the creation of the graph, all nodes are added to the list
906
+ # so that even nodes that are not connected have a chance to get selected,
907
+ # for rewiring and adding of edges.
908
+ # With each new edge, nodes at the ends of the edge are added to the list.
909
+ attachment_preference = []
910
+ attachment_preference.extend(range(m))
911
+
912
+ # Start adding the other n-m nodes. The first node is m.
913
+ new_node = m
914
+ while new_node < n:
915
+ a_probability = seed.random()
916
+
917
+ # Total number of edges of a Clique of all the nodes
918
+ clique_degree = len(G) - 1
919
+ clique_size = (len(G) * clique_degree) / 2
920
+
921
+ # Adding m new edges, if there is room to add them
922
+ if a_probability < p and G.size() <= clique_size - m:
923
+ # Select the nodes where an edge can be added
924
+ eligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
925
+ for i in range(m):
926
+ # Choosing a random source node from eligible_nodes
927
+ src_node = seed.choice(eligible_nodes)
928
+
929
+ # Picking a possible node that is not 'src_node' or
930
+ # neighbor with 'src_node', with preferential attachment
931
+ prohibited_nodes = list(G[src_node])
932
+ prohibited_nodes.append(src_node)
933
+ # This will raise an exception if the sequence is empty
934
+ dest_node = seed.choice(
935
+ [nd for nd in attachment_preference if nd not in prohibited_nodes]
936
+ )
937
+ # Adding the new edge
938
+ G.add_edge(src_node, dest_node)
939
+
940
+ # Appending both nodes to add to their preferential attachment
941
+ attachment_preference.append(src_node)
942
+ attachment_preference.append(dest_node)
943
+
944
+ # Adjusting the eligible nodes. Degree may be saturated.
945
+ if G.degree(src_node) == clique_degree:
946
+ eligible_nodes.remove(src_node)
947
+ if G.degree(dest_node) == clique_degree and dest_node in eligible_nodes:
948
+ eligible_nodes.remove(dest_node)
949
+
950
+ # Rewiring m edges, if there are enough edges
951
+ elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
952
+ # Selecting nodes that have at least 1 edge but that are not
953
+ # fully connected to ALL other nodes (center of star).
954
+ # These nodes are the pivot nodes of the edges to rewire
955
+ eligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
956
+ for i in range(m):
957
+ # Choosing a random source node
958
+ node = seed.choice(eligible_nodes)
959
+
960
+ # The available nodes do have a neighbor at least.
961
+ nbr_nodes = list(G[node])
962
+
963
+ # Choosing the other end that will get detached
964
+ src_node = seed.choice(nbr_nodes)
965
+
966
+ # Picking a target node that is not 'node' or
967
+ # neighbor with 'node', with preferential attachment
968
+ nbr_nodes.append(node)
969
+ dest_node = seed.choice(
970
+ [nd for nd in attachment_preference if nd not in nbr_nodes]
971
+ )
972
+ # Rewire
973
+ G.remove_edge(node, src_node)
974
+ G.add_edge(node, dest_node)
975
+
976
+ # Adjusting the preferential attachment list
977
+ attachment_preference.remove(src_node)
978
+ attachment_preference.append(dest_node)
979
+
980
+ # Adjusting the eligible nodes.
981
+ # nodes may be saturated or isolated.
982
+ if G.degree(src_node) == 0 and src_node in eligible_nodes:
983
+ eligible_nodes.remove(src_node)
984
+ if dest_node in eligible_nodes:
985
+ if G.degree(dest_node) == clique_degree:
986
+ eligible_nodes.remove(dest_node)
987
+ else:
988
+ if G.degree(dest_node) == 1:
989
+ eligible_nodes.append(dest_node)
990
+
991
+ # Adding new node with m edges
992
+ else:
993
+ # Select the edges' nodes by preferential attachment
994
+ targets = _random_subset(attachment_preference, m, seed)
995
+ G.add_edges_from(zip([new_node] * m, targets))
996
+
997
+ # Add one node to the list for each new edge just created.
998
+ attachment_preference.extend(targets)
999
+ # The new node has m edges to it, plus itself: m + 1
1000
+ attachment_preference.extend([new_node] * (m + 1))
1001
+ new_node += 1
1002
+ return G
1003
+
1004
+
1005
+ @py_random_state(3)
1006
+ @nx._dispatchable(graphs=None, returns_graph=True)
1007
+ def powerlaw_cluster_graph(n, m, p, seed=None, *, create_using=None):
1008
+ """Holme and Kim algorithm for growing graphs with powerlaw
1009
+ degree distribution and approximate average clustering.
1010
+
1011
+ Parameters
1012
+ ----------
1013
+ n : int
1014
+ the number of nodes
1015
+ m : int
1016
+ the number of random edges to add for each new node
1017
+ p : float,
1018
+ Probability of adding a triangle after adding a random edge
1019
+ seed : integer, random_state, or None (default)
1020
+ Indicator of random number generation state.
1021
+ See :ref:`Randomness<randomness>`.
1022
+ create_using : Graph constructor, optional (default=nx.Graph)
1023
+ Graph type to create. If graph instance, then cleared before populated.
1024
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1025
+
1026
+ Notes
1027
+ -----
1028
+ The average clustering has a hard time getting above a certain
1029
+ cutoff that depends on `m`. This cutoff is often quite low. The
1030
+ transitivity (fraction of triangles to possible triangles) seems to
1031
+ decrease with network size.
1032
+
1033
+ It is essentially the Barabási–Albert (BA) growth model with an
1034
+ extra step that each random edge is followed by a chance of
1035
+ making an edge to one of its neighbors too (and thus a triangle).
1036
+
1037
+ This algorithm improves on BA in the sense that it enables a
1038
+ higher average clustering to be attained if desired.
1039
+
1040
+ It seems possible to have a disconnected graph with this algorithm
1041
+ since the initial `m` nodes may not be all linked to a new node
1042
+ on the first iteration like the BA model.
1043
+
1044
+ Raises
1045
+ ------
1046
+ NetworkXError
1047
+ If `m` does not satisfy ``1 <= m <= n`` or `p` does not
1048
+ satisfy ``0 <= p <= 1``.
1049
+
1050
+ References
1051
+ ----------
1052
+ .. [1] P. Holme and B. J. Kim,
1053
+ "Growing scale-free networks with tunable clustering",
1054
+ Phys. Rev. E, 65, 026107, 2002.
1055
+ """
1056
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1057
+ if m < 1 or n < m:
1058
+ raise nx.NetworkXError(f"NetworkXError must have m>1 and m<n, m={m},n={n}")
1059
+
1060
+ if p > 1 or p < 0:
1061
+ raise nx.NetworkXError(f"NetworkXError p must be in [0,1], p={p}")
1062
+
1063
+ G = empty_graph(m, create_using) # add m initial nodes (m0 in barabasi-speak)
1064
+ repeated_nodes = list(G) # list of existing nodes to sample from
1065
+ # with nodes repeated once for each adjacent edge
1066
+ source = m # next node is m
1067
+ while source < n: # Now add the other n-1 nodes
1068
+ possible_targets = _random_subset(repeated_nodes, m, seed)
1069
+ # do one preferential attachment for new node
1070
+ target = possible_targets.pop()
1071
+ G.add_edge(source, target)
1072
+ repeated_nodes.append(target) # add one node to list for each new link
1073
+ count = 1
1074
+ while count < m: # add m-1 more new links
1075
+ if seed.random() < p: # clustering step: add triangle
1076
+ neighborhood = [
1077
+ nbr
1078
+ for nbr in G.neighbors(target)
1079
+ if not G.has_edge(source, nbr) and nbr != source
1080
+ ]
1081
+ if neighborhood: # if there is a neighbor without a link
1082
+ nbr = seed.choice(neighborhood)
1083
+ G.add_edge(source, nbr) # add triangle
1084
+ repeated_nodes.append(nbr)
1085
+ count = count + 1
1086
+ continue # go to top of while loop
1087
+ # else do preferential attachment step if above fails
1088
+ target = possible_targets.pop()
1089
+ G.add_edge(source, target)
1090
+ repeated_nodes.append(target)
1091
+ count = count + 1
1092
+
1093
+ repeated_nodes.extend([source] * m) # add source node to list m times
1094
+ source += 1
1095
+ return G
1096
+
1097
+
1098
+ @py_random_state(3)
1099
+ @nx._dispatchable(graphs=None, returns_graph=True)
1100
+ def random_lobster(n, p1, p2, seed=None, *, create_using=None):
1101
+ """Returns a random lobster graph.
1102
+
1103
+ A lobster is a tree that reduces to a caterpillar when pruning all
1104
+ leaf nodes. A caterpillar is a tree that reduces to a path graph
1105
+ when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
1106
+
1107
+ This implementation iterates on the probabilities `p1` and `p2` to add
1108
+ edges at levels 1 and 2, respectively. Graphs are therefore constructed
1109
+ iteratively with uniform randomness at each level rather than being selected
1110
+ uniformly at random from the set of all possible lobsters.
1111
+
1112
+ Parameters
1113
+ ----------
1114
+ n : int
1115
+ The expected number of nodes in the backbone
1116
+ p1 : float
1117
+ Probability of adding an edge to the backbone
1118
+ p2 : float
1119
+ Probability of adding an edge one level beyond backbone
1120
+ seed : integer, random_state, or None (default)
1121
+ Indicator of random number generation state.
1122
+ See :ref:`Randomness<randomness>`.
1123
+ create_using : Graph constructor, optional (default=nx.Grap)
1124
+ Graph type to create. If graph instance, then cleared before populated.
1125
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1126
+
1127
+ Raises
1128
+ ------
1129
+ NetworkXError
1130
+ If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
1131
+ """
1132
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1133
+ p1, p2 = abs(p1), abs(p2)
1134
+ if any(p >= 1 for p in [p1, p2]):
1135
+ raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
1136
+
1137
+ # a necessary ingredient in any self-respecting graph library
1138
+ llen = int(2 * seed.random() * n + 0.5)
1139
+ L = path_graph(llen, create_using)
1140
+ # build caterpillar: add edges to path graph with probability p1
1141
+ current_node = llen - 1
1142
+ for n in range(llen):
1143
+ while seed.random() < p1: # add fuzzy caterpillar parts
1144
+ current_node += 1
1145
+ L.add_edge(n, current_node)
1146
+ cat_node = current_node
1147
+ while seed.random() < p2: # add crunchy lobster bits
1148
+ current_node += 1
1149
+ L.add_edge(cat_node, current_node)
1150
+ return L # voila, un lobster!
1151
+
1152
+
1153
+ @py_random_state(1)
1154
+ @nx._dispatchable(graphs=None, returns_graph=True)
1155
+ def random_shell_graph(constructor, seed=None, *, create_using=None):
1156
+ """Returns a random shell graph for the constructor given.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ constructor : list of three-tuples
1161
+ Represents the parameters for a shell, starting at the center
1162
+ shell. Each element of the list must be of the form `(n, m,
1163
+ d)`, where `n` is the number of nodes in the shell, `m` is
1164
+ the number of edges in the shell, and `d` is the ratio of
1165
+ inter-shell (next) edges to intra-shell edges. If `d` is zero,
1166
+ there will be no intra-shell edges, and if `d` is one there
1167
+ will be all possible intra-shell edges.
1168
+ seed : integer, random_state, or None (default)
1169
+ Indicator of random number generation state.
1170
+ See :ref:`Randomness<randomness>`.
1171
+ create_using : Graph constructor, optional (default=nx.Graph)
1172
+ Graph type to create. Graph instances are not supported.
1173
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1174
+
1175
+ Examples
1176
+ --------
1177
+ >>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
1178
+ >>> G = nx.random_shell_graph(constructor)
1179
+
1180
+ """
1181
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1182
+ G = empty_graph(0, create_using)
1183
+
1184
+ glist = []
1185
+ intra_edges = []
1186
+ nnodes = 0
1187
+ # create gnm graphs for each shell
1188
+ for n, m, d in constructor:
1189
+ inter_edges = int(m * d)
1190
+ intra_edges.append(m - inter_edges)
1191
+ g = nx.convert_node_labels_to_integers(
1192
+ gnm_random_graph(n, inter_edges, seed=seed, create_using=G.__class__),
1193
+ first_label=nnodes,
1194
+ )
1195
+ glist.append(g)
1196
+ nnodes += n
1197
+ G = nx.operators.union(G, g)
1198
+
1199
+ # connect the shells randomly
1200
+ for gi in range(len(glist) - 1):
1201
+ nlist1 = list(glist[gi])
1202
+ nlist2 = list(glist[gi + 1])
1203
+ total_edges = intra_edges[gi]
1204
+ edge_count = 0
1205
+ while edge_count < total_edges:
1206
+ u = seed.choice(nlist1)
1207
+ v = seed.choice(nlist2)
1208
+ if u == v or G.has_edge(u, v):
1209
+ continue
1210
+ else:
1211
+ G.add_edge(u, v)
1212
+ edge_count = edge_count + 1
1213
+ return G
1214
+
1215
+
1216
+ @py_random_state(2)
1217
+ @nx._dispatchable(graphs=None, returns_graph=True)
1218
+ def random_powerlaw_tree(n, gamma=3, seed=None, tries=100, *, create_using=None):
1219
+ """Returns a tree with a power law degree distribution.
1220
+
1221
+ Parameters
1222
+ ----------
1223
+ n : int
1224
+ The number of nodes.
1225
+ gamma : float
1226
+ Exponent of the power law.
1227
+ seed : integer, random_state, or None (default)
1228
+ Indicator of random number generation state.
1229
+ See :ref:`Randomness<randomness>`.
1230
+ tries : int
1231
+ Number of attempts to adjust the sequence to make it a tree.
1232
+ create_using : Graph constructor, optional (default=nx.Graph)
1233
+ Graph type to create. If graph instance, then cleared before populated.
1234
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1235
+
1236
+ Raises
1237
+ ------
1238
+ NetworkXError
1239
+ If no valid sequence is found within the maximum number of
1240
+ attempts.
1241
+
1242
+ Notes
1243
+ -----
1244
+ A trial power law degree sequence is chosen and then elements are
1245
+ swapped with new elements from a powerlaw distribution until the
1246
+ sequence makes a tree (by checking, for example, that the number of
1247
+ edges is one smaller than the number of nodes).
1248
+
1249
+ """
1250
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1251
+ # This call may raise a NetworkXError if the number of tries is succeeded.
1252
+ seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
1253
+ G = degree_sequence_tree(seq, create_using)
1254
+ return G
1255
+
1256
+
1257
+ @py_random_state(2)
1258
+ @nx._dispatchable(graphs=None)
1259
+ def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
1260
+ """Returns a degree sequence for a tree with a power law distribution.
1261
+
1262
+ Parameters
1263
+ ----------
1264
+ n : int,
1265
+ The number of nodes.
1266
+ gamma : float
1267
+ Exponent of the power law.
1268
+ seed : integer, random_state, or None (default)
1269
+ Indicator of random number generation state.
1270
+ See :ref:`Randomness<randomness>`.
1271
+ tries : int
1272
+ Number of attempts to adjust the sequence to make it a tree.
1273
+
1274
+ Raises
1275
+ ------
1276
+ NetworkXError
1277
+ If no valid sequence is found within the maximum number of
1278
+ attempts.
1279
+
1280
+ Notes
1281
+ -----
1282
+ A trial power law degree sequence is chosen and then elements are
1283
+ swapped with new elements from a power law distribution until
1284
+ the sequence makes a tree (by checking, for example, that the number of
1285
+ edges is one smaller than the number of nodes).
1286
+
1287
+ """
1288
+ # get trial sequence
1289
+ z = nx.utils.powerlaw_sequence(n, exponent=gamma, seed=seed)
1290
+ # round to integer values in the range [0,n]
1291
+ zseq = [min(n, max(round(s), 0)) for s in z]
1292
+
1293
+ # another sequence to swap values from
1294
+ z = nx.utils.powerlaw_sequence(tries, exponent=gamma, seed=seed)
1295
+ # round to integer values in the range [0,n]
1296
+ swap = [min(n, max(round(s), 0)) for s in z]
1297
+
1298
+ for deg in swap:
1299
+ # If this degree sequence can be the degree sequence of a tree, return
1300
+ # it. It can be a tree if the number of edges is one fewer than the
1301
+ # number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
1302
+ # use an equivalent condition below that avoids floating point
1303
+ # operations.
1304
+ if 2 * n - sum(zseq) == 2:
1305
+ return zseq
1306
+ index = seed.randint(0, n - 1)
1307
+ zseq[index] = swap.pop()
1308
+
1309
+ raise nx.NetworkXError(
1310
+ f"Exceeded max ({tries}) attempts for a valid tree sequence."
1311
+ )
1312
+
1313
+
1314
+ @py_random_state(3)
1315
+ @nx._dispatchable(graphs=None, returns_graph=True)
1316
+ def random_kernel_graph(
1317
+ n, kernel_integral, kernel_root=None, seed=None, *, create_using=None
1318
+ ):
1319
+ r"""Returns an random graph based on the specified kernel.
1320
+
1321
+ The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
1322
+ probability specified by a kernel $\kappa(x,y)$ [1]_. The kernel
1323
+ $\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
1324
+ bounded function.
1325
+
1326
+ Parameters
1327
+ ----------
1328
+ n : int
1329
+ The number of nodes
1330
+ kernel_integral : function
1331
+ Function that returns the definite integral of the kernel $\kappa(x,y)$,
1332
+ $F(y,a,b) := \int_a^b \kappa(x,y)dx$
1333
+ kernel_root: function (optional)
1334
+ Function that returns the root $b$ of the equation $F(y,a,b) = r$.
1335
+ If None, the root is found using :func:`scipy.optimize.brentq`
1336
+ (this requires SciPy).
1337
+ seed : integer, random_state, or None (default)
1338
+ Indicator of random number generation state.
1339
+ See :ref:`Randomness<randomness>`.
1340
+ create_using : Graph constructor, optional (default=nx.Graph)
1341
+ Graph type to create. If graph instance, then cleared before populated.
1342
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1343
+
1344
+ Notes
1345
+ -----
1346
+ The kernel is specified through its definite integral which must be
1347
+ provided as one of the arguments. If the integral and root of the
1348
+ kernel integral can be found in $O(1)$ time then this algorithm runs in
1349
+ time $O(n+m)$ where m is the expected number of edges [2]_.
1350
+
1351
+ The nodes are set to integers from $0$ to $n-1$.
1352
+
1353
+ Examples
1354
+ --------
1355
+ Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
1356
+ $\kappa(x,y)=c$ where $c$ is the mean expected degree.
1357
+
1358
+ >>> def integral(u, w, z):
1359
+ ... return c * (z - w)
1360
+ >>> def root(u, w, r):
1361
+ ... return r / c + w
1362
+ >>> c = 1
1363
+ >>> graph = nx.random_kernel_graph(1000, integral, root)
1364
+
1365
+ See Also
1366
+ --------
1367
+ gnp_random_graph
1368
+ expected_degree_graph
1369
+
1370
+ References
1371
+ ----------
1372
+ .. [1] Bollobás, Béla, Janson, S. and Riordan, O.
1373
+ "The phase transition in inhomogeneous random graphs",
1374
+ *Random Structures Algorithms*, 31, 3--122, 2007.
1375
+
1376
+ .. [2] Hagberg A, Lemons N (2015),
1377
+ "Fast Generation of Sparse Random Kernel Graphs".
1378
+ PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
1379
+ """
1380
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1381
+ if kernel_root is None:
1382
+ import scipy as sp
1383
+
1384
+ def kernel_root(y, a, r):
1385
+ def my_function(b):
1386
+ return kernel_integral(y, a, b) - r
1387
+
1388
+ return sp.optimize.brentq(my_function, a, 1)
1389
+
1390
+ graph = nx.empty_graph(create_using=create_using)
1391
+ graph.add_nodes_from(range(n))
1392
+ (i, j) = (1, 1)
1393
+ while i < n:
1394
+ r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
1395
+ if kernel_integral(i / n, j / n, 1) <= r:
1396
+ i, j = i + 1, i + 1
1397
+ else:
1398
+ j = math.ceil(n * kernel_root(i / n, j / n, r))
1399
+ graph.add_edge(i - 1, j - 1)
1400
+ return graph
wemm/lib/python3.10/site-packages/networkx/generators/small.py ADDED
@@ -0,0 +1,993 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various small and named graphs, together with some compact generators.
3
+
4
+ """
5
+
6
+ __all__ = [
7
+ "LCF_graph",
8
+ "bull_graph",
9
+ "chvatal_graph",
10
+ "cubical_graph",
11
+ "desargues_graph",
12
+ "diamond_graph",
13
+ "dodecahedral_graph",
14
+ "frucht_graph",
15
+ "heawood_graph",
16
+ "hoffman_singleton_graph",
17
+ "house_graph",
18
+ "house_x_graph",
19
+ "icosahedral_graph",
20
+ "krackhardt_kite_graph",
21
+ "moebius_kantor_graph",
22
+ "octahedral_graph",
23
+ "pappus_graph",
24
+ "petersen_graph",
25
+ "sedgewick_maze_graph",
26
+ "tetrahedral_graph",
27
+ "truncated_cube_graph",
28
+ "truncated_tetrahedron_graph",
29
+ "tutte_graph",
30
+ ]
31
+
32
+ from functools import wraps
33
+
34
+ import networkx as nx
35
+ from networkx.exception import NetworkXError
36
+ from networkx.generators.classic import (
37
+ complete_graph,
38
+ cycle_graph,
39
+ empty_graph,
40
+ path_graph,
41
+ )
42
+
43
+
44
+ def _raise_on_directed(func):
45
+ """
46
+ A decorator which inspects the `create_using` argument and raises a
47
+ NetworkX exception when `create_using` is a DiGraph (class or instance) for
48
+ graph generators that do not support directed outputs.
49
+ """
50
+
51
+ @wraps(func)
52
+ def wrapper(*args, **kwargs):
53
+ if kwargs.get("create_using") is not None:
54
+ G = nx.empty_graph(create_using=kwargs["create_using"])
55
+ if G.is_directed():
56
+ raise NetworkXError("Directed Graph not supported")
57
+ return func(*args, **kwargs)
58
+
59
+ return wrapper
60
+
61
+
62
+ @nx._dispatchable(graphs=None, returns_graph=True)
63
+ def LCF_graph(n, shift_list, repeats, create_using=None):
64
+ """
65
+ Return the cubic graph specified in LCF notation.
66
+
67
+ LCF (Lederberg-Coxeter-Fruchte) notation[1]_ is a compressed
68
+ notation used in the generation of various cubic Hamiltonian
69
+ graphs of high symmetry. See, for example, `dodecahedral_graph`,
70
+ `desargues_graph`, `heawood_graph` and `pappus_graph`.
71
+
72
+ Nodes are drawn from ``range(n)``. Each node ``n_i`` is connected with
73
+ node ``n_i + shift % n`` where ``shift`` is given by cycling through
74
+ the input `shift_list` `repeat` s times.
75
+
76
+ Parameters
77
+ ----------
78
+ n : int
79
+ The starting graph is the `n`-cycle with nodes ``0, ..., n-1``.
80
+ The null graph is returned if `n` < 1.
81
+
82
+ shift_list : list
83
+ A list of integer shifts mod `n`, ``[s1, s2, .., sk]``
84
+
85
+ repeats : int
86
+ Integer specifying the number of times that shifts in `shift_list`
87
+ are successively applied to each current node in the n-cycle
88
+ to generate an edge between ``n_current`` and ``n_current + shift mod n``.
89
+
90
+ Returns
91
+ -------
92
+ G : Graph
93
+ A graph instance created from the specified LCF notation.
94
+
95
+ Examples
96
+ --------
97
+ The utility graph $K_{3,3}$
98
+
99
+ >>> G = nx.LCF_graph(6, [3, -3], 3)
100
+ >>> G.edges()
101
+ EdgeView([(0, 1), (0, 5), (0, 3), (1, 2), (1, 4), (2, 3), (2, 5), (3, 4), (4, 5)])
102
+
103
+ The Heawood graph:
104
+
105
+ >>> G = nx.LCF_graph(14, [5, -5], 7)
106
+ >>> nx.is_isomorphic(G, nx.heawood_graph())
107
+ True
108
+
109
+ References
110
+ ----------
111
+ .. [1] https://en.wikipedia.org/wiki/LCF_notation
112
+
113
+ """
114
+ if n <= 0:
115
+ return empty_graph(0, create_using)
116
+
117
+ # start with the n-cycle
118
+ G = cycle_graph(n, create_using)
119
+ if G.is_directed():
120
+ raise NetworkXError("Directed Graph not supported")
121
+ G.name = "LCF_graph"
122
+ nodes = sorted(G)
123
+
124
+ n_extra_edges = repeats * len(shift_list)
125
+ # edges are added n_extra_edges times
126
+ # (not all of these need be new)
127
+ if n_extra_edges < 1:
128
+ return G
129
+
130
+ for i in range(n_extra_edges):
131
+ shift = shift_list[i % len(shift_list)] # cycle through shift_list
132
+ v1 = nodes[i % n] # cycle repeatedly through nodes
133
+ v2 = nodes[(i + shift) % n]
134
+ G.add_edge(v1, v2)
135
+ return G
136
+
137
+
138
+ # -------------------------------------------------------------------------------
139
+ # Various small and named graphs
140
+ # -------------------------------------------------------------------------------
141
+
142
+
143
+ @_raise_on_directed
144
+ @nx._dispatchable(graphs=None, returns_graph=True)
145
+ def bull_graph(create_using=None):
146
+ """
147
+ Returns the Bull Graph
148
+
149
+ The Bull Graph has 5 nodes and 5 edges. It is a planar undirected
150
+ graph in the form of a triangle with two disjoint pendant edges [1]_
151
+ The name comes from the triangle and pendant edges representing
152
+ respectively the body and legs of a bull.
153
+
154
+ Parameters
155
+ ----------
156
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
157
+ Graph type to create. If graph instance, then cleared before populated.
158
+
159
+ Returns
160
+ -------
161
+ G : networkx Graph
162
+ A bull graph with 5 nodes
163
+
164
+ References
165
+ ----------
166
+ .. [1] https://en.wikipedia.org/wiki/Bull_graph.
167
+
168
+ """
169
+ G = nx.from_dict_of_lists(
170
+ {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 4], 3: [1], 4: [2]},
171
+ create_using=create_using,
172
+ )
173
+ G.name = "Bull Graph"
174
+ return G
175
+
176
+
177
+ @_raise_on_directed
178
+ @nx._dispatchable(graphs=None, returns_graph=True)
179
+ def chvatal_graph(create_using=None):
180
+ """
181
+ Returns the Chvátal Graph
182
+
183
+ The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_.
184
+ It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized
185
+ LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_.
186
+
187
+ Parameters
188
+ ----------
189
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
190
+ Graph type to create. If graph instance, then cleared before populated.
191
+
192
+ Returns
193
+ -------
194
+ G : networkx Graph
195
+ The Chvátal graph with 12 nodes and 24 edges
196
+
197
+ References
198
+ ----------
199
+ .. [1] https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph
200
+ .. [2] https://mathworld.wolfram.com/ChvatalGraph.html
201
+
202
+ """
203
+ G = nx.from_dict_of_lists(
204
+ {
205
+ 0: [1, 4, 6, 9],
206
+ 1: [2, 5, 7],
207
+ 2: [3, 6, 8],
208
+ 3: [4, 7, 9],
209
+ 4: [5, 8],
210
+ 5: [10, 11],
211
+ 6: [10, 11],
212
+ 7: [8, 11],
213
+ 8: [10],
214
+ 9: [10, 11],
215
+ },
216
+ create_using=create_using,
217
+ )
218
+ G.name = "Chvatal Graph"
219
+ return G
220
+
221
+
222
+ @_raise_on_directed
223
+ @nx._dispatchable(graphs=None, returns_graph=True)
224
+ def cubical_graph(create_using=None):
225
+ """
226
+ Returns the 3-regular Platonic Cubical Graph
227
+
228
+ The skeleton of the cube (the nodes and edges) form a graph, with 8
229
+ nodes, and 12 edges. It is a special case of the hypercube graph.
230
+ It is one of 5 Platonic graphs, each a skeleton of its
231
+ Platonic solid [1]_.
232
+ Such graphs arise in parallel processing in computers.
233
+
234
+ Parameters
235
+ ----------
236
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
237
+ Graph type to create. If graph instance, then cleared before populated.
238
+
239
+ Returns
240
+ -------
241
+ G : networkx Graph
242
+ A cubical graph with 8 nodes and 12 edges
243
+
244
+ References
245
+ ----------
246
+ .. [1] https://en.wikipedia.org/wiki/Cube#Cubical_graph
247
+
248
+ """
249
+ G = nx.from_dict_of_lists(
250
+ {
251
+ 0: [1, 3, 4],
252
+ 1: [0, 2, 7],
253
+ 2: [1, 3, 6],
254
+ 3: [0, 2, 5],
255
+ 4: [0, 5, 7],
256
+ 5: [3, 4, 6],
257
+ 6: [2, 5, 7],
258
+ 7: [1, 4, 6],
259
+ },
260
+ create_using=create_using,
261
+ )
262
+ G.name = "Platonic Cubical Graph"
263
+ return G
264
+
265
+
266
+ @nx._dispatchable(graphs=None, returns_graph=True)
267
+ def desargues_graph(create_using=None):
268
+ """
269
+ Returns the Desargues Graph
270
+
271
+ The Desargues Graph is a non-planar, distance-transitive cubic graph
272
+ with 20 nodes and 30 edges [1]_.
273
+ It is a symmetric graph. It can be represented in LCF notation
274
+ as [5,-5,9,-9]^5 [2]_.
275
+
276
+ Parameters
277
+ ----------
278
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
279
+ Graph type to create. If graph instance, then cleared before populated.
280
+
281
+ Returns
282
+ -------
283
+ G : networkx Graph
284
+ Desargues Graph with 20 nodes and 30 edges
285
+
286
+ References
287
+ ----------
288
+ .. [1] https://en.wikipedia.org/wiki/Desargues_graph
289
+ .. [2] https://mathworld.wolfram.com/DesarguesGraph.html
290
+ """
291
+ G = LCF_graph(20, [5, -5, 9, -9], 5, create_using)
292
+ G.name = "Desargues Graph"
293
+ return G
294
+
295
+
296
+ @_raise_on_directed
297
+ @nx._dispatchable(graphs=None, returns_graph=True)
298
+ def diamond_graph(create_using=None):
299
+ """
300
+ Returns the Diamond graph
301
+
302
+ The Diamond Graph is planar undirected graph with 4 nodes and 5 edges.
303
+ It is also sometimes known as the double triangle graph or kite graph [1]_.
304
+
305
+ Parameters
306
+ ----------
307
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
308
+ Graph type to create. If graph instance, then cleared before populated.
309
+
310
+ Returns
311
+ -------
312
+ G : networkx Graph
313
+ Diamond Graph with 4 nodes and 5 edges
314
+
315
+ References
316
+ ----------
317
+ .. [1] https://mathworld.wolfram.com/DiamondGraph.html
318
+ """
319
+ G = nx.from_dict_of_lists(
320
+ {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 3], 3: [1, 2]}, create_using=create_using
321
+ )
322
+ G.name = "Diamond Graph"
323
+ return G
324
+
325
+
326
+ @nx._dispatchable(graphs=None, returns_graph=True)
327
+ def dodecahedral_graph(create_using=None):
328
+ """
329
+ Returns the Platonic Dodecahedral graph.
330
+
331
+ The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the
332
+ dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_.
333
+ It can be described in LCF notation as:
334
+ ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_.
335
+
336
+ Parameters
337
+ ----------
338
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
339
+ Graph type to create. If graph instance, then cleared before populated.
340
+
341
+ Returns
342
+ -------
343
+ G : networkx Graph
344
+ Dodecahedral Graph with 20 nodes and 30 edges
345
+
346
+ References
347
+ ----------
348
+ .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph
349
+ .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html
350
+
351
+ """
352
+ G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using)
353
+ G.name = "Dodecahedral Graph"
354
+ return G
355
+
356
+
357
+ @nx._dispatchable(graphs=None, returns_graph=True)
358
+ def frucht_graph(create_using=None):
359
+ """
360
+ Returns the Frucht Graph.
361
+
362
+ The Frucht Graph is the smallest cubical graph whose
363
+ automorphism group consists only of the identity element [1]_.
364
+ It has 12 nodes and 18 edges and no nontrivial symmetries.
365
+ It is planar and Hamiltonian [2]_.
366
+
367
+ Parameters
368
+ ----------
369
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
370
+ Graph type to create. If graph instance, then cleared before populated.
371
+
372
+ Returns
373
+ -------
374
+ G : networkx Graph
375
+ Frucht Graph with 12 nodes and 18 edges
376
+
377
+ References
378
+ ----------
379
+ .. [1] https://en.wikipedia.org/wiki/Frucht_graph
380
+ .. [2] https://mathworld.wolfram.com/FruchtGraph.html
381
+
382
+ """
383
+ G = cycle_graph(7, create_using)
384
+ G.add_edges_from(
385
+ [
386
+ [0, 7],
387
+ [1, 7],
388
+ [2, 8],
389
+ [3, 9],
390
+ [4, 9],
391
+ [5, 10],
392
+ [6, 10],
393
+ [7, 11],
394
+ [8, 11],
395
+ [8, 9],
396
+ [10, 11],
397
+ ]
398
+ )
399
+
400
+ G.name = "Frucht Graph"
401
+ return G
402
+
403
+
404
+ @nx._dispatchable(graphs=None, returns_graph=True)
405
+ def heawood_graph(create_using=None):
406
+ """
407
+ Returns the Heawood Graph, a (3,6) cage.
408
+
409
+ The Heawood Graph is an undirected graph with 14 nodes and 21 edges,
410
+ named after Percy John Heawood [1]_.
411
+ It is cubic symmetric, nonplanar, Hamiltonian, and can be represented
412
+ in LCF notation as ``[5,-5]^7`` [2]_.
413
+ It is the unique (3,6)-cage: the regular cubic graph of girth 6 with
414
+ minimal number of vertices [3]_.
415
+
416
+ Parameters
417
+ ----------
418
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
419
+ Graph type to create. If graph instance, then cleared before populated.
420
+
421
+ Returns
422
+ -------
423
+ G : networkx Graph
424
+ Heawood Graph with 14 nodes and 21 edges
425
+
426
+ References
427
+ ----------
428
+ .. [1] https://en.wikipedia.org/wiki/Heawood_graph
429
+ .. [2] https://mathworld.wolfram.com/HeawoodGraph.html
430
+ .. [3] https://www.win.tue.nl/~aeb/graphs/Heawood.html
431
+
432
+ """
433
+ G = LCF_graph(14, [5, -5], 7, create_using)
434
+ G.name = "Heawood Graph"
435
+ return G
436
+
437
+
438
+ @nx._dispatchable(graphs=None, returns_graph=True)
439
+ def hoffman_singleton_graph():
440
+ """
441
+ Returns the Hoffman-Singleton Graph.
442
+
443
+ The Hoffman–Singleton graph is a symmetrical undirected graph
444
+ with 50 nodes and 175 edges.
445
+ All indices lie in ``Z % 5``: that is, the integers mod 5 [1]_.
446
+ It is the only regular graph of vertex degree 7, diameter 2, and girth 5.
447
+ It is the unique (7,5)-cage graph and Moore graph, and contains many
448
+ copies of the Petersen graph [2]_.
449
+
450
+ Returns
451
+ -------
452
+ G : networkx Graph
453
+ Hoffman–Singleton Graph with 50 nodes and 175 edges
454
+
455
+ Notes
456
+ -----
457
+ Constructed from pentagon and pentagram as follows: Take five pentagons $P_h$
458
+ and five pentagrams $Q_i$ . Join vertex $j$ of $P_h$ to vertex $h·i+j$ of $Q_i$ [3]_.
459
+
460
+ References
461
+ ----------
462
+ .. [1] https://blogs.ams.org/visualinsight/2016/02/01/hoffman-singleton-graph/
463
+ .. [2] https://mathworld.wolfram.com/Hoffman-SingletonGraph.html
464
+ .. [3] https://en.wikipedia.org/wiki/Hoffman%E2%80%93Singleton_graph
465
+
466
+ """
467
+ G = nx.Graph()
468
+ for i in range(5):
469
+ for j in range(5):
470
+ G.add_edge(("pentagon", i, j), ("pentagon", i, (j - 1) % 5))
471
+ G.add_edge(("pentagon", i, j), ("pentagon", i, (j + 1) % 5))
472
+ G.add_edge(("pentagram", i, j), ("pentagram", i, (j - 2) % 5))
473
+ G.add_edge(("pentagram", i, j), ("pentagram", i, (j + 2) % 5))
474
+ for k in range(5):
475
+ G.add_edge(("pentagon", i, j), ("pentagram", k, (i * k + j) % 5))
476
+ G = nx.convert_node_labels_to_integers(G)
477
+ G.name = "Hoffman-Singleton Graph"
478
+ return G
479
+
480
+
481
+ @_raise_on_directed
482
+ @nx._dispatchable(graphs=None, returns_graph=True)
483
+ def house_graph(create_using=None):
484
+ """
485
+ Returns the House graph (square with triangle on top)
486
+
487
+ The house graph is a simple undirected graph with
488
+ 5 nodes and 6 edges [1]_.
489
+
490
+ Parameters
491
+ ----------
492
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
493
+ Graph type to create. If graph instance, then cleared before populated.
494
+
495
+ Returns
496
+ -------
497
+ G : networkx Graph
498
+ House graph in the form of a square with a triangle on top
499
+
500
+ References
501
+ ----------
502
+ .. [1] https://mathworld.wolfram.com/HouseGraph.html
503
+ """
504
+ G = nx.from_dict_of_lists(
505
+ {0: [1, 2], 1: [0, 3], 2: [0, 3, 4], 3: [1, 2, 4], 4: [2, 3]},
506
+ create_using=create_using,
507
+ )
508
+ G.name = "House Graph"
509
+ return G
510
+
511
+
512
+ @_raise_on_directed
513
+ @nx._dispatchable(graphs=None, returns_graph=True)
514
+ def house_x_graph(create_using=None):
515
+ """
516
+ Returns the House graph with a cross inside the house square.
517
+
518
+ The House X-graph is the House graph plus the two edges connecting diagonally
519
+ opposite vertices of the square base. It is also one of the two graphs
520
+ obtained by removing two edges from the pentatope graph [1]_.
521
+
522
+ Parameters
523
+ ----------
524
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
525
+ Graph type to create. If graph instance, then cleared before populated.
526
+
527
+ Returns
528
+ -------
529
+ G : networkx Graph
530
+ House graph with diagonal vertices connected
531
+
532
+ References
533
+ ----------
534
+ .. [1] https://mathworld.wolfram.com/HouseGraph.html
535
+ """
536
+ G = house_graph(create_using)
537
+ G.add_edges_from([(0, 3), (1, 2)])
538
+ G.name = "House-with-X-inside Graph"
539
+ return G
540
+
541
+
542
+ @_raise_on_directed
543
+ @nx._dispatchable(graphs=None, returns_graph=True)
544
+ def icosahedral_graph(create_using=None):
545
+ """
546
+ Returns the Platonic Icosahedral graph.
547
+
548
+ The icosahedral graph has 12 nodes and 30 edges. It is a Platonic graph
549
+ whose nodes have the connectivity of the icosahedron. It is undirected,
550
+ regular and Hamiltonian [1]_.
551
+
552
+ Parameters
553
+ ----------
554
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
555
+ Graph type to create. If graph instance, then cleared before populated.
556
+
557
+ Returns
558
+ -------
559
+ G : networkx Graph
560
+ Icosahedral graph with 12 nodes and 30 edges.
561
+
562
+ References
563
+ ----------
564
+ .. [1] https://mathworld.wolfram.com/IcosahedralGraph.html
565
+ """
566
+ G = nx.from_dict_of_lists(
567
+ {
568
+ 0: [1, 5, 7, 8, 11],
569
+ 1: [2, 5, 6, 8],
570
+ 2: [3, 6, 8, 9],
571
+ 3: [4, 6, 9, 10],
572
+ 4: [5, 6, 10, 11],
573
+ 5: [6, 11],
574
+ 7: [8, 9, 10, 11],
575
+ 8: [9],
576
+ 9: [10],
577
+ 10: [11],
578
+ },
579
+ create_using=create_using,
580
+ )
581
+ G.name = "Platonic Icosahedral Graph"
582
+ return G
583
+
584
+
585
+ @_raise_on_directed
586
+ @nx._dispatchable(graphs=None, returns_graph=True)
587
+ def krackhardt_kite_graph(create_using=None):
588
+ """
589
+ Returns the Krackhardt Kite Social Network.
590
+
591
+ A 10 actor social network introduced by David Krackhardt
592
+ to illustrate different centrality measures [1]_.
593
+
594
+ Parameters
595
+ ----------
596
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
597
+ Graph type to create. If graph instance, then cleared before populated.
598
+
599
+ Returns
600
+ -------
601
+ G : networkx Graph
602
+ Krackhardt Kite graph with 10 nodes and 18 edges
603
+
604
+ Notes
605
+ -----
606
+ The traditional labeling is:
607
+ Andre=1, Beverley=2, Carol=3, Diane=4,
608
+ Ed=5, Fernando=6, Garth=7, Heather=8, Ike=9, Jane=10.
609
+
610
+ References
611
+ ----------
612
+ .. [1] Krackhardt, David. "Assessing the Political Landscape: Structure,
613
+ Cognition, and Power in Organizations". Administrative Science Quarterly.
614
+ 35 (2): 342–369. doi:10.2307/2393394. JSTOR 2393394. June 1990.
615
+
616
+ """
617
+ G = nx.from_dict_of_lists(
618
+ {
619
+ 0: [1, 2, 3, 5],
620
+ 1: [0, 3, 4, 6],
621
+ 2: [0, 3, 5],
622
+ 3: [0, 1, 2, 4, 5, 6],
623
+ 4: [1, 3, 6],
624
+ 5: [0, 2, 3, 6, 7],
625
+ 6: [1, 3, 4, 5, 7],
626
+ 7: [5, 6, 8],
627
+ 8: [7, 9],
628
+ 9: [8],
629
+ },
630
+ create_using=create_using,
631
+ )
632
+ G.name = "Krackhardt Kite Social Network"
633
+ return G
634
+
635
+
636
+ @nx._dispatchable(graphs=None, returns_graph=True)
637
+ def moebius_kantor_graph(create_using=None):
638
+ """
639
+ Returns the Moebius-Kantor graph.
640
+
641
+ The Möbius-Kantor graph is the cubic symmetric graph on 16 nodes.
642
+ Its LCF notation is [5,-5]^8, and it is isomorphic to the generalized
643
+ Petersen graph [1]_.
644
+
645
+ Parameters
646
+ ----------
647
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
648
+ Graph type to create. If graph instance, then cleared before populated.
649
+
650
+ Returns
651
+ -------
652
+ G : networkx Graph
653
+ Moebius-Kantor graph
654
+
655
+ References
656
+ ----------
657
+ .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph
658
+
659
+ """
660
+ G = LCF_graph(16, [5, -5], 8, create_using)
661
+ G.name = "Moebius-Kantor Graph"
662
+ return G
663
+
664
+
665
+ @_raise_on_directed
666
+ @nx._dispatchable(graphs=None, returns_graph=True)
667
+ def octahedral_graph(create_using=None):
668
+ """
669
+ Returns the Platonic Octahedral graph.
670
+
671
+ The octahedral graph is the 6-node 12-edge Platonic graph having the
672
+ connectivity of the octahedron [1]_. If 6 couples go to a party,
673
+ and each person shakes hands with every person except his or her partner,
674
+ then this graph describes the set of handshakes that take place;
675
+ for this reason it is also called the cocktail party graph [2]_.
676
+
677
+ Parameters
678
+ ----------
679
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
680
+ Graph type to create. If graph instance, then cleared before populated.
681
+
682
+ Returns
683
+ -------
684
+ G : networkx Graph
685
+ Octahedral graph
686
+
687
+ References
688
+ ----------
689
+ .. [1] https://mathworld.wolfram.com/OctahedralGraph.html
690
+ .. [2] https://en.wikipedia.org/wiki/Tur%C3%A1n_graph#Special_cases
691
+
692
+ """
693
+ G = nx.from_dict_of_lists(
694
+ {0: [1, 2, 3, 4], 1: [2, 3, 5], 2: [4, 5], 3: [4, 5], 4: [5]},
695
+ create_using=create_using,
696
+ )
697
+ G.name = "Platonic Octahedral Graph"
698
+ return G
699
+
700
+
701
+ @nx._dispatchable(graphs=None, returns_graph=True)
702
+ def pappus_graph():
703
+ """
704
+ Returns the Pappus graph.
705
+
706
+ The Pappus graph is a cubic symmetric distance-regular graph with 18 nodes
707
+ and 27 edges. It is Hamiltonian and can be represented in LCF notation as
708
+ [5,7,-7,7,-7,-5]^3 [1]_.
709
+
710
+ Returns
711
+ -------
712
+ G : networkx Graph
713
+ Pappus graph
714
+
715
+ References
716
+ ----------
717
+ .. [1] https://en.wikipedia.org/wiki/Pappus_graph
718
+ """
719
+ G = LCF_graph(18, [5, 7, -7, 7, -7, -5], 3)
720
+ G.name = "Pappus Graph"
721
+ return G
722
+
723
+
724
+ @_raise_on_directed
725
+ @nx._dispatchable(graphs=None, returns_graph=True)
726
+ def petersen_graph(create_using=None):
727
+ """
728
+ Returns the Petersen graph.
729
+
730
+ The Peterson graph is a cubic, undirected graph with 10 nodes and 15 edges [1]_.
731
+ Julius Petersen constructed the graph as the smallest counterexample
732
+ against the claim that a connected bridgeless cubic graph
733
+ has an edge colouring with three colours [2]_.
734
+
735
+ Parameters
736
+ ----------
737
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
738
+ Graph type to create. If graph instance, then cleared before populated.
739
+
740
+ Returns
741
+ -------
742
+ G : networkx Graph
743
+ Petersen graph
744
+
745
+ References
746
+ ----------
747
+ .. [1] https://en.wikipedia.org/wiki/Petersen_graph
748
+ .. [2] https://www.win.tue.nl/~aeb/drg/graphs/Petersen.html
749
+ """
750
+ G = nx.from_dict_of_lists(
751
+ {
752
+ 0: [1, 4, 5],
753
+ 1: [0, 2, 6],
754
+ 2: [1, 3, 7],
755
+ 3: [2, 4, 8],
756
+ 4: [3, 0, 9],
757
+ 5: [0, 7, 8],
758
+ 6: [1, 8, 9],
759
+ 7: [2, 5, 9],
760
+ 8: [3, 5, 6],
761
+ 9: [4, 6, 7],
762
+ },
763
+ create_using=create_using,
764
+ )
765
+ G.name = "Petersen Graph"
766
+ return G
767
+
768
+
769
+ @nx._dispatchable(graphs=None, returns_graph=True)
770
+ def sedgewick_maze_graph(create_using=None):
771
+ """
772
+ Return a small maze with a cycle.
773
+
774
+ This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph
775
+ Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_.
776
+ Nodes are numbered 0,..,7
777
+
778
+ Parameters
779
+ ----------
780
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
781
+ Graph type to create. If graph instance, then cleared before populated.
782
+
783
+ Returns
784
+ -------
785
+ G : networkx Graph
786
+ Small maze with a cycle
787
+
788
+ References
789
+ ----------
790
+ .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick
791
+ """
792
+ G = empty_graph(0, create_using)
793
+ G.add_nodes_from(range(8))
794
+ G.add_edges_from([[0, 2], [0, 7], [0, 5]])
795
+ G.add_edges_from([[1, 7], [2, 6]])
796
+ G.add_edges_from([[3, 4], [3, 5]])
797
+ G.add_edges_from([[4, 5], [4, 7], [4, 6]])
798
+ G.name = "Sedgewick Maze"
799
+ return G
800
+
801
+
802
+ @nx._dispatchable(graphs=None, returns_graph=True)
803
+ def tetrahedral_graph(create_using=None):
804
+ """
805
+ Returns the 3-regular Platonic Tetrahedral graph.
806
+
807
+ Tetrahedral graph has 4 nodes and 6 edges. It is a
808
+ special case of the complete graph, K4, and wheel graph, W4.
809
+ It is one of the 5 platonic graphs [1]_.
810
+
811
+ Parameters
812
+ ----------
813
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
814
+ Graph type to create. If graph instance, then cleared before populated.
815
+
816
+ Returns
817
+ -------
818
+ G : networkx Graph
819
+ Tetrahedral Graph
820
+
821
+ References
822
+ ----------
823
+ .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph
824
+
825
+ """
826
+ G = complete_graph(4, create_using)
827
+ G.name = "Platonic Tetrahedral Graph"
828
+ return G
829
+
830
+
831
+ @_raise_on_directed
832
+ @nx._dispatchable(graphs=None, returns_graph=True)
833
+ def truncated_cube_graph(create_using=None):
834
+ """
835
+ Returns the skeleton of the truncated cube.
836
+
837
+ The truncated cube is an Archimedean solid with 14 regular
838
+ faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_.
839
+ The truncated cube is created by truncating (cutting off) the tips
840
+ of the cube one third of the way into each edge [2]_.
841
+
842
+ Parameters
843
+ ----------
844
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
845
+ Graph type to create. If graph instance, then cleared before populated.
846
+
847
+ Returns
848
+ -------
849
+ G : networkx Graph
850
+ Skeleton of the truncated cube
851
+
852
+ References
853
+ ----------
854
+ .. [1] https://en.wikipedia.org/wiki/Truncated_cube
855
+ .. [2] https://www.coolmath.com/reference/polyhedra-truncated-cube
856
+
857
+ """
858
+ G = nx.from_dict_of_lists(
859
+ {
860
+ 0: [1, 2, 4],
861
+ 1: [11, 14],
862
+ 2: [3, 4],
863
+ 3: [6, 8],
864
+ 4: [5],
865
+ 5: [16, 18],
866
+ 6: [7, 8],
867
+ 7: [10, 12],
868
+ 8: [9],
869
+ 9: [17, 20],
870
+ 10: [11, 12],
871
+ 11: [14],
872
+ 12: [13],
873
+ 13: [21, 22],
874
+ 14: [15],
875
+ 15: [19, 23],
876
+ 16: [17, 18],
877
+ 17: [20],
878
+ 18: [19],
879
+ 19: [23],
880
+ 20: [21],
881
+ 21: [22],
882
+ 22: [23],
883
+ },
884
+ create_using=create_using,
885
+ )
886
+ G.name = "Truncated Cube Graph"
887
+ return G
888
+
889
+
890
+ @nx._dispatchable(graphs=None, returns_graph=True)
891
+ def truncated_tetrahedron_graph(create_using=None):
892
+ """
893
+ Returns the skeleton of the truncated Platonic tetrahedron.
894
+
895
+ The truncated tetrahedron is an Archimedean solid with 4 regular hexagonal faces,
896
+ 4 equilateral triangle faces, 12 nodes and 18 edges. It can be constructed by truncating
897
+ all 4 vertices of a regular tetrahedron at one third of the original edge length [1]_.
898
+
899
+ Parameters
900
+ ----------
901
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
902
+ Graph type to create. If graph instance, then cleared before populated.
903
+
904
+ Returns
905
+ -------
906
+ G : networkx Graph
907
+ Skeleton of the truncated tetrahedron
908
+
909
+ References
910
+ ----------
911
+ .. [1] https://en.wikipedia.org/wiki/Truncated_tetrahedron
912
+
913
+ """
914
+ G = path_graph(12, create_using)
915
+ G.add_edges_from([(0, 2), (0, 9), (1, 6), (3, 11), (4, 11), (5, 7), (8, 10)])
916
+ G.name = "Truncated Tetrahedron Graph"
917
+ return G
918
+
919
+
920
+ @_raise_on_directed
921
+ @nx._dispatchable(graphs=None, returns_graph=True)
922
+ def tutte_graph(create_using=None):
923
+ """
924
+ Returns the Tutte graph.
925
+
926
+ The Tutte graph is a cubic polyhedral, non-Hamiltonian graph. It has
927
+ 46 nodes and 69 edges.
928
+ It is a counterexample to Tait's conjecture that every 3-regular polyhedron
929
+ has a Hamiltonian cycle.
930
+ It can be realized geometrically from a tetrahedron by multiply truncating
931
+ three of its vertices [1]_.
932
+
933
+ Parameters
934
+ ----------
935
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
936
+ Graph type to create. If graph instance, then cleared before populated.
937
+
938
+ Returns
939
+ -------
940
+ G : networkx Graph
941
+ Tutte graph
942
+
943
+ References
944
+ ----------
945
+ .. [1] https://en.wikipedia.org/wiki/Tutte_graph
946
+ """
947
+ G = nx.from_dict_of_lists(
948
+ {
949
+ 0: [1, 2, 3],
950
+ 1: [4, 26],
951
+ 2: [10, 11],
952
+ 3: [18, 19],
953
+ 4: [5, 33],
954
+ 5: [6, 29],
955
+ 6: [7, 27],
956
+ 7: [8, 14],
957
+ 8: [9, 38],
958
+ 9: [10, 37],
959
+ 10: [39],
960
+ 11: [12, 39],
961
+ 12: [13, 35],
962
+ 13: [14, 15],
963
+ 14: [34],
964
+ 15: [16, 22],
965
+ 16: [17, 44],
966
+ 17: [18, 43],
967
+ 18: [45],
968
+ 19: [20, 45],
969
+ 20: [21, 41],
970
+ 21: [22, 23],
971
+ 22: [40],
972
+ 23: [24, 27],
973
+ 24: [25, 32],
974
+ 25: [26, 31],
975
+ 26: [33],
976
+ 27: [28],
977
+ 28: [29, 32],
978
+ 29: [30],
979
+ 30: [31, 33],
980
+ 31: [32],
981
+ 34: [35, 38],
982
+ 35: [36],
983
+ 36: [37, 39],
984
+ 37: [38],
985
+ 40: [41, 44],
986
+ 41: [42],
987
+ 42: [43, 45],
988
+ 43: [44],
989
+ },
990
+ create_using=create_using,
991
+ )
992
+ G.name = "Tutte's Graph"
993
+ return G