applied-ai-018 commited on
Commit
a327798
·
verified ·
1 Parent(s): 735dcb6

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. env-llmeval/lib/python3.10/site-packages/networkx/drawing/layout.py +1358 -0
  2. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py +292 -0
  9. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py +515 -0
  10. env-llmeval/lib/python3.10/site-packages/networkx/generators/__init__.py +33 -0
  11. env-llmeval/lib/python3.10/site-packages/networkx/generators/atlas.py +179 -0
  12. env-llmeval/lib/python3.10/site-packages/networkx/generators/classic.py +1054 -0
  13. env-llmeval/lib/python3.10/site-packages/networkx/generators/cographs.py +67 -0
  14. env-llmeval/lib/python3.10/site-packages/networkx/generators/community.py +1069 -0
  15. env-llmeval/lib/python3.10/site-packages/networkx/generators/degree_seq.py +868 -0
  16. env-llmeval/lib/python3.10/site-packages/networkx/generators/directed.py +501 -0
  17. env-llmeval/lib/python3.10/site-packages/networkx/generators/duplication.py +163 -0
  18. env-llmeval/lib/python3.10/site-packages/networkx/generators/ego.py +65 -0
  19. env-llmeval/lib/python3.10/site-packages/networkx/generators/expanders.py +475 -0
  20. env-llmeval/lib/python3.10/site-packages/networkx/generators/geometric.py +1047 -0
  21. env-llmeval/lib/python3.10/site-packages/networkx/generators/harary_graph.py +199 -0
  22. env-llmeval/lib/python3.10/site-packages/networkx/generators/internet_as_graphs.py +441 -0
  23. env-llmeval/lib/python3.10/site-packages/networkx/generators/intersection.py +124 -0
  24. env-llmeval/lib/python3.10/site-packages/networkx/generators/interval_graph.py +69 -0
  25. env-llmeval/lib/python3.10/site-packages/networkx/generators/joint_degree_seq.py +664 -0
  26. env-llmeval/lib/python3.10/site-packages/networkx/generators/lattice.py +367 -0
  27. env-llmeval/lib/python3.10/site-packages/networkx/generators/line.py +499 -0
  28. env-llmeval/lib/python3.10/site-packages/networkx/generators/mycielski.py +110 -0
  29. env-llmeval/lib/python3.10/site-packages/networkx/generators/nonisomorphic_trees.py +212 -0
  30. env-llmeval/lib/python3.10/site-packages/networkx/generators/random_clustered.py +117 -0
  31. env-llmeval/lib/python3.10/site-packages/networkx/generators/random_graphs.py +1331 -0
  32. env-llmeval/lib/python3.10/site-packages/networkx/generators/small.py +993 -0
  33. env-llmeval/lib/python3.10/site-packages/networkx/generators/social.py +546 -0
  34. env-llmeval/lib/python3.10/site-packages/networkx/generators/spectral_graph_forge.py +121 -0
  35. env-llmeval/lib/python3.10/site-packages/networkx/generators/stochastic.py +54 -0
  36. env-llmeval/lib/python3.10/site-packages/networkx/generators/sudoku.py +131 -0
  37. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__init__.py +0 -0
  38. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_atlas.py +75 -0
  39. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_classic.py +635 -0
  40. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_cographs.py +20 -0
  41. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_community.py +362 -0
  42. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_degree_seq.py +230 -0
  43. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_duplication.py +84 -0
  44. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_ego.py +39 -0
  45. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_geometric.py +488 -0
  46. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_harary_graph.py +134 -0
  47. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_internet_as_graphs.py +176 -0
  48. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_intersection.py +28 -0
  49. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_joint_degree_seq.py +125 -0
  50. env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_lattice.py +246 -0
env-llmeval/lib/python3.10/site-packages/networkx/drawing/layout.py ADDED
@@ -0,0 +1,1358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ******
3
+ Layout
4
+ ******
5
+
6
+ Node positioning algorithms for graph drawing.
7
+
8
+ For `random_layout()` the possible resulting shape
9
+ is a square of side [0, scale] (default: [0, 1])
10
+ Changing `center` shifts the layout by that amount.
11
+
12
+ For the other layout routines, the extent is
13
+ [center - scale, center + scale] (default: [-1, 1]).
14
+
15
+ Warning: Most layout routines have only been tested in 2-dimensions.
16
+
17
+ """
18
+ import networkx as nx
19
+ from networkx.utils import np_random_state
20
+
21
+ __all__ = [
22
+ "bipartite_layout",
23
+ "circular_layout",
24
+ "kamada_kawai_layout",
25
+ "random_layout",
26
+ "rescale_layout",
27
+ "rescale_layout_dict",
28
+ "shell_layout",
29
+ "spring_layout",
30
+ "spectral_layout",
31
+ "planar_layout",
32
+ "fruchterman_reingold_layout",
33
+ "spiral_layout",
34
+ "multipartite_layout",
35
+ "bfs_layout",
36
+ "arf_layout",
37
+ ]
38
+
39
+
40
+ def _process_params(G, center, dim):
41
+ # Some boilerplate code.
42
+ import numpy as np
43
+
44
+ if not isinstance(G, nx.Graph):
45
+ empty_graph = nx.Graph()
46
+ empty_graph.add_nodes_from(G)
47
+ G = empty_graph
48
+
49
+ if center is None:
50
+ center = np.zeros(dim)
51
+ else:
52
+ center = np.asarray(center)
53
+
54
+ if len(center) != dim:
55
+ msg = "length of center coordinates must match dimension of layout"
56
+ raise ValueError(msg)
57
+
58
+ return G, center
59
+
60
+
61
+ @np_random_state(3)
62
+ def random_layout(G, center=None, dim=2, seed=None):
63
+ """Position nodes uniformly at random in the unit square.
64
+
65
+ For every node, a position is generated by choosing each of dim
66
+ coordinates uniformly at random on the interval [0.0, 1.0).
67
+
68
+ NumPy (http://scipy.org) is required for this function.
69
+
70
+ Parameters
71
+ ----------
72
+ G : NetworkX graph or list of nodes
73
+ A position will be assigned to every node in G.
74
+
75
+ center : array-like or None
76
+ Coordinate pair around which to center the layout.
77
+
78
+ dim : int
79
+ Dimension of layout.
80
+
81
+ seed : int, RandomState instance or None optional (default=None)
82
+ Set the random state for deterministic node layouts.
83
+ If int, `seed` is the seed used by the random number generator,
84
+ if numpy.random.RandomState instance, `seed` is the random
85
+ number generator,
86
+ if None, the random number generator is the RandomState instance used
87
+ by numpy.random.
88
+
89
+ Returns
90
+ -------
91
+ pos : dict
92
+ A dictionary of positions keyed by node
93
+
94
+ Examples
95
+ --------
96
+ >>> G = nx.lollipop_graph(4, 3)
97
+ >>> pos = nx.random_layout(G)
98
+
99
+ """
100
+ import numpy as np
101
+
102
+ G, center = _process_params(G, center, dim)
103
+ pos = seed.rand(len(G), dim) + center
104
+ pos = pos.astype(np.float32)
105
+ pos = dict(zip(G, pos))
106
+
107
+ return pos
108
+
109
+
110
+ def circular_layout(G, scale=1, center=None, dim=2):
111
+ # dim=2 only
112
+ """Position nodes on a circle.
113
+
114
+ Parameters
115
+ ----------
116
+ G : NetworkX graph or list of nodes
117
+ A position will be assigned to every node in G.
118
+
119
+ scale : number (default: 1)
120
+ Scale factor for positions.
121
+
122
+ center : array-like or None
123
+ Coordinate pair around which to center the layout.
124
+
125
+ dim : int
126
+ Dimension of layout.
127
+ If dim>2, the remaining dimensions are set to zero
128
+ in the returned positions.
129
+ If dim<2, a ValueError is raised.
130
+
131
+ Returns
132
+ -------
133
+ pos : dict
134
+ A dictionary of positions keyed by node
135
+
136
+ Raises
137
+ ------
138
+ ValueError
139
+ If dim < 2
140
+
141
+ Examples
142
+ --------
143
+ >>> G = nx.path_graph(4)
144
+ >>> pos = nx.circular_layout(G)
145
+
146
+ Notes
147
+ -----
148
+ This algorithm currently only works in two dimensions and does not
149
+ try to minimize edge crossings.
150
+
151
+ """
152
+ import numpy as np
153
+
154
+ if dim < 2:
155
+ raise ValueError("cannot handle dimensions < 2")
156
+
157
+ G, center = _process_params(G, center, dim)
158
+
159
+ paddims = max(0, (dim - 2))
160
+
161
+ if len(G) == 0:
162
+ pos = {}
163
+ elif len(G) == 1:
164
+ pos = {nx.utils.arbitrary_element(G): center}
165
+ else:
166
+ # Discard the extra angle since it matches 0 radians.
167
+ theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
168
+ theta = theta.astype(np.float32)
169
+ pos = np.column_stack(
170
+ [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
171
+ )
172
+ pos = rescale_layout(pos, scale=scale) + center
173
+ pos = dict(zip(G, pos))
174
+
175
+ return pos
176
+
177
+
178
+ def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2):
179
+ """Position nodes in concentric circles.
180
+
181
+ Parameters
182
+ ----------
183
+ G : NetworkX graph or list of nodes
184
+ A position will be assigned to every node in G.
185
+
186
+ nlist : list of lists
187
+ List of node lists for each shell.
188
+
189
+ rotate : angle in radians (default=pi/len(nlist))
190
+ Angle by which to rotate the starting position of each shell
191
+ relative to the starting position of the previous shell.
192
+ To recreate behavior before v2.5 use rotate=0.
193
+
194
+ scale : number (default: 1)
195
+ Scale factor for positions.
196
+
197
+ center : array-like or None
198
+ Coordinate pair around which to center the layout.
199
+
200
+ dim : int
201
+ Dimension of layout, currently only dim=2 is supported.
202
+ Other dimension values result in a ValueError.
203
+
204
+ Returns
205
+ -------
206
+ pos : dict
207
+ A dictionary of positions keyed by node
208
+
209
+ Raises
210
+ ------
211
+ ValueError
212
+ If dim != 2
213
+
214
+ Examples
215
+ --------
216
+ >>> G = nx.path_graph(4)
217
+ >>> shells = [[0], [1, 2, 3]]
218
+ >>> pos = nx.shell_layout(G, shells)
219
+
220
+ Notes
221
+ -----
222
+ This algorithm currently only works in two dimensions and does not
223
+ try to minimize edge crossings.
224
+
225
+ """
226
+ import numpy as np
227
+
228
+ if dim != 2:
229
+ raise ValueError("can only handle 2 dimensions")
230
+
231
+ G, center = _process_params(G, center, dim)
232
+
233
+ if len(G) == 0:
234
+ return {}
235
+ if len(G) == 1:
236
+ return {nx.utils.arbitrary_element(G): center}
237
+
238
+ if nlist is None:
239
+ # draw the whole graph in one shell
240
+ nlist = [list(G)]
241
+
242
+ radius_bump = scale / len(nlist)
243
+
244
+ if len(nlist[0]) == 1:
245
+ # single node at center
246
+ radius = 0.0
247
+ else:
248
+ # else start at r=1
249
+ radius = radius_bump
250
+
251
+ if rotate is None:
252
+ rotate = np.pi / len(nlist)
253
+ first_theta = rotate
254
+ npos = {}
255
+ for nodes in nlist:
256
+ # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
257
+ theta = (
258
+ np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
259
+ + first_theta
260
+ )
261
+ pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
262
+ npos.update(zip(nodes, pos))
263
+ radius += radius_bump
264
+ first_theta += rotate
265
+
266
+ return npos
267
+
268
+
269
+ def bipartite_layout(
270
+ G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3
271
+ ):
272
+ """Position nodes in two straight lines.
273
+
274
+ Parameters
275
+ ----------
276
+ G : NetworkX graph or list of nodes
277
+ A position will be assigned to every node in G.
278
+
279
+ nodes : list or container
280
+ Nodes in one node set of the bipartite graph.
281
+ This set will be placed on left or top.
282
+
283
+ align : string (default='vertical')
284
+ The alignment of nodes. Vertical or horizontal.
285
+
286
+ scale : number (default: 1)
287
+ Scale factor for positions.
288
+
289
+ center : array-like or None
290
+ Coordinate pair around which to center the layout.
291
+
292
+ aspect_ratio : number (default=4/3):
293
+ The ratio of the width to the height of the layout.
294
+
295
+ Returns
296
+ -------
297
+ pos : dict
298
+ A dictionary of positions keyed by node.
299
+
300
+ Examples
301
+ --------
302
+ >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
303
+ >>> top = nx.bipartite.sets(G)[0]
304
+ >>> pos = nx.bipartite_layout(G, top)
305
+
306
+ Notes
307
+ -----
308
+ This algorithm currently only works in two dimensions and does not
309
+ try to minimize edge crossings.
310
+
311
+ """
312
+
313
+ import numpy as np
314
+
315
+ if align not in ("vertical", "horizontal"):
316
+ msg = "align must be either vertical or horizontal."
317
+ raise ValueError(msg)
318
+
319
+ G, center = _process_params(G, center=center, dim=2)
320
+ if len(G) == 0:
321
+ return {}
322
+
323
+ height = 1
324
+ width = aspect_ratio * height
325
+ offset = (width / 2, height / 2)
326
+
327
+ top = dict.fromkeys(nodes)
328
+ bottom = [v for v in G if v not in top]
329
+ nodes = list(top) + bottom
330
+
331
+ left_xs = np.repeat(0, len(top))
332
+ right_xs = np.repeat(width, len(bottom))
333
+ left_ys = np.linspace(0, height, len(top))
334
+ right_ys = np.linspace(0, height, len(bottom))
335
+
336
+ top_pos = np.column_stack([left_xs, left_ys]) - offset
337
+ bottom_pos = np.column_stack([right_xs, right_ys]) - offset
338
+
339
+ pos = np.concatenate([top_pos, bottom_pos])
340
+ pos = rescale_layout(pos, scale=scale) + center
341
+ if align == "horizontal":
342
+ pos = pos[:, ::-1] # swap x and y coords
343
+ pos = dict(zip(nodes, pos))
344
+ return pos
345
+
346
+
347
+ @np_random_state(10)
348
+ def spring_layout(
349
+ G,
350
+ k=None,
351
+ pos=None,
352
+ fixed=None,
353
+ iterations=50,
354
+ threshold=1e-4,
355
+ weight="weight",
356
+ scale=1,
357
+ center=None,
358
+ dim=2,
359
+ seed=None,
360
+ ):
361
+ """Position nodes using Fruchterman-Reingold force-directed algorithm.
362
+
363
+ The algorithm simulates a force-directed representation of the network
364
+ treating edges as springs holding nodes close, while treating nodes
365
+ as repelling objects, sometimes called an anti-gravity force.
366
+ Simulation continues until the positions are close to an equilibrium.
367
+
368
+ There are some hard-coded values: minimal distance between
369
+ nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
370
+ During the simulation, `k` helps determine the distance between nodes,
371
+ though `scale` and `center` determine the size and place after
372
+ rescaling occurs at the end of the simulation.
373
+
374
+ Fixing some nodes doesn't allow them to move in the simulation.
375
+ It also turns off the rescaling feature at the simulation's end.
376
+ In addition, setting `scale` to `None` turns off rescaling.
377
+
378
+ Parameters
379
+ ----------
380
+ G : NetworkX graph or list of nodes
381
+ A position will be assigned to every node in G.
382
+
383
+ k : float (default=None)
384
+ Optimal distance between nodes. If None the distance is set to
385
+ 1/sqrt(n) where n is the number of nodes. Increase this value
386
+ to move nodes farther apart.
387
+
388
+ pos : dict or None optional (default=None)
389
+ Initial positions for nodes as a dictionary with node as keys
390
+ and values as a coordinate list or tuple. If None, then use
391
+ random initial positions.
392
+
393
+ fixed : list or None optional (default=None)
394
+ Nodes to keep fixed at initial position.
395
+ Nodes not in ``G.nodes`` are ignored.
396
+ ValueError raised if `fixed` specified and `pos` not.
397
+
398
+ iterations : int optional (default=50)
399
+ Maximum number of iterations taken
400
+
401
+ threshold: float optional (default = 1e-4)
402
+ Threshold for relative error in node position changes.
403
+ The iteration stops if the error is below this threshold.
404
+
405
+ weight : string or None optional (default='weight')
406
+ The edge attribute that holds the numerical value used for
407
+ the edge weight. Larger means a stronger attractive force.
408
+ If None, then all edge weights are 1.
409
+
410
+ scale : number or None (default: 1)
411
+ Scale factor for positions. Not used unless `fixed is None`.
412
+ If scale is None, no rescaling is performed.
413
+
414
+ center : array-like or None
415
+ Coordinate pair around which to center the layout.
416
+ Not used unless `fixed is None`.
417
+
418
+ dim : int
419
+ Dimension of layout.
420
+
421
+ seed : int, RandomState instance or None optional (default=None)
422
+ Set the random state for deterministic node layouts.
423
+ If int, `seed` is the seed used by the random number generator,
424
+ if numpy.random.RandomState instance, `seed` is the random
425
+ number generator,
426
+ if None, the random number generator is the RandomState instance used
427
+ by numpy.random.
428
+
429
+ Returns
430
+ -------
431
+ pos : dict
432
+ A dictionary of positions keyed by node
433
+
434
+ Examples
435
+ --------
436
+ >>> G = nx.path_graph(4)
437
+ >>> pos = nx.spring_layout(G)
438
+
439
+ # The same using longer but equivalent function name
440
+ >>> pos = nx.fruchterman_reingold_layout(G)
441
+ """
442
+ import numpy as np
443
+
444
+ G, center = _process_params(G, center, dim)
445
+
446
+ if fixed is not None:
447
+ if pos is None:
448
+ raise ValueError("nodes are fixed without positions given")
449
+ for node in fixed:
450
+ if node not in pos:
451
+ raise ValueError("nodes are fixed without positions given")
452
+ nfixed = {node: i for i, node in enumerate(G)}
453
+ fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
454
+
455
+ if pos is not None:
456
+ # Determine size of existing domain to adjust initial positions
457
+ dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
458
+ if dom_size == 0:
459
+ dom_size = 1
460
+ pos_arr = seed.rand(len(G), dim) * dom_size + center
461
+
462
+ for i, n in enumerate(G):
463
+ if n in pos:
464
+ pos_arr[i] = np.asarray(pos[n])
465
+ else:
466
+ pos_arr = None
467
+ dom_size = 1
468
+
469
+ if len(G) == 0:
470
+ return {}
471
+ if len(G) == 1:
472
+ return {nx.utils.arbitrary_element(G.nodes()): center}
473
+
474
+ try:
475
+ # Sparse matrix
476
+ if len(G) < 500: # sparse solver for large graphs
477
+ raise ValueError
478
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
479
+ if k is None and fixed is not None:
480
+ # We must adjust k by domain size for layouts not near 1x1
481
+ nnodes, _ = A.shape
482
+ k = dom_size / np.sqrt(nnodes)
483
+ pos = _sparse_fruchterman_reingold(
484
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
485
+ )
486
+ except ValueError:
487
+ A = nx.to_numpy_array(G, weight=weight)
488
+ if k is None and fixed is not None:
489
+ # We must adjust k by domain size for layouts not near 1x1
490
+ nnodes, _ = A.shape
491
+ k = dom_size / np.sqrt(nnodes)
492
+ pos = _fruchterman_reingold(
493
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
494
+ )
495
+ if fixed is None and scale is not None:
496
+ pos = rescale_layout(pos, scale=scale) + center
497
+ pos = dict(zip(G, pos))
498
+ return pos
499
+
500
+
501
+ fruchterman_reingold_layout = spring_layout
502
+
503
+
504
+ @np_random_state(7)
505
+ def _fruchterman_reingold(
506
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
507
+ ):
508
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
509
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
510
+ import numpy as np
511
+
512
+ try:
513
+ nnodes, _ = A.shape
514
+ except AttributeError as err:
515
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
516
+ raise nx.NetworkXError(msg) from err
517
+
518
+ if pos is None:
519
+ # random initial positions
520
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
521
+ else:
522
+ # make sure positions are of same type as matrix
523
+ pos = pos.astype(A.dtype)
524
+
525
+ # optimal distance between nodes
526
+ if k is None:
527
+ k = np.sqrt(1.0 / nnodes)
528
+ # the initial "temperature" is about .1 of domain area (=1x1)
529
+ # this is the largest step allowed in the dynamics.
530
+ # We need to calculate this in case our fixed positions force our domain
531
+ # to be much bigger than 1x1
532
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
533
+ # simple cooling scheme.
534
+ # linearly step down by dt on each iteration so last iteration is size dt.
535
+ dt = t / (iterations + 1)
536
+ delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
537
+ # the inscrutable (but fast) version
538
+ # this is still O(V^2)
539
+ # could use multilevel methods to speed this up significantly
540
+ for iteration in range(iterations):
541
+ # matrix of difference between points
542
+ delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
543
+ # distance between points
544
+ distance = np.linalg.norm(delta, axis=-1)
545
+ # enforce minimum distance of 0.01
546
+ np.clip(distance, 0.01, None, out=distance)
547
+ # displacement "force"
548
+ displacement = np.einsum(
549
+ "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
550
+ )
551
+ # update positions
552
+ length = np.linalg.norm(displacement, axis=-1)
553
+ length = np.where(length < 0.01, 0.1, length)
554
+ delta_pos = np.einsum("ij,i->ij", displacement, t / length)
555
+ if fixed is not None:
556
+ # don't change positions of fixed nodes
557
+ delta_pos[fixed] = 0.0
558
+ pos += delta_pos
559
+ # cool temperature
560
+ t -= dt
561
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
562
+ break
563
+ return pos
564
+
565
+
566
+ @np_random_state(7)
567
+ def _sparse_fruchterman_reingold(
568
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
569
+ ):
570
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
571
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
572
+ # Sparse version
573
+ import numpy as np
574
+ import scipy as sp
575
+
576
+ try:
577
+ nnodes, _ = A.shape
578
+ except AttributeError as err:
579
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
580
+ raise nx.NetworkXError(msg) from err
581
+ # make sure we have a LIst of Lists representation
582
+ try:
583
+ A = A.tolil()
584
+ except AttributeError:
585
+ A = (sp.sparse.coo_array(A)).tolil()
586
+
587
+ if pos is None:
588
+ # random initial positions
589
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
590
+ else:
591
+ # make sure positions are of same type as matrix
592
+ pos = pos.astype(A.dtype)
593
+
594
+ # no fixed nodes
595
+ if fixed is None:
596
+ fixed = []
597
+
598
+ # optimal distance between nodes
599
+ if k is None:
600
+ k = np.sqrt(1.0 / nnodes)
601
+ # the initial "temperature" is about .1 of domain area (=1x1)
602
+ # this is the largest step allowed in the dynamics.
603
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
604
+ # simple cooling scheme.
605
+ # linearly step down by dt on each iteration so last iteration is size dt.
606
+ dt = t / (iterations + 1)
607
+
608
+ displacement = np.zeros((dim, nnodes))
609
+ for iteration in range(iterations):
610
+ displacement *= 0
611
+ # loop over rows
612
+ for i in range(A.shape[0]):
613
+ if i in fixed:
614
+ continue
615
+ # difference between this row's node position and all others
616
+ delta = (pos[i] - pos).T
617
+ # distance between points
618
+ distance = np.sqrt((delta**2).sum(axis=0))
619
+ # enforce minimum distance of 0.01
620
+ distance = np.where(distance < 0.01, 0.01, distance)
621
+ # the adjacency matrix row
622
+ Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
623
+ # displacement "force"
624
+ displacement[:, i] += (
625
+ delta * (k * k / distance**2 - Ai * distance / k)
626
+ ).sum(axis=1)
627
+ # update positions
628
+ length = np.sqrt((displacement**2).sum(axis=0))
629
+ length = np.where(length < 0.01, 0.1, length)
630
+ delta_pos = (displacement * t / length).T
631
+ pos += delta_pos
632
+ # cool temperature
633
+ t -= dt
634
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
635
+ break
636
+ return pos
637
+
638
+
639
+ def kamada_kawai_layout(
640
+ G, dist=None, pos=None, weight="weight", scale=1, center=None, dim=2
641
+ ):
642
+ """Position nodes using Kamada-Kawai path-length cost-function.
643
+
644
+ Parameters
645
+ ----------
646
+ G : NetworkX graph or list of nodes
647
+ A position will be assigned to every node in G.
648
+
649
+ dist : dict (default=None)
650
+ A two-level dictionary of optimal distances between nodes,
651
+ indexed by source and destination node.
652
+ If None, the distance is computed using shortest_path_length().
653
+
654
+ pos : dict or None optional (default=None)
655
+ Initial positions for nodes as a dictionary with node as keys
656
+ and values as a coordinate list or tuple. If None, then use
657
+ circular_layout() for dim >= 2 and a linear layout for dim == 1.
658
+
659
+ weight : string or None optional (default='weight')
660
+ The edge attribute that holds the numerical value used for
661
+ the edge weight. If None, then all edge weights are 1.
662
+
663
+ scale : number (default: 1)
664
+ Scale factor for positions.
665
+
666
+ center : array-like or None
667
+ Coordinate pair around which to center the layout.
668
+
669
+ dim : int
670
+ Dimension of layout.
671
+
672
+ Returns
673
+ -------
674
+ pos : dict
675
+ A dictionary of positions keyed by node
676
+
677
+ Examples
678
+ --------
679
+ >>> G = nx.path_graph(4)
680
+ >>> pos = nx.kamada_kawai_layout(G)
681
+ """
682
+ import numpy as np
683
+
684
+ G, center = _process_params(G, center, dim)
685
+ nNodes = len(G)
686
+ if nNodes == 0:
687
+ return {}
688
+
689
+ if dist is None:
690
+ dist = dict(nx.shortest_path_length(G, weight=weight))
691
+ dist_mtx = 1e6 * np.ones((nNodes, nNodes))
692
+ for row, nr in enumerate(G):
693
+ if nr not in dist:
694
+ continue
695
+ rdist = dist[nr]
696
+ for col, nc in enumerate(G):
697
+ if nc not in rdist:
698
+ continue
699
+ dist_mtx[row][col] = rdist[nc]
700
+
701
+ if pos is None:
702
+ if dim >= 3:
703
+ pos = random_layout(G, dim=dim)
704
+ elif dim == 2:
705
+ pos = circular_layout(G, dim=dim)
706
+ else:
707
+ pos = dict(zip(G, np.linspace(0, 1, len(G))))
708
+ pos_arr = np.array([pos[n] for n in G])
709
+
710
+ pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
711
+
712
+ pos = rescale_layout(pos, scale=scale) + center
713
+ return dict(zip(G, pos))
714
+
715
+
716
+ def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
717
+ # Anneal node locations based on the Kamada-Kawai cost-function,
718
+ # using the supplied matrix of preferred inter-node distances,
719
+ # and starting locations.
720
+
721
+ import numpy as np
722
+ import scipy as sp
723
+
724
+ meanwt = 1e-3
725
+ costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
726
+
727
+ optresult = sp.optimize.minimize(
728
+ _kamada_kawai_costfn,
729
+ pos_arr.ravel(),
730
+ method="L-BFGS-B",
731
+ args=costargs,
732
+ jac=True,
733
+ )
734
+
735
+ return optresult.x.reshape((-1, dim))
736
+
737
+
738
+ def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
739
+ # Cost-function and gradient for Kamada-Kawai layout algorithm
740
+ nNodes = invdist.shape[0]
741
+ pos_arr = pos_vec.reshape((nNodes, dim))
742
+
743
+ delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
744
+ nodesep = np.linalg.norm(delta, axis=-1)
745
+ direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
746
+
747
+ offset = nodesep * invdist - 1.0
748
+ offset[np.diag_indices(nNodes)] = 0
749
+
750
+ cost = 0.5 * np.sum(offset**2)
751
+ grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
752
+ "ij,ij,ijk->jk", invdist, offset, direction
753
+ )
754
+
755
+ # Additional parabolic term to encourage mean position to be near origin:
756
+ sumpos = np.sum(pos_arr, axis=0)
757
+ cost += 0.5 * meanweight * np.sum(sumpos**2)
758
+ grad += meanweight * sumpos
759
+
760
+ return (cost, grad.ravel())
761
+
762
+
763
+ def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
764
+ """Position nodes using the eigenvectors of the graph Laplacian.
765
+
766
+ Using the unnormalized Laplacian, the layout shows possible clusters of
767
+ nodes which are an approximation of the ratio cut. If dim is the number of
768
+ dimensions then the positions are the entries of the dim eigenvectors
769
+ corresponding to the ascending eigenvalues starting from the second one.
770
+
771
+ Parameters
772
+ ----------
773
+ G : NetworkX graph or list of nodes
774
+ A position will be assigned to every node in G.
775
+
776
+ weight : string or None optional (default='weight')
777
+ The edge attribute that holds the numerical value used for
778
+ the edge weight. If None, then all edge weights are 1.
779
+
780
+ scale : number (default: 1)
781
+ Scale factor for positions.
782
+
783
+ center : array-like or None
784
+ Coordinate pair around which to center the layout.
785
+
786
+ dim : int
787
+ Dimension of layout.
788
+
789
+ Returns
790
+ -------
791
+ pos : dict
792
+ A dictionary of positions keyed by node
793
+
794
+ Examples
795
+ --------
796
+ >>> G = nx.path_graph(4)
797
+ >>> pos = nx.spectral_layout(G)
798
+
799
+ Notes
800
+ -----
801
+ Directed graphs will be considered as undirected graphs when
802
+ positioning the nodes.
803
+
804
+ For larger graphs (>500 nodes) this will use the SciPy sparse
805
+ eigenvalue solver (ARPACK).
806
+ """
807
+ # handle some special cases that break the eigensolvers
808
+ import numpy as np
809
+
810
+ G, center = _process_params(G, center, dim)
811
+
812
+ if len(G) <= 2:
813
+ if len(G) == 0:
814
+ pos = np.array([])
815
+ elif len(G) == 1:
816
+ pos = np.array([center])
817
+ else:
818
+ pos = np.array([np.zeros(dim), np.array(center) * 2.0])
819
+ return dict(zip(G, pos))
820
+ try:
821
+ # Sparse matrix
822
+ if len(G) < 500: # dense solver is faster for small graphs
823
+ raise ValueError
824
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
825
+ # Symmetrize directed graphs
826
+ if G.is_directed():
827
+ A = A + np.transpose(A)
828
+ pos = _sparse_spectral(A, dim)
829
+ except (ImportError, ValueError):
830
+ # Dense matrix
831
+ A = nx.to_numpy_array(G, weight=weight)
832
+ # Symmetrize directed graphs
833
+ if G.is_directed():
834
+ A += A.T
835
+ pos = _spectral(A, dim)
836
+
837
+ pos = rescale_layout(pos, scale=scale) + center
838
+ pos = dict(zip(G, pos))
839
+ return pos
840
+
841
+
842
+ def _spectral(A, dim=2):
843
+ # Input adjacency matrix A
844
+ # Uses dense eigenvalue solver from numpy
845
+ import numpy as np
846
+
847
+ try:
848
+ nnodes, _ = A.shape
849
+ except AttributeError as err:
850
+ msg = "spectral() takes an adjacency matrix as input"
851
+ raise nx.NetworkXError(msg) from err
852
+
853
+ # form Laplacian matrix where D is diagonal of degrees
854
+ D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
855
+ L = D - A
856
+
857
+ eigenvalues, eigenvectors = np.linalg.eig(L)
858
+ # sort and keep smallest nonzero
859
+ index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
860
+ return np.real(eigenvectors[:, index])
861
+
862
+
863
+ def _sparse_spectral(A, dim=2):
864
+ # Input adjacency matrix A
865
+ # Uses sparse eigenvalue solver from scipy
866
+ # Could use multilevel methods here, see Koren "On spectral graph drawing"
867
+ import numpy as np
868
+ import scipy as sp
869
+
870
+ try:
871
+ nnodes, _ = A.shape
872
+ except AttributeError as err:
873
+ msg = "sparse_spectral() takes an adjacency matrix as input"
874
+ raise nx.NetworkXError(msg) from err
875
+
876
+ # form Laplacian matrix
877
+ # TODO: Rm csr_array wrapper in favor of spdiags array constructor when available
878
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, nnodes, nnodes))
879
+ L = D - A
880
+
881
+ k = dim + 1
882
+ # number of Lanczos vectors for ARPACK solver.What is the right scaling?
883
+ ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
884
+ # return smallest k eigenvalues and eigenvectors
885
+ eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
886
+ index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
887
+ return np.real(eigenvectors[:, index])
888
+
889
+
890
+ def planar_layout(G, scale=1, center=None, dim=2):
891
+ """Position nodes without edge intersections.
892
+
893
+ Parameters
894
+ ----------
895
+ G : NetworkX graph or list of nodes
896
+ A position will be assigned to every node in G. If G is of type
897
+ nx.PlanarEmbedding, the positions are selected accordingly.
898
+
899
+ scale : number (default: 1)
900
+ Scale factor for positions.
901
+
902
+ center : array-like or None
903
+ Coordinate pair around which to center the layout.
904
+
905
+ dim : int
906
+ Dimension of layout.
907
+
908
+ Returns
909
+ -------
910
+ pos : dict
911
+ A dictionary of positions keyed by node
912
+
913
+ Raises
914
+ ------
915
+ NetworkXException
916
+ If G is not planar
917
+
918
+ Examples
919
+ --------
920
+ >>> G = nx.path_graph(4)
921
+ >>> pos = nx.planar_layout(G)
922
+ """
923
+ import numpy as np
924
+
925
+ if dim != 2:
926
+ raise ValueError("can only handle 2 dimensions")
927
+
928
+ G, center = _process_params(G, center, dim)
929
+
930
+ if len(G) == 0:
931
+ return {}
932
+
933
+ if isinstance(G, nx.PlanarEmbedding):
934
+ embedding = G
935
+ else:
936
+ is_planar, embedding = nx.check_planarity(G)
937
+ if not is_planar:
938
+ raise nx.NetworkXException("G is not planar.")
939
+ pos = nx.combinatorial_embedding_to_pos(embedding)
940
+ node_list = list(embedding)
941
+ pos = np.vstack([pos[x] for x in node_list])
942
+ pos = pos.astype(np.float64)
943
+ pos = rescale_layout(pos, scale=scale) + center
944
+ return dict(zip(node_list, pos))
945
+
946
+
947
+ def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False):
948
+ """Position nodes in a spiral layout.
949
+
950
+ Parameters
951
+ ----------
952
+ G : NetworkX graph or list of nodes
953
+ A position will be assigned to every node in G.
954
+ scale : number (default: 1)
955
+ Scale factor for positions.
956
+ center : array-like or None
957
+ Coordinate pair around which to center the layout.
958
+ dim : int, default=2
959
+ Dimension of layout, currently only dim=2 is supported.
960
+ Other dimension values result in a ValueError.
961
+ resolution : float, default=0.35
962
+ The compactness of the spiral layout returned.
963
+ Lower values result in more compressed spiral layouts.
964
+ equidistant : bool, default=False
965
+ If True, nodes will be positioned equidistant from each other
966
+ by decreasing angle further from center.
967
+ If False, nodes will be positioned at equal angles
968
+ from each other by increasing separation further from center.
969
+
970
+ Returns
971
+ -------
972
+ pos : dict
973
+ A dictionary of positions keyed by node
974
+
975
+ Raises
976
+ ------
977
+ ValueError
978
+ If dim != 2
979
+
980
+ Examples
981
+ --------
982
+ >>> G = nx.path_graph(4)
983
+ >>> pos = nx.spiral_layout(G)
984
+ >>> nx.draw(G, pos=pos)
985
+
986
+ Notes
987
+ -----
988
+ This algorithm currently only works in two dimensions.
989
+
990
+ """
991
+ import numpy as np
992
+
993
+ if dim != 2:
994
+ raise ValueError("can only handle 2 dimensions")
995
+
996
+ G, center = _process_params(G, center, dim)
997
+
998
+ if len(G) == 0:
999
+ return {}
1000
+ if len(G) == 1:
1001
+ return {nx.utils.arbitrary_element(G): center}
1002
+
1003
+ pos = []
1004
+ if equidistant:
1005
+ chord = 1
1006
+ step = 0.5
1007
+ theta = resolution
1008
+ theta += chord / (step * theta)
1009
+ for _ in range(len(G)):
1010
+ r = step * theta
1011
+ theta += chord / r
1012
+ pos.append([np.cos(theta) * r, np.sin(theta) * r])
1013
+
1014
+ else:
1015
+ dist = np.arange(len(G), dtype=float)
1016
+ angle = resolution * dist
1017
+ pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
1018
+
1019
+ pos = rescale_layout(np.array(pos), scale=scale) + center
1020
+
1021
+ pos = dict(zip(G, pos))
1022
+
1023
+ return pos
1024
+
1025
+
1026
+ def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
1027
+ """Position nodes in layers of straight lines.
1028
+
1029
+ Parameters
1030
+ ----------
1031
+ G : NetworkX graph or list of nodes
1032
+ A position will be assigned to every node in G.
1033
+
1034
+ subset_key : string or dict (default='subset')
1035
+ If a string, the key of node data in G that holds the node subset.
1036
+ If a dict, keyed by layer number to the nodes in that layer/subset.
1037
+
1038
+ align : string (default='vertical')
1039
+ The alignment of nodes. Vertical or horizontal.
1040
+
1041
+ scale : number (default: 1)
1042
+ Scale factor for positions.
1043
+
1044
+ center : array-like or None
1045
+ Coordinate pair around which to center the layout.
1046
+
1047
+ Returns
1048
+ -------
1049
+ pos : dict
1050
+ A dictionary of positions keyed by node.
1051
+
1052
+ Examples
1053
+ --------
1054
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1055
+ >>> pos = nx.multipartite_layout(G)
1056
+
1057
+ or use a dict to provide the layers of the layout
1058
+
1059
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
1060
+ >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
1061
+ >>> pos = nx.multipartite_layout(G, subset_key=layers)
1062
+
1063
+ Notes
1064
+ -----
1065
+ This algorithm currently only works in two dimensions and does not
1066
+ try to minimize edge crossings.
1067
+
1068
+ Network does not need to be a complete multipartite graph. As long as nodes
1069
+ have subset_key data, they will be placed in the corresponding layers.
1070
+
1071
+ """
1072
+ import numpy as np
1073
+
1074
+ if align not in ("vertical", "horizontal"):
1075
+ msg = "align must be either vertical or horizontal."
1076
+ raise ValueError(msg)
1077
+
1078
+ G, center = _process_params(G, center=center, dim=2)
1079
+ if len(G) == 0:
1080
+ return {}
1081
+
1082
+ try:
1083
+ # check if subset_key is dict-like
1084
+ if len(G) != sum(len(nodes) for nodes in subset_key.values()):
1085
+ raise nx.NetworkXError(
1086
+ "all nodes must be in one subset of `subset_key` dict"
1087
+ )
1088
+ except AttributeError:
1089
+ # subset_key is not a dict, hence a string
1090
+ node_to_subset = nx.get_node_attributes(G, subset_key)
1091
+ if len(node_to_subset) != len(G):
1092
+ raise nx.NetworkXError(
1093
+ f"all nodes need a subset_key attribute: {subset_key}"
1094
+ )
1095
+ subset_key = nx.utils.groups(node_to_subset)
1096
+
1097
+ # Sort by layer, if possible
1098
+ try:
1099
+ layers = dict(sorted(subset_key.items()))
1100
+ except TypeError:
1101
+ layers = subset_key
1102
+
1103
+ pos = None
1104
+ nodes = []
1105
+ width = len(layers)
1106
+ for i, layer in enumerate(layers.values()):
1107
+ height = len(layer)
1108
+ xs = np.repeat(i, height)
1109
+ ys = np.arange(0, height, dtype=float)
1110
+ offset = ((width - 1) / 2, (height - 1) / 2)
1111
+ layer_pos = np.column_stack([xs, ys]) - offset
1112
+ if pos is None:
1113
+ pos = layer_pos
1114
+ else:
1115
+ pos = np.concatenate([pos, layer_pos])
1116
+ nodes.extend(layer)
1117
+ pos = rescale_layout(pos, scale=scale) + center
1118
+ if align == "horizontal":
1119
+ pos = pos[:, ::-1] # swap x and y coords
1120
+ pos = dict(zip(nodes, pos))
1121
+ return pos
1122
+
1123
+
1124
+ def arf_layout(
1125
+ G,
1126
+ pos=None,
1127
+ scaling=1,
1128
+ a=1.1,
1129
+ etol=1e-6,
1130
+ dt=1e-3,
1131
+ max_iter=1000,
1132
+ ):
1133
+ """Arf layout for networkx
1134
+
1135
+ The attractive and repulsive forces (arf) layout [1]
1136
+ improves the spring layout in three ways. First, it
1137
+ prevents congestion of highly connected nodes due to
1138
+ strong forcing between nodes. Second, it utilizes the
1139
+ layout space more effectively by preventing large gaps
1140
+ that spring layout tends to create. Lastly, the arf
1141
+ layout represents symmetries in the layout better than
1142
+ the default spring layout.
1143
+
1144
+ Parameters
1145
+ ----------
1146
+ G : nx.Graph or nx.DiGraph
1147
+ Networkx graph.
1148
+ pos : dict
1149
+ Initial position of the nodes. If set to None a
1150
+ random layout will be used.
1151
+ scaling : float
1152
+ Scales the radius of the circular layout space.
1153
+ a : float
1154
+ Strength of springs between connected nodes. Should be larger than 1. The greater a, the clearer the separation ofunconnected sub clusters.
1155
+ etol : float
1156
+ Gradient sum of spring forces must be larger than `etol` before successful termination.
1157
+ dt : float
1158
+ Time step for force differential equation simulations.
1159
+ max_iter : int
1160
+ Max iterations before termination of the algorithm.
1161
+
1162
+ References
1163
+ .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
1164
+ International Journal of Modern Physics C, 2007, Vol 18, No 10, pp. 1537-1549.
1165
+ https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
1166
+
1167
+ Returns
1168
+ -------
1169
+ pos : dict
1170
+ A dictionary of positions keyed by node.
1171
+
1172
+ Examples
1173
+ --------
1174
+ >>> G = nx.grid_graph((5, 5))
1175
+ >>> pos = nx.arf_layout(G)
1176
+
1177
+ """
1178
+ import warnings
1179
+
1180
+ import numpy as np
1181
+
1182
+ if a <= 1:
1183
+ msg = "The parameter a should be larger than 1"
1184
+ raise ValueError(msg)
1185
+
1186
+ pos_tmp = nx.random_layout(G)
1187
+ if pos is None:
1188
+ pos = pos_tmp
1189
+ else:
1190
+ for node in G.nodes():
1191
+ if node not in pos:
1192
+ pos[node] = pos_tmp[node].copy()
1193
+
1194
+ # Initialize spring constant matrix
1195
+ N = len(G)
1196
+ # No nodes no computation
1197
+ if N == 0:
1198
+ return pos
1199
+
1200
+ # init force of springs
1201
+ K = np.ones((N, N)) - np.eye(N)
1202
+ node_order = {node: i for i, node in enumerate(G)}
1203
+ for x, y in G.edges():
1204
+ if x != y:
1205
+ idx, jdx = (node_order[i] for i in (x, y))
1206
+ K[idx, jdx] = a
1207
+
1208
+ # vectorize values
1209
+ p = np.asarray(list(pos.values()))
1210
+
1211
+ # equation 10 in [1]
1212
+ rho = scaling * np.sqrt(N)
1213
+
1214
+ # looping variables
1215
+ error = etol + 1
1216
+ n_iter = 0
1217
+ while error > etol:
1218
+ diff = p[:, np.newaxis] - p[np.newaxis]
1219
+ A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
1220
+ # attraction_force - repulsions force
1221
+ # suppress nans due to division; caused by diagonal set to zero.
1222
+ # Does not affect the computation due to nansum
1223
+ with warnings.catch_warnings():
1224
+ warnings.simplefilter("ignore")
1225
+ change = K[..., np.newaxis] * diff - rho / A * diff
1226
+ change = np.nansum(change, axis=0)
1227
+ p += change * dt
1228
+
1229
+ error = np.linalg.norm(change, axis=-1).sum()
1230
+ if n_iter > max_iter:
1231
+ break
1232
+ n_iter += 1
1233
+ return dict(zip(G.nodes(), p))
1234
+
1235
+
1236
+ def rescale_layout(pos, scale=1):
1237
+ """Returns scaled position array to (-scale, scale) in all axes.
1238
+
1239
+ The function acts on NumPy arrays which hold position information.
1240
+ Each position is one row of the array. The dimension of the space
1241
+ equals the number of columns. Each coordinate in one column.
1242
+
1243
+ To rescale, the mean (center) is subtracted from each axis separately.
1244
+ Then all values are scaled so that the largest magnitude value
1245
+ from all axes equals `scale` (thus, the aspect ratio is preserved).
1246
+ The resulting NumPy Array is returned (order of rows unchanged).
1247
+
1248
+ Parameters
1249
+ ----------
1250
+ pos : numpy array
1251
+ positions to be scaled. Each row is a position.
1252
+
1253
+ scale : number (default: 1)
1254
+ The size of the resulting extent in all directions.
1255
+
1256
+ Returns
1257
+ -------
1258
+ pos : numpy array
1259
+ scaled positions. Each row is a position.
1260
+
1261
+ See Also
1262
+ --------
1263
+ rescale_layout_dict
1264
+ """
1265
+ import numpy as np
1266
+
1267
+ # Find max length over all dimensions
1268
+ pos -= pos.mean(axis=0)
1269
+ lim = np.abs(pos).max() # max coordinate for all axes
1270
+ # rescale to (-scale, scale) in all directions, preserves aspect
1271
+ if lim > 0:
1272
+ pos *= scale / lim
1273
+ return pos
1274
+
1275
+
1276
+ def rescale_layout_dict(pos, scale=1):
1277
+ """Return a dictionary of scaled positions keyed by node
1278
+
1279
+ Parameters
1280
+ ----------
1281
+ pos : A dictionary of positions keyed by node
1282
+
1283
+ scale : number (default: 1)
1284
+ The size of the resulting extent in all directions.
1285
+
1286
+ Returns
1287
+ -------
1288
+ pos : A dictionary of positions keyed by node
1289
+
1290
+ Examples
1291
+ --------
1292
+ >>> import numpy as np
1293
+ >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
1294
+ >>> nx.rescale_layout_dict(pos)
1295
+ {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
1296
+
1297
+ >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
1298
+ >>> nx.rescale_layout_dict(pos, scale=2)
1299
+ {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
1300
+
1301
+ See Also
1302
+ --------
1303
+ rescale_layout
1304
+ """
1305
+ import numpy as np
1306
+
1307
+ if not pos: # empty_graph
1308
+ return {}
1309
+ pos_v = np.array(list(pos.values()))
1310
+ pos_v = rescale_layout(pos_v, scale=scale)
1311
+ return dict(zip(pos, pos_v))
1312
+
1313
+
1314
+ def bfs_layout(G, start, *, align="vertical", scale=1, center=None):
1315
+ """Position nodes according to breadth-first search algorithm.
1316
+
1317
+ Parameters
1318
+ ----------
1319
+ G : NetworkX graph
1320
+ A position will be assigned to every node in G.
1321
+
1322
+ start : node in `G`
1323
+ Starting node for bfs
1324
+
1325
+ center : array-like or None
1326
+ Coordinate pair around which to center the layout.
1327
+
1328
+ Returns
1329
+ -------
1330
+ pos : dict
1331
+ A dictionary of positions keyed by node.
1332
+
1333
+ Examples
1334
+ --------
1335
+ >>> G = nx.path_graph(4)
1336
+ >>> pos = nx.bfs_layout(G, 0)
1337
+
1338
+ Notes
1339
+ -----
1340
+ This algorithm currently only works in two dimensions and does not
1341
+ try to minimize edge crossings.
1342
+
1343
+ """
1344
+ G, center = _process_params(G, center, 2)
1345
+
1346
+ # Compute layers with BFS
1347
+ layers = dict(enumerate(nx.bfs_layers(G, start)))
1348
+
1349
+ if len(G) != sum(len(nodes) for nodes in layers.values()):
1350
+ raise nx.NetworkXError(
1351
+ "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
1352
+ " G.subgraph(nx.node_connected_component(G, start))"
1353
+ )
1354
+
1355
+ # Compute node positions with multipartite_layout
1356
+ return multipartite_layout(
1357
+ G, subset_key=layers, align=align, scale=scale, center=center
1358
+ )
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc ADDED
Binary file (9.75 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc ADDED
Binary file (7.38 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc ADDED
Binary file (5.27 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc ADDED
Binary file (26.3 kB). View file
 
env-llmeval/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)
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for layout functions."""
2
+ import pytest
3
+
4
+ import networkx as nx
5
+
6
+ np = pytest.importorskip("numpy")
7
+ pytest.importorskip("scipy")
8
+
9
+
10
+ class TestLayout:
11
+ @classmethod
12
+ def setup_class(cls):
13
+ cls.Gi = nx.grid_2d_graph(5, 5)
14
+ cls.Gs = nx.Graph()
15
+ nx.add_path(cls.Gs, "abcdef")
16
+ cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse
17
+
18
+ def test_spring_fixed_without_pos(self):
19
+ G = nx.path_graph(4)
20
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
21
+ pos = {0: (1, 1), 2: (0, 0)}
22
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
23
+ nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError
24
+
25
+ def test_spring_init_pos(self):
26
+ # Tests GH #2448
27
+ import math
28
+
29
+ G = nx.Graph()
30
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)])
31
+
32
+ init_pos = {0: (0.0, 0.0)}
33
+ fixed_pos = [0]
34
+ pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos)
35
+ has_nan = any(math.isnan(c) for coords in pos.values() for c in coords)
36
+ assert not has_nan, "values should not be nan"
37
+
38
+ def test_smoke_empty_graph(self):
39
+ G = []
40
+ nx.random_layout(G)
41
+ nx.circular_layout(G)
42
+ nx.planar_layout(G)
43
+ nx.spring_layout(G)
44
+ nx.fruchterman_reingold_layout(G)
45
+ nx.spectral_layout(G)
46
+ nx.shell_layout(G)
47
+ nx.bipartite_layout(G, G)
48
+ nx.spiral_layout(G)
49
+ nx.multipartite_layout(G)
50
+ nx.kamada_kawai_layout(G)
51
+
52
+ def test_smoke_int(self):
53
+ G = self.Gi
54
+ nx.random_layout(G)
55
+ nx.circular_layout(G)
56
+ nx.planar_layout(G)
57
+ nx.spring_layout(G)
58
+ nx.fruchterman_reingold_layout(G)
59
+ nx.fruchterman_reingold_layout(self.bigG)
60
+ nx.spectral_layout(G)
61
+ nx.spectral_layout(G.to_directed())
62
+ nx.spectral_layout(self.bigG)
63
+ nx.spectral_layout(self.bigG.to_directed())
64
+ nx.shell_layout(G)
65
+ nx.spiral_layout(G)
66
+ nx.kamada_kawai_layout(G)
67
+ nx.kamada_kawai_layout(G, dim=1)
68
+ nx.kamada_kawai_layout(G, dim=3)
69
+ nx.arf_layout(G)
70
+
71
+ def test_smoke_string(self):
72
+ G = self.Gs
73
+ nx.random_layout(G)
74
+ nx.circular_layout(G)
75
+ nx.planar_layout(G)
76
+ nx.spring_layout(G)
77
+ nx.fruchterman_reingold_layout(G)
78
+ nx.spectral_layout(G)
79
+ nx.shell_layout(G)
80
+ nx.spiral_layout(G)
81
+ nx.kamada_kawai_layout(G)
82
+ nx.kamada_kawai_layout(G, dim=1)
83
+ nx.kamada_kawai_layout(G, dim=3)
84
+ nx.arf_layout(G)
85
+
86
+ def check_scale_and_center(self, pos, scale, center):
87
+ center = np.array(center)
88
+ low = center - scale
89
+ hi = center + scale
90
+ vpos = np.array(list(pos.values()))
91
+ length = vpos.max(0) - vpos.min(0)
92
+ assert (length <= 2 * scale).all()
93
+ assert (vpos >= low).all()
94
+ assert (vpos <= hi).all()
95
+
96
+ def test_scale_and_center_arg(self):
97
+ sc = self.check_scale_and_center
98
+ c = (4, 5)
99
+ G = nx.complete_graph(9)
100
+ G.add_node(9)
101
+ sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
102
+ # rest can have 2*scale length: [-scale, scale]
103
+ sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
104
+ sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
105
+ sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
106
+ sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
107
+ sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
108
+ sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
109
+
110
+ c = (2, 3, 5)
111
+ sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c)
112
+
113
+ def test_planar_layout_non_planar_input(self):
114
+ G = nx.complete_graph(9)
115
+ pytest.raises(nx.NetworkXException, nx.planar_layout, G)
116
+
117
+ def test_smoke_planar_layout_embedding_input(self):
118
+ embedding = nx.PlanarEmbedding()
119
+ embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]})
120
+ nx.planar_layout(embedding)
121
+
122
+ def test_default_scale_and_center(self):
123
+ sc = self.check_scale_and_center
124
+ c = (0, 0)
125
+ G = nx.complete_graph(9)
126
+ G.add_node(9)
127
+ sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
128
+ sc(nx.spring_layout(G), scale=1, center=c)
129
+ sc(nx.spectral_layout(G), scale=1, center=c)
130
+ sc(nx.circular_layout(G), scale=1, center=c)
131
+ sc(nx.shell_layout(G), scale=1, center=c)
132
+ sc(nx.spiral_layout(G), scale=1, center=c)
133
+ sc(nx.kamada_kawai_layout(G), scale=1, center=c)
134
+
135
+ c = (0, 0, 0)
136
+ sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c)
137
+
138
+ def test_circular_planar_and_shell_dim_error(self):
139
+ G = nx.path_graph(4)
140
+ pytest.raises(ValueError, nx.circular_layout, G, dim=1)
141
+ pytest.raises(ValueError, nx.shell_layout, G, dim=1)
142
+ pytest.raises(ValueError, nx.shell_layout, G, dim=3)
143
+ pytest.raises(ValueError, nx.planar_layout, G, dim=1)
144
+ pytest.raises(ValueError, nx.planar_layout, G, dim=3)
145
+
146
+ def test_adjacency_interface_numpy(self):
147
+ A = nx.to_numpy_array(self.Gs)
148
+ pos = nx.drawing.layout._fruchterman_reingold(A)
149
+ assert pos.shape == (6, 2)
150
+ pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
151
+ assert pos.shape == (6, 3)
152
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
153
+ assert pos.shape == (6, 2)
154
+
155
+ def test_adjacency_interface_scipy(self):
156
+ A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
157
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
158
+ assert pos.shape == (6, 2)
159
+ pos = nx.drawing.layout._sparse_spectral(A)
160
+ assert pos.shape == (6, 2)
161
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
162
+ assert pos.shape == (6, 3)
163
+
164
+ def test_single_nodes(self):
165
+ G = nx.path_graph(1)
166
+ vpos = nx.shell_layout(G)
167
+ assert not vpos[0].any()
168
+ G = nx.path_graph(4)
169
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]])
170
+ assert not vpos[0].any()
171
+ assert vpos[3].any() # ensure node 3 not at origin (#3188)
172
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
173
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0)
174
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
175
+
176
+ def test_smoke_initial_pos_fruchterman_reingold(self):
177
+ pos = nx.circular_layout(self.Gi)
178
+ npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
179
+
180
+ def test_smoke_initial_pos_arf(self):
181
+ pos = nx.circular_layout(self.Gi)
182
+ npos = nx.arf_layout(self.Gi, pos=pos)
183
+
184
+ def test_fixed_node_fruchterman_reingold(self):
185
+ # Dense version (numpy based)
186
+ pos = nx.circular_layout(self.Gi)
187
+ npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)])
188
+ assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)])
189
+ # Sparse version (scipy based)
190
+ pos = nx.circular_layout(self.bigG)
191
+ npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)])
192
+ for axis in range(2):
193
+ assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7)
194
+
195
+ def test_center_parameter(self):
196
+ G = nx.path_graph(1)
197
+ nx.random_layout(G, center=(1, 1))
198
+ vpos = nx.circular_layout(G, center=(1, 1))
199
+ assert tuple(vpos[0]) == (1, 1)
200
+ vpos = nx.planar_layout(G, center=(1, 1))
201
+ assert tuple(vpos[0]) == (1, 1)
202
+ vpos = nx.spring_layout(G, center=(1, 1))
203
+ assert tuple(vpos[0]) == (1, 1)
204
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
205
+ assert tuple(vpos[0]) == (1, 1)
206
+ vpos = nx.spectral_layout(G, center=(1, 1))
207
+ assert tuple(vpos[0]) == (1, 1)
208
+ vpos = nx.shell_layout(G, center=(1, 1))
209
+ assert tuple(vpos[0]) == (1, 1)
210
+ vpos = nx.spiral_layout(G, center=(1, 1))
211
+ assert tuple(vpos[0]) == (1, 1)
212
+
213
+ def test_center_wrong_dimensions(self):
214
+ G = nx.path_graph(1)
215
+ assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout)
216
+ pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1))
217
+ pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1))
218
+ pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1))
219
+ pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1))
220
+ pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1))
221
+ pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1))
222
+ pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1))
223
+ pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
224
+ pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1))
225
+ pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1))
226
+
227
+ def test_empty_graph(self):
228
+ G = nx.empty_graph()
229
+ vpos = nx.random_layout(G, center=(1, 1))
230
+ assert vpos == {}
231
+ vpos = nx.circular_layout(G, center=(1, 1))
232
+ assert vpos == {}
233
+ vpos = nx.planar_layout(G, center=(1, 1))
234
+ assert vpos == {}
235
+ vpos = nx.bipartite_layout(G, G)
236
+ assert vpos == {}
237
+ vpos = nx.spring_layout(G, center=(1, 1))
238
+ assert vpos == {}
239
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
240
+ assert vpos == {}
241
+ vpos = nx.spectral_layout(G, center=(1, 1))
242
+ assert vpos == {}
243
+ vpos = nx.shell_layout(G, center=(1, 1))
244
+ assert vpos == {}
245
+ vpos = nx.spiral_layout(G, center=(1, 1))
246
+ assert vpos == {}
247
+ vpos = nx.multipartite_layout(G, center=(1, 1))
248
+ assert vpos == {}
249
+ vpos = nx.kamada_kawai_layout(G, center=(1, 1))
250
+ assert vpos == {}
251
+ vpos = nx.arf_layout(G)
252
+ assert vpos == {}
253
+
254
+ def test_bipartite_layout(self):
255
+ G = nx.complete_bipartite_graph(3, 5)
256
+ top, bottom = nx.bipartite.sets(G)
257
+
258
+ vpos = nx.bipartite_layout(G, top)
259
+ assert len(vpos) == len(G)
260
+
261
+ top_x = vpos[list(top)[0]][0]
262
+ bottom_x = vpos[list(bottom)[0]][0]
263
+ for node in top:
264
+ assert vpos[node][0] == top_x
265
+ for node in bottom:
266
+ assert vpos[node][0] == bottom_x
267
+
268
+ vpos = nx.bipartite_layout(
269
+ G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1
270
+ )
271
+ assert len(vpos) == len(G)
272
+
273
+ top_y = vpos[list(top)[0]][1]
274
+ bottom_y = vpos[list(bottom)[0]][1]
275
+ for node in top:
276
+ assert vpos[node][1] == top_y
277
+ for node in bottom:
278
+ assert vpos[node][1] == bottom_y
279
+
280
+ pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo")
281
+
282
+ def test_multipartite_layout(self):
283
+ sizes = (0, 5, 7, 2, 8)
284
+ G = nx.complete_multipartite_graph(*sizes)
285
+
286
+ vpos = nx.multipartite_layout(G)
287
+ assert len(vpos) == len(G)
288
+
289
+ start = 0
290
+ for n in sizes:
291
+ end = start + n
292
+ assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end))
293
+ start += n
294
+
295
+ vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2))
296
+ assert len(vpos) == len(G)
297
+
298
+ start = 0
299
+ for n in sizes:
300
+ end = start + n
301
+ assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end))
302
+ start += n
303
+
304
+ pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
305
+
306
+ def test_kamada_kawai_costfn_1d(self):
307
+ costfn = nx.drawing.layout._kamada_kawai_costfn
308
+
309
+ pos = np.array([4.0, 7.0])
310
+ invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]])
311
+
312
+ cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1)
313
+
314
+ assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7)
315
+ assert grad[0] == pytest.approx((-0.5), abs=1e-7)
316
+ assert grad[1] == pytest.approx(0.5, abs=1e-7)
317
+
318
+ def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim):
319
+ costfn = nx.drawing.layout._kamada_kawai_costfn
320
+
321
+ cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim)
322
+
323
+ expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2)
324
+ for i in range(pos.shape[0]):
325
+ for j in range(i + 1, pos.shape[0]):
326
+ diff = np.linalg.norm(pos[i] - pos[j])
327
+ expected_cost += (diff * invdist[i][j] - 1.0) ** 2
328
+
329
+ assert cost == pytest.approx(expected_cost, abs=1e-7)
330
+
331
+ dx = 1e-4
332
+ for nd in range(pos.shape[0]):
333
+ for dm in range(pos.shape[1]):
334
+ idx = nd * pos.shape[1] + dm
335
+ ps = pos.flatten()
336
+
337
+ ps[idx] += dx
338
+ cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
339
+
340
+ ps[idx] -= 2 * dx
341
+ cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
342
+
343
+ assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5)
344
+
345
+ def test_kamada_kawai_costfn(self):
346
+ invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]])
347
+ meanwt = 0.3
348
+
349
+ # 2d
350
+ pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]])
351
+
352
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2)
353
+
354
+ # 3d
355
+ pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]])
356
+
357
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3)
358
+
359
+ def test_spiral_layout(self):
360
+ G = self.Gs
361
+
362
+ # a lower value of resolution should result in a more compact layout
363
+ # intuitively, the total distance from the start and end nodes
364
+ # via each node in between (transiting through each) will be less,
365
+ # assuming rescaling does not occur on the computed node positions
366
+ pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values()))
367
+ pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values()))
368
+ distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1)
369
+ distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1)
370
+ assert sum(distances) > sum(distances_tighter)
371
+
372
+ # return near-equidistant points after the first value if set to true
373
+ pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values()))
374
+ distances_equidistant = np.linalg.norm(
375
+ pos_equidistant[:-1] - pos_equidistant[1:], axis=1
376
+ )
377
+ assert np.allclose(
378
+ distances_equidistant[1:], distances_equidistant[-1], atol=0.01
379
+ )
380
+
381
+ def test_spiral_layout_equidistant(self):
382
+ G = nx.path_graph(10)
383
+ pos = nx.spiral_layout(G, equidistant=True)
384
+ # Extract individual node positions as an array
385
+ p = np.array(list(pos.values()))
386
+ # Elementwise-distance between node positions
387
+ dist = np.linalg.norm(p[1:] - p[:-1], axis=1)
388
+ assert np.allclose(np.diff(dist), 0, atol=1e-3)
389
+
390
+ def test_rescale_layout_dict(self):
391
+ G = nx.empty_graph()
392
+ vpos = nx.random_layout(G, center=(1, 1))
393
+ assert nx.rescale_layout_dict(vpos) == {}
394
+
395
+ G = nx.empty_graph(2)
396
+ vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)}
397
+ s_vpos = nx.rescale_layout_dict(vpos)
398
+ assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6
399
+
400
+ G = nx.empty_graph(3)
401
+ vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)}
402
+ s_vpos = nx.rescale_layout_dict(vpos)
403
+
404
+ expectation = {
405
+ 0: np.array((-1, -1)),
406
+ 1: np.array((1, 1)),
407
+ 2: np.array((0, 0)),
408
+ }
409
+ for k, v in expectation.items():
410
+ assert (s_vpos[k] == v).all()
411
+ s_vpos = nx.rescale_layout_dict(vpos, scale=2)
412
+ expectation = {
413
+ 0: np.array((-2, -2)),
414
+ 1: np.array((2, 2)),
415
+ 2: np.array((0, 0)),
416
+ }
417
+ for k, v in expectation.items():
418
+ assert (s_vpos[k] == v).all()
419
+
420
+ def test_arf_layout_partial_input_test(self):
421
+ """
422
+ Checks whether partial pos input still returns a proper position.
423
+ """
424
+ G = self.Gs
425
+ node = nx.utils.arbitrary_element(G)
426
+ pos = nx.circular_layout(G)
427
+ del pos[node]
428
+ pos = nx.arf_layout(G, pos=pos)
429
+ assert len(pos) == len(G)
430
+
431
+ def test_arf_layout_negative_a_check(self):
432
+ """
433
+ Checks input parameters correctly raises errors. For example, `a` should be larger than 1
434
+ """
435
+ G = self.Gs
436
+ pytest.raises(ValueError, nx.arf_layout, G=G, a=-1)
437
+
438
+
439
+ def test_multipartite_layout_nonnumeric_partition_labels():
440
+ """See gh-5123."""
441
+ G = nx.Graph()
442
+ G.add_node(0, subset="s0")
443
+ G.add_node(1, subset="s0")
444
+ G.add_node(2, subset="s1")
445
+ G.add_node(3, subset="s1")
446
+ G.add_edges_from([(0, 2), (0, 3), (1, 2)])
447
+ pos = nx.multipartite_layout(G)
448
+ assert len(pos) == len(G)
449
+
450
+
451
+ def test_multipartite_layout_layer_order():
452
+ """Return the layers in sorted order if the layers of the multipartite
453
+ graph are sortable. See gh-5691"""
454
+ G = nx.Graph()
455
+ node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4)))
456
+ for node, layer in node_group.items():
457
+ G.add_node(node, subset=layer)
458
+
459
+ # Horizontal alignment, therefore y-coord determines layers
460
+ pos = nx.multipartite_layout(G, align="horizontal")
461
+
462
+ layers = nx.utils.groups(node_group)
463
+ pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers)
464
+ for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()):
465
+ assert n1 == n2 and (p1 == p2).all()
466
+
467
+ # Nodes "a" and "d" are in the same layer
468
+ assert pos["a"][-1] == pos["d"][-1]
469
+ # positions should be sorted according to layer
470
+ assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1]
471
+
472
+ # Make sure that multipartite_layout still works when layers are not sortable
473
+ G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints
474
+ pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise
475
+ assert pos_nosort.keys() == pos.keys()
476
+
477
+
478
+ def _num_nodes_per_bfs_layer(pos):
479
+ """Helper function to extract the number of nodes in each layer of bfs_layout"""
480
+ x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension
481
+ _, layer_count = np.unique(x, return_counts=True)
482
+ return layer_count
483
+
484
+
485
+ @pytest.mark.parametrize("n", range(2, 7))
486
+ def test_bfs_layout_complete_graph(n):
487
+ """The complete graph should result in two layers: the starting node and
488
+ a second layer containing all neighbors."""
489
+ G = nx.complete_graph(n)
490
+ pos = nx.bfs_layout(G, start=0)
491
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1])
492
+
493
+
494
+ def test_bfs_layout_barbell():
495
+ G = nx.barbell_graph(5, 3)
496
+ # Start in one of the "bells"
497
+ pos = nx.bfs_layout(G, start=0)
498
+ # start, bell-1, [1] * len(bar)+1, bell-1
499
+ expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4]
500
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
501
+ # Start in the other "bell" - expect same layer pattern
502
+ pos = nx.bfs_layout(G, start=12)
503
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
504
+ # Starting in the center of the bar, expect layers to be symmetric
505
+ pos = nx.bfs_layout(G, start=6)
506
+ # Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells}
507
+ expected_nodes_per_layer = [1, 2, 2, 8]
508
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
509
+
510
+
511
+ def test_bfs_layout_disconnected():
512
+ G = nx.complete_graph(5)
513
+ G.add_edges_from([(10, 11), (11, 12)])
514
+ with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"):
515
+ nx.bfs_layout(G, start=0)
env-llmeval/lib/python3.10/site-packages/networkx/generators/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A package for generating various graphs in networkx.
3
+
4
+ """
5
+ from networkx.generators.atlas import *
6
+ from networkx.generators.classic import *
7
+ from networkx.generators.cographs import *
8
+ from networkx.generators.community import *
9
+ from networkx.generators.degree_seq import *
10
+ from networkx.generators.directed import *
11
+ from networkx.generators.duplication import *
12
+ from networkx.generators.ego import *
13
+ from networkx.generators.expanders import *
14
+ from networkx.generators.geometric import *
15
+ from networkx.generators.harary_graph import *
16
+ from networkx.generators.internet_as_graphs import *
17
+ from networkx.generators.intersection import *
18
+ from networkx.generators.interval_graph import *
19
+ from networkx.generators.joint_degree_seq import *
20
+ from networkx.generators.lattice import *
21
+ from networkx.generators.line import *
22
+ from networkx.generators.mycielski import *
23
+ from networkx.generators.nonisomorphic_trees import *
24
+ from networkx.generators.random_clustered import *
25
+ from networkx.generators.random_graphs import *
26
+ from networkx.generators.small import *
27
+ from networkx.generators.social import *
28
+ from networkx.generators.spectral_graph_forge import *
29
+ from networkx.generators.stochastic import *
30
+ from networkx.generators.sudoku import *
31
+ from networkx.generators.time_series import *
32
+ from networkx.generators.trees import *
33
+ from networkx.generators.triads import *
env-llmeval/lib/python3.10/site-packages/networkx/generators/atlas.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for the small graph atlas.
3
+ """
4
+ import gzip
5
+ import importlib.resources
6
+ import os
7
+ import os.path
8
+ from itertools import islice
9
+
10
+ import networkx as nx
11
+
12
+ __all__ = ["graph_atlas", "graph_atlas_g"]
13
+
14
+ #: The total number of graphs in the atlas.
15
+ #:
16
+ #: The graphs are labeled starting from 0 and extending to (but not
17
+ #: including) this number.
18
+ NUM_GRAPHS = 1253
19
+
20
+ #: The path to the data file containing the graph edge lists.
21
+ #:
22
+ #: This is the absolute path of the gzipped text file containing the
23
+ #: edge list for each graph in the atlas. The file contains one entry
24
+ #: per graph in the atlas, in sequential order, starting from graph
25
+ #: number 0 and extending through graph number 1252 (see
26
+ #: :data:`NUM_GRAPHS`). Each entry looks like
27
+ #:
28
+ #: .. sourcecode:: text
29
+ #:
30
+ #: GRAPH 6
31
+ #: NODES 3
32
+ #: 0 1
33
+ #: 0 2
34
+ #:
35
+ #: where the first two lines are the graph's index in the atlas and the
36
+ #: number of nodes in the graph, and the remaining lines are the edge
37
+ #: list.
38
+ #:
39
+ #: This file was generated from a Python list of graphs via code like
40
+ #: the following::
41
+ #:
42
+ #: import gzip
43
+ #: from networkx.generators.atlas import graph_atlas_g
44
+ #: from networkx.readwrite.edgelist import write_edgelist
45
+ #:
46
+ #: with gzip.open('atlas.dat.gz', 'wb') as f:
47
+ #: for i, G in enumerate(graph_atlas_g()):
48
+ #: f.write(bytes(f'GRAPH {i}\n', encoding='utf-8'))
49
+ #: f.write(bytes(f'NODES {len(G)}\n', encoding='utf-8'))
50
+ #: write_edgelist(G, f, data=False)
51
+ #:
52
+
53
+ # Path to the atlas file
54
+ ATLAS_FILE = importlib.resources.files("networkx.generators") / "atlas.dat.gz"
55
+
56
+
57
+ def _generate_graphs():
58
+ """Sequentially read the file containing the edge list data for the
59
+ graphs in the atlas and generate the graphs one at a time.
60
+
61
+ This function reads the file given in :data:`.ATLAS_FILE`.
62
+
63
+ """
64
+ with gzip.open(ATLAS_FILE, "rb") as f:
65
+ line = f.readline()
66
+ while line and line.startswith(b"GRAPH"):
67
+ # The first two lines of each entry tell us the index of the
68
+ # graph in the list and the number of nodes in the graph.
69
+ # They look like this:
70
+ #
71
+ # GRAPH 3
72
+ # NODES 2
73
+ #
74
+ graph_index = int(line[6:].rstrip())
75
+ line = f.readline()
76
+ num_nodes = int(line[6:].rstrip())
77
+ # The remaining lines contain the edge list, until the next
78
+ # GRAPH line (or until the end of the file).
79
+ edgelist = []
80
+ line = f.readline()
81
+ while line and not line.startswith(b"GRAPH"):
82
+ edgelist.append(line.rstrip())
83
+ line = f.readline()
84
+ G = nx.Graph()
85
+ G.name = f"G{graph_index}"
86
+ G.add_nodes_from(range(num_nodes))
87
+ G.add_edges_from(tuple(map(int, e.split())) for e in edgelist)
88
+ yield G
89
+
90
+
91
+ @nx._dispatchable(graphs=None, returns_graph=True)
92
+ def graph_atlas(i):
93
+ """Returns graph number `i` from the Graph Atlas.
94
+
95
+ For more information, see :func:`.graph_atlas_g`.
96
+
97
+ Parameters
98
+ ----------
99
+ i : int
100
+ The index of the graph from the atlas to get. The graph at index
101
+ 0 is assumed to be the null graph.
102
+
103
+ Returns
104
+ -------
105
+ list
106
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
107
+ corresponding to the graph *i* in the Graph Atlas.
108
+
109
+ See also
110
+ --------
111
+ graph_atlas_g
112
+
113
+ Notes
114
+ -----
115
+ The time required by this function increases linearly with the
116
+ argument `i`, since it reads a large file sequentially in order to
117
+ generate the graph [1]_.
118
+
119
+ References
120
+ ----------
121
+ .. [1] Ronald C. Read and Robin J. Wilson, *An Atlas of Graphs*.
122
+ Oxford University Press, 1998.
123
+
124
+ """
125
+ if not (0 <= i < NUM_GRAPHS):
126
+ raise ValueError(f"index must be between 0 and {NUM_GRAPHS}")
127
+ return next(islice(_generate_graphs(), i, None))
128
+
129
+
130
+ @nx._dispatchable(graphs=None, returns_graph=True)
131
+ def graph_atlas_g():
132
+ """Returns the list of all graphs with up to seven nodes named in the
133
+ Graph Atlas.
134
+
135
+ The graphs are listed in increasing order by
136
+
137
+ 1. number of nodes,
138
+ 2. number of edges,
139
+ 3. degree sequence (for example 111223 < 112222),
140
+ 4. number of automorphisms,
141
+
142
+ in that order, with three exceptions as described in the *Notes*
143
+ section below. This causes the list to correspond with the index of
144
+ the graphs in the Graph Atlas [atlas]_, with the first graph,
145
+ ``G[0]``, being the null graph.
146
+
147
+ Returns
148
+ -------
149
+ list
150
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
151
+ corresponding to the graph *i* in the Graph Atlas.
152
+
153
+ See also
154
+ --------
155
+ graph_atlas
156
+
157
+ Notes
158
+ -----
159
+ This function may be expensive in both time and space, since it
160
+ reads a large file sequentially in order to populate the list.
161
+
162
+ Although the NetworkX atlas functions match the order of graphs
163
+ given in the "Atlas of Graphs" book, there are (at least) three
164
+ errors in the ordering described in the book. The following three
165
+ pairs of nodes violate the lexicographically nondecreasing sorted
166
+ degree sequence rule:
167
+
168
+ - graphs 55 and 56 with degree sequences 001111 and 000112,
169
+ - graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
170
+ - graphs 1012 and 1213 with degree sequences 1244555 and 1244456.
171
+
172
+ References
173
+ ----------
174
+ .. [atlas] Ronald C. Read and Robin J. Wilson,
175
+ *An Atlas of Graphs*.
176
+ Oxford University Press, 1998.
177
+
178
+ """
179
+ return list(_generate_graphs())
env-llmeval/lib/python3.10/site-packages/networkx/generators/classic.py ADDED
@@ -0,0 +1,1054 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for some classic graphs.
2
+
3
+ The typical graph builder function is called as follows:
4
+
5
+ >>> G = nx.complete_graph(100)
6
+
7
+ returning the complete graph on n nodes labeled 0, .., 99
8
+ as a simple graph. Except for `empty_graph`, all the functions
9
+ in this module return a Graph class (i.e. a simple, undirected graph).
10
+
11
+ """
12
+
13
+ import itertools
14
+ import numbers
15
+
16
+ import networkx as nx
17
+ from networkx.classes import Graph
18
+ from networkx.exception import NetworkXError
19
+ from networkx.utils import nodes_or_number, pairwise
20
+
21
+ __all__ = [
22
+ "balanced_tree",
23
+ "barbell_graph",
24
+ "binomial_tree",
25
+ "complete_graph",
26
+ "complete_multipartite_graph",
27
+ "circular_ladder_graph",
28
+ "circulant_graph",
29
+ "cycle_graph",
30
+ "dorogovtsev_goltsev_mendes_graph",
31
+ "empty_graph",
32
+ "full_rary_tree",
33
+ "kneser_graph",
34
+ "ladder_graph",
35
+ "lollipop_graph",
36
+ "null_graph",
37
+ "path_graph",
38
+ "star_graph",
39
+ "tadpole_graph",
40
+ "trivial_graph",
41
+ "turan_graph",
42
+ "wheel_graph",
43
+ ]
44
+
45
+
46
+ # -------------------------------------------------------------------
47
+ # Some Classic Graphs
48
+ # -------------------------------------------------------------------
49
+
50
+
51
+ def _tree_edges(n, r):
52
+ if n == 0:
53
+ return
54
+ # helper function for trees
55
+ # yields edges in rooted tree at 0 with n nodes and branching ratio r
56
+ nodes = iter(range(n))
57
+ parents = [next(nodes)] # stack of max length r
58
+ while parents:
59
+ source = parents.pop(0)
60
+ for i in range(r):
61
+ try:
62
+ target = next(nodes)
63
+ parents.append(target)
64
+ yield source, target
65
+ except StopIteration:
66
+ break
67
+
68
+
69
+ @nx._dispatchable(graphs=None, returns_graph=True)
70
+ def full_rary_tree(r, n, create_using=None):
71
+ """Creates a full r-ary tree of `n` nodes.
72
+
73
+ Sometimes called a k-ary, n-ary, or m-ary tree.
74
+ "... all non-leaf nodes have exactly r children and all levels
75
+ are full except for some rightmost position of the bottom level
76
+ (if a leaf at the bottom level is missing, then so are all of the
77
+ leaves to its right." [1]_
78
+
79
+ .. plot::
80
+
81
+ >>> nx.draw(nx.full_rary_tree(2, 10))
82
+
83
+ Parameters
84
+ ----------
85
+ r : int
86
+ branching factor of the tree
87
+ n : int
88
+ Number of nodes in the tree
89
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
90
+ Graph type to create. If graph instance, then cleared before populated.
91
+
92
+ Returns
93
+ -------
94
+ G : networkx Graph
95
+ An r-ary tree with n nodes
96
+
97
+ References
98
+ ----------
99
+ .. [1] An introduction to data structures and algorithms,
100
+ James Andrew Storer, Birkhauser Boston 2001, (page 225).
101
+ """
102
+ G = empty_graph(n, create_using)
103
+ G.add_edges_from(_tree_edges(n, r))
104
+ return G
105
+
106
+
107
+ @nx._dispatchable(graphs=None, returns_graph=True)
108
+ def kneser_graph(n, k):
109
+ """Returns the Kneser Graph with parameters `n` and `k`.
110
+
111
+ The Kneser Graph has nodes that are k-tuples (subsets) of the integers
112
+ between 0 and ``n-1``. Nodes are adjacent if their corresponding sets are disjoint.
113
+
114
+ Parameters
115
+ ----------
116
+ n: int
117
+ Number of integers from which to make node subsets.
118
+ Subsets are drawn from ``set(range(n))``.
119
+ k: int
120
+ Size of the subsets.
121
+
122
+ Returns
123
+ -------
124
+ G : NetworkX Graph
125
+
126
+ Examples
127
+ --------
128
+ >>> G = nx.kneser_graph(5, 2)
129
+ >>> G.number_of_nodes()
130
+ 10
131
+ >>> G.number_of_edges()
132
+ 15
133
+ >>> nx.is_isomorphic(G, nx.petersen_graph())
134
+ True
135
+ """
136
+ if n <= 0:
137
+ raise NetworkXError("n should be greater than zero")
138
+ if k <= 0 or k > n:
139
+ raise NetworkXError("k should be greater than zero and smaller than n")
140
+
141
+ G = nx.Graph()
142
+ # Create all k-subsets of [0, 1, ..., n-1]
143
+ subsets = list(itertools.combinations(range(n), k))
144
+
145
+ if 2 * k > n:
146
+ G.add_nodes_from(subsets)
147
+
148
+ universe = set(range(n))
149
+ comb = itertools.combinations # only to make it all fit on one line
150
+ G.add_edges_from((s, t) for s in subsets for t in comb(universe - set(s), k))
151
+ return G
152
+
153
+
154
+ @nx._dispatchable(graphs=None, returns_graph=True)
155
+ def balanced_tree(r, h, create_using=None):
156
+ """Returns the perfectly balanced `r`-ary tree of height `h`.
157
+
158
+ .. plot::
159
+
160
+ >>> nx.draw(nx.balanced_tree(2, 3))
161
+
162
+ Parameters
163
+ ----------
164
+ r : int
165
+ Branching factor of the tree; each node will have `r`
166
+ children.
167
+
168
+ h : int
169
+ Height of the tree.
170
+
171
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
172
+ Graph type to create. If graph instance, then cleared before populated.
173
+
174
+ Returns
175
+ -------
176
+ G : NetworkX graph
177
+ A balanced `r`-ary tree of height `h`.
178
+
179
+ Notes
180
+ -----
181
+ This is the rooted tree where all leaves are at distance `h` from
182
+ the root. The root has degree `r` and all other internal nodes
183
+ have degree `r + 1`.
184
+
185
+ Node labels are integers, starting from zero.
186
+
187
+ A balanced tree is also known as a *complete r-ary tree*.
188
+
189
+ """
190
+ # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
191
+ # which is computed by using the closed-form formula for a geometric
192
+ # sum with ratio `r`. In the special case that `r` is 1, the number
193
+ # of nodes is simply `h + 1` (since the tree is actually a path
194
+ # graph).
195
+ if r == 1:
196
+ n = h + 1
197
+ else:
198
+ # This must be an integer if both `r` and `h` are integers. If
199
+ # they are not, we force integer division anyway.
200
+ n = (1 - r ** (h + 1)) // (1 - r)
201
+ return full_rary_tree(r, n, create_using=create_using)
202
+
203
+
204
+ @nx._dispatchable(graphs=None, returns_graph=True)
205
+ def barbell_graph(m1, m2, create_using=None):
206
+ """Returns the Barbell Graph: two complete graphs connected by a path.
207
+
208
+ .. plot::
209
+
210
+ >>> nx.draw(nx.barbell_graph(4, 2))
211
+
212
+ Parameters
213
+ ----------
214
+ m1 : int
215
+ Size of the left and right barbells, must be greater than 2.
216
+
217
+ m2 : int
218
+ Length of the path connecting the barbells.
219
+
220
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
221
+ Graph type to create. If graph instance, then cleared before populated.
222
+ Only undirected Graphs are supported.
223
+
224
+ Returns
225
+ -------
226
+ G : NetworkX graph
227
+ A barbell graph.
228
+
229
+ Notes
230
+ -----
231
+
232
+
233
+ Two identical complete graphs $K_{m1}$ form the left and right bells,
234
+ and are connected by a path $P_{m2}$.
235
+
236
+ The `2*m1+m2` nodes are numbered
237
+ `0, ..., m1-1` for the left barbell,
238
+ `m1, ..., m1+m2-1` for the path,
239
+ and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
240
+
241
+ The 3 subgraphs are joined via the edges `(m1-1, m1)` and
242
+ `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
243
+ graphs joined together.
244
+
245
+ This graph is an extremal example in David Aldous
246
+ and Jim Fill's e-text on Random Walks on Graphs.
247
+
248
+ """
249
+ if m1 < 2:
250
+ raise NetworkXError("Invalid graph description, m1 should be >=2")
251
+ if m2 < 0:
252
+ raise NetworkXError("Invalid graph description, m2 should be >=0")
253
+
254
+ # left barbell
255
+ G = complete_graph(m1, create_using)
256
+ if G.is_directed():
257
+ raise NetworkXError("Directed Graph not supported")
258
+
259
+ # connecting path
260
+ G.add_nodes_from(range(m1, m1 + m2 - 1))
261
+ if m2 > 1:
262
+ G.add_edges_from(pairwise(range(m1, m1 + m2)))
263
+
264
+ # right barbell
265
+ G.add_edges_from(
266
+ (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
267
+ )
268
+
269
+ # connect it up
270
+ G.add_edge(m1 - 1, m1)
271
+ if m2 > 0:
272
+ G.add_edge(m1 + m2 - 1, m1 + m2)
273
+
274
+ return G
275
+
276
+
277
+ @nx._dispatchable(graphs=None, returns_graph=True)
278
+ def binomial_tree(n, create_using=None):
279
+ """Returns the Binomial Tree of order n.
280
+
281
+ The binomial tree of order 0 consists of a single node. A binomial tree of order k
282
+ is defined recursively by linking two binomial trees of order k-1: the root of one is
283
+ the leftmost child of the root of the other.
284
+
285
+ .. plot::
286
+
287
+ >>> nx.draw(nx.binomial_tree(3))
288
+
289
+ Parameters
290
+ ----------
291
+ n : int
292
+ Order of the binomial tree.
293
+
294
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
295
+ Graph type to create. If graph instance, then cleared before populated.
296
+
297
+ Returns
298
+ -------
299
+ G : NetworkX graph
300
+ A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
301
+
302
+ """
303
+ G = nx.empty_graph(1, create_using)
304
+
305
+ N = 1
306
+ for i in range(n):
307
+ # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
308
+ edges = [(u + N, v + N) for (u, v) in G.edges()]
309
+ G.add_edges_from(edges)
310
+ G.add_edge(0, N)
311
+ N *= 2
312
+ return G
313
+
314
+
315
+ @nx._dispatchable(graphs=None, returns_graph=True)
316
+ @nodes_or_number(0)
317
+ def complete_graph(n, create_using=None):
318
+ """Return the complete graph `K_n` with n nodes.
319
+
320
+ A complete graph on `n` nodes means that all pairs
321
+ of distinct nodes have an edge connecting them.
322
+
323
+ .. plot::
324
+
325
+ >>> nx.draw(nx.complete_graph(5))
326
+
327
+ Parameters
328
+ ----------
329
+ n : int or iterable container of nodes
330
+ If n is an integer, nodes are from range(n).
331
+ If n is a container of nodes, those nodes appear in the graph.
332
+ Warning: n is not checked for duplicates and if present the
333
+ resulting graph may not be as desired. Make sure you have no duplicates.
334
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
335
+ Graph type to create. If graph instance, then cleared before populated.
336
+
337
+ Examples
338
+ --------
339
+ >>> G = nx.complete_graph(9)
340
+ >>> len(G)
341
+ 9
342
+ >>> G.size()
343
+ 36
344
+ >>> G = nx.complete_graph(range(11, 14))
345
+ >>> list(G.nodes())
346
+ [11, 12, 13]
347
+ >>> G = nx.complete_graph(4, nx.DiGraph())
348
+ >>> G.is_directed()
349
+ True
350
+
351
+ """
352
+ _, nodes = n
353
+ G = empty_graph(nodes, create_using)
354
+ if len(nodes) > 1:
355
+ if G.is_directed():
356
+ edges = itertools.permutations(nodes, 2)
357
+ else:
358
+ edges = itertools.combinations(nodes, 2)
359
+ G.add_edges_from(edges)
360
+ return G
361
+
362
+
363
+ @nx._dispatchable(graphs=None, returns_graph=True)
364
+ def circular_ladder_graph(n, create_using=None):
365
+ """Returns the circular ladder graph $CL_n$ of length n.
366
+
367
+ $CL_n$ consists of two concentric n-cycles in which
368
+ each of the n pairs of concentric nodes are joined by an edge.
369
+
370
+ Node labels are the integers 0 to n-1
371
+
372
+ .. plot::
373
+
374
+ >>> nx.draw(nx.circular_ladder_graph(5))
375
+
376
+ """
377
+ G = ladder_graph(n, create_using)
378
+ G.add_edge(0, n - 1)
379
+ G.add_edge(n, 2 * n - 1)
380
+ return G
381
+
382
+
383
+ @nx._dispatchable(graphs=None, returns_graph=True)
384
+ def circulant_graph(n, offsets, create_using=None):
385
+ r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
386
+
387
+ The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
388
+ such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
389
+ for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
390
+
391
+ .. plot::
392
+
393
+ >>> nx.draw(nx.circulant_graph(10, [1]))
394
+
395
+ Parameters
396
+ ----------
397
+ n : integer
398
+ The number of nodes in the graph.
399
+ offsets : list of integers
400
+ A list of node offsets, $x_1$ up to $x_m$, as described above.
401
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
402
+ Graph type to create. If graph instance, then cleared before populated.
403
+
404
+ Returns
405
+ -------
406
+ NetworkX Graph of type create_using
407
+
408
+ Examples
409
+ --------
410
+ Many well-known graph families are subfamilies of the circulant graphs;
411
+ for example, to create the cycle graph on n points, we connect every
412
+ node to nodes on either side (with offset plus or minus one). For n = 10,
413
+
414
+ >>> G = nx.circulant_graph(10, [1])
415
+ >>> edges = [
416
+ ... (0, 9),
417
+ ... (0, 1),
418
+ ... (1, 2),
419
+ ... (2, 3),
420
+ ... (3, 4),
421
+ ... (4, 5),
422
+ ... (5, 6),
423
+ ... (6, 7),
424
+ ... (7, 8),
425
+ ... (8, 9),
426
+ ... ]
427
+ >>> sorted(edges) == sorted(G.edges())
428
+ True
429
+
430
+ Similarly, we can create the complete graph
431
+ on 5 points with the set of offsets [1, 2]:
432
+
433
+ >>> G = nx.circulant_graph(5, [1, 2])
434
+ >>> edges = [
435
+ ... (0, 1),
436
+ ... (0, 2),
437
+ ... (0, 3),
438
+ ... (0, 4),
439
+ ... (1, 2),
440
+ ... (1, 3),
441
+ ... (1, 4),
442
+ ... (2, 3),
443
+ ... (2, 4),
444
+ ... (3, 4),
445
+ ... ]
446
+ >>> sorted(edges) == sorted(G.edges())
447
+ True
448
+
449
+ """
450
+ G = empty_graph(n, create_using)
451
+ for i in range(n):
452
+ for j in offsets:
453
+ G.add_edge(i, (i - j) % n)
454
+ G.add_edge(i, (i + j) % n)
455
+ return G
456
+
457
+
458
+ @nx._dispatchable(graphs=None, returns_graph=True)
459
+ @nodes_or_number(0)
460
+ def cycle_graph(n, create_using=None):
461
+ """Returns the cycle graph $C_n$ of cyclically connected nodes.
462
+
463
+ $C_n$ is a path with its two end-nodes connected.
464
+
465
+ .. plot::
466
+
467
+ >>> nx.draw(nx.cycle_graph(5))
468
+
469
+ Parameters
470
+ ----------
471
+ n : int or iterable container of nodes
472
+ If n is an integer, nodes are from `range(n)`.
473
+ If n is a container of nodes, those nodes appear in the graph.
474
+ Warning: n is not checked for duplicates and if present the
475
+ resulting graph may not be as desired. Make sure you have no duplicates.
476
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
477
+ Graph type to create. If graph instance, then cleared before populated.
478
+
479
+ Notes
480
+ -----
481
+ If create_using is directed, the direction is in increasing order.
482
+
483
+ """
484
+ _, nodes = n
485
+ G = empty_graph(nodes, create_using)
486
+ G.add_edges_from(pairwise(nodes, cyclic=True))
487
+ return G
488
+
489
+
490
+ @nx._dispatchable(graphs=None, returns_graph=True)
491
+ def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
492
+ """Returns the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.
493
+
494
+ The Dorogovtsev-Goltsev-Mendes [1]_ procedure produces a scale-free graph
495
+ deterministically with the following properties for a given `n`:
496
+ - Total number of nodes = ``3 * (3**n + 1) / 2``
497
+ - Total number of edges = ``3 ** (n + 1)``
498
+
499
+ .. plot::
500
+
501
+ >>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
502
+
503
+ Parameters
504
+ ----------
505
+ n : integer
506
+ The generation number.
507
+
508
+ create_using : NetworkX Graph, optional
509
+ Graph type to be returned. Directed graphs and multi graphs are not
510
+ supported.
511
+
512
+ Returns
513
+ -------
514
+ G : NetworkX Graph
515
+
516
+ Examples
517
+ --------
518
+ >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
519
+ >>> G.number_of_nodes()
520
+ 15
521
+ >>> G.number_of_edges()
522
+ 27
523
+ >>> nx.is_planar(G)
524
+ True
525
+
526
+ References
527
+ ----------
528
+ .. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
529
+ "Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
530
+ https://arxiv.org/pdf/cond-mat/0112143.pdf
531
+ """
532
+ G = empty_graph(0, create_using)
533
+ if G.is_directed():
534
+ raise NetworkXError("Directed Graph not supported")
535
+ if G.is_multigraph():
536
+ raise NetworkXError("Multigraph not supported")
537
+
538
+ G.add_edge(0, 1)
539
+ if n == 0:
540
+ return G
541
+ new_node = 2 # next node to be added
542
+ for i in range(1, n + 1): # iterate over number of generations.
543
+ last_generation_edges = list(G.edges())
544
+ number_of_edges_in_last_generation = len(last_generation_edges)
545
+ for j in range(number_of_edges_in_last_generation):
546
+ G.add_edge(new_node, last_generation_edges[j][0])
547
+ G.add_edge(new_node, last_generation_edges[j][1])
548
+ new_node += 1
549
+ return G
550
+
551
+
552
+ @nx._dispatchable(graphs=None, returns_graph=True)
553
+ @nodes_or_number(0)
554
+ def empty_graph(n=0, create_using=None, default=Graph):
555
+ """Returns the empty graph with n nodes and zero edges.
556
+
557
+ .. plot::
558
+
559
+ >>> nx.draw(nx.empty_graph(5))
560
+
561
+ Parameters
562
+ ----------
563
+ n : int or iterable container of nodes (default = 0)
564
+ If n is an integer, nodes are from `range(n)`.
565
+ If n is a container of nodes, those nodes appear in the graph.
566
+ create_using : Graph Instance, Constructor or None
567
+ Indicator of type of graph to return.
568
+ If a Graph-type instance, then clear and use it.
569
+ If None, use the `default` constructor.
570
+ If a constructor, call it to create an empty graph.
571
+ default : Graph constructor (optional, default = nx.Graph)
572
+ The constructor to use if create_using is None.
573
+ If None, then nx.Graph is used.
574
+ This is used when passing an unknown `create_using` value
575
+ through your home-grown function to `empty_graph` and
576
+ you want a default constructor other than nx.Graph.
577
+
578
+ Examples
579
+ --------
580
+ >>> G = nx.empty_graph(10)
581
+ >>> G.number_of_nodes()
582
+ 10
583
+ >>> G.number_of_edges()
584
+ 0
585
+ >>> G = nx.empty_graph("ABC")
586
+ >>> G.number_of_nodes()
587
+ 3
588
+ >>> sorted(G)
589
+ ['A', 'B', 'C']
590
+
591
+ Notes
592
+ -----
593
+ The variable create_using should be a Graph Constructor or a
594
+ "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
595
+ will be used to create the returned graph. "graph"-like objects
596
+ will be cleared (nodes and edges will be removed) and refitted as
597
+ an empty "graph" with nodes specified in n. This capability
598
+ is useful for specifying the class-nature of the resulting empty
599
+ "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
600
+
601
+ The variable create_using has three main uses:
602
+ Firstly, the variable create_using can be used to create an
603
+ empty digraph, multigraph, etc. For example,
604
+
605
+ >>> n = 10
606
+ >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
607
+
608
+ will create an empty digraph on n nodes.
609
+
610
+ Secondly, one can pass an existing graph (digraph, multigraph,
611
+ etc.) via create_using. For example, if G is an existing graph
612
+ (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
613
+ will empty G (i.e. delete all nodes and edges using G.clear())
614
+ and then add n nodes and zero edges, and return the modified graph.
615
+
616
+ Thirdly, when constructing your home-grown graph creation function
617
+ you can use empty_graph to construct the graph by passing a user
618
+ defined create_using to empty_graph. In this case, if you want the
619
+ default constructor to be other than nx.Graph, specify `default`.
620
+
621
+ >>> def mygraph(n, create_using=None):
622
+ ... G = nx.empty_graph(n, create_using, nx.MultiGraph)
623
+ ... G.add_edges_from([(0, 1), (0, 1)])
624
+ ... return G
625
+ >>> G = mygraph(3)
626
+ >>> G.is_multigraph()
627
+ True
628
+ >>> G = mygraph(3, nx.Graph)
629
+ >>> G.is_multigraph()
630
+ False
631
+
632
+ See also create_empty_copy(G).
633
+
634
+ """
635
+ if create_using is None:
636
+ G = default()
637
+ elif isinstance(create_using, type):
638
+ G = create_using()
639
+ elif not hasattr(create_using, "adj"):
640
+ raise TypeError("create_using is not a valid NetworkX graph type or instance")
641
+ else:
642
+ # create_using is a NetworkX style Graph
643
+ create_using.clear()
644
+ G = create_using
645
+
646
+ _, nodes = n
647
+ G.add_nodes_from(nodes)
648
+ return G
649
+
650
+
651
+ @nx._dispatchable(graphs=None, returns_graph=True)
652
+ def ladder_graph(n, create_using=None):
653
+ """Returns the Ladder graph of length n.
654
+
655
+ This is two paths of n nodes, with
656
+ each pair connected by a single edge.
657
+
658
+ Node labels are the integers 0 to 2*n - 1.
659
+
660
+ .. plot::
661
+
662
+ >>> nx.draw(nx.ladder_graph(5))
663
+
664
+ """
665
+ G = empty_graph(2 * n, create_using)
666
+ if G.is_directed():
667
+ raise NetworkXError("Directed Graph not supported")
668
+ G.add_edges_from(pairwise(range(n)))
669
+ G.add_edges_from(pairwise(range(n, 2 * n)))
670
+ G.add_edges_from((v, v + n) for v in range(n))
671
+ return G
672
+
673
+
674
+ @nx._dispatchable(graphs=None, returns_graph=True)
675
+ @nodes_or_number([0, 1])
676
+ def lollipop_graph(m, n, create_using=None):
677
+ """Returns the Lollipop Graph; ``K_m`` connected to ``P_n``.
678
+
679
+ This is the Barbell Graph without the right barbell.
680
+
681
+ .. plot::
682
+
683
+ >>> nx.draw(nx.lollipop_graph(3, 4))
684
+
685
+ Parameters
686
+ ----------
687
+ m, n : int or iterable container of nodes
688
+ If an integer, nodes are from ``range(m)`` and ``range(m, m+n)``.
689
+ If a container of nodes, those nodes appear in the graph.
690
+ Warning: `m` and `n` are not checked for duplicates and if present the
691
+ resulting graph may not be as desired. Make sure you have no duplicates.
692
+
693
+ The nodes for `m` appear in the complete graph $K_m$ and the nodes
694
+ for `n` appear in the path $P_n$
695
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
696
+ Graph type to create. If graph instance, then cleared before populated.
697
+
698
+ Returns
699
+ -------
700
+ Networkx graph
701
+ A complete graph with `m` nodes connected to a path of length `n`.
702
+
703
+ Notes
704
+ -----
705
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
706
+ If ``n=0``, this is merely a complete graph.
707
+
708
+ (This graph is an extremal example in David Aldous and Jim
709
+ Fill's etext on Random Walks on Graphs.)
710
+
711
+ """
712
+ m, m_nodes = m
713
+ M = len(m_nodes)
714
+ if M < 2:
715
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
716
+
717
+ n, n_nodes = n
718
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
719
+ n_nodes = list(range(M, M + n))
720
+ N = len(n_nodes)
721
+
722
+ # the ball
723
+ G = complete_graph(m_nodes, create_using)
724
+ if G.is_directed():
725
+ raise NetworkXError("Directed Graph not supported")
726
+
727
+ # the stick
728
+ G.add_nodes_from(n_nodes)
729
+ if N > 1:
730
+ G.add_edges_from(pairwise(n_nodes))
731
+
732
+ if len(G) != M + N:
733
+ raise NetworkXError("Nodes must be distinct in containers m and n")
734
+
735
+ # connect ball to stick
736
+ if M > 0 and N > 0:
737
+ G.add_edge(m_nodes[-1], n_nodes[0])
738
+ return G
739
+
740
+
741
+ @nx._dispatchable(graphs=None, returns_graph=True)
742
+ def null_graph(create_using=None):
743
+ """Returns the Null graph with no nodes or edges.
744
+
745
+ See empty_graph for the use of create_using.
746
+
747
+ """
748
+ G = empty_graph(0, create_using)
749
+ return G
750
+
751
+
752
+ @nx._dispatchable(graphs=None, returns_graph=True)
753
+ @nodes_or_number(0)
754
+ def path_graph(n, create_using=None):
755
+ """Returns the Path graph `P_n` of linearly connected nodes.
756
+
757
+ .. plot::
758
+
759
+ >>> nx.draw(nx.path_graph(5))
760
+
761
+ Parameters
762
+ ----------
763
+ n : int or iterable
764
+ If an integer, nodes are 0 to n - 1.
765
+ If an iterable of nodes, in the order they appear in the path.
766
+ Warning: n is not checked for duplicates and if present the
767
+ resulting graph may not be as desired. Make sure you have no duplicates.
768
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
769
+ Graph type to create. If graph instance, then cleared before populated.
770
+
771
+ """
772
+ _, nodes = n
773
+ G = empty_graph(nodes, create_using)
774
+ G.add_edges_from(pairwise(nodes))
775
+ return G
776
+
777
+
778
+ @nx._dispatchable(graphs=None, returns_graph=True)
779
+ @nodes_or_number(0)
780
+ def star_graph(n, create_using=None):
781
+ """Return the star graph
782
+
783
+ The star graph consists of one center node connected to n outer nodes.
784
+
785
+ .. plot::
786
+
787
+ >>> nx.draw(nx.star_graph(6))
788
+
789
+ Parameters
790
+ ----------
791
+ n : int or iterable
792
+ If an integer, node labels are 0 to n with center 0.
793
+ If an iterable of nodes, the center is the first.
794
+ Warning: n is not checked for duplicates and if present the
795
+ resulting graph may not be as desired. Make sure you have no duplicates.
796
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
797
+ Graph type to create. If graph instance, then cleared before populated.
798
+
799
+ Notes
800
+ -----
801
+ The graph has n+1 nodes for integer n.
802
+ So star_graph(3) is the same as star_graph(range(4)).
803
+ """
804
+ n, nodes = n
805
+ if isinstance(n, numbers.Integral):
806
+ nodes.append(int(n)) # there should be n+1 nodes
807
+ G = empty_graph(nodes, create_using)
808
+ if G.is_directed():
809
+ raise NetworkXError("Directed Graph not supported")
810
+
811
+ if len(nodes) > 1:
812
+ hub, *spokes = nodes
813
+ G.add_edges_from((hub, node) for node in spokes)
814
+ return G
815
+
816
+
817
+ @nx._dispatchable(graphs=None, returns_graph=True)
818
+ @nodes_or_number([0, 1])
819
+ def tadpole_graph(m, n, create_using=None):
820
+ """Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``.
821
+
822
+ This graph on m+n nodes connects a cycle of size `m` to a path of length `n`.
823
+ It looks like a tadpole. It is also called a kite graph or a dragon graph.
824
+
825
+ .. plot::
826
+
827
+ >>> nx.draw(nx.tadpole_graph(3, 5))
828
+
829
+ Parameters
830
+ ----------
831
+ m, n : int or iterable container of nodes
832
+ If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``.
833
+ If a container of nodes, those nodes appear in the graph.
834
+ Warning: `m` and `n` are not checked for duplicates and if present the
835
+ resulting graph may not be as desired.
836
+
837
+ The nodes for `m` appear in the cycle graph $C_m$ and the nodes
838
+ for `n` appear in the path $P_n$.
839
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
840
+ Graph type to create. If graph instance, then cleared before populated.
841
+
842
+ Returns
843
+ -------
844
+ Networkx graph
845
+ A cycle of size `m` connected to a path of length `n`.
846
+
847
+ Raises
848
+ ------
849
+ NetworkXError
850
+ If ``m < 2``. The tadpole graph is undefined for ``m<2``.
851
+
852
+ Notes
853
+ -----
854
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
855
+ If ``n=0``, this is a cycle graph.
856
+ `m` and/or `n` can be a container of nodes instead of an integer.
857
+
858
+ """
859
+ m, m_nodes = m
860
+ M = len(m_nodes)
861
+ if M < 2:
862
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
863
+
864
+ n, n_nodes = n
865
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
866
+ n_nodes = list(range(M, M + n))
867
+
868
+ # the circle
869
+ G = cycle_graph(m_nodes, create_using)
870
+ if G.is_directed():
871
+ raise NetworkXError("Directed Graph not supported")
872
+
873
+ # the stick
874
+ nx.add_path(G, [m_nodes[-1]] + list(n_nodes))
875
+
876
+ return G
877
+
878
+
879
+ @nx._dispatchable(graphs=None, returns_graph=True)
880
+ def trivial_graph(create_using=None):
881
+ """Return the Trivial graph with one node (with label 0) and no edges.
882
+
883
+ .. plot::
884
+
885
+ >>> nx.draw(nx.trivial_graph(), with_labels=True)
886
+
887
+ """
888
+ G = empty_graph(1, create_using)
889
+ return G
890
+
891
+
892
+ @nx._dispatchable(graphs=None, returns_graph=True)
893
+ def turan_graph(n, r):
894
+ r"""Return the Turan Graph
895
+
896
+ The Turan Graph is a complete multipartite graph on $n$ nodes
897
+ with $r$ disjoint subsets. That is, edges connect each node to
898
+ every node not in its subset.
899
+
900
+ Given $n$ and $r$, we create a complete multipartite graph with
901
+ $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
902
+ $n \mod r$ partitions of size $n/r+1$, rounded down.
903
+
904
+ .. plot::
905
+
906
+ >>> nx.draw(nx.turan_graph(6, 2))
907
+
908
+ Parameters
909
+ ----------
910
+ n : int
911
+ The number of nodes.
912
+ r : int
913
+ The number of partitions.
914
+ Must be less than or equal to n.
915
+
916
+ Notes
917
+ -----
918
+ Must satisfy $1 <= r <= n$.
919
+ The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
920
+ """
921
+
922
+ if not 1 <= r <= n:
923
+ raise NetworkXError("Must satisfy 1 <= r <= n")
924
+
925
+ partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
926
+ G = complete_multipartite_graph(*partitions)
927
+ return G
928
+
929
+
930
+ @nx._dispatchable(graphs=None, returns_graph=True)
931
+ @nodes_or_number(0)
932
+ def wheel_graph(n, create_using=None):
933
+ """Return the wheel graph
934
+
935
+ The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
936
+
937
+ .. plot::
938
+
939
+ >>> nx.draw(nx.wheel_graph(5))
940
+
941
+ Parameters
942
+ ----------
943
+ n : int or iterable
944
+ If an integer, node labels are 0 to n with center 0.
945
+ If an iterable of nodes, the center is the first.
946
+ Warning: n is not checked for duplicates and if present the
947
+ resulting graph may not be as desired. Make sure you have no duplicates.
948
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
949
+ Graph type to create. If graph instance, then cleared before populated.
950
+
951
+ Node labels are the integers 0 to n - 1.
952
+ """
953
+ _, nodes = n
954
+ G = empty_graph(nodes, create_using)
955
+ if G.is_directed():
956
+ raise NetworkXError("Directed Graph not supported")
957
+
958
+ if len(nodes) > 1:
959
+ hub, *rim = nodes
960
+ G.add_edges_from((hub, node) for node in rim)
961
+ if len(rim) > 1:
962
+ G.add_edges_from(pairwise(rim, cyclic=True))
963
+ return G
964
+
965
+
966
+ @nx._dispatchable(graphs=None, returns_graph=True)
967
+ def complete_multipartite_graph(*subset_sizes):
968
+ """Returns the complete multipartite graph with the specified subset sizes.
969
+
970
+ .. plot::
971
+
972
+ >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3))
973
+
974
+ Parameters
975
+ ----------
976
+ subset_sizes : tuple of integers or tuple of node iterables
977
+ The arguments can either all be integer number of nodes or they
978
+ can all be iterables of nodes. If integers, they represent the
979
+ number of nodes in each subset of the multipartite graph.
980
+ If iterables, each is used to create the nodes for that subset.
981
+ The length of subset_sizes is the number of subsets.
982
+
983
+ Returns
984
+ -------
985
+ G : NetworkX Graph
986
+ Returns the complete multipartite graph with the specified subsets.
987
+
988
+ For each node, the node attribute 'subset' is an integer
989
+ indicating which subset contains the node.
990
+
991
+ Examples
992
+ --------
993
+ Creating a complete tripartite graph, with subsets of one, two, and three
994
+ nodes, respectively.
995
+
996
+ >>> G = nx.complete_multipartite_graph(1, 2, 3)
997
+ >>> [G.nodes[u]["subset"] for u in G]
998
+ [0, 1, 1, 2, 2, 2]
999
+ >>> list(G.edges(0))
1000
+ [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
1001
+ >>> list(G.edges(2))
1002
+ [(2, 0), (2, 3), (2, 4), (2, 5)]
1003
+ >>> list(G.edges(4))
1004
+ [(4, 0), (4, 1), (4, 2)]
1005
+
1006
+ >>> G = nx.complete_multipartite_graph("a", "bc", "def")
1007
+ >>> [G.nodes[u]["subset"] for u in sorted(G)]
1008
+ [0, 1, 1, 2, 2, 2]
1009
+
1010
+ Notes
1011
+ -----
1012
+ This function generalizes several other graph builder functions.
1013
+
1014
+ - If no subset sizes are given, this returns the null graph.
1015
+ - If a single subset size `n` is given, this returns the empty graph on
1016
+ `n` nodes.
1017
+ - If two subset sizes `m` and `n` are given, this returns the complete
1018
+ bipartite graph on `m + n` nodes.
1019
+ - If subset sizes `1` and `n` are given, this returns the star graph on
1020
+ `n + 1` nodes.
1021
+
1022
+ See also
1023
+ --------
1024
+ complete_bipartite_graph
1025
+ """
1026
+ # The complete multipartite graph is an undirected simple graph.
1027
+ G = Graph()
1028
+
1029
+ if len(subset_sizes) == 0:
1030
+ return G
1031
+
1032
+ # set up subsets of nodes
1033
+ try:
1034
+ extents = pairwise(itertools.accumulate((0,) + subset_sizes))
1035
+ subsets = [range(start, end) for start, end in extents]
1036
+ except TypeError:
1037
+ subsets = subset_sizes
1038
+ else:
1039
+ if any(size < 0 for size in subset_sizes):
1040
+ raise NetworkXError(f"Negative number of nodes not valid: {subset_sizes}")
1041
+
1042
+ # add nodes with subset attribute
1043
+ # while checking that ints are not mixed with iterables
1044
+ try:
1045
+ for i, subset in enumerate(subsets):
1046
+ G.add_nodes_from(subset, subset=i)
1047
+ except TypeError as err:
1048
+ raise NetworkXError("Arguments must be all ints or all iterables") from err
1049
+
1050
+ # Across subsets, all nodes should be adjacent.
1051
+ # We can use itertools.combinations() because undirected.
1052
+ for subset1, subset2 in itertools.combinations(subsets, 2):
1053
+ G.add_edges_from(itertools.product(subset1, subset2))
1054
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/cographs.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Generators for cographs
2
+
3
+ A cograph is a graph containing no path on four vertices.
4
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
5
+ by disjoint union and complementation operations.
6
+
7
+ References
8
+ ----------
9
+ .. [0] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
10
+ "Complement reducible graphs",
11
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
12
+ ISSN 0166-218X.
13
+ """
14
+ import networkx as nx
15
+ from networkx.utils import py_random_state
16
+
17
+ __all__ = ["random_cograph"]
18
+
19
+
20
+ @py_random_state(1)
21
+ @nx._dispatchable(graphs=None, returns_graph=True)
22
+ def random_cograph(n, seed=None):
23
+ r"""Returns a random cograph with $2 ^ n$ nodes.
24
+
25
+ A cograph is a graph containing no path on four vertices.
26
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
27
+ by disjoint union and complementation operations.
28
+
29
+ This generator starts off from a single vertex and performs disjoint
30
+ union and full join operations on itself.
31
+ The decision on which operation will take place is random.
32
+
33
+ Parameters
34
+ ----------
35
+ n : int
36
+ The order of the cograph.
37
+ seed : integer, random_state, or None (default)
38
+ Indicator of random number generation state.
39
+ See :ref:`Randomness<randomness>`.
40
+
41
+ Returns
42
+ -------
43
+ G : A random graph containing no path on four vertices.
44
+
45
+ See Also
46
+ --------
47
+ full_join
48
+ union
49
+
50
+ References
51
+ ----------
52
+ .. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
53
+ "Complement reducible graphs",
54
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
55
+ ISSN 0166-218X.
56
+ """
57
+ R = nx.empty_graph(1)
58
+
59
+ for i in range(n):
60
+ RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
61
+
62
+ if seed.randint(0, 1) == 0:
63
+ R = nx.full_join(R, RR)
64
+ else:
65
+ R = nx.disjoint_union(R, RR)
66
+
67
+ return R
env-llmeval/lib/python3.10/site-packages/networkx/generators/community.py ADDED
@@ -0,0 +1,1069 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for classes of graphs used in studying social networks."""
2
+ import itertools
3
+ import math
4
+
5
+ import networkx as nx
6
+ from networkx.utils import py_random_state
7
+
8
+ __all__ = [
9
+ "caveman_graph",
10
+ "connected_caveman_graph",
11
+ "relaxed_caveman_graph",
12
+ "random_partition_graph",
13
+ "planted_partition_graph",
14
+ "gaussian_random_partition_graph",
15
+ "ring_of_cliques",
16
+ "windmill_graph",
17
+ "stochastic_block_model",
18
+ "LFR_benchmark_graph",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable(graphs=None, returns_graph=True)
23
+ def caveman_graph(l, k):
24
+ """Returns a caveman graph of `l` cliques of size `k`.
25
+
26
+ Parameters
27
+ ----------
28
+ l : int
29
+ Number of cliques
30
+ k : int
31
+ Size of cliques
32
+
33
+ Returns
34
+ -------
35
+ G : NetworkX Graph
36
+ caveman graph
37
+
38
+ Notes
39
+ -----
40
+ This returns an undirected graph, it can be converted to a directed
41
+ graph using :func:`nx.to_directed`, or a multigraph using
42
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
43
+ described in [1]_ and it is unclear which of the directed
44
+ generalizations is most useful.
45
+
46
+ Examples
47
+ --------
48
+ >>> G = nx.caveman_graph(3, 3)
49
+
50
+ See also
51
+ --------
52
+
53
+ connected_caveman_graph
54
+
55
+ References
56
+ ----------
57
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
58
+ Amer. J. Soc. 105, 493-527, 1999.
59
+ """
60
+ # l disjoint cliques of size k
61
+ G = nx.empty_graph(l * k)
62
+ if k > 1:
63
+ for start in range(0, l * k, k):
64
+ edges = itertools.combinations(range(start, start + k), 2)
65
+ G.add_edges_from(edges)
66
+ return G
67
+
68
+
69
+ @nx._dispatchable(graphs=None, returns_graph=True)
70
+ def connected_caveman_graph(l, k):
71
+ """Returns a connected caveman graph of `l` cliques of size `k`.
72
+
73
+ The connected caveman graph is formed by creating `n` cliques of size
74
+ `k`, then a single edge in each clique is rewired to a node in an
75
+ adjacent clique.
76
+
77
+ Parameters
78
+ ----------
79
+ l : int
80
+ number of cliques
81
+ k : int
82
+ size of cliques (k at least 2 or NetworkXError is raised)
83
+
84
+ Returns
85
+ -------
86
+ G : NetworkX Graph
87
+ connected caveman graph
88
+
89
+ Raises
90
+ ------
91
+ NetworkXError
92
+ If the size of cliques `k` is smaller than 2.
93
+
94
+ Notes
95
+ -----
96
+ This returns an undirected graph, it can be converted to a directed
97
+ graph using :func:`nx.to_directed`, or a multigraph using
98
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
99
+ described in [1]_ and it is unclear which of the directed
100
+ generalizations is most useful.
101
+
102
+ Examples
103
+ --------
104
+ >>> G = nx.connected_caveman_graph(3, 3)
105
+
106
+ References
107
+ ----------
108
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
109
+ Amer. J. Soc. 105, 493-527, 1999.
110
+ """
111
+ if k < 2:
112
+ raise nx.NetworkXError(
113
+ "The size of cliques in a connected caveman graph must be at least 2."
114
+ )
115
+
116
+ G = nx.caveman_graph(l, k)
117
+ for start in range(0, l * k, k):
118
+ G.remove_edge(start, start + 1)
119
+ G.add_edge(start, (start - 1) % (l * k))
120
+ return G
121
+
122
+
123
+ @py_random_state(3)
124
+ @nx._dispatchable(graphs=None, returns_graph=True)
125
+ def relaxed_caveman_graph(l, k, p, seed=None):
126
+ """Returns a relaxed caveman graph.
127
+
128
+ A relaxed caveman graph starts with `l` cliques of size `k`. Edges are
129
+ then randomly rewired with probability `p` to link different cliques.
130
+
131
+ Parameters
132
+ ----------
133
+ l : int
134
+ Number of groups
135
+ k : int
136
+ Size of cliques
137
+ p : float
138
+ Probability of rewiring each edge.
139
+ seed : integer, random_state, or None (default)
140
+ Indicator of random number generation state.
141
+ See :ref:`Randomness<randomness>`.
142
+
143
+ Returns
144
+ -------
145
+ G : NetworkX Graph
146
+ Relaxed Caveman Graph
147
+
148
+ Raises
149
+ ------
150
+ NetworkXError
151
+ If p is not in [0,1]
152
+
153
+ Examples
154
+ --------
155
+ >>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42)
156
+
157
+ References
158
+ ----------
159
+ .. [1] Santo Fortunato, Community Detection in Graphs,
160
+ Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174.
161
+ https://arxiv.org/abs/0906.0612
162
+ """
163
+ G = nx.caveman_graph(l, k)
164
+ nodes = list(G)
165
+ for u, v in G.edges():
166
+ if seed.random() < p: # rewire the edge
167
+ x = seed.choice(nodes)
168
+ if G.has_edge(u, x):
169
+ continue
170
+ G.remove_edge(u, v)
171
+ G.add_edge(u, x)
172
+ return G
173
+
174
+
175
+ @py_random_state(3)
176
+ @nx._dispatchable(graphs=None, returns_graph=True)
177
+ def random_partition_graph(sizes, p_in, p_out, seed=None, directed=False):
178
+ """Returns the random partition graph with a partition of sizes.
179
+
180
+ A partition graph is a graph of communities with sizes defined by
181
+ s in sizes. Nodes in the same group are connected with probability
182
+ p_in and nodes of different groups are connected with probability
183
+ p_out.
184
+
185
+ Parameters
186
+ ----------
187
+ sizes : list of ints
188
+ Sizes of groups
189
+ p_in : float
190
+ probability of edges with in groups
191
+ p_out : float
192
+ probability of edges between groups
193
+ directed : boolean optional, default=False
194
+ Whether to create a directed graph
195
+ seed : integer, random_state, or None (default)
196
+ Indicator of random number generation state.
197
+ See :ref:`Randomness<randomness>`.
198
+
199
+ Returns
200
+ -------
201
+ G : NetworkX Graph or DiGraph
202
+ random partition graph of size sum(gs)
203
+
204
+ Raises
205
+ ------
206
+ NetworkXError
207
+ If p_in or p_out is not in [0,1]
208
+
209
+ Examples
210
+ --------
211
+ >>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
212
+ >>> len(G)
213
+ 30
214
+ >>> partition = G.graph["partition"]
215
+ >>> len(partition)
216
+ 3
217
+
218
+ Notes
219
+ -----
220
+ This is a generalization of the planted-l-partition described in
221
+ [1]_. It allows for the creation of groups of any size.
222
+
223
+ The partition is store as a graph attribute 'partition'.
224
+
225
+ References
226
+ ----------
227
+ .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
228
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
229
+ """
230
+ # Use geometric method for O(n+m) complexity algorithm
231
+ # partition = nx.community_sets(nx.get_node_attributes(G, 'affiliation'))
232
+ if not 0.0 <= p_in <= 1.0:
233
+ raise nx.NetworkXError("p_in must be in [0,1]")
234
+ if not 0.0 <= p_out <= 1.0:
235
+ raise nx.NetworkXError("p_out must be in [0,1]")
236
+
237
+ # create connection matrix
238
+ num_blocks = len(sizes)
239
+ p = [[p_out for s in range(num_blocks)] for r in range(num_blocks)]
240
+ for r in range(num_blocks):
241
+ p[r][r] = p_in
242
+
243
+ return stochastic_block_model(
244
+ sizes,
245
+ p,
246
+ nodelist=None,
247
+ seed=seed,
248
+ directed=directed,
249
+ selfloops=False,
250
+ sparse=True,
251
+ )
252
+
253
+
254
+ @py_random_state(4)
255
+ @nx._dispatchable(graphs=None, returns_graph=True)
256
+ def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
257
+ """Returns the planted l-partition graph.
258
+
259
+ This model partitions a graph with n=l*k vertices in
260
+ l groups with k vertices each. Vertices of the same
261
+ group are linked with a probability p_in, and vertices
262
+ of different groups are linked with probability p_out.
263
+
264
+ Parameters
265
+ ----------
266
+ l : int
267
+ Number of groups
268
+ k : int
269
+ Number of vertices in each group
270
+ p_in : float
271
+ probability of connecting vertices within a group
272
+ p_out : float
273
+ probability of connected vertices between groups
274
+ seed : integer, random_state, or None (default)
275
+ Indicator of random number generation state.
276
+ See :ref:`Randomness<randomness>`.
277
+ directed : bool,optional (default=False)
278
+ If True return a directed graph
279
+
280
+ Returns
281
+ -------
282
+ G : NetworkX Graph or DiGraph
283
+ planted l-partition graph
284
+
285
+ Raises
286
+ ------
287
+ NetworkXError
288
+ If `p_in`, `p_out` are not in `[0, 1]`
289
+
290
+ Examples
291
+ --------
292
+ >>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)
293
+
294
+ See Also
295
+ --------
296
+ random_partition_model
297
+
298
+ References
299
+ ----------
300
+ .. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
301
+ on the planted partition model,
302
+ Random Struct. Algor. 18 (2001) 116-140.
303
+
304
+ .. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
305
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
306
+ """
307
+ return random_partition_graph([k] * l, p_in, p_out, seed=seed, directed=directed)
308
+
309
+
310
+ @py_random_state(6)
311
+ @nx._dispatchable(graphs=None, returns_graph=True)
312
+ def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
313
+ """Generate a Gaussian random partition graph.
314
+
315
+ A Gaussian random partition graph is created by creating k partitions
316
+ each with a size drawn from a normal distribution with mean s and variance
317
+ s/v. Nodes are connected within clusters with probability p_in and
318
+ between clusters with probability p_out[1]
319
+
320
+ Parameters
321
+ ----------
322
+ n : int
323
+ Number of nodes in the graph
324
+ s : float
325
+ Mean cluster size
326
+ v : float
327
+ Shape parameter. The variance of cluster size distribution is s/v.
328
+ p_in : float
329
+ Probability of intra cluster connection.
330
+ p_out : float
331
+ Probability of inter cluster connection.
332
+ directed : boolean, optional default=False
333
+ Whether to create a directed graph or not
334
+ seed : integer, random_state, or None (default)
335
+ Indicator of random number generation state.
336
+ See :ref:`Randomness<randomness>`.
337
+
338
+ Returns
339
+ -------
340
+ G : NetworkX Graph or DiGraph
341
+ gaussian random partition graph
342
+
343
+ Raises
344
+ ------
345
+ NetworkXError
346
+ If s is > n
347
+ If p_in or p_out is not in [0,1]
348
+
349
+ Notes
350
+ -----
351
+ Note the number of partitions is dependent on s,v and n, and that the
352
+ last partition may be considerably smaller, as it is sized to simply
353
+ fill out the nodes [1]
354
+
355
+ See Also
356
+ --------
357
+ random_partition_graph
358
+
359
+ Examples
360
+ --------
361
+ >>> G = nx.gaussian_random_partition_graph(100, 10, 10, 0.25, 0.1)
362
+ >>> len(G)
363
+ 100
364
+
365
+ References
366
+ ----------
367
+ .. [1] Ulrik Brandes, Marco Gaertler, Dorothea Wagner,
368
+ Experiments on Graph Clustering Algorithms,
369
+ In the proceedings of the 11th Europ. Symp. Algorithms, 2003.
370
+ """
371
+ if s > n:
372
+ raise nx.NetworkXError("s must be <= n")
373
+ assigned = 0
374
+ sizes = []
375
+ while True:
376
+ size = int(seed.gauss(s, s / v + 0.5))
377
+ if size < 1: # how to handle 0 or negative sizes?
378
+ continue
379
+ if assigned + size >= n:
380
+ sizes.append(n - assigned)
381
+ break
382
+ assigned += size
383
+ sizes.append(size)
384
+ return random_partition_graph(sizes, p_in, p_out, seed=seed, directed=directed)
385
+
386
+
387
+ @nx._dispatchable(graphs=None, returns_graph=True)
388
+ def ring_of_cliques(num_cliques, clique_size):
389
+ """Defines a "ring of cliques" graph.
390
+
391
+ A ring of cliques graph is consisting of cliques, connected through single
392
+ links. Each clique is a complete graph.
393
+
394
+ Parameters
395
+ ----------
396
+ num_cliques : int
397
+ Number of cliques
398
+ clique_size : int
399
+ Size of cliques
400
+
401
+ Returns
402
+ -------
403
+ G : NetworkX Graph
404
+ ring of cliques graph
405
+
406
+ Raises
407
+ ------
408
+ NetworkXError
409
+ If the number of cliques is lower than 2 or
410
+ if the size of cliques is smaller than 2.
411
+
412
+ Examples
413
+ --------
414
+ >>> G = nx.ring_of_cliques(8, 4)
415
+
416
+ See Also
417
+ --------
418
+ connected_caveman_graph
419
+
420
+ Notes
421
+ -----
422
+ The `connected_caveman_graph` graph removes a link from each clique to
423
+ connect it with the next clique. Instead, the `ring_of_cliques` graph
424
+ simply adds the link without removing any link from the cliques.
425
+ """
426
+ if num_cliques < 2:
427
+ raise nx.NetworkXError("A ring of cliques must have at least two cliques")
428
+ if clique_size < 2:
429
+ raise nx.NetworkXError("The cliques must have at least two nodes")
430
+
431
+ G = nx.Graph()
432
+ for i in range(num_cliques):
433
+ edges = itertools.combinations(
434
+ range(i * clique_size, i * clique_size + clique_size), 2
435
+ )
436
+ G.add_edges_from(edges)
437
+ G.add_edge(
438
+ i * clique_size + 1, (i + 1) * clique_size % (num_cliques * clique_size)
439
+ )
440
+ return G
441
+
442
+
443
+ @nx._dispatchable(graphs=None, returns_graph=True)
444
+ def windmill_graph(n, k):
445
+ """Generate a windmill graph.
446
+ A windmill graph is a graph of `n` cliques each of size `k` that are all
447
+ joined at one node.
448
+ It can be thought of as taking a disjoint union of `n` cliques of size `k`,
449
+ selecting one point from each, and contracting all of the selected points.
450
+ Alternatively, one could generate `n` cliques of size `k-1` and one node
451
+ that is connected to all other nodes in the graph.
452
+
453
+ Parameters
454
+ ----------
455
+ n : int
456
+ Number of cliques
457
+ k : int
458
+ Size of cliques
459
+
460
+ Returns
461
+ -------
462
+ G : NetworkX Graph
463
+ windmill graph with n cliques of size k
464
+
465
+ Raises
466
+ ------
467
+ NetworkXError
468
+ If the number of cliques is less than two
469
+ If the size of the cliques are less than two
470
+
471
+ Examples
472
+ --------
473
+ >>> G = nx.windmill_graph(4, 5)
474
+
475
+ Notes
476
+ -----
477
+ The node labeled `0` will be the node connected to all other nodes.
478
+ Note that windmill graphs are usually denoted `Wd(k,n)`, so the parameters
479
+ are in the opposite order as the parameters of this method.
480
+ """
481
+ if n < 2:
482
+ msg = "A windmill graph must have at least two cliques"
483
+ raise nx.NetworkXError(msg)
484
+ if k < 2:
485
+ raise nx.NetworkXError("The cliques must have at least two nodes")
486
+
487
+ G = nx.disjoint_union_all(
488
+ itertools.chain(
489
+ [nx.complete_graph(k)], (nx.complete_graph(k - 1) for _ in range(n - 1))
490
+ )
491
+ )
492
+ G.add_edges_from((0, i) for i in range(k, G.number_of_nodes()))
493
+ return G
494
+
495
+
496
+ @py_random_state(3)
497
+ @nx._dispatchable(graphs=None, returns_graph=True)
498
+ def stochastic_block_model(
499
+ sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True
500
+ ):
501
+ """Returns a stochastic block model graph.
502
+
503
+ This model partitions the nodes in blocks of arbitrary sizes, and places
504
+ edges between pairs of nodes independently, with a probability that depends
505
+ on the blocks.
506
+
507
+ Parameters
508
+ ----------
509
+ sizes : list of ints
510
+ Sizes of blocks
511
+ p : list of list of floats
512
+ Element (r,s) gives the density of edges going from the nodes
513
+ of group r to nodes of group s.
514
+ p must match the number of groups (len(sizes) == len(p)),
515
+ and it must be symmetric if the graph is undirected.
516
+ nodelist : list, optional
517
+ The block tags are assigned according to the node identifiers
518
+ in nodelist. If nodelist is None, then the ordering is the
519
+ range [0,sum(sizes)-1].
520
+ seed : integer, random_state, or None (default)
521
+ Indicator of random number generation state.
522
+ See :ref:`Randomness<randomness>`.
523
+ directed : boolean optional, default=False
524
+ Whether to create a directed graph or not.
525
+ selfloops : boolean optional, default=False
526
+ Whether to include self-loops or not.
527
+ sparse: boolean optional, default=True
528
+ Use the sparse heuristic to speed up the generator.
529
+
530
+ Returns
531
+ -------
532
+ g : NetworkX Graph or DiGraph
533
+ Stochastic block model graph of size sum(sizes)
534
+
535
+ Raises
536
+ ------
537
+ NetworkXError
538
+ If probabilities are not in [0,1].
539
+ If the probability matrix is not square (directed case).
540
+ If the probability matrix is not symmetric (undirected case).
541
+ If the sizes list does not match nodelist or the probability matrix.
542
+ If nodelist contains duplicate.
543
+
544
+ Examples
545
+ --------
546
+ >>> sizes = [75, 75, 300]
547
+ >>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
548
+ >>> g = nx.stochastic_block_model(sizes, probs, seed=0)
549
+ >>> len(g)
550
+ 450
551
+ >>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True)
552
+ >>> for v in H.nodes(data=True):
553
+ ... print(round(v[1]["density"], 3))
554
+ 0.245
555
+ 0.348
556
+ 0.405
557
+ >>> for v in H.edges(data=True):
558
+ ... print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3))
559
+ 0.051
560
+ 0.022
561
+ 0.07
562
+
563
+ See Also
564
+ --------
565
+ random_partition_graph
566
+ planted_partition_graph
567
+ gaussian_random_partition_graph
568
+ gnp_random_graph
569
+
570
+ References
571
+ ----------
572
+ .. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S.,
573
+ "Stochastic blockmodels: First steps",
574
+ Social networks, 5(2), 109-137, 1983.
575
+ """
576
+ # Check if dimensions match
577
+ if len(sizes) != len(p):
578
+ raise nx.NetworkXException("'sizes' and 'p' do not match.")
579
+ # Check for probability symmetry (undirected) and shape (directed)
580
+ for row in p:
581
+ if len(p) != len(row):
582
+ raise nx.NetworkXException("'p' must be a square matrix.")
583
+ if not directed:
584
+ p_transpose = [list(i) for i in zip(*p)]
585
+ for i in zip(p, p_transpose):
586
+ for j in zip(i[0], i[1]):
587
+ if abs(j[0] - j[1]) > 1e-08:
588
+ raise nx.NetworkXException("'p' must be symmetric.")
589
+ # Check for probability range
590
+ for row in p:
591
+ for prob in row:
592
+ if prob < 0 or prob > 1:
593
+ raise nx.NetworkXException("Entries of 'p' not in [0,1].")
594
+ # Check for nodelist consistency
595
+ if nodelist is not None:
596
+ if len(nodelist) != sum(sizes):
597
+ raise nx.NetworkXException("'nodelist' and 'sizes' do not match.")
598
+ if len(nodelist) != len(set(nodelist)):
599
+ raise nx.NetworkXException("nodelist contains duplicate.")
600
+ else:
601
+ nodelist = range(sum(sizes))
602
+
603
+ # Setup the graph conditionally to the directed switch.
604
+ block_range = range(len(sizes))
605
+ if directed:
606
+ g = nx.DiGraph()
607
+ block_iter = itertools.product(block_range, block_range)
608
+ else:
609
+ g = nx.Graph()
610
+ block_iter = itertools.combinations_with_replacement(block_range, 2)
611
+ # Split nodelist in a partition (list of sets).
612
+ size_cumsum = [sum(sizes[0:x]) for x in range(len(sizes) + 1)]
613
+ g.graph["partition"] = [
614
+ set(nodelist[size_cumsum[x] : size_cumsum[x + 1]])
615
+ for x in range(len(size_cumsum) - 1)
616
+ ]
617
+ # Setup nodes and graph name
618
+ for block_id, nodes in enumerate(g.graph["partition"]):
619
+ for node in nodes:
620
+ g.add_node(node, block=block_id)
621
+
622
+ g.name = "stochastic_block_model"
623
+
624
+ # Test for edge existence
625
+ parts = g.graph["partition"]
626
+ for i, j in block_iter:
627
+ if i == j:
628
+ if directed:
629
+ if selfloops:
630
+ edges = itertools.product(parts[i], parts[i])
631
+ else:
632
+ edges = itertools.permutations(parts[i], 2)
633
+ else:
634
+ edges = itertools.combinations(parts[i], 2)
635
+ if selfloops:
636
+ edges = itertools.chain(edges, zip(parts[i], parts[i]))
637
+ for e in edges:
638
+ if seed.random() < p[i][j]:
639
+ g.add_edge(*e)
640
+ else:
641
+ edges = itertools.product(parts[i], parts[j])
642
+ if sparse:
643
+ if p[i][j] == 1: # Test edges cases p_ij = 0 or 1
644
+ for e in edges:
645
+ g.add_edge(*e)
646
+ elif p[i][j] > 0:
647
+ while True:
648
+ try:
649
+ logrand = math.log(seed.random())
650
+ skip = math.floor(logrand / math.log(1 - p[i][j]))
651
+ # consume "skip" edges
652
+ next(itertools.islice(edges, skip, skip), None)
653
+ e = next(edges)
654
+ g.add_edge(*e) # __safe
655
+ except StopIteration:
656
+ break
657
+ else:
658
+ for e in edges:
659
+ if seed.random() < p[i][j]:
660
+ g.add_edge(*e) # __safe
661
+ return g
662
+
663
+
664
+ def _zipf_rv_below(gamma, xmin, threshold, seed):
665
+ """Returns a random value chosen from the bounded Zipf distribution.
666
+
667
+ Repeatedly draws values from the Zipf distribution until the
668
+ threshold is met, then returns that value.
669
+ """
670
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
671
+ while result > threshold:
672
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
673
+ return result
674
+
675
+
676
+ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters, seed):
677
+ """Returns a list of numbers obeying a constrained power law distribution.
678
+
679
+ ``gamma`` and ``low`` are the parameters for the Zipf distribution.
680
+
681
+ ``high`` is the maximum allowed value for values draw from the Zipf
682
+ distribution. For more information, see :func:`_zipf_rv_below`.
683
+
684
+ ``condition`` and ``length`` are Boolean-valued functions on
685
+ lists. While generating the list, random values are drawn and
686
+ appended to the list until ``length`` is satisfied by the created
687
+ list. Once ``condition`` is satisfied, the sequence generated in
688
+ this way is returned.
689
+
690
+ ``max_iters`` indicates the number of times to generate a list
691
+ satisfying ``length``. If the number of iterations exceeds this
692
+ value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.
693
+
694
+ seed : integer, random_state, or None (default)
695
+ Indicator of random number generation state.
696
+ See :ref:`Randomness<randomness>`.
697
+ """
698
+ for i in range(max_iters):
699
+ seq = []
700
+ while not length(seq):
701
+ seq.append(_zipf_rv_below(gamma, low, high, seed))
702
+ if condition(seq):
703
+ return seq
704
+ raise nx.ExceededMaxIterations("Could not create power law sequence")
705
+
706
+
707
+ def _hurwitz_zeta(x, q, tolerance):
708
+ """The Hurwitz zeta function, or the Riemann zeta function of two arguments.
709
+
710
+ ``x`` must be greater than one and ``q`` must be positive.
711
+
712
+ This function repeatedly computes subsequent partial sums until
713
+ convergence, as decided by ``tolerance``.
714
+ """
715
+ z = 0
716
+ z_prev = -float("inf")
717
+ k = 0
718
+ while abs(z - z_prev) > tolerance:
719
+ z_prev = z
720
+ z += 1 / ((k + q) ** x)
721
+ k += 1
722
+ return z
723
+
724
+
725
+ def _generate_min_degree(gamma, average_degree, max_degree, tolerance, max_iters):
726
+ """Returns a minimum degree from the given average degree."""
727
+ # Defines zeta function whether or not Scipy is available
728
+ try:
729
+ from scipy.special import zeta
730
+ except ImportError:
731
+
732
+ def zeta(x, q):
733
+ return _hurwitz_zeta(x, q, tolerance)
734
+
735
+ min_deg_top = max_degree
736
+ min_deg_bot = 1
737
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
738
+ itrs = 0
739
+ mid_avg_deg = 0
740
+ while abs(mid_avg_deg - average_degree) > tolerance:
741
+ if itrs > max_iters:
742
+ raise nx.ExceededMaxIterations("Could not match average_degree")
743
+ mid_avg_deg = 0
744
+ for x in range(int(min_deg_mid), max_degree + 1):
745
+ mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid)
746
+ if mid_avg_deg > average_degree:
747
+ min_deg_top = min_deg_mid
748
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
749
+ else:
750
+ min_deg_bot = min_deg_mid
751
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
752
+ itrs += 1
753
+ # return int(min_deg_mid + 0.5)
754
+ return round(min_deg_mid)
755
+
756
+
757
+ def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed):
758
+ """Returns a list of sets, each of which represents a community.
759
+
760
+ ``degree_seq`` is the degree sequence that must be met by the
761
+ graph.
762
+
763
+ ``community_sizes`` is the community size distribution that must be
764
+ met by the generated list of sets.
765
+
766
+ ``mu`` is a float in the interval [0, 1] indicating the fraction of
767
+ intra-community edges incident to each node.
768
+
769
+ ``max_iters`` is the number of times to try to add a node to a
770
+ community. This must be greater than the length of
771
+ ``degree_seq``, otherwise this function will always fail. If
772
+ the number of iterations exceeds this value,
773
+ :exc:`~networkx.exception.ExceededMaxIterations` is raised.
774
+
775
+ seed : integer, random_state, or None (default)
776
+ Indicator of random number generation state.
777
+ See :ref:`Randomness<randomness>`.
778
+
779
+ The communities returned by this are sets of integers in the set {0,
780
+ ..., *n* - 1}, where *n* is the length of ``degree_seq``.
781
+
782
+ """
783
+ # This assumes the nodes in the graph will be natural numbers.
784
+ result = [set() for _ in community_sizes]
785
+ n = len(degree_seq)
786
+ free = list(range(n))
787
+ for i in range(max_iters):
788
+ v = free.pop()
789
+ c = seed.choice(range(len(community_sizes)))
790
+ # s = int(degree_seq[v] * (1 - mu) + 0.5)
791
+ s = round(degree_seq[v] * (1 - mu))
792
+ # If the community is large enough, add the node to the chosen
793
+ # community. Otherwise, return it to the list of unaffiliated
794
+ # nodes.
795
+ if s < community_sizes[c]:
796
+ result[c].add(v)
797
+ else:
798
+ free.append(v)
799
+ # If the community is too big, remove a node from it.
800
+ if len(result[c]) > community_sizes[c]:
801
+ free.append(result[c].pop())
802
+ if not free:
803
+ return result
804
+ msg = "Could not assign communities; try increasing min_community"
805
+ raise nx.ExceededMaxIterations(msg)
806
+
807
+
808
+ @py_random_state(11)
809
+ @nx._dispatchable(graphs=None, returns_graph=True)
810
+ def LFR_benchmark_graph(
811
+ n,
812
+ tau1,
813
+ tau2,
814
+ mu,
815
+ average_degree=None,
816
+ min_degree=None,
817
+ max_degree=None,
818
+ min_community=None,
819
+ max_community=None,
820
+ tol=1.0e-7,
821
+ max_iters=500,
822
+ seed=None,
823
+ ):
824
+ r"""Returns the LFR benchmark graph.
825
+
826
+ This algorithm proceeds as follows:
827
+
828
+ 1) Find a degree sequence with a power law distribution, and minimum
829
+ value ``min_degree``, which has approximate average degree
830
+ ``average_degree``. This is accomplished by either
831
+
832
+ a) specifying ``min_degree`` and not ``average_degree``,
833
+ b) specifying ``average_degree`` and not ``min_degree``, in which
834
+ case a suitable minimum degree will be found.
835
+
836
+ ``max_degree`` can also be specified, otherwise it will be set to
837
+ ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
838
+ joining it to nodes in communities other than its own and $(1 -
839
+ \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
840
+ community.
841
+ 2) Generate community sizes according to a power law distribution
842
+ with exponent ``tau2``. If ``min_community`` and
843
+ ``max_community`` are not specified they will be selected to be
844
+ ``min_degree`` and ``max_degree``, respectively. Community sizes
845
+ are generated until the sum of their sizes equals ``n``.
846
+ 3) Each node will be randomly assigned a community with the
847
+ condition that the community is large enough for the node's
848
+ intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
849
+ described in step 2. If a community grows too large, a random node
850
+ will be selected for reassignment to a new community, until all
851
+ nodes have been assigned a community.
852
+ 4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
853
+ intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
854
+ edges.
855
+
856
+ Parameters
857
+ ----------
858
+ n : int
859
+ Number of nodes in the created graph.
860
+
861
+ tau1 : float
862
+ Power law exponent for the degree distribution of the created
863
+ graph. This value must be strictly greater than one.
864
+
865
+ tau2 : float
866
+ Power law exponent for the community size distribution in the
867
+ created graph. This value must be strictly greater than one.
868
+
869
+ mu : float
870
+ Fraction of inter-community edges incident to each node. This
871
+ value must be in the interval [0, 1].
872
+
873
+ average_degree : float
874
+ Desired average degree of nodes in the created graph. This value
875
+ must be in the interval [0, *n*]. Exactly one of this and
876
+ ``min_degree`` must be specified, otherwise a
877
+ :exc:`NetworkXError` is raised.
878
+
879
+ min_degree : int
880
+ Minimum degree of nodes in the created graph. This value must be
881
+ in the interval [0, *n*]. Exactly one of this and
882
+ ``average_degree`` must be specified, otherwise a
883
+ :exc:`NetworkXError` is raised.
884
+
885
+ max_degree : int
886
+ Maximum degree of nodes in the created graph. If not specified,
887
+ this is set to ``n``, the total number of nodes in the graph.
888
+
889
+ min_community : int
890
+ Minimum size of communities in the graph. If not specified, this
891
+ is set to ``min_degree``.
892
+
893
+ max_community : int
894
+ Maximum size of communities in the graph. If not specified, this
895
+ is set to ``n``, the total number of nodes in the graph.
896
+
897
+ tol : float
898
+ Tolerance when comparing floats, specifically when comparing
899
+ average degree values.
900
+
901
+ max_iters : int
902
+ Maximum number of iterations to try to create the community sizes,
903
+ degree distribution, and community affiliations.
904
+
905
+ seed : integer, random_state, or None (default)
906
+ Indicator of random number generation state.
907
+ See :ref:`Randomness<randomness>`.
908
+
909
+ Returns
910
+ -------
911
+ G : NetworkX graph
912
+ The LFR benchmark graph generated according to the specified
913
+ parameters.
914
+
915
+ Each node in the graph has a node attribute ``'community'`` that
916
+ stores the community (that is, the set of nodes) that includes
917
+ it.
918
+
919
+ Raises
920
+ ------
921
+ NetworkXError
922
+ If any of the parameters do not meet their upper and lower bounds:
923
+
924
+ - ``tau1`` and ``tau2`` must be strictly greater than 1.
925
+ - ``mu`` must be in [0, 1].
926
+ - ``max_degree`` must be in {1, ..., *n*}.
927
+ - ``min_community`` and ``max_community`` must be in {0, ...,
928
+ *n*}.
929
+
930
+ If not exactly one of ``average_degree`` and ``min_degree`` is
931
+ specified.
932
+
933
+ If ``min_degree`` is not specified and a suitable ``min_degree``
934
+ cannot be found.
935
+
936
+ ExceededMaxIterations
937
+ If a valid degree sequence cannot be created within
938
+ ``max_iters`` number of iterations.
939
+
940
+ If a valid set of community sizes cannot be created within
941
+ ``max_iters`` number of iterations.
942
+
943
+ If a valid community assignment cannot be created within ``10 *
944
+ n * max_iters`` number of iterations.
945
+
946
+ Examples
947
+ --------
948
+ Basic usage::
949
+
950
+ >>> from networkx.generators.community import LFR_benchmark_graph
951
+ >>> n = 250
952
+ >>> tau1 = 3
953
+ >>> tau2 = 1.5
954
+ >>> mu = 0.1
955
+ >>> G = LFR_benchmark_graph(
956
+ ... n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
957
+ ... )
958
+
959
+ Continuing the example above, you can get the communities from the
960
+ node attributes of the graph::
961
+
962
+ >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}
963
+
964
+ Notes
965
+ -----
966
+ This algorithm differs slightly from the original way it was
967
+ presented in [1].
968
+
969
+ 1) Rather than connecting the graph via a configuration model then
970
+ rewiring to match the intra-community and inter-community
971
+ degrees, we do this wiring explicitly at the end, which should be
972
+ equivalent.
973
+ 2) The code posted on the author's website [2] calculates the random
974
+ power law distributed variables and their average using
975
+ continuous approximations, whereas we use the discrete
976
+ distributions here as both degree and community size are
977
+ discrete.
978
+
979
+ Though the authors describe the algorithm as quite robust, testing
980
+ during development indicates that a somewhat narrower parameter set
981
+ is likely to successfully produce a graph. Some suggestions have
982
+ been provided in the event of exceptions.
983
+
984
+ References
985
+ ----------
986
+ .. [1] "Benchmark graphs for testing community detection algorithms",
987
+ Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
988
+ Phys. Rev. E 78, 046110 2008
989
+ .. [2] https://www.santofortunato.net/resources
990
+
991
+ """
992
+ # Perform some basic parameter validation.
993
+ if not tau1 > 1:
994
+ raise nx.NetworkXError("tau1 must be greater than one")
995
+ if not tau2 > 1:
996
+ raise nx.NetworkXError("tau2 must be greater than one")
997
+ if not 0 <= mu <= 1:
998
+ raise nx.NetworkXError("mu must be in the interval [0, 1]")
999
+
1000
+ # Validate parameters for generating the degree sequence.
1001
+ if max_degree is None:
1002
+ max_degree = n
1003
+ elif not 0 < max_degree <= n:
1004
+ raise nx.NetworkXError("max_degree must be in the interval (0, n]")
1005
+ if not ((min_degree is None) ^ (average_degree is None)):
1006
+ raise nx.NetworkXError(
1007
+ "Must assign exactly one of min_degree and average_degree"
1008
+ )
1009
+ if min_degree is None:
1010
+ min_degree = _generate_min_degree(
1011
+ tau1, average_degree, max_degree, tol, max_iters
1012
+ )
1013
+
1014
+ # Generate a degree sequence with a power law distribution.
1015
+ low, high = min_degree, max_degree
1016
+
1017
+ def condition(seq):
1018
+ return sum(seq) % 2 == 0
1019
+
1020
+ def length(seq):
1021
+ return len(seq) >= n
1022
+
1023
+ deg_seq = _powerlaw_sequence(tau1, low, high, condition, length, max_iters, seed)
1024
+
1025
+ # Validate parameters for generating the community size sequence.
1026
+ if min_community is None:
1027
+ min_community = min(deg_seq)
1028
+ if max_community is None:
1029
+ max_community = max(deg_seq)
1030
+
1031
+ # Generate a community size sequence with a power law distribution.
1032
+ #
1033
+ # TODO The original code incremented the number of iterations each
1034
+ # time a new Zipf random value was drawn from the distribution. This
1035
+ # differed from the way the number of iterations was incremented in
1036
+ # `_powerlaw_degree_sequence`, so this code was changed to match
1037
+ # that one. As a result, this code is allowed many more chances to
1038
+ # generate a valid community size sequence.
1039
+ low, high = min_community, max_community
1040
+
1041
+ def condition(seq):
1042
+ return sum(seq) == n
1043
+
1044
+ def length(seq):
1045
+ return sum(seq) >= n
1046
+
1047
+ comms = _powerlaw_sequence(tau2, low, high, condition, length, max_iters, seed)
1048
+
1049
+ # Generate the communities based on the given degree sequence and
1050
+ # community sizes.
1051
+ max_iters *= 10 * n
1052
+ communities = _generate_communities(deg_seq, comms, mu, max_iters, seed)
1053
+
1054
+ # Finally, generate the benchmark graph based on the given
1055
+ # communities, joining nodes according to the intra- and
1056
+ # inter-community degrees.
1057
+ G = nx.Graph()
1058
+ G.add_nodes_from(range(n))
1059
+ for c in communities:
1060
+ for u in c:
1061
+ while G.degree(u) < round(deg_seq[u] * (1 - mu)):
1062
+ v = seed.choice(list(c))
1063
+ G.add_edge(u, v)
1064
+ while G.degree(u) < deg_seq[u]:
1065
+ v = seed.choice(range(n))
1066
+ if v not in c:
1067
+ G.add_edge(u, v)
1068
+ G.nodes[u]["community"] = c
1069
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/degree_seq.py ADDED
@@ -0,0 +1,868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given degree sequence or expected degree sequence.
2
+ """
3
+
4
+ import heapq
5
+ import math
6
+ from itertools import chain, combinations, zip_longest
7
+ from operator import itemgetter
8
+
9
+ import networkx as nx
10
+ from networkx.utils import py_random_state, random_weighted_sample
11
+
12
+ __all__ = [
13
+ "configuration_model",
14
+ "directed_configuration_model",
15
+ "expected_degree_graph",
16
+ "havel_hakimi_graph",
17
+ "directed_havel_hakimi_graph",
18
+ "degree_sequence_tree",
19
+ "random_degree_sequence_graph",
20
+ ]
21
+
22
+ chaini = chain.from_iterable
23
+
24
+
25
+ def _to_stublist(degree_sequence):
26
+ """Returns a list of degree-repeated node numbers.
27
+
28
+ ``degree_sequence`` is a list of nonnegative integers representing
29
+ the degrees of nodes in a graph.
30
+
31
+ This function returns a list of node numbers with multiplicities
32
+ according to the given degree sequence. For example, if the first
33
+ element of ``degree_sequence`` is ``3``, then the first node number,
34
+ ``0``, will appear at the head of the returned list three times. The
35
+ node numbers are assumed to be the numbers zero through
36
+ ``len(degree_sequence) - 1``.
37
+
38
+ Examples
39
+ --------
40
+
41
+ >>> degree_sequence = [1, 2, 3]
42
+ >>> _to_stublist(degree_sequence)
43
+ [0, 1, 1, 2, 2, 2]
44
+
45
+ If a zero appears in the sequence, that means the node exists but
46
+ has degree zero, so that number will be skipped in the returned
47
+ list::
48
+
49
+ >>> degree_sequence = [2, 0, 1]
50
+ >>> _to_stublist(degree_sequence)
51
+ [0, 0, 2]
52
+
53
+ """
54
+ return list(chaini([n] * d for n, d in enumerate(degree_sequence)))
55
+
56
+
57
+ def _configuration_model(
58
+ deg_sequence, create_using, directed=False, in_deg_sequence=None, seed=None
59
+ ):
60
+ """Helper function for generating either undirected or directed
61
+ configuration model graphs.
62
+
63
+ ``deg_sequence`` is a list of nonnegative integers representing the
64
+ degree of the node whose label is the index of the list element.
65
+
66
+ ``create_using`` see :func:`~networkx.empty_graph`.
67
+
68
+ ``directed`` and ``in_deg_sequence`` are required if you want the
69
+ returned graph to be generated using the directed configuration
70
+ model algorithm. If ``directed`` is ``False``, then ``deg_sequence``
71
+ is interpreted as the degree sequence of an undirected graph and
72
+ ``in_deg_sequence`` is ignored. Otherwise, if ``directed`` is
73
+ ``True``, then ``deg_sequence`` is interpreted as the out-degree
74
+ sequence and ``in_deg_sequence`` as the in-degree sequence of a
75
+ directed graph.
76
+
77
+ .. note::
78
+
79
+ ``deg_sequence`` and ``in_deg_sequence`` need not be the same
80
+ length.
81
+
82
+ ``seed`` is a random.Random or numpy.random.RandomState instance
83
+
84
+ This function returns a graph, directed if and only if ``directed``
85
+ is ``True``, generated according to the configuration model
86
+ algorithm. For more information on the algorithm, see the
87
+ :func:`configuration_model` or :func:`directed_configuration_model`
88
+ functions.
89
+
90
+ """
91
+ n = len(deg_sequence)
92
+ G = nx.empty_graph(n, create_using)
93
+ # If empty, return the null graph immediately.
94
+ if n == 0:
95
+ return G
96
+ # Build a list of available degree-repeated nodes. For example,
97
+ # for degree sequence [3, 2, 1, 1, 1], the "stub list" is
98
+ # initially [0, 0, 0, 1, 1, 2, 3, 4], that is, node 0 has degree
99
+ # 3 and thus is repeated 3 times, etc.
100
+ #
101
+ # Also, shuffle the stub list in order to get a random sequence of
102
+ # node pairs.
103
+ if directed:
104
+ pairs = zip_longest(deg_sequence, in_deg_sequence, fillvalue=0)
105
+ # Unzip the list of pairs into a pair of lists.
106
+ out_deg, in_deg = zip(*pairs)
107
+
108
+ out_stublist = _to_stublist(out_deg)
109
+ in_stublist = _to_stublist(in_deg)
110
+
111
+ seed.shuffle(out_stublist)
112
+ seed.shuffle(in_stublist)
113
+ else:
114
+ stublist = _to_stublist(deg_sequence)
115
+ # Choose a random balanced bipartition of the stublist, which
116
+ # gives a random pairing of nodes. In this implementation, we
117
+ # shuffle the list and then split it in half.
118
+ n = len(stublist)
119
+ half = n // 2
120
+ seed.shuffle(stublist)
121
+ out_stublist, in_stublist = stublist[:half], stublist[half:]
122
+ G.add_edges_from(zip(out_stublist, in_stublist))
123
+ return G
124
+
125
+
126
+ @py_random_state(2)
127
+ @nx._dispatchable(graphs=None, returns_graph=True)
128
+ def configuration_model(deg_sequence, create_using=None, seed=None):
129
+ """Returns a random graph with the given degree sequence.
130
+
131
+ The configuration model generates a random pseudograph (graph with
132
+ parallel edges and self loops) by randomly assigning edges to
133
+ match the given degree sequence.
134
+
135
+ Parameters
136
+ ----------
137
+ deg_sequence : list of nonnegative integers
138
+ Each list entry corresponds to the degree of a node.
139
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
140
+ Graph type to create. If graph instance, then cleared before populated.
141
+ seed : integer, random_state, or None (default)
142
+ Indicator of random number generation state.
143
+ See :ref:`Randomness<randomness>`.
144
+
145
+ Returns
146
+ -------
147
+ G : MultiGraph
148
+ A graph with the specified degree sequence.
149
+ Nodes are labeled starting at 0 with an index
150
+ corresponding to the position in deg_sequence.
151
+
152
+ Raises
153
+ ------
154
+ NetworkXError
155
+ If the degree sequence does not have an even sum.
156
+
157
+ See Also
158
+ --------
159
+ is_graphical
160
+
161
+ Notes
162
+ -----
163
+ As described by Newman [1]_.
164
+
165
+ A non-graphical degree sequence (not realizable by some simple
166
+ graph) is allowed since this function returns graphs with self
167
+ loops and parallel edges. An exception is raised if the degree
168
+ sequence does not have an even sum.
169
+
170
+ This configuration model construction process can lead to
171
+ duplicate edges and loops. You can remove the self-loops and
172
+ parallel edges (see below) which will likely result in a graph
173
+ that doesn't have the exact degree sequence specified.
174
+
175
+ The density of self-loops and parallel edges tends to decrease as
176
+ the number of nodes increases. However, typically the number of
177
+ self-loops will approach a Poisson distribution with a nonzero mean,
178
+ and similarly for the number of parallel edges. Consider a node
179
+ with *k* stubs. The probability of being joined to another stub of
180
+ the same node is basically (*k* - *1*) / *N*, where *k* is the
181
+ degree and *N* is the number of nodes. So the probability of a
182
+ self-loop scales like *c* / *N* for some constant *c*. As *N* grows,
183
+ this means we expect *c* self-loops. Similarly for parallel edges.
184
+
185
+ References
186
+ ----------
187
+ .. [1] M.E.J. Newman, "The structure and function of complex networks",
188
+ SIAM REVIEW 45-2, pp 167-256, 2003.
189
+
190
+ Examples
191
+ --------
192
+ You can create a degree sequence following a particular distribution
193
+ by using the one of the distribution functions in
194
+ :mod:`~networkx.utils.random_sequence` (or one of your own). For
195
+ example, to create an undirected multigraph on one hundred nodes
196
+ with degree sequence chosen from the power law distribution:
197
+
198
+ >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000)
199
+ >>> G = nx.configuration_model(sequence)
200
+ >>> len(G)
201
+ 100
202
+ >>> actual_degrees = [d for v, d in G.degree()]
203
+ >>> actual_degrees == sequence
204
+ True
205
+
206
+ The returned graph is a multigraph, which may have parallel
207
+ edges. To remove any parallel edges from the returned graph:
208
+
209
+ >>> G = nx.Graph(G)
210
+
211
+ Similarly, to remove self-loops:
212
+
213
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
214
+
215
+ """
216
+ if sum(deg_sequence) % 2 != 0:
217
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
218
+ raise nx.NetworkXError(msg)
219
+
220
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
221
+ if G.is_directed():
222
+ raise nx.NetworkXNotImplemented("not implemented for directed graphs")
223
+
224
+ G = _configuration_model(deg_sequence, G, seed=seed)
225
+
226
+ return G
227
+
228
+
229
+ @py_random_state(3)
230
+ @nx._dispatchable(graphs=None, returns_graph=True)
231
+ def directed_configuration_model(
232
+ in_degree_sequence, out_degree_sequence, create_using=None, seed=None
233
+ ):
234
+ """Returns a directed_random graph with the given degree sequences.
235
+
236
+ The configuration model generates a random directed pseudograph
237
+ (graph with parallel edges and self loops) by randomly assigning
238
+ edges to match the given degree sequences.
239
+
240
+ Parameters
241
+ ----------
242
+ in_degree_sequence : list of nonnegative integers
243
+ Each list entry corresponds to the in-degree of a node.
244
+ out_degree_sequence : list of nonnegative integers
245
+ Each list entry corresponds to the out-degree of a node.
246
+ create_using : NetworkX graph constructor, optional (default MultiDiGraph)
247
+ Graph type to create. If graph instance, then cleared before populated.
248
+ seed : integer, random_state, or None (default)
249
+ Indicator of random number generation state.
250
+ See :ref:`Randomness<randomness>`.
251
+
252
+ Returns
253
+ -------
254
+ G : MultiDiGraph
255
+ A graph with the specified degree sequences.
256
+ Nodes are labeled starting at 0 with an index
257
+ corresponding to the position in deg_sequence.
258
+
259
+ Raises
260
+ ------
261
+ NetworkXError
262
+ If the degree sequences do not have the same sum.
263
+
264
+ See Also
265
+ --------
266
+ configuration_model
267
+
268
+ Notes
269
+ -----
270
+ Algorithm as described by Newman [1]_.
271
+
272
+ A non-graphical degree sequence (not realizable by some simple
273
+ graph) is allowed since this function returns graphs with self
274
+ loops and parallel edges. An exception is raised if the degree
275
+ sequences does not have the same sum.
276
+
277
+ This configuration model construction process can lead to
278
+ duplicate edges and loops. You can remove the self-loops and
279
+ parallel edges (see below) which will likely result in a graph
280
+ that doesn't have the exact degree sequence specified. This
281
+ "finite-size effect" decreases as the size of the graph increases.
282
+
283
+ References
284
+ ----------
285
+ .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
286
+ Random graphs with arbitrary degree distributions and their applications
287
+ Phys. Rev. E, 64, 026118 (2001)
288
+
289
+ Examples
290
+ --------
291
+ One can modify the in- and out-degree sequences from an existing
292
+ directed graph in order to create a new directed graph. For example,
293
+ here we modify the directed path graph:
294
+
295
+ >>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
296
+ >>> din = list(d for n, d in D.in_degree())
297
+ >>> dout = list(d for n, d in D.out_degree())
298
+ >>> din.append(1)
299
+ >>> dout[0] = 2
300
+ >>> # We now expect an edge from node 0 to a new node, node 3.
301
+ ... D = nx.directed_configuration_model(din, dout)
302
+
303
+ The returned graph is a directed multigraph, which may have parallel
304
+ edges. To remove any parallel edges from the returned graph:
305
+
306
+ >>> D = nx.DiGraph(D)
307
+
308
+ Similarly, to remove self-loops:
309
+
310
+ >>> D.remove_edges_from(nx.selfloop_edges(D))
311
+
312
+ """
313
+ if sum(in_degree_sequence) != sum(out_degree_sequence):
314
+ msg = "Invalid degree sequences: sequences must have equal sums"
315
+ raise nx.NetworkXError(msg)
316
+
317
+ if create_using is None:
318
+ create_using = nx.MultiDiGraph
319
+
320
+ G = _configuration_model(
321
+ out_degree_sequence,
322
+ create_using,
323
+ directed=True,
324
+ in_deg_sequence=in_degree_sequence,
325
+ seed=seed,
326
+ )
327
+
328
+ name = "directed configuration_model {} nodes {} edges"
329
+ return G
330
+
331
+
332
+ @py_random_state(1)
333
+ @nx._dispatchable(graphs=None, returns_graph=True)
334
+ def expected_degree_graph(w, seed=None, selfloops=True):
335
+ r"""Returns a random graph with given expected degrees.
336
+
337
+ Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$
338
+ of length $n$ this algorithm assigns an edge between node $u$ and
339
+ node $v$ with probability
340
+
341
+ .. math::
342
+
343
+ p_{uv} = \frac{w_u w_v}{\sum_k w_k} .
344
+
345
+ Parameters
346
+ ----------
347
+ w : list
348
+ The list of expected degrees.
349
+ selfloops: bool (default=True)
350
+ Set to False to remove the possibility of self-loop edges.
351
+ seed : integer, random_state, or None (default)
352
+ Indicator of random number generation state.
353
+ See :ref:`Randomness<randomness>`.
354
+
355
+ Returns
356
+ -------
357
+ Graph
358
+
359
+ Examples
360
+ --------
361
+ >>> z = [10 for i in range(100)]
362
+ >>> G = nx.expected_degree_graph(z)
363
+
364
+ Notes
365
+ -----
366
+ The nodes have integer labels corresponding to index of expected degrees
367
+ input sequence.
368
+
369
+ The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the
370
+ number of nodes and $m$ is the expected number of edges.
371
+
372
+ The model in [1]_ includes the possibility of self-loop edges.
373
+ Set selfloops=False to produce a graph without self loops.
374
+
375
+ For finite graphs this model doesn't produce exactly the given
376
+ expected degree sequence. Instead the expected degrees are as
377
+ follows.
378
+
379
+ For the case without self loops (selfloops=False),
380
+
381
+ .. math::
382
+
383
+ E[deg(u)] = \sum_{v \ne u} p_{uv}
384
+ = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .
385
+
386
+
387
+ NetworkX uses the standard convention that a self-loop edge counts 2
388
+ in the degree of a node, so with self loops (selfloops=True),
389
+
390
+ .. math::
391
+
392
+ E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}
393
+ = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .
394
+
395
+ References
396
+ ----------
397
+ .. [1] Fan Chung and L. Lu, Connected components in random graphs with
398
+ given expected degree sequences, Ann. Combinatorics, 6,
399
+ pp. 125-145, 2002.
400
+ .. [2] Joel Miller and Aric Hagberg,
401
+ Efficient generation of networks with given expected degrees,
402
+ in Algorithms and Models for the Web-Graph (WAW 2011),
403
+ Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
404
+ pp. 115-126, 2011.
405
+ """
406
+ n = len(w)
407
+ G = nx.empty_graph(n)
408
+
409
+ # If there are no nodes are no edges in the graph, return the empty graph.
410
+ if n == 0 or max(w) == 0:
411
+ return G
412
+
413
+ rho = 1 / sum(w)
414
+ # Sort the weights in decreasing order. The original order of the
415
+ # weights dictates the order of the (integer) node labels, so we
416
+ # need to remember the permutation applied in the sorting.
417
+ order = sorted(enumerate(w), key=itemgetter(1), reverse=True)
418
+ mapping = {c: u for c, (u, v) in enumerate(order)}
419
+ seq = [v for u, v in order]
420
+ last = n
421
+ if not selfloops:
422
+ last -= 1
423
+ for u in range(last):
424
+ v = u
425
+ if not selfloops:
426
+ v += 1
427
+ factor = seq[u] * rho
428
+ p = min(seq[v] * factor, 1)
429
+ while v < n and p > 0:
430
+ if p != 1:
431
+ r = seed.random()
432
+ v += math.floor(math.log(r, 1 - p))
433
+ if v < n:
434
+ q = min(seq[v] * factor, 1)
435
+ if seed.random() < q / p:
436
+ G.add_edge(mapping[u], mapping[v])
437
+ v += 1
438
+ p = q
439
+ return G
440
+
441
+
442
+ @nx._dispatchable(graphs=None, returns_graph=True)
443
+ def havel_hakimi_graph(deg_sequence, create_using=None):
444
+ """Returns a simple graph with given degree sequence constructed
445
+ using the Havel-Hakimi algorithm.
446
+
447
+ Parameters
448
+ ----------
449
+ deg_sequence: list of integers
450
+ Each integer corresponds to the degree of a node (need not be sorted).
451
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
452
+ Graph type to create. If graph instance, then cleared before populated.
453
+ Directed graphs are not allowed.
454
+
455
+ Raises
456
+ ------
457
+ NetworkXException
458
+ For a non-graphical degree sequence (i.e. one
459
+ not realizable by some simple graph).
460
+
461
+ Notes
462
+ -----
463
+ The Havel-Hakimi algorithm constructs a simple graph by
464
+ successively connecting the node of highest degree to other nodes
465
+ of highest degree, resorting remaining nodes by degree, and
466
+ repeating the process. The resulting graph has a high
467
+ degree-associativity. Nodes are labeled 1,.., len(deg_sequence),
468
+ corresponding to their position in deg_sequence.
469
+
470
+ The basic algorithm is from Hakimi [1]_ and was generalized by
471
+ Kleitman and Wang [2]_.
472
+
473
+ References
474
+ ----------
475
+ .. [1] Hakimi S., On Realizability of a Set of Integers as
476
+ Degrees of the Vertices of a Linear Graph. I,
477
+ Journal of SIAM, 10(3), pp. 496-506 (1962)
478
+ .. [2] Kleitman D.J. and Wang D.L.
479
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
480
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
481
+ """
482
+ if not nx.is_graphical(deg_sequence):
483
+ raise nx.NetworkXError("Invalid degree sequence")
484
+
485
+ p = len(deg_sequence)
486
+ G = nx.empty_graph(p, create_using)
487
+ if G.is_directed():
488
+ raise nx.NetworkXError("Directed graphs are not supported")
489
+ num_degs = [[] for i in range(p)]
490
+ dmax, dsum, n = 0, 0, 0
491
+ for d in deg_sequence:
492
+ # Process only the non-zero integers
493
+ if d > 0:
494
+ num_degs[d].append(n)
495
+ dmax, dsum, n = max(dmax, d), dsum + d, n + 1
496
+ # Return graph if no edges
497
+ if n == 0:
498
+ return G
499
+
500
+ modstubs = [(0, 0)] * (dmax + 1)
501
+ # Successively reduce degree sequence by removing the maximum degree
502
+ while n > 0:
503
+ # Retrieve the maximum degree in the sequence
504
+ while len(num_degs[dmax]) == 0:
505
+ dmax -= 1
506
+ # If there are not enough stubs to connect to, then the sequence is
507
+ # not graphical
508
+ if dmax > n - 1:
509
+ raise nx.NetworkXError("Non-graphical integer sequence")
510
+
511
+ # Remove largest stub in list
512
+ source = num_degs[dmax].pop()
513
+ n -= 1
514
+ # Reduce the next dmax largest stubs
515
+ mslen = 0
516
+ k = dmax
517
+ for i in range(dmax):
518
+ while len(num_degs[k]) == 0:
519
+ k -= 1
520
+ target = num_degs[k].pop()
521
+ G.add_edge(source, target)
522
+ n -= 1
523
+ if k > 1:
524
+ modstubs[mslen] = (k - 1, target)
525
+ mslen += 1
526
+ # Add back to the list any nonzero stubs that were removed
527
+ for i in range(mslen):
528
+ (stubval, stubtarget) = modstubs[i]
529
+ num_degs[stubval].append(stubtarget)
530
+ n += 1
531
+
532
+ return G
533
+
534
+
535
+ @nx._dispatchable(graphs=None, returns_graph=True)
536
+ def directed_havel_hakimi_graph(in_deg_sequence, out_deg_sequence, create_using=None):
537
+ """Returns a directed graph with the given degree sequences.
538
+
539
+ Parameters
540
+ ----------
541
+ in_deg_sequence : list of integers
542
+ Each list entry corresponds to the in-degree of a node.
543
+ out_deg_sequence : list of integers
544
+ Each list entry corresponds to the out-degree of a node.
545
+ create_using : NetworkX graph constructor, optional (default DiGraph)
546
+ Graph type to create. If graph instance, then cleared before populated.
547
+
548
+ Returns
549
+ -------
550
+ G : DiGraph
551
+ A graph with the specified degree sequences.
552
+ Nodes are labeled starting at 0 with an index
553
+ corresponding to the position in deg_sequence
554
+
555
+ Raises
556
+ ------
557
+ NetworkXError
558
+ If the degree sequences are not digraphical.
559
+
560
+ See Also
561
+ --------
562
+ configuration_model
563
+
564
+ Notes
565
+ -----
566
+ Algorithm as described by Kleitman and Wang [1]_.
567
+
568
+ References
569
+ ----------
570
+ .. [1] D.J. Kleitman and D.L. Wang
571
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
572
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
573
+ """
574
+ in_deg_sequence = nx.utils.make_list_of_ints(in_deg_sequence)
575
+ out_deg_sequence = nx.utils.make_list_of_ints(out_deg_sequence)
576
+
577
+ # Process the sequences and form two heaps to store degree pairs with
578
+ # either zero or nonzero out degrees
579
+ sumin, sumout = 0, 0
580
+ nin, nout = len(in_deg_sequence), len(out_deg_sequence)
581
+ maxn = max(nin, nout)
582
+ G = nx.empty_graph(maxn, create_using, default=nx.DiGraph)
583
+ if maxn == 0:
584
+ return G
585
+ maxin = 0
586
+ stubheap, zeroheap = [], []
587
+ for n in range(maxn):
588
+ in_deg, out_deg = 0, 0
589
+ if n < nout:
590
+ out_deg = out_deg_sequence[n]
591
+ if n < nin:
592
+ in_deg = in_deg_sequence[n]
593
+ if in_deg < 0 or out_deg < 0:
594
+ raise nx.NetworkXError(
595
+ "Invalid degree sequences. Sequence values must be positive."
596
+ )
597
+ sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
598
+ if in_deg > 0:
599
+ stubheap.append((-1 * out_deg, -1 * in_deg, n))
600
+ elif out_deg > 0:
601
+ zeroheap.append((-1 * out_deg, n))
602
+ if sumin != sumout:
603
+ raise nx.NetworkXError(
604
+ "Invalid degree sequences. Sequences must have equal sums."
605
+ )
606
+ heapq.heapify(stubheap)
607
+ heapq.heapify(zeroheap)
608
+
609
+ modstubs = [(0, 0, 0)] * (maxin + 1)
610
+ # Successively reduce degree sequence by removing the maximum
611
+ while stubheap:
612
+ # Remove first value in the sequence with a non-zero in degree
613
+ (freeout, freein, target) = heapq.heappop(stubheap)
614
+ freein *= -1
615
+ if freein > len(stubheap) + len(zeroheap):
616
+ raise nx.NetworkXError("Non-digraphical integer sequence")
617
+
618
+ # Attach arcs from the nodes with the most stubs
619
+ mslen = 0
620
+ for i in range(freein):
621
+ if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]):
622
+ (stubout, stubsource) = heapq.heappop(zeroheap)
623
+ stubin = 0
624
+ else:
625
+ (stubout, stubin, stubsource) = heapq.heappop(stubheap)
626
+ if stubout == 0:
627
+ raise nx.NetworkXError("Non-digraphical integer sequence")
628
+ G.add_edge(stubsource, target)
629
+ # Check if source is now totally connected
630
+ if stubout + 1 < 0 or stubin < 0:
631
+ modstubs[mslen] = (stubout + 1, stubin, stubsource)
632
+ mslen += 1
633
+
634
+ # Add the nodes back to the heaps that still have available stubs
635
+ for i in range(mslen):
636
+ stub = modstubs[i]
637
+ if stub[1] < 0:
638
+ heapq.heappush(stubheap, stub)
639
+ else:
640
+ heapq.heappush(zeroheap, (stub[0], stub[2]))
641
+ if freeout < 0:
642
+ heapq.heappush(zeroheap, (freeout, target))
643
+
644
+ return G
645
+
646
+
647
+ @nx._dispatchable(graphs=None, returns_graph=True)
648
+ def degree_sequence_tree(deg_sequence, create_using=None):
649
+ """Make a tree for the given degree sequence.
650
+
651
+ A tree has #nodes-#edges=1 so
652
+ the degree sequence must have
653
+ len(deg_sequence)-sum(deg_sequence)/2=1
654
+ """
655
+ # The sum of the degree sequence must be even (for any undirected graph).
656
+ degree_sum = sum(deg_sequence)
657
+ if degree_sum % 2 != 0:
658
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
659
+ raise nx.NetworkXError(msg)
660
+ if len(deg_sequence) - degree_sum // 2 != 1:
661
+ msg = (
662
+ "Invalid degree sequence: tree must have number of nodes equal"
663
+ " to one less than the number of edges"
664
+ )
665
+ raise nx.NetworkXError(msg)
666
+ G = nx.empty_graph(0, create_using)
667
+ if G.is_directed():
668
+ raise nx.NetworkXError("Directed Graph not supported")
669
+
670
+ # Sort all degrees greater than 1 in decreasing order.
671
+ #
672
+ # TODO Does this need to be sorted in reverse order?
673
+ deg = sorted((s for s in deg_sequence if s > 1), reverse=True)
674
+
675
+ # make path graph as backbone
676
+ n = len(deg) + 2
677
+ nx.add_path(G, range(n))
678
+ last = n
679
+
680
+ # add the leaves
681
+ for source in range(1, n - 1):
682
+ nedges = deg.pop() - 2
683
+ for target in range(last, last + nedges):
684
+ G.add_edge(source, target)
685
+ last += nedges
686
+
687
+ # in case we added one too many
688
+ if len(G) > len(deg_sequence):
689
+ G.remove_node(0)
690
+ return G
691
+
692
+
693
+ @py_random_state(1)
694
+ @nx._dispatchable(graphs=None, returns_graph=True)
695
+ def random_degree_sequence_graph(sequence, seed=None, tries=10):
696
+ r"""Returns a simple random graph with the given degree sequence.
697
+
698
+ If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the
699
+ algorithm produces almost uniform random graphs in $O(m d_m)$ time
700
+ where $m$ is the number of edges.
701
+
702
+ Parameters
703
+ ----------
704
+ sequence : list of integers
705
+ Sequence of degrees
706
+ seed : integer, random_state, or None (default)
707
+ Indicator of random number generation state.
708
+ See :ref:`Randomness<randomness>`.
709
+ tries : int, optional
710
+ Maximum number of tries to create a graph
711
+
712
+ Returns
713
+ -------
714
+ G : Graph
715
+ A graph with the specified degree sequence.
716
+ Nodes are labeled starting at 0 with an index
717
+ corresponding to the position in the sequence.
718
+
719
+ Raises
720
+ ------
721
+ NetworkXUnfeasible
722
+ If the degree sequence is not graphical.
723
+ NetworkXError
724
+ If a graph is not produced in specified number of tries
725
+
726
+ See Also
727
+ --------
728
+ is_graphical, configuration_model
729
+
730
+ Notes
731
+ -----
732
+ The generator algorithm [1]_ is not guaranteed to produce a graph.
733
+
734
+ References
735
+ ----------
736
+ .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
737
+ A sequential algorithm for generating random graphs.
738
+ Algorithmica, Volume 58, Number 4, 860-910,
739
+ DOI: 10.1007/s00453-009-9340-1
740
+
741
+ Examples
742
+ --------
743
+ >>> sequence = [1, 2, 2, 3]
744
+ >>> G = nx.random_degree_sequence_graph(sequence, seed=42)
745
+ >>> sorted(d for n, d in G.degree())
746
+ [1, 2, 2, 3]
747
+ """
748
+ DSRG = DegreeSequenceRandomGraph(sequence, seed)
749
+ for try_n in range(tries):
750
+ try:
751
+ return DSRG.generate()
752
+ except nx.NetworkXUnfeasible:
753
+ pass
754
+ raise nx.NetworkXError(f"failed to generate graph in {tries} tries")
755
+
756
+
757
+ class DegreeSequenceRandomGraph:
758
+ # class to generate random graphs with a given degree sequence
759
+ # use random_degree_sequence_graph()
760
+ def __init__(self, degree, rng):
761
+ if not nx.is_graphical(degree):
762
+ raise nx.NetworkXUnfeasible("degree sequence is not graphical")
763
+ self.rng = rng
764
+ self.degree = list(degree)
765
+ # node labels are integers 0,...,n-1
766
+ self.m = sum(self.degree) / 2.0 # number of edges
767
+ try:
768
+ self.dmax = max(self.degree) # maximum degree
769
+ except ValueError:
770
+ self.dmax = 0
771
+
772
+ def generate(self):
773
+ # remaining_degree is mapping from int->remaining degree
774
+ self.remaining_degree = dict(enumerate(self.degree))
775
+ # add all nodes to make sure we get isolated nodes
776
+ self.graph = nx.Graph()
777
+ self.graph.add_nodes_from(self.remaining_degree)
778
+ # remove zero degree nodes
779
+ for n, d in list(self.remaining_degree.items()):
780
+ if d == 0:
781
+ del self.remaining_degree[n]
782
+ if len(self.remaining_degree) > 0:
783
+ # build graph in three phases according to how many unmatched edges
784
+ self.phase1()
785
+ self.phase2()
786
+ self.phase3()
787
+ return self.graph
788
+
789
+ def update_remaining(self, u, v, aux_graph=None):
790
+ # decrement remaining nodes, modify auxiliary graph if in phase3
791
+ if aux_graph is not None:
792
+ # remove edges from auxiliary graph
793
+ aux_graph.remove_edge(u, v)
794
+ if self.remaining_degree[u] == 1:
795
+ del self.remaining_degree[u]
796
+ if aux_graph is not None:
797
+ aux_graph.remove_node(u)
798
+ else:
799
+ self.remaining_degree[u] -= 1
800
+ if self.remaining_degree[v] == 1:
801
+ del self.remaining_degree[v]
802
+ if aux_graph is not None:
803
+ aux_graph.remove_node(v)
804
+ else:
805
+ self.remaining_degree[v] -= 1
806
+
807
+ def p(self, u, v):
808
+ # degree probability
809
+ return 1 - self.degree[u] * self.degree[v] / (4.0 * self.m)
810
+
811
+ def q(self, u, v):
812
+ # remaining degree probability
813
+ norm = max(self.remaining_degree.values()) ** 2
814
+ return self.remaining_degree[u] * self.remaining_degree[v] / norm
815
+
816
+ def suitable_edge(self):
817
+ """Returns True if and only if an arbitrary remaining node can
818
+ potentially be joined with some other remaining node.
819
+
820
+ """
821
+ nodes = iter(self.remaining_degree)
822
+ u = next(nodes)
823
+ return any(v not in self.graph[u] for v in nodes)
824
+
825
+ def phase1(self):
826
+ # choose node pairs from (degree) weighted distribution
827
+ rem_deg = self.remaining_degree
828
+ while sum(rem_deg.values()) >= 2 * self.dmax**2:
829
+ u, v = sorted(random_weighted_sample(rem_deg, 2, self.rng))
830
+ if self.graph.has_edge(u, v):
831
+ continue
832
+ if self.rng.random() < self.p(u, v): # accept edge
833
+ self.graph.add_edge(u, v)
834
+ self.update_remaining(u, v)
835
+
836
+ def phase2(self):
837
+ # choose remaining nodes uniformly at random and use rejection sampling
838
+ remaining_deg = self.remaining_degree
839
+ rng = self.rng
840
+ while len(remaining_deg) >= 2 * self.dmax:
841
+ while True:
842
+ u, v = sorted(rng.sample(list(remaining_deg.keys()), 2))
843
+ if self.graph.has_edge(u, v):
844
+ continue
845
+ if rng.random() < self.q(u, v):
846
+ break
847
+ if rng.random() < self.p(u, v): # accept edge
848
+ self.graph.add_edge(u, v)
849
+ self.update_remaining(u, v)
850
+
851
+ def phase3(self):
852
+ # build potential remaining edges and choose with rejection sampling
853
+ potential_edges = combinations(self.remaining_degree, 2)
854
+ # build auxiliary graph of potential edges not already in graph
855
+ H = nx.Graph(
856
+ [(u, v) for (u, v) in potential_edges if not self.graph.has_edge(u, v)]
857
+ )
858
+ rng = self.rng
859
+ while self.remaining_degree:
860
+ if not self.suitable_edge():
861
+ raise nx.NetworkXUnfeasible("no suitable edges left")
862
+ while True:
863
+ u, v = sorted(rng.choice(list(H.edges())))
864
+ if rng.random() < self.q(u, v):
865
+ break
866
+ if rng.random() < self.p(u, v): # accept edge
867
+ self.graph.add_edge(u, v)
868
+ self.update_remaining(u, v, aux_graph=H)
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/networkx/generators/duplication.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating graphs based on the "duplication" method.
2
+
3
+ These graph generators start with a small initial graph then duplicate
4
+ nodes and (partially) duplicate their edges. These functions are
5
+ generally inspired by biological networks.
6
+
7
+ """
8
+ import networkx as nx
9
+ from networkx.exception import NetworkXError
10
+ from networkx.utils import py_random_state
11
+
12
+ __all__ = ["partial_duplication_graph", "duplication_divergence_graph"]
13
+
14
+
15
+ @py_random_state(4)
16
+ @nx._dispatchable(graphs=None, returns_graph=True)
17
+ def partial_duplication_graph(N, n, p, q, seed=None):
18
+ """Returns a random graph using the partial duplication model.
19
+
20
+ Parameters
21
+ ----------
22
+ N : int
23
+ The total number of nodes in the final graph.
24
+
25
+ n : int
26
+ The number of nodes in the initial clique.
27
+
28
+ p : float
29
+ The probability of joining each neighbor of a node to the
30
+ duplicate node. Must be a number in the between zero and one,
31
+ inclusive.
32
+
33
+ q : float
34
+ The probability of joining the source node to the duplicate
35
+ node. Must be a number in the between zero and one, inclusive.
36
+
37
+ seed : integer, random_state, or None (default)
38
+ Indicator of random number generation state.
39
+ See :ref:`Randomness<randomness>`.
40
+
41
+ Notes
42
+ -----
43
+ A graph of nodes is grown by creating a fully connected graph
44
+ of size `n`. The following procedure is then repeated until
45
+ a total of `N` nodes have been reached.
46
+
47
+ 1. A random node, *u*, is picked and a new node, *v*, is created.
48
+ 2. For each neighbor of *u* an edge from the neighbor to *v* is created
49
+ with probability `p`.
50
+ 3. An edge from *u* to *v* is created with probability `q`.
51
+
52
+ This algorithm appears in [1].
53
+
54
+ This implementation allows the possibility of generating
55
+ disconnected graphs.
56
+
57
+ References
58
+ ----------
59
+ .. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
60
+ randomly grown graphs." Journal of Applied Mathematics 2008.
61
+ <https://doi.org/10.1155/2008/190836>
62
+
63
+ """
64
+ if p < 0 or p > 1 or q < 0 or q > 1:
65
+ msg = "partial duplication graph must have 0 <= p, q <= 1."
66
+ raise NetworkXError(msg)
67
+ if n > N:
68
+ raise NetworkXError("partial duplication graph must have n <= N.")
69
+
70
+ G = nx.complete_graph(n)
71
+ for new_node in range(n, N):
72
+ # Pick a random vertex, u, already in the graph.
73
+ src_node = seed.randint(0, new_node - 1)
74
+
75
+ # Add a new vertex, v, to the graph.
76
+ G.add_node(new_node)
77
+
78
+ # For each neighbor of u...
79
+ for nbr_node in list(nx.all_neighbors(G, src_node)):
80
+ # Add the neighbor to v with probability p.
81
+ if seed.random() < p:
82
+ G.add_edge(new_node, nbr_node)
83
+
84
+ # Join v and u with probability q.
85
+ if seed.random() < q:
86
+ G.add_edge(new_node, src_node)
87
+ return G
88
+
89
+
90
+ @py_random_state(2)
91
+ @nx._dispatchable(graphs=None, returns_graph=True)
92
+ def duplication_divergence_graph(n, p, seed=None):
93
+ """Returns an undirected graph using the duplication-divergence model.
94
+
95
+ A graph of `n` nodes is created by duplicating the initial nodes
96
+ and retaining edges incident to the original nodes with a retention
97
+ probability `p`.
98
+
99
+ Parameters
100
+ ----------
101
+ n : int
102
+ The desired number of nodes in the graph.
103
+ p : float
104
+ The probability for retaining the edge of the replicated node.
105
+ seed : integer, random_state, or None (default)
106
+ Indicator of random number generation state.
107
+ See :ref:`Randomness<randomness>`.
108
+
109
+ Returns
110
+ -------
111
+ G : Graph
112
+
113
+ Raises
114
+ ------
115
+ NetworkXError
116
+ If `p` is not a valid probability.
117
+ If `n` is less than 2.
118
+
119
+ Notes
120
+ -----
121
+ This algorithm appears in [1].
122
+
123
+ This implementation disallows the possibility of generating
124
+ disconnected graphs.
125
+
126
+ References
127
+ ----------
128
+ .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
129
+ "Duplication-divergence model of protein interaction network",
130
+ Phys. Rev. E, 71, 061911, 2005.
131
+
132
+ """
133
+ if p > 1 or p < 0:
134
+ msg = f"NetworkXError p={p} is not in [0,1]."
135
+ raise nx.NetworkXError(msg)
136
+ if n < 2:
137
+ msg = "n must be greater than or equal to 2"
138
+ raise nx.NetworkXError(msg)
139
+
140
+ G = nx.Graph()
141
+
142
+ # Initialize the graph with two connected nodes.
143
+ G.add_edge(0, 1)
144
+ i = 2
145
+ while i < n:
146
+ # Choose a random node from current graph to duplicate.
147
+ random_node = seed.choice(list(G))
148
+ # Make the replica.
149
+ G.add_node(i)
150
+ # flag indicates whether at least one edge is connected on the replica.
151
+ flag = False
152
+ for nbr in G.neighbors(random_node):
153
+ if seed.random() < p:
154
+ # Link retention step.
155
+ G.add_edge(i, nbr)
156
+ flag = True
157
+ if not flag:
158
+ # Delete replica if no edges retained.
159
+ G.remove_node(i)
160
+ else:
161
+ # Successful duplication.
162
+ i += 1
163
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/ego.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ego graph.
3
+ """
4
+ __all__ = ["ego_graph"]
5
+
6
+ import networkx as nx
7
+
8
+
9
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
10
+ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
11
+ """Returns induced subgraph of neighbors centered at node n within
12
+ a given radius.
13
+
14
+ Parameters
15
+ ----------
16
+ G : graph
17
+ A NetworkX Graph or DiGraph
18
+
19
+ n : node
20
+ A single node
21
+
22
+ radius : number, optional
23
+ Include all neighbors of distance<=radius from n.
24
+
25
+ center : bool, optional
26
+ If False, do not include center node in graph
27
+
28
+ undirected : bool, optional
29
+ If True use both in- and out-neighbors of directed graphs.
30
+
31
+ distance : key, optional
32
+ Use specified edge data key as distance. For example, setting
33
+ distance='weight' will use the edge weight to measure the
34
+ distance from the node n.
35
+
36
+ Notes
37
+ -----
38
+ For directed graphs D this produces the "out" neighborhood
39
+ or successors. If you want the neighborhood of predecessors
40
+ first reverse the graph with D.reverse(). If you want both
41
+ directions use the keyword argument undirected=True.
42
+
43
+ Node, edge, and graph attributes are copied to the returned subgraph.
44
+ """
45
+ if undirected:
46
+ if distance is not None:
47
+ sp, _ = nx.single_source_dijkstra(
48
+ G.to_undirected(), n, cutoff=radius, weight=distance
49
+ )
50
+ else:
51
+ sp = dict(
52
+ nx.single_source_shortest_path_length(
53
+ G.to_undirected(), n, cutoff=radius
54
+ )
55
+ )
56
+ else:
57
+ if distance is not None:
58
+ sp, _ = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
59
+ else:
60
+ sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))
61
+
62
+ H = G.subgraph(sp).copy()
63
+ if not center:
64
+ H.remove_node(n)
65
+ return H
env-llmeval/lib/python3.10/site-packages/networkx/generators/expanders.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides explicit constructions of expander graphs.
2
+
3
+ """
4
+ import itertools
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = [
9
+ "margulis_gabber_galil_graph",
10
+ "chordal_cycle_graph",
11
+ "paley_graph",
12
+ "maybe_regular_expander",
13
+ "is_regular_expander",
14
+ "random_regular_expander_graph",
15
+ ]
16
+
17
+
18
+ # Other discrete torus expanders can be constructed by using the following edge
19
+ # sets. For more information, see Chapter 4, "Expander Graphs", in
20
+ # "Pseudorandomness", by Salil Vadhan.
21
+ #
22
+ # For a directed expander, add edges from (x, y) to:
23
+ #
24
+ # (x, y),
25
+ # ((x + 1) % n, y),
26
+ # (x, (y + 1) % n),
27
+ # (x, (x + y) % n),
28
+ # (-y % n, x)
29
+ #
30
+ # For an undirected expander, add the reverse edges.
31
+ #
32
+ # Also appearing in the paper of Gabber and Galil:
33
+ #
34
+ # (x, y),
35
+ # (x, (x + y) % n),
36
+ # (x, (x + y + 1) % n),
37
+ # ((x + y) % n, y),
38
+ # ((x + y + 1) % n, y)
39
+ #
40
+ # and:
41
+ #
42
+ # (x, y),
43
+ # ((x + 2*y) % n, y),
44
+ # ((x + (2*y + 1)) % n, y),
45
+ # ((x + (2*y + 2)) % n, y),
46
+ # (x, (y + 2*x) % n),
47
+ # (x, (y + (2*x + 1)) % n),
48
+ # (x, (y + (2*x + 2)) % n),
49
+ #
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def margulis_gabber_galil_graph(n, create_using=None):
52
+ r"""Returns the Margulis-Gabber-Galil undirected MultiGraph on `n^2` nodes.
53
+
54
+ The undirected MultiGraph is regular with degree `8`. Nodes are integer
55
+ pairs. The second-largest eigenvalue of the adjacency matrix of the graph
56
+ is at most `5 \sqrt{2}`, regardless of `n`.
57
+
58
+ Parameters
59
+ ----------
60
+ n : int
61
+ Determines the number of nodes in the graph: `n^2`.
62
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
63
+ Graph type to create. If graph instance, then cleared before populated.
64
+
65
+ Returns
66
+ -------
67
+ G : graph
68
+ The constructed undirected multigraph.
69
+
70
+ Raises
71
+ ------
72
+ NetworkXError
73
+ If the graph is directed or not a multigraph.
74
+
75
+ """
76
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
77
+ if G.is_directed() or not G.is_multigraph():
78
+ msg = "`create_using` must be an undirected multigraph."
79
+ raise nx.NetworkXError(msg)
80
+
81
+ for x, y in itertools.product(range(n), repeat=2):
82
+ for u, v in (
83
+ ((x + 2 * y) % n, y),
84
+ ((x + (2 * y + 1)) % n, y),
85
+ (x, (y + 2 * x) % n),
86
+ (x, (y + (2 * x + 1)) % n),
87
+ ):
88
+ G.add_edge((x, y), (u, v))
89
+ G.graph["name"] = f"margulis_gabber_galil_graph({n})"
90
+ return G
91
+
92
+
93
+ @nx._dispatchable(graphs=None, returns_graph=True)
94
+ def chordal_cycle_graph(p, create_using=None):
95
+ """Returns the chordal cycle graph on `p` nodes.
96
+
97
+ The returned graph is a cycle graph on `p` nodes with chords joining each
98
+ vertex `x` to its inverse modulo `p`. This graph is a (mildly explicit)
99
+ 3-regular expander [1]_.
100
+
101
+ `p` *must* be a prime number.
102
+
103
+ Parameters
104
+ ----------
105
+ p : a prime number
106
+
107
+ The number of vertices in the graph. This also indicates where the
108
+ chordal edges in the cycle will be created.
109
+
110
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
111
+ Graph type to create. If graph instance, then cleared before populated.
112
+
113
+ Returns
114
+ -------
115
+ G : graph
116
+ The constructed undirected multigraph.
117
+
118
+ Raises
119
+ ------
120
+ NetworkXError
121
+
122
+ If `create_using` indicates directed or not a multigraph.
123
+
124
+ References
125
+ ----------
126
+
127
+ .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and
128
+ invariant measures", volume 125 of Progress in Mathematics.
129
+ Birkhäuser Verlag, Basel, 1994.
130
+
131
+ """
132
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
133
+ if G.is_directed() or not G.is_multigraph():
134
+ msg = "`create_using` must be an undirected multigraph."
135
+ raise nx.NetworkXError(msg)
136
+
137
+ for x in range(p):
138
+ left = (x - 1) % p
139
+ right = (x + 1) % p
140
+ # Here we apply Fermat's Little Theorem to compute the multiplicative
141
+ # inverse of x in Z/pZ. By Fermat's Little Theorem,
142
+ #
143
+ # x^p = x (mod p)
144
+ #
145
+ # Therefore,
146
+ #
147
+ # x * x^(p - 2) = 1 (mod p)
148
+ #
149
+ # The number 0 is a special case: we just let its inverse be itself.
150
+ chord = pow(x, p - 2, p) if x > 0 else 0
151
+ for y in (left, right, chord):
152
+ G.add_edge(x, y)
153
+ G.graph["name"] = f"chordal_cycle_graph({p})"
154
+ return G
155
+
156
+
157
+ @nx._dispatchable(graphs=None, returns_graph=True)
158
+ def paley_graph(p, create_using=None):
159
+ r"""Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
160
+
161
+ The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
162
+ if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
163
+
164
+ If $p \equiv 1 \pmod 4$, $-1$ is a square in $\mathbb{Z}/p\mathbb{Z}$ and therefore $x-y$ is a square if and
165
+ only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
166
+
167
+ If $p \equiv 3 \pmod 4$, $-1$ is not a square in $\mathbb{Z}/p\mathbb{Z}$ and therefore either $x-y$ or $y-x$
168
+ is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
169
+
170
+ Note that a more general definition of Paley graphs extends this construction
171
+ to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of $\mathbb{Z}/p\mathbb{Z}$.
172
+ This construction requires to compute squares in general finite fields and is
173
+ not what is implemented here (i.e `paley_graph(25)` does not return the true
174
+ Paley graph associated with $5^2$).
175
+
176
+ Parameters
177
+ ----------
178
+ p : int, an odd prime number.
179
+
180
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
181
+ Graph type to create. If graph instance, then cleared before populated.
182
+
183
+ Returns
184
+ -------
185
+ G : graph
186
+ The constructed directed graph.
187
+
188
+ Raises
189
+ ------
190
+ NetworkXError
191
+ If the graph is a multigraph.
192
+
193
+ References
194
+ ----------
195
+ Chapter 13 in B. Bollobas, Random Graphs. Second edition.
196
+ Cambridge Studies in Advanced Mathematics, 73.
197
+ Cambridge University Press, Cambridge (2001).
198
+ """
199
+ G = nx.empty_graph(0, create_using, default=nx.DiGraph)
200
+ if G.is_multigraph():
201
+ msg = "`create_using` cannot be a multigraph."
202
+ raise nx.NetworkXError(msg)
203
+
204
+ # Compute the squares in Z/pZ.
205
+ # Make it a set to uniquify (there are exactly (p-1)/2 squares in Z/pZ
206
+ # when is prime).
207
+ square_set = {(x**2) % p for x in range(1, p) if (x**2) % p != 0}
208
+
209
+ for x in range(p):
210
+ for x2 in square_set:
211
+ G.add_edge(x, (x + x2) % p)
212
+ G.graph["name"] = f"paley({p})"
213
+ return G
214
+
215
+
216
+ @nx.utils.decorators.np_random_state("seed")
217
+ @nx._dispatchable(graphs=None, returns_graph=True)
218
+ def maybe_regular_expander(n, d, *, create_using=None, max_tries=100, seed=None):
219
+ r"""Utility for creating a random regular expander.
220
+
221
+ Returns a random $d$-regular graph on $n$ nodes which is an expander
222
+ graph with very good probability.
223
+
224
+ Parameters
225
+ ----------
226
+ n : int
227
+ The number of nodes.
228
+ d : int
229
+ The degree of each node.
230
+ create_using : Graph Instance or Constructor
231
+ Indicator of type of graph to return.
232
+ If a Graph-type instance, then clear and use it.
233
+ If a constructor, call it to create an empty graph.
234
+ Use the Graph constructor by default.
235
+ max_tries : int. (default: 100)
236
+ The number of allowed loops when generating each independent cycle
237
+ seed : (default: None)
238
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
239
+
240
+ Notes
241
+ -----
242
+ The nodes are numbered from $0$ to $n - 1$.
243
+
244
+ The graph is generated by taking $d / 2$ random independent cycles.
245
+
246
+ Joel Friedman proved that in this model the resulting
247
+ graph is an expander with probability
248
+ $1 - O(n^{-\tau})$ where $\tau = \lceil (\sqrt{d - 1}) / 2 \rceil - 1$. [1]_
249
+
250
+ Examples
251
+ --------
252
+ >>> G = nx.maybe_regular_expander(n=200, d=6, seed=8020)
253
+
254
+ Returns
255
+ -------
256
+ G : graph
257
+ The constructed undirected graph.
258
+
259
+ Raises
260
+ ------
261
+ NetworkXError
262
+ If $d % 2 != 0$ as the degree must be even.
263
+ If $n - 1$ is less than $ 2d $ as the graph is complete at most.
264
+ If max_tries is reached
265
+
266
+ See Also
267
+ --------
268
+ is_regular_expander
269
+ random_regular_expander_graph
270
+
271
+ References
272
+ ----------
273
+ .. [1] Joel Friedman,
274
+ A Proof of Alon’s Second Eigenvalue Conjecture and Related Problems, 2004
275
+ https://arxiv.org/abs/cs/0405020
276
+
277
+ """
278
+
279
+ import numpy as np
280
+
281
+ if n < 1:
282
+ raise nx.NetworkXError("n must be a positive integer")
283
+
284
+ if not (d >= 2):
285
+ raise nx.NetworkXError("d must be greater than or equal to 2")
286
+
287
+ if not (d % 2 == 0):
288
+ raise nx.NetworkXError("d must be even")
289
+
290
+ if not (n - 1 >= d):
291
+ raise nx.NetworkXError(
292
+ f"Need n-1>= d to have room for {d//2} independent cycles with {n} nodes"
293
+ )
294
+
295
+ G = nx.empty_graph(n, create_using)
296
+
297
+ if n < 2:
298
+ return G
299
+
300
+ cycles = []
301
+ edges = set()
302
+
303
+ # Create d / 2 cycles
304
+ for i in range(d // 2):
305
+ iterations = max_tries
306
+ # Make sure the cycles are independent to have a regular graph
307
+ while len(edges) != (i + 1) * n:
308
+ iterations -= 1
309
+ # Faster than random.permutation(n) since there are only
310
+ # (n-1)! distinct cycles against n! permutations of size n
311
+ cycle = seed.permutation(n - 1).tolist()
312
+ cycle.append(n - 1)
313
+
314
+ new_edges = {
315
+ (u, v)
316
+ for u, v in nx.utils.pairwise(cycle, cyclic=True)
317
+ if (u, v) not in edges and (v, u) not in edges
318
+ }
319
+ # If the new cycle has no edges in common with previous cycles
320
+ # then add it to the list otherwise try again
321
+ if len(new_edges) == n:
322
+ cycles.append(cycle)
323
+ edges.update(new_edges)
324
+
325
+ if iterations == 0:
326
+ raise nx.NetworkXError("Too many iterations in maybe_regular_expander")
327
+
328
+ G.add_edges_from(edges)
329
+
330
+ return G
331
+
332
+
333
+ @nx.utils.not_implemented_for("directed")
334
+ @nx.utils.not_implemented_for("multigraph")
335
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
336
+ def is_regular_expander(G, *, epsilon=0):
337
+ r"""Determines whether the graph G is a regular expander. [1]_
338
+
339
+ An expander graph is a sparse graph with strong connectivity properties.
340
+
341
+ More precisely, this helper checks whether the graph is a
342
+ regular $(n, d, \lambda)$-expander with $\lambda$ close to
343
+ the Alon-Boppana bound and given by
344
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$. [2]_
345
+
346
+ In the case where $\epsilon = 0$ then if the graph successfully passes the test
347
+ it is a Ramanujan graph. [3]_
348
+
349
+ A Ramanujan graph has spectral gap almost as large as possible, which makes them
350
+ excellent expanders.
351
+
352
+ Parameters
353
+ ----------
354
+ G : NetworkX graph
355
+ epsilon : int, float, default=0
356
+
357
+ Returns
358
+ -------
359
+ bool
360
+ Whether the given graph is a regular $(n, d, \lambda)$-expander
361
+ where $\lambda = 2 \sqrt{d - 1} + \epsilon$.
362
+
363
+ Examples
364
+ --------
365
+ >>> G = nx.random_regular_expander_graph(20, 4)
366
+ >>> nx.is_regular_expander(G)
367
+ True
368
+
369
+ See Also
370
+ --------
371
+ maybe_regular_expander
372
+ random_regular_expander_graph
373
+
374
+ References
375
+ ----------
376
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
377
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
378
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
379
+
380
+ """
381
+
382
+ import numpy as np
383
+ from scipy.sparse.linalg import eigsh
384
+
385
+ if epsilon < 0:
386
+ raise nx.NetworkXError("epsilon must be non negative")
387
+
388
+ if not nx.is_regular(G):
389
+ return False
390
+
391
+ _, d = nx.utils.arbitrary_element(G.degree)
392
+
393
+ A = nx.adjacency_matrix(G, dtype=float)
394
+ lams = eigsh(A, which="LM", k=2, return_eigenvectors=False)
395
+
396
+ # lambda2 is the second biggest eigenvalue
397
+ lambda2 = min(lams)
398
+
399
+ # Use bool() to convert numpy scalar to Python Boolean
400
+ return bool(abs(lambda2) < 2 ** np.sqrt(d - 1) + epsilon)
401
+
402
+
403
+ @nx.utils.decorators.np_random_state("seed")
404
+ @nx._dispatchable(graphs=None, returns_graph=True)
405
+ def random_regular_expander_graph(
406
+ n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None
407
+ ):
408
+ r"""Returns a random regular expander graph on $n$ nodes with degree $d$.
409
+
410
+ An expander graph is a sparse graph with strong connectivity properties. [1]_
411
+
412
+ More precisely the returned graph is a $(n, d, \lambda)$-expander with
413
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
414
+
415
+ In the case where $\epsilon = 0$ it returns a Ramanujan graph.
416
+ A Ramanujan graph has spectral gap almost as large as possible,
417
+ which makes them excellent expanders. [3]_
418
+
419
+ Parameters
420
+ ----------
421
+ n : int
422
+ The number of nodes.
423
+ d : int
424
+ The degree of each node.
425
+ epsilon : int, float, default=0
426
+ max_tries : int, (default: 100)
427
+ The number of allowed loops, also used in the maybe_regular_expander utility
428
+ seed : (default: None)
429
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
430
+
431
+ Raises
432
+ ------
433
+ NetworkXError
434
+ If max_tries is reached
435
+
436
+ Examples
437
+ --------
438
+ >>> G = nx.random_regular_expander_graph(20, 4)
439
+ >>> nx.is_regular_expander(G)
440
+ True
441
+
442
+ Notes
443
+ -----
444
+ This loops over `maybe_regular_expander` and can be slow when
445
+ $n$ is too big or $\epsilon$ too small.
446
+
447
+ See Also
448
+ --------
449
+ maybe_regular_expander
450
+ is_regular_expander
451
+
452
+ References
453
+ ----------
454
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
455
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
456
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
457
+
458
+ """
459
+ G = maybe_regular_expander(
460
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
461
+ )
462
+ iterations = max_tries
463
+
464
+ while not is_regular_expander(G, epsilon=epsilon):
465
+ iterations -= 1
466
+ G = maybe_regular_expander(
467
+ n=n, d=d, create_using=create_using, max_tries=max_tries, seed=seed
468
+ )
469
+
470
+ if iterations == 0:
471
+ raise nx.NetworkXError(
472
+ "Too many iterations in random_regular_expander_graph"
473
+ )
474
+
475
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/geometric.py ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for geometric graphs.
2
+ """
3
+
4
+ import math
5
+ from bisect import bisect_left
6
+ from itertools import accumulate, combinations, product
7
+
8
+ import networkx as nx
9
+ from networkx.utils import py_random_state
10
+
11
+ __all__ = [
12
+ "geometric_edges",
13
+ "geographical_threshold_graph",
14
+ "navigable_small_world_graph",
15
+ "random_geometric_graph",
16
+ "soft_random_geometric_graph",
17
+ "thresholded_random_geometric_graph",
18
+ "waxman_graph",
19
+ "geometric_soft_configuration_graph",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(node_attrs="pos_name")
24
+ def geometric_edges(G, radius, p=2, *, pos_name="pos"):
25
+ """Returns edge list of node pairs within `radius` of each other.
26
+
27
+ Parameters
28
+ ----------
29
+ G : networkx graph
30
+ The graph from which to generate the edge list. The nodes in `G` should
31
+ have an attribute ``pos`` corresponding to the node position, which is
32
+ used to compute the distance to other nodes.
33
+ radius : scalar
34
+ The distance threshold. Edges are included in the edge list if the
35
+ distance between the two nodes is less than `radius`.
36
+ pos_name : string, default="pos"
37
+ The name of the node attribute which represents the position of each
38
+ node in 2D coordinates. Every node in the Graph must have this attribute.
39
+ p : scalar, default=2
40
+ The `Minkowski distance metric
41
+ <https://en.wikipedia.org/wiki/Minkowski_distance>`_ used to compute
42
+ distances. The default value is 2, i.e. Euclidean distance.
43
+
44
+ Returns
45
+ -------
46
+ edges : list
47
+ List of edges whose distances are less than `radius`
48
+
49
+ Notes
50
+ -----
51
+ Radius uses Minkowski distance metric `p`.
52
+ If scipy is available, `scipy.spatial.cKDTree` is used to speed computation.
53
+
54
+ Examples
55
+ --------
56
+ Create a graph with nodes that have a "pos" attribute representing 2D
57
+ coordinates.
58
+
59
+ >>> G = nx.Graph()
60
+ >>> G.add_nodes_from(
61
+ ... [
62
+ ... (0, {"pos": (0, 0)}),
63
+ ... (1, {"pos": (3, 0)}),
64
+ ... (2, {"pos": (8, 0)}),
65
+ ... ]
66
+ ... )
67
+ >>> nx.geometric_edges(G, radius=1)
68
+ []
69
+ >>> nx.geometric_edges(G, radius=4)
70
+ [(0, 1)]
71
+ >>> nx.geometric_edges(G, radius=6)
72
+ [(0, 1), (1, 2)]
73
+ >>> nx.geometric_edges(G, radius=9)
74
+ [(0, 1), (0, 2), (1, 2)]
75
+ """
76
+ # Input validation - every node must have a "pos" attribute
77
+ for n, pos in G.nodes(data=pos_name):
78
+ if pos is None:
79
+ raise nx.NetworkXError(
80
+ f"Node {n} (and all nodes) must have a '{pos_name}' attribute."
81
+ )
82
+
83
+ # NOTE: See _geometric_edges for the actual implementation. The reason this
84
+ # is split into two functions is to avoid the overhead of input validation
85
+ # every time the function is called internally in one of the other
86
+ # geometric generators
87
+ return _geometric_edges(G, radius, p, pos_name)
88
+
89
+
90
+ def _geometric_edges(G, radius, p, pos_name):
91
+ """
92
+ Implements `geometric_edges` without input validation. See `geometric_edges`
93
+ for complete docstring.
94
+ """
95
+ nodes_pos = G.nodes(data=pos_name)
96
+ try:
97
+ import scipy as sp
98
+ except ImportError:
99
+ # no scipy KDTree so compute by for-loop
100
+ radius_p = radius**p
101
+ edges = [
102
+ (u, v)
103
+ for (u, pu), (v, pv) in combinations(nodes_pos, 2)
104
+ if sum(abs(a - b) ** p for a, b in zip(pu, pv)) <= radius_p
105
+ ]
106
+ return edges
107
+ # scipy KDTree is available
108
+ nodes, coords = list(zip(*nodes_pos))
109
+ kdtree = sp.spatial.cKDTree(coords) # Cannot provide generator.
110
+ edge_indexes = kdtree.query_pairs(radius, p)
111
+ edges = [(nodes[u], nodes[v]) for u, v in sorted(edge_indexes)]
112
+ return edges
113
+
114
+
115
+ @py_random_state(5)
116
+ @nx._dispatchable(graphs=None, returns_graph=True)
117
+ def random_geometric_graph(
118
+ n, radius, dim=2, pos=None, p=2, seed=None, *, pos_name="pos"
119
+ ):
120
+ """Returns a random geometric graph in the unit cube of dimensions `dim`.
121
+
122
+ The random geometric graph model places `n` nodes uniformly at
123
+ random in the unit cube. Two nodes are joined by an edge if the
124
+ distance between the nodes is at most `radius`.
125
+
126
+ Edges are determined using a KDTree when SciPy is available.
127
+ This reduces the time complexity from $O(n^2)$ to $O(n)$.
128
+
129
+ Parameters
130
+ ----------
131
+ n : int or iterable
132
+ Number of nodes or iterable of nodes
133
+ radius: float
134
+ Distance threshold value
135
+ dim : int, optional
136
+ Dimension of graph
137
+ pos : dict, optional
138
+ A dictionary keyed by node with node positions as values.
139
+ p : float, optional
140
+ Which Minkowski distance metric to use. `p` has to meet the condition
141
+ ``1 <= p <= infinity``.
142
+
143
+ If this argument is not specified, the :math:`L^2` metric
144
+ (the Euclidean distance metric), p = 2 is used.
145
+ This should not be confused with the `p` of an Erdős-Rényi random
146
+ graph, which represents probability.
147
+ seed : integer, random_state, or None (default)
148
+ Indicator of random number generation state.
149
+ See :ref:`Randomness<randomness>`.
150
+ pos_name : string, default="pos"
151
+ The name of the node attribute which represents the position
152
+ in 2D coordinates of the node in the returned graph.
153
+
154
+ Returns
155
+ -------
156
+ Graph
157
+ A random geometric graph, undirected and without self-loops.
158
+ Each node has a node attribute ``'pos'`` that stores the
159
+ position of that node in Euclidean space as provided by the
160
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
161
+ generated by this function.
162
+
163
+ Examples
164
+ --------
165
+ Create a random geometric graph on twenty nodes where nodes are joined by
166
+ an edge if their distance is at most 0.1::
167
+
168
+ >>> G = nx.random_geometric_graph(20, 0.1)
169
+
170
+ Notes
171
+ -----
172
+ This uses a *k*-d tree to build the graph.
173
+
174
+ The `pos` keyword argument can be used to specify node positions so you
175
+ can create an arbitrary distribution and domain for positions.
176
+
177
+ For example, to use a 2D Gaussian distribution of node positions with mean
178
+ (0, 0) and standard deviation 2::
179
+
180
+ >>> import random
181
+ >>> n = 20
182
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
183
+ >>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
184
+
185
+ References
186
+ ----------
187
+ .. [1] Penrose, Mathew, *Random Geometric Graphs*,
188
+ Oxford Studies in Probability, 5, 2003.
189
+
190
+ """
191
+ # TODO Is this function just a special case of the geographical
192
+ # threshold graph?
193
+ #
194
+ # half_radius = {v: radius / 2 for v in n}
195
+ # return geographical_threshold_graph(nodes, theta=1, alpha=1,
196
+ # weight=half_radius)
197
+ #
198
+ G = nx.empty_graph(n)
199
+ # If no positions are provided, choose uniformly random vectors in
200
+ # Euclidean space of the specified dimension.
201
+ if pos is None:
202
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
203
+ nx.set_node_attributes(G, pos, pos_name)
204
+
205
+ G.add_edges_from(_geometric_edges(G, radius, p, pos_name))
206
+ return G
207
+
208
+
209
+ @py_random_state(6)
210
+ @nx._dispatchable(graphs=None, returns_graph=True)
211
+ def soft_random_geometric_graph(
212
+ n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name="pos"
213
+ ):
214
+ r"""Returns a soft random geometric graph in the unit cube.
215
+
216
+ The soft random geometric graph [1] model places `n` nodes uniformly at
217
+ random in the unit cube in dimension `dim`. Two nodes of distance, `dist`,
218
+ computed by the `p`-Minkowski distance metric are joined by an edge with
219
+ probability `p_dist` if the computed distance metric value of the nodes
220
+ is at most `radius`, otherwise they are not joined.
221
+
222
+ Edges within `radius` of each other are determined using a KDTree when
223
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
224
+ to :math:`O(n)`.
225
+
226
+ Parameters
227
+ ----------
228
+ n : int or iterable
229
+ Number of nodes or iterable of nodes
230
+ radius: float
231
+ Distance threshold value
232
+ dim : int, optional
233
+ Dimension of graph
234
+ pos : dict, optional
235
+ A dictionary keyed by node with node positions as values.
236
+ p : float, optional
237
+ Which Minkowski distance metric to use.
238
+ `p` has to meet the condition ``1 <= p <= infinity``.
239
+
240
+ If this argument is not specified, the :math:`L^2` metric
241
+ (the Euclidean distance metric), p = 2 is used.
242
+
243
+ This should not be confused with the `p` of an Erdős-Rényi random
244
+ graph, which represents probability.
245
+ p_dist : function, optional
246
+ A probability density function computing the probability of
247
+ connecting two nodes that are of distance, dist, computed by the
248
+ Minkowski distance metric. The probability density function, `p_dist`,
249
+ must be any function that takes the metric value as input
250
+ and outputs a single probability value between 0-1. The scipy.stats
251
+ package has many probability distribution functions implemented and
252
+ tools for custom probability distribution definitions [2], and passing
253
+ the .pdf method of scipy.stats distributions can be used here. If the
254
+ probability function, `p_dist`, is not supplied, the default function
255
+ is an exponential distribution with rate parameter :math:`\lambda=1`.
256
+ seed : integer, random_state, or None (default)
257
+ Indicator of random number generation state.
258
+ See :ref:`Randomness<randomness>`.
259
+ pos_name : string, default="pos"
260
+ The name of the node attribute which represents the position
261
+ in 2D coordinates of the node in the returned graph.
262
+
263
+ Returns
264
+ -------
265
+ Graph
266
+ A soft random geometric graph, undirected and without self-loops.
267
+ Each node has a node attribute ``'pos'`` that stores the
268
+ position of that node in Euclidean space as provided by the
269
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
270
+ generated by this function.
271
+
272
+ Examples
273
+ --------
274
+ Default Graph:
275
+
276
+ G = nx.soft_random_geometric_graph(50, 0.2)
277
+
278
+ Custom Graph:
279
+
280
+ Create a soft random geometric graph on 100 uniformly distributed nodes
281
+ where nodes are joined by an edge with probability computed from an
282
+ exponential distribution with rate parameter :math:`\lambda=1` if their
283
+ Euclidean distance is at most 0.2.
284
+
285
+ Notes
286
+ -----
287
+ This uses a *k*-d tree to build the graph.
288
+
289
+ The `pos` keyword argument can be used to specify node positions so you
290
+ can create an arbitrary distribution and domain for positions.
291
+
292
+ For example, to use a 2D Gaussian distribution of node positions with mean
293
+ (0, 0) and standard deviation 2
294
+
295
+ The scipy.stats package can be used to define the probability distribution
296
+ with the .pdf method used as `p_dist`.
297
+
298
+ ::
299
+
300
+ >>> import random
301
+ >>> import math
302
+ >>> n = 100
303
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
304
+ >>> p_dist = lambda dist: math.exp(-dist)
305
+ >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist)
306
+
307
+ References
308
+ ----------
309
+ .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs."
310
+ The Annals of Applied Probability 26.2 (2016): 986-1028.
311
+ .. [2] scipy.stats -
312
+ https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
313
+
314
+ """
315
+ G = nx.empty_graph(n)
316
+ G.name = f"soft_random_geometric_graph({n}, {radius}, {dim})"
317
+ # If no positions are provided, choose uniformly random vectors in
318
+ # Euclidean space of the specified dimension.
319
+ if pos is None:
320
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
321
+ nx.set_node_attributes(G, pos, pos_name)
322
+
323
+ # if p_dist function not supplied the default function is an exponential
324
+ # distribution with rate parameter :math:`\lambda=1`.
325
+ if p_dist is None:
326
+
327
+ def p_dist(dist):
328
+ return math.exp(-dist)
329
+
330
+ def should_join(edge):
331
+ u, v = edge
332
+ dist = (sum(abs(a - b) ** p for a, b in zip(pos[u], pos[v]))) ** (1 / p)
333
+ return seed.random() < p_dist(dist)
334
+
335
+ G.add_edges_from(filter(should_join, _geometric_edges(G, radius, p, pos_name)))
336
+ return G
337
+
338
+
339
+ @py_random_state(7)
340
+ @nx._dispatchable(graphs=None, returns_graph=True)
341
+ def geographical_threshold_graph(
342
+ n,
343
+ theta,
344
+ dim=2,
345
+ pos=None,
346
+ weight=None,
347
+ metric=None,
348
+ p_dist=None,
349
+ seed=None,
350
+ *,
351
+ pos_name="pos",
352
+ weight_name="weight",
353
+ ):
354
+ r"""Returns a geographical threshold graph.
355
+
356
+ The geographical threshold graph model places $n$ nodes uniformly at
357
+ random in a rectangular domain. Each node $u$ is assigned a weight
358
+ $w_u$. Two nodes $u$ and $v$ are joined by an edge if
359
+
360
+ .. math::
361
+
362
+ (w_u + w_v)p_{dist}(r) \ge \theta
363
+
364
+ where `r` is the distance between `u` and `v`, `p_dist` is any function of
365
+ `r`, and :math:`\theta` as the threshold parameter. `p_dist` is used to
366
+ give weight to the distance between nodes when deciding whether or not
367
+ they should be connected. The larger `p_dist` is, the more prone nodes
368
+ separated by `r` are to be connected, and vice versa.
369
+
370
+ Parameters
371
+ ----------
372
+ n : int or iterable
373
+ Number of nodes or iterable of nodes
374
+ theta: float
375
+ Threshold value
376
+ dim : int, optional
377
+ Dimension of graph
378
+ pos : dict
379
+ Node positions as a dictionary of tuples keyed by node.
380
+ weight : dict
381
+ Node weights as a dictionary of numbers keyed by node.
382
+ metric : function
383
+ A metric on vectors of numbers (represented as lists or
384
+ tuples). This must be a function that accepts two lists (or
385
+ tuples) as input and yields a number as output. The function
386
+ must also satisfy the four requirements of a `metric`_.
387
+ Specifically, if $d$ is the function and $x$, $y$,
388
+ and $z$ are vectors in the graph, then $d$ must satisfy
389
+
390
+ 1. $d(x, y) \ge 0$,
391
+ 2. $d(x, y) = 0$ if and only if $x = y$,
392
+ 3. $d(x, y) = d(y, x)$,
393
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
394
+
395
+ If this argument is not specified, the Euclidean distance metric is
396
+ used.
397
+
398
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
399
+ p_dist : function, optional
400
+ Any function used to give weight to the distance between nodes when
401
+ deciding whether or not they should be connected. `p_dist` was
402
+ originally conceived as a probability density function giving the
403
+ probability of connecting two nodes that are of metric distance `r`
404
+ apart. The implementation here allows for more arbitrary definitions
405
+ of `p_dist` that do not need to correspond to valid probability
406
+ density functions. The :mod:`scipy.stats` package has many
407
+ probability density functions implemented and tools for custom
408
+ probability density definitions, and passing the ``.pdf`` method of
409
+ scipy.stats distributions can be used here. If ``p_dist=None``
410
+ (the default), the exponential function :math:`r^{-2}` is used.
411
+ seed : integer, random_state, or None (default)
412
+ Indicator of random number generation state.
413
+ See :ref:`Randomness<randomness>`.
414
+ pos_name : string, default="pos"
415
+ The name of the node attribute which represents the position
416
+ in 2D coordinates of the node in the returned graph.
417
+ weight_name : string, default="weight"
418
+ The name of the node attribute which represents the weight
419
+ of the node in the returned graph.
420
+
421
+ Returns
422
+ -------
423
+ Graph
424
+ A random geographic threshold graph, undirected and without
425
+ self-loops.
426
+
427
+ Each node has a node attribute ``pos`` that stores the
428
+ position of that node in Euclidean space as provided by the
429
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
430
+ generated by this function. Similarly, each node has a node
431
+ attribute ``weight`` that stores the weight of that node as
432
+ provided or as generated.
433
+
434
+ Examples
435
+ --------
436
+ Specify an alternate distance metric using the ``metric`` keyword
437
+ argument. For example, to use the `taxicab metric`_ instead of the
438
+ default `Euclidean metric`_::
439
+
440
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
441
+ >>> G = nx.geographical_threshold_graph(10, 0.1, metric=dist)
442
+
443
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
444
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
445
+
446
+ Notes
447
+ -----
448
+ If weights are not specified they are assigned to nodes by drawing randomly
449
+ from the exponential distribution with rate parameter $\lambda=1$.
450
+ To specify weights from a different distribution, use the `weight` keyword
451
+ argument::
452
+
453
+ >>> import random
454
+ >>> n = 20
455
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
456
+ >>> G = nx.geographical_threshold_graph(20, 50, weight=w)
457
+
458
+ If node positions are not specified they are randomly assigned from the
459
+ uniform distribution.
460
+
461
+ References
462
+ ----------
463
+ .. [1] Masuda, N., Miwa, H., Konno, N.:
464
+ Geographical threshold graphs with small-world and scale-free
465
+ properties.
466
+ Physical Review E 71, 036108 (2005)
467
+ .. [2] Milan Bradonjić, Aric Hagberg and Allon G. Percus,
468
+ Giant component and connectivity in geographical threshold graphs,
469
+ in Algorithms and Models for the Web-Graph (WAW 2007),
470
+ Antony Bonato and Fan Chung (Eds), pp. 209--216, 2007
471
+ """
472
+ G = nx.empty_graph(n)
473
+ # If no weights are provided, choose them from an exponential
474
+ # distribution.
475
+ if weight is None:
476
+ weight = {v: seed.expovariate(1) for v in G}
477
+ # If no positions are provided, choose uniformly random vectors in
478
+ # Euclidean space of the specified dimension.
479
+ if pos is None:
480
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
481
+ # If no distance metric is provided, use Euclidean distance.
482
+ if metric is None:
483
+ metric = math.dist
484
+ nx.set_node_attributes(G, weight, weight_name)
485
+ nx.set_node_attributes(G, pos, pos_name)
486
+
487
+ # if p_dist is not supplied, use default r^-2
488
+ if p_dist is None:
489
+
490
+ def p_dist(r):
491
+ return r**-2
492
+
493
+ # Returns ``True`` if and only if the nodes whose attributes are
494
+ # ``du`` and ``dv`` should be joined, according to the threshold
495
+ # condition.
496
+ def should_join(pair):
497
+ u, v = pair
498
+ u_pos, v_pos = pos[u], pos[v]
499
+ u_weight, v_weight = weight[u], weight[v]
500
+ return (u_weight + v_weight) * p_dist(metric(u_pos, v_pos)) >= theta
501
+
502
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
503
+ return G
504
+
505
+
506
+ @py_random_state(6)
507
+ @nx._dispatchable(graphs=None, returns_graph=True)
508
+ def waxman_graph(
509
+ n,
510
+ beta=0.4,
511
+ alpha=0.1,
512
+ L=None,
513
+ domain=(0, 0, 1, 1),
514
+ metric=None,
515
+ seed=None,
516
+ *,
517
+ pos_name="pos",
518
+ ):
519
+ r"""Returns a Waxman random graph.
520
+
521
+ The Waxman random graph model places `n` nodes uniformly at random
522
+ in a rectangular domain. Each pair of nodes at distance `d` is
523
+ joined by an edge with probability
524
+
525
+ .. math::
526
+ p = \beta \exp(-d / \alpha L).
527
+
528
+ This function implements both Waxman models, using the `L` keyword
529
+ argument.
530
+
531
+ * Waxman-1: if `L` is not specified, it is set to be the maximum distance
532
+ between any pair of nodes.
533
+ * Waxman-2: if `L` is specified, the distance between a pair of nodes is
534
+ chosen uniformly at random from the interval `[0, L]`.
535
+
536
+ Parameters
537
+ ----------
538
+ n : int or iterable
539
+ Number of nodes or iterable of nodes
540
+ beta: float
541
+ Model parameter
542
+ alpha: float
543
+ Model parameter
544
+ L : float, optional
545
+ Maximum distance between nodes. If not specified, the actual distance
546
+ is calculated.
547
+ domain : four-tuple of numbers, optional
548
+ Domain size, given as a tuple of the form `(x_min, y_min, x_max,
549
+ y_max)`.
550
+ metric : function
551
+ A metric on vectors of numbers (represented as lists or
552
+ tuples). This must be a function that accepts two lists (or
553
+ tuples) as input and yields a number as output. The function
554
+ must also satisfy the four requirements of a `metric`_.
555
+ Specifically, if $d$ is the function and $x$, $y$,
556
+ and $z$ are vectors in the graph, then $d$ must satisfy
557
+
558
+ 1. $d(x, y) \ge 0$,
559
+ 2. $d(x, y) = 0$ if and only if $x = y$,
560
+ 3. $d(x, y) = d(y, x)$,
561
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
562
+
563
+ If this argument is not specified, the Euclidean distance metric is
564
+ used.
565
+
566
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
567
+
568
+ seed : integer, random_state, or None (default)
569
+ Indicator of random number generation state.
570
+ See :ref:`Randomness<randomness>`.
571
+ pos_name : string, default="pos"
572
+ The name of the node attribute which represents the position
573
+ in 2D coordinates of the node in the returned graph.
574
+
575
+ Returns
576
+ -------
577
+ Graph
578
+ A random Waxman graph, undirected and without self-loops. Each
579
+ node has a node attribute ``'pos'`` that stores the position of
580
+ that node in Euclidean space as generated by this function.
581
+
582
+ Examples
583
+ --------
584
+ Specify an alternate distance metric using the ``metric`` keyword
585
+ argument. For example, to use the "`taxicab metric`_" instead of the
586
+ default `Euclidean metric`_::
587
+
588
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
589
+ >>> G = nx.waxman_graph(10, 0.5, 0.1, metric=dist)
590
+
591
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
592
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
593
+
594
+ Notes
595
+ -----
596
+ Starting in NetworkX 2.0 the parameters alpha and beta align with their
597
+ usual roles in the probability distribution. In earlier versions their
598
+ positions in the expression were reversed. Their position in the calling
599
+ sequence reversed as well to minimize backward incompatibility.
600
+
601
+ References
602
+ ----------
603
+ .. [1] B. M. Waxman, *Routing of multipoint connections*.
604
+ IEEE J. Select. Areas Commun. 6(9),(1988) 1617--1622.
605
+ """
606
+ G = nx.empty_graph(n)
607
+ (xmin, ymin, xmax, ymax) = domain
608
+ # Each node gets a uniformly random position in the given rectangle.
609
+ pos = {v: (seed.uniform(xmin, xmax), seed.uniform(ymin, ymax)) for v in G}
610
+ nx.set_node_attributes(G, pos, pos_name)
611
+ # If no distance metric is provided, use Euclidean distance.
612
+ if metric is None:
613
+ metric = math.dist
614
+ # If the maximum distance L is not specified (that is, we are in the
615
+ # Waxman-1 model), then find the maximum distance between any pair
616
+ # of nodes.
617
+ #
618
+ # In the Waxman-1 model, join nodes randomly based on distance. In
619
+ # the Waxman-2 model, join randomly based on random l.
620
+ if L is None:
621
+ L = max(metric(x, y) for x, y in combinations(pos.values(), 2))
622
+
623
+ def dist(u, v):
624
+ return metric(pos[u], pos[v])
625
+
626
+ else:
627
+
628
+ def dist(u, v):
629
+ return seed.random() * L
630
+
631
+ # `pair` is the pair of nodes to decide whether to join.
632
+ def should_join(pair):
633
+ return seed.random() < beta * math.exp(-dist(*pair) / (alpha * L))
634
+
635
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
636
+ return G
637
+
638
+
639
+ @py_random_state(5)
640
+ @nx._dispatchable(graphs=None, returns_graph=True)
641
+ def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None):
642
+ r"""Returns a navigable small-world graph.
643
+
644
+ A navigable small-world graph is a directed grid with additional long-range
645
+ connections that are chosen randomly.
646
+
647
+ [...] we begin with a set of nodes [...] that are identified with the set
648
+ of lattice points in an $n \times n$ square,
649
+ $\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
650
+ and we define the *lattice distance* between two nodes $(i, j)$ and
651
+ $(k, l)$ to be the number of "lattice steps" separating them:
652
+ $d((i, j), (k, l)) = |k - i| + |l - j|$.
653
+
654
+ For a universal constant $p >= 1$, the node $u$ has a directed edge to
655
+ every other node within lattice distance $p$---these are its *local
656
+ contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
657
+ construct directed edges from $u$ to $q$ other nodes (the *long-range
658
+ contacts*) using independent random trials; the $i$th directed edge from
659
+ $u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
660
+
661
+ -- [1]_
662
+
663
+ Parameters
664
+ ----------
665
+ n : int
666
+ The length of one side of the lattice; the number of nodes in
667
+ the graph is therefore $n^2$.
668
+ p : int
669
+ The diameter of short range connections. Each node is joined with every
670
+ other node within this lattice distance.
671
+ q : int
672
+ The number of long-range connections for each node.
673
+ r : float
674
+ Exponent for decaying probability of connections. The probability of
675
+ connecting to a node at lattice distance $d$ is $1/d^r$.
676
+ dim : int
677
+ Dimension of grid
678
+ seed : integer, random_state, or None (default)
679
+ Indicator of random number generation state.
680
+ See :ref:`Randomness<randomness>`.
681
+
682
+ References
683
+ ----------
684
+ .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
685
+ perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
686
+ """
687
+ if p < 1:
688
+ raise nx.NetworkXException("p must be >= 1")
689
+ if q < 0:
690
+ raise nx.NetworkXException("q must be >= 0")
691
+ if r < 0:
692
+ raise nx.NetworkXException("r must be >= 0")
693
+
694
+ G = nx.DiGraph()
695
+ nodes = list(product(range(n), repeat=dim))
696
+ for p1 in nodes:
697
+ probs = [0]
698
+ for p2 in nodes:
699
+ if p1 == p2:
700
+ continue
701
+ d = sum((abs(b - a) for a, b in zip(p1, p2)))
702
+ if d <= p:
703
+ G.add_edge(p1, p2)
704
+ probs.append(d**-r)
705
+ cdf = list(accumulate(probs))
706
+ for _ in range(q):
707
+ target = nodes[bisect_left(cdf, seed.uniform(0, cdf[-1]))]
708
+ G.add_edge(p1, target)
709
+ return G
710
+
711
+
712
+ @py_random_state(7)
713
+ @nx._dispatchable(graphs=None, returns_graph=True)
714
+ def thresholded_random_geometric_graph(
715
+ n,
716
+ radius,
717
+ theta,
718
+ dim=2,
719
+ pos=None,
720
+ weight=None,
721
+ p=2,
722
+ seed=None,
723
+ *,
724
+ pos_name="pos",
725
+ weight_name="weight",
726
+ ):
727
+ r"""Returns a thresholded random geometric graph in the unit cube.
728
+
729
+ The thresholded random geometric graph [1] model places `n` nodes
730
+ uniformly at random in the unit cube of dimensions `dim`. Each node
731
+ `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are
732
+ joined by an edge if they are within the maximum connection distance,
733
+ `radius` computed by the `p`-Minkowski distance and the summation of
734
+ weights :math:`w_u` + :math:`w_v` is greater than or equal
735
+ to the threshold parameter `theta`.
736
+
737
+ Edges within `radius` of each other are determined using a KDTree when
738
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
739
+ to :math:`O(n)`.
740
+
741
+ Parameters
742
+ ----------
743
+ n : int or iterable
744
+ Number of nodes or iterable of nodes
745
+ radius: float
746
+ Distance threshold value
747
+ theta: float
748
+ Threshold value
749
+ dim : int, optional
750
+ Dimension of graph
751
+ pos : dict, optional
752
+ A dictionary keyed by node with node positions as values.
753
+ weight : dict, optional
754
+ Node weights as a dictionary of numbers keyed by node.
755
+ p : float, optional (default 2)
756
+ Which Minkowski distance metric to use. `p` has to meet the condition
757
+ ``1 <= p <= infinity``.
758
+
759
+ If this argument is not specified, the :math:`L^2` metric
760
+ (the Euclidean distance metric), p = 2 is used.
761
+
762
+ This should not be confused with the `p` of an Erdős-Rényi random
763
+ graph, which represents probability.
764
+ seed : integer, random_state, or None (default)
765
+ Indicator of random number generation state.
766
+ See :ref:`Randomness<randomness>`.
767
+ pos_name : string, default="pos"
768
+ The name of the node attribute which represents the position
769
+ in 2D coordinates of the node in the returned graph.
770
+ weight_name : string, default="weight"
771
+ The name of the node attribute which represents the weight
772
+ of the node in the returned graph.
773
+
774
+ Returns
775
+ -------
776
+ Graph
777
+ A thresholded random geographic graph, undirected and without
778
+ self-loops.
779
+
780
+ Each node has a node attribute ``'pos'`` that stores the
781
+ position of that node in Euclidean space as provided by the
782
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
783
+ generated by this function. Similarly, each node has a nodethre
784
+ attribute ``'weight'`` that stores the weight of that node as
785
+ provided or as generated.
786
+
787
+ Examples
788
+ --------
789
+ Default Graph:
790
+
791
+ G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
792
+
793
+ Custom Graph:
794
+
795
+ Create a thresholded random geometric graph on 50 uniformly distributed
796
+ nodes where nodes are joined by an edge if their sum weights drawn from
797
+ a exponential distribution with rate = 5 are >= theta = 0.1 and their
798
+ Euclidean distance is at most 0.2.
799
+
800
+ Notes
801
+ -----
802
+ This uses a *k*-d tree to build the graph.
803
+
804
+ The `pos` keyword argument can be used to specify node positions so you
805
+ can create an arbitrary distribution and domain for positions.
806
+
807
+ For example, to use a 2D Gaussian distribution of node positions with mean
808
+ (0, 0) and standard deviation 2
809
+
810
+ If weights are not specified they are assigned to nodes by drawing randomly
811
+ from the exponential distribution with rate parameter :math:`\lambda=1`.
812
+ To specify weights from a different distribution, use the `weight` keyword
813
+ argument::
814
+
815
+ ::
816
+
817
+ >>> import random
818
+ >>> import math
819
+ >>> n = 50
820
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
821
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
822
+ >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w)
823
+
824
+ References
825
+ ----------
826
+ .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
827
+
828
+ """
829
+ G = nx.empty_graph(n)
830
+ G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})"
831
+ # If no weights are provided, choose them from an exponential
832
+ # distribution.
833
+ if weight is None:
834
+ weight = {v: seed.expovariate(1) for v in G}
835
+ # If no positions are provided, choose uniformly random vectors in
836
+ # Euclidean space of the specified dimension.
837
+ if pos is None:
838
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
839
+ # If no distance metric is provided, use Euclidean distance.
840
+ nx.set_node_attributes(G, weight, weight_name)
841
+ nx.set_node_attributes(G, pos, pos_name)
842
+
843
+ edges = (
844
+ (u, v)
845
+ for u, v in _geometric_edges(G, radius, p, pos_name)
846
+ if weight[u] + weight[v] >= theta
847
+ )
848
+ G.add_edges_from(edges)
849
+ return G
850
+
851
+
852
+ @py_random_state(5)
853
+ @nx._dispatchable(graphs=None, returns_graph=True)
854
+ def geometric_soft_configuration_graph(
855
+ *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None
856
+ ):
857
+ r"""Returns a random graph from the geometric soft configuration model.
858
+
859
+ The $\mathbb{S}^1$ model [1]_ is the geometric soft configuration model
860
+ which is able to explain many fundamental features of real networks such as
861
+ small-world property, heteregenous degree distributions, high level of
862
+ clustering, and self-similarity.
863
+
864
+ In the geometric soft configuration model, a node $i$ is assigned two hidden
865
+ variables: a hidden degree $\kappa_i$, quantifying its popularity, influence,
866
+ or importance, and an angular position $\theta_i$ in a circle abstracting the
867
+ similarity space, where angular distances between nodes are a proxy for their
868
+ similarity. Focusing on the angular position, this model is often called
869
+ the $\mathbb{S}^1$ model (a one-dimensional sphere). The circle's radius is
870
+ adjusted to $R = N/2\pi$, where $N$ is the number of nodes, so that the density
871
+ is set to 1 without loss of generality.
872
+
873
+ The connection probability between any pair of nodes increases with
874
+ the product of their hidden degrees (i.e., their combined popularities),
875
+ and decreases with the angular distance between the two nodes.
876
+ Specifically, nodes $i$ and $j$ are connected with the probability
877
+
878
+ $p_{ij} = \frac{1}{1 + \frac{d_{ij}^\beta}{\left(\mu \kappa_i \kappa_j\right)^{\max(1, \beta)}}}$
879
+
880
+ where $d_{ij} = R\Delta\theta_{ij}$ is the arc length of the circle between
881
+ nodes $i$ and $j$ separated by an angular distance $\Delta\theta_{ij}$.
882
+ Parameters $\mu$ and $\beta$ (also called inverse temperature) control the
883
+ average degree and the clustering coefficient, respectively.
884
+
885
+ It can be shown [2]_ that the model undergoes a structural phase transition
886
+ at $\beta=1$ so that for $\beta<1$ networks are unclustered in the thermodynamic
887
+ limit (when $N\to \infty$) whereas for $\beta>1$ the ensemble generates
888
+ networks with finite clustering coefficient.
889
+
890
+ The $\mathbb{S}^1$ model can be expressed as a purely geometric model
891
+ $\mathbb{H}^2$ in the hyperbolic plane [3]_ by mapping the hidden degree of
892
+ each node into a radial coordinate as
893
+
894
+ $r_i = \hat{R} - \frac{2 \max(1, \beta)}{\beta \zeta} \ln \left(\frac{\kappa_i}{\kappa_0}\right)$
895
+
896
+ where $\hat{R}$ is the radius of the hyperbolic disk and $\zeta$ is the curvature,
897
+
898
+ $\hat{R} = \frac{2}{\zeta} \ln \left(\frac{N}{\pi}\right)
899
+ - \frac{2\max(1, \beta)}{\beta \zeta} \ln (\mu \kappa_0^2)$
900
+
901
+ The connection probability then reads
902
+
903
+ $p_{ij} = \frac{1}{1 + \exp\left({\frac{\beta\zeta}{2} (x_{ij} - \hat{R})}\right)}$
904
+
905
+ where
906
+
907
+ $x_{ij} = r_i + r_j + \frac{2}{\zeta} \ln \frac{\Delta\theta_{ij}}{2}$
908
+
909
+ is a good approximation of the hyperbolic distance between two nodes separated
910
+ by an angular distance $\Delta\theta_{ij}$ with radial coordinates $r_i$ and $r_j$.
911
+ For $\beta > 1$, the curvature $\zeta = 1$, for $\beta < 1$, $\zeta = \beta^{-1}$.
912
+
913
+
914
+ Parameters
915
+ ----------
916
+ Either `n`, `gamma`, `mean_degree` are provided or `kappas`. The values of
917
+ `n`, `gamma`, `mean_degree` (if provided) are used to construct a random
918
+ kappa-dict keyed by node with values sampled from a power-law distribution.
919
+
920
+ beta : positive number
921
+ Inverse temperature, controlling the clustering coefficient.
922
+ n : int (default: None)
923
+ Size of the network (number of nodes).
924
+ If not provided, `kappas` must be provided and holds the nodes.
925
+ gamma : float (default: None)
926
+ Exponent of the power-law distribution for hidden degrees `kappas`.
927
+ If not provided, `kappas` must be provided directly.
928
+ mean_degree : float (default: None)
929
+ The mean degree in the network.
930
+ If not provided, `kappas` must be provided directly.
931
+ kappas : dict (default: None)
932
+ A dict keyed by node to its hidden degree value.
933
+ If not provided, random values are computed based on a power-law
934
+ distribution using `n`, `gamma` and `mean_degree`.
935
+ seed : int, random_state, or None (default)
936
+ Indicator of random number generation state.
937
+ See :ref:`Randomness<randomness>`.
938
+
939
+ Returns
940
+ -------
941
+ Graph
942
+ A random geometric soft configuration graph (undirected with no self-loops).
943
+ Each node has three node-attributes:
944
+
945
+ - ``kappa`` that represents the hidden degree.
946
+
947
+ - ``theta`` the position in the similarity space ($\mathbb{S}^1$) which is
948
+ also the angular position in the hyperbolic plane.
949
+
950
+ - ``radius`` the radial position in the hyperbolic plane
951
+ (based on the hidden degree).
952
+
953
+
954
+ Examples
955
+ --------
956
+ Generate a network with specified parameters:
957
+
958
+ >>> G = nx.geometric_soft_configuration_graph(beta=1.5, n=100, gamma=2.7, mean_degree=5)
959
+
960
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
961
+ is set to 1.5 and the exponent of the powerlaw distribution of the hidden
962
+ degrees is 2.7 with mean value of 5.
963
+
964
+ Generate a network with predefined hidden degrees:
965
+
966
+ >>> kappas = {i: 10 for i in range(100)}
967
+ >>> G = nx.geometric_soft_configuration_graph(beta=2.5, kappas=kappas)
968
+
969
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
970
+ is set to 2.5 and all nodes with hidden degree $\kappa=10$.
971
+
972
+
973
+ References
974
+ ----------
975
+ .. [1] Serrano, M. Á., Krioukov, D., & Boguñá, M. (2008). Self-similarity
976
+ of complex networks and hidden metric spaces. Physical review letters, 100(7), 078701.
977
+
978
+ .. [2] van der Kolk, J., Serrano, M. Á., & Boguñá, M. (2022). An anomalous
979
+ topological phase transition in spatial random graphs. Communications Physics, 5(1), 245.
980
+
981
+ .. [3] Krioukov, D., Papadopoulos, F., Kitsak, M., Vahdat, A., & Boguná, M. (2010).
982
+ Hyperbolic geometry of complex networks. Physical Review E, 82(3), 036106.
983
+
984
+ """
985
+ if beta <= 0:
986
+ raise nx.NetworkXError("The parameter beta cannot be smaller or equal to 0.")
987
+
988
+ if kappas is not None:
989
+ if not all((n is None, gamma is None, mean_degree is None)):
990
+ raise nx.NetworkXError(
991
+ "When kappas is input, n, gamma and mean_degree must not be."
992
+ )
993
+
994
+ n = len(kappas)
995
+ mean_degree = sum(kappas) / len(kappas)
996
+ else:
997
+ if any((n is None, gamma is None, mean_degree is None)):
998
+ raise nx.NetworkXError(
999
+ "Please provide either kappas, or all 3 of: n, gamma and mean_degree."
1000
+ )
1001
+
1002
+ # Generate `n` hidden degrees from a powerlaw distribution
1003
+ # with given exponent `gamma` and mean value `mean_degree`
1004
+ gam_ratio = (gamma - 2) / (gamma - 1)
1005
+ kappa_0 = mean_degree * gam_ratio * (1 - 1 / n) / (1 - 1 / n**gam_ratio)
1006
+ base = 1 - 1 / n
1007
+ power = 1 / (1 - gamma)
1008
+ kappas = {i: kappa_0 * (1 - seed.random() * base) ** power for i in range(n)}
1009
+
1010
+ G = nx.Graph()
1011
+ R = n / (2 * math.pi)
1012
+
1013
+ # Approximate values for mu in the thermodynamic limit (when n -> infinity)
1014
+ if beta > 1:
1015
+ mu = beta * math.sin(math.pi / beta) / (2 * math.pi * mean_degree)
1016
+ elif beta == 1:
1017
+ mu = 1 / (2 * mean_degree * math.log(n))
1018
+ else:
1019
+ mu = (1 - beta) / (2**beta * mean_degree * n ** (1 - beta))
1020
+
1021
+ # Generate random positions on a circle
1022
+ thetas = {k: seed.uniform(0, 2 * math.pi) for k in kappas}
1023
+
1024
+ for u in kappas:
1025
+ for v in list(G):
1026
+ angle = math.pi - math.fabs(math.pi - math.fabs(thetas[u] - thetas[v]))
1027
+ dij = math.pow(R * angle, beta)
1028
+ mu_kappas = math.pow(mu * kappas[u] * kappas[v], max(1, beta))
1029
+ p_ij = 1 / (1 + dij / mu_kappas)
1030
+
1031
+ # Create an edge with a certain connection probability
1032
+ if seed.random() < p_ij:
1033
+ G.add_edge(u, v)
1034
+ G.add_node(u)
1035
+
1036
+ nx.set_node_attributes(G, thetas, "theta")
1037
+ nx.set_node_attributes(G, kappas, "kappa")
1038
+
1039
+ # Map hidden degrees into the radial coordiantes
1040
+ zeta = 1 if beta > 1 else 1 / beta
1041
+ kappa_min = min(kappas.values())
1042
+ R_c = 2 * max(1, beta) / (beta * zeta)
1043
+ R_hat = (2 / zeta) * math.log(n / math.pi) - R_c * math.log(mu * kappa_min)
1044
+ radii = {node: R_hat - R_c * math.log(kappa) for node, kappa in kappas.items()}
1045
+ nx.set_node_attributes(G, radii, "radius")
1046
+
1047
+ return G
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/networkx/generators/internet_as_graphs.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates graphs resembling the Internet Autonomous System network"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = ["random_internet_as_graph"]
7
+
8
+
9
+ def uniform_int_from_avg(a, m, seed):
10
+ """Pick a random integer with uniform probability.
11
+
12
+ Returns a random integer uniformly taken from a distribution with
13
+ minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where
14
+ b = 2*m - a.
15
+
16
+ Notes
17
+ -----
18
+ p = (b-floor(b))/2
19
+ X = X1 + X2; X1~U(a,floor(b)), X2~B(p)
20
+ E[X] = E[X1] + E[X2] = (floor(b)+a)/2 + (b-floor(b))/2 = (b+a)/2 = m
21
+ """
22
+
23
+ from math import floor
24
+
25
+ assert m >= a
26
+ b = 2 * m - a
27
+ p = (b - floor(b)) / 2
28
+ X1 = round(seed.random() * (floor(b) - a) + a)
29
+ if seed.random() < p:
30
+ X2 = 1
31
+ else:
32
+ X2 = 0
33
+ return X1 + X2
34
+
35
+
36
+ def choose_pref_attach(degs, seed):
37
+ """Pick a random value, with a probability given by its weight.
38
+
39
+ Returns a random choice among degs keys, each of which has a
40
+ probability proportional to the corresponding dictionary value.
41
+
42
+ Parameters
43
+ ----------
44
+ degs: dictionary
45
+ It contains the possible values (keys) and the corresponding
46
+ probabilities (values)
47
+ seed: random state
48
+
49
+ Returns
50
+ -------
51
+ v: object
52
+ A key of degs or None if degs is empty
53
+ """
54
+
55
+ if len(degs) == 0:
56
+ return None
57
+ s = sum(degs.values())
58
+ if s == 0:
59
+ return seed.choice(list(degs.keys()))
60
+ v = seed.random() * s
61
+
62
+ nodes = list(degs.keys())
63
+ i = 0
64
+ acc = degs[nodes[i]]
65
+ while v > acc:
66
+ i += 1
67
+ acc += degs[nodes[i]]
68
+ return nodes[i]
69
+
70
+
71
+ class AS_graph_generator:
72
+ """Generates random internet AS graphs."""
73
+
74
+ def __init__(self, n, seed):
75
+ """Initializes variables. Immediate numbers are taken from [1].
76
+
77
+ Parameters
78
+ ----------
79
+ n: integer
80
+ Number of graph nodes
81
+ seed: random state
82
+ Indicator of random number generation state.
83
+ See :ref:`Randomness<randomness>`.
84
+
85
+ Returns
86
+ -------
87
+ GG: AS_graph_generator object
88
+
89
+ References
90
+ ----------
91
+ [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
92
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
93
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
94
+ """
95
+
96
+ self.seed = seed
97
+ self.n_t = min(n, round(self.seed.random() * 2 + 4)) # num of T nodes
98
+ self.n_m = round(0.15 * n) # number of M nodes
99
+ self.n_cp = round(0.05 * n) # number of CP nodes
100
+ self.n_c = max(0, n - self.n_t - self.n_m - self.n_cp) # number of C nodes
101
+
102
+ self.d_m = 2 + (2.5 * n) / 10000 # average multihoming degree for M nodes
103
+ self.d_cp = 2 + (1.5 * n) / 10000 # avg multihoming degree for CP nodes
104
+ self.d_c = 1 + (5 * n) / 100000 # average multihoming degree for C nodes
105
+
106
+ self.p_m_m = 1 + (2 * n) / 10000 # avg num of peer edges between M and M
107
+ self.p_cp_m = 0.2 + (2 * n) / 10000 # avg num of peer edges between CP, M
108
+ self.p_cp_cp = 0.05 + (2 * n) / 100000 # avg num of peer edges btwn CP, CP
109
+
110
+ self.t_m = 0.375 # probability M's provider is T
111
+ self.t_cp = 0.375 # probability CP's provider is T
112
+ self.t_c = 0.125 # probability C's provider is T
113
+
114
+ def t_graph(self):
115
+ """Generates the core mesh network of tier one nodes of a AS graph.
116
+
117
+ Returns
118
+ -------
119
+ G: Networkx Graph
120
+ Core network
121
+ """
122
+
123
+ self.G = nx.Graph()
124
+ for i in range(self.n_t):
125
+ self.G.add_node(i, type="T")
126
+ for r in self.regions:
127
+ self.regions[r].add(i)
128
+ for j in self.G.nodes():
129
+ if i != j:
130
+ self.add_edge(i, j, "peer")
131
+ self.customers[i] = set()
132
+ self.providers[i] = set()
133
+ return self.G
134
+
135
+ def add_edge(self, i, j, kind):
136
+ if kind == "transit":
137
+ customer = str(i)
138
+ else:
139
+ customer = "none"
140
+ self.G.add_edge(i, j, type=kind, customer=customer)
141
+
142
+ def choose_peer_pref_attach(self, node_list):
143
+ """Pick a node with a probability weighted by its peer degree.
144
+
145
+ Pick a node from node_list with preferential attachment
146
+ computed only on their peer degree
147
+ """
148
+
149
+ d = {}
150
+ for n in node_list:
151
+ d[n] = self.G.nodes[n]["peers"]
152
+ return choose_pref_attach(d, self.seed)
153
+
154
+ def choose_node_pref_attach(self, node_list):
155
+ """Pick a node with a probability weighted by its degree.
156
+
157
+ Pick a node from node_list with preferential attachment
158
+ computed on their degree
159
+ """
160
+
161
+ degs = dict(self.G.degree(node_list))
162
+ return choose_pref_attach(degs, self.seed)
163
+
164
+ def add_customer(self, i, j):
165
+ """Keep the dictionaries 'customers' and 'providers' consistent."""
166
+
167
+ self.customers[j].add(i)
168
+ self.providers[i].add(j)
169
+ for z in self.providers[j]:
170
+ self.customers[z].add(i)
171
+ self.providers[i].add(z)
172
+
173
+ def add_node(self, i, kind, reg2prob, avg_deg, t_edge_prob):
174
+ """Add a node and its customer transit edges to the graph.
175
+
176
+ Parameters
177
+ ----------
178
+ i: object
179
+ Identifier of the new node
180
+ kind: string
181
+ Type of the new node. Options are: 'M' for middle node, 'CP' for
182
+ content provider and 'C' for customer.
183
+ reg2prob: float
184
+ Probability the new node can be in two different regions.
185
+ avg_deg: float
186
+ Average number of transit nodes of which node i is customer.
187
+ t_edge_prob: float
188
+ Probability node i establish a customer transit edge with a tier
189
+ one (T) node
190
+
191
+ Returns
192
+ -------
193
+ i: object
194
+ Identifier of the new node
195
+ """
196
+
197
+ regs = 1 # regions in which node resides
198
+ if self.seed.random() < reg2prob: # node is in two regions
199
+ regs = 2
200
+ node_options = set()
201
+
202
+ self.G.add_node(i, type=kind, peers=0)
203
+ self.customers[i] = set()
204
+ self.providers[i] = set()
205
+ self.nodes[kind].add(i)
206
+ for r in self.seed.sample(list(self.regions), regs):
207
+ node_options = node_options.union(self.regions[r])
208
+ self.regions[r].add(i)
209
+
210
+ edge_num = uniform_int_from_avg(1, avg_deg, self.seed)
211
+
212
+ t_options = node_options.intersection(self.nodes["T"])
213
+ m_options = node_options.intersection(self.nodes["M"])
214
+ if i in m_options:
215
+ m_options.remove(i)
216
+ d = 0
217
+ while d < edge_num and (len(t_options) > 0 or len(m_options) > 0):
218
+ if len(m_options) == 0 or (
219
+ len(t_options) > 0 and self.seed.random() < t_edge_prob
220
+ ): # add edge to a T node
221
+ j = self.choose_node_pref_attach(t_options)
222
+ t_options.remove(j)
223
+ else:
224
+ j = self.choose_node_pref_attach(m_options)
225
+ m_options.remove(j)
226
+ self.add_edge(i, j, "transit")
227
+ self.add_customer(i, j)
228
+ d += 1
229
+
230
+ return i
231
+
232
+ def add_m_peering_link(self, m, to_kind):
233
+ """Add a peering link between two middle tier (M) nodes.
234
+
235
+ Target node j is drawn considering a preferential attachment based on
236
+ other M node peering degree.
237
+
238
+ Parameters
239
+ ----------
240
+ m: object
241
+ Node identifier
242
+ to_kind: string
243
+ type for target node j (must be always M)
244
+
245
+ Returns
246
+ -------
247
+ success: boolean
248
+ """
249
+
250
+ # candidates are of type 'M' and are not customers of m
251
+ node_options = self.nodes["M"].difference(self.customers[m])
252
+ # candidates are not providers of m
253
+ node_options = node_options.difference(self.providers[m])
254
+ # remove self
255
+ if m in node_options:
256
+ node_options.remove(m)
257
+
258
+ # remove candidates we are already connected to
259
+ for j in self.G.neighbors(m):
260
+ if j in node_options:
261
+ node_options.remove(j)
262
+
263
+ if len(node_options) > 0:
264
+ j = self.choose_peer_pref_attach(node_options)
265
+ self.add_edge(m, j, "peer")
266
+ self.G.nodes[m]["peers"] += 1
267
+ self.G.nodes[j]["peers"] += 1
268
+ return True
269
+ else:
270
+ return False
271
+
272
+ def add_cp_peering_link(self, cp, to_kind):
273
+ """Add a peering link to a content provider (CP) node.
274
+
275
+ Target node j can be CP or M and it is drawn uniformly among the nodes
276
+ belonging to the same region as cp.
277
+
278
+ Parameters
279
+ ----------
280
+ cp: object
281
+ Node identifier
282
+ to_kind: string
283
+ type for target node j (must be M or CP)
284
+
285
+ Returns
286
+ -------
287
+ success: boolean
288
+ """
289
+
290
+ node_options = set()
291
+ for r in self.regions: # options include nodes in the same region(s)
292
+ if cp in self.regions[r]:
293
+ node_options = node_options.union(self.regions[r])
294
+
295
+ # options are restricted to the indicated kind ('M' or 'CP')
296
+ node_options = self.nodes[to_kind].intersection(node_options)
297
+
298
+ # remove self
299
+ if cp in node_options:
300
+ node_options.remove(cp)
301
+
302
+ # remove nodes that are cp's providers
303
+ node_options = node_options.difference(self.providers[cp])
304
+
305
+ # remove nodes we are already connected to
306
+ for j in self.G.neighbors(cp):
307
+ if j in node_options:
308
+ node_options.remove(j)
309
+
310
+ if len(node_options) > 0:
311
+ j = self.seed.sample(list(node_options), 1)[0]
312
+ self.add_edge(cp, j, "peer")
313
+ self.G.nodes[cp]["peers"] += 1
314
+ self.G.nodes[j]["peers"] += 1
315
+ return True
316
+ else:
317
+ return False
318
+
319
+ def graph_regions(self, rn):
320
+ """Initializes AS network regions.
321
+
322
+ Parameters
323
+ ----------
324
+ rn: integer
325
+ Number of regions
326
+ """
327
+
328
+ self.regions = {}
329
+ for i in range(rn):
330
+ self.regions["REG" + str(i)] = set()
331
+
332
+ def add_peering_links(self, from_kind, to_kind):
333
+ """Utility function to add peering links among node groups."""
334
+ peer_link_method = None
335
+ if from_kind == "M":
336
+ peer_link_method = self.add_m_peering_link
337
+ m = self.p_m_m
338
+ if from_kind == "CP":
339
+ peer_link_method = self.add_cp_peering_link
340
+ if to_kind == "M":
341
+ m = self.p_cp_m
342
+ else:
343
+ m = self.p_cp_cp
344
+
345
+ for i in self.nodes[from_kind]:
346
+ num = uniform_int_from_avg(0, m, self.seed)
347
+ for _ in range(num):
348
+ peer_link_method(i, to_kind)
349
+
350
+ def generate(self):
351
+ """Generates a random AS network graph as described in [1].
352
+
353
+ Returns
354
+ -------
355
+ G: Graph object
356
+
357
+ Notes
358
+ -----
359
+ The process steps are the following: first we create the core network
360
+ of tier one nodes, then we add the middle tier (M), the content
361
+ provider (CP) and the customer (C) nodes along with their transit edges
362
+ (link i,j means i is customer of j). Finally we add peering links
363
+ between M nodes, between M and CP nodes and between CP node couples.
364
+ For a detailed description of the algorithm, please refer to [1].
365
+
366
+ References
367
+ ----------
368
+ [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
369
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
370
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
371
+ """
372
+
373
+ self.graph_regions(5)
374
+ self.customers = {}
375
+ self.providers = {}
376
+ self.nodes = {"T": set(), "M": set(), "CP": set(), "C": set()}
377
+
378
+ self.t_graph()
379
+ self.nodes["T"] = set(self.G.nodes())
380
+
381
+ i = len(self.nodes["T"])
382
+ for _ in range(self.n_m):
383
+ self.nodes["M"].add(self.add_node(i, "M", 0.2, self.d_m, self.t_m))
384
+ i += 1
385
+ for _ in range(self.n_cp):
386
+ self.nodes["CP"].add(self.add_node(i, "CP", 0.05, self.d_cp, self.t_cp))
387
+ i += 1
388
+ for _ in range(self.n_c):
389
+ self.nodes["C"].add(self.add_node(i, "C", 0, self.d_c, self.t_c))
390
+ i += 1
391
+
392
+ self.add_peering_links("M", "M")
393
+ self.add_peering_links("CP", "M")
394
+ self.add_peering_links("CP", "CP")
395
+
396
+ return self.G
397
+
398
+
399
+ @py_random_state(1)
400
+ @nx._dispatchable(graphs=None, returns_graph=True)
401
+ def random_internet_as_graph(n, seed=None):
402
+ """Generates a random undirected graph resembling the Internet AS network
403
+
404
+ Parameters
405
+ ----------
406
+ n: integer in [1000, 10000]
407
+ Number of graph nodes
408
+ seed : integer, random_state, or None (default)
409
+ Indicator of random number generation state.
410
+ See :ref:`Randomness<randomness>`.
411
+
412
+ Returns
413
+ -------
414
+ G: Networkx Graph object
415
+ A randomly generated undirected graph
416
+
417
+ Notes
418
+ -----
419
+ This algorithm returns an undirected graph resembling the Internet
420
+ Autonomous System (AS) network, it uses the approach by Elmokashfi et al.
421
+ [1]_ and it grants the properties described in the related paper [1]_.
422
+
423
+ Each node models an autonomous system, with an attribute 'type' specifying
424
+ its kind; tier-1 (T), mid-level (M), customer (C) or content-provider (CP).
425
+ Each edge models an ADV communication link (hence, bidirectional) with
426
+ attributes:
427
+
428
+ - type: transit|peer, the kind of commercial agreement between nodes;
429
+ - customer: <node id>, the identifier of the node acting as customer
430
+ ('none' if type is peer).
431
+
432
+ References
433
+ ----------
434
+ .. [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
435
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
436
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
437
+ """
438
+
439
+ GG = AS_graph_generator(n, seed)
440
+ G = GG.generate()
441
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/intersection.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random intersection graphs.
3
+ """
4
+ import networkx as nx
5
+ from networkx.utils import py_random_state
6
+
7
+ __all__ = [
8
+ "uniform_random_intersection_graph",
9
+ "k_random_intersection_graph",
10
+ "general_random_intersection_graph",
11
+ ]
12
+
13
+
14
+ @py_random_state(3)
15
+ @nx._dispatchable(graphs=None, returns_graph=True)
16
+ def uniform_random_intersection_graph(n, m, p, seed=None):
17
+ """Returns a uniform random intersection graph.
18
+
19
+ Parameters
20
+ ----------
21
+ n : int
22
+ The number of nodes in the first bipartite set (nodes)
23
+ m : int
24
+ The number of nodes in the second bipartite set (attributes)
25
+ p : float
26
+ Probability of connecting nodes between bipartite sets
27
+ seed : integer, random_state, or None (default)
28
+ Indicator of random number generation state.
29
+ See :ref:`Randomness<randomness>`.
30
+
31
+ See Also
32
+ --------
33
+ gnp_random_graph
34
+
35
+ References
36
+ ----------
37
+ .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995,
38
+ PhD thesis, Johns Hopkins University
39
+ .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B.,
40
+ Random intersection graphs when m = !(n):
41
+ An equivalence theorem relating the evolution of the g(n, m, p)
42
+ and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176.
43
+ """
44
+ from networkx.algorithms import bipartite
45
+
46
+ G = bipartite.random_graph(n, m, p, seed)
47
+ return nx.projected_graph(G, range(n))
48
+
49
+
50
+ @py_random_state(3)
51
+ @nx._dispatchable(graphs=None, returns_graph=True)
52
+ def k_random_intersection_graph(n, m, k, seed=None):
53
+ """Returns a intersection graph with randomly chosen attribute sets for
54
+ each node that are of equal size (k).
55
+
56
+ Parameters
57
+ ----------
58
+ n : int
59
+ The number of nodes in the first bipartite set (nodes)
60
+ m : int
61
+ The number of nodes in the second bipartite set (attributes)
62
+ k : float
63
+ Size of attribute set to assign to each node.
64
+ seed : integer, random_state, or None (default)
65
+ Indicator of random number generation state.
66
+ See :ref:`Randomness<randomness>`.
67
+
68
+ See Also
69
+ --------
70
+ gnp_random_graph, uniform_random_intersection_graph
71
+
72
+ References
73
+ ----------
74
+ .. [1] Godehardt, E., and Jaworski, J.
75
+ Two models of random intersection graphs and their applications.
76
+ Electronic Notes in Discrete Mathematics 10 (2001), 129--132.
77
+ """
78
+ G = nx.empty_graph(n + m)
79
+ mset = range(n, n + m)
80
+ for v in range(n):
81
+ targets = seed.sample(mset, k)
82
+ G.add_edges_from(zip([v] * len(targets), targets))
83
+ return nx.projected_graph(G, range(n))
84
+
85
+
86
+ @py_random_state(3)
87
+ @nx._dispatchable(graphs=None, returns_graph=True)
88
+ def general_random_intersection_graph(n, m, p, seed=None):
89
+ """Returns a random intersection graph with independent probabilities
90
+ for connections between node and attribute sets.
91
+
92
+ Parameters
93
+ ----------
94
+ n : int
95
+ The number of nodes in the first bipartite set (nodes)
96
+ m : int
97
+ The number of nodes in the second bipartite set (attributes)
98
+ p : list of floats of length m
99
+ Probabilities for connecting nodes to each attribute
100
+ seed : integer, random_state, or None (default)
101
+ Indicator of random number generation state.
102
+ See :ref:`Randomness<randomness>`.
103
+
104
+ See Also
105
+ --------
106
+ gnp_random_graph, uniform_random_intersection_graph
107
+
108
+ References
109
+ ----------
110
+ .. [1] Nikoletseas, S. E., Raptopoulos, C., and Spirakis, P. G.
111
+ The existence and efficient construction of large independent sets
112
+ in general random intersection graphs. In ICALP (2004), J. D´ıaz,
113
+ J. Karhum¨aki, A. Lepist¨o, and D. Sannella, Eds., vol. 3142
114
+ of Lecture Notes in Computer Science, Springer, pp. 1029–1040.
115
+ """
116
+ if len(p) != m:
117
+ raise ValueError("Probability list p must have m elements.")
118
+ G = nx.empty_graph(n + m)
119
+ mset = range(n, n + m)
120
+ for u in range(n):
121
+ for v, q in zip(mset, p):
122
+ if seed.random() < q:
123
+ G.add_edge(u, v)
124
+ return nx.projected_graph(G, range(n))
env-llmeval/lib/python3.10/site-packages/networkx/generators/interval_graph.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for interval graph.
3
+ """
4
+ from collections.abc import Sequence
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = ["interval_graph"]
9
+
10
+
11
+ @nx._dispatchable(graphs=None, returns_graph=True)
12
+ def interval_graph(intervals):
13
+ """Generates an interval graph for a list of intervals given.
14
+
15
+ In graph theory, an interval graph is an undirected graph formed from a set
16
+ of closed intervals on the real line, with a vertex for each interval
17
+ and an edge between vertices whose intervals intersect.
18
+ It is the intersection graph of the intervals.
19
+
20
+ More information can be found at:
21
+ https://en.wikipedia.org/wiki/Interval_graph
22
+
23
+ Parameters
24
+ ----------
25
+ intervals : a sequence of intervals, say (l, r) where l is the left end,
26
+ and r is the right end of the closed interval.
27
+
28
+ Returns
29
+ -------
30
+ G : networkx graph
31
+
32
+ Examples
33
+ --------
34
+ >>> intervals = [(-2, 3), [1, 4], (2, 3), (4, 6)]
35
+ >>> G = nx.interval_graph(intervals)
36
+ >>> sorted(G.edges)
37
+ [((-2, 3), (1, 4)), ((-2, 3), (2, 3)), ((1, 4), (2, 3)), ((1, 4), (4, 6))]
38
+
39
+ Raises
40
+ ------
41
+ :exc:`TypeError`
42
+ if `intervals` contains None or an element which is not
43
+ collections.abc.Sequence or not a length of 2.
44
+ :exc:`ValueError`
45
+ if `intervals` contains an interval such that min1 > max1
46
+ where min1,max1 = interval
47
+ """
48
+ intervals = list(intervals)
49
+ for interval in intervals:
50
+ if not (isinstance(interval, Sequence) and len(interval) == 2):
51
+ raise TypeError(
52
+ "Each interval must have length 2, and be a "
53
+ "collections.abc.Sequence such as tuple or list."
54
+ )
55
+ if interval[0] > interval[1]:
56
+ raise ValueError(f"Interval must have lower value first. Got {interval}")
57
+
58
+ graph = nx.Graph()
59
+
60
+ tupled_intervals = [tuple(interval) for interval in intervals]
61
+ graph.add_nodes_from(tupled_intervals)
62
+
63
+ while tupled_intervals:
64
+ min1, max1 = interval1 = tupled_intervals.pop()
65
+ for interval2 in tupled_intervals:
66
+ min2, max2 = interval2
67
+ if max1 >= min2 and max2 >= min1:
68
+ graph.add_edge(interval1, interval2)
69
+ return graph
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/networkx/generators/lattice.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating grid graphs and lattices
2
+
3
+ The :func:`grid_2d_graph`, :func:`triangular_lattice_graph`, and
4
+ :func:`hexagonal_lattice_graph` functions correspond to the three
5
+ `regular tilings of the plane`_, the square, triangular, and hexagonal
6
+ tilings, respectively. :func:`grid_graph` and :func:`hypercube_graph`
7
+ are similar for arbitrary dimensions. Useful relevant discussion can
8
+ be found about `Triangular Tiling`_, and `Square, Hex and Triangle Grids`_
9
+
10
+ .. _regular tilings of the plane: https://en.wikipedia.org/wiki/List_of_regular_polytopes_and_compounds#Euclidean_tilings
11
+ .. _Square, Hex and Triangle Grids: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
12
+ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
13
+
14
+ """
15
+
16
+ from itertools import repeat
17
+ from math import sqrt
18
+
19
+ import networkx as nx
20
+ from networkx.classes import set_node_attributes
21
+ from networkx.exception import NetworkXError
22
+ from networkx.generators.classic import cycle_graph, empty_graph, path_graph
23
+ from networkx.relabel import relabel_nodes
24
+ from networkx.utils import flatten, nodes_or_number, pairwise
25
+
26
+ __all__ = [
27
+ "grid_2d_graph",
28
+ "grid_graph",
29
+ "hypercube_graph",
30
+ "triangular_lattice_graph",
31
+ "hexagonal_lattice_graph",
32
+ ]
33
+
34
+
35
+ @nx._dispatchable(graphs=None, returns_graph=True)
36
+ @nodes_or_number([0, 1])
37
+ def grid_2d_graph(m, n, periodic=False, create_using=None):
38
+ """Returns the two-dimensional grid graph.
39
+
40
+ The grid graph has each node connected to its four nearest neighbors.
41
+
42
+ Parameters
43
+ ----------
44
+ m, n : int or iterable container of nodes
45
+ If an integer, nodes are from `range(n)`.
46
+ If a container, elements become the coordinate of the nodes.
47
+
48
+ periodic : bool or iterable
49
+ If `periodic` is True, both dimensions are periodic. If False, none
50
+ are periodic. If `periodic` is iterable, it should yield 2 bool
51
+ values indicating whether the 1st and 2nd axes, respectively, are
52
+ periodic.
53
+
54
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
55
+ Graph type to create. If graph instance, then cleared before populated.
56
+
57
+ Returns
58
+ -------
59
+ NetworkX graph
60
+ The (possibly periodic) grid graph of the specified dimensions.
61
+
62
+ """
63
+ G = empty_graph(0, create_using)
64
+ row_name, rows = m
65
+ col_name, cols = n
66
+ G.add_nodes_from((i, j) for i in rows for j in cols)
67
+ G.add_edges_from(((i, j), (pi, j)) for pi, i in pairwise(rows) for j in cols)
68
+ G.add_edges_from(((i, j), (i, pj)) for i in rows for pj, j in pairwise(cols))
69
+
70
+ try:
71
+ periodic_r, periodic_c = periodic
72
+ except TypeError:
73
+ periodic_r = periodic_c = periodic
74
+
75
+ if periodic_r and len(rows) > 2:
76
+ first = rows[0]
77
+ last = rows[-1]
78
+ G.add_edges_from(((first, j), (last, j)) for j in cols)
79
+ if periodic_c and len(cols) > 2:
80
+ first = cols[0]
81
+ last = cols[-1]
82
+ G.add_edges_from(((i, first), (i, last)) for i in rows)
83
+ # both directions for directed
84
+ if G.is_directed():
85
+ G.add_edges_from((v, u) for u, v in G.edges())
86
+ return G
87
+
88
+
89
+ @nx._dispatchable(graphs=None, returns_graph=True)
90
+ def grid_graph(dim, periodic=False):
91
+ """Returns the *n*-dimensional grid graph.
92
+
93
+ The dimension *n* is the length of the list `dim` and the size in
94
+ each dimension is the value of the corresponding list element.
95
+
96
+ Parameters
97
+ ----------
98
+ dim : list or tuple of numbers or iterables of nodes
99
+ 'dim' is a tuple or list with, for each dimension, either a number
100
+ that is the size of that dimension or an iterable of nodes for
101
+ that dimension. The dimension of the grid_graph is the length
102
+ of `dim`.
103
+
104
+ periodic : bool or iterable
105
+ If `periodic` is True, all dimensions are periodic. If False all
106
+ dimensions are not periodic. If `periodic` is iterable, it should
107
+ yield `dim` bool values each of which indicates whether the
108
+ corresponding axis is periodic.
109
+
110
+ Returns
111
+ -------
112
+ NetworkX graph
113
+ The (possibly periodic) grid graph of the specified dimensions.
114
+
115
+ Examples
116
+ --------
117
+ To produce a 2 by 3 by 4 grid graph, a graph on 24 nodes:
118
+
119
+ >>> from networkx import grid_graph
120
+ >>> G = grid_graph(dim=(2, 3, 4))
121
+ >>> len(G)
122
+ 24
123
+ >>> G = grid_graph(dim=(range(7, 9), range(3, 6)))
124
+ >>> len(G)
125
+ 6
126
+ """
127
+ from networkx.algorithms.operators.product import cartesian_product
128
+
129
+ if not dim:
130
+ return empty_graph(0)
131
+
132
+ try:
133
+ func = (cycle_graph if p else path_graph for p in periodic)
134
+ except TypeError:
135
+ func = repeat(cycle_graph if periodic else path_graph)
136
+
137
+ G = next(func)(dim[0])
138
+ for current_dim in dim[1:]:
139
+ Gnew = next(func)(current_dim)
140
+ G = cartesian_product(Gnew, G)
141
+ # graph G is done but has labels of the form (1, (2, (3, 1))) so relabel
142
+ H = relabel_nodes(G, flatten)
143
+ return H
144
+
145
+
146
+ @nx._dispatchable(graphs=None, returns_graph=True)
147
+ def hypercube_graph(n):
148
+ """Returns the *n*-dimensional hypercube graph.
149
+
150
+ The nodes are the integers between 0 and ``2 ** n - 1``, inclusive.
151
+
152
+ For more information on the hypercube graph, see the Wikipedia
153
+ article `Hypercube graph`_.
154
+
155
+ .. _Hypercube graph: https://en.wikipedia.org/wiki/Hypercube_graph
156
+
157
+ Parameters
158
+ ----------
159
+ n : int
160
+ The dimension of the hypercube.
161
+ The number of nodes in the graph will be ``2 ** n``.
162
+
163
+ Returns
164
+ -------
165
+ NetworkX graph
166
+ The hypercube graph of dimension *n*.
167
+ """
168
+ dim = n * [2]
169
+ G = grid_graph(dim)
170
+ return G
171
+
172
+
173
+ @nx._dispatchable(graphs=None, returns_graph=True)
174
+ def triangular_lattice_graph(
175
+ m, n, periodic=False, with_positions=True, create_using=None
176
+ ):
177
+ r"""Returns the $m$ by $n$ triangular lattice graph.
178
+
179
+ The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in
180
+ which each square unit has a diagonal edge (each grid unit has a chord).
181
+
182
+ The returned graph has $m$ rows and $n$ columns of triangles. Rows and
183
+ columns include both triangles pointing up and down. Rows form a strip
184
+ of constant height. Columns form a series of diamond shapes, staggered
185
+ with the columns on either side. Another way to state the size is that
186
+ the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns.
187
+ The odd row nodes are shifted horizontally relative to the even rows.
188
+
189
+ Directed graph types have edges pointed up or right.
190
+
191
+ Positions of nodes are computed by default or `with_positions is True`.
192
+ The position of each node (embedded in a euclidean plane) is stored in
193
+ the graph using equilateral triangles with sidelength 1.
194
+ The height between rows of nodes is thus $\sqrt(3)/2$.
195
+ Nodes lie in the first quadrant with the node $(0, 0)$ at the origin.
196
+
197
+ .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html
198
+ .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
199
+ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
200
+
201
+ Parameters
202
+ ----------
203
+ m : int
204
+ The number of rows in the lattice.
205
+
206
+ n : int
207
+ The number of columns in the lattice.
208
+
209
+ periodic : bool (default: False)
210
+ If True, join the boundary vertices of the grid using periodic
211
+ boundary conditions. The join between boundaries is the final row
212
+ and column of triangles. This means there is one row and one column
213
+ fewer nodes for the periodic lattice. Periodic lattices require
214
+ `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd
215
+
216
+ with_positions : bool (default: True)
217
+ Store the coordinates of each node in the graph node attribute 'pos'.
218
+ The coordinates provide a lattice with equilateral triangles.
219
+ Periodic positions shift the nodes vertically in a nonlinear way so
220
+ the edges don't overlap so much.
221
+
222
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
223
+ Graph type to create. If graph instance, then cleared before populated.
224
+
225
+ Returns
226
+ -------
227
+ NetworkX graph
228
+ The *m* by *n* triangular lattice graph.
229
+ """
230
+ H = empty_graph(0, create_using)
231
+ if n == 0 or m == 0:
232
+ return H
233
+ if periodic:
234
+ if n < 5 or m < 3:
235
+ msg = f"m > 2 and n > 4 required for periodic. m={m}, n={n}"
236
+ raise NetworkXError(msg)
237
+
238
+ N = (n + 1) // 2 # number of nodes in row
239
+ rows = range(m + 1)
240
+ cols = range(N + 1)
241
+ # Make grid
242
+ H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N])
243
+ H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols)
244
+ # add diagonals
245
+ H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N])
246
+ H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N])
247
+ # identify boundary nodes if periodic
248
+ from networkx.algorithms.minors import contracted_nodes
249
+
250
+ if periodic is True:
251
+ for i in cols:
252
+ H = contracted_nodes(H, (i, 0), (i, m))
253
+ for j in rows[:m]:
254
+ H = contracted_nodes(H, (0, j), (N, j))
255
+ elif n % 2:
256
+ # remove extra nodes
257
+ H.remove_nodes_from((N, j) for j in rows[1::2])
258
+
259
+ # Add position node attributes
260
+ if with_positions:
261
+ ii = (i for i in cols for j in rows)
262
+ jj = (j for i in cols for j in rows)
263
+ xx = (0.5 * (j % 2) + i for i in cols for j in rows)
264
+ h = sqrt(3) / 2
265
+ if periodic:
266
+ yy = (h * j + 0.01 * i * i for i in cols for j in rows)
267
+ else:
268
+ yy = (h * j for i in cols for j in rows)
269
+ pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H}
270
+ set_node_attributes(H, pos, "pos")
271
+ return H
272
+
273
+
274
+ @nx._dispatchable(graphs=None, returns_graph=True)
275
+ def hexagonal_lattice_graph(
276
+ m, n, periodic=False, with_positions=True, create_using=None
277
+ ):
278
+ """Returns an `m` by `n` hexagonal lattice graph.
279
+
280
+ The *hexagonal lattice graph* is a graph whose nodes and edges are
281
+ the `hexagonal tiling`_ of the plane.
282
+
283
+ The returned graph will have `m` rows and `n` columns of hexagons.
284
+ `Odd numbered columns`_ are shifted up relative to even numbered columns.
285
+
286
+ Positions of nodes are computed by default or `with_positions is True`.
287
+ Node positions creating the standard embedding in the plane
288
+ with sidelength 1 and are stored in the node attribute 'pos'.
289
+ `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing.
290
+
291
+ .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling
292
+ .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
293
+
294
+ Parameters
295
+ ----------
296
+ m : int
297
+ The number of rows of hexagons in the lattice.
298
+
299
+ n : int
300
+ The number of columns of hexagons in the lattice.
301
+
302
+ periodic : bool
303
+ Whether to make a periodic grid by joining the boundary vertices.
304
+ For this to work `n` must be even and both `n > 1` and `m > 1`.
305
+ The periodic connections create another row and column of hexagons
306
+ so these graphs have fewer nodes as boundary nodes are identified.
307
+
308
+ with_positions : bool (default: True)
309
+ Store the coordinates of each node in the graph node attribute 'pos'.
310
+ The coordinates provide a lattice with vertical columns of hexagons
311
+ offset to interleave and cover the plane.
312
+ Periodic positions shift the nodes vertically in a nonlinear way so
313
+ the edges don't overlap so much.
314
+
315
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
316
+ Graph type to create. If graph instance, then cleared before populated.
317
+ If graph is directed, edges will point up or right.
318
+
319
+ Returns
320
+ -------
321
+ NetworkX graph
322
+ The *m* by *n* hexagonal lattice graph.
323
+ """
324
+ G = empty_graph(0, create_using)
325
+ if m == 0 or n == 0:
326
+ return G
327
+ if periodic and (n % 2 == 1 or m < 2 or n < 2):
328
+ msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n"
329
+ raise NetworkXError(msg)
330
+
331
+ M = 2 * m # twice as many nodes as hexagons vertically
332
+ rows = range(M + 2)
333
+ cols = range(n + 1)
334
+ # make lattice
335
+ col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[: M + 1])
336
+ row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows if i % 2 == j % 2)
337
+ G.add_edges_from(col_edges)
338
+ G.add_edges_from(row_edges)
339
+ # Remove corner nodes with one edge
340
+ G.remove_node((0, M + 1))
341
+ G.remove_node((n, (M + 1) * (n % 2)))
342
+
343
+ # identify boundary nodes if periodic
344
+ from networkx.algorithms.minors import contracted_nodes
345
+
346
+ if periodic:
347
+ for i in cols[:n]:
348
+ G = contracted_nodes(G, (i, 0), (i, M))
349
+ for i in cols[1:]:
350
+ G = contracted_nodes(G, (i, 1), (i, M + 1))
351
+ for j in rows[1:M]:
352
+ G = contracted_nodes(G, (0, j), (n, j))
353
+ G.remove_node((n, M))
354
+
355
+ # calc position in embedded space
356
+ ii = (i for i in cols for j in rows)
357
+ jj = (j for i in cols for j in rows)
358
+ xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - 0.5) for i in cols for j in rows)
359
+ h = sqrt(3) / 2
360
+ if periodic:
361
+ yy = (h * j + 0.01 * i * i for i in cols for j in rows)
362
+ else:
363
+ yy = (h * j for i in cols for j in rows)
364
+ # exclude nodes not in G
365
+ pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G}
366
+ set_node_attributes(G, pos, "pos")
367
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/line.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating line graphs."""
2
+ from collections import defaultdict
3
+ from functools import partial
4
+ from itertools import combinations
5
+
6
+ import networkx as nx
7
+ from networkx.utils import arbitrary_element
8
+ from networkx.utils.decorators import not_implemented_for
9
+
10
+ __all__ = ["line_graph", "inverse_line_graph"]
11
+
12
+
13
+ @nx._dispatchable(returns_graph=True)
14
+ def line_graph(G, create_using=None):
15
+ r"""Returns the line graph of the graph or digraph `G`.
16
+
17
+ The line graph of a graph `G` has a node for each edge in `G` and an
18
+ edge joining those nodes if the two edges in `G` share a common node. For
19
+ directed graphs, nodes are adjacent exactly when the edges they represent
20
+ form a directed path of length two.
21
+
22
+ The nodes of the line graph are 2-tuples of nodes in the original graph (or
23
+ 3-tuples for multigraphs, with the key of the edge as the third element).
24
+
25
+ For information about self-loops and more discussion, see the **Notes**
26
+ section below.
27
+
28
+ Parameters
29
+ ----------
30
+ G : graph
31
+ A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
32
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
33
+ Graph type to create. If graph instance, then cleared before populated.
34
+
35
+ Returns
36
+ -------
37
+ L : graph
38
+ The line graph of G.
39
+
40
+ Examples
41
+ --------
42
+ >>> G = nx.star_graph(3)
43
+ >>> L = nx.line_graph(G)
44
+ >>> print(sorted(map(sorted, L.edges()))) # makes a 3-clique, K3
45
+ [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
46
+
47
+ Edge attributes from `G` are not copied over as node attributes in `L`, but
48
+ attributes can be copied manually:
49
+
50
+ >>> G = nx.path_graph(4)
51
+ >>> G.add_edges_from((u, v, {"tot": u + v}) for u, v in G.edges)
52
+ >>> G.edges(data=True)
53
+ EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
54
+ >>> H = nx.line_graph(G)
55
+ >>> H.add_nodes_from((node, G.edges[node]) for node in H)
56
+ >>> H.nodes(data=True)
57
+ NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
58
+
59
+ Notes
60
+ -----
61
+ Graph, node, and edge data are not propagated to the new graph. For
62
+ undirected graphs, the nodes in G must be sortable, otherwise the
63
+ constructed line graph may not be correct.
64
+
65
+ *Self-loops in undirected graphs*
66
+
67
+ For an undirected graph `G` without multiple edges, each edge can be
68
+ written as a set `\{u, v\}`. Its line graph `L` has the edges of `G` as
69
+ its nodes. If `x` and `y` are two nodes in `L`, then `\{x, y\}` is an edge
70
+ in `L` if and only if the intersection of `x` and `y` is nonempty. Thus,
71
+ the set of all edges is determined by the set of all pairwise intersections
72
+ of edges in `G`.
73
+
74
+ Trivially, every edge in G would have a nonzero intersection with itself,
75
+ and so every node in `L` should have a self-loop. This is not so
76
+ interesting, and the original context of line graphs was with simple
77
+ graphs, which had no self-loops or multiple edges. The line graph was also
78
+ meant to be a simple graph and thus, self-loops in `L` are not part of the
79
+ standard definition of a line graph. In a pairwise intersection matrix,
80
+ this is analogous to excluding the diagonal entries from the line graph
81
+ definition.
82
+
83
+ Self-loops and multiple edges in `G` add nodes to `L` in a natural way, and
84
+ do not require any fundamental changes to the definition. It might be
85
+ argued that the self-loops we excluded before should now be included.
86
+ However, the self-loops are still "trivial" in some sense and thus, are
87
+ usually excluded.
88
+
89
+ *Self-loops in directed graphs*
90
+
91
+ For a directed graph `G` without multiple edges, each edge can be written
92
+ as a tuple `(u, v)`. Its line graph `L` has the edges of `G` as its
93
+ nodes. If `x` and `y` are two nodes in `L`, then `(x, y)` is an edge in `L`
94
+ if and only if the tail of `x` matches the head of `y`, for example, if `x
95
+ = (a, b)` and `y = (b, c)` for some vertices `a`, `b`, and `c` in `G`.
96
+
97
+ Due to the directed nature of the edges, it is no longer the case that
98
+ every edge in `G` should have a self-loop in `L`. Now, the only time
99
+ self-loops arise is if a node in `G` itself has a self-loop. So such
100
+ self-loops are no longer "trivial" but instead, represent essential
101
+ features of the topology of `G`. For this reason, the historical
102
+ development of line digraphs is such that self-loops are included. When the
103
+ graph `G` has multiple edges, once again only superficial changes are
104
+ required to the definition.
105
+
106
+ References
107
+ ----------
108
+ * Harary, Frank, and Norman, Robert Z., "Some properties of line digraphs",
109
+ Rend. Circ. Mat. Palermo, II. Ser. 9 (1960), 161--168.
110
+ * Hemminger, R. L.; Beineke, L. W. (1978), "Line graphs and line digraphs",
111
+ in Beineke, L. W.; Wilson, R. J., Selected Topics in Graph Theory,
112
+ Academic Press Inc., pp. 271--305.
113
+
114
+ """
115
+ if G.is_directed():
116
+ L = _lg_directed(G, create_using=create_using)
117
+ else:
118
+ L = _lg_undirected(G, selfloops=False, create_using=create_using)
119
+ return L
120
+
121
+
122
+ def _lg_directed(G, create_using=None):
123
+ """Returns the line graph L of the (multi)digraph G.
124
+
125
+ Edges in G appear as nodes in L, represented as tuples of the form (u,v)
126
+ or (u,v,key) if G is a multidigraph. A node in L corresponding to the edge
127
+ (u,v) is connected to every node corresponding to an edge (v,w).
128
+
129
+ Parameters
130
+ ----------
131
+ G : digraph
132
+ A directed graph or directed multigraph.
133
+ create_using : NetworkX graph constructor, optional
134
+ Graph type to create. If graph instance, then cleared before populated.
135
+ Default is to use the same graph class as `G`.
136
+
137
+ """
138
+ L = nx.empty_graph(0, create_using, default=G.__class__)
139
+
140
+ # Create a graph specific edge function.
141
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
142
+
143
+ for from_node in get_edges():
144
+ # from_node is: (u,v) or (u,v,key)
145
+ L.add_node(from_node)
146
+ for to_node in get_edges(from_node[1]):
147
+ L.add_edge(from_node, to_node)
148
+
149
+ return L
150
+
151
+
152
+ def _lg_undirected(G, selfloops=False, create_using=None):
153
+ """Returns the line graph L of the (multi)graph G.
154
+
155
+ Edges in G appear as nodes in L, represented as sorted tuples of the form
156
+ (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
157
+ the edge {u,v} is connected to every node corresponding to an edge that
158
+ involves u or v.
159
+
160
+ Parameters
161
+ ----------
162
+ G : graph
163
+ An undirected graph or multigraph.
164
+ selfloops : bool
165
+ If `True`, then self-loops are included in the line graph. If `False`,
166
+ they are excluded.
167
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
168
+ Graph type to create. If graph instance, then cleared before populated.
169
+
170
+ Notes
171
+ -----
172
+ The standard algorithm for line graphs of undirected graphs does not
173
+ produce self-loops.
174
+
175
+ """
176
+ L = nx.empty_graph(0, create_using, default=G.__class__)
177
+
178
+ # Graph specific functions for edges.
179
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
180
+
181
+ # Determine if we include self-loops or not.
182
+ shift = 0 if selfloops else 1
183
+
184
+ # Introduce numbering of nodes
185
+ node_index = {n: i for i, n in enumerate(G)}
186
+
187
+ # Lift canonical representation of nodes to edges in line graph
188
+ edge_key_function = lambda edge: (node_index[edge[0]], node_index[edge[1]])
189
+
190
+ edges = set()
191
+ for u in G:
192
+ # Label nodes as a sorted tuple of nodes in original graph.
193
+ # Decide on representation of {u, v} as (u, v) or (v, u) depending on node_index.
194
+ # -> This ensures a canonical representation and avoids comparing values of different types.
195
+ nodes = [tuple(sorted(x[:2], key=node_index.get)) + x[2:] for x in get_edges(u)]
196
+
197
+ if len(nodes) == 1:
198
+ # Then the edge will be an isolated node in L.
199
+ L.add_node(nodes[0])
200
+
201
+ # Add a clique of `nodes` to graph. To prevent double adding edges,
202
+ # especially important for multigraphs, we store the edges in
203
+ # canonical form in a set.
204
+ for i, a in enumerate(nodes):
205
+ edges.update(
206
+ [
207
+ tuple(sorted((a, b), key=edge_key_function))
208
+ for b in nodes[i + shift :]
209
+ ]
210
+ )
211
+
212
+ L.add_edges_from(edges)
213
+ return L
214
+
215
+
216
+ @not_implemented_for("directed")
217
+ @not_implemented_for("multigraph")
218
+ @nx._dispatchable(returns_graph=True)
219
+ def inverse_line_graph(G):
220
+ """Returns the inverse line graph of graph G.
221
+
222
+ If H is a graph, and G is the line graph of H, such that G = L(H).
223
+ Then H is the inverse line graph of G.
224
+
225
+ Not all graphs are line graphs and these do not have an inverse line graph.
226
+ In these cases this function raises a NetworkXError.
227
+
228
+ Parameters
229
+ ----------
230
+ G : graph
231
+ A NetworkX Graph
232
+
233
+ Returns
234
+ -------
235
+ H : graph
236
+ The inverse line graph of G.
237
+
238
+ Raises
239
+ ------
240
+ NetworkXNotImplemented
241
+ If G is directed or a multigraph
242
+
243
+ NetworkXError
244
+ If G is not a line graph
245
+
246
+ Notes
247
+ -----
248
+ This is an implementation of the Roussopoulos algorithm[1]_.
249
+
250
+ If G consists of multiple components, then the algorithm doesn't work.
251
+ You should invert every component separately:
252
+
253
+ >>> K5 = nx.complete_graph(5)
254
+ >>> P4 = nx.Graph([("a", "b"), ("b", "c"), ("c", "d")])
255
+ >>> G = nx.union(K5, P4)
256
+ >>> root_graphs = []
257
+ >>> for comp in nx.connected_components(G):
258
+ ... root_graphs.append(nx.inverse_line_graph(G.subgraph(comp)))
259
+ >>> len(root_graphs)
260
+ 2
261
+
262
+ References
263
+ ----------
264
+ .. [1] Roussopoulos, N.D. , "A max {m, n} algorithm for determining the graph H from
265
+ its line graph G", Information Processing Letters 2, (1973), 108--112, ISSN 0020-0190,
266
+ `DOI link <https://doi.org/10.1016/0020-0190(73)90029-X>`_
267
+
268
+ """
269
+ if G.number_of_nodes() == 0:
270
+ return nx.empty_graph(1)
271
+ elif G.number_of_nodes() == 1:
272
+ v = arbitrary_element(G)
273
+ a = (v, 0)
274
+ b = (v, 1)
275
+ H = nx.Graph([(a, b)])
276
+ return H
277
+ elif G.number_of_nodes() > 1 and G.number_of_edges() == 0:
278
+ msg = (
279
+ "inverse_line_graph() doesn't work on an edgeless graph. "
280
+ "Please use this function on each component separately."
281
+ )
282
+ raise nx.NetworkXError(msg)
283
+
284
+ if nx.number_of_selfloops(G) != 0:
285
+ msg = (
286
+ "A line graph as generated by NetworkX has no selfloops, so G has no "
287
+ "inverse line graph. Please remove the selfloops from G and try again."
288
+ )
289
+ raise nx.NetworkXError(msg)
290
+
291
+ starting_cell = _select_starting_cell(G)
292
+ P = _find_partition(G, starting_cell)
293
+ # count how many times each vertex appears in the partition set
294
+ P_count = {u: 0 for u in G.nodes}
295
+ for p in P:
296
+ for u in p:
297
+ P_count[u] += 1
298
+
299
+ if max(P_count.values()) > 2:
300
+ msg = "G is not a line graph (vertex found in more than two partition cells)"
301
+ raise nx.NetworkXError(msg)
302
+ W = tuple((u,) for u in P_count if P_count[u] == 1)
303
+ H = nx.Graph()
304
+ H.add_nodes_from(P)
305
+ H.add_nodes_from(W)
306
+ for a, b in combinations(H.nodes, 2):
307
+ if any(a_bit in b for a_bit in a):
308
+ H.add_edge(a, b)
309
+ return H
310
+
311
+
312
+ def _triangles(G, e):
313
+ """Return list of all triangles containing edge e"""
314
+ u, v = e
315
+ if u not in G:
316
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
317
+ if v not in G[u]:
318
+ raise nx.NetworkXError(f"Edge ({u}, {v}) not in graph")
319
+ triangle_list = []
320
+ for x in G[u]:
321
+ if x in G[v]:
322
+ triangle_list.append((u, v, x))
323
+ return triangle_list
324
+
325
+
326
+ def _odd_triangle(G, T):
327
+ """Test whether T is an odd triangle in G
328
+
329
+ Parameters
330
+ ----------
331
+ G : NetworkX Graph
332
+ T : 3-tuple of vertices forming triangle in G
333
+
334
+ Returns
335
+ -------
336
+ True is T is an odd triangle
337
+ False otherwise
338
+
339
+ Raises
340
+ ------
341
+ NetworkXError
342
+ T is not a triangle in G
343
+
344
+ Notes
345
+ -----
346
+ An odd triangle is one in which there exists another vertex in G which is
347
+ adjacent to either exactly one or exactly all three of the vertices in the
348
+ triangle.
349
+
350
+ """
351
+ for u in T:
352
+ if u not in G.nodes():
353
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
354
+ for e in list(combinations(T, 2)):
355
+ if e[0] not in G[e[1]]:
356
+ raise nx.NetworkXError(f"Edge ({e[0]}, {e[1]}) not in graph")
357
+
358
+ T_nbrs = defaultdict(int)
359
+ for t in T:
360
+ for v in G[t]:
361
+ if v not in T:
362
+ T_nbrs[v] += 1
363
+ return any(T_nbrs[v] in [1, 3] for v in T_nbrs)
364
+
365
+
366
+ def _find_partition(G, starting_cell):
367
+ """Find a partition of the vertices of G into cells of complete graphs
368
+
369
+ Parameters
370
+ ----------
371
+ G : NetworkX Graph
372
+ starting_cell : tuple of vertices in G which form a cell
373
+
374
+ Returns
375
+ -------
376
+ List of tuples of vertices of G
377
+
378
+ Raises
379
+ ------
380
+ NetworkXError
381
+ If a cell is not a complete subgraph then G is not a line graph
382
+ """
383
+ G_partition = G.copy()
384
+ P = [starting_cell] # partition set
385
+ G_partition.remove_edges_from(list(combinations(starting_cell, 2)))
386
+ # keep list of partitioned nodes which might have an edge in G_partition
387
+ partitioned_vertices = list(starting_cell)
388
+ while G_partition.number_of_edges() > 0:
389
+ # there are still edges left and so more cells to be made
390
+ u = partitioned_vertices.pop()
391
+ deg_u = len(G_partition[u])
392
+ if deg_u != 0:
393
+ # if u still has edges then we need to find its other cell
394
+ # this other cell must be a complete subgraph or else G is
395
+ # not a line graph
396
+ new_cell = [u] + list(G_partition[u])
397
+ for u in new_cell:
398
+ for v in new_cell:
399
+ if (u != v) and (v not in G_partition[u]):
400
+ msg = (
401
+ "G is not a line graph "
402
+ "(partition cell not a complete subgraph)"
403
+ )
404
+ raise nx.NetworkXError(msg)
405
+ P.append(tuple(new_cell))
406
+ G_partition.remove_edges_from(list(combinations(new_cell, 2)))
407
+ partitioned_vertices += new_cell
408
+ return P
409
+
410
+
411
+ def _select_starting_cell(G, starting_edge=None):
412
+ """Select a cell to initiate _find_partition
413
+
414
+ Parameters
415
+ ----------
416
+ G : NetworkX Graph
417
+ starting_edge: an edge to build the starting cell from
418
+
419
+ Returns
420
+ -------
421
+ Tuple of vertices in G
422
+
423
+ Raises
424
+ ------
425
+ NetworkXError
426
+ If it is determined that G is not a line graph
427
+
428
+ Notes
429
+ -----
430
+ If starting edge not specified then pick an arbitrary edge - doesn't
431
+ matter which. However, this function may call itself requiring a
432
+ specific starting edge. Note that the r, s notation for counting
433
+ triangles is the same as in the Roussopoulos paper cited above.
434
+ """
435
+ if starting_edge is None:
436
+ e = arbitrary_element(G.edges())
437
+ else:
438
+ e = starting_edge
439
+ if e[0] not in G.nodes():
440
+ raise nx.NetworkXError(f"Vertex {e[0]} not in graph")
441
+ if e[1] not in G[e[0]]:
442
+ msg = f"starting_edge ({e[0]}, {e[1]}) is not in the Graph"
443
+ raise nx.NetworkXError(msg)
444
+ e_triangles = _triangles(G, e)
445
+ r = len(e_triangles)
446
+ if r == 0:
447
+ # there are no triangles containing e, so the starting cell is just e
448
+ starting_cell = e
449
+ elif r == 1:
450
+ # there is exactly one triangle, T, containing e. If other 2 edges
451
+ # of T belong only to this triangle then T is starting cell
452
+ T = e_triangles[0]
453
+ a, b, c = T
454
+ # ab was original edge so check the other 2 edges
455
+ ac_edges = len(_triangles(G, (a, c)))
456
+ bc_edges = len(_triangles(G, (b, c)))
457
+ if ac_edges == 1:
458
+ if bc_edges == 1:
459
+ starting_cell = T
460
+ else:
461
+ return _select_starting_cell(G, starting_edge=(b, c))
462
+ else:
463
+ return _select_starting_cell(G, starting_edge=(a, c))
464
+ else:
465
+ # r >= 2 so we need to count the number of odd triangles, s
466
+ s = 0
467
+ odd_triangles = []
468
+ for T in e_triangles:
469
+ if _odd_triangle(G, T):
470
+ s += 1
471
+ odd_triangles.append(T)
472
+ if r == 2 and s == 0:
473
+ # in this case either triangle works, so just use T
474
+ starting_cell = T
475
+ elif r - 1 <= s <= r:
476
+ # check if odd triangles containing e form complete subgraph
477
+ triangle_nodes = set()
478
+ for T in odd_triangles:
479
+ for x in T:
480
+ triangle_nodes.add(x)
481
+
482
+ for u in triangle_nodes:
483
+ for v in triangle_nodes:
484
+ if u != v and (v not in G[u]):
485
+ msg = (
486
+ "G is not a line graph (odd triangles "
487
+ "do not form complete subgraph)"
488
+ )
489
+ raise nx.NetworkXError(msg)
490
+ # otherwise then we can use this as the starting cell
491
+ starting_cell = tuple(triangle_nodes)
492
+
493
+ else:
494
+ msg = (
495
+ "G is not a line graph (incorrect number of "
496
+ "odd triangles around starting edge)"
497
+ )
498
+ raise nx.NetworkXError(msg)
499
+ return starting_cell
env-llmeval/lib/python3.10/site-packages/networkx/generators/mycielski.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to the Mycielski Operation and the Mycielskian family
2
+ of graphs.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for
8
+
9
+ __all__ = ["mycielskian", "mycielski_graph"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ @nx._dispatchable(returns_graph=True)
15
+ def mycielskian(G, iterations=1):
16
+ r"""Returns the Mycielskian of a simple, undirected graph G
17
+
18
+ The Mycielskian of graph preserves a graph's triangle free
19
+ property while increasing the chromatic number by 1.
20
+
21
+ The Mycielski Operation on a graph, :math:`G=(V, E)`, constructs a new
22
+ graph with :math:`2|V| + 1` nodes and :math:`3|E| + |V|` edges.
23
+
24
+ The construction is as follows:
25
+
26
+ Let :math:`V = {0, ..., n-1}`. Construct another vertex set
27
+ :math:`U = {n, ..., 2n}` and a vertex, `w`.
28
+ Construct a new graph, `M`, with vertices :math:`U \bigcup V \bigcup w`.
29
+ For edges, :math:`(u, v) \in E` add edges :math:`(u, v), (u, v + n)`, and
30
+ :math:`(u + n, v)` to M. Finally, for all vertices :math:`u \in U`, add
31
+ edge :math:`(u, w)` to M.
32
+
33
+ The Mycielski Operation can be done multiple times by repeating the above
34
+ process iteratively.
35
+
36
+ More information can be found at https://en.wikipedia.org/wiki/Mycielskian
37
+
38
+ Parameters
39
+ ----------
40
+ G : graph
41
+ A simple, undirected NetworkX graph
42
+ iterations : int
43
+ The number of iterations of the Mycielski operation to
44
+ perform on G. Defaults to 1. Must be a non-negative integer.
45
+
46
+ Returns
47
+ -------
48
+ M : graph
49
+ The Mycielskian of G after the specified number of iterations.
50
+
51
+ Notes
52
+ -----
53
+ Graph, node, and edge data are not necessarily propagated to the new graph.
54
+
55
+ """
56
+
57
+ M = nx.convert_node_labels_to_integers(G)
58
+
59
+ for i in range(iterations):
60
+ n = M.number_of_nodes()
61
+ M.add_nodes_from(range(n, 2 * n))
62
+ old_edges = list(M.edges())
63
+ M.add_edges_from((u, v + n) for u, v in old_edges)
64
+ M.add_edges_from((u + n, v) for u, v in old_edges)
65
+ M.add_node(2 * n)
66
+ M.add_edges_from((u + n, 2 * n) for u in range(n))
67
+
68
+ return M
69
+
70
+
71
+ @nx._dispatchable(graphs=None, returns_graph=True)
72
+ def mycielski_graph(n):
73
+ """Generator for the n_th Mycielski Graph.
74
+
75
+ The Mycielski family of graphs is an infinite set of graphs.
76
+ :math:`M_1` is the singleton graph, :math:`M_2` is two vertices with an
77
+ edge, and, for :math:`i > 2`, :math:`M_i` is the Mycielskian of
78
+ :math:`M_{i-1}`.
79
+
80
+ More information can be found at
81
+ http://mathworld.wolfram.com/MycielskiGraph.html
82
+
83
+ Parameters
84
+ ----------
85
+ n : int
86
+ The desired Mycielski Graph.
87
+
88
+ Returns
89
+ -------
90
+ M : graph
91
+ The n_th Mycielski Graph
92
+
93
+ Notes
94
+ -----
95
+ The first graph in the Mycielski sequence is the singleton graph.
96
+ The Mycielskian of this graph is not the :math:`P_2` graph, but rather the
97
+ :math:`P_2` graph with an extra, isolated vertex. The second Mycielski
98
+ graph is the :math:`P_2` graph, so the first two are hard coded.
99
+ The remaining graphs are generated using the Mycielski operation.
100
+
101
+ """
102
+
103
+ if n < 1:
104
+ raise nx.NetworkXError("must satisfy n >= 1")
105
+
106
+ if n == 1:
107
+ return nx.empty_graph(1)
108
+
109
+ else:
110
+ return mycielskian(nx.path_graph(2), n - 2)
env-llmeval/lib/python3.10/site-packages/networkx/generators/nonisomorphic_trees.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of the Wright, Richmond, Odlyzko and McKay (WROM)
3
+ algorithm for the enumeration of all non-isomorphic free trees of a
4
+ given order. Rooted trees are represented by level sequences, i.e.,
5
+ lists in which the i-th element specifies the distance of vertex i to
6
+ the root.
7
+
8
+ """
9
+
10
+ __all__ = ["nonisomorphic_trees", "number_of_nonisomorphic_trees"]
11
+
12
+ import networkx as nx
13
+
14
+
15
+ @nx._dispatchable(graphs=None, returns_graph=True)
16
+ def nonisomorphic_trees(order, create="graph"):
17
+ """Generates lists of nonisomorphic trees
18
+
19
+ Parameters
20
+ ----------
21
+ order : int
22
+ order of the desired tree(s)
23
+
24
+ create : one of {"graph", "matrix"} (default="graph")
25
+ If ``"graph"`` is selected a list of ``Graph`` instances will be returned,
26
+ if matrix is selected a list of adjacency matrices will be returned.
27
+
28
+ .. deprecated:: 3.3
29
+
30
+ The `create` argument is deprecated and will be removed in NetworkX
31
+ version 3.5. In the future, `nonisomorphic_trees` will yield graph
32
+ instances by default. To generate adjacency matrices, call
33
+ ``nx.to_numpy_array`` on the output, e.g.::
34
+
35
+ [nx.to_numpy_array(G) for G in nx.nonisomorphic_trees(N)]
36
+
37
+ Yields
38
+ ------
39
+ list
40
+ A list of nonisomorphic trees, in one of two formats depending on the
41
+ value of the `create` parameter:
42
+ - ``create="graph"``: yields a list of `networkx.Graph` instances
43
+ - ``create="matrix"``: yields a list of list-of-lists representing adjacency matrices
44
+ """
45
+
46
+ if order < 2:
47
+ raise ValueError
48
+ # start at the path graph rooted at its center
49
+ layout = list(range(order // 2 + 1)) + list(range(1, (order + 1) // 2))
50
+
51
+ while layout is not None:
52
+ layout = _next_tree(layout)
53
+ if layout is not None:
54
+ if create == "graph":
55
+ yield _layout_to_graph(layout)
56
+ elif create == "matrix":
57
+ import warnings
58
+
59
+ warnings.warn(
60
+ (
61
+ "\n\nThe 'create=matrix' argument of nonisomorphic_trees\n"
62
+ "is deprecated and will be removed in version 3.5.\n"
63
+ "Use ``nx.to_numpy_array`` to convert graphs to adjacency "
64
+ "matrices, e.g.::\n\n"
65
+ " [nx.to_numpy_array(G) for G in nx.nonisomorphic_trees(N)]"
66
+ ),
67
+ category=DeprecationWarning,
68
+ stacklevel=2,
69
+ )
70
+
71
+ yield _layout_to_matrix(layout)
72
+ layout = _next_rooted_tree(layout)
73
+
74
+
75
+ @nx._dispatchable(graphs=None)
76
+ def number_of_nonisomorphic_trees(order):
77
+ """Returns the number of nonisomorphic trees
78
+
79
+ Parameters
80
+ ----------
81
+ order : int
82
+ order of the desired tree(s)
83
+
84
+ Returns
85
+ -------
86
+ length : Number of nonisomorphic graphs for the given order
87
+
88
+ References
89
+ ----------
90
+
91
+ """
92
+ return sum(1 for _ in nonisomorphic_trees(order))
93
+
94
+
95
+ def _next_rooted_tree(predecessor, p=None):
96
+ """One iteration of the Beyer-Hedetniemi algorithm."""
97
+
98
+ if p is None:
99
+ p = len(predecessor) - 1
100
+ while predecessor[p] == 1:
101
+ p -= 1
102
+ if p == 0:
103
+ return None
104
+
105
+ q = p - 1
106
+ while predecessor[q] != predecessor[p] - 1:
107
+ q -= 1
108
+ result = list(predecessor)
109
+ for i in range(p, len(result)):
110
+ result[i] = result[i - p + q]
111
+ return result
112
+
113
+
114
+ def _next_tree(candidate):
115
+ """One iteration of the Wright, Richmond, Odlyzko and McKay
116
+ algorithm."""
117
+
118
+ # valid representation of a free tree if:
119
+ # there are at least two vertices at layer 1
120
+ # (this is always the case because we start at the path graph)
121
+ left, rest = _split_tree(candidate)
122
+
123
+ # and the left subtree of the root
124
+ # is less high than the tree with the left subtree removed
125
+ left_height = max(left)
126
+ rest_height = max(rest)
127
+ valid = rest_height >= left_height
128
+
129
+ if valid and rest_height == left_height:
130
+ # and, if left and rest are of the same height,
131
+ # if left does not encompass more vertices
132
+ if len(left) > len(rest):
133
+ valid = False
134
+ # and, if they have the same number or vertices,
135
+ # if left does not come after rest lexicographically
136
+ elif len(left) == len(rest) and left > rest:
137
+ valid = False
138
+
139
+ if valid:
140
+ return candidate
141
+ else:
142
+ # jump to the next valid free tree
143
+ p = len(left)
144
+ new_candidate = _next_rooted_tree(candidate, p)
145
+ if candidate[p] > 2:
146
+ new_left, new_rest = _split_tree(new_candidate)
147
+ new_left_height = max(new_left)
148
+ suffix = range(1, new_left_height + 2)
149
+ new_candidate[-len(suffix) :] = suffix
150
+ return new_candidate
151
+
152
+
153
+ def _split_tree(layout):
154
+ """Returns a tuple of two layouts, one containing the left
155
+ subtree of the root vertex, and one containing the original tree
156
+ with the left subtree removed."""
157
+
158
+ one_found = False
159
+ m = None
160
+ for i in range(len(layout)):
161
+ if layout[i] == 1:
162
+ if one_found:
163
+ m = i
164
+ break
165
+ else:
166
+ one_found = True
167
+
168
+ if m is None:
169
+ m = len(layout)
170
+
171
+ left = [layout[i] - 1 for i in range(1, m)]
172
+ rest = [0] + [layout[i] for i in range(m, len(layout))]
173
+ return (left, rest)
174
+
175
+
176
+ def _layout_to_matrix(layout):
177
+ """Create the adjacency matrix for the tree specified by the
178
+ given layout (level sequence)."""
179
+
180
+ result = [[0] * len(layout) for i in range(len(layout))]
181
+ stack = []
182
+ for i in range(len(layout)):
183
+ i_level = layout[i]
184
+ if stack:
185
+ j = stack[-1]
186
+ j_level = layout[j]
187
+ while j_level >= i_level:
188
+ stack.pop()
189
+ j = stack[-1]
190
+ j_level = layout[j]
191
+ result[i][j] = result[j][i] = 1
192
+ stack.append(i)
193
+ return result
194
+
195
+
196
+ def _layout_to_graph(layout):
197
+ """Create a NetworkX Graph for the tree specified by the
198
+ given layout(level sequence)"""
199
+ G = nx.Graph()
200
+ stack = []
201
+ for i in range(len(layout)):
202
+ i_level = layout[i]
203
+ if stack:
204
+ j = stack[-1]
205
+ j_level = layout[j]
206
+ while j_level >= i_level:
207
+ stack.pop()
208
+ j = stack[-1]
209
+ j_level = layout[j]
210
+ G.add_edge(i, j)
211
+ stack.append(i)
212
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/random_clustered.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with given degree and triangle sequence.
2
+ """
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = ["random_clustered_graph"]
7
+
8
+
9
+ @py_random_state(2)
10
+ @nx._dispatchable(graphs=None, returns_graph=True)
11
+ def random_clustered_graph(joint_degree_sequence, create_using=None, seed=None):
12
+ r"""Generate a random graph with the given joint independent edge degree and
13
+ triangle degree sequence.
14
+
15
+ This uses a configuration model-like approach to generate a random graph
16
+ (with parallel edges and self-loops) by randomly assigning edges to match
17
+ the given joint degree sequence.
18
+
19
+ The joint degree sequence is a list of pairs of integers of the form
20
+ $[(d_{1,i}, d_{1,t}), \dotsc, (d_{n,i}, d_{n,t})]$. According to this list,
21
+ vertex $u$ is a member of $d_{u,t}$ triangles and has $d_{u, i}$ other
22
+ edges. The number $d_{u,t}$ is the *triangle degree* of $u$ and the number
23
+ $d_{u,i}$ is the *independent edge degree*.
24
+
25
+ Parameters
26
+ ----------
27
+ joint_degree_sequence : list of integer pairs
28
+ Each list entry corresponds to the independent edge degree and
29
+ triangle degree of a node.
30
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
31
+ Graph type to create. If graph instance, then cleared before populated.
32
+ seed : integer, random_state, or None (default)
33
+ Indicator of random number generation state.
34
+ See :ref:`Randomness<randomness>`.
35
+
36
+ Returns
37
+ -------
38
+ G : MultiGraph
39
+ A graph with the specified degree sequence. Nodes are labeled
40
+ starting at 0 with an index corresponding to the position in
41
+ deg_sequence.
42
+
43
+ Raises
44
+ ------
45
+ NetworkXError
46
+ If the independent edge degree sequence sum is not even
47
+ or the triangle degree sequence sum is not divisible by 3.
48
+
49
+ Notes
50
+ -----
51
+ As described by Miller [1]_ (see also Newman [2]_ for an equivalent
52
+ description).
53
+
54
+ A non-graphical degree sequence (not realizable by some simple
55
+ graph) is allowed since this function returns graphs with self
56
+ loops and parallel edges. An exception is raised if the
57
+ independent degree sequence does not have an even sum or the
58
+ triangle degree sequence sum is not divisible by 3.
59
+
60
+ This configuration model-like construction process can lead to
61
+ duplicate edges and loops. You can remove the self-loops and
62
+ parallel edges (see below) which will likely result in a graph
63
+ that doesn't have the exact degree sequence specified. This
64
+ "finite-size effect" decreases as the size of the graph increases.
65
+
66
+ References
67
+ ----------
68
+ .. [1] Joel C. Miller. "Percolation and epidemics in random clustered
69
+ networks". In: Physical review. E, Statistical, nonlinear, and soft
70
+ matter physics 80 (2 Part 1 August 2009).
71
+ .. [2] M. E. J. Newman. "Random Graphs with Clustering".
72
+ In: Physical Review Letters 103 (5 July 2009)
73
+
74
+ Examples
75
+ --------
76
+ >>> deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)]
77
+ >>> G = nx.random_clustered_graph(deg)
78
+
79
+ To remove parallel edges:
80
+
81
+ >>> G = nx.Graph(G)
82
+
83
+ To remove self loops:
84
+
85
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
86
+
87
+ """
88
+ # In Python 3, zip() returns an iterator. Make this into a list.
89
+ joint_degree_sequence = list(joint_degree_sequence)
90
+
91
+ N = len(joint_degree_sequence)
92
+ G = nx.empty_graph(N, create_using, default=nx.MultiGraph)
93
+ if G.is_directed():
94
+ raise nx.NetworkXError("Directed Graph not supported")
95
+
96
+ ilist = []
97
+ tlist = []
98
+ for n in G:
99
+ degrees = joint_degree_sequence[n]
100
+ for icount in range(degrees[0]):
101
+ ilist.append(n)
102
+ for tcount in range(degrees[1]):
103
+ tlist.append(n)
104
+
105
+ if len(ilist) % 2 != 0 or len(tlist) % 3 != 0:
106
+ raise nx.NetworkXError("Invalid degree sequence")
107
+
108
+ seed.shuffle(ilist)
109
+ seed.shuffle(tlist)
110
+ while ilist:
111
+ G.add_edge(ilist.pop(), ilist.pop())
112
+ while tlist:
113
+ n1 = tlist.pop()
114
+ n2 = tlist.pop()
115
+ n3 = tlist.pop()
116
+ G.add_edges_from([(n1, n2), (n1, n3), (n2, n3)])
117
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/random_graphs.py ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .classic import complete_graph, empty_graph, path_graph, star_graph
14
+ from .degree_seq import degree_sequence_tree
15
+
16
+ __all__ = [
17
+ "fast_gnp_random_graph",
18
+ "gnp_random_graph",
19
+ "dense_gnm_random_graph",
20
+ "gnm_random_graph",
21
+ "erdos_renyi_graph",
22
+ "binomial_graph",
23
+ "newman_watts_strogatz_graph",
24
+ "watts_strogatz_graph",
25
+ "connected_watts_strogatz_graph",
26
+ "random_regular_graph",
27
+ "barabasi_albert_graph",
28
+ "dual_barabasi_albert_graph",
29
+ "extended_barabasi_albert_graph",
30
+ "powerlaw_cluster_graph",
31
+ "random_lobster",
32
+ "random_shell_graph",
33
+ "random_powerlaw_tree",
34
+ "random_powerlaw_tree_sequence",
35
+ "random_kernel_graph",
36
+ ]
37
+
38
+
39
+ @py_random_state(2)
40
+ @nx._dispatchable(graphs=None, returns_graph=True)
41
+ def fast_gnp_random_graph(n, p, seed=None, directed=False):
42
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
43
+ a binomial graph.
44
+
45
+ Parameters
46
+ ----------
47
+ n : int
48
+ The number of nodes.
49
+ p : float
50
+ Probability for edge creation.
51
+ seed : integer, random_state, or None (default)
52
+ Indicator of random number generation state.
53
+ See :ref:`Randomness<randomness>`.
54
+ directed : bool, optional (default=False)
55
+ If True, this function returns a directed graph.
56
+
57
+ Notes
58
+ -----
59
+ The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
60
+ (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
61
+
62
+ This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
63
+ edges, which equals $p n (n - 1) / 2$. This should be faster than
64
+ :func:`gnp_random_graph` when $p$ is small and the expected number of edges
65
+ is small (that is, the graph is sparse).
66
+
67
+ See Also
68
+ --------
69
+ gnp_random_graph
70
+
71
+ References
72
+ ----------
73
+ .. [1] Vladimir Batagelj and Ulrik Brandes,
74
+ "Efficient generation of large random networks",
75
+ Phys. Rev. E, 71, 036113, 2005.
76
+ """
77
+ G = empty_graph(n)
78
+
79
+ if p <= 0 or p >= 1:
80
+ return nx.gnp_random_graph(n, p, seed=seed, directed=directed)
81
+
82
+ lp = math.log(1.0 - p)
83
+
84
+ if directed:
85
+ G = nx.DiGraph(G)
86
+ v = 1
87
+ w = -1
88
+ while v < n:
89
+ lr = math.log(1.0 - seed.random())
90
+ w = w + 1 + int(lr / lp)
91
+ while w >= v and v < n:
92
+ w = w - v
93
+ v = v + 1
94
+ if v < n:
95
+ G.add_edge(w, v)
96
+
97
+ # Nodes in graph are from 0,n-1 (start with v as the second node index).
98
+ v = 1
99
+ w = -1
100
+ while v < n:
101
+ lr = math.log(1.0 - seed.random())
102
+ w = w + 1 + int(lr / lp)
103
+ while w >= v and v < n:
104
+ w = w - v
105
+ v = v + 1
106
+ if v < n:
107
+ G.add_edge(v, w)
108
+ return G
109
+
110
+
111
+ @py_random_state(2)
112
+ @nx._dispatchable(graphs=None, returns_graph=True)
113
+ def gnp_random_graph(n, p, seed=None, directed=False):
114
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
115
+ or a binomial graph.
116
+
117
+ The $G_{n,p}$ model chooses each of the possible edges with probability $p$.
118
+
119
+ Parameters
120
+ ----------
121
+ n : int
122
+ The number of nodes.
123
+ p : float
124
+ Probability for edge creation.
125
+ seed : integer, random_state, or None (default)
126
+ Indicator of random number generation state.
127
+ See :ref:`Randomness<randomness>`.
128
+ directed : bool, optional (default=False)
129
+ If True, this function returns a directed graph.
130
+
131
+ See Also
132
+ --------
133
+ fast_gnp_random_graph
134
+
135
+ Notes
136
+ -----
137
+ This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for
138
+ small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm.
139
+
140
+ :func:`binomial_graph` and :func:`erdos_renyi_graph` are
141
+ aliases for :func:`gnp_random_graph`.
142
+
143
+ >>> nx.binomial_graph is nx.gnp_random_graph
144
+ True
145
+ >>> nx.erdos_renyi_graph is nx.gnp_random_graph
146
+ True
147
+
148
+ References
149
+ ----------
150
+ .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
151
+ .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
152
+ """
153
+ if directed:
154
+ edges = itertools.permutations(range(n), 2)
155
+ G = nx.DiGraph()
156
+ else:
157
+ edges = itertools.combinations(range(n), 2)
158
+ G = nx.Graph()
159
+ G.add_nodes_from(range(n))
160
+ if p <= 0:
161
+ return G
162
+ if p >= 1:
163
+ return complete_graph(n, create_using=G)
164
+
165
+ for e in edges:
166
+ if seed.random() < p:
167
+ G.add_edge(*e)
168
+ return G
169
+
170
+
171
+ # add some aliases to common names
172
+ binomial_graph = gnp_random_graph
173
+ erdos_renyi_graph = gnp_random_graph
174
+
175
+
176
+ @py_random_state(2)
177
+ @nx._dispatchable(graphs=None, returns_graph=True)
178
+ def dense_gnm_random_graph(n, m, seed=None):
179
+ """Returns a $G_{n,m}$ random graph.
180
+
181
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
182
+ of all graphs with $n$ nodes and $m$ edges.
183
+
184
+ This algorithm should be faster than :func:`gnm_random_graph` for dense
185
+ graphs.
186
+
187
+ Parameters
188
+ ----------
189
+ n : int
190
+ The number of nodes.
191
+ m : int
192
+ The number of edges.
193
+ seed : integer, random_state, or None (default)
194
+ Indicator of random number generation state.
195
+ See :ref:`Randomness<randomness>`.
196
+
197
+ See Also
198
+ --------
199
+ gnm_random_graph
200
+
201
+ Notes
202
+ -----
203
+ Algorithm by Keith M. Briggs Mar 31, 2006.
204
+ Inspired by Knuth's Algorithm S (Selection sampling technique),
205
+ in section 3.4.2 of [1]_.
206
+
207
+ References
208
+ ----------
209
+ .. [1] Donald E. Knuth, The Art of Computer Programming,
210
+ Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
211
+ """
212
+ mmax = n * (n - 1) // 2
213
+ if m >= mmax:
214
+ G = complete_graph(n)
215
+ else:
216
+ G = empty_graph(n)
217
+
218
+ if n == 1 or m >= mmax:
219
+ return G
220
+
221
+ u = 0
222
+ v = 1
223
+ t = 0
224
+ k = 0
225
+ while True:
226
+ if seed.randrange(mmax - t) < m - k:
227
+ G.add_edge(u, v)
228
+ k += 1
229
+ if k == m:
230
+ return G
231
+ t += 1
232
+ v += 1
233
+ if v == n: # go to next row of adjacency matrix
234
+ u += 1
235
+ v = u + 1
236
+
237
+
238
+ @py_random_state(2)
239
+ @nx._dispatchable(graphs=None, returns_graph=True)
240
+ def gnm_random_graph(n, m, seed=None, directed=False):
241
+ """Returns a $G_{n,m}$ random graph.
242
+
243
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
244
+ of all graphs with $n$ nodes and $m$ edges.
245
+
246
+ This algorithm should be faster than :func:`dense_gnm_random_graph` for
247
+ sparse graphs.
248
+
249
+ Parameters
250
+ ----------
251
+ n : int
252
+ The number of nodes.
253
+ m : int
254
+ The number of edges.
255
+ seed : integer, random_state, or None (default)
256
+ Indicator of random number generation state.
257
+ See :ref:`Randomness<randomness>`.
258
+ directed : bool, optional (default=False)
259
+ If True return a directed graph
260
+
261
+ See also
262
+ --------
263
+ dense_gnm_random_graph
264
+
265
+ """
266
+ if directed:
267
+ G = nx.DiGraph()
268
+ else:
269
+ G = nx.Graph()
270
+ G.add_nodes_from(range(n))
271
+
272
+ if n == 1:
273
+ return G
274
+ max_edges = n * (n - 1)
275
+ if not directed:
276
+ max_edges /= 2.0
277
+ if m >= max_edges:
278
+ return complete_graph(n, create_using=G)
279
+
280
+ nlist = list(G)
281
+ edge_count = 0
282
+ while edge_count < m:
283
+ # generate random edge,u,v
284
+ u = seed.choice(nlist)
285
+ v = seed.choice(nlist)
286
+ if u == v or G.has_edge(u, v):
287
+ continue
288
+ else:
289
+ G.add_edge(u, v)
290
+ edge_count = edge_count + 1
291
+ return G
292
+
293
+
294
+ @py_random_state(3)
295
+ @nx._dispatchable(graphs=None, returns_graph=True)
296
+ def newman_watts_strogatz_graph(n, k, p, seed=None):
297
+ """Returns a Newman–Watts–Strogatz small-world graph.
298
+
299
+ Parameters
300
+ ----------
301
+ n : int
302
+ The number of nodes.
303
+ k : int
304
+ Each node is joined with its `k` nearest neighbors in a ring
305
+ topology.
306
+ p : float
307
+ The probability of adding a new edge for each edge.
308
+ seed : integer, random_state, or None (default)
309
+ Indicator of random number generation state.
310
+ See :ref:`Randomness<randomness>`.
311
+
312
+ Notes
313
+ -----
314
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is
315
+ connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
316
+ is odd). Then shortcuts are created by adding new edges as follows: for
317
+ each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
318
+ neighbors" with probability $p$ add a new edge $(u, w)$ with
319
+ randomly-chosen existing node $w$. In contrast with
320
+ :func:`watts_strogatz_graph`, no edges are removed.
321
+
322
+ See Also
323
+ --------
324
+ watts_strogatz_graph
325
+
326
+ References
327
+ ----------
328
+ .. [1] M. E. J. Newman and D. J. Watts,
329
+ Renormalization group analysis of the small-world network model,
330
+ Physics Letters A, 263, 341, 1999.
331
+ https://doi.org/10.1016/S0375-9601(99)00757-4
332
+ """
333
+ if k > n:
334
+ raise nx.NetworkXError("k>=n, choose smaller k or larger n")
335
+
336
+ # If k == n the graph return is a complete graph
337
+ if k == n:
338
+ return nx.complete_graph(n)
339
+
340
+ G = empty_graph(n)
341
+ nlist = list(G.nodes())
342
+ fromv = nlist
343
+ # connect the k/2 neighbors
344
+ for j in range(1, k // 2 + 1):
345
+ tov = fromv[j:] + fromv[0:j] # the first j are now last
346
+ for i in range(len(fromv)):
347
+ G.add_edge(fromv[i], tov[i])
348
+ # for each edge u-v, with probability p, randomly select existing
349
+ # node w and add new edge u-w
350
+ e = list(G.edges())
351
+ for u, v in e:
352
+ if seed.random() < p:
353
+ w = seed.choice(nlist)
354
+ # no self-loops and reject if edge u-w exists
355
+ # is that the correct NWS model?
356
+ while w == u or G.has_edge(u, w):
357
+ w = seed.choice(nlist)
358
+ if G.degree(u) >= n - 1:
359
+ break # skip this rewiring
360
+ else:
361
+ G.add_edge(u, w)
362
+ return G
363
+
364
+
365
+ @py_random_state(3)
366
+ @nx._dispatchable(graphs=None, returns_graph=True)
367
+ def watts_strogatz_graph(n, k, p, seed=None):
368
+ """Returns a Watts–Strogatz small-world graph.
369
+
370
+ Parameters
371
+ ----------
372
+ n : int
373
+ The number of nodes
374
+ k : int
375
+ Each node is joined with its `k` nearest neighbors in a ring
376
+ topology.
377
+ p : float
378
+ The probability of rewiring each edge
379
+ seed : integer, random_state, or None (default)
380
+ Indicator of random number generation state.
381
+ See :ref:`Randomness<randomness>`.
382
+
383
+ See Also
384
+ --------
385
+ newman_watts_strogatz_graph
386
+ connected_watts_strogatz_graph
387
+
388
+ Notes
389
+ -----
390
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
391
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
392
+ Then shortcuts are created by replacing some edges as follows: for each
393
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
394
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
395
+ random choice of existing node $w$.
396
+
397
+ In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring
398
+ does not increase the number of edges. The rewired graph is not guaranteed
399
+ to be connected as in :func:`connected_watts_strogatz_graph`.
400
+
401
+ References
402
+ ----------
403
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
404
+ Collective dynamics of small-world networks,
405
+ Nature, 393, pp. 440--442, 1998.
406
+ """
407
+ if k > n:
408
+ raise nx.NetworkXError("k>n, choose smaller k or larger n")
409
+
410
+ # If k == n, the graph is complete not Watts-Strogatz
411
+ if k == n:
412
+ return nx.complete_graph(n)
413
+
414
+ G = nx.Graph()
415
+ nodes = list(range(n)) # nodes are labeled 0 to n-1
416
+ # connect each node to k/2 neighbors
417
+ for j in range(1, k // 2 + 1):
418
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
419
+ G.add_edges_from(zip(nodes, targets))
420
+ # rewire edges from each node
421
+ # loop over all nodes in order (label) and neighbors in order (distance)
422
+ # no self loops or multiple edges allowed
423
+ for j in range(1, k // 2 + 1): # outer loop is neighbors
424
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
425
+ # inner loop in node order
426
+ for u, v in zip(nodes, targets):
427
+ if seed.random() < p:
428
+ w = seed.choice(nodes)
429
+ # Enforce no self-loops or multiple edges
430
+ while w == u or G.has_edge(u, w):
431
+ w = seed.choice(nodes)
432
+ if G.degree(u) >= n - 1:
433
+ break # skip this rewiring
434
+ else:
435
+ G.remove_edge(u, v)
436
+ G.add_edge(u, w)
437
+ return G
438
+
439
+
440
+ @py_random_state(4)
441
+ @nx._dispatchable(graphs=None, returns_graph=True)
442
+ def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None):
443
+ """Returns a connected Watts–Strogatz small-world graph.
444
+
445
+ Attempts to generate a connected graph by repeated generation of
446
+ Watts–Strogatz small-world graphs. An exception is raised if the maximum
447
+ number of tries is exceeded.
448
+
449
+ Parameters
450
+ ----------
451
+ n : int
452
+ The number of nodes
453
+ k : int
454
+ Each node is joined with its `k` nearest neighbors in a ring
455
+ topology.
456
+ p : float
457
+ The probability of rewiring each edge
458
+ tries : int
459
+ Number of attempts to generate a connected graph.
460
+ seed : integer, random_state, or None (default)
461
+ Indicator of random number generation state.
462
+ See :ref:`Randomness<randomness>`.
463
+
464
+ Notes
465
+ -----
466
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
467
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
468
+ Then shortcuts are created by replacing some edges as follows: for each
469
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
470
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
471
+ random choice of existing node $w$.
472
+ The entire process is repeated until a connected graph results.
473
+
474
+ See Also
475
+ --------
476
+ newman_watts_strogatz_graph
477
+ watts_strogatz_graph
478
+
479
+ References
480
+ ----------
481
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
482
+ Collective dynamics of small-world networks,
483
+ Nature, 393, pp. 440--442, 1998.
484
+ """
485
+ for i in range(tries):
486
+ # seed is an RNG so should change sequence each call
487
+ G = watts_strogatz_graph(n, k, p, seed)
488
+ if nx.is_connected(G):
489
+ return G
490
+ raise nx.NetworkXError("Maximum number of tries exceeded")
491
+
492
+
493
+ @py_random_state(2)
494
+ @nx._dispatchable(graphs=None, returns_graph=True)
495
+ def random_regular_graph(d, n, seed=None):
496
+ r"""Returns a random $d$-regular graph on $n$ nodes.
497
+
498
+ A regular graph is a graph where each node has the same number of neighbors.
499
+
500
+ The resulting graph has no self-loops or parallel edges.
501
+
502
+ Parameters
503
+ ----------
504
+ d : int
505
+ The degree of each node.
506
+ n : integer
507
+ The number of nodes. The value of $n \times d$ must be even.
508
+ seed : integer, random_state, or None (default)
509
+ Indicator of random number generation state.
510
+ See :ref:`Randomness<randomness>`.
511
+
512
+ Notes
513
+ -----
514
+ The nodes are numbered from $0$ to $n - 1$.
515
+
516
+ Kim and Vu's paper [2]_ shows that this algorithm samples in an
517
+ asymptotically uniform way from the space of random graphs when
518
+ $d = O(n^{1 / 3 - \epsilon})$.
519
+
520
+ Raises
521
+ ------
522
+
523
+ NetworkXError
524
+ If $n \times d$ is odd or $d$ is greater than or equal to $n$.
525
+
526
+ References
527
+ ----------
528
+ .. [1] A. Steger and N. Wormald,
529
+ Generating random regular graphs quickly,
530
+ Probability and Computing 8 (1999), 377-396, 1999.
531
+ https://doi.org/10.1017/S0963548399003867
532
+
533
+ .. [2] Jeong Han Kim and Van H. Vu,
534
+ Generating random regular graphs,
535
+ Proceedings of the thirty-fifth ACM symposium on Theory of computing,
536
+ San Diego, CA, USA, pp 213--222, 2003.
537
+ http://portal.acm.org/citation.cfm?id=780542.780576
538
+ """
539
+ if (n * d) % 2 != 0:
540
+ raise nx.NetworkXError("n * d must be even")
541
+
542
+ if not 0 <= d < n:
543
+ raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
544
+
545
+ if d == 0:
546
+ return empty_graph(n)
547
+
548
+ def _suitable(edges, potential_edges):
549
+ # Helper subroutine to check if there are suitable edges remaining
550
+ # If False, the generation of the graph has failed
551
+ if not potential_edges:
552
+ return True
553
+ for s1 in potential_edges:
554
+ for s2 in potential_edges:
555
+ # Two iterators on the same dictionary are guaranteed
556
+ # to visit it in the same order if there are no
557
+ # intervening modifications.
558
+ if s1 == s2:
559
+ # Only need to consider s1-s2 pair one time
560
+ break
561
+ if s1 > s2:
562
+ s1, s2 = s2, s1
563
+ if (s1, s2) not in edges:
564
+ return True
565
+ return False
566
+
567
+ def _try_creation():
568
+ # Attempt to create an edge set
569
+
570
+ edges = set()
571
+ stubs = list(range(n)) * d
572
+
573
+ while stubs:
574
+ potential_edges = defaultdict(lambda: 0)
575
+ seed.shuffle(stubs)
576
+ stubiter = iter(stubs)
577
+ for s1, s2 in zip(stubiter, stubiter):
578
+ if s1 > s2:
579
+ s1, s2 = s2, s1
580
+ if s1 != s2 and ((s1, s2) not in edges):
581
+ edges.add((s1, s2))
582
+ else:
583
+ potential_edges[s1] += 1
584
+ potential_edges[s2] += 1
585
+
586
+ if not _suitable(edges, potential_edges):
587
+ return None # failed to find suitable edge set
588
+
589
+ stubs = [
590
+ node
591
+ for node, potential in potential_edges.items()
592
+ for _ in range(potential)
593
+ ]
594
+ return edges
595
+
596
+ # Even though a suitable edge set exists,
597
+ # the generation of such a set is not guaranteed.
598
+ # Try repeatedly to find one.
599
+ edges = _try_creation()
600
+ while edges is None:
601
+ edges = _try_creation()
602
+
603
+ G = nx.Graph()
604
+ G.add_edges_from(edges)
605
+
606
+ return G
607
+
608
+
609
+ def _random_subset(seq, m, rng):
610
+ """Return m unique elements from seq.
611
+
612
+ This differs from random.sample which can return repeated
613
+ elements if seq holds repeated elements.
614
+
615
+ Note: rng is a random.Random or numpy.random.RandomState instance.
616
+ """
617
+ targets = set()
618
+ while len(targets) < m:
619
+ x = rng.choice(seq)
620
+ targets.add(x)
621
+ return targets
622
+
623
+
624
+ @py_random_state(2)
625
+ @nx._dispatchable(graphs=None, returns_graph=True)
626
+ def barabasi_albert_graph(n, m, seed=None, initial_graph=None):
627
+ """Returns a random graph using Barabási–Albert preferential attachment
628
+
629
+ A graph of $n$ nodes is grown by attaching new nodes each with $m$
630
+ edges that are preferentially attached to existing nodes with high degree.
631
+
632
+ Parameters
633
+ ----------
634
+ n : int
635
+ Number of nodes
636
+ m : int
637
+ Number of edges to attach from a new node to existing nodes
638
+ seed : integer, random_state, or None (default)
639
+ Indicator of random number generation state.
640
+ See :ref:`Randomness<randomness>`.
641
+ initial_graph : Graph or None (default)
642
+ Initial network for Barabási–Albert algorithm.
643
+ It should be a connected graph for most use cases.
644
+ A copy of `initial_graph` is used.
645
+ If None, starts from a star graph on (m+1) nodes.
646
+
647
+ Returns
648
+ -------
649
+ G : Graph
650
+
651
+ Raises
652
+ ------
653
+ NetworkXError
654
+ If `m` does not satisfy ``1 <= m < n``, or
655
+ the initial graph number of nodes m0 does not satisfy ``m <= m0 <= n``.
656
+
657
+ References
658
+ ----------
659
+ .. [1] A. L. Barabási and R. Albert "Emergence of scaling in
660
+ random networks", Science 286, pp 509-512, 1999.
661
+ """
662
+
663
+ if m < 1 or m >= n:
664
+ raise nx.NetworkXError(
665
+ f"Barabási–Albert network must have m >= 1 and m < n, m = {m}, n = {n}"
666
+ )
667
+
668
+ if initial_graph is None:
669
+ # Default initial graph : star graph on (m + 1) nodes
670
+ G = star_graph(m)
671
+ else:
672
+ if len(initial_graph) < m or len(initial_graph) > n:
673
+ raise nx.NetworkXError(
674
+ f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
675
+ )
676
+ G = initial_graph.copy()
677
+
678
+ # List of existing nodes, with nodes repeated once for each adjacent edge
679
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
680
+ # Start adding the other n - m0 nodes.
681
+ source = len(G)
682
+ while source < n:
683
+ # Now choose m unique nodes from the existing nodes
684
+ # Pick uniformly from repeated_nodes (preferential attachment)
685
+ targets = _random_subset(repeated_nodes, m, seed)
686
+ # Add edges to m nodes from the source.
687
+ G.add_edges_from(zip([source] * m, targets))
688
+ # Add one node to the list for each new edge just created.
689
+ repeated_nodes.extend(targets)
690
+ # And the new node "source" has m edges to add to the list.
691
+ repeated_nodes.extend([source] * m)
692
+
693
+ source += 1
694
+ return G
695
+
696
+
697
+ @py_random_state(4)
698
+ @nx._dispatchable(graphs=None, returns_graph=True)
699
+ def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
700
+ """Returns a random graph using dual Barabási–Albert preferential attachment
701
+
702
+ A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
703
+ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
704
+ are preferentially attached to existing nodes with high degree.
705
+
706
+ Parameters
707
+ ----------
708
+ n : int
709
+ Number of nodes
710
+ m1 : int
711
+ Number of edges to link each new node to existing nodes with probability $p$
712
+ m2 : int
713
+ Number of edges to link each new node to existing nodes with probability $1-p$
714
+ p : float
715
+ The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
716
+ seed : integer, random_state, or None (default)
717
+ Indicator of random number generation state.
718
+ See :ref:`Randomness<randomness>`.
719
+ initial_graph : Graph or None (default)
720
+ Initial network for Barabási–Albert algorithm.
721
+ A copy of `initial_graph` is used.
722
+ It should be connected for most use cases.
723
+ If None, starts from an star graph on max(m1, m2) + 1 nodes.
724
+
725
+ Returns
726
+ -------
727
+ G : Graph
728
+
729
+ Raises
730
+ ------
731
+ NetworkXError
732
+ If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
733
+ `p` does not satisfy ``0 <= p <= 1``, or
734
+ the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
735
+
736
+ References
737
+ ----------
738
+ .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
739
+ """
740
+
741
+ if m1 < 1 or m1 >= n:
742
+ raise nx.NetworkXError(
743
+ f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
744
+ )
745
+ if m2 < 1 or m2 >= n:
746
+ raise nx.NetworkXError(
747
+ f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
748
+ )
749
+ if p < 0 or p > 1:
750
+ raise nx.NetworkXError(
751
+ f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
752
+ )
753
+
754
+ # For simplicity, if p == 0 or 1, just return BA
755
+ if p == 1:
756
+ return barabasi_albert_graph(n, m1, seed)
757
+ elif p == 0:
758
+ return barabasi_albert_graph(n, m2, seed)
759
+
760
+ if initial_graph is None:
761
+ # Default initial graph : empty graph on max(m1, m2) nodes
762
+ G = star_graph(max(m1, m2))
763
+ else:
764
+ if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
765
+ raise nx.NetworkXError(
766
+ f"Barabási–Albert initial graph must have between "
767
+ f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
768
+ )
769
+ G = initial_graph.copy()
770
+
771
+ # Target nodes for new edges
772
+ targets = list(G)
773
+ # List of existing nodes, with nodes repeated once for each adjacent edge
774
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
775
+ # Start adding the remaining nodes.
776
+ source = len(G)
777
+ while source < n:
778
+ # Pick which m to use (m1 or m2)
779
+ if seed.random() < p:
780
+ m = m1
781
+ else:
782
+ m = m2
783
+ # Now choose m unique nodes from the existing nodes
784
+ # Pick uniformly from repeated_nodes (preferential attachment)
785
+ targets = _random_subset(repeated_nodes, m, seed)
786
+ # Add edges to m nodes from the source.
787
+ G.add_edges_from(zip([source] * m, targets))
788
+ # Add one node to the list for each new edge just created.
789
+ repeated_nodes.extend(targets)
790
+ # And the new node "source" has m edges to add to the list.
791
+ repeated_nodes.extend([source] * m)
792
+
793
+ source += 1
794
+ return G
795
+
796
+
797
+ @py_random_state(4)
798
+ @nx._dispatchable(graphs=None, returns_graph=True)
799
+ def extended_barabasi_albert_graph(n, m, p, q, seed=None):
800
+ """Returns an extended Barabási–Albert model graph.
801
+
802
+ An extended Barabási–Albert model graph is a random graph constructed
803
+ using preferential attachment. The extended model allows new edges,
804
+ rewired edges or new nodes. Based on the probabilities $p$ and $q$
805
+ with $p + q < 1$, the growing behavior of the graph is determined as:
806
+
807
+ 1) With $p$ probability, $m$ new edges are added to the graph,
808
+ starting from randomly chosen existing nodes and attached preferentially at the other end.
809
+
810
+ 2) With $q$ probability, $m$ existing edges are rewired
811
+ by randomly choosing an edge and rewiring one end to a preferentially chosen node.
812
+
813
+ 3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
814
+ with edges attached preferentially.
815
+
816
+ When $p = q = 0$, the model behaves just like the Barabási–Alber model.
817
+
818
+ Parameters
819
+ ----------
820
+ n : int
821
+ Number of nodes
822
+ m : int
823
+ Number of edges with which a new node attaches to existing nodes
824
+ p : float
825
+ Probability value for adding an edge between existing nodes. p + q < 1
826
+ q : float
827
+ Probability value of rewiring of existing edges. p + q < 1
828
+ seed : integer, random_state, or None (default)
829
+ Indicator of random number generation state.
830
+ See :ref:`Randomness<randomness>`.
831
+
832
+ Returns
833
+ -------
834
+ G : Graph
835
+
836
+ Raises
837
+ ------
838
+ NetworkXError
839
+ If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
840
+
841
+ References
842
+ ----------
843
+ .. [1] Albert, R., & Barabási, A. L. (2000)
844
+ Topology of evolving networks: local events and universality
845
+ Physical review letters, 85(24), 5234.
846
+ """
847
+ if m < 1 or m >= n:
848
+ msg = f"Extended Barabasi-Albert network needs m>=1 and m<n, m={m}, n={n}"
849
+ raise nx.NetworkXError(msg)
850
+ if p + q >= 1:
851
+ msg = f"Extended Barabasi-Albert network needs p + q <= 1, p={p}, q={q}"
852
+ raise nx.NetworkXError(msg)
853
+
854
+ # Add m initial nodes (m0 in barabasi-speak)
855
+ G = empty_graph(m)
856
+
857
+ # List of nodes to represent the preferential attachment random selection.
858
+ # At the creation of the graph, all nodes are added to the list
859
+ # so that even nodes that are not connected have a chance to get selected,
860
+ # for rewiring and adding of edges.
861
+ # With each new edge, nodes at the ends of the edge are added to the list.
862
+ attachment_preference = []
863
+ attachment_preference.extend(range(m))
864
+
865
+ # Start adding the other n-m nodes. The first node is m.
866
+ new_node = m
867
+ while new_node < n:
868
+ a_probability = seed.random()
869
+
870
+ # Total number of edges of a Clique of all the nodes
871
+ clique_degree = len(G) - 1
872
+ clique_size = (len(G) * clique_degree) / 2
873
+
874
+ # Adding m new edges, if there is room to add them
875
+ if a_probability < p and G.size() <= clique_size - m:
876
+ # Select the nodes where an edge can be added
877
+ eligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
878
+ for i in range(m):
879
+ # Choosing a random source node from eligible_nodes
880
+ src_node = seed.choice(eligible_nodes)
881
+
882
+ # Picking a possible node that is not 'src_node' or
883
+ # neighbor with 'src_node', with preferential attachment
884
+ prohibited_nodes = list(G[src_node])
885
+ prohibited_nodes.append(src_node)
886
+ # This will raise an exception if the sequence is empty
887
+ dest_node = seed.choice(
888
+ [nd for nd in attachment_preference if nd not in prohibited_nodes]
889
+ )
890
+ # Adding the new edge
891
+ G.add_edge(src_node, dest_node)
892
+
893
+ # Appending both nodes to add to their preferential attachment
894
+ attachment_preference.append(src_node)
895
+ attachment_preference.append(dest_node)
896
+
897
+ # Adjusting the eligible nodes. Degree may be saturated.
898
+ if G.degree(src_node) == clique_degree:
899
+ eligible_nodes.remove(src_node)
900
+ if G.degree(dest_node) == clique_degree and dest_node in eligible_nodes:
901
+ eligible_nodes.remove(dest_node)
902
+
903
+ # Rewiring m edges, if there are enough edges
904
+ elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
905
+ # Selecting nodes that have at least 1 edge but that are not
906
+ # fully connected to ALL other nodes (center of star).
907
+ # These nodes are the pivot nodes of the edges to rewire
908
+ eligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
909
+ for i in range(m):
910
+ # Choosing a random source node
911
+ node = seed.choice(eligible_nodes)
912
+
913
+ # The available nodes do have a neighbor at least.
914
+ nbr_nodes = list(G[node])
915
+
916
+ # Choosing the other end that will get detached
917
+ src_node = seed.choice(nbr_nodes)
918
+
919
+ # Picking a target node that is not 'node' or
920
+ # neighbor with 'node', with preferential attachment
921
+ nbr_nodes.append(node)
922
+ dest_node = seed.choice(
923
+ [nd for nd in attachment_preference if nd not in nbr_nodes]
924
+ )
925
+ # Rewire
926
+ G.remove_edge(node, src_node)
927
+ G.add_edge(node, dest_node)
928
+
929
+ # Adjusting the preferential attachment list
930
+ attachment_preference.remove(src_node)
931
+ attachment_preference.append(dest_node)
932
+
933
+ # Adjusting the eligible nodes.
934
+ # nodes may be saturated or isolated.
935
+ if G.degree(src_node) == 0 and src_node in eligible_nodes:
936
+ eligible_nodes.remove(src_node)
937
+ if dest_node in eligible_nodes:
938
+ if G.degree(dest_node) == clique_degree:
939
+ eligible_nodes.remove(dest_node)
940
+ else:
941
+ if G.degree(dest_node) == 1:
942
+ eligible_nodes.append(dest_node)
943
+
944
+ # Adding new node with m edges
945
+ else:
946
+ # Select the edges' nodes by preferential attachment
947
+ targets = _random_subset(attachment_preference, m, seed)
948
+ G.add_edges_from(zip([new_node] * m, targets))
949
+
950
+ # Add one node to the list for each new edge just created.
951
+ attachment_preference.extend(targets)
952
+ # The new node has m edges to it, plus itself: m + 1
953
+ attachment_preference.extend([new_node] * (m + 1))
954
+ new_node += 1
955
+ return G
956
+
957
+
958
+ @py_random_state(3)
959
+ @nx._dispatchable(graphs=None, returns_graph=True)
960
+ def powerlaw_cluster_graph(n, m, p, seed=None):
961
+ """Holme and Kim algorithm for growing graphs with powerlaw
962
+ degree distribution and approximate average clustering.
963
+
964
+ Parameters
965
+ ----------
966
+ n : int
967
+ the number of nodes
968
+ m : int
969
+ the number of random edges to add for each new node
970
+ p : float,
971
+ Probability of adding a triangle after adding a random edge
972
+ seed : integer, random_state, or None (default)
973
+ Indicator of random number generation state.
974
+ See :ref:`Randomness<randomness>`.
975
+
976
+ Notes
977
+ -----
978
+ The average clustering has a hard time getting above a certain
979
+ cutoff that depends on `m`. This cutoff is often quite low. The
980
+ transitivity (fraction of triangles to possible triangles) seems to
981
+ decrease with network size.
982
+
983
+ It is essentially the Barabási–Albert (BA) growth model with an
984
+ extra step that each random edge is followed by a chance of
985
+ making an edge to one of its neighbors too (and thus a triangle).
986
+
987
+ This algorithm improves on BA in the sense that it enables a
988
+ higher average clustering to be attained if desired.
989
+
990
+ It seems possible to have a disconnected graph with this algorithm
991
+ since the initial `m` nodes may not be all linked to a new node
992
+ on the first iteration like the BA model.
993
+
994
+ Raises
995
+ ------
996
+ NetworkXError
997
+ If `m` does not satisfy ``1 <= m <= n`` or `p` does not
998
+ satisfy ``0 <= p <= 1``.
999
+
1000
+ References
1001
+ ----------
1002
+ .. [1] P. Holme and B. J. Kim,
1003
+ "Growing scale-free networks with tunable clustering",
1004
+ Phys. Rev. E, 65, 026107, 2002.
1005
+ """
1006
+
1007
+ if m < 1 or n < m:
1008
+ raise nx.NetworkXError(f"NetworkXError must have m>1 and m<n, m={m},n={n}")
1009
+
1010
+ if p > 1 or p < 0:
1011
+ raise nx.NetworkXError(f"NetworkXError p must be in [0,1], p={p}")
1012
+
1013
+ G = empty_graph(m) # add m initial nodes (m0 in barabasi-speak)
1014
+ repeated_nodes = list(G.nodes()) # list of existing nodes to sample from
1015
+ # with nodes repeated once for each adjacent edge
1016
+ source = m # next node is m
1017
+ while source < n: # Now add the other n-1 nodes
1018
+ possible_targets = _random_subset(repeated_nodes, m, seed)
1019
+ # do one preferential attachment for new node
1020
+ target = possible_targets.pop()
1021
+ G.add_edge(source, target)
1022
+ repeated_nodes.append(target) # add one node to list for each new link
1023
+ count = 1
1024
+ while count < m: # add m-1 more new links
1025
+ if seed.random() < p: # clustering step: add triangle
1026
+ neighborhood = [
1027
+ nbr
1028
+ for nbr in G.neighbors(target)
1029
+ if not G.has_edge(source, nbr) and nbr != source
1030
+ ]
1031
+ if neighborhood: # if there is a neighbor without a link
1032
+ nbr = seed.choice(neighborhood)
1033
+ G.add_edge(source, nbr) # add triangle
1034
+ repeated_nodes.append(nbr)
1035
+ count = count + 1
1036
+ continue # go to top of while loop
1037
+ # else do preferential attachment step if above fails
1038
+ target = possible_targets.pop()
1039
+ G.add_edge(source, target)
1040
+ repeated_nodes.append(target)
1041
+ count = count + 1
1042
+
1043
+ repeated_nodes.extend([source] * m) # add source node to list m times
1044
+ source += 1
1045
+ return G
1046
+
1047
+
1048
+ @py_random_state(3)
1049
+ @nx._dispatchable(graphs=None, returns_graph=True)
1050
+ def random_lobster(n, p1, p2, seed=None):
1051
+ """Returns a random lobster graph.
1052
+
1053
+ A lobster is a tree that reduces to a caterpillar when pruning all
1054
+ leaf nodes. A caterpillar is a tree that reduces to a path graph
1055
+ when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
1056
+
1057
+ This implementation iterates on the probabilities `p1` and `p2` to add
1058
+ edges at levels 1 and 2, respectively. Graphs are therefore constructed
1059
+ iteratively with uniform randomness at each level rather than being selected
1060
+ uniformly at random from the set of all possible lobsters.
1061
+
1062
+ Parameters
1063
+ ----------
1064
+ n : int
1065
+ The expected number of nodes in the backbone
1066
+ p1 : float
1067
+ Probability of adding an edge to the backbone
1068
+ p2 : float
1069
+ Probability of adding an edge one level beyond backbone
1070
+ seed : integer, random_state, or None (default)
1071
+ Indicator of random number generation state.
1072
+ See :ref:`Randomness<randomness>`.
1073
+
1074
+ Raises
1075
+ ------
1076
+ NetworkXError
1077
+ If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
1078
+ """
1079
+ p1, p2 = abs(p1), abs(p2)
1080
+ if any(p >= 1 for p in [p1, p2]):
1081
+ raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
1082
+
1083
+ # a necessary ingredient in any self-respecting graph library
1084
+ llen = int(2 * seed.random() * n + 0.5)
1085
+ L = path_graph(llen)
1086
+ # build caterpillar: add edges to path graph with probability p1
1087
+ current_node = llen - 1
1088
+ for n in range(llen):
1089
+ while seed.random() < p1: # add fuzzy caterpillar parts
1090
+ current_node += 1
1091
+ L.add_edge(n, current_node)
1092
+ cat_node = current_node
1093
+ while seed.random() < p2: # add crunchy lobster bits
1094
+ current_node += 1
1095
+ L.add_edge(cat_node, current_node)
1096
+ return L # voila, un lobster!
1097
+
1098
+
1099
+ @py_random_state(1)
1100
+ @nx._dispatchable(graphs=None, returns_graph=True)
1101
+ def random_shell_graph(constructor, seed=None):
1102
+ """Returns a random shell graph for the constructor given.
1103
+
1104
+ Parameters
1105
+ ----------
1106
+ constructor : list of three-tuples
1107
+ Represents the parameters for a shell, starting at the center
1108
+ shell. Each element of the list must be of the form `(n, m,
1109
+ d)`, where `n` is the number of nodes in the shell, `m` is
1110
+ the number of edges in the shell, and `d` is the ratio of
1111
+ inter-shell (next) edges to intra-shell edges. If `d` is zero,
1112
+ there will be no intra-shell edges, and if `d` is one there
1113
+ will be all possible intra-shell edges.
1114
+ seed : integer, random_state, or None (default)
1115
+ Indicator of random number generation state.
1116
+ See :ref:`Randomness<randomness>`.
1117
+
1118
+ Examples
1119
+ --------
1120
+ >>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
1121
+ >>> G = nx.random_shell_graph(constructor)
1122
+
1123
+ """
1124
+ G = empty_graph(0)
1125
+
1126
+ glist = []
1127
+ intra_edges = []
1128
+ nnodes = 0
1129
+ # create gnm graphs for each shell
1130
+ for n, m, d in constructor:
1131
+ inter_edges = int(m * d)
1132
+ intra_edges.append(m - inter_edges)
1133
+ g = nx.convert_node_labels_to_integers(
1134
+ gnm_random_graph(n, inter_edges, seed=seed), first_label=nnodes
1135
+ )
1136
+ glist.append(g)
1137
+ nnodes += n
1138
+ G = nx.operators.union(G, g)
1139
+
1140
+ # connect the shells randomly
1141
+ for gi in range(len(glist) - 1):
1142
+ nlist1 = list(glist[gi])
1143
+ nlist2 = list(glist[gi + 1])
1144
+ total_edges = intra_edges[gi]
1145
+ edge_count = 0
1146
+ while edge_count < total_edges:
1147
+ u = seed.choice(nlist1)
1148
+ v = seed.choice(nlist2)
1149
+ if u == v or G.has_edge(u, v):
1150
+ continue
1151
+ else:
1152
+ G.add_edge(u, v)
1153
+ edge_count = edge_count + 1
1154
+ return G
1155
+
1156
+
1157
+ @py_random_state(2)
1158
+ @nx._dispatchable(graphs=None, returns_graph=True)
1159
+ def random_powerlaw_tree(n, gamma=3, seed=None, tries=100):
1160
+ """Returns a tree with a power law degree distribution.
1161
+
1162
+ Parameters
1163
+ ----------
1164
+ n : int
1165
+ The number of nodes.
1166
+ gamma : float
1167
+ Exponent of the power law.
1168
+ seed : integer, random_state, or None (default)
1169
+ Indicator of random number generation state.
1170
+ See :ref:`Randomness<randomness>`.
1171
+ tries : int
1172
+ Number of attempts to adjust the sequence to make it a tree.
1173
+
1174
+ Raises
1175
+ ------
1176
+ NetworkXError
1177
+ If no valid sequence is found within the maximum number of
1178
+ attempts.
1179
+
1180
+ Notes
1181
+ -----
1182
+ A trial power law degree sequence is chosen and then elements are
1183
+ swapped with new elements from a powerlaw distribution until the
1184
+ sequence makes a tree (by checking, for example, that the number of
1185
+ edges is one smaller than the number of nodes).
1186
+
1187
+ """
1188
+ # This call may raise a NetworkXError if the number of tries is succeeded.
1189
+ seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
1190
+ G = degree_sequence_tree(seq)
1191
+ return G
1192
+
1193
+
1194
+ @py_random_state(2)
1195
+ @nx._dispatchable(graphs=None)
1196
+ def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
1197
+ """Returns a degree sequence for a tree with a power law distribution.
1198
+
1199
+ Parameters
1200
+ ----------
1201
+ n : int,
1202
+ The number of nodes.
1203
+ gamma : float
1204
+ Exponent of the power law.
1205
+ seed : integer, random_state, or None (default)
1206
+ Indicator of random number generation state.
1207
+ See :ref:`Randomness<randomness>`.
1208
+ tries : int
1209
+ Number of attempts to adjust the sequence to make it a tree.
1210
+
1211
+ Raises
1212
+ ------
1213
+ NetworkXError
1214
+ If no valid sequence is found within the maximum number of
1215
+ attempts.
1216
+
1217
+ Notes
1218
+ -----
1219
+ A trial power law degree sequence is chosen and then elements are
1220
+ swapped with new elements from a power law distribution until
1221
+ the sequence makes a tree (by checking, for example, that the number of
1222
+ edges is one smaller than the number of nodes).
1223
+
1224
+ """
1225
+ # get trial sequence
1226
+ z = nx.utils.powerlaw_sequence(n, exponent=gamma, seed=seed)
1227
+ # round to integer values in the range [0,n]
1228
+ zseq = [min(n, max(round(s), 0)) for s in z]
1229
+
1230
+ # another sequence to swap values from
1231
+ z = nx.utils.powerlaw_sequence(tries, exponent=gamma, seed=seed)
1232
+ # round to integer values in the range [0,n]
1233
+ swap = [min(n, max(round(s), 0)) for s in z]
1234
+
1235
+ for deg in swap:
1236
+ # If this degree sequence can be the degree sequence of a tree, return
1237
+ # it. It can be a tree if the number of edges is one fewer than the
1238
+ # number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
1239
+ # use an equivalent condition below that avoids floating point
1240
+ # operations.
1241
+ if 2 * n - sum(zseq) == 2:
1242
+ return zseq
1243
+ index = seed.randint(0, n - 1)
1244
+ zseq[index] = swap.pop()
1245
+
1246
+ raise nx.NetworkXError(
1247
+ f"Exceeded max ({tries}) attempts for a valid tree sequence."
1248
+ )
1249
+
1250
+
1251
+ @py_random_state(3)
1252
+ @nx._dispatchable(graphs=None, returns_graph=True)
1253
+ def random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None):
1254
+ r"""Returns an random graph based on the specified kernel.
1255
+
1256
+ The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
1257
+ probability specified by a kernel $\kappa(x,y)$ [1]_. The kernel
1258
+ $\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
1259
+ bounded function.
1260
+
1261
+ Parameters
1262
+ ----------
1263
+ n : int
1264
+ The number of nodes
1265
+ kernel_integral : function
1266
+ Function that returns the definite integral of the kernel $\kappa(x,y)$,
1267
+ $F(y,a,b) := \int_a^b \kappa(x,y)dx$
1268
+ kernel_root: function (optional)
1269
+ Function that returns the root $b$ of the equation $F(y,a,b) = r$.
1270
+ If None, the root is found using :func:`scipy.optimize.brentq`
1271
+ (this requires SciPy).
1272
+ seed : integer, random_state, or None (default)
1273
+ Indicator of random number generation state.
1274
+ See :ref:`Randomness<randomness>`.
1275
+
1276
+ Notes
1277
+ -----
1278
+ The kernel is specified through its definite integral which must be
1279
+ provided as one of the arguments. If the integral and root of the
1280
+ kernel integral can be found in $O(1)$ time then this algorithm runs in
1281
+ time $O(n+m)$ where m is the expected number of edges [2]_.
1282
+
1283
+ The nodes are set to integers from $0$ to $n-1$.
1284
+
1285
+ Examples
1286
+ --------
1287
+ Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
1288
+ $\kappa(x,y)=c$ where $c$ is the mean expected degree.
1289
+
1290
+ >>> def integral(u, w, z):
1291
+ ... return c * (z - w)
1292
+ >>> def root(u, w, r):
1293
+ ... return r / c + w
1294
+ >>> c = 1
1295
+ >>> graph = nx.random_kernel_graph(1000, integral, root)
1296
+
1297
+ See Also
1298
+ --------
1299
+ gnp_random_graph
1300
+ expected_degree_graph
1301
+
1302
+ References
1303
+ ----------
1304
+ .. [1] Bollobás, Béla, Janson, S. and Riordan, O.
1305
+ "The phase transition in inhomogeneous random graphs",
1306
+ *Random Structures Algorithms*, 31, 3--122, 2007.
1307
+
1308
+ .. [2] Hagberg A, Lemons N (2015),
1309
+ "Fast Generation of Sparse Random Kernel Graphs".
1310
+ PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
1311
+ """
1312
+ if kernel_root is None:
1313
+ import scipy as sp
1314
+
1315
+ def kernel_root(y, a, r):
1316
+ def my_function(b):
1317
+ return kernel_integral(y, a, b) - r
1318
+
1319
+ return sp.optimize.brentq(my_function, a, 1)
1320
+
1321
+ graph = nx.Graph()
1322
+ graph.add_nodes_from(range(n))
1323
+ (i, j) = (1, 1)
1324
+ while i < n:
1325
+ r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
1326
+ if kernel_integral(i / n, j / n, 1) <= r:
1327
+ i, j = i + 1, i + 1
1328
+ else:
1329
+ j = math.ceil(n * kernel_root(i / n, j / n, r))
1330
+ graph.add_edge(i - 1, j - 1)
1331
+ return graph
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/networkx/generators/social.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Famous social networks.
3
+ """
4
+ import networkx as nx
5
+
6
+ __all__ = [
7
+ "karate_club_graph",
8
+ "davis_southern_women_graph",
9
+ "florentine_families_graph",
10
+ "les_miserables_graph",
11
+ ]
12
+
13
+
14
+ @nx._dispatchable(graphs=None, returns_graph=True)
15
+ def karate_club_graph():
16
+ """Returns Zachary's Karate Club graph.
17
+
18
+ Each node in the returned graph has a node attribute 'club' that
19
+ indicates the name of the club to which the member represented by that node
20
+ belongs, either 'Mr. Hi' or 'Officer'. Each edge has a weight based on the
21
+ number of contexts in which that edge's incident node members interacted.
22
+
23
+ Examples
24
+ --------
25
+ To get the name of the club to which a node belongs::
26
+
27
+ >>> G = nx.karate_club_graph()
28
+ >>> G.nodes[5]["club"]
29
+ 'Mr. Hi'
30
+ >>> G.nodes[9]["club"]
31
+ 'Officer'
32
+
33
+ References
34
+ ----------
35
+ .. [1] Zachary, Wayne W.
36
+ "An Information Flow Model for Conflict and Fission in Small Groups."
37
+ *Journal of Anthropological Research*, 33, 452--473, (1977).
38
+ """
39
+ # Create the set of all members, and the members of each club.
40
+ all_members = set(range(34))
41
+ club1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21}
42
+ # club2 = all_members - club1
43
+
44
+ G = nx.Graph()
45
+ G.add_nodes_from(all_members)
46
+ G.name = "Zachary's Karate Club"
47
+
48
+ zacharydat = """\
49
+ 0 4 5 3 3 3 3 2 2 0 2 3 2 3 0 0 0 2 0 2 0 2 0 0 0 0 0 0 0 0 0 2 0 0
50
+ 4 0 6 3 0 0 0 4 0 0 0 0 0 5 0 0 0 1 0 2 0 2 0 0 0 0 0 0 0 0 2 0 0 0
51
+ 5 6 0 3 0 0 0 4 5 1 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 0 0 0 3 0
52
+ 3 3 3 0 0 0 0 3 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
53
+ 3 0 0 0 0 0 2 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
54
+ 3 0 0 0 0 0 5 0 0 0 3 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
55
+ 3 0 0 0 2 5 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
56
+ 2 4 4 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
57
+ 2 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 4 3
58
+ 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
59
+ 2 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
60
+ 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
61
+ 1 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
62
+ 3 5 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3
63
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2
64
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 4
65
+ 0 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
66
+ 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
67
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2
68
+ 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
69
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1
70
+ 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
71
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0
72
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 4 0 2 0 0 5 4
73
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 3 0 0 0 2 0 0
74
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 2 0 0 0 0 0 0 7 0 0
75
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 2
76
+ 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 3 0 0 0 0 0 0 0 0 4
77
+ 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 2
78
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 4 0 0 0 0 0 3 2
79
+ 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3
80
+ 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 7 0 0 2 0 0 0 4 4
81
+ 0 0 2 0 0 0 0 0 3 0 0 0 0 0 3 3 0 0 1 0 3 0 2 5 0 0 0 0 0 4 3 4 0 5
82
+ 0 0 0 0 0 0 0 0 4 2 0 0 0 3 2 4 0 0 2 1 1 0 3 4 0 0 2 4 2 2 3 4 5 0"""
83
+
84
+ for row, line in enumerate(zacharydat.split("\n")):
85
+ thisrow = [int(b) for b in line.split()]
86
+ for col, entry in enumerate(thisrow):
87
+ if entry >= 1:
88
+ G.add_edge(row, col, weight=entry)
89
+
90
+ # Add the name of each member's club as a node attribute.
91
+ for v in G:
92
+ G.nodes[v]["club"] = "Mr. Hi" if v in club1 else "Officer"
93
+ return G
94
+
95
+
96
+ @nx._dispatchable(graphs=None, returns_graph=True)
97
+ def davis_southern_women_graph():
98
+ """Returns Davis Southern women social network.
99
+
100
+ This is a bipartite graph.
101
+
102
+ References
103
+ ----------
104
+ .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.
105
+ University of Chicago Press, Chicago, IL.
106
+ """
107
+ G = nx.Graph()
108
+ # Top nodes
109
+ women = [
110
+ "Evelyn Jefferson",
111
+ "Laura Mandeville",
112
+ "Theresa Anderson",
113
+ "Brenda Rogers",
114
+ "Charlotte McDowd",
115
+ "Frances Anderson",
116
+ "Eleanor Nye",
117
+ "Pearl Oglethorpe",
118
+ "Ruth DeSand",
119
+ "Verne Sanderson",
120
+ "Myra Liddel",
121
+ "Katherina Rogers",
122
+ "Sylvia Avondale",
123
+ "Nora Fayette",
124
+ "Helen Lloyd",
125
+ "Dorothy Murchison",
126
+ "Olivia Carleton",
127
+ "Flora Price",
128
+ ]
129
+ G.add_nodes_from(women, bipartite=0)
130
+ # Bottom nodes
131
+ events = [
132
+ "E1",
133
+ "E2",
134
+ "E3",
135
+ "E4",
136
+ "E5",
137
+ "E6",
138
+ "E7",
139
+ "E8",
140
+ "E9",
141
+ "E10",
142
+ "E11",
143
+ "E12",
144
+ "E13",
145
+ "E14",
146
+ ]
147
+ G.add_nodes_from(events, bipartite=1)
148
+
149
+ G.add_edges_from(
150
+ [
151
+ ("Evelyn Jefferson", "E1"),
152
+ ("Evelyn Jefferson", "E2"),
153
+ ("Evelyn Jefferson", "E3"),
154
+ ("Evelyn Jefferson", "E4"),
155
+ ("Evelyn Jefferson", "E5"),
156
+ ("Evelyn Jefferson", "E6"),
157
+ ("Evelyn Jefferson", "E8"),
158
+ ("Evelyn Jefferson", "E9"),
159
+ ("Laura Mandeville", "E1"),
160
+ ("Laura Mandeville", "E2"),
161
+ ("Laura Mandeville", "E3"),
162
+ ("Laura Mandeville", "E5"),
163
+ ("Laura Mandeville", "E6"),
164
+ ("Laura Mandeville", "E7"),
165
+ ("Laura Mandeville", "E8"),
166
+ ("Theresa Anderson", "E2"),
167
+ ("Theresa Anderson", "E3"),
168
+ ("Theresa Anderson", "E4"),
169
+ ("Theresa Anderson", "E5"),
170
+ ("Theresa Anderson", "E6"),
171
+ ("Theresa Anderson", "E7"),
172
+ ("Theresa Anderson", "E8"),
173
+ ("Theresa Anderson", "E9"),
174
+ ("Brenda Rogers", "E1"),
175
+ ("Brenda Rogers", "E3"),
176
+ ("Brenda Rogers", "E4"),
177
+ ("Brenda Rogers", "E5"),
178
+ ("Brenda Rogers", "E6"),
179
+ ("Brenda Rogers", "E7"),
180
+ ("Brenda Rogers", "E8"),
181
+ ("Charlotte McDowd", "E3"),
182
+ ("Charlotte McDowd", "E4"),
183
+ ("Charlotte McDowd", "E5"),
184
+ ("Charlotte McDowd", "E7"),
185
+ ("Frances Anderson", "E3"),
186
+ ("Frances Anderson", "E5"),
187
+ ("Frances Anderson", "E6"),
188
+ ("Frances Anderson", "E8"),
189
+ ("Eleanor Nye", "E5"),
190
+ ("Eleanor Nye", "E6"),
191
+ ("Eleanor Nye", "E7"),
192
+ ("Eleanor Nye", "E8"),
193
+ ("Pearl Oglethorpe", "E6"),
194
+ ("Pearl Oglethorpe", "E8"),
195
+ ("Pearl Oglethorpe", "E9"),
196
+ ("Ruth DeSand", "E5"),
197
+ ("Ruth DeSand", "E7"),
198
+ ("Ruth DeSand", "E8"),
199
+ ("Ruth DeSand", "E9"),
200
+ ("Verne Sanderson", "E7"),
201
+ ("Verne Sanderson", "E8"),
202
+ ("Verne Sanderson", "E9"),
203
+ ("Verne Sanderson", "E12"),
204
+ ("Myra Liddel", "E8"),
205
+ ("Myra Liddel", "E9"),
206
+ ("Myra Liddel", "E10"),
207
+ ("Myra Liddel", "E12"),
208
+ ("Katherina Rogers", "E8"),
209
+ ("Katherina Rogers", "E9"),
210
+ ("Katherina Rogers", "E10"),
211
+ ("Katherina Rogers", "E12"),
212
+ ("Katherina Rogers", "E13"),
213
+ ("Katherina Rogers", "E14"),
214
+ ("Sylvia Avondale", "E7"),
215
+ ("Sylvia Avondale", "E8"),
216
+ ("Sylvia Avondale", "E9"),
217
+ ("Sylvia Avondale", "E10"),
218
+ ("Sylvia Avondale", "E12"),
219
+ ("Sylvia Avondale", "E13"),
220
+ ("Sylvia Avondale", "E14"),
221
+ ("Nora Fayette", "E6"),
222
+ ("Nora Fayette", "E7"),
223
+ ("Nora Fayette", "E9"),
224
+ ("Nora Fayette", "E10"),
225
+ ("Nora Fayette", "E11"),
226
+ ("Nora Fayette", "E12"),
227
+ ("Nora Fayette", "E13"),
228
+ ("Nora Fayette", "E14"),
229
+ ("Helen Lloyd", "E7"),
230
+ ("Helen Lloyd", "E8"),
231
+ ("Helen Lloyd", "E10"),
232
+ ("Helen Lloyd", "E11"),
233
+ ("Helen Lloyd", "E12"),
234
+ ("Dorothy Murchison", "E8"),
235
+ ("Dorothy Murchison", "E9"),
236
+ ("Olivia Carleton", "E9"),
237
+ ("Olivia Carleton", "E11"),
238
+ ("Flora Price", "E9"),
239
+ ("Flora Price", "E11"),
240
+ ]
241
+ )
242
+ G.graph["top"] = women
243
+ G.graph["bottom"] = events
244
+ return G
245
+
246
+
247
+ @nx._dispatchable(graphs=None, returns_graph=True)
248
+ def florentine_families_graph():
249
+ """Returns Florentine families graph.
250
+
251
+ References
252
+ ----------
253
+ .. [1] Ronald L. Breiger and Philippa E. Pattison
254
+ Cumulated social roles: The duality of persons and their algebras,1
255
+ Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
256
+ """
257
+ G = nx.Graph()
258
+ G.add_edge("Acciaiuoli", "Medici")
259
+ G.add_edge("Castellani", "Peruzzi")
260
+ G.add_edge("Castellani", "Strozzi")
261
+ G.add_edge("Castellani", "Barbadori")
262
+ G.add_edge("Medici", "Barbadori")
263
+ G.add_edge("Medici", "Ridolfi")
264
+ G.add_edge("Medici", "Tornabuoni")
265
+ G.add_edge("Medici", "Albizzi")
266
+ G.add_edge("Medici", "Salviati")
267
+ G.add_edge("Salviati", "Pazzi")
268
+ G.add_edge("Peruzzi", "Strozzi")
269
+ G.add_edge("Peruzzi", "Bischeri")
270
+ G.add_edge("Strozzi", "Ridolfi")
271
+ G.add_edge("Strozzi", "Bischeri")
272
+ G.add_edge("Ridolfi", "Tornabuoni")
273
+ G.add_edge("Tornabuoni", "Guadagni")
274
+ G.add_edge("Albizzi", "Ginori")
275
+ G.add_edge("Albizzi", "Guadagni")
276
+ G.add_edge("Bischeri", "Guadagni")
277
+ G.add_edge("Guadagni", "Lamberteschi")
278
+ return G
279
+
280
+
281
+ @nx._dispatchable(graphs=None, returns_graph=True)
282
+ def les_miserables_graph():
283
+ """Returns coappearance network of characters in the novel Les Miserables.
284
+
285
+ References
286
+ ----------
287
+ .. [1] D. E. Knuth, 1993.
288
+ The Stanford GraphBase: a platform for combinatorial computing,
289
+ pp. 74-87. New York: AcM Press.
290
+ """
291
+ G = nx.Graph()
292
+ G.add_edge("Napoleon", "Myriel", weight=1)
293
+ G.add_edge("MlleBaptistine", "Myriel", weight=8)
294
+ G.add_edge("MmeMagloire", "Myriel", weight=10)
295
+ G.add_edge("MmeMagloire", "MlleBaptistine", weight=6)
296
+ G.add_edge("CountessDeLo", "Myriel", weight=1)
297
+ G.add_edge("Geborand", "Myriel", weight=1)
298
+ G.add_edge("Champtercier", "Myriel", weight=1)
299
+ G.add_edge("Cravatte", "Myriel", weight=1)
300
+ G.add_edge("Count", "Myriel", weight=2)
301
+ G.add_edge("OldMan", "Myriel", weight=1)
302
+ G.add_edge("Valjean", "Labarre", weight=1)
303
+ G.add_edge("Valjean", "MmeMagloire", weight=3)
304
+ G.add_edge("Valjean", "MlleBaptistine", weight=3)
305
+ G.add_edge("Valjean", "Myriel", weight=5)
306
+ G.add_edge("Marguerite", "Valjean", weight=1)
307
+ G.add_edge("MmeDeR", "Valjean", weight=1)
308
+ G.add_edge("Isabeau", "Valjean", weight=1)
309
+ G.add_edge("Gervais", "Valjean", weight=1)
310
+ G.add_edge("Listolier", "Tholomyes", weight=4)
311
+ G.add_edge("Fameuil", "Tholomyes", weight=4)
312
+ G.add_edge("Fameuil", "Listolier", weight=4)
313
+ G.add_edge("Blacheville", "Tholomyes", weight=4)
314
+ G.add_edge("Blacheville", "Listolier", weight=4)
315
+ G.add_edge("Blacheville", "Fameuil", weight=4)
316
+ G.add_edge("Favourite", "Tholomyes", weight=3)
317
+ G.add_edge("Favourite", "Listolier", weight=3)
318
+ G.add_edge("Favourite", "Fameuil", weight=3)
319
+ G.add_edge("Favourite", "Blacheville", weight=4)
320
+ G.add_edge("Dahlia", "Tholomyes", weight=3)
321
+ G.add_edge("Dahlia", "Listolier", weight=3)
322
+ G.add_edge("Dahlia", "Fameuil", weight=3)
323
+ G.add_edge("Dahlia", "Blacheville", weight=3)
324
+ G.add_edge("Dahlia", "Favourite", weight=5)
325
+ G.add_edge("Zephine", "Tholomyes", weight=3)
326
+ G.add_edge("Zephine", "Listolier", weight=3)
327
+ G.add_edge("Zephine", "Fameuil", weight=3)
328
+ G.add_edge("Zephine", "Blacheville", weight=3)
329
+ G.add_edge("Zephine", "Favourite", weight=4)
330
+ G.add_edge("Zephine", "Dahlia", weight=4)
331
+ G.add_edge("Fantine", "Tholomyes", weight=3)
332
+ G.add_edge("Fantine", "Listolier", weight=3)
333
+ G.add_edge("Fantine", "Fameuil", weight=3)
334
+ G.add_edge("Fantine", "Blacheville", weight=3)
335
+ G.add_edge("Fantine", "Favourite", weight=4)
336
+ G.add_edge("Fantine", "Dahlia", weight=4)
337
+ G.add_edge("Fantine", "Zephine", weight=4)
338
+ G.add_edge("Fantine", "Marguerite", weight=2)
339
+ G.add_edge("Fantine", "Valjean", weight=9)
340
+ G.add_edge("MmeThenardier", "Fantine", weight=2)
341
+ G.add_edge("MmeThenardier", "Valjean", weight=7)
342
+ G.add_edge("Thenardier", "MmeThenardier", weight=13)
343
+ G.add_edge("Thenardier", "Fantine", weight=1)
344
+ G.add_edge("Thenardier", "Valjean", weight=12)
345
+ G.add_edge("Cosette", "MmeThenardier", weight=4)
346
+ G.add_edge("Cosette", "Valjean", weight=31)
347
+ G.add_edge("Cosette", "Tholomyes", weight=1)
348
+ G.add_edge("Cosette", "Thenardier", weight=1)
349
+ G.add_edge("Javert", "Valjean", weight=17)
350
+ G.add_edge("Javert", "Fantine", weight=5)
351
+ G.add_edge("Javert", "Thenardier", weight=5)
352
+ G.add_edge("Javert", "MmeThenardier", weight=1)
353
+ G.add_edge("Javert", "Cosette", weight=1)
354
+ G.add_edge("Fauchelevent", "Valjean", weight=8)
355
+ G.add_edge("Fauchelevent", "Javert", weight=1)
356
+ G.add_edge("Bamatabois", "Fantine", weight=1)
357
+ G.add_edge("Bamatabois", "Javert", weight=1)
358
+ G.add_edge("Bamatabois", "Valjean", weight=2)
359
+ G.add_edge("Perpetue", "Fantine", weight=1)
360
+ G.add_edge("Simplice", "Perpetue", weight=2)
361
+ G.add_edge("Simplice", "Valjean", weight=3)
362
+ G.add_edge("Simplice", "Fantine", weight=2)
363
+ G.add_edge("Simplice", "Javert", weight=1)
364
+ G.add_edge("Scaufflaire", "Valjean", weight=1)
365
+ G.add_edge("Woman1", "Valjean", weight=2)
366
+ G.add_edge("Woman1", "Javert", weight=1)
367
+ G.add_edge("Judge", "Valjean", weight=3)
368
+ G.add_edge("Judge", "Bamatabois", weight=2)
369
+ G.add_edge("Champmathieu", "Valjean", weight=3)
370
+ G.add_edge("Champmathieu", "Judge", weight=3)
371
+ G.add_edge("Champmathieu", "Bamatabois", weight=2)
372
+ G.add_edge("Brevet", "Judge", weight=2)
373
+ G.add_edge("Brevet", "Champmathieu", weight=2)
374
+ G.add_edge("Brevet", "Valjean", weight=2)
375
+ G.add_edge("Brevet", "Bamatabois", weight=1)
376
+ G.add_edge("Chenildieu", "Judge", weight=2)
377
+ G.add_edge("Chenildieu", "Champmathieu", weight=2)
378
+ G.add_edge("Chenildieu", "Brevet", weight=2)
379
+ G.add_edge("Chenildieu", "Valjean", weight=2)
380
+ G.add_edge("Chenildieu", "Bamatabois", weight=1)
381
+ G.add_edge("Cochepaille", "Judge", weight=2)
382
+ G.add_edge("Cochepaille", "Champmathieu", weight=2)
383
+ G.add_edge("Cochepaille", "Brevet", weight=2)
384
+ G.add_edge("Cochepaille", "Chenildieu", weight=2)
385
+ G.add_edge("Cochepaille", "Valjean", weight=2)
386
+ G.add_edge("Cochepaille", "Bamatabois", weight=1)
387
+ G.add_edge("Pontmercy", "Thenardier", weight=1)
388
+ G.add_edge("Boulatruelle", "Thenardier", weight=1)
389
+ G.add_edge("Eponine", "MmeThenardier", weight=2)
390
+ G.add_edge("Eponine", "Thenardier", weight=3)
391
+ G.add_edge("Anzelma", "Eponine", weight=2)
392
+ G.add_edge("Anzelma", "Thenardier", weight=2)
393
+ G.add_edge("Anzelma", "MmeThenardier", weight=1)
394
+ G.add_edge("Woman2", "Valjean", weight=3)
395
+ G.add_edge("Woman2", "Cosette", weight=1)
396
+ G.add_edge("Woman2", "Javert", weight=1)
397
+ G.add_edge("MotherInnocent", "Fauchelevent", weight=3)
398
+ G.add_edge("MotherInnocent", "Valjean", weight=1)
399
+ G.add_edge("Gribier", "Fauchelevent", weight=2)
400
+ G.add_edge("MmeBurgon", "Jondrette", weight=1)
401
+ G.add_edge("Gavroche", "MmeBurgon", weight=2)
402
+ G.add_edge("Gavroche", "Thenardier", weight=1)
403
+ G.add_edge("Gavroche", "Javert", weight=1)
404
+ G.add_edge("Gavroche", "Valjean", weight=1)
405
+ G.add_edge("Gillenormand", "Cosette", weight=3)
406
+ G.add_edge("Gillenormand", "Valjean", weight=2)
407
+ G.add_edge("Magnon", "Gillenormand", weight=1)
408
+ G.add_edge("Magnon", "MmeThenardier", weight=1)
409
+ G.add_edge("MlleGillenormand", "Gillenormand", weight=9)
410
+ G.add_edge("MlleGillenormand", "Cosette", weight=2)
411
+ G.add_edge("MlleGillenormand", "Valjean", weight=2)
412
+ G.add_edge("MmePontmercy", "MlleGillenormand", weight=1)
413
+ G.add_edge("MmePontmercy", "Pontmercy", weight=1)
414
+ G.add_edge("MlleVaubois", "MlleGillenormand", weight=1)
415
+ G.add_edge("LtGillenormand", "MlleGillenormand", weight=2)
416
+ G.add_edge("LtGillenormand", "Gillenormand", weight=1)
417
+ G.add_edge("LtGillenormand", "Cosette", weight=1)
418
+ G.add_edge("Marius", "MlleGillenormand", weight=6)
419
+ G.add_edge("Marius", "Gillenormand", weight=12)
420
+ G.add_edge("Marius", "Pontmercy", weight=1)
421
+ G.add_edge("Marius", "LtGillenormand", weight=1)
422
+ G.add_edge("Marius", "Cosette", weight=21)
423
+ G.add_edge("Marius", "Valjean", weight=19)
424
+ G.add_edge("Marius", "Tholomyes", weight=1)
425
+ G.add_edge("Marius", "Thenardier", weight=2)
426
+ G.add_edge("Marius", "Eponine", weight=5)
427
+ G.add_edge("Marius", "Gavroche", weight=4)
428
+ G.add_edge("BaronessT", "Gillenormand", weight=1)
429
+ G.add_edge("BaronessT", "Marius", weight=1)
430
+ G.add_edge("Mabeuf", "Marius", weight=1)
431
+ G.add_edge("Mabeuf", "Eponine", weight=1)
432
+ G.add_edge("Mabeuf", "Gavroche", weight=1)
433
+ G.add_edge("Enjolras", "Marius", weight=7)
434
+ G.add_edge("Enjolras", "Gavroche", weight=7)
435
+ G.add_edge("Enjolras", "Javert", weight=6)
436
+ G.add_edge("Enjolras", "Mabeuf", weight=1)
437
+ G.add_edge("Enjolras", "Valjean", weight=4)
438
+ G.add_edge("Combeferre", "Enjolras", weight=15)
439
+ G.add_edge("Combeferre", "Marius", weight=5)
440
+ G.add_edge("Combeferre", "Gavroche", weight=6)
441
+ G.add_edge("Combeferre", "Mabeuf", weight=2)
442
+ G.add_edge("Prouvaire", "Gavroche", weight=1)
443
+ G.add_edge("Prouvaire", "Enjolras", weight=4)
444
+ G.add_edge("Prouvaire", "Combeferre", weight=2)
445
+ G.add_edge("Feuilly", "Gavroche", weight=2)
446
+ G.add_edge("Feuilly", "Enjolras", weight=6)
447
+ G.add_edge("Feuilly", "Prouvaire", weight=2)
448
+ G.add_edge("Feuilly", "Combeferre", weight=5)
449
+ G.add_edge("Feuilly", "Mabeuf", weight=1)
450
+ G.add_edge("Feuilly", "Marius", weight=1)
451
+ G.add_edge("Courfeyrac", "Marius", weight=9)
452
+ G.add_edge("Courfeyrac", "Enjolras", weight=17)
453
+ G.add_edge("Courfeyrac", "Combeferre", weight=13)
454
+ G.add_edge("Courfeyrac", "Gavroche", weight=7)
455
+ G.add_edge("Courfeyrac", "Mabeuf", weight=2)
456
+ G.add_edge("Courfeyrac", "Eponine", weight=1)
457
+ G.add_edge("Courfeyrac", "Feuilly", weight=6)
458
+ G.add_edge("Courfeyrac", "Prouvaire", weight=3)
459
+ G.add_edge("Bahorel", "Combeferre", weight=5)
460
+ G.add_edge("Bahorel", "Gavroche", weight=5)
461
+ G.add_edge("Bahorel", "Courfeyrac", weight=6)
462
+ G.add_edge("Bahorel", "Mabeuf", weight=2)
463
+ G.add_edge("Bahorel", "Enjolras", weight=4)
464
+ G.add_edge("Bahorel", "Feuilly", weight=3)
465
+ G.add_edge("Bahorel", "Prouvaire", weight=2)
466
+ G.add_edge("Bahorel", "Marius", weight=1)
467
+ G.add_edge("Bossuet", "Marius", weight=5)
468
+ G.add_edge("Bossuet", "Courfeyrac", weight=12)
469
+ G.add_edge("Bossuet", "Gavroche", weight=5)
470
+ G.add_edge("Bossuet", "Bahorel", weight=4)
471
+ G.add_edge("Bossuet", "Enjolras", weight=10)
472
+ G.add_edge("Bossuet", "Feuilly", weight=6)
473
+ G.add_edge("Bossuet", "Prouvaire", weight=2)
474
+ G.add_edge("Bossuet", "Combeferre", weight=9)
475
+ G.add_edge("Bossuet", "Mabeuf", weight=1)
476
+ G.add_edge("Bossuet", "Valjean", weight=1)
477
+ G.add_edge("Joly", "Bahorel", weight=5)
478
+ G.add_edge("Joly", "Bossuet", weight=7)
479
+ G.add_edge("Joly", "Gavroche", weight=3)
480
+ G.add_edge("Joly", "Courfeyrac", weight=5)
481
+ G.add_edge("Joly", "Enjolras", weight=5)
482
+ G.add_edge("Joly", "Feuilly", weight=5)
483
+ G.add_edge("Joly", "Prouvaire", weight=2)
484
+ G.add_edge("Joly", "Combeferre", weight=5)
485
+ G.add_edge("Joly", "Mabeuf", weight=1)
486
+ G.add_edge("Joly", "Marius", weight=2)
487
+ G.add_edge("Grantaire", "Bossuet", weight=3)
488
+ G.add_edge("Grantaire", "Enjolras", weight=3)
489
+ G.add_edge("Grantaire", "Combeferre", weight=1)
490
+ G.add_edge("Grantaire", "Courfeyrac", weight=2)
491
+ G.add_edge("Grantaire", "Joly", weight=2)
492
+ G.add_edge("Grantaire", "Gavroche", weight=1)
493
+ G.add_edge("Grantaire", "Bahorel", weight=1)
494
+ G.add_edge("Grantaire", "Feuilly", weight=1)
495
+ G.add_edge("Grantaire", "Prouvaire", weight=1)
496
+ G.add_edge("MotherPlutarch", "Mabeuf", weight=3)
497
+ G.add_edge("Gueulemer", "Thenardier", weight=5)
498
+ G.add_edge("Gueulemer", "Valjean", weight=1)
499
+ G.add_edge("Gueulemer", "MmeThenardier", weight=1)
500
+ G.add_edge("Gueulemer", "Javert", weight=1)
501
+ G.add_edge("Gueulemer", "Gavroche", weight=1)
502
+ G.add_edge("Gueulemer", "Eponine", weight=1)
503
+ G.add_edge("Babet", "Thenardier", weight=6)
504
+ G.add_edge("Babet", "Gueulemer", weight=6)
505
+ G.add_edge("Babet", "Valjean", weight=1)
506
+ G.add_edge("Babet", "MmeThenardier", weight=1)
507
+ G.add_edge("Babet", "Javert", weight=2)
508
+ G.add_edge("Babet", "Gavroche", weight=1)
509
+ G.add_edge("Babet", "Eponine", weight=1)
510
+ G.add_edge("Claquesous", "Thenardier", weight=4)
511
+ G.add_edge("Claquesous", "Babet", weight=4)
512
+ G.add_edge("Claquesous", "Gueulemer", weight=4)
513
+ G.add_edge("Claquesous", "Valjean", weight=1)
514
+ G.add_edge("Claquesous", "MmeThenardier", weight=1)
515
+ G.add_edge("Claquesous", "Javert", weight=1)
516
+ G.add_edge("Claquesous", "Eponine", weight=1)
517
+ G.add_edge("Claquesous", "Enjolras", weight=1)
518
+ G.add_edge("Montparnasse", "Javert", weight=1)
519
+ G.add_edge("Montparnasse", "Babet", weight=2)
520
+ G.add_edge("Montparnasse", "Gueulemer", weight=2)
521
+ G.add_edge("Montparnasse", "Claquesous", weight=2)
522
+ G.add_edge("Montparnasse", "Valjean", weight=1)
523
+ G.add_edge("Montparnasse", "Gavroche", weight=1)
524
+ G.add_edge("Montparnasse", "Eponine", weight=1)
525
+ G.add_edge("Montparnasse", "Thenardier", weight=1)
526
+ G.add_edge("Toussaint", "Cosette", weight=2)
527
+ G.add_edge("Toussaint", "Javert", weight=1)
528
+ G.add_edge("Toussaint", "Valjean", weight=1)
529
+ G.add_edge("Child1", "Gavroche", weight=2)
530
+ G.add_edge("Child2", "Gavroche", weight=2)
531
+ G.add_edge("Child2", "Child1", weight=3)
532
+ G.add_edge("Brujon", "Babet", weight=3)
533
+ G.add_edge("Brujon", "Gueulemer", weight=3)
534
+ G.add_edge("Brujon", "Thenardier", weight=3)
535
+ G.add_edge("Brujon", "Gavroche", weight=1)
536
+ G.add_edge("Brujon", "Eponine", weight=1)
537
+ G.add_edge("Brujon", "Claquesous", weight=1)
538
+ G.add_edge("Brujon", "Montparnasse", weight=1)
539
+ G.add_edge("MmeHucheloup", "Bossuet", weight=1)
540
+ G.add_edge("MmeHucheloup", "Joly", weight=1)
541
+ G.add_edge("MmeHucheloup", "Grantaire", weight=1)
542
+ G.add_edge("MmeHucheloup", "Bahorel", weight=1)
543
+ G.add_edge("MmeHucheloup", "Courfeyrac", weight=1)
544
+ G.add_edge("MmeHucheloup", "Gavroche", weight=1)
545
+ G.add_edge("MmeHucheloup", "Enjolras", weight=1)
546
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/spectral_graph_forge.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates graphs with a given eigenvector structure"""
2
+
3
+
4
+ import networkx as nx
5
+ from networkx.utils import np_random_state
6
+
7
+ __all__ = ["spectral_graph_forge"]
8
+
9
+
10
+ @np_random_state(3)
11
+ @nx._dispatchable(returns_graph=True)
12
+ def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
13
+ """Returns a random simple graph with spectrum resembling that of `G`
14
+
15
+ This algorithm, called Spectral Graph Forge (SGF), computes the
16
+ eigenvectors of a given graph adjacency matrix, filters them and
17
+ builds a random graph with a similar eigenstructure.
18
+ SGF has been proved to be particularly useful for synthesizing
19
+ realistic social networks and it can also be used to anonymize
20
+ graph sensitive data.
21
+
22
+ Parameters
23
+ ----------
24
+ G : Graph
25
+ alpha : float
26
+ Ratio representing the percentage of eigenvectors of G to consider,
27
+ values in [0,1].
28
+ transformation : string, optional
29
+ Represents the intended matrix linear transformation, possible values
30
+ are 'identity' and 'modularity'
31
+ seed : integer, random_state, or None (default)
32
+ Indicator of numpy random number generation state.
33
+ See :ref:`Randomness<randomness>`.
34
+
35
+ Returns
36
+ -------
37
+ H : Graph
38
+ A graph with a similar eigenvector structure of the input one.
39
+
40
+ Raises
41
+ ------
42
+ NetworkXError
43
+ If transformation has a value different from 'identity' or 'modularity'
44
+
45
+ Notes
46
+ -----
47
+ Spectral Graph Forge (SGF) generates a random simple graph resembling the
48
+ global properties of the given one.
49
+ It leverages the low-rank approximation of the associated adjacency matrix
50
+ driven by the *alpha* precision parameter.
51
+ SGF preserves the number of nodes of the input graph and their ordering.
52
+ This way, nodes of output graphs resemble the properties of the input one
53
+ and attributes can be directly mapped.
54
+
55
+ It considers the graph adjacency matrices which can optionally be
56
+ transformed to other symmetric real matrices (currently transformation
57
+ options include *identity* and *modularity*).
58
+ The *modularity* transformation, in the sense of Newman's modularity matrix
59
+ allows the focusing on community structure related properties of the graph.
60
+
61
+ SGF applies a low-rank approximation whose fixed rank is computed from the
62
+ ratio *alpha* of the input graph adjacency matrix dimension.
63
+ This step performs a filtering on the input eigenvectors similar to the low
64
+ pass filtering common in telecommunications.
65
+
66
+ The filtered values (after truncation) are used as input to a Bernoulli
67
+ sampling for constructing a random adjacency matrix.
68
+
69
+ References
70
+ ----------
71
+ .. [1] L. Baldesi, C. T. Butts, A. Markopoulou, "Spectral Graph Forge:
72
+ Graph Generation Targeting Modularity", IEEE Infocom, '18.
73
+ https://arxiv.org/abs/1801.01715
74
+ .. [2] M. Newman, "Networks: an introduction", Oxford university press,
75
+ 2010
76
+
77
+ Examples
78
+ --------
79
+ >>> G = nx.karate_club_graph()
80
+ >>> H = nx.spectral_graph_forge(G, 0.3)
81
+ >>>
82
+ """
83
+ import numpy as np
84
+ import scipy as sp
85
+
86
+ available_transformations = ["identity", "modularity"]
87
+ alpha = np.clip(alpha, 0, 1)
88
+ A = nx.to_numpy_array(G)
89
+ n = A.shape[1]
90
+ level = round(n * alpha)
91
+
92
+ if transformation not in available_transformations:
93
+ msg = f"{transformation!r} is not a valid transformation. "
94
+ msg += f"Transformations: {available_transformations}"
95
+ raise nx.NetworkXError(msg)
96
+
97
+ K = np.ones((1, n)) @ A
98
+
99
+ B = A
100
+ if transformation == "modularity":
101
+ B -= K.T @ K / K.sum()
102
+
103
+ # Compute low-rank approximation of B
104
+ evals, evecs = np.linalg.eigh(B)
105
+ k = np.argsort(np.abs(evals))[::-1] # indices of evals in descending order
106
+ evecs[:, k[np.arange(level, n)]] = 0 # set smallest eigenvectors to 0
107
+ B = evecs @ np.diag(evals) @ evecs.T
108
+
109
+ if transformation == "modularity":
110
+ B += K.T @ K / K.sum()
111
+
112
+ B = np.clip(B, 0, 1)
113
+ np.fill_diagonal(B, 0)
114
+
115
+ for i in range(n - 1):
116
+ B[i, i + 1 :] = sp.stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed)
117
+ B[i + 1 :, i] = np.transpose(B[i, i + 1 :])
118
+
119
+ H = nx.from_numpy_array(B)
120
+
121
+ return H
env-llmeval/lib/python3.10/site-packages/networkx/generators/stochastic.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating stochastic graphs from a given weighted directed
2
+ graph.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.classes import DiGraph, MultiDiGraph
8
+ from networkx.utils import not_implemented_for
9
+
10
+ __all__ = ["stochastic_graph"]
11
+
12
+
13
+ @not_implemented_for("undirected")
14
+ @nx._dispatchable(
15
+ edge_attrs="weight", mutates_input={"not copy": 1}, returns_graph=True
16
+ )
17
+ def stochastic_graph(G, copy=True, weight="weight"):
18
+ """Returns a right-stochastic representation of directed graph `G`.
19
+
20
+ A right-stochastic graph is a weighted digraph in which for each
21
+ node, the sum of the weights of all the out-edges of that node is
22
+ 1. If the graph is already weighted (for example, via a 'weight'
23
+ edge attribute), the reweighting takes that into account.
24
+
25
+ Parameters
26
+ ----------
27
+ G : directed graph
28
+ A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.
29
+
30
+ copy : boolean, optional
31
+ If this is True, then this function returns a new graph with
32
+ the stochastic reweighting. Otherwise, the original graph is
33
+ modified in-place (and also returned, for convenience).
34
+
35
+ weight : edge attribute key (optional, default='weight')
36
+ Edge attribute key used for reading the existing weight and
37
+ setting the new weight. If no attribute with this key is found
38
+ for an edge, then the edge weight is assumed to be 1. If an edge
39
+ has a weight, it must be a positive number.
40
+
41
+ """
42
+ if copy:
43
+ G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
44
+ # There is a tradeoff here: the dictionary of node degrees may
45
+ # require a lot of memory, whereas making a call to `G.out_degree`
46
+ # inside the loop may be costly in computation time.
47
+ degree = dict(G.out_degree(weight=weight))
48
+ for u, v, d in G.edges(data=True):
49
+ if degree[u] == 0:
50
+ d[weight] = 0
51
+ else:
52
+ d[weight] = d.get(weight, 1) / degree[u]
53
+ nx._clear_cache(G)
54
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/sudoku.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generator for Sudoku graphs
2
+
3
+ This module gives a generator for n-Sudoku graphs. It can be used to develop
4
+ algorithms for solving or generating Sudoku puzzles.
5
+
6
+ A completed Sudoku grid is a 9x9 array of integers between 1 and 9, with no
7
+ number appearing twice in the same row, column, or 3x3 box.
8
+
9
+ +---------+---------+---------+
10
+ | | 8 6 4 | | 3 7 1 | | 2 5 9 |
11
+ | | 3 2 5 | | 8 4 9 | | 7 6 1 |
12
+ | | 9 7 1 | | 2 6 5 | | 8 4 3 |
13
+ +---------+---------+---------+
14
+ | | 4 3 6 | | 1 9 2 | | 5 8 7 |
15
+ | | 1 9 8 | | 6 5 7 | | 4 3 2 |
16
+ | | 2 5 7 | | 4 8 3 | | 9 1 6 |
17
+ +---------+---------+---------+
18
+ | | 6 8 9 | | 7 3 4 | | 1 2 5 |
19
+ | | 7 1 3 | | 5 2 8 | | 6 9 4 |
20
+ | | 5 4 2 | | 9 1 6 | | 3 7 8 |
21
+ +---------+---------+---------+
22
+
23
+
24
+ The Sudoku graph is an undirected graph with 81 vertices, corresponding to
25
+ the cells of a Sudoku grid. It is a regular graph of degree 20. Two distinct
26
+ vertices are adjacent if and only if the corresponding cells belong to the
27
+ same row, column, or box. A completed Sudoku grid corresponds to a vertex
28
+ coloring of the Sudoku graph with nine colors.
29
+
30
+ More generally, the n-Sudoku graph is a graph with n^4 vertices, corresponding
31
+ to the cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
32
+ only if they belong to the same row, column, or n by n box.
33
+
34
+ References
35
+ ----------
36
+ .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
37
+ polynomials. Notices of the AMS, 54(6), 708-717.
38
+ .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
39
+ Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
40
+ .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
41
+ Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
42
+ """
43
+
44
+ import networkx as nx
45
+ from networkx.exception import NetworkXError
46
+
47
+ __all__ = ["sudoku_graph"]
48
+
49
+
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def sudoku_graph(n=3):
52
+ """Returns the n-Sudoku graph. The default value of n is 3.
53
+
54
+ The n-Sudoku graph is a graph with n^4 vertices, corresponding to the
55
+ cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and
56
+ only if they belong to the same row, column, or n-by-n box.
57
+
58
+ Parameters
59
+ ----------
60
+ n: integer
61
+ The order of the Sudoku graph, equal to the square root of the
62
+ number of rows. The default is 3.
63
+
64
+ Returns
65
+ -------
66
+ NetworkX graph
67
+ The n-Sudoku graph Sud(n).
68
+
69
+ Examples
70
+ --------
71
+ >>> G = nx.sudoku_graph()
72
+ >>> G.number_of_nodes()
73
+ 81
74
+ >>> G.number_of_edges()
75
+ 810
76
+ >>> sorted(G.neighbors(42))
77
+ [6, 15, 24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 51, 52, 53, 60, 69, 78]
78
+ >>> G = nx.sudoku_graph(2)
79
+ >>> G.number_of_nodes()
80
+ 16
81
+ >>> G.number_of_edges()
82
+ 56
83
+
84
+ References
85
+ ----------
86
+ .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic
87
+ polynomials. Notices of the AMS, 54(6), 708-717.
88
+ .. [2] Sander, Torsten (2009), "Sudoku graphs are integral",
89
+ Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816
90
+ .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free
91
+ Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
92
+ """
93
+
94
+ if n < 0:
95
+ raise NetworkXError("The order must be greater than or equal to zero.")
96
+
97
+ n2 = n * n
98
+ n3 = n2 * n
99
+ n4 = n3 * n
100
+
101
+ # Construct an empty graph with n^4 nodes
102
+ G = nx.empty_graph(n4)
103
+
104
+ # A Sudoku graph of order 0 or 1 has no edges
105
+ if n < 2:
106
+ return G
107
+
108
+ # Add edges for cells in the same row
109
+ for row_no in range(n2):
110
+ row_start = row_no * n2
111
+ for j in range(1, n2):
112
+ for i in range(j):
113
+ G.add_edge(row_start + i, row_start + j)
114
+
115
+ # Add edges for cells in the same column
116
+ for col_no in range(n2):
117
+ for j in range(col_no, n4, n2):
118
+ for i in range(col_no, j, n2):
119
+ G.add_edge(i, j)
120
+
121
+ # Add edges for cells in the same box
122
+ for band_no in range(n):
123
+ for stack_no in range(n):
124
+ box_start = n3 * band_no + n * stack_no
125
+ for j in range(1, n2):
126
+ for i in range(j):
127
+ u = box_start + (i % n) + n2 * (i // n)
128
+ v = box_start + (j % n) + n2 * (j // n)
129
+ G.add_edge(u, v)
130
+
131
+ return G
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_atlas.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import groupby
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx import graph_atlas, graph_atlas_g
7
+ from networkx.generators.atlas import NUM_GRAPHS
8
+ from networkx.utils import edges_equal, nodes_equal, pairwise
9
+
10
+
11
+ class TestAtlasGraph:
12
+ """Unit tests for the :func:`~networkx.graph_atlas` function."""
13
+
14
+ def test_index_too_small(self):
15
+ with pytest.raises(ValueError):
16
+ graph_atlas(-1)
17
+
18
+ def test_index_too_large(self):
19
+ with pytest.raises(ValueError):
20
+ graph_atlas(NUM_GRAPHS)
21
+
22
+ def test_graph(self):
23
+ G = graph_atlas(6)
24
+ assert nodes_equal(G.nodes(), range(3))
25
+ assert edges_equal(G.edges(), [(0, 1), (0, 2)])
26
+
27
+
28
+ class TestAtlasGraphG:
29
+ """Unit tests for the :func:`~networkx.graph_atlas_g` function."""
30
+
31
+ @classmethod
32
+ def setup_class(cls):
33
+ cls.GAG = graph_atlas_g()
34
+
35
+ def test_sizes(self):
36
+ G = self.GAG[0]
37
+ assert G.number_of_nodes() == 0
38
+ assert G.number_of_edges() == 0
39
+
40
+ G = self.GAG[7]
41
+ assert G.number_of_nodes() == 3
42
+ assert G.number_of_edges() == 3
43
+
44
+ def test_names(self):
45
+ for i, G in enumerate(self.GAG):
46
+ assert int(G.name[1:]) == i
47
+
48
+ def test_nondecreasing_nodes(self):
49
+ # check for nondecreasing number of nodes
50
+ for n1, n2 in pairwise(map(len, self.GAG)):
51
+ assert n2 <= n1 + 1
52
+
53
+ def test_nondecreasing_edges(self):
54
+ # check for nondecreasing number of edges (for fixed number of
55
+ # nodes)
56
+ for n, group in groupby(self.GAG, key=nx.number_of_nodes):
57
+ for m1, m2 in pairwise(map(nx.number_of_edges, group)):
58
+ assert m2 <= m1 + 1
59
+
60
+ def test_nondecreasing_degree_sequence(self):
61
+ # Check for lexicographically nondecreasing degree sequences
62
+ # (for fixed number of nodes and edges).
63
+ #
64
+ # There are three exceptions to this rule in the order given in
65
+ # the "Atlas of Graphs" book, so we need to manually exclude
66
+ # those.
67
+ exceptions = [("G55", "G56"), ("G1007", "G1008"), ("G1012", "G1013")]
68
+ for n, group in groupby(self.GAG, key=nx.number_of_nodes):
69
+ for m, group in groupby(group, key=nx.number_of_edges):
70
+ for G1, G2 in pairwise(group):
71
+ if (G1.name, G2.name) in exceptions:
72
+ continue
73
+ d1 = sorted(d for v, d in G1.degree())
74
+ d2 = sorted(d for v, d in G2.degree())
75
+ assert d1 <= d2
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_classic.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ====================
3
+ Generators - Classic
4
+ ====================
5
+
6
+ Unit tests for various classic graph generators in generators/classic.py
7
+ """
8
+ import itertools
9
+ import typing
10
+
11
+ import pytest
12
+
13
+ import networkx as nx
14
+ from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic
15
+ from networkx.utils import edges_equal, nodes_equal
16
+
17
+ is_isomorphic = graph_could_be_isomorphic
18
+
19
+
20
+ class TestGeneratorClassic:
21
+ def test_balanced_tree(self):
22
+ # balanced_tree(r,h) is a tree with (r**(h+1)-1)/(r-1) edges
23
+ for r, h in [(2, 2), (3, 3), (6, 2)]:
24
+ t = nx.balanced_tree(r, h)
25
+ order = t.order()
26
+ assert order == (r ** (h + 1) - 1) / (r - 1)
27
+ assert nx.is_connected(t)
28
+ assert t.size() == order - 1
29
+ dh = nx.degree_histogram(t)
30
+ assert dh[0] == 0 # no nodes of 0
31
+ assert dh[1] == r**h # nodes of degree 1 are leaves
32
+ assert dh[r] == 1 # root is degree r
33
+ assert dh[r + 1] == order - r**h - 1 # everyone else is degree r+1
34
+ assert len(dh) == r + 2
35
+
36
+ def test_balanced_tree_star(self):
37
+ # balanced_tree(r,1) is the r-star
38
+ t = nx.balanced_tree(r=2, h=1)
39
+ assert is_isomorphic(t, nx.star_graph(2))
40
+ t = nx.balanced_tree(r=5, h=1)
41
+ assert is_isomorphic(t, nx.star_graph(5))
42
+ t = nx.balanced_tree(r=10, h=1)
43
+ assert is_isomorphic(t, nx.star_graph(10))
44
+
45
+ def test_balanced_tree_path(self):
46
+ """Tests that the balanced tree with branching factor one is the
47
+ path graph.
48
+
49
+ """
50
+ # A tree of height four has five levels.
51
+ T = nx.balanced_tree(1, 4)
52
+ P = nx.path_graph(5)
53
+ assert is_isomorphic(T, P)
54
+
55
+ def test_full_rary_tree(self):
56
+ r = 2
57
+ n = 9
58
+ t = nx.full_rary_tree(r, n)
59
+ assert t.order() == n
60
+ assert nx.is_connected(t)
61
+ dh = nx.degree_histogram(t)
62
+ assert dh[0] == 0 # no nodes of 0
63
+ assert dh[1] == 5 # nodes of degree 1 are leaves
64
+ assert dh[r] == 1 # root is degree r
65
+ assert dh[r + 1] == 9 - 5 - 1 # everyone else is degree r+1
66
+ assert len(dh) == r + 2
67
+
68
+ def test_full_rary_tree_balanced(self):
69
+ t = nx.full_rary_tree(2, 15)
70
+ th = nx.balanced_tree(2, 3)
71
+ assert is_isomorphic(t, th)
72
+
73
+ def test_full_rary_tree_path(self):
74
+ t = nx.full_rary_tree(1, 10)
75
+ assert is_isomorphic(t, nx.path_graph(10))
76
+
77
+ def test_full_rary_tree_empty(self):
78
+ t = nx.full_rary_tree(0, 10)
79
+ assert is_isomorphic(t, nx.empty_graph(10))
80
+ t = nx.full_rary_tree(3, 0)
81
+ assert is_isomorphic(t, nx.empty_graph(0))
82
+
83
+ def test_full_rary_tree_3_20(self):
84
+ t = nx.full_rary_tree(3, 20)
85
+ assert t.order() == 20
86
+
87
+ def test_barbell_graph(self):
88
+ # number of nodes = 2*m1 + m2 (2 m1-complete graphs + m2-path + 2 edges)
89
+ # number of edges = 2*(nx.number_of_edges(m1-complete graph) + m2 + 1
90
+ m1 = 3
91
+ m2 = 5
92
+ b = nx.barbell_graph(m1, m2)
93
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
94
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
95
+
96
+ m1 = 4
97
+ m2 = 10
98
+ b = nx.barbell_graph(m1, m2)
99
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
100
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
101
+
102
+ m1 = 3
103
+ m2 = 20
104
+ b = nx.barbell_graph(m1, m2)
105
+ assert nx.number_of_nodes(b) == 2 * m1 + m2
106
+ assert nx.number_of_edges(b) == m1 * (m1 - 1) + m2 + 1
107
+
108
+ # Raise NetworkXError if m1<2
109
+ m1 = 1
110
+ m2 = 20
111
+ pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
112
+
113
+ # Raise NetworkXError if m2<0
114
+ m1 = 5
115
+ m2 = -2
116
+ pytest.raises(nx.NetworkXError, nx.barbell_graph, m1, m2)
117
+
118
+ # nx.barbell_graph(2,m) = nx.path_graph(m+4)
119
+ m1 = 2
120
+ m2 = 5
121
+ b = nx.barbell_graph(m1, m2)
122
+ assert is_isomorphic(b, nx.path_graph(m2 + 4))
123
+
124
+ m1 = 2
125
+ m2 = 10
126
+ b = nx.barbell_graph(m1, m2)
127
+ assert is_isomorphic(b, nx.path_graph(m2 + 4))
128
+
129
+ m1 = 2
130
+ m2 = 20
131
+ b = nx.barbell_graph(m1, m2)
132
+ assert is_isomorphic(b, nx.path_graph(m2 + 4))
133
+
134
+ pytest.raises(
135
+ nx.NetworkXError, nx.barbell_graph, m1, m2, create_using=nx.DiGraph()
136
+ )
137
+
138
+ mb = nx.barbell_graph(m1, m2, create_using=nx.MultiGraph())
139
+ assert edges_equal(mb.edges(), b.edges())
140
+
141
+ def test_binomial_tree(self):
142
+ graphs = (None, nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
143
+ for create_using in graphs:
144
+ for n in range(4):
145
+ b = nx.binomial_tree(n, create_using)
146
+ assert nx.number_of_nodes(b) == 2**n
147
+ assert nx.number_of_edges(b) == (2**n - 1)
148
+
149
+ def test_complete_graph(self):
150
+ # complete_graph(m) is a connected graph with
151
+ # m nodes and m*(m+1)/2 edges
152
+ for m in [0, 1, 3, 5]:
153
+ g = nx.complete_graph(m)
154
+ assert nx.number_of_nodes(g) == m
155
+ assert nx.number_of_edges(g) == m * (m - 1) // 2
156
+
157
+ mg = nx.complete_graph(m, create_using=nx.MultiGraph)
158
+ assert edges_equal(mg.edges(), g.edges())
159
+
160
+ g = nx.complete_graph("abc")
161
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
162
+ assert g.size() == 3
163
+
164
+ # creates a self-loop... should it? <backward compatible says yes>
165
+ g = nx.complete_graph("abcb")
166
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
167
+ assert g.size() == 4
168
+
169
+ g = nx.complete_graph("abcb", create_using=nx.MultiGraph)
170
+ assert nodes_equal(g.nodes(), ["a", "b", "c"])
171
+ assert g.size() == 6
172
+
173
+ def test_complete_digraph(self):
174
+ # complete_graph(m) is a connected graph with
175
+ # m nodes and m*(m+1)/2 edges
176
+ for m in [0, 1, 3, 5]:
177
+ g = nx.complete_graph(m, create_using=nx.DiGraph)
178
+ assert nx.number_of_nodes(g) == m
179
+ assert nx.number_of_edges(g) == m * (m - 1)
180
+
181
+ g = nx.complete_graph("abc", create_using=nx.DiGraph)
182
+ assert len(g) == 3
183
+ assert g.size() == 6
184
+ assert g.is_directed()
185
+
186
+ def test_circular_ladder_graph(self):
187
+ G = nx.circular_ladder_graph(5)
188
+ pytest.raises(
189
+ nx.NetworkXError, nx.circular_ladder_graph, 5, create_using=nx.DiGraph
190
+ )
191
+ mG = nx.circular_ladder_graph(5, create_using=nx.MultiGraph)
192
+ assert edges_equal(mG.edges(), G.edges())
193
+
194
+ def test_circulant_graph(self):
195
+ # Ci_n(1) is the cycle graph for all n
196
+ Ci6_1 = nx.circulant_graph(6, [1])
197
+ C6 = nx.cycle_graph(6)
198
+ assert edges_equal(Ci6_1.edges(), C6.edges())
199
+
200
+ # Ci_n(1, 2, ..., n div 2) is the complete graph for all n
201
+ Ci7 = nx.circulant_graph(7, [1, 2, 3])
202
+ K7 = nx.complete_graph(7)
203
+ assert edges_equal(Ci7.edges(), K7.edges())
204
+
205
+ # Ci_6(1, 3) is K_3,3 i.e. the utility graph
206
+ Ci6_1_3 = nx.circulant_graph(6, [1, 3])
207
+ K3_3 = nx.complete_bipartite_graph(3, 3)
208
+ assert is_isomorphic(Ci6_1_3, K3_3)
209
+
210
+ def test_cycle_graph(self):
211
+ G = nx.cycle_graph(4)
212
+ assert edges_equal(G.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
213
+ mG = nx.cycle_graph(4, create_using=nx.MultiGraph)
214
+ assert edges_equal(mG.edges(), [(0, 1), (0, 3), (1, 2), (2, 3)])
215
+ G = nx.cycle_graph(4, create_using=nx.DiGraph)
216
+ assert not G.has_edge(2, 1)
217
+ assert G.has_edge(1, 2)
218
+ assert G.is_directed()
219
+
220
+ G = nx.cycle_graph("abc")
221
+ assert len(G) == 3
222
+ assert G.size() == 3
223
+ G = nx.cycle_graph("abcb")
224
+ assert len(G) == 3
225
+ assert G.size() == 2
226
+ g = nx.cycle_graph("abc", nx.DiGraph)
227
+ assert len(g) == 3
228
+ assert g.size() == 3
229
+ assert g.is_directed()
230
+ g = nx.cycle_graph("abcb", nx.DiGraph)
231
+ assert len(g) == 3
232
+ assert g.size() == 4
233
+
234
+ def test_dorogovtsev_goltsev_mendes_graph(self):
235
+ G = nx.dorogovtsev_goltsev_mendes_graph(0)
236
+ assert edges_equal(G.edges(), [(0, 1)])
237
+ assert nodes_equal(list(G), [0, 1])
238
+ G = nx.dorogovtsev_goltsev_mendes_graph(1)
239
+ assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
240
+ assert nx.average_clustering(G) == 1.0
241
+ assert sorted(nx.triangles(G).values()) == [1, 1, 1]
242
+ G = nx.dorogovtsev_goltsev_mendes_graph(10)
243
+ assert nx.number_of_nodes(G) == 29526
244
+ assert nx.number_of_edges(G) == 59049
245
+ assert G.degree(0) == 1024
246
+ assert G.degree(1) == 1024
247
+ assert G.degree(2) == 1024
248
+
249
+ pytest.raises(
250
+ nx.NetworkXError,
251
+ nx.dorogovtsev_goltsev_mendes_graph,
252
+ 7,
253
+ create_using=nx.DiGraph,
254
+ )
255
+ pytest.raises(
256
+ nx.NetworkXError,
257
+ nx.dorogovtsev_goltsev_mendes_graph,
258
+ 7,
259
+ create_using=nx.MultiGraph,
260
+ )
261
+
262
+ def test_create_using(self):
263
+ G = nx.empty_graph()
264
+ assert isinstance(G, nx.Graph)
265
+ pytest.raises(TypeError, nx.empty_graph, create_using=0.0)
266
+ pytest.raises(TypeError, nx.empty_graph, create_using="Graph")
267
+
268
+ G = nx.empty_graph(create_using=nx.MultiGraph)
269
+ assert isinstance(G, nx.MultiGraph)
270
+ G = nx.empty_graph(create_using=nx.DiGraph)
271
+ assert isinstance(G, nx.DiGraph)
272
+
273
+ G = nx.empty_graph(create_using=nx.DiGraph, default=nx.MultiGraph)
274
+ assert isinstance(G, nx.DiGraph)
275
+ G = nx.empty_graph(create_using=None, default=nx.MultiGraph)
276
+ assert isinstance(G, nx.MultiGraph)
277
+ G = nx.empty_graph(default=nx.MultiGraph)
278
+ assert isinstance(G, nx.MultiGraph)
279
+
280
+ G = nx.path_graph(5)
281
+ H = nx.empty_graph(create_using=G)
282
+ assert not H.is_multigraph()
283
+ assert not H.is_directed()
284
+ assert len(H) == 0
285
+ assert G is H
286
+
287
+ H = nx.empty_graph(create_using=nx.MultiGraph())
288
+ assert H.is_multigraph()
289
+ assert not H.is_directed()
290
+ assert G is not H
291
+
292
+ # test for subclasses that also use typing.Protocol. See gh-6243
293
+ class Mixin(typing.Protocol):
294
+ pass
295
+
296
+ class MyGraph(Mixin, nx.DiGraph):
297
+ pass
298
+
299
+ G = nx.empty_graph(create_using=MyGraph)
300
+
301
+ def test_empty_graph(self):
302
+ G = nx.empty_graph()
303
+ assert nx.number_of_nodes(G) == 0
304
+ G = nx.empty_graph(42)
305
+ assert nx.number_of_nodes(G) == 42
306
+ assert nx.number_of_edges(G) == 0
307
+
308
+ G = nx.empty_graph("abc")
309
+ assert len(G) == 3
310
+ assert G.size() == 0
311
+
312
+ # create empty digraph
313
+ G = nx.empty_graph(42, create_using=nx.DiGraph(name="duh"))
314
+ assert nx.number_of_nodes(G) == 42
315
+ assert nx.number_of_edges(G) == 0
316
+ assert isinstance(G, nx.DiGraph)
317
+
318
+ # create empty multigraph
319
+ G = nx.empty_graph(42, create_using=nx.MultiGraph(name="duh"))
320
+ assert nx.number_of_nodes(G) == 42
321
+ assert nx.number_of_edges(G) == 0
322
+ assert isinstance(G, nx.MultiGraph)
323
+
324
+ # create empty graph from another
325
+ pete = nx.petersen_graph()
326
+ G = nx.empty_graph(42, create_using=pete)
327
+ assert nx.number_of_nodes(G) == 42
328
+ assert nx.number_of_edges(G) == 0
329
+ assert isinstance(G, nx.Graph)
330
+
331
+ def test_ladder_graph(self):
332
+ for i, G in [
333
+ (0, nx.empty_graph(0)),
334
+ (1, nx.path_graph(2)),
335
+ (2, nx.hypercube_graph(2)),
336
+ (10, nx.grid_graph([2, 10])),
337
+ ]:
338
+ assert is_isomorphic(nx.ladder_graph(i), G)
339
+
340
+ pytest.raises(nx.NetworkXError, nx.ladder_graph, 2, create_using=nx.DiGraph)
341
+
342
+ g = nx.ladder_graph(2)
343
+ mg = nx.ladder_graph(2, create_using=nx.MultiGraph)
344
+ assert edges_equal(mg.edges(), g.edges())
345
+
346
+ @pytest.mark.parametrize(("m", "n"), [(3, 5), (4, 10), (3, 20)])
347
+ def test_lollipop_graph_right_sizes(self, m, n):
348
+ G = nx.lollipop_graph(m, n)
349
+ assert nx.number_of_nodes(G) == m + n
350
+ assert nx.number_of_edges(G) == m * (m - 1) / 2 + n
351
+
352
+ @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("abc", "defg")])
353
+ def test_lollipop_graph_size_node_sequence(self, m, n):
354
+ G = nx.lollipop_graph(m, n)
355
+ assert nx.number_of_nodes(G) == len(m) + len(n)
356
+ assert nx.number_of_edges(G) == len(m) * (len(m) - 1) / 2 + len(n)
357
+
358
+ def test_lollipop_graph_exceptions(self):
359
+ # Raise NetworkXError if m<2
360
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, -1, 2)
361
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, 1, 20)
362
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, "", 20)
363
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, "a", 20)
364
+
365
+ # Raise NetworkXError if n<0
366
+ pytest.raises(nx.NetworkXError, nx.lollipop_graph, 5, -2)
367
+
368
+ # raise NetworkXError if create_using is directed
369
+ with pytest.raises(nx.NetworkXError):
370
+ nx.lollipop_graph(2, 20, create_using=nx.DiGraph)
371
+ with pytest.raises(nx.NetworkXError):
372
+ nx.lollipop_graph(2, 20, create_using=nx.MultiDiGraph)
373
+
374
+ @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
375
+ def test_lollipop_graph_same_as_path_when_m1_is_2(self, m, n):
376
+ G = nx.lollipop_graph(m, n)
377
+ assert is_isomorphic(G, nx.path_graph(n + 2))
378
+
379
+ def test_lollipop_graph_for_multigraph(self):
380
+ G = nx.lollipop_graph(5, 20)
381
+ MG = nx.lollipop_graph(5, 20, create_using=nx.MultiGraph)
382
+ assert edges_equal(MG.edges(), G.edges())
383
+
384
+ @pytest.mark.parametrize(
385
+ ("m", "n"),
386
+ [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
387
+ )
388
+ def test_lollipop_graph_mixing_input_types(self, m, n):
389
+ expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
390
+ expected.add_edge(0, 100) # Connect complete graph and path graph
391
+ assert is_isomorphic(nx.lollipop_graph(m, n), expected)
392
+
393
+ def test_lollipop_graph_non_builtin_ints(self):
394
+ np = pytest.importorskip("numpy")
395
+ G = nx.lollipop_graph(np.int32(4), np.int64(3))
396
+ expected = nx.compose(nx.complete_graph(4), nx.path_graph(range(100, 103)))
397
+ expected.add_edge(0, 100) # Connect complete graph and path graph
398
+ assert is_isomorphic(G, expected)
399
+
400
+ def test_null_graph(self):
401
+ assert nx.number_of_nodes(nx.null_graph()) == 0
402
+
403
+ def test_path_graph(self):
404
+ p = nx.path_graph(0)
405
+ assert is_isomorphic(p, nx.null_graph())
406
+
407
+ p = nx.path_graph(1)
408
+ assert is_isomorphic(p, nx.empty_graph(1))
409
+
410
+ p = nx.path_graph(10)
411
+ assert nx.is_connected(p)
412
+ assert sorted(d for n, d in p.degree()) == [1, 1, 2, 2, 2, 2, 2, 2, 2, 2]
413
+ assert p.order() - 1 == p.size()
414
+
415
+ dp = nx.path_graph(3, create_using=nx.DiGraph)
416
+ assert dp.has_edge(0, 1)
417
+ assert not dp.has_edge(1, 0)
418
+
419
+ mp = nx.path_graph(10, create_using=nx.MultiGraph)
420
+ assert edges_equal(mp.edges(), p.edges())
421
+
422
+ G = nx.path_graph("abc")
423
+ assert len(G) == 3
424
+ assert G.size() == 2
425
+ G = nx.path_graph("abcb")
426
+ assert len(G) == 3
427
+ assert G.size() == 2
428
+ g = nx.path_graph("abc", nx.DiGraph)
429
+ assert len(g) == 3
430
+ assert g.size() == 2
431
+ assert g.is_directed()
432
+ g = nx.path_graph("abcb", nx.DiGraph)
433
+ assert len(g) == 3
434
+ assert g.size() == 3
435
+
436
+ G = nx.path_graph((1, 2, 3, 2, 4))
437
+ assert G.has_edge(2, 4)
438
+
439
+ def test_star_graph(self):
440
+ assert is_isomorphic(nx.star_graph(""), nx.empty_graph(0))
441
+ assert is_isomorphic(nx.star_graph([]), nx.empty_graph(0))
442
+ assert is_isomorphic(nx.star_graph(0), nx.empty_graph(1))
443
+ assert is_isomorphic(nx.star_graph(1), nx.path_graph(2))
444
+ assert is_isomorphic(nx.star_graph(2), nx.path_graph(3))
445
+ assert is_isomorphic(nx.star_graph(5), nx.complete_bipartite_graph(1, 5))
446
+
447
+ s = nx.star_graph(10)
448
+ assert sorted(d for n, d in s.degree()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10]
449
+
450
+ pytest.raises(nx.NetworkXError, nx.star_graph, 10, create_using=nx.DiGraph)
451
+
452
+ ms = nx.star_graph(10, create_using=nx.MultiGraph)
453
+ assert edges_equal(ms.edges(), s.edges())
454
+
455
+ G = nx.star_graph("abc")
456
+ assert len(G) == 3
457
+ assert G.size() == 2
458
+
459
+ G = nx.star_graph("abcb")
460
+ assert len(G) == 3
461
+ assert G.size() == 2
462
+ G = nx.star_graph("abcb", create_using=nx.MultiGraph)
463
+ assert len(G) == 3
464
+ assert G.size() == 3
465
+
466
+ G = nx.star_graph("abcdefg")
467
+ assert len(G) == 7
468
+ assert G.size() == 6
469
+
470
+ def test_non_int_integers_for_star_graph(self):
471
+ np = pytest.importorskip("numpy")
472
+ G = nx.star_graph(np.int32(3))
473
+ assert len(G) == 4
474
+ assert G.size() == 3
475
+
476
+ @pytest.mark.parametrize(("m", "n"), [(3, 0), (3, 5), (4, 10), (3, 20)])
477
+ def test_tadpole_graph_right_sizes(self, m, n):
478
+ G = nx.tadpole_graph(m, n)
479
+ assert nx.number_of_nodes(G) == m + n
480
+ assert nx.number_of_edges(G) == m + n - (m == 2)
481
+
482
+ @pytest.mark.parametrize(("m", "n"), [("ab", ""), ("ab", "c"), ("abc", "defg")])
483
+ def test_tadpole_graph_size_node_sequences(self, m, n):
484
+ G = nx.tadpole_graph(m, n)
485
+ assert nx.number_of_nodes(G) == len(m) + len(n)
486
+ assert nx.number_of_edges(G) == len(m) + len(n) - (len(m) == 2)
487
+
488
+ def test_tadpole_graph_exceptions(self):
489
+ # Raise NetworkXError if m<2
490
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, -1, 3)
491
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 0, 3)
492
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 1, 3)
493
+
494
+ # Raise NetworkXError if n<0
495
+ pytest.raises(nx.NetworkXError, nx.tadpole_graph, 5, -2)
496
+
497
+ # Raise NetworkXError for digraphs
498
+ with pytest.raises(nx.NetworkXError):
499
+ nx.tadpole_graph(2, 20, create_using=nx.DiGraph)
500
+ with pytest.raises(nx.NetworkXError):
501
+ nx.tadpole_graph(2, 20, create_using=nx.MultiDiGraph)
502
+
503
+ @pytest.mark.parametrize(("m", "n"), [(2, 0), (2, 5), (2, 10), ("ab", 20)])
504
+ def test_tadpole_graph_same_as_path_when_m_is_2(self, m, n):
505
+ G = nx.tadpole_graph(m, n)
506
+ assert is_isomorphic(G, nx.path_graph(n + 2))
507
+
508
+ @pytest.mark.parametrize("m", [4, 7])
509
+ def test_tadpole_graph_same_as_cycle_when_m2_is_0(self, m):
510
+ G = nx.tadpole_graph(m, 0)
511
+ assert is_isomorphic(G, nx.cycle_graph(m))
512
+
513
+ def test_tadpole_graph_for_multigraph(self):
514
+ G = nx.tadpole_graph(5, 20)
515
+ MG = nx.tadpole_graph(5, 20, create_using=nx.MultiGraph)
516
+ assert edges_equal(MG.edges(), G.edges())
517
+
518
+ @pytest.mark.parametrize(
519
+ ("m", "n"),
520
+ [(4, "abc"), ("abcd", 3), ([1, 2, 3, 4], "abc"), ("abcd", [1, 2, 3])],
521
+ )
522
+ def test_tadpole_graph_mixing_input_types(self, m, n):
523
+ expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
524
+ expected.add_edge(0, 100) # Connect cycle and path
525
+ assert is_isomorphic(nx.tadpole_graph(m, n), expected)
526
+
527
+ def test_tadpole_graph_non_builtin_integers(self):
528
+ np = pytest.importorskip("numpy")
529
+ G = nx.tadpole_graph(np.int32(4), np.int64(3))
530
+ expected = nx.compose(nx.cycle_graph(4), nx.path_graph(range(100, 103)))
531
+ expected.add_edge(0, 100) # Connect cycle and path
532
+ assert is_isomorphic(G, expected)
533
+
534
+ def test_trivial_graph(self):
535
+ assert nx.number_of_nodes(nx.trivial_graph()) == 1
536
+
537
+ def test_turan_graph(self):
538
+ assert nx.number_of_edges(nx.turan_graph(13, 4)) == 63
539
+ assert is_isomorphic(
540
+ nx.turan_graph(13, 4), nx.complete_multipartite_graph(3, 4, 3, 3)
541
+ )
542
+
543
+ def test_wheel_graph(self):
544
+ for n, G in [
545
+ ("", nx.null_graph()),
546
+ (0, nx.null_graph()),
547
+ (1, nx.empty_graph(1)),
548
+ (2, nx.path_graph(2)),
549
+ (3, nx.complete_graph(3)),
550
+ (4, nx.complete_graph(4)),
551
+ ]:
552
+ g = nx.wheel_graph(n)
553
+ assert is_isomorphic(g, G)
554
+
555
+ g = nx.wheel_graph(10)
556
+ assert sorted(d for n, d in g.degree()) == [3, 3, 3, 3, 3, 3, 3, 3, 3, 9]
557
+
558
+ pytest.raises(nx.NetworkXError, nx.wheel_graph, 10, create_using=nx.DiGraph)
559
+
560
+ mg = nx.wheel_graph(10, create_using=nx.MultiGraph())
561
+ assert edges_equal(mg.edges(), g.edges())
562
+
563
+ G = nx.wheel_graph("abc")
564
+ assert len(G) == 3
565
+ assert G.size() == 3
566
+
567
+ G = nx.wheel_graph("abcb")
568
+ assert len(G) == 3
569
+ assert G.size() == 4
570
+ G = nx.wheel_graph("abcb", nx.MultiGraph)
571
+ assert len(G) == 3
572
+ assert G.size() == 6
573
+
574
+ def test_non_int_integers_for_wheel_graph(self):
575
+ np = pytest.importorskip("numpy")
576
+ G = nx.wheel_graph(np.int32(3))
577
+ assert len(G) == 3
578
+ assert G.size() == 3
579
+
580
+ def test_complete_0_partite_graph(self):
581
+ """Tests that the complete 0-partite graph is the null graph."""
582
+ G = nx.complete_multipartite_graph()
583
+ H = nx.null_graph()
584
+ assert nodes_equal(G, H)
585
+ assert edges_equal(G.edges(), H.edges())
586
+
587
+ def test_complete_1_partite_graph(self):
588
+ """Tests that the complete 1-partite graph is the empty graph."""
589
+ G = nx.complete_multipartite_graph(3)
590
+ H = nx.empty_graph(3)
591
+ assert nodes_equal(G, H)
592
+ assert edges_equal(G.edges(), H.edges())
593
+
594
+ def test_complete_2_partite_graph(self):
595
+ """Tests that the complete 2-partite graph is the complete bipartite
596
+ graph.
597
+
598
+ """
599
+ G = nx.complete_multipartite_graph(2, 3)
600
+ H = nx.complete_bipartite_graph(2, 3)
601
+ assert nodes_equal(G, H)
602
+ assert edges_equal(G.edges(), H.edges())
603
+
604
+ def test_complete_multipartite_graph(self):
605
+ """Tests for generating the complete multipartite graph."""
606
+ G = nx.complete_multipartite_graph(2, 3, 4)
607
+ blocks = [(0, 1), (2, 3, 4), (5, 6, 7, 8)]
608
+ # Within each block, no two vertices should be adjacent.
609
+ for block in blocks:
610
+ for u, v in itertools.combinations_with_replacement(block, 2):
611
+ assert v not in G[u]
612
+ assert G.nodes[u] == G.nodes[v]
613
+ # Across blocks, all vertices should be adjacent.
614
+ for block1, block2 in itertools.combinations(blocks, 2):
615
+ for u, v in itertools.product(block1, block2):
616
+ assert v in G[u]
617
+ assert G.nodes[u] != G.nodes[v]
618
+ with pytest.raises(nx.NetworkXError, match="Negative number of nodes"):
619
+ nx.complete_multipartite_graph(2, -3, 4)
620
+
621
+ def test_kneser_graph(self):
622
+ # the petersen graph is a special case of the kneser graph when n=5 and k=2
623
+ assert is_isomorphic(nx.kneser_graph(5, 2), nx.petersen_graph())
624
+
625
+ # when k is 1, the kneser graph returns a complete graph with n vertices
626
+ for i in range(1, 7):
627
+ assert is_isomorphic(nx.kneser_graph(i, 1), nx.complete_graph(i))
628
+
629
+ # the kneser graph of n and n-1 is the empty graph with n vertices
630
+ for j in range(3, 7):
631
+ assert is_isomorphic(nx.kneser_graph(j, j - 1), nx.empty_graph(j))
632
+
633
+ # in general the number of edges of the kneser graph is equal to
634
+ # (n choose k) times (n-k choose k) divided by 2
635
+ assert nx.number_of_edges(nx.kneser_graph(8, 3)) == 280
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_cographs.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.cographs` module.
2
+
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def test_random_cograph():
9
+ n = 3
10
+ G = nx.random_cograph(n)
11
+
12
+ assert len(G) == 2**n
13
+
14
+ # Every connected subgraph of G has diameter <= 2
15
+ if nx.is_connected(G):
16
+ assert nx.diameter(G) <= 2
17
+ else:
18
+ components = nx.connected_components(G)
19
+ for component in components:
20
+ assert nx.diameter(G.subgraph(component)) <= 2
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_community.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_random_partition_graph():
7
+ G = nx.random_partition_graph([3, 3, 3], 1, 0, seed=42)
8
+ C = G.graph["partition"]
9
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
10
+ assert len(G) == 9
11
+ assert len(list(G.edges())) == 9
12
+
13
+ G = nx.random_partition_graph([3, 3, 3], 0, 1)
14
+ C = G.graph["partition"]
15
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
16
+ assert len(G) == 9
17
+ assert len(list(G.edges())) == 27
18
+
19
+ G = nx.random_partition_graph([3, 3, 3], 1, 0, directed=True)
20
+ C = G.graph["partition"]
21
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
22
+ assert len(G) == 9
23
+ assert len(list(G.edges())) == 18
24
+
25
+ G = nx.random_partition_graph([3, 3, 3], 0, 1, directed=True)
26
+ C = G.graph["partition"]
27
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
28
+ assert len(G) == 9
29
+ assert len(list(G.edges())) == 54
30
+
31
+ G = nx.random_partition_graph([1, 2, 3, 4, 5], 0.5, 0.1)
32
+ C = G.graph["partition"]
33
+ assert C == [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {10, 11, 12, 13, 14}]
34
+ assert len(G) == 15
35
+
36
+ rpg = nx.random_partition_graph
37
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 1.1, 0.1)
38
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], -0.1, 0.1)
39
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, 1.1)
40
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, -0.1)
41
+
42
+
43
+ def test_planted_partition_graph():
44
+ G = nx.planted_partition_graph(4, 3, 1, 0, seed=42)
45
+ C = G.graph["partition"]
46
+ assert len(C) == 4
47
+ assert len(G) == 12
48
+ assert len(list(G.edges())) == 12
49
+
50
+ G = nx.planted_partition_graph(4, 3, 0, 1)
51
+ C = G.graph["partition"]
52
+ assert len(C) == 4
53
+ assert len(G) == 12
54
+ assert len(list(G.edges())) == 54
55
+
56
+ G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42)
57
+ C = G.graph["partition"]
58
+ assert len(C) == 10
59
+ assert len(G) == 40
60
+
61
+ G = nx.planted_partition_graph(4, 3, 1, 0, directed=True)
62
+ C = G.graph["partition"]
63
+ assert len(C) == 4
64
+ assert len(G) == 12
65
+ assert len(list(G.edges())) == 24
66
+
67
+ G = nx.planted_partition_graph(4, 3, 0, 1, directed=True)
68
+ C = G.graph["partition"]
69
+ assert len(C) == 4
70
+ assert len(G) == 12
71
+ assert len(list(G.edges())) == 108
72
+
73
+ G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42, directed=True)
74
+ C = G.graph["partition"]
75
+ assert len(C) == 10
76
+ assert len(G) == 40
77
+
78
+ ppg = nx.planted_partition_graph
79
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 1.1, 0.1)
80
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, -0.1, 0.1)
81
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, 1.1)
82
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, -0.1)
83
+
84
+
85
+ def test_relaxed_caveman_graph():
86
+ G = nx.relaxed_caveman_graph(4, 3, 0)
87
+ assert len(G) == 12
88
+ G = nx.relaxed_caveman_graph(4, 3, 1)
89
+ assert len(G) == 12
90
+ G = nx.relaxed_caveman_graph(4, 3, 0.5)
91
+ assert len(G) == 12
92
+ G = nx.relaxed_caveman_graph(4, 3, 0.5, seed=42)
93
+ assert len(G) == 12
94
+
95
+
96
+ def test_connected_caveman_graph():
97
+ G = nx.connected_caveman_graph(4, 3)
98
+ assert len(G) == 12
99
+
100
+ G = nx.connected_caveman_graph(1, 5)
101
+ K5 = nx.complete_graph(5)
102
+ K5.remove_edge(3, 4)
103
+ assert nx.is_isomorphic(G, K5)
104
+
105
+ # need at least 2 nodes in each clique
106
+ pytest.raises(nx.NetworkXError, nx.connected_caveman_graph, 4, 1)
107
+
108
+
109
+ def test_caveman_graph():
110
+ G = nx.caveman_graph(4, 3)
111
+ assert len(G) == 12
112
+
113
+ G = nx.caveman_graph(5, 1)
114
+ E5 = nx.empty_graph(5)
115
+ assert nx.is_isomorphic(G, E5)
116
+
117
+ G = nx.caveman_graph(1, 5)
118
+ K5 = nx.complete_graph(5)
119
+ assert nx.is_isomorphic(G, K5)
120
+
121
+
122
+ def test_gaussian_random_partition_graph():
123
+ G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01)
124
+ assert len(G) == 100
125
+ G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True)
126
+ assert len(G) == 100
127
+ G = nx.gaussian_random_partition_graph(
128
+ 100, 10, 10, 0.3, 0.01, directed=False, seed=42
129
+ )
130
+ assert len(G) == 100
131
+ assert not isinstance(G, nx.DiGraph)
132
+ G = nx.gaussian_random_partition_graph(
133
+ 100, 10, 10, 0.3, 0.01, directed=True, seed=42
134
+ )
135
+ assert len(G) == 100
136
+ assert isinstance(G, nx.DiGraph)
137
+ pytest.raises(
138
+ nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0
139
+ )
140
+ # Test when clusters are likely less than 1
141
+ G = nx.gaussian_random_partition_graph(10, 0.5, 0.5, 0.5, 0.5, seed=1)
142
+ assert len(G) == 10
143
+
144
+
145
+ def test_ring_of_cliques():
146
+ for i in range(2, 20, 3):
147
+ for j in range(2, 20, 3):
148
+ G = nx.ring_of_cliques(i, j)
149
+ assert G.number_of_nodes() == i * j
150
+ if i != 2 or j != 1:
151
+ expected_num_edges = i * (((j * (j - 1)) // 2) + 1)
152
+ else:
153
+ # the edge that already exists cannot be duplicated
154
+ expected_num_edges = i * (((j * (j - 1)) // 2) + 1) - 1
155
+ assert G.number_of_edges() == expected_num_edges
156
+ with pytest.raises(
157
+ nx.NetworkXError, match="A ring of cliques must have at least two cliques"
158
+ ):
159
+ nx.ring_of_cliques(1, 5)
160
+ with pytest.raises(
161
+ nx.NetworkXError, match="The cliques must have at least two nodes"
162
+ ):
163
+ nx.ring_of_cliques(3, 0)
164
+
165
+
166
+ def test_windmill_graph():
167
+ for n in range(2, 20, 3):
168
+ for k in range(2, 20, 3):
169
+ G = nx.windmill_graph(n, k)
170
+ assert G.number_of_nodes() == (k - 1) * n + 1
171
+ assert G.number_of_edges() == n * k * (k - 1) / 2
172
+ assert G.degree(0) == G.number_of_nodes() - 1
173
+ for i in range(1, G.number_of_nodes()):
174
+ assert G.degree(i) == k - 1
175
+ with pytest.raises(
176
+ nx.NetworkXError, match="A windmill graph must have at least two cliques"
177
+ ):
178
+ nx.windmill_graph(1, 3)
179
+ with pytest.raises(
180
+ nx.NetworkXError, match="The cliques must have at least two nodes"
181
+ ):
182
+ nx.windmill_graph(3, 0)
183
+
184
+
185
+ def test_stochastic_block_model():
186
+ sizes = [75, 75, 300]
187
+ probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
188
+ G = nx.stochastic_block_model(sizes, probs, seed=0)
189
+ C = G.graph["partition"]
190
+ assert len(C) == 3
191
+ assert len(G) == 450
192
+ assert G.size() == 22160
193
+
194
+ GG = nx.stochastic_block_model(sizes, probs, range(450), seed=0)
195
+ assert G.nodes == GG.nodes
196
+
197
+ # Test Exceptions
198
+ sbm = nx.stochastic_block_model
199
+ badnodelist = list(range(400)) # not enough nodes to match sizes
200
+ badprobs1 = [[0.25, 0.05, 1.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
201
+ badprobs2 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
202
+ probs_rect1 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07]]
203
+ probs_rect2 = [[0.25, 0.05], [0.05, -0.35], [0.02, 0.07]]
204
+ asymprobs = [[0.25, 0.05, 0.01], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
205
+ pytest.raises(nx.NetworkXException, sbm, sizes, badprobs1)
206
+ pytest.raises(nx.NetworkXException, sbm, sizes, badprobs2)
207
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect1, directed=True)
208
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect2, directed=True)
209
+ pytest.raises(nx.NetworkXException, sbm, sizes, asymprobs, directed=False)
210
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs, badnodelist)
211
+ nodelist = [0] + list(range(449)) # repeated node name in nodelist
212
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs, nodelist)
213
+
214
+ # Extra keyword arguments test
215
+ GG = nx.stochastic_block_model(sizes, probs, seed=0, selfloops=True)
216
+ assert G.nodes == GG.nodes
217
+ GG = nx.stochastic_block_model(sizes, probs, selfloops=True, directed=True)
218
+ assert G.nodes == GG.nodes
219
+ GG = nx.stochastic_block_model(sizes, probs, seed=0, sparse=False)
220
+ assert G.nodes == GG.nodes
221
+
222
+
223
+ def test_generator():
224
+ n = 250
225
+ tau1 = 3
226
+ tau2 = 1.5
227
+ mu = 0.1
228
+ G = nx.LFR_benchmark_graph(
229
+ n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
230
+ )
231
+ assert len(G) == 250
232
+ C = {frozenset(G.nodes[v]["community"]) for v in G}
233
+ assert nx.community.is_partition(G.nodes(), C)
234
+
235
+
236
+ def test_invalid_tau1():
237
+ with pytest.raises(nx.NetworkXError, match="tau2 must be greater than one"):
238
+ n = 100
239
+ tau1 = 2
240
+ tau2 = 1
241
+ mu = 0.1
242
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
243
+
244
+
245
+ def test_invalid_tau2():
246
+ with pytest.raises(nx.NetworkXError, match="tau1 must be greater than one"):
247
+ n = 100
248
+ tau1 = 1
249
+ tau2 = 2
250
+ mu = 0.1
251
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
252
+
253
+
254
+ def test_mu_too_large():
255
+ with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
256
+ n = 100
257
+ tau1 = 2
258
+ tau2 = 2
259
+ mu = 1.1
260
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
261
+
262
+
263
+ def test_mu_too_small():
264
+ with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
265
+ n = 100
266
+ tau1 = 2
267
+ tau2 = 2
268
+ mu = -1
269
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
270
+
271
+
272
+ def test_both_degrees_none():
273
+ with pytest.raises(
274
+ nx.NetworkXError,
275
+ match="Must assign exactly one of min_degree and average_degree",
276
+ ):
277
+ n = 100
278
+ tau1 = 2
279
+ tau2 = 2
280
+ mu = 1
281
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu)
282
+
283
+
284
+ def test_neither_degrees_none():
285
+ with pytest.raises(
286
+ nx.NetworkXError,
287
+ match="Must assign exactly one of min_degree and average_degree",
288
+ ):
289
+ n = 100
290
+ tau1 = 2
291
+ tau2 = 2
292
+ mu = 1
293
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, average_degree=5)
294
+
295
+
296
+ def test_max_iters_exceeded():
297
+ with pytest.raises(
298
+ nx.ExceededMaxIterations,
299
+ match="Could not assign communities; try increasing min_community",
300
+ ):
301
+ n = 10
302
+ tau1 = 2
303
+ tau2 = 2
304
+ mu = 0.1
305
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=10, seed=1)
306
+
307
+
308
+ def test_max_deg_out_of_range():
309
+ with pytest.raises(
310
+ nx.NetworkXError, match="max_degree must be in the interval \\(0, n\\]"
311
+ ):
312
+ n = 10
313
+ tau1 = 2
314
+ tau2 = 2
315
+ mu = 0.1
316
+ nx.LFR_benchmark_graph(
317
+ n, tau1, tau2, mu, max_degree=n + 1, max_iters=10, seed=1
318
+ )
319
+
320
+
321
+ def test_max_community():
322
+ n = 250
323
+ tau1 = 3
324
+ tau2 = 1.5
325
+ mu = 0.1
326
+ G = nx.LFR_benchmark_graph(
327
+ n,
328
+ tau1,
329
+ tau2,
330
+ mu,
331
+ average_degree=5,
332
+ max_degree=100,
333
+ min_community=50,
334
+ max_community=200,
335
+ seed=10,
336
+ )
337
+ assert len(G) == 250
338
+ C = {frozenset(G.nodes[v]["community"]) for v in G}
339
+ assert nx.community.is_partition(G.nodes(), C)
340
+
341
+
342
+ def test_powerlaw_iterations_exceeded():
343
+ with pytest.raises(
344
+ nx.ExceededMaxIterations, match="Could not create power law sequence"
345
+ ):
346
+ n = 100
347
+ tau1 = 2
348
+ tau2 = 2
349
+ mu = 1
350
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=0)
351
+
352
+
353
+ def test_no_scipy_zeta():
354
+ zeta2 = 1.6449340668482264
355
+ assert abs(zeta2 - nx.generators.community._hurwitz_zeta(2, 1, 0.0001)) < 0.01
356
+
357
+
358
+ def test_generate_min_degree_itr():
359
+ with pytest.raises(
360
+ nx.ExceededMaxIterations, match="Could not match average_degree"
361
+ ):
362
+ nx.generators.community._generate_min_degree(2, 2, 1, 0.01, 0)
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_degree_seq.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestConfigurationModel:
7
+ """Unit tests for the :func:`~networkx.configuration_model`
8
+ function.
9
+
10
+ """
11
+
12
+ def test_empty_degree_sequence(self):
13
+ """Tests that an empty degree sequence yields the null graph."""
14
+ G = nx.configuration_model([])
15
+ assert len(G) == 0
16
+
17
+ def test_degree_zero(self):
18
+ """Tests that a degree sequence of all zeros yields the empty
19
+ graph.
20
+
21
+ """
22
+ G = nx.configuration_model([0, 0, 0])
23
+ assert len(G) == 3
24
+ assert G.number_of_edges() == 0
25
+
26
+ def test_degree_sequence(self):
27
+ """Tests that the degree sequence of the generated graph matches
28
+ the input degree sequence.
29
+
30
+ """
31
+ deg_seq = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
32
+ G = nx.configuration_model(deg_seq, seed=12345678)
33
+ assert sorted((d for n, d in G.degree()), reverse=True) == [
34
+ 5,
35
+ 3,
36
+ 3,
37
+ 3,
38
+ 3,
39
+ 2,
40
+ 2,
41
+ 2,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ ]
46
+ assert sorted((d for n, d in G.degree(range(len(deg_seq)))), reverse=True) == [
47
+ 5,
48
+ 3,
49
+ 3,
50
+ 3,
51
+ 3,
52
+ 2,
53
+ 2,
54
+ 2,
55
+ 1,
56
+ 1,
57
+ 1,
58
+ ]
59
+
60
+ def test_random_seed(self):
61
+ """Tests that each call with the same random seed generates the
62
+ same graph.
63
+
64
+ """
65
+ deg_seq = [3] * 12
66
+ G1 = nx.configuration_model(deg_seq, seed=1000)
67
+ G2 = nx.configuration_model(deg_seq, seed=1000)
68
+ assert nx.is_isomorphic(G1, G2)
69
+ G1 = nx.configuration_model(deg_seq, seed=10)
70
+ G2 = nx.configuration_model(deg_seq, seed=10)
71
+ assert nx.is_isomorphic(G1, G2)
72
+
73
+ def test_directed_disallowed(self):
74
+ """Tests that attempting to create a configuration model graph
75
+ using a directed graph yields an exception.
76
+
77
+ """
78
+ with pytest.raises(nx.NetworkXNotImplemented):
79
+ nx.configuration_model([], create_using=nx.DiGraph())
80
+
81
+ def test_odd_degree_sum(self):
82
+ """Tests that a degree sequence whose sum is odd yields an
83
+ exception.
84
+
85
+ """
86
+ with pytest.raises(nx.NetworkXError):
87
+ nx.configuration_model([1, 2])
88
+
89
+
90
+ def test_directed_configuration_raise_unequal():
91
+ with pytest.raises(nx.NetworkXError):
92
+ zin = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1]
93
+ zout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 2]
94
+ nx.directed_configuration_model(zin, zout)
95
+
96
+
97
+ def test_directed_configuration_model():
98
+ G = nx.directed_configuration_model([], [], seed=0)
99
+ assert len(G) == 0
100
+
101
+
102
+ def test_simple_directed_configuration_model():
103
+ G = nx.directed_configuration_model([1, 1], [1, 1], seed=0)
104
+ assert len(G) == 2
105
+
106
+
107
+ def test_expected_degree_graph_empty():
108
+ # empty graph has empty degree sequence
109
+ deg_seq = []
110
+ G = nx.expected_degree_graph(deg_seq)
111
+ assert dict(G.degree()) == {}
112
+
113
+
114
+ def test_expected_degree_graph():
115
+ # test that fixed seed delivers the same graph
116
+ deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
117
+ G1 = nx.expected_degree_graph(deg_seq, seed=1000)
118
+ assert len(G1) == 12
119
+
120
+ G2 = nx.expected_degree_graph(deg_seq, seed=1000)
121
+ assert nx.is_isomorphic(G1, G2)
122
+
123
+ G1 = nx.expected_degree_graph(deg_seq, seed=10)
124
+ G2 = nx.expected_degree_graph(deg_seq, seed=10)
125
+ assert nx.is_isomorphic(G1, G2)
126
+
127
+
128
+ def test_expected_degree_graph_selfloops():
129
+ deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
130
+ G1 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
131
+ G2 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
132
+ assert nx.is_isomorphic(G1, G2)
133
+ assert len(G1) == 12
134
+
135
+
136
+ def test_expected_degree_graph_skew():
137
+ deg_seq = [10, 2, 2, 2, 2]
138
+ G1 = nx.expected_degree_graph(deg_seq, seed=1000)
139
+ G2 = nx.expected_degree_graph(deg_seq, seed=1000)
140
+ assert nx.is_isomorphic(G1, G2)
141
+ assert len(G1) == 5
142
+
143
+
144
+ def test_havel_hakimi_construction():
145
+ G = nx.havel_hakimi_graph([])
146
+ assert len(G) == 0
147
+
148
+ z = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
149
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
150
+ z = ["A", 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
151
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
152
+
153
+ z = [5, 4, 3, 3, 3, 2, 2, 2]
154
+ G = nx.havel_hakimi_graph(z)
155
+ G = nx.configuration_model(z)
156
+ z = [6, 5, 4, 4, 2, 1, 1, 1]
157
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
158
+
159
+ z = [10, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
160
+
161
+ G = nx.havel_hakimi_graph(z)
162
+
163
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z, create_using=nx.DiGraph())
164
+
165
+
166
+ def test_directed_havel_hakimi():
167
+ # Test range of valid directed degree sequences
168
+ n, r = 100, 10
169
+ p = 1.0 / r
170
+ for i in range(r):
171
+ G1 = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
172
+ din1 = [d for n, d in G1.in_degree()]
173
+ dout1 = [d for n, d in G1.out_degree()]
174
+ G2 = nx.directed_havel_hakimi_graph(din1, dout1)
175
+ din2 = [d for n, d in G2.in_degree()]
176
+ dout2 = [d for n, d in G2.out_degree()]
177
+ assert sorted(din1) == sorted(din2)
178
+ assert sorted(dout1) == sorted(dout2)
179
+
180
+ # Test non-graphical sequence
181
+ dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
182
+ din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
183
+ pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
184
+ # Test valid sequences
185
+ dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
186
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 0, 2]
187
+ G2 = nx.directed_havel_hakimi_graph(din, dout)
188
+ dout2 = (d for n, d in G2.out_degree())
189
+ din2 = (d for n, d in G2.in_degree())
190
+ assert sorted(dout) == sorted(dout2)
191
+ assert sorted(din) == sorted(din2)
192
+ # Test unequal sums
193
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
194
+ pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
195
+ # Test for negative values
196
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -2]
197
+ pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
198
+
199
+
200
+ def test_degree_sequence_tree():
201
+ z = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
202
+ G = nx.degree_sequence_tree(z)
203
+ assert len(G) == len(z)
204
+ assert len(list(G.edges())) == sum(z) / 2
205
+
206
+ pytest.raises(
207
+ nx.NetworkXError, nx.degree_sequence_tree, z, create_using=nx.DiGraph()
208
+ )
209
+
210
+ z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
211
+ pytest.raises(nx.NetworkXError, nx.degree_sequence_tree, z)
212
+
213
+
214
+ def test_random_degree_sequence_graph():
215
+ d = [1, 2, 2, 3]
216
+ G = nx.random_degree_sequence_graph(d, seed=42)
217
+ assert d == sorted(d for n, d in G.degree())
218
+
219
+
220
+ def test_random_degree_sequence_graph_raise():
221
+ z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
222
+ pytest.raises(nx.NetworkXUnfeasible, nx.random_degree_sequence_graph, z)
223
+
224
+
225
+ def test_random_degree_sequence_large():
226
+ G1 = nx.fast_gnp_random_graph(100, 0.1, seed=42)
227
+ d1 = (d for n, d in G1.degree())
228
+ G2 = nx.random_degree_sequence_graph(d1, seed=42)
229
+ d2 = (d for n, d in G2.degree())
230
+ assert sorted(d1) == sorted(d2)
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_duplication.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.duplication` module.
2
+
3
+ """
4
+ import pytest
5
+
6
+ from networkx.exception import NetworkXError
7
+ from networkx.generators.duplication import (
8
+ duplication_divergence_graph,
9
+ partial_duplication_graph,
10
+ )
11
+
12
+
13
+ class TestDuplicationDivergenceGraph:
14
+ """Unit tests for the
15
+ :func:`networkx.generators.duplication.duplication_divergence_graph`
16
+ function.
17
+
18
+ """
19
+
20
+ def test_final_size(self):
21
+ G = duplication_divergence_graph(3, p=1)
22
+ assert len(G) == 3
23
+ G = duplication_divergence_graph(3, p=1, seed=42)
24
+ assert len(G) == 3
25
+
26
+ def test_probability_too_large(self):
27
+ with pytest.raises(NetworkXError):
28
+ duplication_divergence_graph(3, p=2)
29
+
30
+ def test_probability_too_small(self):
31
+ with pytest.raises(NetworkXError):
32
+ duplication_divergence_graph(3, p=-1)
33
+
34
+ def test_non_extreme_probability_value(self):
35
+ G = duplication_divergence_graph(6, p=0.3, seed=42)
36
+ assert len(G) == 6
37
+ assert list(G.degree()) == [(0, 2), (1, 3), (2, 2), (3, 3), (4, 1), (5, 1)]
38
+
39
+ def test_minimum_desired_nodes(self):
40
+ with pytest.raises(
41
+ NetworkXError, match=".*n must be greater than or equal to 2"
42
+ ):
43
+ duplication_divergence_graph(1, p=1)
44
+
45
+
46
+ class TestPartialDuplicationGraph:
47
+ """Unit tests for the
48
+ :func:`networkx.generators.duplication.partial_duplication_graph`
49
+ function.
50
+
51
+ """
52
+
53
+ def test_final_size(self):
54
+ N = 10
55
+ n = 5
56
+ p = 0.5
57
+ q = 0.5
58
+ G = partial_duplication_graph(N, n, p, q)
59
+ assert len(G) == N
60
+ G = partial_duplication_graph(N, n, p, q, seed=42)
61
+ assert len(G) == N
62
+
63
+ def test_initial_clique_size(self):
64
+ N = 10
65
+ n = 10
66
+ p = 0.5
67
+ q = 0.5
68
+ G = partial_duplication_graph(N, n, p, q)
69
+ assert len(G) == n
70
+
71
+ def test_invalid_initial_size(self):
72
+ with pytest.raises(NetworkXError):
73
+ N = 5
74
+ n = 10
75
+ p = 0.5
76
+ q = 0.5
77
+ G = partial_duplication_graph(N, n, p, q)
78
+
79
+ def test_invalid_probabilities(self):
80
+ N = 1
81
+ n = 1
82
+ for p, q in [(0.5, 2), (0.5, -1), (2, 0.5), (-1, 0.5)]:
83
+ args = (N, n, p, q)
84
+ pytest.raises(NetworkXError, partial_duplication_graph, *args)
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_ego.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ego graph
3
+ ---------
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.utils import edges_equal, nodes_equal
8
+
9
+
10
+ class TestGeneratorEgo:
11
+ def test_ego(self):
12
+ G = nx.star_graph(3)
13
+ H = nx.ego_graph(G, 0)
14
+ assert nx.is_isomorphic(G, H)
15
+ G.add_edge(1, 11)
16
+ G.add_edge(2, 22)
17
+ G.add_edge(3, 33)
18
+ H = nx.ego_graph(G, 0)
19
+ assert nx.is_isomorphic(nx.star_graph(3), H)
20
+ G = nx.path_graph(3)
21
+ H = nx.ego_graph(G, 0)
22
+ assert edges_equal(H.edges(), [(0, 1)])
23
+ H = nx.ego_graph(G, 0, undirected=True)
24
+ assert edges_equal(H.edges(), [(0, 1)])
25
+ H = nx.ego_graph(G, 0, center=False)
26
+ assert edges_equal(H.edges(), [])
27
+
28
+ def test_ego_distance(self):
29
+ G = nx.Graph()
30
+ G.add_edge(0, 1, weight=2, distance=1)
31
+ G.add_edge(1, 2, weight=2, distance=2)
32
+ G.add_edge(2, 3, weight=2, distance=1)
33
+ assert nodes_equal(nx.ego_graph(G, 0, radius=3).nodes(), [0, 1, 2, 3])
34
+ eg = nx.ego_graph(G, 0, radius=3, distance="weight")
35
+ assert nodes_equal(eg.nodes(), [0, 1])
36
+ eg = nx.ego_graph(G, 0, radius=3, distance="weight", undirected=True)
37
+ assert nodes_equal(eg.nodes(), [0, 1])
38
+ eg = nx.ego_graph(G, 0, radius=3, distance="distance")
39
+ assert nodes_equal(eg.nodes(), [0, 1, 2])
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_geometric.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+ from itertools import combinations
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+
9
+
10
+ def l1dist(x, y):
11
+ return sum(abs(a - b) for a, b in zip(x, y))
12
+
13
+
14
+ class TestRandomGeometricGraph:
15
+ """Unit tests for :func:`~networkx.random_geometric_graph`"""
16
+
17
+ def test_number_of_nodes(self):
18
+ G = nx.random_geometric_graph(50, 0.25, seed=42)
19
+ assert len(G) == 50
20
+ G = nx.random_geometric_graph(range(50), 0.25, seed=42)
21
+ assert len(G) == 50
22
+
23
+ def test_distances(self):
24
+ """Tests that pairs of vertices adjacent if and only if they are
25
+ within the prescribed radius.
26
+ """
27
+ # Use the Euclidean metric, the default according to the
28
+ # documentation.
29
+ G = nx.random_geometric_graph(50, 0.25)
30
+ for u, v in combinations(G, 2):
31
+ # Adjacent vertices must be within the given distance.
32
+ if v in G[u]:
33
+ assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
34
+ # Nonadjacent vertices must be at greater distance.
35
+ else:
36
+ assert not math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
37
+
38
+ def test_p(self):
39
+ """Tests for providing an alternate distance metric to the generator."""
40
+ # Use the L1 metric.
41
+ G = nx.random_geometric_graph(50, 0.25, p=1)
42
+ for u, v in combinations(G, 2):
43
+ # Adjacent vertices must be within the given distance.
44
+ if v in G[u]:
45
+ assert l1dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
46
+ # Nonadjacent vertices must be at greater distance.
47
+ else:
48
+ assert not l1dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
49
+
50
+ def test_node_names(self):
51
+ """Tests using values other than sequential numbers as node IDs."""
52
+ import string
53
+
54
+ nodes = list(string.ascii_lowercase)
55
+ G = nx.random_geometric_graph(nodes, 0.25)
56
+ assert len(G) == len(nodes)
57
+
58
+ for u, v in combinations(G, 2):
59
+ # Adjacent vertices must be within the given distance.
60
+ if v in G[u]:
61
+ assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
62
+ # Nonadjacent vertices must be at greater distance.
63
+ else:
64
+ assert not math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
65
+
66
+ def test_pos_name(self):
67
+ G = nx.random_geometric_graph(50, 0.25, seed=42, pos_name="coords")
68
+ assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
69
+
70
+
71
+ class TestSoftRandomGeometricGraph:
72
+ """Unit tests for :func:`~networkx.soft_random_geometric_graph`"""
73
+
74
+ def test_number_of_nodes(self):
75
+ G = nx.soft_random_geometric_graph(50, 0.25, seed=42)
76
+ assert len(G) == 50
77
+ G = nx.soft_random_geometric_graph(range(50), 0.25, seed=42)
78
+ assert len(G) == 50
79
+
80
+ def test_distances(self):
81
+ """Tests that pairs of vertices adjacent if and only if they are
82
+ within the prescribed radius.
83
+ """
84
+ # Use the Euclidean metric, the default according to the
85
+ # documentation.
86
+ G = nx.soft_random_geometric_graph(50, 0.25)
87
+ for u, v in combinations(G, 2):
88
+ # Adjacent vertices must be within the given distance.
89
+ if v in G[u]:
90
+ assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
91
+
92
+ def test_p(self):
93
+ """Tests for providing an alternate distance metric to the generator."""
94
+
95
+ # Use the L1 metric.
96
+ def dist(x, y):
97
+ return sum(abs(a - b) for a, b in zip(x, y))
98
+
99
+ G = nx.soft_random_geometric_graph(50, 0.25, p=1)
100
+ for u, v in combinations(G, 2):
101
+ # Adjacent vertices must be within the given distance.
102
+ if v in G[u]:
103
+ assert dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
104
+
105
+ def test_node_names(self):
106
+ """Tests using values other than sequential numbers as node IDs."""
107
+ import string
108
+
109
+ nodes = list(string.ascii_lowercase)
110
+ G = nx.soft_random_geometric_graph(nodes, 0.25)
111
+ assert len(G) == len(nodes)
112
+
113
+ for u, v in combinations(G, 2):
114
+ # Adjacent vertices must be within the given distance.
115
+ if v in G[u]:
116
+ assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
117
+
118
+ def test_p_dist_default(self):
119
+ """Tests default p_dict = 0.5 returns graph with edge count <= RGG with
120
+ same n, radius, dim and positions
121
+ """
122
+ nodes = 50
123
+ dim = 2
124
+ pos = {v: [random.random() for i in range(dim)] for v in range(nodes)}
125
+ RGG = nx.random_geometric_graph(50, 0.25, pos=pos)
126
+ SRGG = nx.soft_random_geometric_graph(50, 0.25, pos=pos)
127
+ assert len(SRGG.edges()) <= len(RGG.edges())
128
+
129
+ def test_p_dist_zero(self):
130
+ """Tests if p_dict = 0 returns disconnected graph with 0 edges"""
131
+
132
+ def p_dist(dist):
133
+ return 0
134
+
135
+ G = nx.soft_random_geometric_graph(50, 0.25, p_dist=p_dist)
136
+ assert len(G.edges) == 0
137
+
138
+ def test_pos_name(self):
139
+ G = nx.soft_random_geometric_graph(50, 0.25, seed=42, pos_name="coords")
140
+ assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
141
+
142
+
143
+ def join(G, u, v, theta, alpha, metric):
144
+ """Returns ``True`` if and only if the nodes whose attributes are
145
+ ``du`` and ``dv`` should be joined, according to the threshold
146
+ condition for geographical threshold graphs.
147
+
148
+ ``G`` is an undirected NetworkX graph, and ``u`` and ``v`` are nodes
149
+ in that graph. The nodes must have node attributes ``'pos'`` and
150
+ ``'weight'``.
151
+
152
+ ``metric`` is a distance metric.
153
+ """
154
+ du, dv = G.nodes[u], G.nodes[v]
155
+ u_pos, v_pos = du["pos"], dv["pos"]
156
+ u_weight, v_weight = du["weight"], dv["weight"]
157
+ return (u_weight + v_weight) * metric(u_pos, v_pos) ** alpha >= theta
158
+
159
+
160
+ class TestGeographicalThresholdGraph:
161
+ """Unit tests for :func:`~networkx.geographical_threshold_graph`"""
162
+
163
+ def test_number_of_nodes(self):
164
+ G = nx.geographical_threshold_graph(50, 100, seed=42)
165
+ assert len(G) == 50
166
+ G = nx.geographical_threshold_graph(range(50), 100, seed=42)
167
+ assert len(G) == 50
168
+
169
+ def test_distances(self):
170
+ """Tests that pairs of vertices adjacent if and only if their
171
+ distances meet the given threshold.
172
+ """
173
+ # Use the Euclidean metric and alpha = -2
174
+ # the default according to the documentation.
175
+ G = nx.geographical_threshold_graph(50, 10)
176
+ for u, v in combinations(G, 2):
177
+ # Adjacent vertices must exceed the threshold.
178
+ if v in G[u]:
179
+ assert join(G, u, v, 10, -2, math.dist)
180
+ # Nonadjacent vertices must not exceed the threshold.
181
+ else:
182
+ assert not join(G, u, v, 10, -2, math.dist)
183
+
184
+ def test_metric(self):
185
+ """Tests for providing an alternate distance metric to the generator."""
186
+ # Use the L1 metric.
187
+ G = nx.geographical_threshold_graph(50, 10, metric=l1dist)
188
+ for u, v in combinations(G, 2):
189
+ # Adjacent vertices must exceed the threshold.
190
+ if v in G[u]:
191
+ assert join(G, u, v, 10, -2, l1dist)
192
+ # Nonadjacent vertices must not exceed the threshold.
193
+ else:
194
+ assert not join(G, u, v, 10, -2, l1dist)
195
+
196
+ def test_p_dist_zero(self):
197
+ """Tests if p_dict = 0 returns disconnected graph with 0 edges"""
198
+
199
+ def p_dist(dist):
200
+ return 0
201
+
202
+ G = nx.geographical_threshold_graph(50, 1, p_dist=p_dist)
203
+ assert len(G.edges) == 0
204
+
205
+ def test_pos_weight_name(self):
206
+ gtg = nx.geographical_threshold_graph
207
+ G = gtg(50, 100, seed=42, pos_name="coords", weight_name="wt")
208
+ assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
209
+ assert all(d["wt"] > 0 for n, d in G.nodes.items())
210
+
211
+
212
+ class TestWaxmanGraph:
213
+ """Unit tests for the :func:`~networkx.waxman_graph` function."""
214
+
215
+ def test_number_of_nodes_1(self):
216
+ G = nx.waxman_graph(50, 0.5, 0.1, seed=42)
217
+ assert len(G) == 50
218
+ G = nx.waxman_graph(range(50), 0.5, 0.1, seed=42)
219
+ assert len(G) == 50
220
+
221
+ def test_number_of_nodes_2(self):
222
+ G = nx.waxman_graph(50, 0.5, 0.1, L=1)
223
+ assert len(G) == 50
224
+ G = nx.waxman_graph(range(50), 0.5, 0.1, L=1)
225
+ assert len(G) == 50
226
+
227
+ def test_metric(self):
228
+ """Tests for providing an alternate distance metric to the generator."""
229
+ # Use the L1 metric.
230
+ G = nx.waxman_graph(50, 0.5, 0.1, metric=l1dist)
231
+ assert len(G) == 50
232
+
233
+ def test_pos_name(self):
234
+ G = nx.waxman_graph(50, 0.5, 0.1, seed=42, pos_name="coords")
235
+ assert all(len(d["coords"]) == 2 for n, d in G.nodes.items())
236
+
237
+
238
+ class TestNavigableSmallWorldGraph:
239
+ def test_navigable_small_world(self):
240
+ G = nx.navigable_small_world_graph(5, p=1, q=0, seed=42)
241
+ gg = nx.grid_2d_graph(5, 5).to_directed()
242
+ assert nx.is_isomorphic(G, gg)
243
+
244
+ G = nx.navigable_small_world_graph(5, p=1, q=0, dim=3)
245
+ gg = nx.grid_graph([5, 5, 5]).to_directed()
246
+ assert nx.is_isomorphic(G, gg)
247
+
248
+ G = nx.navigable_small_world_graph(5, p=1, q=0, dim=1)
249
+ gg = nx.grid_graph([5]).to_directed()
250
+ assert nx.is_isomorphic(G, gg)
251
+
252
+ def test_invalid_diameter_value(self):
253
+ with pytest.raises(nx.NetworkXException, match=".*p must be >= 1"):
254
+ nx.navigable_small_world_graph(5, p=0, q=0, dim=1)
255
+
256
+ def test_invalid_long_range_connections_value(self):
257
+ with pytest.raises(nx.NetworkXException, match=".*q must be >= 0"):
258
+ nx.navigable_small_world_graph(5, p=1, q=-1, dim=1)
259
+
260
+ def test_invalid_exponent_for_decaying_probability_value(self):
261
+ with pytest.raises(nx.NetworkXException, match=".*r must be >= 0"):
262
+ nx.navigable_small_world_graph(5, p=1, q=0, r=-1, dim=1)
263
+
264
+ def test_r_between_0_and_1(self):
265
+ """Smoke test for radius in range [0, 1]"""
266
+ # q=0 means no long-range connections
267
+ G = nx.navigable_small_world_graph(3, p=1, q=0, r=0.5, dim=2, seed=42)
268
+ expected = nx.grid_2d_graph(3, 3, create_using=nx.DiGraph)
269
+ assert nx.utils.graphs_equal(G, expected)
270
+
271
+ @pytest.mark.parametrize("seed", range(2478, 2578, 10))
272
+ def test_r_general_scaling(self, seed):
273
+ """The probability of adding a long-range edge scales with `1 / dist**r`,
274
+ so a navigable_small_world graph created with r < 1 should generally
275
+ result in more edges than a navigable_small_world graph with r >= 1
276
+ (for 0 < q << n).
277
+
278
+ N.B. this is probabilistic, so this test may not hold for all seeds."""
279
+ G1 = nx.navigable_small_world_graph(7, q=3, r=0.5, seed=seed)
280
+ G2 = nx.navigable_small_world_graph(7, q=3, r=1, seed=seed)
281
+ G3 = nx.navigable_small_world_graph(7, q=3, r=2, seed=seed)
282
+ assert G1.number_of_edges() > G2.number_of_edges()
283
+ assert G2.number_of_edges() > G3.number_of_edges()
284
+
285
+
286
+ class TestThresholdedRandomGeometricGraph:
287
+ """Unit tests for :func:`~networkx.thresholded_random_geometric_graph`"""
288
+
289
+ def test_number_of_nodes(self):
290
+ G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1, seed=42)
291
+ assert len(G) == 50
292
+ G = nx.thresholded_random_geometric_graph(range(50), 0.2, 0.1, seed=42)
293
+ assert len(G) == 50
294
+
295
+ def test_distances(self):
296
+ """Tests that pairs of vertices adjacent if and only if they are
297
+ within the prescribed radius.
298
+ """
299
+ # Use the Euclidean metric, the default according to the
300
+ # documentation.
301
+ G = nx.thresholded_random_geometric_graph(50, 0.25, 0.1, seed=42)
302
+ for u, v in combinations(G, 2):
303
+ # Adjacent vertices must be within the given distance.
304
+ if v in G[u]:
305
+ assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
306
+
307
+ def test_p(self):
308
+ """Tests for providing an alternate distance metric to the generator."""
309
+
310
+ # Use the L1 metric.
311
+ def dist(x, y):
312
+ return sum(abs(a - b) for a, b in zip(x, y))
313
+
314
+ G = nx.thresholded_random_geometric_graph(50, 0.25, 0.1, p=1, seed=42)
315
+ for u, v in combinations(G, 2):
316
+ # Adjacent vertices must be within the given distance.
317
+ if v in G[u]:
318
+ assert dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
319
+
320
+ def test_node_names(self):
321
+ """Tests using values other than sequential numbers as node IDs."""
322
+ import string
323
+
324
+ nodes = list(string.ascii_lowercase)
325
+ G = nx.thresholded_random_geometric_graph(nodes, 0.25, 0.1, seed=42)
326
+ assert len(G) == len(nodes)
327
+
328
+ for u, v in combinations(G, 2):
329
+ # Adjacent vertices must be within the given distance.
330
+ if v in G[u]:
331
+ assert math.dist(G.nodes[u]["pos"], G.nodes[v]["pos"]) <= 0.25
332
+
333
+ def test_theta(self):
334
+ """Tests that pairs of vertices adjacent if and only if their sum
335
+ weights exceeds the threshold parameter theta.
336
+ """
337
+ G = nx.thresholded_random_geometric_graph(50, 0.25, 0.1, seed=42)
338
+
339
+ for u, v in combinations(G, 2):
340
+ # Adjacent vertices must be within the given distance.
341
+ if v in G[u]:
342
+ assert (G.nodes[u]["weight"] + G.nodes[v]["weight"]) >= 0.1
343
+
344
+ def test_pos_name(self):
345
+ trgg = nx.thresholded_random_geometric_graph
346
+ G = trgg(50, 0.25, 0.1, seed=42, pos_name="p", weight_name="wt")
347
+ assert all(len(d["p"]) == 2 for n, d in G.nodes.items())
348
+ assert all(d["wt"] > 0 for n, d in G.nodes.items())
349
+
350
+
351
+ def test_geometric_edges_pos_attribute():
352
+ G = nx.Graph()
353
+ G.add_nodes_from(
354
+ [
355
+ (0, {"position": (0, 0)}),
356
+ (1, {"position": (0, 1)}),
357
+ (2, {"position": (1, 0)}),
358
+ ]
359
+ )
360
+ expected_edges = [(0, 1), (0, 2)]
361
+ assert expected_edges == nx.geometric_edges(G, radius=1, pos_name="position")
362
+
363
+
364
+ def test_geometric_edges_raises_no_pos():
365
+ G = nx.path_graph(3)
366
+ msg = "all nodes. must have a '"
367
+ with pytest.raises(nx.NetworkXError, match=msg):
368
+ nx.geometric_edges(G, radius=1)
369
+
370
+
371
+ def test_number_of_nodes_S1():
372
+ G = nx.geometric_soft_configuration_graph(
373
+ beta=1.5, n=100, gamma=2.7, mean_degree=10, seed=42
374
+ )
375
+ assert len(G) == 100
376
+
377
+
378
+ def test_set_attributes_S1():
379
+ G = nx.geometric_soft_configuration_graph(
380
+ beta=1.5, n=100, gamma=2.7, mean_degree=10, seed=42
381
+ )
382
+ kappas = nx.get_node_attributes(G, "kappa")
383
+ assert len(kappas) == 100
384
+ thetas = nx.get_node_attributes(G, "theta")
385
+ assert len(thetas) == 100
386
+ radii = nx.get_node_attributes(G, "radius")
387
+ assert len(radii) == 100
388
+
389
+
390
+ def test_mean_kappas_mean_degree_S1():
391
+ G = nx.geometric_soft_configuration_graph(
392
+ beta=2.5, n=50, gamma=2.7, mean_degree=10, seed=8023
393
+ )
394
+
395
+ kappas = nx.get_node_attributes(G, "kappa")
396
+ mean_kappas = sum(kappas.values()) / len(kappas)
397
+ assert math.fabs(mean_kappas - 10) < 0.5
398
+
399
+ degrees = dict(G.degree())
400
+ mean_degree = sum(degrees.values()) / len(degrees)
401
+ assert math.fabs(mean_degree - 10) < 1
402
+
403
+
404
+ def test_dict_kappas_S1():
405
+ kappas = {i: 10 for i in range(1000)}
406
+ G = nx.geometric_soft_configuration_graph(beta=1, kappas=kappas)
407
+ assert len(G) == 1000
408
+ kappas = nx.get_node_attributes(G, "kappa")
409
+ assert all(kappa == 10 for kappa in kappas.values())
410
+
411
+
412
+ def test_beta_clustering_S1():
413
+ G1 = nx.geometric_soft_configuration_graph(
414
+ beta=1.5, n=100, gamma=3.5, mean_degree=10, seed=42
415
+ )
416
+ G2 = nx.geometric_soft_configuration_graph(
417
+ beta=3.0, n=100, gamma=3.5, mean_degree=10, seed=42
418
+ )
419
+ assert nx.average_clustering(G1) < nx.average_clustering(G2)
420
+
421
+
422
+ def test_wrong_parameters_S1():
423
+ with pytest.raises(
424
+ nx.NetworkXError,
425
+ match="Please provide either kappas, or all 3 of: n, gamma and mean_degree.",
426
+ ):
427
+ G = nx.geometric_soft_configuration_graph(
428
+ beta=1.5, gamma=3.5, mean_degree=10, seed=42
429
+ )
430
+
431
+ with pytest.raises(
432
+ nx.NetworkXError,
433
+ match="When kappas is input, n, gamma and mean_degree must not be.",
434
+ ):
435
+ kappas = {i: 10 for i in range(1000)}
436
+ G = nx.geometric_soft_configuration_graph(
437
+ beta=1.5, kappas=kappas, gamma=2.3, seed=42
438
+ )
439
+
440
+ with pytest.raises(
441
+ nx.NetworkXError,
442
+ match="Please provide either kappas, or all 3 of: n, gamma and mean_degree.",
443
+ ):
444
+ G = nx.geometric_soft_configuration_graph(beta=1.5, seed=42)
445
+
446
+
447
+ def test_negative_beta_S1():
448
+ with pytest.raises(
449
+ nx.NetworkXError, match="The parameter beta cannot be smaller or equal to 0."
450
+ ):
451
+ G = nx.geometric_soft_configuration_graph(
452
+ beta=-1, n=100, gamma=2.3, mean_degree=10, seed=42
453
+ )
454
+
455
+
456
+ def test_non_zero_clustering_beta_lower_one_S1():
457
+ G = nx.geometric_soft_configuration_graph(
458
+ beta=0.5, n=100, gamma=3.5, mean_degree=10, seed=42
459
+ )
460
+ assert nx.average_clustering(G) > 0
461
+
462
+
463
+ def test_mean_degree_influence_on_connectivity_S1():
464
+ low_mean_degree = 2
465
+ high_mean_degree = 20
466
+ G_low = nx.geometric_soft_configuration_graph(
467
+ beta=1.2, n=100, gamma=2.7, mean_degree=low_mean_degree, seed=42
468
+ )
469
+ G_high = nx.geometric_soft_configuration_graph(
470
+ beta=1.2, n=100, gamma=2.7, mean_degree=high_mean_degree, seed=42
471
+ )
472
+ assert nx.number_connected_components(G_low) > nx.number_connected_components(
473
+ G_high
474
+ )
475
+
476
+
477
+ def test_compare_mean_kappas_different_gammas_S1():
478
+ G1 = nx.geometric_soft_configuration_graph(
479
+ beta=1.5, n=20, gamma=2.7, mean_degree=5, seed=42
480
+ )
481
+ G2 = nx.geometric_soft_configuration_graph(
482
+ beta=1.5, n=20, gamma=3.5, mean_degree=5, seed=42
483
+ )
484
+ kappas1 = nx.get_node_attributes(G1, "kappa")
485
+ mean_kappas1 = sum(kappas1.values()) / len(kappas1)
486
+ kappas2 = nx.get_node_attributes(G2, "kappa")
487
+ mean_kappas2 = sum(kappas2.values()) / len(kappas2)
488
+ assert math.fabs(mean_kappas1 - mean_kappas2) < 1
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_harary_graph.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.harary_graph` module.
2
+ """
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.algorithms.isomorphism.isomorph import is_isomorphic
8
+ from networkx.generators.harary_graph import hkn_harary_graph, hnm_harary_graph
9
+
10
+
11
+ class TestHararyGraph:
12
+ """
13
+ Suppose n nodes, m >= n-1 edges, d = 2m // n, r = 2m % n
14
+ """
15
+
16
+ def test_hnm_harary_graph(self):
17
+ # When d is even and r = 0, the hnm_harary_graph(n,m) is
18
+ # the circulant_graph(n, list(range(1,d/2+1)))
19
+ for n, m in [(5, 5), (6, 12), (7, 14)]:
20
+ G1 = hnm_harary_graph(n, m)
21
+ d = 2 * m // n
22
+ G2 = nx.circulant_graph(n, list(range(1, d // 2 + 1)))
23
+ assert is_isomorphic(G1, G2)
24
+
25
+ # When d is even and r > 0, the hnm_harary_graph(n,m) is
26
+ # the circulant_graph(n, list(range(1,d/2+1)))
27
+ # with r edges added arbitrarily
28
+ for n, m in [(5, 7), (6, 13), (7, 16)]:
29
+ G1 = hnm_harary_graph(n, m)
30
+ d = 2 * m // n
31
+ G2 = nx.circulant_graph(n, list(range(1, d // 2 + 1)))
32
+ assert set(G2.edges) < set(G1.edges)
33
+ assert G1.number_of_edges() == m
34
+
35
+ # When d is odd and n is even and r = 0, the hnm_harary_graph(n,m)
36
+ # is the circulant_graph(n, list(range(1,(d+1)/2) plus [n//2])
37
+ for n, m in [(6, 9), (8, 12), (10, 15)]:
38
+ G1 = hnm_harary_graph(n, m)
39
+ d = 2 * m // n
40
+ L = list(range(1, (d + 1) // 2))
41
+ L.append(n // 2)
42
+ G2 = nx.circulant_graph(n, L)
43
+ assert is_isomorphic(G1, G2)
44
+
45
+ # When d is odd and n is even and r > 0, the hnm_harary_graph(n,m)
46
+ # is the circulant_graph(n, list(range(1,(d+1)/2) plus [n//2])
47
+ # with r edges added arbitrarily
48
+ for n, m in [(6, 10), (8, 13), (10, 17)]:
49
+ G1 = hnm_harary_graph(n, m)
50
+ d = 2 * m // n
51
+ L = list(range(1, (d + 1) // 2))
52
+ L.append(n // 2)
53
+ G2 = nx.circulant_graph(n, L)
54
+ assert set(G2.edges) < set(G1.edges)
55
+ assert G1.number_of_edges() == m
56
+
57
+ # When d is odd and n is odd, the hnm_harary_graph(n,m) is
58
+ # the circulant_graph(n, list(range(1,(d+1)/2))
59
+ # with m - n*(d-1)/2 edges added arbitrarily
60
+ for n, m in [(5, 4), (7, 12), (9, 14)]:
61
+ G1 = hnm_harary_graph(n, m)
62
+ d = 2 * m // n
63
+ L = list(range(1, (d + 1) // 2))
64
+ G2 = nx.circulant_graph(n, L)
65
+ assert set(G2.edges) < set(G1.edges)
66
+ assert G1.number_of_edges() == m
67
+
68
+ # Raise NetworkXError if n<1
69
+ n = 0
70
+ m = 0
71
+ pytest.raises(nx.NetworkXError, hnm_harary_graph, n, m)
72
+
73
+ # Raise NetworkXError if m < n-1
74
+ n = 6
75
+ m = 4
76
+ pytest.raises(nx.NetworkXError, hnm_harary_graph, n, m)
77
+
78
+ # Raise NetworkXError if m > n(n-1)/2
79
+ n = 6
80
+ m = 16
81
+ pytest.raises(nx.NetworkXError, hnm_harary_graph, n, m)
82
+
83
+ """
84
+ Suppose connectivity k, number of nodes n
85
+ """
86
+
87
+ def test_hkn_harary_graph(self):
88
+ # When k == 1, the hkn_harary_graph(k,n) is
89
+ # the path_graph(n)
90
+ for k, n in [(1, 6), (1, 7)]:
91
+ G1 = hkn_harary_graph(k, n)
92
+ G2 = nx.path_graph(n)
93
+ assert is_isomorphic(G1, G2)
94
+
95
+ # When k is even, the hkn_harary_graph(k,n) is
96
+ # the circulant_graph(n, list(range(1,k/2+1)))
97
+ for k, n in [(2, 6), (2, 7), (4, 6), (4, 7)]:
98
+ G1 = hkn_harary_graph(k, n)
99
+ G2 = nx.circulant_graph(n, list(range(1, k // 2 + 1)))
100
+ assert is_isomorphic(G1, G2)
101
+
102
+ # When k is odd and n is even, the hkn_harary_graph(k,n) is
103
+ # the circulant_graph(n, list(range(1,(k+1)/2)) plus [n/2])
104
+ for k, n in [(3, 6), (5, 8), (7, 10)]:
105
+ G1 = hkn_harary_graph(k, n)
106
+ L = list(range(1, (k + 1) // 2))
107
+ L.append(n // 2)
108
+ G2 = nx.circulant_graph(n, L)
109
+ assert is_isomorphic(G1, G2)
110
+
111
+ # When k is odd and n is odd, the hkn_harary_graph(k,n) is
112
+ # the circulant_graph(n, list(range(1,(k+1)/2))) with
113
+ # n//2+1 edges added between node i and node i+n//2+1
114
+ for k, n in [(3, 5), (5, 9), (7, 11)]:
115
+ G1 = hkn_harary_graph(k, n)
116
+ G2 = nx.circulant_graph(n, list(range(1, (k + 1) // 2)))
117
+ eSet1 = set(G1.edges)
118
+ eSet2 = set(G2.edges)
119
+ eSet3 = set()
120
+ half = n // 2
121
+ for i in range(half + 1):
122
+ # add half+1 edges between i and i+half
123
+ eSet3.add((i, (i + half) % n))
124
+ assert eSet1 == eSet2 | eSet3
125
+
126
+ # Raise NetworkXError if k<1
127
+ k = 0
128
+ n = 0
129
+ pytest.raises(nx.NetworkXError, hkn_harary_graph, k, n)
130
+
131
+ # Raise NetworkXError if n<k+1
132
+ k = 6
133
+ n = 6
134
+ pytest.raises(nx.NetworkXError, hkn_harary_graph, k, n)
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_internet_as_graphs.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytest import approx
2
+
3
+ from networkx import is_connected, neighbors
4
+ from networkx.generators.internet_as_graphs import random_internet_as_graph
5
+
6
+
7
+ class TestInternetASTopology:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ cls.n = 1000
11
+ cls.seed = 42
12
+ cls.G = random_internet_as_graph(cls.n, cls.seed)
13
+ cls.T = []
14
+ cls.M = []
15
+ cls.C = []
16
+ cls.CP = []
17
+ cls.customers = {}
18
+ cls.providers = {}
19
+
20
+ for i in cls.G.nodes():
21
+ if cls.G.nodes[i]["type"] == "T":
22
+ cls.T.append(i)
23
+ elif cls.G.nodes[i]["type"] == "M":
24
+ cls.M.append(i)
25
+ elif cls.G.nodes[i]["type"] == "C":
26
+ cls.C.append(i)
27
+ elif cls.G.nodes[i]["type"] == "CP":
28
+ cls.CP.append(i)
29
+ else:
30
+ raise ValueError("Inconsistent data in the graph node attributes")
31
+ cls.set_customers(i)
32
+ cls.set_providers(i)
33
+
34
+ @classmethod
35
+ def set_customers(cls, i):
36
+ if i not in cls.customers:
37
+ cls.customers[i] = set()
38
+ for j in neighbors(cls.G, i):
39
+ e = cls.G.edges[(i, j)]
40
+ if e["type"] == "transit":
41
+ customer = int(e["customer"])
42
+ if j == customer:
43
+ cls.set_customers(j)
44
+ cls.customers[i] = cls.customers[i].union(cls.customers[j])
45
+ cls.customers[i].add(j)
46
+ elif i != customer:
47
+ raise ValueError(
48
+ "Inconsistent data in the graph edge attributes"
49
+ )
50
+
51
+ @classmethod
52
+ def set_providers(cls, i):
53
+ if i not in cls.providers:
54
+ cls.providers[i] = set()
55
+ for j in neighbors(cls.G, i):
56
+ e = cls.G.edges[(i, j)]
57
+ if e["type"] == "transit":
58
+ customer = int(e["customer"])
59
+ if i == customer:
60
+ cls.set_providers(j)
61
+ cls.providers[i] = cls.providers[i].union(cls.providers[j])
62
+ cls.providers[i].add(j)
63
+ elif j != customer:
64
+ raise ValueError(
65
+ "Inconsistent data in the graph edge attributes"
66
+ )
67
+
68
+ def test_wrong_input(self):
69
+ G = random_internet_as_graph(0)
70
+ assert len(G.nodes()) == 0
71
+
72
+ G = random_internet_as_graph(-1)
73
+ assert len(G.nodes()) == 0
74
+
75
+ G = random_internet_as_graph(1)
76
+ assert len(G.nodes()) == 1
77
+
78
+ def test_node_numbers(self):
79
+ assert len(self.G.nodes()) == self.n
80
+ assert len(self.T) < 7
81
+ assert len(self.M) == round(self.n * 0.15)
82
+ assert len(self.CP) == round(self.n * 0.05)
83
+ numb = self.n - len(self.T) - len(self.M) - len(self.CP)
84
+ assert len(self.C) == numb
85
+
86
+ def test_connectivity(self):
87
+ assert is_connected(self.G)
88
+
89
+ def test_relationships(self):
90
+ # T nodes are not customers of anyone
91
+ for i in self.T:
92
+ assert len(self.providers[i]) == 0
93
+
94
+ # C nodes are not providers of anyone
95
+ for i in self.C:
96
+ assert len(self.customers[i]) == 0
97
+
98
+ # CP nodes are not providers of anyone
99
+ for i in self.CP:
100
+ assert len(self.customers[i]) == 0
101
+
102
+ # test whether there is a customer-provider loop
103
+ for i in self.G.nodes():
104
+ assert len(self.customers[i].intersection(self.providers[i])) == 0
105
+
106
+ # test whether there is a peering with a customer or provider
107
+ for i, j in self.G.edges():
108
+ if self.G.edges[(i, j)]["type"] == "peer":
109
+ assert j not in self.customers[i]
110
+ assert i not in self.customers[j]
111
+ assert j not in self.providers[i]
112
+ assert i not in self.providers[j]
113
+
114
+ def test_degree_values(self):
115
+ d_m = 0 # multihoming degree for M nodes
116
+ d_cp = 0 # multihoming degree for CP nodes
117
+ d_c = 0 # multihoming degree for C nodes
118
+ p_m_m = 0 # avg number of peering edges between M and M
119
+ p_cp_m = 0 # avg number of peering edges between CP and M
120
+ p_cp_cp = 0 # avg number of peering edges between CP and CP
121
+ t_m = 0 # probability M's provider is T
122
+ t_cp = 0 # probability CP's provider is T
123
+ t_c = 0 # probability C's provider is T
124
+
125
+ for i, j in self.G.edges():
126
+ e = self.G.edges[(i, j)]
127
+ if e["type"] == "transit":
128
+ cust = int(e["customer"])
129
+ if i == cust:
130
+ prov = j
131
+ elif j == cust:
132
+ prov = i
133
+ else:
134
+ raise ValueError("Inconsistent data in the graph edge attributes")
135
+ if cust in self.M:
136
+ d_m += 1
137
+ if self.G.nodes[prov]["type"] == "T":
138
+ t_m += 1
139
+ elif cust in self.C:
140
+ d_c += 1
141
+ if self.G.nodes[prov]["type"] == "T":
142
+ t_c += 1
143
+ elif cust in self.CP:
144
+ d_cp += 1
145
+ if self.G.nodes[prov]["type"] == "T":
146
+ t_cp += 1
147
+ else:
148
+ raise ValueError("Inconsistent data in the graph edge attributes")
149
+ elif e["type"] == "peer":
150
+ if self.G.nodes[i]["type"] == "M" and self.G.nodes[j]["type"] == "M":
151
+ p_m_m += 1
152
+ if self.G.nodes[i]["type"] == "CP" and self.G.nodes[j]["type"] == "CP":
153
+ p_cp_cp += 1
154
+ if (
155
+ self.G.nodes[i]["type"] == "M"
156
+ and self.G.nodes[j]["type"] == "CP"
157
+ or self.G.nodes[i]["type"] == "CP"
158
+ and self.G.nodes[j]["type"] == "M"
159
+ ):
160
+ p_cp_m += 1
161
+ else:
162
+ raise ValueError("Unexpected data in the graph edge attributes")
163
+
164
+ assert d_m / len(self.M) == approx((2 + (2.5 * self.n) / 10000), abs=1e-0)
165
+ assert d_cp / len(self.CP) == approx((2 + (1.5 * self.n) / 10000), abs=1e-0)
166
+ assert d_c / len(self.C) == approx((1 + (5 * self.n) / 100000), abs=1e-0)
167
+
168
+ assert p_m_m / len(self.M) == approx((1 + (2 * self.n) / 10000), abs=1e-0)
169
+ assert p_cp_m / len(self.CP) == approx((0.2 + (2 * self.n) / 10000), abs=1e-0)
170
+ assert p_cp_cp / len(self.CP) == approx(
171
+ (0.05 + (2 * self.n) / 100000), abs=1e-0
172
+ )
173
+
174
+ assert t_m / d_m == approx(0.375, abs=1e-1)
175
+ assert t_cp / d_cp == approx(0.375, abs=1e-1)
176
+ assert t_c / d_c == approx(0.125, abs=1e-1)
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_intersection.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestIntersectionGraph:
7
+ def test_random_intersection_graph(self):
8
+ G = nx.uniform_random_intersection_graph(10, 5, 0.5)
9
+ assert len(G) == 10
10
+
11
+ def test_k_random_intersection_graph(self):
12
+ G = nx.k_random_intersection_graph(10, 5, 2)
13
+ assert len(G) == 10
14
+
15
+ def test_k_random_intersection_graph_seeded(self):
16
+ G = nx.k_random_intersection_graph(10, 5, 2, seed=1234)
17
+ assert len(G) == 10
18
+
19
+ def test_general_random_intersection_graph(self):
20
+ G = nx.general_random_intersection_graph(10, 5, [0.1, 0.2, 0.2, 0.1, 0.1])
21
+ assert len(G) == 10
22
+ pytest.raises(
23
+ ValueError,
24
+ nx.general_random_intersection_graph,
25
+ 10,
26
+ 5,
27
+ [0.1, 0.2, 0.2, 0.1],
28
+ )
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_joint_degree_seq.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ from networkx.algorithms.assortativity import degree_mixing_dict
4
+ from networkx.generators import gnm_random_graph, powerlaw_cluster_graph
5
+ from networkx.generators.joint_degree_seq import (
6
+ directed_joint_degree_graph,
7
+ is_valid_directed_joint_degree,
8
+ is_valid_joint_degree,
9
+ joint_degree_graph,
10
+ )
11
+
12
+
13
+ def test_is_valid_joint_degree():
14
+ """Tests for conditions that invalidate a joint degree dict"""
15
+
16
+ # valid joint degree that satisfies all five conditions
17
+ joint_degrees = {
18
+ 1: {4: 1},
19
+ 2: {2: 2, 3: 2, 4: 2},
20
+ 3: {2: 2, 4: 1},
21
+ 4: {1: 1, 2: 2, 3: 1},
22
+ }
23
+ assert is_valid_joint_degree(joint_degrees)
24
+
25
+ # test condition 1
26
+ # joint_degrees_1[1][4] not integer
27
+ joint_degrees_1 = {
28
+ 1: {4: 1.5},
29
+ 2: {2: 2, 3: 2, 4: 2},
30
+ 3: {2: 2, 4: 1},
31
+ 4: {1: 1.5, 2: 2, 3: 1},
32
+ }
33
+ assert not is_valid_joint_degree(joint_degrees_1)
34
+
35
+ # test condition 2
36
+ # degree_count[2] = sum(joint_degrees_2[2][j)/2, is not an int
37
+ # degree_count[4] = sum(joint_degrees_2[4][j)/4, is not an int
38
+ joint_degrees_2 = {
39
+ 1: {4: 1},
40
+ 2: {2: 2, 3: 2, 4: 3},
41
+ 3: {2: 2, 4: 1},
42
+ 4: {1: 1, 2: 3, 3: 1},
43
+ }
44
+ assert not is_valid_joint_degree(joint_degrees_2)
45
+
46
+ # test conditions 3 and 4
47
+ # joint_degrees_3[1][4]>degree_count[1]*degree_count[4]
48
+ joint_degrees_3 = {
49
+ 1: {4: 2},
50
+ 2: {2: 2, 3: 2, 4: 2},
51
+ 3: {2: 2, 4: 1},
52
+ 4: {1: 2, 2: 2, 3: 1},
53
+ }
54
+ assert not is_valid_joint_degree(joint_degrees_3)
55
+
56
+ # test condition 5
57
+ # joint_degrees_5[1][1] not even
58
+ joint_degrees_5 = {1: {1: 9}}
59
+ assert not is_valid_joint_degree(joint_degrees_5)
60
+
61
+
62
+ def test_joint_degree_graph(ntimes=10):
63
+ for _ in range(ntimes):
64
+ seed = int(time.time())
65
+
66
+ n, m, p = 20, 10, 1
67
+ # generate random graph with model powerlaw_cluster and calculate
68
+ # its joint degree
69
+ g = powerlaw_cluster_graph(n, m, p, seed=seed)
70
+ joint_degrees_g = degree_mixing_dict(g, normalized=False)
71
+
72
+ # generate simple undirected graph with given joint degree
73
+ # joint_degrees_g
74
+ G = joint_degree_graph(joint_degrees_g)
75
+ joint_degrees_G = degree_mixing_dict(G, normalized=False)
76
+
77
+ # assert that the given joint degree is equal to the generated
78
+ # graph's joint degree
79
+ assert joint_degrees_g == joint_degrees_G
80
+
81
+
82
+ def test_is_valid_directed_joint_degree():
83
+ in_degrees = [0, 1, 1, 2]
84
+ out_degrees = [1, 1, 1, 1]
85
+ nkk = {1: {1: 2, 2: 2}}
86
+ assert is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
87
+
88
+ # not realizable, values are not integers.
89
+ nkk = {1: {1: 1.5, 2: 2.5}}
90
+ assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
91
+
92
+ # not realizable, number of edges between 1-2 are insufficient.
93
+ nkk = {1: {1: 2, 2: 1}}
94
+ assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
95
+
96
+ # not realizable, in/out degree sequences have different number of nodes.
97
+ out_degrees = [1, 1, 1]
98
+ nkk = {1: {1: 2, 2: 2}}
99
+ assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
100
+
101
+ # not realizable, degree sequences have fewer than required nodes.
102
+ in_degrees = [0, 1, 2]
103
+ assert not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk)
104
+
105
+
106
+ def test_directed_joint_degree_graph(n=15, m=100, ntimes=1000):
107
+ for _ in range(ntimes):
108
+ # generate gnm random graph and calculate its joint degree.
109
+ g = gnm_random_graph(n, m, None, directed=True)
110
+
111
+ # in-degree sequence of g as a list of integers.
112
+ in_degrees = list(dict(g.in_degree()).values())
113
+ # out-degree sequence of g as a list of integers.
114
+ out_degrees = list(dict(g.out_degree()).values())
115
+ nkk = degree_mixing_dict(g)
116
+
117
+ # generate simple directed graph with given degree sequence and joint
118
+ # degree matrix.
119
+ G = directed_joint_degree_graph(in_degrees, out_degrees, nkk)
120
+
121
+ # assert degree sequence correctness.
122
+ assert in_degrees == list(dict(G.in_degree()).values())
123
+ assert out_degrees == list(dict(G.out_degree()).values())
124
+ # assert joint degree matrix correctness.
125
+ assert nkk == degree_mixing_dict(G)
env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_lattice.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.lattice` module."""
2
+
3
+ from itertools import product
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.utils import edges_equal
9
+
10
+
11
+ class TestGrid2DGraph:
12
+ """Unit tests for :func:`networkx.generators.lattice.grid_2d_graph`"""
13
+
14
+ def test_number_of_vertices(self):
15
+ m, n = 5, 6
16
+ G = nx.grid_2d_graph(m, n)
17
+ assert len(G) == m * n
18
+
19
+ def test_degree_distribution(self):
20
+ m, n = 5, 6
21
+ G = nx.grid_2d_graph(m, n)
22
+ expected_histogram = [0, 0, 4, 2 * (m + n) - 8, (m - 2) * (n - 2)]
23
+ assert nx.degree_histogram(G) == expected_histogram
24
+
25
+ def test_directed(self):
26
+ m, n = 5, 6
27
+ G = nx.grid_2d_graph(m, n)
28
+ H = nx.grid_2d_graph(m, n, create_using=nx.DiGraph())
29
+ assert H.succ == G.adj
30
+ assert H.pred == G.adj
31
+
32
+ def test_multigraph(self):
33
+ m, n = 5, 6
34
+ G = nx.grid_2d_graph(m, n)
35
+ H = nx.grid_2d_graph(m, n, create_using=nx.MultiGraph())
36
+ assert list(H.edges()) == list(G.edges())
37
+
38
+ def test_periodic(self):
39
+ G = nx.grid_2d_graph(0, 0, periodic=True)
40
+ assert dict(G.degree()) == {}
41
+
42
+ for m, n, H in [
43
+ (2, 2, nx.cycle_graph(4)),
44
+ (1, 7, nx.cycle_graph(7)),
45
+ (7, 1, nx.cycle_graph(7)),
46
+ (2, 5, nx.circular_ladder_graph(5)),
47
+ (5, 2, nx.circular_ladder_graph(5)),
48
+ (2, 4, nx.cubical_graph()),
49
+ (4, 2, nx.cubical_graph()),
50
+ ]:
51
+ G = nx.grid_2d_graph(m, n, periodic=True)
52
+ assert nx.could_be_isomorphic(G, H)
53
+
54
+ def test_periodic_iterable(self):
55
+ m, n = 3, 7
56
+ for a, b in product([0, 1], [0, 1]):
57
+ G = nx.grid_2d_graph(m, n, periodic=(a, b))
58
+ assert G.number_of_nodes() == m * n
59
+ assert G.number_of_edges() == (m + a - 1) * n + (n + b - 1) * m
60
+
61
+ def test_periodic_directed(self):
62
+ G = nx.grid_2d_graph(4, 2, periodic=True)
63
+ H = nx.grid_2d_graph(4, 2, periodic=True, create_using=nx.DiGraph())
64
+ assert H.succ == G.adj
65
+ assert H.pred == G.adj
66
+
67
+ def test_periodic_multigraph(self):
68
+ G = nx.grid_2d_graph(4, 2, periodic=True)
69
+ H = nx.grid_2d_graph(4, 2, periodic=True, create_using=nx.MultiGraph())
70
+ assert list(G.edges()) == list(H.edges())
71
+
72
+ def test_exceptions(self):
73
+ pytest.raises(nx.NetworkXError, nx.grid_2d_graph, -3, 2)
74
+ pytest.raises(nx.NetworkXError, nx.grid_2d_graph, 3, -2)
75
+ pytest.raises(TypeError, nx.grid_2d_graph, 3.3, 2)
76
+ pytest.raises(TypeError, nx.grid_2d_graph, 3, 2.2)
77
+
78
+ def test_node_input(self):
79
+ G = nx.grid_2d_graph(4, 2, periodic=True)
80
+ H = nx.grid_2d_graph(range(4), range(2), periodic=True)
81
+ assert nx.is_isomorphic(H, G)
82
+ H = nx.grid_2d_graph("abcd", "ef", periodic=True)
83
+ assert nx.is_isomorphic(H, G)
84
+ G = nx.grid_2d_graph(5, 6)
85
+ H = nx.grid_2d_graph(range(5), range(6))
86
+ assert edges_equal(H, G)
87
+
88
+
89
+ class TestGridGraph:
90
+ """Unit tests for :func:`networkx.generators.lattice.grid_graph`"""
91
+
92
+ def test_grid_graph(self):
93
+ """grid_graph([n,m]) is a connected simple graph with the
94
+ following properties:
95
+ number_of_nodes = n*m
96
+ degree_histogram = [0,0,4,2*(n+m)-8,(n-2)*(m-2)]
97
+ """
98
+ for n, m in [(3, 5), (5, 3), (4, 5), (5, 4)]:
99
+ dim = [n, m]
100
+ g = nx.grid_graph(dim)
101
+ assert len(g) == n * m
102
+ assert nx.degree_histogram(g) == [
103
+ 0,
104
+ 0,
105
+ 4,
106
+ 2 * (n + m) - 8,
107
+ (n - 2) * (m - 2),
108
+ ]
109
+
110
+ for n, m in [(1, 5), (5, 1)]:
111
+ dim = [n, m]
112
+ g = nx.grid_graph(dim)
113
+ assert len(g) == n * m
114
+ assert nx.is_isomorphic(g, nx.path_graph(5))
115
+
116
+ # mg = nx.grid_graph([n,m], create_using=MultiGraph())
117
+ # assert_equal(mg.edges(), g.edges())
118
+
119
+ def test_node_input(self):
120
+ G = nx.grid_graph([range(7, 9), range(3, 6)])
121
+ assert len(G) == 2 * 3
122
+ assert nx.is_isomorphic(G, nx.grid_graph([2, 3]))
123
+
124
+ def test_periodic_iterable(self):
125
+ m, n, k = 3, 7, 5
126
+ for a, b, c in product([0, 1], [0, 1], [0, 1]):
127
+ G = nx.grid_graph([m, n, k], periodic=(a, b, c))
128
+ num_e = (m + a - 1) * n * k + (n + b - 1) * m * k + (k + c - 1) * m * n
129
+ assert G.number_of_nodes() == m * n * k
130
+ assert G.number_of_edges() == num_e
131
+
132
+
133
+ class TestHypercubeGraph:
134
+ """Unit tests for :func:`networkx.generators.lattice.hypercube_graph`"""
135
+
136
+ def test_special_cases(self):
137
+ for n, H in [
138
+ (0, nx.null_graph()),
139
+ (1, nx.path_graph(2)),
140
+ (2, nx.cycle_graph(4)),
141
+ (3, nx.cubical_graph()),
142
+ ]:
143
+ G = nx.hypercube_graph(n)
144
+ assert nx.could_be_isomorphic(G, H)
145
+
146
+ def test_degree_distribution(self):
147
+ for n in range(1, 10):
148
+ G = nx.hypercube_graph(n)
149
+ expected_histogram = [0] * n + [2**n]
150
+ assert nx.degree_histogram(G) == expected_histogram
151
+
152
+
153
+ class TestTriangularLatticeGraph:
154
+ "Tests for :func:`networkx.generators.lattice.triangular_lattice_graph`"
155
+
156
+ def test_lattice_points(self):
157
+ """Tests that the graph is really a triangular lattice."""
158
+ for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
159
+ G = nx.triangular_lattice_graph(m, n)
160
+ N = (n + 1) // 2
161
+ assert len(G) == (m + 1) * (1 + N) - (n % 2) * ((m + 1) // 2)
162
+ for i, j in G.nodes():
163
+ nbrs = G[(i, j)]
164
+ if i < N:
165
+ assert (i + 1, j) in nbrs
166
+ if j < m:
167
+ assert (i, j + 1) in nbrs
168
+ if j < m and (i > 0 or j % 2) and (i < N or (j + 1) % 2):
169
+ assert (i + 1, j + 1) in nbrs or (i - 1, j + 1) in nbrs
170
+
171
+ def test_directed(self):
172
+ """Tests for creating a directed triangular lattice."""
173
+ G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
174
+ H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
175
+ assert H.is_directed()
176
+ for u, v in H.edges():
177
+ assert v[1] >= u[1]
178
+ if v[1] == u[1]:
179
+ assert v[0] > u[0]
180
+
181
+ def test_multigraph(self):
182
+ """Tests for creating a triangular lattice multigraph."""
183
+ G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
184
+ H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
185
+ assert list(H.edges()) == list(G.edges())
186
+
187
+ def test_periodic(self):
188
+ G = nx.triangular_lattice_graph(4, 6, periodic=True)
189
+ assert len(G) == 12
190
+ assert G.size() == 36
191
+ # all degrees are 6
192
+ assert len([n for n, d in G.degree() if d != 6]) == 0
193
+ G = nx.triangular_lattice_graph(5, 7, periodic=True)
194
+ TLG = nx.triangular_lattice_graph
195
+ pytest.raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
196
+ pytest.raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
197
+ pytest.raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
198
+
199
+
200
+ class TestHexagonalLatticeGraph:
201
+ "Tests for :func:`networkx.generators.lattice.hexagonal_lattice_graph`"
202
+
203
+ def test_lattice_points(self):
204
+ """Tests that the graph is really a hexagonal lattice."""
205
+ for m, n in [(4, 5), (4, 4), (4, 3), (3, 2), (3, 3), (3, 5)]:
206
+ G = nx.hexagonal_lattice_graph(m, n)
207
+ assert len(G) == 2 * (m + 1) * (n + 1) - 2
208
+ C_6 = nx.cycle_graph(6)
209
+ hexagons = [
210
+ [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)],
211
+ [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)],
212
+ [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)],
213
+ [(2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)],
214
+ [(2, 2), (2, 3), (2, 4), (3, 2), (3, 3), (3, 4)],
215
+ ]
216
+ for hexagon in hexagons:
217
+ assert nx.is_isomorphic(G.subgraph(hexagon), C_6)
218
+
219
+ def test_directed(self):
220
+ """Tests for creating a directed hexagonal lattice."""
221
+ G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
222
+ H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.DiGraph())
223
+ assert H.is_directed()
224
+ pos = nx.get_node_attributes(H, "pos")
225
+ for u, v in H.edges():
226
+ assert pos[v][1] >= pos[u][1]
227
+ if pos[v][1] == pos[u][1]:
228
+ assert pos[v][0] > pos[u][0]
229
+
230
+ def test_multigraph(self):
231
+ """Tests for creating a hexagonal lattice multigraph."""
232
+ G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
233
+ H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.MultiGraph())
234
+ assert list(H.edges()) == list(G.edges())
235
+
236
+ def test_periodic(self):
237
+ G = nx.hexagonal_lattice_graph(4, 6, periodic=True)
238
+ assert len(G) == 48
239
+ assert G.size() == 72
240
+ # all degrees are 3
241
+ assert len([n for n, d in G.degree() if d != 3]) == 0
242
+ G = nx.hexagonal_lattice_graph(5, 8, periodic=True)
243
+ HLG = nx.hexagonal_lattice_graph
244
+ pytest.raises(nx.NetworkXError, HLG, 2, 7, periodic=True)
245
+ pytest.raises(nx.NetworkXError, HLG, 1, 4, periodic=True)
246
+ pytest.raises(nx.NetworkXError, HLG, 2, 1, periodic=True)