ZTWHHH commited on
Commit
4b28474
·
verified ·
1 Parent(s): 49ad095

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. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/pairs.cpython-310.pyc +0 -0
  2. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/equitable_coloring.py +505 -0
  3. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py +0 -0
  4. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  5. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_connected.cpython-310.pyc +0 -0
  6. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc +0 -0
  7. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_attracting.py +70 -0
  8. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py +248 -0
  9. janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_semiconnected.py +55 -0
  10. janus/lib/python3.10/site-packages/networkx/algorithms/components/weakly_connected.py +197 -0
  11. janus/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png +3 -0
  12. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc +0 -0
  13. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc +0 -0
  14. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc +0 -0
  15. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc +0 -0
  16. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc +0 -0
  17. janus/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc +0 -0
  18. janus/lib/python3.10/site-packages/networkx/generators/atlas.py +180 -0
  19. janus/lib/python3.10/site-packages/networkx/generators/cographs.py +68 -0
  20. janus/lib/python3.10/site-packages/networkx/generators/duplication.py +174 -0
  21. janus/lib/python3.10/site-packages/networkx/generators/ego.py +66 -0
  22. janus/lib/python3.10/site-packages/networkx/generators/expanders.py +474 -0
  23. janus/lib/python3.10/site-packages/networkx/generators/geometric.py +1048 -0
  24. janus/lib/python3.10/site-packages/networkx/generators/harary_graph.py +199 -0
  25. janus/lib/python3.10/site-packages/networkx/generators/interval_graph.py +70 -0
  26. janus/lib/python3.10/site-packages/networkx/generators/joint_degree_seq.py +664 -0
  27. janus/lib/python3.10/site-packages/networkx/generators/line.py +500 -0
  28. janus/lib/python3.10/site-packages/networkx/generators/random_graphs.py +1400 -0
  29. janus/lib/python3.10/site-packages/networkx/generators/social.py +554 -0
  30. janus/lib/python3.10/site-packages/networkx/generators/stochastic.py +54 -0
  31. janus/lib/python3.10/site-packages/networkx/generators/sudoku.py +131 -0
  32. janus/lib/python3.10/site-packages/networkx/generators/tests/__init__.py +0 -0
  33. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  34. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc +0 -0
  35. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc +0 -0
  36. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc +0 -0
  37. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc +0 -0
  38. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc +0 -0
  39. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc +0 -0
  40. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-310.pyc +0 -0
  41. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc +0 -0
  42. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc +0 -0
  46. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc +0 -0
  47. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc +0 -0
  48. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc +0 -0
  49. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-310.pyc +0 -0
  50. janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-310.pyc +0 -0
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/pairs.cpython-310.pyc ADDED
Binary file (3.88 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/equitable_coloring.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Equitable coloring of graphs with bounded degree.
3
+ """
4
+
5
+ from collections import defaultdict
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = ["equitable_color"]
10
+
11
+
12
+ @nx._dispatchable
13
+ def is_coloring(G, coloring):
14
+ """Determine if the coloring is a valid coloring for the graph G."""
15
+ # Verify that the coloring is valid.
16
+ return all(coloring[s] != coloring[d] for s, d in G.edges)
17
+
18
+
19
+ @nx._dispatchable
20
+ def is_equitable(G, coloring, num_colors=None):
21
+ """Determines if the coloring is valid and equitable for the graph G."""
22
+
23
+ if not is_coloring(G, coloring):
24
+ return False
25
+
26
+ # Verify whether it is equitable.
27
+ color_set_size = defaultdict(int)
28
+ for color in coloring.values():
29
+ color_set_size[color] += 1
30
+
31
+ if num_colors is not None:
32
+ for color in range(num_colors):
33
+ if color not in color_set_size:
34
+ # These colors do not have any vertices attached to them.
35
+ color_set_size[color] = 0
36
+
37
+ # If there are more than 2 distinct values, the coloring cannot be equitable
38
+ all_set_sizes = set(color_set_size.values())
39
+ if len(all_set_sizes) == 0 and num_colors is None: # Was an empty graph
40
+ return True
41
+ elif len(all_set_sizes) == 1:
42
+ return True
43
+ elif len(all_set_sizes) == 2:
44
+ a, b = list(all_set_sizes)
45
+ return abs(a - b) <= 1
46
+ else: # len(all_set_sizes) > 2:
47
+ return False
48
+
49
+
50
+ def make_C_from_F(F):
51
+ C = defaultdict(list)
52
+ for node, color in F.items():
53
+ C[color].append(node)
54
+
55
+ return C
56
+
57
+
58
+ def make_N_from_L_C(L, C):
59
+ nodes = L.keys()
60
+ colors = C.keys()
61
+ return {
62
+ (node, color): sum(1 for v in L[node] if v in C[color])
63
+ for node in nodes
64
+ for color in colors
65
+ }
66
+
67
+
68
+ def make_H_from_C_N(C, N):
69
+ return {
70
+ (c1, c2): sum(1 for node in C[c1] if N[(node, c2)] == 0) for c1 in C for c2 in C
71
+ }
72
+
73
+
74
+ def change_color(u, X, Y, N, H, F, C, L):
75
+ """Change the color of 'u' from X to Y and update N, H, F, C."""
76
+ assert F[u] == X and X != Y
77
+
78
+ # Change the class of 'u' from X to Y
79
+ F[u] = Y
80
+
81
+ for k in C:
82
+ # 'u' witnesses an edge from k -> Y instead of from k -> X now.
83
+ if N[u, k] == 0:
84
+ H[(X, k)] -= 1
85
+ H[(Y, k)] += 1
86
+
87
+ for v in L[u]:
88
+ # 'v' has lost a neighbor in X and gained one in Y
89
+ N[(v, X)] -= 1
90
+ N[(v, Y)] += 1
91
+
92
+ if N[(v, X)] == 0:
93
+ # 'v' witnesses F[v] -> X
94
+ H[(F[v], X)] += 1
95
+
96
+ if N[(v, Y)] == 1:
97
+ # 'v' no longer witnesses F[v] -> Y
98
+ H[(F[v], Y)] -= 1
99
+
100
+ C[X].remove(u)
101
+ C[Y].append(u)
102
+
103
+
104
+ def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L):
105
+ """Move witness along a path from src_color to dst_color."""
106
+ X = src_color
107
+ while X != dst_color:
108
+ Y = T_cal[X]
109
+ # Move _any_ witness from X to Y = T_cal[X]
110
+ w = next(x for x in C[X] if N[(x, Y)] == 0)
111
+ change_color(w, X, Y, N=N, H=H, F=F, C=C, L=L)
112
+ X = Y
113
+
114
+
115
+ @nx._dispatchable(mutates_input=True)
116
+ def pad_graph(G, num_colors):
117
+ """Add a disconnected complete clique K_p such that the number of nodes in
118
+ the graph becomes a multiple of `num_colors`.
119
+
120
+ Assumes that the graph's nodes are labelled using integers.
121
+
122
+ Returns the number of nodes with each color.
123
+ """
124
+
125
+ n_ = len(G)
126
+ r = num_colors - 1
127
+
128
+ # Ensure that the number of nodes in G is a multiple of (r + 1)
129
+ s = n_ // (r + 1)
130
+ if n_ != s * (r + 1):
131
+ p = (r + 1) - n_ % (r + 1)
132
+ s += 1
133
+
134
+ # Complete graph K_p between (imaginary) nodes [n_, ... , n_ + p]
135
+ K = nx.relabel_nodes(nx.complete_graph(p), {idx: idx + n_ for idx in range(p)})
136
+ G.add_edges_from(K.edges)
137
+
138
+ return s
139
+
140
+
141
+ def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None):
142
+ """Procedure P as described in the paper."""
143
+
144
+ if excluded_colors is None:
145
+ excluded_colors = set()
146
+
147
+ A_cal = set()
148
+ T_cal = {}
149
+ R_cal = []
150
+
151
+ # BFS to determine A_cal, i.e. colors reachable from V-
152
+ reachable = [V_minus]
153
+ marked = set(reachable)
154
+ idx = 0
155
+
156
+ while idx < len(reachable):
157
+ pop = reachable[idx]
158
+ idx += 1
159
+
160
+ A_cal.add(pop)
161
+ R_cal.append(pop)
162
+
163
+ # TODO: Checking whether a color has been visited can be made faster by
164
+ # using a look-up table instead of testing for membership in a set by a
165
+ # logarithmic factor.
166
+ next_layer = []
167
+ for k in C:
168
+ if (
169
+ H[(k, pop)] > 0
170
+ and k not in A_cal
171
+ and k not in excluded_colors
172
+ and k not in marked
173
+ ):
174
+ next_layer.append(k)
175
+
176
+ for dst in next_layer:
177
+ # Record that `dst` can reach `pop`
178
+ T_cal[dst] = pop
179
+
180
+ marked.update(next_layer)
181
+ reachable.extend(next_layer)
182
+
183
+ # Variables for the algorithm
184
+ b = len(C) - len(A_cal)
185
+
186
+ if V_plus in A_cal:
187
+ # Easy case: V+ is in A_cal
188
+ # Move one node from V+ to V- using T_cal to find the parents.
189
+ move_witnesses(V_plus, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L)
190
+ else:
191
+ # If there is a solo edge, we can resolve the situation by
192
+ # moving witnesses from B to A, making G[A] equitable and then
193
+ # recursively balancing G[B - w] with a different V_minus and
194
+ # but the same V_plus.
195
+
196
+ A_0 = set()
197
+ A_cal_0 = set()
198
+ num_terminal_sets_found = 0
199
+ made_equitable = False
200
+
201
+ for W_1 in R_cal[::-1]:
202
+ for v in C[W_1]:
203
+ X = None
204
+
205
+ for U in C:
206
+ if N[(v, U)] == 0 and U in A_cal and U != W_1:
207
+ X = U
208
+
209
+ # v does not witness an edge in H[A_cal]
210
+ if X is None:
211
+ continue
212
+
213
+ for U in C:
214
+ # Note: Departing from the paper here.
215
+ if N[(v, U)] >= 1 and U not in A_cal:
216
+ X_prime = U
217
+ w = v
218
+
219
+ try:
220
+ # Finding the solo neighbor of w in X_prime
221
+ y = next(
222
+ node
223
+ for node in L[w]
224
+ if F[node] == X_prime and N[(node, W_1)] == 1
225
+ )
226
+ except StopIteration:
227
+ pass
228
+ else:
229
+ W = W_1
230
+
231
+ # Move w from W to X, now X has one extra node.
232
+ change_color(w, W, X, N=N, H=H, F=F, C=C, L=L)
233
+
234
+ # Move witness from X to V_minus, making the coloring
235
+ # equitable.
236
+ move_witnesses(
237
+ src_color=X,
238
+ dst_color=V_minus,
239
+ N=N,
240
+ H=H,
241
+ F=F,
242
+ C=C,
243
+ T_cal=T_cal,
244
+ L=L,
245
+ )
246
+
247
+ # Move y from X_prime to W, making W the correct size.
248
+ change_color(y, X_prime, W, N=N, H=H, F=F, C=C, L=L)
249
+
250
+ # Then call the procedure on G[B - y]
251
+ procedure_P(
252
+ V_minus=X_prime,
253
+ V_plus=V_plus,
254
+ N=N,
255
+ H=H,
256
+ C=C,
257
+ F=F,
258
+ L=L,
259
+ excluded_colors=excluded_colors.union(A_cal),
260
+ )
261
+ made_equitable = True
262
+ break
263
+
264
+ if made_equitable:
265
+ break
266
+ else:
267
+ # No node in W_1 was found such that
268
+ # it had a solo-neighbor.
269
+ A_cal_0.add(W_1)
270
+ A_0.update(C[W_1])
271
+ num_terminal_sets_found += 1
272
+
273
+ if num_terminal_sets_found == b:
274
+ # Otherwise, construct the maximal independent set and find
275
+ # a pair of z_1, z_2 as in Case II.
276
+
277
+ # BFS to determine B_cal': the set of colors reachable from V+
278
+ B_cal_prime = set()
279
+ T_cal_prime = {}
280
+
281
+ reachable = [V_plus]
282
+ marked = set(reachable)
283
+ idx = 0
284
+ while idx < len(reachable):
285
+ pop = reachable[idx]
286
+ idx += 1
287
+
288
+ B_cal_prime.add(pop)
289
+
290
+ # No need to check for excluded_colors here because
291
+ # they only exclude colors from A_cal
292
+ next_layer = [
293
+ k
294
+ for k in C
295
+ if H[(pop, k)] > 0 and k not in B_cal_prime and k not in marked
296
+ ]
297
+
298
+ for dst in next_layer:
299
+ T_cal_prime[pop] = dst
300
+
301
+ marked.update(next_layer)
302
+ reachable.extend(next_layer)
303
+
304
+ # Construct the independent set of G[B']
305
+ I_set = set()
306
+ I_covered = set()
307
+ W_covering = {}
308
+
309
+ B_prime = [node for k in B_cal_prime for node in C[k]]
310
+
311
+ # Add the nodes in V_plus to I first.
312
+ for z in C[V_plus] + B_prime:
313
+ if z in I_covered or F[z] not in B_cal_prime:
314
+ continue
315
+
316
+ I_set.add(z)
317
+ I_covered.add(z)
318
+ I_covered.update(list(L[z]))
319
+
320
+ for w in L[z]:
321
+ if F[w] in A_cal_0 and N[(z, F[w])] == 1:
322
+ if w not in W_covering:
323
+ W_covering[w] = z
324
+ else:
325
+ # Found z1, z2 which have the same solo
326
+ # neighbor in some W
327
+ z_1 = W_covering[w]
328
+ # z_2 = z
329
+
330
+ Z = F[z_1]
331
+ W = F[w]
332
+
333
+ # shift nodes along W, V-
334
+ move_witnesses(
335
+ W, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L
336
+ )
337
+
338
+ # shift nodes along V+ to Z
339
+ move_witnesses(
340
+ V_plus,
341
+ Z,
342
+ N=N,
343
+ H=H,
344
+ F=F,
345
+ C=C,
346
+ T_cal=T_cal_prime,
347
+ L=L,
348
+ )
349
+
350
+ # change color of z_1 to W
351
+ change_color(z_1, Z, W, N=N, H=H, F=F, C=C, L=L)
352
+
353
+ # change color of w to some color in B_cal
354
+ W_plus = next(
355
+ k for k in C if N[(w, k)] == 0 and k not in A_cal
356
+ )
357
+ change_color(w, W, W_plus, N=N, H=H, F=F, C=C, L=L)
358
+
359
+ # recurse with G[B \cup W*]
360
+ excluded_colors.update(
361
+ [k for k in C if k != W and k not in B_cal_prime]
362
+ )
363
+ procedure_P(
364
+ V_minus=W,
365
+ V_plus=W_plus,
366
+ N=N,
367
+ H=H,
368
+ C=C,
369
+ F=F,
370
+ L=L,
371
+ excluded_colors=excluded_colors,
372
+ )
373
+
374
+ made_equitable = True
375
+ break
376
+
377
+ if made_equitable:
378
+ break
379
+ else:
380
+ assert False, (
381
+ "Must find a w which is the solo neighbor "
382
+ "of two vertices in B_cal_prime."
383
+ )
384
+
385
+ if made_equitable:
386
+ break
387
+
388
+
389
+ @nx._dispatchable
390
+ def equitable_color(G, num_colors):
391
+ """Provides an equitable coloring for nodes of `G`.
392
+
393
+ Attempts to color a graph using `num_colors` colors, where no neighbors of
394
+ a node can have same color as the node itself and the number of nodes with
395
+ each color differ by at most 1. `num_colors` must be greater than the
396
+ maximum degree of `G`. The algorithm is described in [1]_ and has
397
+ complexity O(num_colors * n**2).
398
+
399
+ Parameters
400
+ ----------
401
+ G : networkX graph
402
+ The nodes of this graph will be colored.
403
+
404
+ num_colors : number of colors to use
405
+ This number must be at least one more than the maximum degree of nodes
406
+ in the graph.
407
+
408
+ Returns
409
+ -------
410
+ A dictionary with keys representing nodes and values representing
411
+ corresponding coloring.
412
+
413
+ Examples
414
+ --------
415
+ >>> G = nx.cycle_graph(4)
416
+ >>> nx.coloring.equitable_color(G, num_colors=3) # doctest: +SKIP
417
+ {0: 2, 1: 1, 2: 2, 3: 0}
418
+
419
+ Raises
420
+ ------
421
+ NetworkXAlgorithmError
422
+ If `num_colors` is not at least the maximum degree of the graph `G`
423
+
424
+ References
425
+ ----------
426
+ .. [1] Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E.
427
+ (2010). A fast algorithm for equitable coloring. Combinatorica, 30(2),
428
+ 217-224.
429
+ """
430
+
431
+ # Map nodes to integers for simplicity later.
432
+ nodes_to_int = {}
433
+ int_to_nodes = {}
434
+
435
+ for idx, node in enumerate(G.nodes):
436
+ nodes_to_int[node] = idx
437
+ int_to_nodes[idx] = node
438
+
439
+ G = nx.relabel_nodes(G, nodes_to_int, copy=True)
440
+
441
+ # Basic graph statistics and sanity check.
442
+ if len(G.nodes) > 0:
443
+ r_ = max(G.degree(node) for node in G.nodes)
444
+ else:
445
+ r_ = 0
446
+
447
+ if r_ >= num_colors:
448
+ raise nx.NetworkXAlgorithmError(
449
+ f"Graph has maximum degree {r_}, needs "
450
+ f"{r_ + 1} (> {num_colors}) colors for guaranteed coloring."
451
+ )
452
+
453
+ # Ensure that the number of nodes in G is a multiple of (r + 1)
454
+ pad_graph(G, num_colors)
455
+
456
+ # Starting the algorithm.
457
+ # L = {node: list(G.neighbors(node)) for node in G.nodes}
458
+ L_ = {node: [] for node in G.nodes}
459
+
460
+ # Arbitrary equitable allocation of colors to nodes.
461
+ F = {node: idx % num_colors for idx, node in enumerate(G.nodes)}
462
+
463
+ C = make_C_from_F(F)
464
+
465
+ # The neighborhood is empty initially.
466
+ N = make_N_from_L_C(L_, C)
467
+
468
+ # Currently all nodes witness all edges.
469
+ H = make_H_from_C_N(C, N)
470
+
471
+ # Start of algorithm.
472
+ edges_seen = set()
473
+
474
+ for u in sorted(G.nodes):
475
+ for v in sorted(G.neighbors(u)):
476
+ # Do not double count edges if (v, u) has already been seen.
477
+ if (v, u) in edges_seen:
478
+ continue
479
+
480
+ edges_seen.add((u, v))
481
+
482
+ L_[u].append(v)
483
+ L_[v].append(u)
484
+
485
+ N[(u, F[v])] += 1
486
+ N[(v, F[u])] += 1
487
+
488
+ if F[u] != F[v]:
489
+ # Were 'u' and 'v' witnesses for F[u] -> F[v] or F[v] -> F[u]?
490
+ if N[(u, F[v])] == 1:
491
+ H[F[u], F[v]] -= 1 # u cannot witness an edge between F[u], F[v]
492
+
493
+ if N[(v, F[u])] == 1:
494
+ H[F[v], F[u]] -= 1 # v cannot witness an edge between F[v], F[u]
495
+
496
+ if N[(u, F[u])] != 0:
497
+ # Find the first color where 'u' does not have any neighbors.
498
+ Y = next(k for k in C if N[(u, k)] == 0)
499
+ X = F[u]
500
+ change_color(u, X, Y, N=N, H=H, F=F, C=C, L=L_)
501
+
502
+ # Procedure P
503
+ procedure_P(V_minus=X, V_plus=Y, N=N, H=H, F=F, C=C, L=L_)
504
+
505
+ return {int_to_nodes[x]: F[x] for x in int_to_nodes}
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_connected.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc ADDED
Binary file (6.58 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_attracting.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ class TestAttractingComponents:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ cls.G1 = nx.DiGraph()
11
+ cls.G1.add_edges_from(
12
+ [
13
+ (5, 11),
14
+ (11, 2),
15
+ (11, 9),
16
+ (11, 10),
17
+ (7, 11),
18
+ (7, 8),
19
+ (8, 9),
20
+ (3, 8),
21
+ (3, 10),
22
+ ]
23
+ )
24
+ cls.G2 = nx.DiGraph()
25
+ cls.G2.add_edges_from([(0, 1), (0, 2), (1, 1), (1, 2), (2, 1)])
26
+
27
+ cls.G3 = nx.DiGraph()
28
+ cls.G3.add_edges_from([(0, 1), (1, 2), (2, 1), (0, 3), (3, 4), (4, 3)])
29
+
30
+ cls.G4 = nx.DiGraph()
31
+
32
+ def test_attracting_components(self):
33
+ ac = list(nx.attracting_components(self.G1))
34
+ assert {2} in ac
35
+ assert {9} in ac
36
+ assert {10} in ac
37
+
38
+ ac = list(nx.attracting_components(self.G2))
39
+ ac = [tuple(sorted(x)) for x in ac]
40
+ assert ac == [(1, 2)]
41
+
42
+ ac = list(nx.attracting_components(self.G3))
43
+ ac = [tuple(sorted(x)) for x in ac]
44
+ assert (1, 2) in ac
45
+ assert (3, 4) in ac
46
+ assert len(ac) == 2
47
+
48
+ ac = list(nx.attracting_components(self.G4))
49
+ assert ac == []
50
+
51
+ def test_number_attacting_components(self):
52
+ assert nx.number_attracting_components(self.G1) == 3
53
+ assert nx.number_attracting_components(self.G2) == 1
54
+ assert nx.number_attracting_components(self.G3) == 2
55
+ assert nx.number_attracting_components(self.G4) == 0
56
+
57
+ def test_is_attracting_component(self):
58
+ assert not nx.is_attracting_component(self.G1)
59
+ assert not nx.is_attracting_component(self.G2)
60
+ assert not nx.is_attracting_component(self.G3)
61
+ g2 = self.G3.subgraph([1, 2])
62
+ assert nx.is_attracting_component(g2)
63
+ assert not nx.is_attracting_component(self.G4)
64
+
65
+ def test_connected_raise(self):
66
+ G = nx.Graph()
67
+ with pytest.raises(NetworkXNotImplemented):
68
+ next(nx.attracting_components(G))
69
+ pytest.raises(NetworkXNotImplemented, nx.number_attracting_components, G)
70
+ pytest.raises(NetworkXNotImplemented, nx.is_attracting_component, G)
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ def assert_components_edges_equal(x, y):
8
+ sx = {frozenset(frozenset(e) for e in c) for c in x}
9
+ sy = {frozenset(frozenset(e) for e in c) for c in y}
10
+ assert sx == sy
11
+
12
+
13
+ def assert_components_equal(x, y):
14
+ sx = {frozenset(c) for c in x}
15
+ sy = {frozenset(c) for c in y}
16
+ assert sx == sy
17
+
18
+
19
+ def test_barbell():
20
+ G = nx.barbell_graph(8, 4)
21
+ nx.add_path(G, [7, 20, 21, 22])
22
+ nx.add_cycle(G, [22, 23, 24, 25])
23
+ pts = set(nx.articulation_points(G))
24
+ assert pts == {7, 8, 9, 10, 11, 12, 20, 21, 22}
25
+
26
+ answer = [
27
+ {12, 13, 14, 15, 16, 17, 18, 19},
28
+ {0, 1, 2, 3, 4, 5, 6, 7},
29
+ {22, 23, 24, 25},
30
+ {11, 12},
31
+ {10, 11},
32
+ {9, 10},
33
+ {8, 9},
34
+ {7, 8},
35
+ {21, 22},
36
+ {20, 21},
37
+ {7, 20},
38
+ ]
39
+ assert_components_equal(list(nx.biconnected_components(G)), answer)
40
+
41
+ G.add_edge(2, 17)
42
+ pts = set(nx.articulation_points(G))
43
+ assert pts == {7, 20, 21, 22}
44
+
45
+
46
+ def test_articulation_points_repetitions():
47
+ G = nx.Graph()
48
+ G.add_edges_from([(0, 1), (1, 2), (1, 3)])
49
+ assert list(nx.articulation_points(G)) == [1]
50
+
51
+
52
+ def test_articulation_points_cycle():
53
+ G = nx.cycle_graph(3)
54
+ nx.add_cycle(G, [1, 3, 4])
55
+ pts = set(nx.articulation_points(G))
56
+ assert pts == {1}
57
+
58
+
59
+ def test_is_biconnected():
60
+ G = nx.cycle_graph(3)
61
+ assert nx.is_biconnected(G)
62
+ nx.add_cycle(G, [1, 3, 4])
63
+ assert not nx.is_biconnected(G)
64
+
65
+
66
+ def test_empty_is_biconnected():
67
+ G = nx.empty_graph(5)
68
+ assert not nx.is_biconnected(G)
69
+ G.add_edge(0, 1)
70
+ assert not nx.is_biconnected(G)
71
+
72
+
73
+ def test_biconnected_components_cycle():
74
+ G = nx.cycle_graph(3)
75
+ nx.add_cycle(G, [1, 3, 4])
76
+ answer = [{0, 1, 2}, {1, 3, 4}]
77
+ assert_components_equal(list(nx.biconnected_components(G)), answer)
78
+
79
+
80
+ def test_biconnected_components1():
81
+ # graph example from
82
+ # https://web.archive.org/web/20121229123447/http://www.ibluemojo.com/school/articul_algorithm.html
83
+ edges = [
84
+ (0, 1),
85
+ (0, 5),
86
+ (0, 6),
87
+ (0, 14),
88
+ (1, 5),
89
+ (1, 6),
90
+ (1, 14),
91
+ (2, 4),
92
+ (2, 10),
93
+ (3, 4),
94
+ (3, 15),
95
+ (4, 6),
96
+ (4, 7),
97
+ (4, 10),
98
+ (5, 14),
99
+ (6, 14),
100
+ (7, 9),
101
+ (8, 9),
102
+ (8, 12),
103
+ (8, 13),
104
+ (10, 15),
105
+ (11, 12),
106
+ (11, 13),
107
+ (12, 13),
108
+ ]
109
+ G = nx.Graph(edges)
110
+ pts = set(nx.articulation_points(G))
111
+ assert pts == {4, 6, 7, 8, 9}
112
+ comps = list(nx.biconnected_component_edges(G))
113
+ answer = [
114
+ [(3, 4), (15, 3), (10, 15), (10, 4), (2, 10), (4, 2)],
115
+ [(13, 12), (13, 8), (11, 13), (12, 11), (8, 12)],
116
+ [(9, 8)],
117
+ [(7, 9)],
118
+ [(4, 7)],
119
+ [(6, 4)],
120
+ [(14, 0), (5, 1), (5, 0), (14, 5), (14, 1), (6, 14), (6, 0), (1, 6), (0, 1)],
121
+ ]
122
+ assert_components_edges_equal(comps, answer)
123
+
124
+
125
+ def test_biconnected_components2():
126
+ G = nx.Graph()
127
+ nx.add_cycle(G, "ABC")
128
+ nx.add_cycle(G, "CDE")
129
+ nx.add_cycle(G, "FIJHG")
130
+ nx.add_cycle(G, "GIJ")
131
+ G.add_edge("E", "G")
132
+ comps = list(nx.biconnected_component_edges(G))
133
+ answer = [
134
+ [
135
+ tuple("GF"),
136
+ tuple("FI"),
137
+ tuple("IG"),
138
+ tuple("IJ"),
139
+ tuple("JG"),
140
+ tuple("JH"),
141
+ tuple("HG"),
142
+ ],
143
+ [tuple("EG")],
144
+ [tuple("CD"), tuple("DE"), tuple("CE")],
145
+ [tuple("AB"), tuple("BC"), tuple("AC")],
146
+ ]
147
+ assert_components_edges_equal(comps, answer)
148
+
149
+
150
+ def test_biconnected_davis():
151
+ D = nx.davis_southern_women_graph()
152
+ bcc = list(nx.biconnected_components(D))[0]
153
+ assert set(D) == bcc # All nodes in a giant bicomponent
154
+ # So no articulation points
155
+ assert len(list(nx.articulation_points(D))) == 0
156
+
157
+
158
+ def test_biconnected_karate():
159
+ K = nx.karate_club_graph()
160
+ answer = [
161
+ {
162
+ 0,
163
+ 1,
164
+ 2,
165
+ 3,
166
+ 7,
167
+ 8,
168
+ 9,
169
+ 12,
170
+ 13,
171
+ 14,
172
+ 15,
173
+ 17,
174
+ 18,
175
+ 19,
176
+ 20,
177
+ 21,
178
+ 22,
179
+ 23,
180
+ 24,
181
+ 25,
182
+ 26,
183
+ 27,
184
+ 28,
185
+ 29,
186
+ 30,
187
+ 31,
188
+ 32,
189
+ 33,
190
+ },
191
+ {0, 4, 5, 6, 10, 16},
192
+ {0, 11},
193
+ ]
194
+ bcc = list(nx.biconnected_components(K))
195
+ assert_components_equal(bcc, answer)
196
+ assert set(nx.articulation_points(K)) == {0}
197
+
198
+
199
+ def test_biconnected_eppstein():
200
+ # tests from http://www.ics.uci.edu/~eppstein/PADS/Biconnectivity.py
201
+ G1 = nx.Graph(
202
+ {
203
+ 0: [1, 2, 5],
204
+ 1: [0, 5],
205
+ 2: [0, 3, 4],
206
+ 3: [2, 4, 5, 6],
207
+ 4: [2, 3, 5, 6],
208
+ 5: [0, 1, 3, 4],
209
+ 6: [3, 4],
210
+ }
211
+ )
212
+ G2 = nx.Graph(
213
+ {
214
+ 0: [2, 5],
215
+ 1: [3, 8],
216
+ 2: [0, 3, 5],
217
+ 3: [1, 2, 6, 8],
218
+ 4: [7],
219
+ 5: [0, 2],
220
+ 6: [3, 8],
221
+ 7: [4],
222
+ 8: [1, 3, 6],
223
+ }
224
+ )
225
+ assert nx.is_biconnected(G1)
226
+ assert not nx.is_biconnected(G2)
227
+ answer_G2 = [{1, 3, 6, 8}, {0, 2, 5}, {2, 3}, {4, 7}]
228
+ bcc = list(nx.biconnected_components(G2))
229
+ assert_components_equal(bcc, answer_G2)
230
+
231
+
232
+ def test_null_graph():
233
+ G = nx.Graph()
234
+ assert not nx.is_biconnected(G)
235
+ assert list(nx.biconnected_components(G)) == []
236
+ assert list(nx.biconnected_component_edges(G)) == []
237
+ assert list(nx.articulation_points(G)) == []
238
+
239
+
240
+ def test_connected_raise():
241
+ DG = nx.DiGraph()
242
+ with pytest.raises(NetworkXNotImplemented):
243
+ next(nx.biconnected_components(DG))
244
+ with pytest.raises(NetworkXNotImplemented):
245
+ next(nx.biconnected_component_edges(DG))
246
+ with pytest.raises(NetworkXNotImplemented):
247
+ next(nx.articulation_points(DG))
248
+ pytest.raises(NetworkXNotImplemented, nx.is_biconnected, DG)
janus/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_semiconnected.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestIsSemiconnected:
9
+ def test_undirected(self):
10
+ pytest.raises(nx.NetworkXNotImplemented, nx.is_semiconnected, nx.Graph())
11
+ pytest.raises(nx.NetworkXNotImplemented, nx.is_semiconnected, nx.MultiGraph())
12
+
13
+ def test_empty(self):
14
+ pytest.raises(nx.NetworkXPointlessConcept, nx.is_semiconnected, nx.DiGraph())
15
+ pytest.raises(
16
+ nx.NetworkXPointlessConcept, nx.is_semiconnected, nx.MultiDiGraph()
17
+ )
18
+
19
+ def test_single_node_graph(self):
20
+ G = nx.DiGraph()
21
+ G.add_node(0)
22
+ assert nx.is_semiconnected(G)
23
+
24
+ def test_path(self):
25
+ G = nx.path_graph(100, create_using=nx.DiGraph())
26
+ assert nx.is_semiconnected(G)
27
+ G.add_edge(100, 99)
28
+ assert not nx.is_semiconnected(G)
29
+
30
+ def test_cycle(self):
31
+ G = nx.cycle_graph(100, create_using=nx.DiGraph())
32
+ assert nx.is_semiconnected(G)
33
+ G = nx.path_graph(100, create_using=nx.DiGraph())
34
+ G.add_edge(0, 99)
35
+ assert nx.is_semiconnected(G)
36
+
37
+ def test_tree(self):
38
+ G = nx.DiGraph()
39
+ G.add_edges_from(
40
+ chain.from_iterable([(i, 2 * i + 1), (i, 2 * i + 2)] for i in range(100))
41
+ )
42
+ assert not nx.is_semiconnected(G)
43
+
44
+ def test_dumbbell(self):
45
+ G = nx.cycle_graph(100, create_using=nx.DiGraph())
46
+ G.add_edges_from((i + 100, (i + 1) % 100 + 100) for i in range(100))
47
+ assert not nx.is_semiconnected(G) # G is disconnected.
48
+ G.add_edge(100, 99)
49
+ assert nx.is_semiconnected(G)
50
+
51
+ def test_alternating_path(self):
52
+ G = nx.DiGraph(
53
+ chain.from_iterable([(i, i - 1), (i, i + 1)] for i in range(0, 100, 2))
54
+ )
55
+ assert not nx.is_semiconnected(G)
janus/lib/python3.10/site-packages/networkx/algorithms/components/weakly_connected.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Weakly connected components."""
2
+
3
+ import networkx as nx
4
+ from networkx.utils.decorators import not_implemented_for
5
+
6
+ __all__ = [
7
+ "number_weakly_connected_components",
8
+ "weakly_connected_components",
9
+ "is_weakly_connected",
10
+ ]
11
+
12
+
13
+ @not_implemented_for("undirected")
14
+ @nx._dispatchable
15
+ def weakly_connected_components(G):
16
+ """Generate weakly connected components of G.
17
+
18
+ Parameters
19
+ ----------
20
+ G : NetworkX graph
21
+ A directed graph
22
+
23
+ Returns
24
+ -------
25
+ comp : generator of sets
26
+ A generator of sets of nodes, one for each weakly connected
27
+ component of G.
28
+
29
+ Raises
30
+ ------
31
+ NetworkXNotImplemented
32
+ If G is undirected.
33
+
34
+ Examples
35
+ --------
36
+ Generate a sorted list of weakly connected components, largest first.
37
+
38
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph())
39
+ >>> nx.add_path(G, [10, 11, 12])
40
+ >>> [
41
+ ... len(c)
42
+ ... for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)
43
+ ... ]
44
+ [4, 3]
45
+
46
+ If you only want the largest component, it's more efficient to
47
+ use max instead of sort:
48
+
49
+ >>> largest_cc = max(nx.weakly_connected_components(G), key=len)
50
+
51
+ See Also
52
+ --------
53
+ connected_components
54
+ strongly_connected_components
55
+
56
+ Notes
57
+ -----
58
+ For directed graphs only.
59
+
60
+ """
61
+ seen = set()
62
+ n = len(G) # must be outside the loop to avoid performance hit with graph views
63
+ for v in G:
64
+ if v not in seen:
65
+ c = set(_plain_bfs(G, n, v))
66
+ seen.update(c)
67
+ yield c
68
+
69
+
70
+ @not_implemented_for("undirected")
71
+ @nx._dispatchable
72
+ def number_weakly_connected_components(G):
73
+ """Returns the number of weakly connected components in G.
74
+
75
+ Parameters
76
+ ----------
77
+ G : NetworkX graph
78
+ A directed graph.
79
+
80
+ Returns
81
+ -------
82
+ n : integer
83
+ Number of weakly connected components
84
+
85
+ Raises
86
+ ------
87
+ NetworkXNotImplemented
88
+ If G is undirected.
89
+
90
+ Examples
91
+ --------
92
+ >>> G = nx.DiGraph([(0, 1), (2, 1), (3, 4)])
93
+ >>> nx.number_weakly_connected_components(G)
94
+ 2
95
+
96
+ See Also
97
+ --------
98
+ weakly_connected_components
99
+ number_connected_components
100
+ number_strongly_connected_components
101
+
102
+ Notes
103
+ -----
104
+ For directed graphs only.
105
+
106
+ """
107
+ return sum(1 for wcc in weakly_connected_components(G))
108
+
109
+
110
+ @not_implemented_for("undirected")
111
+ @nx._dispatchable
112
+ def is_weakly_connected(G):
113
+ """Test directed graph for weak connectivity.
114
+
115
+ A directed graph is weakly connected if and only if the graph
116
+ is connected when the direction of the edge between nodes is ignored.
117
+
118
+ Note that if a graph is strongly connected (i.e. the graph is connected
119
+ even when we account for directionality), it is by definition weakly
120
+ connected as well.
121
+
122
+ Parameters
123
+ ----------
124
+ G : NetworkX Graph
125
+ A directed graph.
126
+
127
+ Returns
128
+ -------
129
+ connected : bool
130
+ True if the graph is weakly connected, False otherwise.
131
+
132
+ Raises
133
+ ------
134
+ NetworkXNotImplemented
135
+ If G is undirected.
136
+
137
+ Examples
138
+ --------
139
+ >>> G = nx.DiGraph([(0, 1), (2, 1)])
140
+ >>> G.add_node(3)
141
+ >>> nx.is_weakly_connected(G) # node 3 is not connected to the graph
142
+ False
143
+ >>> G.add_edge(2, 3)
144
+ >>> nx.is_weakly_connected(G)
145
+ True
146
+
147
+ See Also
148
+ --------
149
+ is_strongly_connected
150
+ is_semiconnected
151
+ is_connected
152
+ is_biconnected
153
+ weakly_connected_components
154
+
155
+ Notes
156
+ -----
157
+ For directed graphs only.
158
+
159
+ """
160
+ if len(G) == 0:
161
+ raise nx.NetworkXPointlessConcept(
162
+ """Connectivity is undefined for the null graph."""
163
+ )
164
+
165
+ return len(next(weakly_connected_components(G))) == len(G)
166
+
167
+
168
+ def _plain_bfs(G, n, source):
169
+ """A fast BFS node generator
170
+
171
+ The direction of the edge between nodes is ignored.
172
+
173
+ For directed graphs only.
174
+
175
+ """
176
+ Gsucc = G._succ
177
+ Gpred = G._pred
178
+ seen = {source}
179
+ nextlevel = [source]
180
+
181
+ yield source
182
+ while nextlevel:
183
+ thislevel = nextlevel
184
+ nextlevel = []
185
+ for v in thislevel:
186
+ for w in Gsucc[v]:
187
+ if w not in seen:
188
+ seen.add(w)
189
+ nextlevel.append(w)
190
+ yield w
191
+ for w in Gpred[v]:
192
+ if w not in seen:
193
+ seen.add(w)
194
+ nextlevel.append(w)
195
+ yield w
196
+ if len(seen) == n:
197
+ return
janus/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png ADDED

Git LFS Details

  • SHA256: 1508bda48445c23ab882f801f1c0dd0472f97ae414245c3ab1094005fda4455a
  • Pointer size: 130 Bytes
  • Size of remote file: 21.9 kB
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc ADDED
Binary file (38.9 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc ADDED
Binary file (2.32 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc ADDED
Binary file (4.12 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc ADDED
Binary file (26.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/atlas.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for the small graph atlas.
3
+ """
4
+
5
+ import gzip
6
+ import importlib.resources
7
+ import os
8
+ import os.path
9
+ from itertools import islice
10
+
11
+ import networkx as nx
12
+
13
+ __all__ = ["graph_atlas", "graph_atlas_g"]
14
+
15
+ #: The total number of graphs in the atlas.
16
+ #:
17
+ #: The graphs are labeled starting from 0 and extending to (but not
18
+ #: including) this number.
19
+ NUM_GRAPHS = 1253
20
+
21
+ #: The path to the data file containing the graph edge lists.
22
+ #:
23
+ #: This is the absolute path of the gzipped text file containing the
24
+ #: edge list for each graph in the atlas. The file contains one entry
25
+ #: per graph in the atlas, in sequential order, starting from graph
26
+ #: number 0 and extending through graph number 1252 (see
27
+ #: :data:`NUM_GRAPHS`). Each entry looks like
28
+ #:
29
+ #: .. sourcecode:: text
30
+ #:
31
+ #: GRAPH 6
32
+ #: NODES 3
33
+ #: 0 1
34
+ #: 0 2
35
+ #:
36
+ #: where the first two lines are the graph's index in the atlas and the
37
+ #: number of nodes in the graph, and the remaining lines are the edge
38
+ #: list.
39
+ #:
40
+ #: This file was generated from a Python list of graphs via code like
41
+ #: the following::
42
+ #:
43
+ #: import gzip
44
+ #: from networkx.generators.atlas import graph_atlas_g
45
+ #: from networkx.readwrite.edgelist import write_edgelist
46
+ #:
47
+ #: with gzip.open('atlas.dat.gz', 'wb') as f:
48
+ #: for i, G in enumerate(graph_atlas_g()):
49
+ #: f.write(bytes(f'GRAPH {i}\n', encoding='utf-8'))
50
+ #: f.write(bytes(f'NODES {len(G)}\n', encoding='utf-8'))
51
+ #: write_edgelist(G, f, data=False)
52
+ #:
53
+
54
+ # Path to the atlas file
55
+ ATLAS_FILE = importlib.resources.files("networkx.generators") / "atlas.dat.gz"
56
+
57
+
58
+ def _generate_graphs():
59
+ """Sequentially read the file containing the edge list data for the
60
+ graphs in the atlas and generate the graphs one at a time.
61
+
62
+ This function reads the file given in :data:`.ATLAS_FILE`.
63
+
64
+ """
65
+ with gzip.open(ATLAS_FILE, "rb") as f:
66
+ line = f.readline()
67
+ while line and line.startswith(b"GRAPH"):
68
+ # The first two lines of each entry tell us the index of the
69
+ # graph in the list and the number of nodes in the graph.
70
+ # They look like this:
71
+ #
72
+ # GRAPH 3
73
+ # NODES 2
74
+ #
75
+ graph_index = int(line[6:].rstrip())
76
+ line = f.readline()
77
+ num_nodes = int(line[6:].rstrip())
78
+ # The remaining lines contain the edge list, until the next
79
+ # GRAPH line (or until the end of the file).
80
+ edgelist = []
81
+ line = f.readline()
82
+ while line and not line.startswith(b"GRAPH"):
83
+ edgelist.append(line.rstrip())
84
+ line = f.readline()
85
+ G = nx.Graph()
86
+ G.name = f"G{graph_index}"
87
+ G.add_nodes_from(range(num_nodes))
88
+ G.add_edges_from(tuple(map(int, e.split())) for e in edgelist)
89
+ yield G
90
+
91
+
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def graph_atlas(i):
94
+ """Returns graph number `i` from the Graph Atlas.
95
+
96
+ For more information, see :func:`.graph_atlas_g`.
97
+
98
+ Parameters
99
+ ----------
100
+ i : int
101
+ The index of the graph from the atlas to get. The graph at index
102
+ 0 is assumed to be the null graph.
103
+
104
+ Returns
105
+ -------
106
+ list
107
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
108
+ corresponding to the graph *i* in the Graph Atlas.
109
+
110
+ See also
111
+ --------
112
+ graph_atlas_g
113
+
114
+ Notes
115
+ -----
116
+ The time required by this function increases linearly with the
117
+ argument `i`, since it reads a large file sequentially in order to
118
+ generate the graph [1]_.
119
+
120
+ References
121
+ ----------
122
+ .. [1] Ronald C. Read and Robin J. Wilson, *An Atlas of Graphs*.
123
+ Oxford University Press, 1998.
124
+
125
+ """
126
+ if not (0 <= i < NUM_GRAPHS):
127
+ raise ValueError(f"index must be between 0 and {NUM_GRAPHS}")
128
+ return next(islice(_generate_graphs(), i, None))
129
+
130
+
131
+ @nx._dispatchable(graphs=None, returns_graph=True)
132
+ def graph_atlas_g():
133
+ """Returns the list of all graphs with up to seven nodes named in the
134
+ Graph Atlas.
135
+
136
+ The graphs are listed in increasing order by
137
+
138
+ 1. number of nodes,
139
+ 2. number of edges,
140
+ 3. degree sequence (for example 111223 < 112222),
141
+ 4. number of automorphisms,
142
+
143
+ in that order, with three exceptions as described in the *Notes*
144
+ section below. This causes the list to correspond with the index of
145
+ the graphs in the Graph Atlas [atlas]_, with the first graph,
146
+ ``G[0]``, being the null graph.
147
+
148
+ Returns
149
+ -------
150
+ list
151
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
152
+ corresponding to the graph *i* in the Graph Atlas.
153
+
154
+ See also
155
+ --------
156
+ graph_atlas
157
+
158
+ Notes
159
+ -----
160
+ This function may be expensive in both time and space, since it
161
+ reads a large file sequentially in order to populate the list.
162
+
163
+ Although the NetworkX atlas functions match the order of graphs
164
+ given in the "Atlas of Graphs" book, there are (at least) three
165
+ errors in the ordering described in the book. The following three
166
+ pairs of nodes violate the lexicographically nondecreasing sorted
167
+ degree sequence rule:
168
+
169
+ - graphs 55 and 56 with degree sequences 001111 and 000112,
170
+ - graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
171
+ - graphs 1012 and 1213 with degree sequences 1244555 and 1244456.
172
+
173
+ References
174
+ ----------
175
+ .. [atlas] Ronald C. Read and Robin J. Wilson,
176
+ *An Atlas of Graphs*.
177
+ Oxford University Press, 1998.
178
+
179
+ """
180
+ return list(_generate_graphs())
janus/lib/python3.10/site-packages/networkx/generators/cographs.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ import networkx as nx
16
+ from networkx.utils import py_random_state
17
+
18
+ __all__ = ["random_cograph"]
19
+
20
+
21
+ @py_random_state(1)
22
+ @nx._dispatchable(graphs=None, returns_graph=True)
23
+ def random_cograph(n, seed=None):
24
+ r"""Returns a random cograph with $2 ^ n$ nodes.
25
+
26
+ A cograph is a graph containing no path on four vertices.
27
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
28
+ by disjoint union and complementation operations.
29
+
30
+ This generator starts off from a single vertex and performs disjoint
31
+ union and full join operations on itself.
32
+ The decision on which operation will take place is random.
33
+
34
+ Parameters
35
+ ----------
36
+ n : int
37
+ The order of the cograph.
38
+ seed : integer, random_state, or None (default)
39
+ Indicator of random number generation state.
40
+ See :ref:`Randomness<randomness>`.
41
+
42
+ Returns
43
+ -------
44
+ G : A random graph containing no path on four vertices.
45
+
46
+ See Also
47
+ --------
48
+ full_join
49
+ union
50
+
51
+ References
52
+ ----------
53
+ .. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
54
+ "Complement reducible graphs",
55
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
56
+ ISSN 0166-218X.
57
+ """
58
+ R = nx.empty_graph(1)
59
+
60
+ for i in range(n):
61
+ RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
62
+
63
+ if seed.randint(0, 1) == 0:
64
+ R = nx.full_join(R, RR)
65
+ else:
66
+ R = nx.disjoint_union(R, RR)
67
+
68
+ return R
janus/lib/python3.10/site-packages/networkx/generators/duplication.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ import networkx as nx
10
+ from networkx.exception import NetworkXError
11
+ from networkx.utils import py_random_state
12
+ from networkx.utils.misc import check_create_using
13
+
14
+ __all__ = ["partial_duplication_graph", "duplication_divergence_graph"]
15
+
16
+
17
+ @py_random_state(4)
18
+ @nx._dispatchable(graphs=None, returns_graph=True)
19
+ def partial_duplication_graph(N, n, p, q, seed=None, *, create_using=None):
20
+ """Returns a random graph using the partial duplication model.
21
+
22
+ Parameters
23
+ ----------
24
+ N : int
25
+ The total number of nodes in the final graph.
26
+
27
+ n : int
28
+ The number of nodes in the initial clique.
29
+
30
+ p : float
31
+ The probability of joining each neighbor of a node to the
32
+ duplicate node. Must be a number in the between zero and one,
33
+ inclusive.
34
+
35
+ q : float
36
+ The probability of joining the source node to the duplicate
37
+ node. Must be a number in the between zero and one, inclusive.
38
+
39
+ seed : integer, random_state, or None (default)
40
+ Indicator of random number generation state.
41
+ See :ref:`Randomness<randomness>`.
42
+
43
+ create_using : Graph constructor, optional (default=nx.Graph)
44
+ Graph type to create. If graph instance, then cleared before populated.
45
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
46
+
47
+ Notes
48
+ -----
49
+ A graph of nodes is grown by creating a fully connected graph
50
+ of size `n`. The following procedure is then repeated until
51
+ a total of `N` nodes have been reached.
52
+
53
+ 1. A random node, *u*, is picked and a new node, *v*, is created.
54
+ 2. For each neighbor of *u* an edge from the neighbor to *v* is created
55
+ with probability `p`.
56
+ 3. An edge from *u* to *v* is created with probability `q`.
57
+
58
+ This algorithm appears in [1].
59
+
60
+ This implementation allows the possibility of generating
61
+ disconnected graphs.
62
+
63
+ References
64
+ ----------
65
+ .. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
66
+ randomly grown graphs." Journal of Applied Mathematics 2008.
67
+ <https://doi.org/10.1155/2008/190836>
68
+
69
+ """
70
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
71
+ if p < 0 or p > 1 or q < 0 or q > 1:
72
+ msg = "partial duplication graph must have 0 <= p, q <= 1."
73
+ raise NetworkXError(msg)
74
+ if n > N:
75
+ raise NetworkXError("partial duplication graph must have n <= N.")
76
+
77
+ G = nx.complete_graph(n, create_using)
78
+ for new_node in range(n, N):
79
+ # Pick a random vertex, u, already in the graph.
80
+ src_node = seed.randint(0, new_node - 1)
81
+
82
+ # Add a new vertex, v, to the graph.
83
+ G.add_node(new_node)
84
+
85
+ # For each neighbor of u...
86
+ for nbr_node in list(nx.all_neighbors(G, src_node)):
87
+ # Add the neighbor to v with probability p.
88
+ if seed.random() < p:
89
+ G.add_edge(new_node, nbr_node)
90
+
91
+ # Join v and u with probability q.
92
+ if seed.random() < q:
93
+ G.add_edge(new_node, src_node)
94
+ return G
95
+
96
+
97
+ @py_random_state(2)
98
+ @nx._dispatchable(graphs=None, returns_graph=True)
99
+ def duplication_divergence_graph(n, p, seed=None, *, create_using=None):
100
+ """Returns an undirected graph using the duplication-divergence model.
101
+
102
+ A graph of `n` nodes is created by duplicating the initial nodes
103
+ and retaining edges incident to the original nodes with a retention
104
+ probability `p`.
105
+
106
+ Parameters
107
+ ----------
108
+ n : int
109
+ The desired number of nodes in the graph.
110
+ p : float
111
+ The probability for retaining the edge of the replicated node.
112
+ seed : integer, random_state, or None (default)
113
+ Indicator of random number generation state.
114
+ See :ref:`Randomness<randomness>`.
115
+ create_using : Graph constructor, optional (default=nx.Graph)
116
+ Graph type to create. If graph instance, then cleared before populated.
117
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
118
+
119
+ Returns
120
+ -------
121
+ G : Graph
122
+
123
+ Raises
124
+ ------
125
+ NetworkXError
126
+ If `p` is not a valid probability.
127
+ If `n` is less than 2.
128
+
129
+ Notes
130
+ -----
131
+ This algorithm appears in [1].
132
+
133
+ This implementation disallows the possibility of generating
134
+ disconnected graphs.
135
+
136
+ References
137
+ ----------
138
+ .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
139
+ "Duplication-divergence model of protein interaction network",
140
+ Phys. Rev. E, 71, 061911, 2005.
141
+
142
+ """
143
+ if p > 1 or p < 0:
144
+ msg = f"NetworkXError p={p} is not in [0,1]."
145
+ raise nx.NetworkXError(msg)
146
+ if n < 2:
147
+ msg = "n must be greater than or equal to 2"
148
+ raise nx.NetworkXError(msg)
149
+
150
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
151
+ G = nx.empty_graph(create_using=create_using)
152
+
153
+ # Initialize the graph with two connected nodes.
154
+ G.add_edge(0, 1)
155
+ i = 2
156
+ while i < n:
157
+ # Choose a random node from current graph to duplicate.
158
+ random_node = seed.choice(list(G))
159
+ # Make the replica.
160
+ G.add_node(i)
161
+ # flag indicates whether at least one edge is connected on the replica.
162
+ flag = False
163
+ for nbr in G.neighbors(random_node):
164
+ if seed.random() < p:
165
+ # Link retention step.
166
+ G.add_edge(i, nbr)
167
+ flag = True
168
+ if not flag:
169
+ # Delete replica if no edges retained.
170
+ G.remove_node(i)
171
+ else:
172
+ # Successful duplication.
173
+ i += 1
174
+ return G
janus/lib/python3.10/site-packages/networkx/generators/ego.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ego graph.
3
+ """
4
+
5
+ __all__ = ["ego_graph"]
6
+
7
+ import networkx as nx
8
+
9
+
10
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
11
+ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
12
+ """Returns induced subgraph of neighbors centered at node n within
13
+ a given radius.
14
+
15
+ Parameters
16
+ ----------
17
+ G : graph
18
+ A NetworkX Graph or DiGraph
19
+
20
+ n : node
21
+ A single node
22
+
23
+ radius : number, optional
24
+ Include all neighbors of distance<=radius from n.
25
+
26
+ center : bool, optional
27
+ If False, do not include center node in graph
28
+
29
+ undirected : bool, optional
30
+ If True use both in- and out-neighbors of directed graphs.
31
+
32
+ distance : key, optional
33
+ Use specified edge data key as distance. For example, setting
34
+ distance='weight' will use the edge weight to measure the
35
+ distance from the node n.
36
+
37
+ Notes
38
+ -----
39
+ For directed graphs D this produces the "out" neighborhood
40
+ or successors. If you want the neighborhood of predecessors
41
+ first reverse the graph with D.reverse(). If you want both
42
+ directions use the keyword argument undirected=True.
43
+
44
+ Node, edge, and graph attributes are copied to the returned subgraph.
45
+ """
46
+ if undirected:
47
+ if distance is not None:
48
+ sp, _ = nx.single_source_dijkstra(
49
+ G.to_undirected(), n, cutoff=radius, weight=distance
50
+ )
51
+ else:
52
+ sp = dict(
53
+ nx.single_source_shortest_path_length(
54
+ G.to_undirected(), n, cutoff=radius
55
+ )
56
+ )
57
+ else:
58
+ if distance is not None:
59
+ sp, _ = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
60
+ else:
61
+ sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))
62
+
63
+ H = G.subgraph(sp).copy()
64
+ if not center:
65
+ H.remove_node(n)
66
+ return H
janus/lib/python3.10/site-packages/networkx/generators/expanders.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides explicit constructions of expander graphs."""
2
+
3
+ import itertools
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "margulis_gabber_galil_graph",
9
+ "chordal_cycle_graph",
10
+ "paley_graph",
11
+ "maybe_regular_expander",
12
+ "is_regular_expander",
13
+ "random_regular_expander_graph",
14
+ ]
15
+
16
+
17
+ # Other discrete torus expanders can be constructed by using the following edge
18
+ # sets. For more information, see Chapter 4, "Expander Graphs", in
19
+ # "Pseudorandomness", by Salil Vadhan.
20
+ #
21
+ # For a directed expander, add edges from (x, y) to:
22
+ #
23
+ # (x, y),
24
+ # ((x + 1) % n, y),
25
+ # (x, (y + 1) % n),
26
+ # (x, (x + y) % n),
27
+ # (-y % n, x)
28
+ #
29
+ # For an undirected expander, add the reverse edges.
30
+ #
31
+ # Also appearing in the paper of Gabber and Galil:
32
+ #
33
+ # (x, y),
34
+ # (x, (x + y) % n),
35
+ # (x, (x + y + 1) % n),
36
+ # ((x + y) % n, y),
37
+ # ((x + y + 1) % n, y)
38
+ #
39
+ # and:
40
+ #
41
+ # (x, y),
42
+ # ((x + 2*y) % n, y),
43
+ # ((x + (2*y + 1)) % n, y),
44
+ # ((x + (2*y + 2)) % n, y),
45
+ # (x, (y + 2*x) % n),
46
+ # (x, (y + (2*x + 1)) % n),
47
+ # (x, (y + (2*x + 2)) % n),
48
+ #
49
+ @nx._dispatchable(graphs=None, returns_graph=True)
50
+ def margulis_gabber_galil_graph(n, create_using=None):
51
+ r"""Returns the Margulis-Gabber-Galil undirected MultiGraph on `n^2` nodes.
52
+
53
+ The undirected MultiGraph is regular with degree `8`. Nodes are integer
54
+ pairs. The second-largest eigenvalue of the adjacency matrix of the graph
55
+ is at most `5 \sqrt{2}`, regardless of `n`.
56
+
57
+ Parameters
58
+ ----------
59
+ n : int
60
+ Determines the number of nodes in the graph: `n^2`.
61
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
62
+ Graph type to create. If graph instance, then cleared before populated.
63
+
64
+ Returns
65
+ -------
66
+ G : graph
67
+ The constructed undirected multigraph.
68
+
69
+ Raises
70
+ ------
71
+ NetworkXError
72
+ If the graph is directed or not a multigraph.
73
+
74
+ """
75
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
76
+ if G.is_directed() or not G.is_multigraph():
77
+ msg = "`create_using` must be an undirected multigraph."
78
+ raise nx.NetworkXError(msg)
79
+
80
+ for x, y in itertools.product(range(n), repeat=2):
81
+ for u, v in (
82
+ ((x + 2 * y) % n, y),
83
+ ((x + (2 * y + 1)) % n, y),
84
+ (x, (y + 2 * x) % n),
85
+ (x, (y + (2 * x + 1)) % n),
86
+ ):
87
+ G.add_edge((x, y), (u, v))
88
+ G.graph["name"] = f"margulis_gabber_galil_graph({n})"
89
+ return G
90
+
91
+
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def chordal_cycle_graph(p, create_using=None):
94
+ """Returns the chordal cycle graph on `p` nodes.
95
+
96
+ The returned graph is a cycle graph on `p` nodes with chords joining each
97
+ vertex `x` to its inverse modulo `p`. This graph is a (mildly explicit)
98
+ 3-regular expander [1]_.
99
+
100
+ `p` *must* be a prime number.
101
+
102
+ Parameters
103
+ ----------
104
+ p : a prime number
105
+
106
+ The number of vertices in the graph. This also indicates where the
107
+ chordal edges in the cycle will be created.
108
+
109
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
110
+ Graph type to create. If graph instance, then cleared before populated.
111
+
112
+ Returns
113
+ -------
114
+ G : graph
115
+ The constructed undirected multigraph.
116
+
117
+ Raises
118
+ ------
119
+ NetworkXError
120
+
121
+ If `create_using` indicates directed or not a multigraph.
122
+
123
+ References
124
+ ----------
125
+
126
+ .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and
127
+ invariant measures", volume 125 of Progress in Mathematics.
128
+ Birkhäuser Verlag, Basel, 1994.
129
+
130
+ """
131
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
132
+ if G.is_directed() or not G.is_multigraph():
133
+ msg = "`create_using` must be an undirected multigraph."
134
+ raise nx.NetworkXError(msg)
135
+
136
+ for x in range(p):
137
+ left = (x - 1) % p
138
+ right = (x + 1) % p
139
+ # Here we apply Fermat's Little Theorem to compute the multiplicative
140
+ # inverse of x in Z/pZ. By Fermat's Little Theorem,
141
+ #
142
+ # x^p = x (mod p)
143
+ #
144
+ # Therefore,
145
+ #
146
+ # x * x^(p - 2) = 1 (mod p)
147
+ #
148
+ # The number 0 is a special case: we just let its inverse be itself.
149
+ chord = pow(x, p - 2, p) if x > 0 else 0
150
+ for y in (left, right, chord):
151
+ G.add_edge(x, y)
152
+ G.graph["name"] = f"chordal_cycle_graph({p})"
153
+ return G
154
+
155
+
156
+ @nx._dispatchable(graphs=None, returns_graph=True)
157
+ def paley_graph(p, create_using=None):
158
+ r"""Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
159
+
160
+ The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
161
+ if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
162
+
163
+ 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
164
+ only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
165
+
166
+ 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$
167
+ is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
168
+
169
+ Note that a more general definition of Paley graphs extends this construction
170
+ to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of $\mathbb{Z}/p\mathbb{Z}$.
171
+ This construction requires to compute squares in general finite fields and is
172
+ not what is implemented here (i.e `paley_graph(25)` does not return the true
173
+ Paley graph associated with $5^2$).
174
+
175
+ Parameters
176
+ ----------
177
+ p : int, an odd prime number.
178
+
179
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
180
+ Graph type to create. If graph instance, then cleared before populated.
181
+
182
+ Returns
183
+ -------
184
+ G : graph
185
+ The constructed directed graph.
186
+
187
+ Raises
188
+ ------
189
+ NetworkXError
190
+ If the graph is a multigraph.
191
+
192
+ References
193
+ ----------
194
+ Chapter 13 in B. Bollobas, Random Graphs. Second edition.
195
+ Cambridge Studies in Advanced Mathematics, 73.
196
+ Cambridge University Press, Cambridge (2001).
197
+ """
198
+ G = nx.empty_graph(0, create_using, default=nx.DiGraph)
199
+ if G.is_multigraph():
200
+ msg = "`create_using` cannot be a multigraph."
201
+ raise nx.NetworkXError(msg)
202
+
203
+ # Compute the squares in Z/pZ.
204
+ # Make it a set to uniquify (there are exactly (p-1)/2 squares in Z/pZ
205
+ # when is prime).
206
+ square_set = {(x**2) % p for x in range(1, p) if (x**2) % p != 0}
207
+
208
+ for x in range(p):
209
+ for x2 in square_set:
210
+ G.add_edge(x, (x + x2) % p)
211
+ G.graph["name"] = f"paley({p})"
212
+ return G
213
+
214
+
215
+ @nx.utils.decorators.np_random_state("seed")
216
+ @nx._dispatchable(graphs=None, returns_graph=True)
217
+ def maybe_regular_expander(n, d, *, create_using=None, max_tries=100, seed=None):
218
+ r"""Utility for creating a random regular expander.
219
+
220
+ Returns a random $d$-regular graph on $n$ nodes which is an expander
221
+ graph with very good probability.
222
+
223
+ Parameters
224
+ ----------
225
+ n : int
226
+ The number of nodes.
227
+ d : int
228
+ The degree of each node.
229
+ create_using : Graph Instance or Constructor
230
+ Indicator of type of graph to return.
231
+ If a Graph-type instance, then clear and use it.
232
+ If a constructor, call it to create an empty graph.
233
+ Use the Graph constructor by default.
234
+ max_tries : int. (default: 100)
235
+ The number of allowed loops when generating each independent cycle
236
+ seed : (default: None)
237
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
238
+
239
+ Notes
240
+ -----
241
+ The nodes are numbered from $0$ to $n - 1$.
242
+
243
+ The graph is generated by taking $d / 2$ random independent cycles.
244
+
245
+ Joel Friedman proved that in this model the resulting
246
+ graph is an expander with probability
247
+ $1 - O(n^{-\tau})$ where $\tau = \lceil (\sqrt{d - 1}) / 2 \rceil - 1$. [1]_
248
+
249
+ Examples
250
+ --------
251
+ >>> G = nx.maybe_regular_expander(n=200, d=6, seed=8020)
252
+
253
+ Returns
254
+ -------
255
+ G : graph
256
+ The constructed undirected graph.
257
+
258
+ Raises
259
+ ------
260
+ NetworkXError
261
+ If $d % 2 != 0$ as the degree must be even.
262
+ If $n - 1$ is less than $ 2d $ as the graph is complete at most.
263
+ If max_tries is reached
264
+
265
+ See Also
266
+ --------
267
+ is_regular_expander
268
+ random_regular_expander_graph
269
+
270
+ References
271
+ ----------
272
+ .. [1] Joel Friedman,
273
+ A Proof of Alon’s Second Eigenvalue Conjecture and Related Problems, 2004
274
+ https://arxiv.org/abs/cs/0405020
275
+
276
+ """
277
+
278
+ import numpy as np
279
+
280
+ if n < 1:
281
+ raise nx.NetworkXError("n must be a positive integer")
282
+
283
+ if not (d >= 2):
284
+ raise nx.NetworkXError("d must be greater than or equal to 2")
285
+
286
+ if not (d % 2 == 0):
287
+ raise nx.NetworkXError("d must be even")
288
+
289
+ if not (n - 1 >= d):
290
+ raise nx.NetworkXError(
291
+ f"Need n-1>= d to have room for {d//2} independent cycles with {n} nodes"
292
+ )
293
+
294
+ G = nx.empty_graph(n, create_using)
295
+
296
+ if n < 2:
297
+ return G
298
+
299
+ cycles = []
300
+ edges = set()
301
+
302
+ # Create d / 2 cycles
303
+ for i in range(d // 2):
304
+ iterations = max_tries
305
+ # Make sure the cycles are independent to have a regular graph
306
+ while len(edges) != (i + 1) * n:
307
+ iterations -= 1
308
+ # Faster than random.permutation(n) since there are only
309
+ # (n-1)! distinct cycles against n! permutations of size n
310
+ cycle = seed.permutation(n - 1).tolist()
311
+ cycle.append(n - 1)
312
+
313
+ new_edges = {
314
+ (u, v)
315
+ for u, v in nx.utils.pairwise(cycle, cyclic=True)
316
+ if (u, v) not in edges and (v, u) not in edges
317
+ }
318
+ # If the new cycle has no edges in common with previous cycles
319
+ # then add it to the list otherwise try again
320
+ if len(new_edges) == n:
321
+ cycles.append(cycle)
322
+ edges.update(new_edges)
323
+
324
+ if iterations == 0:
325
+ raise nx.NetworkXError("Too many iterations in maybe_regular_expander")
326
+
327
+ G.add_edges_from(edges)
328
+
329
+ return G
330
+
331
+
332
+ @nx.utils.not_implemented_for("directed")
333
+ @nx.utils.not_implemented_for("multigraph")
334
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
335
+ def is_regular_expander(G, *, epsilon=0):
336
+ r"""Determines whether the graph G is a regular expander. [1]_
337
+
338
+ An expander graph is a sparse graph with strong connectivity properties.
339
+
340
+ More precisely, this helper checks whether the graph is a
341
+ regular $(n, d, \lambda)$-expander with $\lambda$ close to
342
+ the Alon-Boppana bound and given by
343
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$. [2]_
344
+
345
+ In the case where $\epsilon = 0$ then if the graph successfully passes the test
346
+ it is a Ramanujan graph. [3]_
347
+
348
+ A Ramanujan graph has spectral gap almost as large as possible, which makes them
349
+ excellent expanders.
350
+
351
+ Parameters
352
+ ----------
353
+ G : NetworkX graph
354
+ epsilon : int, float, default=0
355
+
356
+ Returns
357
+ -------
358
+ bool
359
+ Whether the given graph is a regular $(n, d, \lambda)$-expander
360
+ where $\lambda = 2 \sqrt{d - 1} + \epsilon$.
361
+
362
+ Examples
363
+ --------
364
+ >>> G = nx.random_regular_expander_graph(20, 4)
365
+ >>> nx.is_regular_expander(G)
366
+ True
367
+
368
+ See Also
369
+ --------
370
+ maybe_regular_expander
371
+ random_regular_expander_graph
372
+
373
+ References
374
+ ----------
375
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
376
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
377
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
378
+
379
+ """
380
+
381
+ import numpy as np
382
+ from scipy.sparse.linalg import eigsh
383
+
384
+ if epsilon < 0:
385
+ raise nx.NetworkXError("epsilon must be non negative")
386
+
387
+ if not nx.is_regular(G):
388
+ return False
389
+
390
+ _, d = nx.utils.arbitrary_element(G.degree)
391
+
392
+ A = nx.adjacency_matrix(G, dtype=float)
393
+ lams = eigsh(A, which="LM", k=2, return_eigenvectors=False)
394
+
395
+ # lambda2 is the second biggest eigenvalue
396
+ lambda2 = min(lams)
397
+
398
+ # Use bool() to convert numpy scalar to Python Boolean
399
+ return bool(abs(lambda2) < 2 ** np.sqrt(d - 1) + epsilon)
400
+
401
+
402
+ @nx.utils.decorators.np_random_state("seed")
403
+ @nx._dispatchable(graphs=None, returns_graph=True)
404
+ def random_regular_expander_graph(
405
+ n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None
406
+ ):
407
+ r"""Returns a random regular expander graph on $n$ nodes with degree $d$.
408
+
409
+ An expander graph is a sparse graph with strong connectivity properties. [1]_
410
+
411
+ More precisely the returned graph is a $(n, d, \lambda)$-expander with
412
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
413
+
414
+ In the case where $\epsilon = 0$ it returns a Ramanujan graph.
415
+ A Ramanujan graph has spectral gap almost as large as possible,
416
+ which makes them excellent expanders. [3]_
417
+
418
+ Parameters
419
+ ----------
420
+ n : int
421
+ The number of nodes.
422
+ d : int
423
+ The degree of each node.
424
+ epsilon : int, float, default=0
425
+ max_tries : int, (default: 100)
426
+ The number of allowed loops, also used in the maybe_regular_expander utility
427
+ seed : (default: None)
428
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
429
+
430
+ Raises
431
+ ------
432
+ NetworkXError
433
+ If max_tries is reached
434
+
435
+ Examples
436
+ --------
437
+ >>> G = nx.random_regular_expander_graph(20, 4)
438
+ >>> nx.is_regular_expander(G)
439
+ True
440
+
441
+ Notes
442
+ -----
443
+ This loops over `maybe_regular_expander` and can be slow when
444
+ $n$ is too big or $\epsilon$ too small.
445
+
446
+ See Also
447
+ --------
448
+ maybe_regular_expander
449
+ is_regular_expander
450
+
451
+ References
452
+ ----------
453
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
454
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
455
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
456
+
457
+ """
458
+ G = maybe_regular_expander(
459
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
460
+ )
461
+ iterations = max_tries
462
+
463
+ while not is_regular_expander(G, epsilon=epsilon):
464
+ iterations -= 1
465
+ G = maybe_regular_expander(
466
+ n=n, d=d, create_using=create_using, max_tries=max_tries, seed=seed
467
+ )
468
+
469
+ if iterations == 0:
470
+ raise nx.NetworkXError(
471
+ "Too many iterations in random_regular_expander_graph"
472
+ )
473
+
474
+ return G
janus/lib/python3.10/site-packages/networkx/generators/geometric.py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for geometric graphs."""
2
+
3
+ import math
4
+ from bisect import bisect_left
5
+ from itertools import accumulate, combinations, product
6
+
7
+ import networkx as nx
8
+ from networkx.utils import py_random_state
9
+
10
+ __all__ = [
11
+ "geometric_edges",
12
+ "geographical_threshold_graph",
13
+ "navigable_small_world_graph",
14
+ "random_geometric_graph",
15
+ "soft_random_geometric_graph",
16
+ "thresholded_random_geometric_graph",
17
+ "waxman_graph",
18
+ "geometric_soft_configuration_graph",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable(node_attrs="pos_name")
23
+ def geometric_edges(G, radius, p=2, *, pos_name="pos"):
24
+ """Returns edge list of node pairs within `radius` of each other.
25
+
26
+ Parameters
27
+ ----------
28
+ G : networkx graph
29
+ The graph from which to generate the edge list. The nodes in `G` should
30
+ have an attribute ``pos`` corresponding to the node position, which is
31
+ used to compute the distance to other nodes.
32
+ radius : scalar
33
+ The distance threshold. Edges are included in the edge list if the
34
+ distance between the two nodes is less than `radius`.
35
+ pos_name : string, default="pos"
36
+ The name of the node attribute which represents the position of each
37
+ node in 2D coordinates. Every node in the Graph must have this attribute.
38
+ p : scalar, default=2
39
+ The `Minkowski distance metric
40
+ <https://en.wikipedia.org/wiki/Minkowski_distance>`_ used to compute
41
+ distances. The default value is 2, i.e. Euclidean distance.
42
+
43
+ Returns
44
+ -------
45
+ edges : list
46
+ List of edges whose distances are less than `radius`
47
+
48
+ Notes
49
+ -----
50
+ Radius uses Minkowski distance metric `p`.
51
+ If scipy is available, `scipy.spatial.cKDTree` is used to speed computation.
52
+
53
+ Examples
54
+ --------
55
+ Create a graph with nodes that have a "pos" attribute representing 2D
56
+ coordinates.
57
+
58
+ >>> G = nx.Graph()
59
+ >>> G.add_nodes_from(
60
+ ... [
61
+ ... (0, {"pos": (0, 0)}),
62
+ ... (1, {"pos": (3, 0)}),
63
+ ... (2, {"pos": (8, 0)}),
64
+ ... ]
65
+ ... )
66
+ >>> nx.geometric_edges(G, radius=1)
67
+ []
68
+ >>> nx.geometric_edges(G, radius=4)
69
+ [(0, 1)]
70
+ >>> nx.geometric_edges(G, radius=6)
71
+ [(0, 1), (1, 2)]
72
+ >>> nx.geometric_edges(G, radius=9)
73
+ [(0, 1), (0, 2), (1, 2)]
74
+ """
75
+ # Input validation - every node must have a "pos" attribute
76
+ for n, pos in G.nodes(data=pos_name):
77
+ if pos is None:
78
+ raise nx.NetworkXError(
79
+ f"Node {n} (and all nodes) must have a '{pos_name}' attribute."
80
+ )
81
+
82
+ # NOTE: See _geometric_edges for the actual implementation. The reason this
83
+ # is split into two functions is to avoid the overhead of input validation
84
+ # every time the function is called internally in one of the other
85
+ # geometric generators
86
+ return _geometric_edges(G, radius, p, pos_name)
87
+
88
+
89
+ def _geometric_edges(G, radius, p, pos_name):
90
+ """
91
+ Implements `geometric_edges` without input validation. See `geometric_edges`
92
+ for complete docstring.
93
+ """
94
+ nodes_pos = G.nodes(data=pos_name)
95
+ try:
96
+ import scipy as sp
97
+ except ImportError:
98
+ # no scipy KDTree so compute by for-loop
99
+ radius_p = radius**p
100
+ edges = [
101
+ (u, v)
102
+ for (u, pu), (v, pv) in combinations(nodes_pos, 2)
103
+ if sum(abs(a - b) ** p for a, b in zip(pu, pv)) <= radius_p
104
+ ]
105
+ return edges
106
+ # scipy KDTree is available
107
+ nodes, coords = list(zip(*nodes_pos))
108
+ kdtree = sp.spatial.cKDTree(coords) # Cannot provide generator.
109
+ edge_indexes = kdtree.query_pairs(radius, p)
110
+ edges = [(nodes[u], nodes[v]) for u, v in sorted(edge_indexes)]
111
+ return edges
112
+
113
+
114
+ @py_random_state(5)
115
+ @nx._dispatchable(graphs=None, returns_graph=True)
116
+ def random_geometric_graph(
117
+ n, radius, dim=2, pos=None, p=2, seed=None, *, pos_name="pos"
118
+ ):
119
+ """Returns a random geometric graph in the unit cube of dimensions `dim`.
120
+
121
+ The random geometric graph model places `n` nodes uniformly at
122
+ random in the unit cube. Two nodes are joined by an edge if the
123
+ distance between the nodes is at most `radius`.
124
+
125
+ Edges are determined using a KDTree when SciPy is available.
126
+ This reduces the time complexity from $O(n^2)$ to $O(n)$.
127
+
128
+ Parameters
129
+ ----------
130
+ n : int or iterable
131
+ Number of nodes or iterable of nodes
132
+ radius: float
133
+ Distance threshold value
134
+ dim : int, optional
135
+ Dimension of graph
136
+ pos : dict, optional
137
+ A dictionary keyed by node with node positions as values.
138
+ p : float, optional
139
+ Which Minkowski distance metric to use. `p` has to meet the condition
140
+ ``1 <= p <= infinity``.
141
+
142
+ If this argument is not specified, the :math:`L^2` metric
143
+ (the Euclidean distance metric), p = 2 is used.
144
+ This should not be confused with the `p` of an Erdős-Rényi random
145
+ graph, which represents probability.
146
+ seed : integer, random_state, or None (default)
147
+ Indicator of random number generation state.
148
+ See :ref:`Randomness<randomness>`.
149
+ pos_name : string, default="pos"
150
+ The name of the node attribute which represents the position
151
+ in 2D coordinates of the node in the returned graph.
152
+
153
+ Returns
154
+ -------
155
+ Graph
156
+ A random geometric graph, undirected and without self-loops.
157
+ Each node has a node attribute ``'pos'`` that stores the
158
+ position of that node in Euclidean space as provided by the
159
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
160
+ generated by this function.
161
+
162
+ Examples
163
+ --------
164
+ Create a random geometric graph on twenty nodes where nodes are joined by
165
+ an edge if their distance is at most 0.1::
166
+
167
+ >>> G = nx.random_geometric_graph(20, 0.1)
168
+
169
+ Notes
170
+ -----
171
+ This uses a *k*-d tree to build the graph.
172
+
173
+ The `pos` keyword argument can be used to specify node positions so you
174
+ can create an arbitrary distribution and domain for positions.
175
+
176
+ For example, to use a 2D Gaussian distribution of node positions with mean
177
+ (0, 0) and standard deviation 2::
178
+
179
+ >>> import random
180
+ >>> n = 20
181
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
182
+ >>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
183
+
184
+ References
185
+ ----------
186
+ .. [1] Penrose, Mathew, *Random Geometric Graphs*,
187
+ Oxford Studies in Probability, 5, 2003.
188
+
189
+ """
190
+ # TODO Is this function just a special case of the geographical
191
+ # threshold graph?
192
+ #
193
+ # half_radius = {v: radius / 2 for v in n}
194
+ # return geographical_threshold_graph(nodes, theta=1, alpha=1,
195
+ # weight=half_radius)
196
+ #
197
+ G = nx.empty_graph(n)
198
+ # If no positions are provided, choose uniformly random vectors in
199
+ # Euclidean space of the specified dimension.
200
+ if pos is None:
201
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
202
+ nx.set_node_attributes(G, pos, pos_name)
203
+
204
+ G.add_edges_from(_geometric_edges(G, radius, p, pos_name))
205
+ return G
206
+
207
+
208
+ @py_random_state(6)
209
+ @nx._dispatchable(graphs=None, returns_graph=True)
210
+ def soft_random_geometric_graph(
211
+ n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name="pos"
212
+ ):
213
+ r"""Returns a soft random geometric graph in the unit cube.
214
+
215
+ The soft random geometric graph [1] model places `n` nodes uniformly at
216
+ random in the unit cube in dimension `dim`. Two nodes of distance, `dist`,
217
+ computed by the `p`-Minkowski distance metric are joined by an edge with
218
+ probability `p_dist` if the computed distance metric value of the nodes
219
+ is at most `radius`, otherwise they are not joined.
220
+
221
+ Edges within `radius` of each other are determined using a KDTree when
222
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
223
+ to :math:`O(n)`.
224
+
225
+ Parameters
226
+ ----------
227
+ n : int or iterable
228
+ Number of nodes or iterable of nodes
229
+ radius: float
230
+ Distance threshold value
231
+ dim : int, optional
232
+ Dimension of graph
233
+ pos : dict, optional
234
+ A dictionary keyed by node with node positions as values.
235
+ p : float, optional
236
+ Which Minkowski distance metric to use.
237
+ `p` has to meet the condition ``1 <= p <= infinity``.
238
+
239
+ If this argument is not specified, the :math:`L^2` metric
240
+ (the Euclidean distance metric), p = 2 is used.
241
+
242
+ This should not be confused with the `p` of an Erdős-Rényi random
243
+ graph, which represents probability.
244
+ p_dist : function, optional
245
+ A probability density function computing the probability of
246
+ connecting two nodes that are of distance, dist, computed by the
247
+ Minkowski distance metric. The probability density function, `p_dist`,
248
+ must be any function that takes the metric value as input
249
+ and outputs a single probability value between 0-1. The scipy.stats
250
+ package has many probability distribution functions implemented and
251
+ tools for custom probability distribution definitions [2], and passing
252
+ the .pdf method of scipy.stats distributions can be used here. If the
253
+ probability function, `p_dist`, is not supplied, the default function
254
+ is an exponential distribution with rate parameter :math:`\lambda=1`.
255
+ seed : integer, random_state, or None (default)
256
+ Indicator of random number generation state.
257
+ See :ref:`Randomness<randomness>`.
258
+ pos_name : string, default="pos"
259
+ The name of the node attribute which represents the position
260
+ in 2D coordinates of the node in the returned graph.
261
+
262
+ Returns
263
+ -------
264
+ Graph
265
+ A soft random geometric graph, undirected and without self-loops.
266
+ Each node has a node attribute ``'pos'`` that stores the
267
+ position of that node in Euclidean space as provided by the
268
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
269
+ generated by this function.
270
+
271
+ Examples
272
+ --------
273
+ Default Graph:
274
+
275
+ G = nx.soft_random_geometric_graph(50, 0.2)
276
+
277
+ Custom Graph:
278
+
279
+ Create a soft random geometric graph on 100 uniformly distributed nodes
280
+ where nodes are joined by an edge with probability computed from an
281
+ exponential distribution with rate parameter :math:`\lambda=1` if their
282
+ Euclidean distance is at most 0.2.
283
+
284
+ Notes
285
+ -----
286
+ This uses a *k*-d tree to build the graph.
287
+
288
+ The `pos` keyword argument can be used to specify node positions so you
289
+ can create an arbitrary distribution and domain for positions.
290
+
291
+ For example, to use a 2D Gaussian distribution of node positions with mean
292
+ (0, 0) and standard deviation 2
293
+
294
+ The scipy.stats package can be used to define the probability distribution
295
+ with the .pdf method used as `p_dist`.
296
+
297
+ ::
298
+
299
+ >>> import random
300
+ >>> import math
301
+ >>> n = 100
302
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
303
+ >>> p_dist = lambda dist: math.exp(-dist)
304
+ >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist)
305
+
306
+ References
307
+ ----------
308
+ .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs."
309
+ The Annals of Applied Probability 26.2 (2016): 986-1028.
310
+ .. [2] scipy.stats -
311
+ https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
312
+
313
+ """
314
+ G = nx.empty_graph(n)
315
+ G.name = f"soft_random_geometric_graph({n}, {radius}, {dim})"
316
+ # If no positions are provided, choose uniformly random vectors in
317
+ # Euclidean space of the specified dimension.
318
+ if pos is None:
319
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
320
+ nx.set_node_attributes(G, pos, pos_name)
321
+
322
+ # if p_dist function not supplied the default function is an exponential
323
+ # distribution with rate parameter :math:`\lambda=1`.
324
+ if p_dist is None:
325
+
326
+ def p_dist(dist):
327
+ return math.exp(-dist)
328
+
329
+ def should_join(edge):
330
+ u, v = edge
331
+ dist = (sum(abs(a - b) ** p for a, b in zip(pos[u], pos[v]))) ** (1 / p)
332
+ return seed.random() < p_dist(dist)
333
+
334
+ G.add_edges_from(filter(should_join, _geometric_edges(G, radius, p, pos_name)))
335
+ return G
336
+
337
+
338
+ @py_random_state(7)
339
+ @nx._dispatchable(graphs=None, returns_graph=True)
340
+ def geographical_threshold_graph(
341
+ n,
342
+ theta,
343
+ dim=2,
344
+ pos=None,
345
+ weight=None,
346
+ metric=None,
347
+ p_dist=None,
348
+ seed=None,
349
+ *,
350
+ pos_name="pos",
351
+ weight_name="weight",
352
+ ):
353
+ r"""Returns a geographical threshold graph.
354
+
355
+ The geographical threshold graph model places $n$ nodes uniformly at
356
+ random in a rectangular domain. Each node $u$ is assigned a weight
357
+ $w_u$. Two nodes $u$ and $v$ are joined by an edge if
358
+
359
+ .. math::
360
+
361
+ (w_u + w_v)p_{dist}(r) \ge \theta
362
+
363
+ where `r` is the distance between `u` and `v`, `p_dist` is any function of
364
+ `r`, and :math:`\theta` as the threshold parameter. `p_dist` is used to
365
+ give weight to the distance between nodes when deciding whether or not
366
+ they should be connected. The larger `p_dist` is, the more prone nodes
367
+ separated by `r` are to be connected, and vice versa.
368
+
369
+ Parameters
370
+ ----------
371
+ n : int or iterable
372
+ Number of nodes or iterable of nodes
373
+ theta: float
374
+ Threshold value
375
+ dim : int, optional
376
+ Dimension of graph
377
+ pos : dict
378
+ Node positions as a dictionary of tuples keyed by node.
379
+ weight : dict
380
+ Node weights as a dictionary of numbers keyed by node.
381
+ metric : function
382
+ A metric on vectors of numbers (represented as lists or
383
+ tuples). This must be a function that accepts two lists (or
384
+ tuples) as input and yields a number as output. The function
385
+ must also satisfy the four requirements of a `metric`_.
386
+ Specifically, if $d$ is the function and $x$, $y$,
387
+ and $z$ are vectors in the graph, then $d$ must satisfy
388
+
389
+ 1. $d(x, y) \ge 0$,
390
+ 2. $d(x, y) = 0$ if and only if $x = y$,
391
+ 3. $d(x, y) = d(y, x)$,
392
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
393
+
394
+ If this argument is not specified, the Euclidean distance metric is
395
+ used.
396
+
397
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
398
+ p_dist : function, optional
399
+ Any function used to give weight to the distance between nodes when
400
+ deciding whether or not they should be connected. `p_dist` was
401
+ originally conceived as a probability density function giving the
402
+ probability of connecting two nodes that are of metric distance `r`
403
+ apart. The implementation here allows for more arbitrary definitions
404
+ of `p_dist` that do not need to correspond to valid probability
405
+ density functions. The :mod:`scipy.stats` package has many
406
+ probability density functions implemented and tools for custom
407
+ probability density definitions, and passing the ``.pdf`` method of
408
+ scipy.stats distributions can be used here. If ``p_dist=None``
409
+ (the default), the exponential function :math:`r^{-2}` is used.
410
+ seed : integer, random_state, or None (default)
411
+ Indicator of random number generation state.
412
+ See :ref:`Randomness<randomness>`.
413
+ pos_name : string, default="pos"
414
+ The name of the node attribute which represents the position
415
+ in 2D coordinates of the node in the returned graph.
416
+ weight_name : string, default="weight"
417
+ The name of the node attribute which represents the weight
418
+ of the node in the returned graph.
419
+
420
+ Returns
421
+ -------
422
+ Graph
423
+ A random geographic threshold graph, undirected and without
424
+ self-loops.
425
+
426
+ Each node has a node attribute ``pos`` that stores the
427
+ position of that node in Euclidean space as provided by the
428
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
429
+ generated by this function. Similarly, each node has a node
430
+ attribute ``weight`` that stores the weight of that node as
431
+ provided or as generated.
432
+
433
+ Examples
434
+ --------
435
+ Specify an alternate distance metric using the ``metric`` keyword
436
+ argument. For example, to use the `taxicab metric`_ instead of the
437
+ default `Euclidean metric`_::
438
+
439
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
440
+ >>> G = nx.geographical_threshold_graph(10, 0.1, metric=dist)
441
+
442
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
443
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
444
+
445
+ Notes
446
+ -----
447
+ If weights are not specified they are assigned to nodes by drawing randomly
448
+ from the exponential distribution with rate parameter $\lambda=1$.
449
+ To specify weights from a different distribution, use the `weight` keyword
450
+ argument::
451
+
452
+ >>> import random
453
+ >>> n = 20
454
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
455
+ >>> G = nx.geographical_threshold_graph(20, 50, weight=w)
456
+
457
+ If node positions are not specified they are randomly assigned from the
458
+ uniform distribution.
459
+
460
+ References
461
+ ----------
462
+ .. [1] Masuda, N., Miwa, H., Konno, N.:
463
+ Geographical threshold graphs with small-world and scale-free
464
+ properties.
465
+ Physical Review E 71, 036108 (2005)
466
+ .. [2] Milan Bradonjić, Aric Hagberg and Allon G. Percus,
467
+ Giant component and connectivity in geographical threshold graphs,
468
+ in Algorithms and Models for the Web-Graph (WAW 2007),
469
+ Antony Bonato and Fan Chung (Eds), pp. 209--216, 2007
470
+ """
471
+ G = nx.empty_graph(n)
472
+ # If no weights are provided, choose them from an exponential
473
+ # distribution.
474
+ if weight is None:
475
+ weight = {v: seed.expovariate(1) for v in G}
476
+ # If no positions are provided, choose uniformly random vectors in
477
+ # Euclidean space of the specified dimension.
478
+ if pos is None:
479
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
480
+ # If no distance metric is provided, use Euclidean distance.
481
+ if metric is None:
482
+ metric = math.dist
483
+ nx.set_node_attributes(G, weight, weight_name)
484
+ nx.set_node_attributes(G, pos, pos_name)
485
+
486
+ # if p_dist is not supplied, use default r^-2
487
+ if p_dist is None:
488
+
489
+ def p_dist(r):
490
+ return r**-2
491
+
492
+ # Returns ``True`` if and only if the nodes whose attributes are
493
+ # ``du`` and ``dv`` should be joined, according to the threshold
494
+ # condition.
495
+ def should_join(pair):
496
+ u, v = pair
497
+ u_pos, v_pos = pos[u], pos[v]
498
+ u_weight, v_weight = weight[u], weight[v]
499
+ return (u_weight + v_weight) * p_dist(metric(u_pos, v_pos)) >= theta
500
+
501
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
502
+ return G
503
+
504
+
505
+ @py_random_state(6)
506
+ @nx._dispatchable(graphs=None, returns_graph=True)
507
+ def waxman_graph(
508
+ n,
509
+ beta=0.4,
510
+ alpha=0.1,
511
+ L=None,
512
+ domain=(0, 0, 1, 1),
513
+ metric=None,
514
+ seed=None,
515
+ *,
516
+ pos_name="pos",
517
+ ):
518
+ r"""Returns a Waxman random graph.
519
+
520
+ The Waxman random graph model places `n` nodes uniformly at random
521
+ in a rectangular domain. Each pair of nodes at distance `d` is
522
+ joined by an edge with probability
523
+
524
+ .. math::
525
+ p = \beta \exp(-d / \alpha L).
526
+
527
+ This function implements both Waxman models, using the `L` keyword
528
+ argument.
529
+
530
+ * Waxman-1: if `L` is not specified, it is set to be the maximum distance
531
+ between any pair of nodes.
532
+ * Waxman-2: if `L` is specified, the distance between a pair of nodes is
533
+ chosen uniformly at random from the interval `[0, L]`.
534
+
535
+ Parameters
536
+ ----------
537
+ n : int or iterable
538
+ Number of nodes or iterable of nodes
539
+ beta: float
540
+ Model parameter
541
+ alpha: float
542
+ Model parameter
543
+ L : float, optional
544
+ Maximum distance between nodes. If not specified, the actual distance
545
+ is calculated.
546
+ domain : four-tuple of numbers, optional
547
+ Domain size, given as a tuple of the form `(x_min, y_min, x_max,
548
+ y_max)`.
549
+ metric : function
550
+ A metric on vectors of numbers (represented as lists or
551
+ tuples). This must be a function that accepts two lists (or
552
+ tuples) as input and yields a number as output. The function
553
+ must also satisfy the four requirements of a `metric`_.
554
+ Specifically, if $d$ is the function and $x$, $y$,
555
+ and $z$ are vectors in the graph, then $d$ must satisfy
556
+
557
+ 1. $d(x, y) \ge 0$,
558
+ 2. $d(x, y) = 0$ if and only if $x = y$,
559
+ 3. $d(x, y) = d(y, x)$,
560
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
561
+
562
+ If this argument is not specified, the Euclidean distance metric is
563
+ used.
564
+
565
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
566
+
567
+ seed : integer, random_state, or None (default)
568
+ Indicator of random number generation state.
569
+ See :ref:`Randomness<randomness>`.
570
+ pos_name : string, default="pos"
571
+ The name of the node attribute which represents the position
572
+ in 2D coordinates of the node in the returned graph.
573
+
574
+ Returns
575
+ -------
576
+ Graph
577
+ A random Waxman graph, undirected and without self-loops. Each
578
+ node has a node attribute ``'pos'`` that stores the position of
579
+ that node in Euclidean space as generated by this function.
580
+
581
+ Examples
582
+ --------
583
+ Specify an alternate distance metric using the ``metric`` keyword
584
+ argument. For example, to use the "`taxicab metric`_" instead of the
585
+ default `Euclidean metric`_::
586
+
587
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
588
+ >>> G = nx.waxman_graph(10, 0.5, 0.1, metric=dist)
589
+
590
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
591
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
592
+
593
+ Notes
594
+ -----
595
+ Starting in NetworkX 2.0 the parameters alpha and beta align with their
596
+ usual roles in the probability distribution. In earlier versions their
597
+ positions in the expression were reversed. Their position in the calling
598
+ sequence reversed as well to minimize backward incompatibility.
599
+
600
+ References
601
+ ----------
602
+ .. [1] B. M. Waxman, *Routing of multipoint connections*.
603
+ IEEE J. Select. Areas Commun. 6(9),(1988) 1617--1622.
604
+ """
605
+ G = nx.empty_graph(n)
606
+ (xmin, ymin, xmax, ymax) = domain
607
+ # Each node gets a uniformly random position in the given rectangle.
608
+ pos = {v: (seed.uniform(xmin, xmax), seed.uniform(ymin, ymax)) for v in G}
609
+ nx.set_node_attributes(G, pos, pos_name)
610
+ # If no distance metric is provided, use Euclidean distance.
611
+ if metric is None:
612
+ metric = math.dist
613
+ # If the maximum distance L is not specified (that is, we are in the
614
+ # Waxman-1 model), then find the maximum distance between any pair
615
+ # of nodes.
616
+ #
617
+ # In the Waxman-1 model, join nodes randomly based on distance. In
618
+ # the Waxman-2 model, join randomly based on random l.
619
+ if L is None:
620
+ L = max(metric(x, y) for x, y in combinations(pos.values(), 2))
621
+
622
+ def dist(u, v):
623
+ return metric(pos[u], pos[v])
624
+
625
+ else:
626
+
627
+ def dist(u, v):
628
+ return seed.random() * L
629
+
630
+ # `pair` is the pair of nodes to decide whether to join.
631
+ def should_join(pair):
632
+ return seed.random() < beta * math.exp(-dist(*pair) / (alpha * L))
633
+
634
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
635
+ return G
636
+
637
+
638
+ @py_random_state(5)
639
+ @nx._dispatchable(graphs=None, returns_graph=True)
640
+ def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None):
641
+ r"""Returns a navigable small-world graph.
642
+
643
+ A navigable small-world graph is a directed grid with additional long-range
644
+ connections that are chosen randomly.
645
+
646
+ [...] we begin with a set of nodes [...] that are identified with the set
647
+ of lattice points in an $n \times n$ square,
648
+ $\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
649
+ and we define the *lattice distance* between two nodes $(i, j)$ and
650
+ $(k, l)$ to be the number of "lattice steps" separating them:
651
+ $d((i, j), (k, l)) = |k - i| + |l - j|$.
652
+
653
+ For a universal constant $p >= 1$, the node $u$ has a directed edge to
654
+ every other node within lattice distance $p$---these are its *local
655
+ contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
656
+ construct directed edges from $u$ to $q$ other nodes (the *long-range
657
+ contacts*) using independent random trials; the $i$th directed edge from
658
+ $u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
659
+
660
+ -- [1]_
661
+
662
+ Parameters
663
+ ----------
664
+ n : int
665
+ The length of one side of the lattice; the number of nodes in
666
+ the graph is therefore $n^2$.
667
+ p : int
668
+ The diameter of short range connections. Each node is joined with every
669
+ other node within this lattice distance.
670
+ q : int
671
+ The number of long-range connections for each node.
672
+ r : float
673
+ Exponent for decaying probability of connections. The probability of
674
+ connecting to a node at lattice distance $d$ is $1/d^r$.
675
+ dim : int
676
+ Dimension of grid
677
+ seed : integer, random_state, or None (default)
678
+ Indicator of random number generation state.
679
+ See :ref:`Randomness<randomness>`.
680
+
681
+ References
682
+ ----------
683
+ .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
684
+ perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
685
+ """
686
+ if p < 1:
687
+ raise nx.NetworkXException("p must be >= 1")
688
+ if q < 0:
689
+ raise nx.NetworkXException("q must be >= 0")
690
+ if r < 0:
691
+ raise nx.NetworkXException("r must be >= 0")
692
+
693
+ G = nx.DiGraph()
694
+ nodes = list(product(range(n), repeat=dim))
695
+ for p1 in nodes:
696
+ probs = [0]
697
+ for p2 in nodes:
698
+ if p1 == p2:
699
+ continue
700
+ d = sum((abs(b - a) for a, b in zip(p1, p2)))
701
+ if d <= p:
702
+ G.add_edge(p1, p2)
703
+ probs.append(d**-r)
704
+ cdf = list(accumulate(probs))
705
+ for _ in range(q):
706
+ target = nodes[bisect_left(cdf, seed.uniform(0, cdf[-1]))]
707
+ G.add_edge(p1, target)
708
+ return G
709
+
710
+
711
+ @py_random_state(7)
712
+ @nx._dispatchable(graphs=None, returns_graph=True)
713
+ def thresholded_random_geometric_graph(
714
+ n,
715
+ radius,
716
+ theta,
717
+ dim=2,
718
+ pos=None,
719
+ weight=None,
720
+ p=2,
721
+ seed=None,
722
+ *,
723
+ pos_name="pos",
724
+ weight_name="weight",
725
+ ):
726
+ r"""Returns a thresholded random geometric graph in the unit cube.
727
+
728
+ The thresholded random geometric graph [1] model places `n` nodes
729
+ uniformly at random in the unit cube of dimensions `dim`. Each node
730
+ `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are
731
+ joined by an edge if they are within the maximum connection distance,
732
+ `radius` computed by the `p`-Minkowski distance and the summation of
733
+ weights :math:`w_u` + :math:`w_v` is greater than or equal
734
+ to the threshold parameter `theta`.
735
+
736
+ Edges within `radius` of each other are determined using a KDTree when
737
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
738
+ to :math:`O(n)`.
739
+
740
+ Parameters
741
+ ----------
742
+ n : int or iterable
743
+ Number of nodes or iterable of nodes
744
+ radius: float
745
+ Distance threshold value
746
+ theta: float
747
+ Threshold value
748
+ dim : int, optional
749
+ Dimension of graph
750
+ pos : dict, optional
751
+ A dictionary keyed by node with node positions as values.
752
+ weight : dict, optional
753
+ Node weights as a dictionary of numbers keyed by node.
754
+ p : float, optional (default 2)
755
+ Which Minkowski distance metric to use. `p` has to meet the condition
756
+ ``1 <= p <= infinity``.
757
+
758
+ If this argument is not specified, the :math:`L^2` metric
759
+ (the Euclidean distance metric), p = 2 is used.
760
+
761
+ This should not be confused with the `p` of an Erdős-Rényi random
762
+ graph, which represents probability.
763
+ seed : integer, random_state, or None (default)
764
+ Indicator of random number generation state.
765
+ See :ref:`Randomness<randomness>`.
766
+ pos_name : string, default="pos"
767
+ The name of the node attribute which represents the position
768
+ in 2D coordinates of the node in the returned graph.
769
+ weight_name : string, default="weight"
770
+ The name of the node attribute which represents the weight
771
+ of the node in the returned graph.
772
+
773
+ Returns
774
+ -------
775
+ Graph
776
+ A thresholded random geographic graph, undirected and without
777
+ self-loops.
778
+
779
+ Each node has a node attribute ``'pos'`` that stores the
780
+ position of that node in Euclidean space as provided by the
781
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
782
+ generated by this function. Similarly, each node has a nodethre
783
+ attribute ``'weight'`` that stores the weight of that node as
784
+ provided or as generated.
785
+
786
+ Examples
787
+ --------
788
+ Default Graph:
789
+
790
+ G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
791
+
792
+ Custom Graph:
793
+
794
+ Create a thresholded random geometric graph on 50 uniformly distributed
795
+ nodes where nodes are joined by an edge if their sum weights drawn from
796
+ a exponential distribution with rate = 5 are >= theta = 0.1 and their
797
+ Euclidean distance is at most 0.2.
798
+
799
+ Notes
800
+ -----
801
+ This uses a *k*-d tree to build the graph.
802
+
803
+ The `pos` keyword argument can be used to specify node positions so you
804
+ can create an arbitrary distribution and domain for positions.
805
+
806
+ For example, to use a 2D Gaussian distribution of node positions with mean
807
+ (0, 0) and standard deviation 2
808
+
809
+ If weights are not specified they are assigned to nodes by drawing randomly
810
+ from the exponential distribution with rate parameter :math:`\lambda=1`.
811
+ To specify weights from a different distribution, use the `weight` keyword
812
+ argument::
813
+
814
+ ::
815
+
816
+ >>> import random
817
+ >>> import math
818
+ >>> n = 50
819
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
820
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
821
+ >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w)
822
+
823
+ References
824
+ ----------
825
+ .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
826
+
827
+ """
828
+ G = nx.empty_graph(n)
829
+ G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})"
830
+ # If no weights are provided, choose them from an exponential
831
+ # distribution.
832
+ if weight is None:
833
+ weight = {v: seed.expovariate(1) for v in G}
834
+ # If no positions are provided, choose uniformly random vectors in
835
+ # Euclidean space of the specified dimension.
836
+ if pos is None:
837
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
838
+ # If no distance metric is provided, use Euclidean distance.
839
+ nx.set_node_attributes(G, weight, weight_name)
840
+ nx.set_node_attributes(G, pos, pos_name)
841
+
842
+ edges = (
843
+ (u, v)
844
+ for u, v in _geometric_edges(G, radius, p, pos_name)
845
+ if weight[u] + weight[v] >= theta
846
+ )
847
+ G.add_edges_from(edges)
848
+ return G
849
+
850
+
851
+ @py_random_state(5)
852
+ @nx._dispatchable(graphs=None, returns_graph=True)
853
+ def geometric_soft_configuration_graph(
854
+ *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None
855
+ ):
856
+ r"""Returns a random graph from the geometric soft configuration model.
857
+
858
+ The $\mathbb{S}^1$ model [1]_ is the geometric soft configuration model
859
+ which is able to explain many fundamental features of real networks such as
860
+ small-world property, heteregenous degree distributions, high level of
861
+ clustering, and self-similarity.
862
+
863
+ In the geometric soft configuration model, a node $i$ is assigned two hidden
864
+ variables: a hidden degree $\kappa_i$, quantifying its popularity, influence,
865
+ or importance, and an angular position $\theta_i$ in a circle abstracting the
866
+ similarity space, where angular distances between nodes are a proxy for their
867
+ similarity. Focusing on the angular position, this model is often called
868
+ the $\mathbb{S}^1$ model (a one-dimensional sphere). The circle's radius is
869
+ adjusted to $R = N/2\pi$, where $N$ is the number of nodes, so that the density
870
+ is set to 1 without loss of generality.
871
+
872
+ The connection probability between any pair of nodes increases with
873
+ the product of their hidden degrees (i.e., their combined popularities),
874
+ and decreases with the angular distance between the two nodes.
875
+ Specifically, nodes $i$ and $j$ are connected with the probability
876
+
877
+ $p_{ij} = \frac{1}{1 + \frac{d_{ij}^\beta}{\left(\mu \kappa_i \kappa_j\right)^{\max(1, \beta)}}}$
878
+
879
+ where $d_{ij} = R\Delta\theta_{ij}$ is the arc length of the circle between
880
+ nodes $i$ and $j$ separated by an angular distance $\Delta\theta_{ij}$.
881
+ Parameters $\mu$ and $\beta$ (also called inverse temperature) control the
882
+ average degree and the clustering coefficient, respectively.
883
+
884
+ It can be shown [2]_ that the model undergoes a structural phase transition
885
+ at $\beta=1$ so that for $\beta<1$ networks are unclustered in the thermodynamic
886
+ limit (when $N\to \infty$) whereas for $\beta>1$ the ensemble generates
887
+ networks with finite clustering coefficient.
888
+
889
+ The $\mathbb{S}^1$ model can be expressed as a purely geometric model
890
+ $\mathbb{H}^2$ in the hyperbolic plane [3]_ by mapping the hidden degree of
891
+ each node into a radial coordinate as
892
+
893
+ $r_i = \hat{R} - \frac{2 \max(1, \beta)}{\beta \zeta} \ln \left(\frac{\kappa_i}{\kappa_0}\right)$
894
+
895
+ where $\hat{R}$ is the radius of the hyperbolic disk and $\zeta$ is the curvature,
896
+
897
+ $\hat{R} = \frac{2}{\zeta} \ln \left(\frac{N}{\pi}\right)
898
+ - \frac{2\max(1, \beta)}{\beta \zeta} \ln (\mu \kappa_0^2)$
899
+
900
+ The connection probability then reads
901
+
902
+ $p_{ij} = \frac{1}{1 + \exp\left({\frac{\beta\zeta}{2} (x_{ij} - \hat{R})}\right)}$
903
+
904
+ where
905
+
906
+ $x_{ij} = r_i + r_j + \frac{2}{\zeta} \ln \frac{\Delta\theta_{ij}}{2}$
907
+
908
+ is a good approximation of the hyperbolic distance between two nodes separated
909
+ by an angular distance $\Delta\theta_{ij}$ with radial coordinates $r_i$ and $r_j$.
910
+ For $\beta > 1$, the curvature $\zeta = 1$, for $\beta < 1$, $\zeta = \beta^{-1}$.
911
+
912
+
913
+ Parameters
914
+ ----------
915
+ Either `n`, `gamma`, `mean_degree` are provided or `kappas`. The values of
916
+ `n`, `gamma`, `mean_degree` (if provided) are used to construct a random
917
+ kappa-dict keyed by node with values sampled from a power-law distribution.
918
+
919
+ beta : positive number
920
+ Inverse temperature, controlling the clustering coefficient.
921
+ n : int (default: None)
922
+ Size of the network (number of nodes).
923
+ If not provided, `kappas` must be provided and holds the nodes.
924
+ gamma : float (default: None)
925
+ Exponent of the power-law distribution for hidden degrees `kappas`.
926
+ If not provided, `kappas` must be provided directly.
927
+ mean_degree : float (default: None)
928
+ The mean degree in the network.
929
+ If not provided, `kappas` must be provided directly.
930
+ kappas : dict (default: None)
931
+ A dict keyed by node to its hidden degree value.
932
+ If not provided, random values are computed based on a power-law
933
+ distribution using `n`, `gamma` and `mean_degree`.
934
+ seed : int, random_state, or None (default)
935
+ Indicator of random number generation state.
936
+ See :ref:`Randomness<randomness>`.
937
+
938
+ Returns
939
+ -------
940
+ Graph
941
+ A random geometric soft configuration graph (undirected with no self-loops).
942
+ Each node has three node-attributes:
943
+
944
+ - ``kappa`` that represents the hidden degree.
945
+
946
+ - ``theta`` the position in the similarity space ($\mathbb{S}^1$) which is
947
+ also the angular position in the hyperbolic plane.
948
+
949
+ - ``radius`` the radial position in the hyperbolic plane
950
+ (based on the hidden degree).
951
+
952
+
953
+ Examples
954
+ --------
955
+ Generate a network with specified parameters:
956
+
957
+ >>> G = nx.geometric_soft_configuration_graph(
958
+ ... beta=1.5, n=100, gamma=2.7, mean_degree=5
959
+ ... )
960
+
961
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
962
+ is set to 1.5 and the exponent of the powerlaw distribution of the hidden
963
+ degrees is 2.7 with mean value of 5.
964
+
965
+ Generate a network with predefined hidden degrees:
966
+
967
+ >>> kappas = {i: 10 for i in range(100)}
968
+ >>> G = nx.geometric_soft_configuration_graph(beta=2.5, kappas=kappas)
969
+
970
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
971
+ is set to 2.5 and all nodes with hidden degree $\kappa=10$.
972
+
973
+
974
+ References
975
+ ----------
976
+ .. [1] Serrano, M. Á., Krioukov, D., & Boguñá, M. (2008). Self-similarity
977
+ of complex networks and hidden metric spaces. Physical review letters, 100(7), 078701.
978
+
979
+ .. [2] van der Kolk, J., Serrano, M. Á., & Boguñá, M. (2022). An anomalous
980
+ topological phase transition in spatial random graphs. Communications Physics, 5(1), 245.
981
+
982
+ .. [3] Krioukov, D., Papadopoulos, F., Kitsak, M., Vahdat, A., & Boguná, M. (2010).
983
+ Hyperbolic geometry of complex networks. Physical Review E, 82(3), 036106.
984
+
985
+ """
986
+ if beta <= 0:
987
+ raise nx.NetworkXError("The parameter beta cannot be smaller or equal to 0.")
988
+
989
+ if kappas is not None:
990
+ if not all((n is None, gamma is None, mean_degree is None)):
991
+ raise nx.NetworkXError(
992
+ "When kappas is input, n, gamma and mean_degree must not be."
993
+ )
994
+
995
+ n = len(kappas)
996
+ mean_degree = sum(kappas) / len(kappas)
997
+ else:
998
+ if any((n is None, gamma is None, mean_degree is None)):
999
+ raise nx.NetworkXError(
1000
+ "Please provide either kappas, or all 3 of: n, gamma and mean_degree."
1001
+ )
1002
+
1003
+ # Generate `n` hidden degrees from a powerlaw distribution
1004
+ # with given exponent `gamma` and mean value `mean_degree`
1005
+ gam_ratio = (gamma - 2) / (gamma - 1)
1006
+ kappa_0 = mean_degree * gam_ratio * (1 - 1 / n) / (1 - 1 / n**gam_ratio)
1007
+ base = 1 - 1 / n
1008
+ power = 1 / (1 - gamma)
1009
+ kappas = {i: kappa_0 * (1 - seed.random() * base) ** power for i in range(n)}
1010
+
1011
+ G = nx.Graph()
1012
+ R = n / (2 * math.pi)
1013
+
1014
+ # Approximate values for mu in the thermodynamic limit (when n -> infinity)
1015
+ if beta > 1:
1016
+ mu = beta * math.sin(math.pi / beta) / (2 * math.pi * mean_degree)
1017
+ elif beta == 1:
1018
+ mu = 1 / (2 * mean_degree * math.log(n))
1019
+ else:
1020
+ mu = (1 - beta) / (2**beta * mean_degree * n ** (1 - beta))
1021
+
1022
+ # Generate random positions on a circle
1023
+ thetas = {k: seed.uniform(0, 2 * math.pi) for k in kappas}
1024
+
1025
+ for u in kappas:
1026
+ for v in list(G):
1027
+ angle = math.pi - math.fabs(math.pi - math.fabs(thetas[u] - thetas[v]))
1028
+ dij = math.pow(R * angle, beta)
1029
+ mu_kappas = math.pow(mu * kappas[u] * kappas[v], max(1, beta))
1030
+ p_ij = 1 / (1 + dij / mu_kappas)
1031
+
1032
+ # Create an edge with a certain connection probability
1033
+ if seed.random() < p_ij:
1034
+ G.add_edge(u, v)
1035
+ G.add_node(u)
1036
+
1037
+ nx.set_node_attributes(G, thetas, "theta")
1038
+ nx.set_node_attributes(G, kappas, "kappa")
1039
+
1040
+ # Map hidden degrees into the radial coordinates
1041
+ zeta = 1 if beta > 1 else 1 / beta
1042
+ kappa_min = min(kappas.values())
1043
+ R_c = 2 * max(1, beta) / (beta * zeta)
1044
+ R_hat = (2 / zeta) * math.log(n / math.pi) - R_c * math.log(mu * kappa_min)
1045
+ radii = {node: R_hat - R_c * math.log(kappa) for node, kappa in kappas.items()}
1046
+ nx.set_node_attributes(G, radii, "radius")
1047
+
1048
+ return G
janus/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
janus/lib/python3.10/site-packages/networkx/generators/interval_graph.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for interval graph.
3
+ """
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = ["interval_graph"]
10
+
11
+
12
+ @nx._dispatchable(graphs=None, returns_graph=True)
13
+ def interval_graph(intervals):
14
+ """Generates an interval graph for a list of intervals given.
15
+
16
+ In graph theory, an interval graph is an undirected graph formed from a set
17
+ of closed intervals on the real line, with a vertex for each interval
18
+ and an edge between vertices whose intervals intersect.
19
+ It is the intersection graph of the intervals.
20
+
21
+ More information can be found at:
22
+ https://en.wikipedia.org/wiki/Interval_graph
23
+
24
+ Parameters
25
+ ----------
26
+ intervals : a sequence of intervals, say (l, r) where l is the left end,
27
+ and r is the right end of the closed interval.
28
+
29
+ Returns
30
+ -------
31
+ G : networkx graph
32
+
33
+ Examples
34
+ --------
35
+ >>> intervals = [(-2, 3), [1, 4], (2, 3), (4, 6)]
36
+ >>> G = nx.interval_graph(intervals)
37
+ >>> sorted(G.edges)
38
+ [((-2, 3), (1, 4)), ((-2, 3), (2, 3)), ((1, 4), (2, 3)), ((1, 4), (4, 6))]
39
+
40
+ Raises
41
+ ------
42
+ :exc:`TypeError`
43
+ if `intervals` contains None or an element which is not
44
+ collections.abc.Sequence or not a length of 2.
45
+ :exc:`ValueError`
46
+ if `intervals` contains an interval such that min1 > max1
47
+ where min1,max1 = interval
48
+ """
49
+ intervals = list(intervals)
50
+ for interval in intervals:
51
+ if not (isinstance(interval, Sequence) and len(interval) == 2):
52
+ raise TypeError(
53
+ "Each interval must have length 2, and be a "
54
+ "collections.abc.Sequence such as tuple or list."
55
+ )
56
+ if interval[0] > interval[1]:
57
+ raise ValueError(f"Interval must have lower value first. Got {interval}")
58
+
59
+ graph = nx.Graph()
60
+
61
+ tupled_intervals = [tuple(interval) for interval in intervals]
62
+ graph.add_nodes_from(tupled_intervals)
63
+
64
+ while tupled_intervals:
65
+ min1, max1 = interval1 = tupled_intervals.pop()
66
+ for interval2 in tupled_intervals:
67
+ min2, max2 = interval2
68
+ if max1 >= min2 and max2 >= min1:
69
+ graph.add_edge(interval1, interval2)
70
+ return graph
janus/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
janus/lib/python3.10/site-packages/networkx/generators/line.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating line graphs."""
2
+
3
+ from collections import defaultdict
4
+ from functools import partial
5
+ from itertools import combinations
6
+
7
+ import networkx as nx
8
+ from networkx.utils import arbitrary_element
9
+ from networkx.utils.decorators import not_implemented_for
10
+
11
+ __all__ = ["line_graph", "inverse_line_graph"]
12
+
13
+
14
+ @nx._dispatchable(returns_graph=True)
15
+ def line_graph(G, create_using=None):
16
+ r"""Returns the line graph of the graph or digraph `G`.
17
+
18
+ The line graph of a graph `G` has a node for each edge in `G` and an
19
+ edge joining those nodes if the two edges in `G` share a common node. For
20
+ directed graphs, nodes are adjacent exactly when the edges they represent
21
+ form a directed path of length two.
22
+
23
+ The nodes of the line graph are 2-tuples of nodes in the original graph (or
24
+ 3-tuples for multigraphs, with the key of the edge as the third element).
25
+
26
+ For information about self-loops and more discussion, see the **Notes**
27
+ section below.
28
+
29
+ Parameters
30
+ ----------
31
+ G : graph
32
+ A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
33
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
34
+ Graph type to create. If graph instance, then cleared before populated.
35
+
36
+ Returns
37
+ -------
38
+ L : graph
39
+ The line graph of G.
40
+
41
+ Examples
42
+ --------
43
+ >>> G = nx.star_graph(3)
44
+ >>> L = nx.line_graph(G)
45
+ >>> print(sorted(map(sorted, L.edges()))) # makes a 3-clique, K3
46
+ [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
47
+
48
+ Edge attributes from `G` are not copied over as node attributes in `L`, but
49
+ attributes can be copied manually:
50
+
51
+ >>> G = nx.path_graph(4)
52
+ >>> G.add_edges_from((u, v, {"tot": u + v}) for u, v in G.edges)
53
+ >>> G.edges(data=True)
54
+ EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
55
+ >>> H = nx.line_graph(G)
56
+ >>> H.add_nodes_from((node, G.edges[node]) for node in H)
57
+ >>> H.nodes(data=True)
58
+ NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
59
+
60
+ Notes
61
+ -----
62
+ Graph, node, and edge data are not propagated to the new graph. For
63
+ undirected graphs, the nodes in G must be sortable, otherwise the
64
+ constructed line graph may not be correct.
65
+
66
+ *Self-loops in undirected graphs*
67
+
68
+ For an undirected graph `G` without multiple edges, each edge can be
69
+ written as a set `\{u, v\}`. Its line graph `L` has the edges of `G` as
70
+ its nodes. If `x` and `y` are two nodes in `L`, then `\{x, y\}` is an edge
71
+ in `L` if and only if the intersection of `x` and `y` is nonempty. Thus,
72
+ the set of all edges is determined by the set of all pairwise intersections
73
+ of edges in `G`.
74
+
75
+ Trivially, every edge in G would have a nonzero intersection with itself,
76
+ and so every node in `L` should have a self-loop. This is not so
77
+ interesting, and the original context of line graphs was with simple
78
+ graphs, which had no self-loops or multiple edges. The line graph was also
79
+ meant to be a simple graph and thus, self-loops in `L` are not part of the
80
+ standard definition of a line graph. In a pairwise intersection matrix,
81
+ this is analogous to excluding the diagonal entries from the line graph
82
+ definition.
83
+
84
+ Self-loops and multiple edges in `G` add nodes to `L` in a natural way, and
85
+ do not require any fundamental changes to the definition. It might be
86
+ argued that the self-loops we excluded before should now be included.
87
+ However, the self-loops are still "trivial" in some sense and thus, are
88
+ usually excluded.
89
+
90
+ *Self-loops in directed graphs*
91
+
92
+ For a directed graph `G` without multiple edges, each edge can be written
93
+ as a tuple `(u, v)`. Its line graph `L` has the edges of `G` as its
94
+ nodes. If `x` and `y` are two nodes in `L`, then `(x, y)` is an edge in `L`
95
+ if and only if the tail of `x` matches the head of `y`, for example, if `x
96
+ = (a, b)` and `y = (b, c)` for some vertices `a`, `b`, and `c` in `G`.
97
+
98
+ Due to the directed nature of the edges, it is no longer the case that
99
+ every edge in `G` should have a self-loop in `L`. Now, the only time
100
+ self-loops arise is if a node in `G` itself has a self-loop. So such
101
+ self-loops are no longer "trivial" but instead, represent essential
102
+ features of the topology of `G`. For this reason, the historical
103
+ development of line digraphs is such that self-loops are included. When the
104
+ graph `G` has multiple edges, once again only superficial changes are
105
+ required to the definition.
106
+
107
+ References
108
+ ----------
109
+ * Harary, Frank, and Norman, Robert Z., "Some properties of line digraphs",
110
+ Rend. Circ. Mat. Palermo, II. Ser. 9 (1960), 161--168.
111
+ * Hemminger, R. L.; Beineke, L. W. (1978), "Line graphs and line digraphs",
112
+ in Beineke, L. W.; Wilson, R. J., Selected Topics in Graph Theory,
113
+ Academic Press Inc., pp. 271--305.
114
+
115
+ """
116
+ if G.is_directed():
117
+ L = _lg_directed(G, create_using=create_using)
118
+ else:
119
+ L = _lg_undirected(G, selfloops=False, create_using=create_using)
120
+ return L
121
+
122
+
123
+ def _lg_directed(G, create_using=None):
124
+ """Returns the line graph L of the (multi)digraph G.
125
+
126
+ Edges in G appear as nodes in L, represented as tuples of the form (u,v)
127
+ or (u,v,key) if G is a multidigraph. A node in L corresponding to the edge
128
+ (u,v) is connected to every node corresponding to an edge (v,w).
129
+
130
+ Parameters
131
+ ----------
132
+ G : digraph
133
+ A directed graph or directed multigraph.
134
+ create_using : NetworkX graph constructor, optional
135
+ Graph type to create. If graph instance, then cleared before populated.
136
+ Default is to use the same graph class as `G`.
137
+
138
+ """
139
+ L = nx.empty_graph(0, create_using, default=G.__class__)
140
+
141
+ # Create a graph specific edge function.
142
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
143
+
144
+ for from_node in get_edges():
145
+ # from_node is: (u,v) or (u,v,key)
146
+ L.add_node(from_node)
147
+ for to_node in get_edges(from_node[1]):
148
+ L.add_edge(from_node, to_node)
149
+
150
+ return L
151
+
152
+
153
+ def _lg_undirected(G, selfloops=False, create_using=None):
154
+ """Returns the line graph L of the (multi)graph G.
155
+
156
+ Edges in G appear as nodes in L, represented as sorted tuples of the form
157
+ (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
158
+ the edge {u,v} is connected to every node corresponding to an edge that
159
+ involves u or v.
160
+
161
+ Parameters
162
+ ----------
163
+ G : graph
164
+ An undirected graph or multigraph.
165
+ selfloops : bool
166
+ If `True`, then self-loops are included in the line graph. If `False`,
167
+ they are excluded.
168
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
169
+ Graph type to create. If graph instance, then cleared before populated.
170
+
171
+ Notes
172
+ -----
173
+ The standard algorithm for line graphs of undirected graphs does not
174
+ produce self-loops.
175
+
176
+ """
177
+ L = nx.empty_graph(0, create_using, default=G.__class__)
178
+
179
+ # Graph specific functions for edges.
180
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
181
+
182
+ # Determine if we include self-loops or not.
183
+ shift = 0 if selfloops else 1
184
+
185
+ # Introduce numbering of nodes
186
+ node_index = {n: i for i, n in enumerate(G)}
187
+
188
+ # Lift canonical representation of nodes to edges in line graph
189
+ edge_key_function = lambda edge: (node_index[edge[0]], node_index[edge[1]])
190
+
191
+ edges = set()
192
+ for u in G:
193
+ # Label nodes as a sorted tuple of nodes in original graph.
194
+ # Decide on representation of {u, v} as (u, v) or (v, u) depending on node_index.
195
+ # -> This ensures a canonical representation and avoids comparing values of different types.
196
+ nodes = [tuple(sorted(x[:2], key=node_index.get)) + x[2:] for x in get_edges(u)]
197
+
198
+ if len(nodes) == 1:
199
+ # Then the edge will be an isolated node in L.
200
+ L.add_node(nodes[0])
201
+
202
+ # Add a clique of `nodes` to graph. To prevent double adding edges,
203
+ # especially important for multigraphs, we store the edges in
204
+ # canonical form in a set.
205
+ for i, a in enumerate(nodes):
206
+ edges.update(
207
+ [
208
+ tuple(sorted((a, b), key=edge_key_function))
209
+ for b in nodes[i + shift :]
210
+ ]
211
+ )
212
+
213
+ L.add_edges_from(edges)
214
+ return L
215
+
216
+
217
+ @not_implemented_for("directed")
218
+ @not_implemented_for("multigraph")
219
+ @nx._dispatchable(returns_graph=True)
220
+ def inverse_line_graph(G):
221
+ """Returns the inverse line graph of graph G.
222
+
223
+ If H is a graph, and G is the line graph of H, such that G = L(H).
224
+ Then H is the inverse line graph of G.
225
+
226
+ Not all graphs are line graphs and these do not have an inverse line graph.
227
+ In these cases this function raises a NetworkXError.
228
+
229
+ Parameters
230
+ ----------
231
+ G : graph
232
+ A NetworkX Graph
233
+
234
+ Returns
235
+ -------
236
+ H : graph
237
+ The inverse line graph of G.
238
+
239
+ Raises
240
+ ------
241
+ NetworkXNotImplemented
242
+ If G is directed or a multigraph
243
+
244
+ NetworkXError
245
+ If G is not a line graph
246
+
247
+ Notes
248
+ -----
249
+ This is an implementation of the Roussopoulos algorithm[1]_.
250
+
251
+ If G consists of multiple components, then the algorithm doesn't work.
252
+ You should invert every component separately:
253
+
254
+ >>> K5 = nx.complete_graph(5)
255
+ >>> P4 = nx.Graph([("a", "b"), ("b", "c"), ("c", "d")])
256
+ >>> G = nx.union(K5, P4)
257
+ >>> root_graphs = []
258
+ >>> for comp in nx.connected_components(G):
259
+ ... root_graphs.append(nx.inverse_line_graph(G.subgraph(comp)))
260
+ >>> len(root_graphs)
261
+ 2
262
+
263
+ References
264
+ ----------
265
+ .. [1] Roussopoulos, N.D. , "A max {m, n} algorithm for determining the graph H from
266
+ its line graph G", Information Processing Letters 2, (1973), 108--112, ISSN 0020-0190,
267
+ `DOI link <https://doi.org/10.1016/0020-0190(73)90029-X>`_
268
+
269
+ """
270
+ if G.number_of_nodes() == 0:
271
+ return nx.empty_graph(1)
272
+ elif G.number_of_nodes() == 1:
273
+ v = arbitrary_element(G)
274
+ a = (v, 0)
275
+ b = (v, 1)
276
+ H = nx.Graph([(a, b)])
277
+ return H
278
+ elif G.number_of_nodes() > 1 and G.number_of_edges() == 0:
279
+ msg = (
280
+ "inverse_line_graph() doesn't work on an edgeless graph. "
281
+ "Please use this function on each component separately."
282
+ )
283
+ raise nx.NetworkXError(msg)
284
+
285
+ if nx.number_of_selfloops(G) != 0:
286
+ msg = (
287
+ "A line graph as generated by NetworkX has no selfloops, so G has no "
288
+ "inverse line graph. Please remove the selfloops from G and try again."
289
+ )
290
+ raise nx.NetworkXError(msg)
291
+
292
+ starting_cell = _select_starting_cell(G)
293
+ P = _find_partition(G, starting_cell)
294
+ # count how many times each vertex appears in the partition set
295
+ P_count = {u: 0 for u in G.nodes}
296
+ for p in P:
297
+ for u in p:
298
+ P_count[u] += 1
299
+
300
+ if max(P_count.values()) > 2:
301
+ msg = "G is not a line graph (vertex found in more than two partition cells)"
302
+ raise nx.NetworkXError(msg)
303
+ W = tuple((u,) for u in P_count if P_count[u] == 1)
304
+ H = nx.Graph()
305
+ H.add_nodes_from(P)
306
+ H.add_nodes_from(W)
307
+ for a, b in combinations(H.nodes, 2):
308
+ if any(a_bit in b for a_bit in a):
309
+ H.add_edge(a, b)
310
+ return H
311
+
312
+
313
+ def _triangles(G, e):
314
+ """Return list of all triangles containing edge e"""
315
+ u, v = e
316
+ if u not in G:
317
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
318
+ if v not in G[u]:
319
+ raise nx.NetworkXError(f"Edge ({u}, {v}) not in graph")
320
+ triangle_list = []
321
+ for x in G[u]:
322
+ if x in G[v]:
323
+ triangle_list.append((u, v, x))
324
+ return triangle_list
325
+
326
+
327
+ def _odd_triangle(G, T):
328
+ """Test whether T is an odd triangle in G
329
+
330
+ Parameters
331
+ ----------
332
+ G : NetworkX Graph
333
+ T : 3-tuple of vertices forming triangle in G
334
+
335
+ Returns
336
+ -------
337
+ True is T is an odd triangle
338
+ False otherwise
339
+
340
+ Raises
341
+ ------
342
+ NetworkXError
343
+ T is not a triangle in G
344
+
345
+ Notes
346
+ -----
347
+ An odd triangle is one in which there exists another vertex in G which is
348
+ adjacent to either exactly one or exactly all three of the vertices in the
349
+ triangle.
350
+
351
+ """
352
+ for u in T:
353
+ if u not in G.nodes():
354
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
355
+ for e in list(combinations(T, 2)):
356
+ if e[0] not in G[e[1]]:
357
+ raise nx.NetworkXError(f"Edge ({e[0]}, {e[1]}) not in graph")
358
+
359
+ T_nbrs = defaultdict(int)
360
+ for t in T:
361
+ for v in G[t]:
362
+ if v not in T:
363
+ T_nbrs[v] += 1
364
+ return any(T_nbrs[v] in [1, 3] for v in T_nbrs)
365
+
366
+
367
+ def _find_partition(G, starting_cell):
368
+ """Find a partition of the vertices of G into cells of complete graphs
369
+
370
+ Parameters
371
+ ----------
372
+ G : NetworkX Graph
373
+ starting_cell : tuple of vertices in G which form a cell
374
+
375
+ Returns
376
+ -------
377
+ List of tuples of vertices of G
378
+
379
+ Raises
380
+ ------
381
+ NetworkXError
382
+ If a cell is not a complete subgraph then G is not a line graph
383
+ """
384
+ G_partition = G.copy()
385
+ P = [starting_cell] # partition set
386
+ G_partition.remove_edges_from(list(combinations(starting_cell, 2)))
387
+ # keep list of partitioned nodes which might have an edge in G_partition
388
+ partitioned_vertices = list(starting_cell)
389
+ while G_partition.number_of_edges() > 0:
390
+ # there are still edges left and so more cells to be made
391
+ u = partitioned_vertices.pop()
392
+ deg_u = len(G_partition[u])
393
+ if deg_u != 0:
394
+ # if u still has edges then we need to find its other cell
395
+ # this other cell must be a complete subgraph or else G is
396
+ # not a line graph
397
+ new_cell = [u] + list(G_partition[u])
398
+ for u in new_cell:
399
+ for v in new_cell:
400
+ if (u != v) and (v not in G_partition[u]):
401
+ msg = (
402
+ "G is not a line graph "
403
+ "(partition cell not a complete subgraph)"
404
+ )
405
+ raise nx.NetworkXError(msg)
406
+ P.append(tuple(new_cell))
407
+ G_partition.remove_edges_from(list(combinations(new_cell, 2)))
408
+ partitioned_vertices += new_cell
409
+ return P
410
+
411
+
412
+ def _select_starting_cell(G, starting_edge=None):
413
+ """Select a cell to initiate _find_partition
414
+
415
+ Parameters
416
+ ----------
417
+ G : NetworkX Graph
418
+ starting_edge: an edge to build the starting cell from
419
+
420
+ Returns
421
+ -------
422
+ Tuple of vertices in G
423
+
424
+ Raises
425
+ ------
426
+ NetworkXError
427
+ If it is determined that G is not a line graph
428
+
429
+ Notes
430
+ -----
431
+ If starting edge not specified then pick an arbitrary edge - doesn't
432
+ matter which. However, this function may call itself requiring a
433
+ specific starting edge. Note that the r, s notation for counting
434
+ triangles is the same as in the Roussopoulos paper cited above.
435
+ """
436
+ if starting_edge is None:
437
+ e = arbitrary_element(G.edges())
438
+ else:
439
+ e = starting_edge
440
+ if e[0] not in G.nodes():
441
+ raise nx.NetworkXError(f"Vertex {e[0]} not in graph")
442
+ if e[1] not in G[e[0]]:
443
+ msg = f"starting_edge ({e[0]}, {e[1]}) is not in the Graph"
444
+ raise nx.NetworkXError(msg)
445
+ e_triangles = _triangles(G, e)
446
+ r = len(e_triangles)
447
+ if r == 0:
448
+ # there are no triangles containing e, so the starting cell is just e
449
+ starting_cell = e
450
+ elif r == 1:
451
+ # there is exactly one triangle, T, containing e. If other 2 edges
452
+ # of T belong only to this triangle then T is starting cell
453
+ T = e_triangles[0]
454
+ a, b, c = T
455
+ # ab was original edge so check the other 2 edges
456
+ ac_edges = len(_triangles(G, (a, c)))
457
+ bc_edges = len(_triangles(G, (b, c)))
458
+ if ac_edges == 1:
459
+ if bc_edges == 1:
460
+ starting_cell = T
461
+ else:
462
+ return _select_starting_cell(G, starting_edge=(b, c))
463
+ else:
464
+ return _select_starting_cell(G, starting_edge=(a, c))
465
+ else:
466
+ # r >= 2 so we need to count the number of odd triangles, s
467
+ s = 0
468
+ odd_triangles = []
469
+ for T in e_triangles:
470
+ if _odd_triangle(G, T):
471
+ s += 1
472
+ odd_triangles.append(T)
473
+ if r == 2 and s == 0:
474
+ # in this case either triangle works, so just use T
475
+ starting_cell = T
476
+ elif r - 1 <= s <= r:
477
+ # check if odd triangles containing e form complete subgraph
478
+ triangle_nodes = set()
479
+ for T in odd_triangles:
480
+ for x in T:
481
+ triangle_nodes.add(x)
482
+
483
+ for u in triangle_nodes:
484
+ for v in triangle_nodes:
485
+ if u != v and (v not in G[u]):
486
+ msg = (
487
+ "G is not a line graph (odd triangles "
488
+ "do not form complete subgraph)"
489
+ )
490
+ raise nx.NetworkXError(msg)
491
+ # otherwise then we can use this as the starting cell
492
+ starting_cell = tuple(triangle_nodes)
493
+
494
+ else:
495
+ msg = (
496
+ "G is not a line graph (incorrect number of "
497
+ "odd triangles around starting edge)"
498
+ )
499
+ raise nx.NetworkXError(msg)
500
+ return starting_cell
janus/lib/python3.10/site-packages/networkx/generators/random_graphs.py ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random graphs.
3
+
4
+ """
5
+
6
+ import itertools
7
+ import math
8
+ from collections import defaultdict
9
+
10
+ import networkx as nx
11
+ from networkx.utils import py_random_state
12
+
13
+ from ..utils.misc import check_create_using
14
+ from .classic import complete_graph, empty_graph, path_graph, star_graph
15
+ from .degree_seq import degree_sequence_tree
16
+
17
+ __all__ = [
18
+ "fast_gnp_random_graph",
19
+ "gnp_random_graph",
20
+ "dense_gnm_random_graph",
21
+ "gnm_random_graph",
22
+ "erdos_renyi_graph",
23
+ "binomial_graph",
24
+ "newman_watts_strogatz_graph",
25
+ "watts_strogatz_graph",
26
+ "connected_watts_strogatz_graph",
27
+ "random_regular_graph",
28
+ "barabasi_albert_graph",
29
+ "dual_barabasi_albert_graph",
30
+ "extended_barabasi_albert_graph",
31
+ "powerlaw_cluster_graph",
32
+ "random_lobster",
33
+ "random_shell_graph",
34
+ "random_powerlaw_tree",
35
+ "random_powerlaw_tree_sequence",
36
+ "random_kernel_graph",
37
+ ]
38
+
39
+
40
+ @py_random_state(2)
41
+ @nx._dispatchable(graphs=None, returns_graph=True)
42
+ def fast_gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
43
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
44
+ a binomial graph.
45
+
46
+ Parameters
47
+ ----------
48
+ n : int
49
+ The number of nodes.
50
+ p : float
51
+ Probability for edge creation.
52
+ seed : integer, random_state, or None (default)
53
+ Indicator of random number generation state.
54
+ See :ref:`Randomness<randomness>`.
55
+ directed : bool, optional (default=False)
56
+ If True, this function returns a directed graph.
57
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
58
+ Graph type to create. If graph instance, then cleared before populated.
59
+ Multigraph types are not supported and raise a ``NetworkXError``.
60
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
61
+
62
+ Notes
63
+ -----
64
+ The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
65
+ (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
66
+
67
+ This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
68
+ edges, which equals $p n (n - 1) / 2$. This should be faster than
69
+ :func:`gnp_random_graph` when $p$ is small and the expected number of edges
70
+ is small (that is, the graph is sparse).
71
+
72
+ See Also
73
+ --------
74
+ gnp_random_graph
75
+
76
+ References
77
+ ----------
78
+ .. [1] Vladimir Batagelj and Ulrik Brandes,
79
+ "Efficient generation of large random networks",
80
+ Phys. Rev. E, 71, 036113, 2005.
81
+ """
82
+ default = nx.DiGraph if directed else nx.Graph
83
+ create_using = check_create_using(
84
+ create_using, directed=directed, multigraph=False, default=default
85
+ )
86
+ if p <= 0 or p >= 1:
87
+ return nx.gnp_random_graph(
88
+ n, p, seed=seed, directed=directed, create_using=create_using
89
+ )
90
+
91
+ G = empty_graph(n, create_using=create_using)
92
+
93
+ lp = math.log(1.0 - p)
94
+
95
+ if directed:
96
+ v = 1
97
+ w = -1
98
+ while v < n:
99
+ lr = math.log(1.0 - seed.random())
100
+ w = w + 1 + int(lr / lp)
101
+ while w >= v and v < n:
102
+ w = w - v
103
+ v = v + 1
104
+ if v < n:
105
+ G.add_edge(w, v)
106
+
107
+ # Nodes in graph are from 0,n-1 (start with v as the second node index).
108
+ v = 1
109
+ w = -1
110
+ while v < n:
111
+ lr = math.log(1.0 - seed.random())
112
+ w = w + 1 + int(lr / lp)
113
+ while w >= v and v < n:
114
+ w = w - v
115
+ v = v + 1
116
+ if v < n:
117
+ G.add_edge(v, w)
118
+ return G
119
+
120
+
121
+ @py_random_state(2)
122
+ @nx._dispatchable(graphs=None, returns_graph=True)
123
+ def gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
124
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
125
+ or a binomial graph.
126
+
127
+ The $G_{n,p}$ model chooses each of the possible edges with probability $p$.
128
+
129
+ Parameters
130
+ ----------
131
+ n : int
132
+ The number of nodes.
133
+ p : float
134
+ Probability for edge creation.
135
+ seed : integer, random_state, or None (default)
136
+ Indicator of random number generation state.
137
+ See :ref:`Randomness<randomness>`.
138
+ directed : bool, optional (default=False)
139
+ If True, this function returns a directed graph.
140
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
141
+ Graph type to create. If graph instance, then cleared before populated.
142
+ Multigraph types are not supported and raise a ``NetworkXError``.
143
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
144
+
145
+ See Also
146
+ --------
147
+ fast_gnp_random_graph
148
+
149
+ Notes
150
+ -----
151
+ This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for
152
+ small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm.
153
+
154
+ :func:`binomial_graph` and :func:`erdos_renyi_graph` are
155
+ aliases for :func:`gnp_random_graph`.
156
+
157
+ >>> nx.binomial_graph is nx.gnp_random_graph
158
+ True
159
+ >>> nx.erdos_renyi_graph is nx.gnp_random_graph
160
+ True
161
+
162
+ References
163
+ ----------
164
+ .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
165
+ .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
166
+ """
167
+ default = nx.DiGraph if directed else nx.Graph
168
+ create_using = check_create_using(
169
+ create_using, directed=directed, multigraph=False, default=default
170
+ )
171
+ if p >= 1:
172
+ return complete_graph(n, create_using=create_using)
173
+
174
+ G = nx.empty_graph(n, create_using=create_using)
175
+ if p <= 0:
176
+ return G
177
+
178
+ edgetool = itertools.permutations if directed else itertools.combinations
179
+ for e in edgetool(range(n), 2):
180
+ if seed.random() < p:
181
+ G.add_edge(*e)
182
+ return G
183
+
184
+
185
+ # add some aliases to common names
186
+ binomial_graph = gnp_random_graph
187
+ erdos_renyi_graph = gnp_random_graph
188
+
189
+
190
+ @py_random_state(2)
191
+ @nx._dispatchable(graphs=None, returns_graph=True)
192
+ def dense_gnm_random_graph(n, m, seed=None, *, create_using=None):
193
+ """Returns a $G_{n,m}$ random graph.
194
+
195
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
196
+ of all graphs with $n$ nodes and $m$ edges.
197
+
198
+ This algorithm should be faster than :func:`gnm_random_graph` for dense
199
+ graphs.
200
+
201
+ Parameters
202
+ ----------
203
+ n : int
204
+ The number of nodes.
205
+ m : int
206
+ The number of edges.
207
+ seed : integer, random_state, or None (default)
208
+ Indicator of random number generation state.
209
+ See :ref:`Randomness<randomness>`.
210
+ create_using : Graph constructor, optional (default=nx.Graph)
211
+ Graph type to create. If graph instance, then cleared before populated.
212
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
213
+
214
+ See Also
215
+ --------
216
+ gnm_random_graph
217
+
218
+ Notes
219
+ -----
220
+ Algorithm by Keith M. Briggs Mar 31, 2006.
221
+ Inspired by Knuth's Algorithm S (Selection sampling technique),
222
+ in section 3.4.2 of [1]_.
223
+
224
+ References
225
+ ----------
226
+ .. [1] Donald E. Knuth, The Art of Computer Programming,
227
+ Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
228
+ """
229
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
230
+ mmax = n * (n - 1) // 2
231
+ if m >= mmax:
232
+ return complete_graph(n, create_using)
233
+ G = empty_graph(n, create_using)
234
+
235
+ if n == 1:
236
+ return G
237
+
238
+ u = 0
239
+ v = 1
240
+ t = 0
241
+ k = 0
242
+ while True:
243
+ if seed.randrange(mmax - t) < m - k:
244
+ G.add_edge(u, v)
245
+ k += 1
246
+ if k == m:
247
+ return G
248
+ t += 1
249
+ v += 1
250
+ if v == n: # go to next row of adjacency matrix
251
+ u += 1
252
+ v = u + 1
253
+
254
+
255
+ @py_random_state(2)
256
+ @nx._dispatchable(graphs=None, returns_graph=True)
257
+ def gnm_random_graph(n, m, seed=None, directed=False, *, create_using=None):
258
+ """Returns a $G_{n,m}$ random graph.
259
+
260
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
261
+ of all graphs with $n$ nodes and $m$ edges.
262
+
263
+ This algorithm should be faster than :func:`dense_gnm_random_graph` for
264
+ sparse graphs.
265
+
266
+ Parameters
267
+ ----------
268
+ n : int
269
+ The number of nodes.
270
+ m : int
271
+ The number of edges.
272
+ seed : integer, random_state, or None (default)
273
+ Indicator of random number generation state.
274
+ See :ref:`Randomness<randomness>`.
275
+ directed : bool, optional (default=False)
276
+ If True return a directed graph
277
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
278
+ Graph type to create. If graph instance, then cleared before populated.
279
+ Multigraph types are not supported and raise a ``NetworkXError``.
280
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
281
+
282
+ See also
283
+ --------
284
+ dense_gnm_random_graph
285
+
286
+ """
287
+ default = nx.DiGraph if directed else nx.Graph
288
+ create_using = check_create_using(
289
+ create_using, directed=directed, multigraph=False, default=default
290
+ )
291
+ if n == 1:
292
+ return nx.empty_graph(n, create_using=create_using)
293
+ max_edges = n * (n - 1) if directed else n * (n - 1) / 2.0
294
+ if m >= max_edges:
295
+ return complete_graph(n, create_using=create_using)
296
+
297
+ G = nx.empty_graph(n, create_using=create_using)
298
+ nlist = list(G)
299
+ edge_count = 0
300
+ while edge_count < m:
301
+ # generate random edge,u,v
302
+ u = seed.choice(nlist)
303
+ v = seed.choice(nlist)
304
+ if u == v or G.has_edge(u, v):
305
+ continue
306
+ else:
307
+ G.add_edge(u, v)
308
+ edge_count = edge_count + 1
309
+ return G
310
+
311
+
312
+ @py_random_state(3)
313
+ @nx._dispatchable(graphs=None, returns_graph=True)
314
+ def newman_watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
315
+ """Returns a Newman–Watts–Strogatz small-world graph.
316
+
317
+ Parameters
318
+ ----------
319
+ n : int
320
+ The number of nodes.
321
+ k : int
322
+ Each node is joined with its `k` nearest neighbors in a ring
323
+ topology.
324
+ p : float
325
+ The probability of adding a new edge for each edge.
326
+ seed : integer, random_state, or None (default)
327
+ Indicator of random number generation state.
328
+ See :ref:`Randomness<randomness>`.
329
+ create_using : Graph constructor, optional (default=nx.Graph)
330
+ Graph type to create. If graph instance, then cleared before populated.
331
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
332
+
333
+ Notes
334
+ -----
335
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is
336
+ connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
337
+ is odd). Then shortcuts are created by adding new edges as follows: for
338
+ each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
339
+ neighbors" with probability $p$ add a new edge $(u, w)$ with
340
+ randomly-chosen existing node $w$. In contrast with
341
+ :func:`watts_strogatz_graph`, no edges are removed.
342
+
343
+ See Also
344
+ --------
345
+ watts_strogatz_graph
346
+
347
+ References
348
+ ----------
349
+ .. [1] M. E. J. Newman and D. J. Watts,
350
+ Renormalization group analysis of the small-world network model,
351
+ Physics Letters A, 263, 341, 1999.
352
+ https://doi.org/10.1016/S0375-9601(99)00757-4
353
+ """
354
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
355
+ if k > n:
356
+ raise nx.NetworkXError("k>=n, choose smaller k or larger n")
357
+
358
+ # If k == n the graph return is a complete graph
359
+ if k == n:
360
+ return nx.complete_graph(n, create_using)
361
+
362
+ G = empty_graph(n, create_using)
363
+ nlist = list(G.nodes())
364
+ fromv = nlist
365
+ # connect the k/2 neighbors
366
+ for j in range(1, k // 2 + 1):
367
+ tov = fromv[j:] + fromv[0:j] # the first j are now last
368
+ for i in range(len(fromv)):
369
+ G.add_edge(fromv[i], tov[i])
370
+ # for each edge u-v, with probability p, randomly select existing
371
+ # node w and add new edge u-w
372
+ e = list(G.edges())
373
+ for u, v in e:
374
+ if seed.random() < p:
375
+ w = seed.choice(nlist)
376
+ # no self-loops and reject if edge u-w exists
377
+ # is that the correct NWS model?
378
+ while w == u or G.has_edge(u, w):
379
+ w = seed.choice(nlist)
380
+ if G.degree(u) >= n - 1:
381
+ break # skip this rewiring
382
+ else:
383
+ G.add_edge(u, w)
384
+ return G
385
+
386
+
387
+ @py_random_state(3)
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
390
+ """Returns a Watts–Strogatz small-world graph.
391
+
392
+ Parameters
393
+ ----------
394
+ n : int
395
+ The number of nodes
396
+ k : int
397
+ Each node is joined with its `k` nearest neighbors in a ring
398
+ topology.
399
+ p : float
400
+ The probability of rewiring each edge
401
+ seed : integer, random_state, or None (default)
402
+ Indicator of random number generation state.
403
+ See :ref:`Randomness<randomness>`.
404
+ create_using : Graph constructor, optional (default=nx.Graph)
405
+ Graph type to create. If graph instance, then cleared before populated.
406
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
407
+
408
+ See Also
409
+ --------
410
+ newman_watts_strogatz_graph
411
+ connected_watts_strogatz_graph
412
+
413
+ Notes
414
+ -----
415
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
416
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
417
+ Then shortcuts are created by replacing some edges as follows: for each
418
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
419
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
420
+ random choice of existing node $w$.
421
+
422
+ In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring
423
+ does not increase the number of edges. The rewired graph is not guaranteed
424
+ to be connected as in :func:`connected_watts_strogatz_graph`.
425
+
426
+ References
427
+ ----------
428
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
429
+ Collective dynamics of small-world networks,
430
+ Nature, 393, pp. 440--442, 1998.
431
+ """
432
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
433
+ if k > n:
434
+ raise nx.NetworkXError("k>n, choose smaller k or larger n")
435
+
436
+ # If k == n, the graph is complete not Watts-Strogatz
437
+ if k == n:
438
+ G = nx.complete_graph(n, create_using)
439
+ return G
440
+
441
+ G = nx.empty_graph(n, create_using=create_using)
442
+ nodes = list(range(n)) # nodes are labeled 0 to n-1
443
+ # connect each node to k/2 neighbors
444
+ for j in range(1, k // 2 + 1):
445
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
446
+ G.add_edges_from(zip(nodes, targets))
447
+ # rewire edges from each node
448
+ # loop over all nodes in order (label) and neighbors in order (distance)
449
+ # no self loops or multiple edges allowed
450
+ for j in range(1, k // 2 + 1): # outer loop is neighbors
451
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
452
+ # inner loop in node order
453
+ for u, v in zip(nodes, targets):
454
+ if seed.random() < p:
455
+ w = seed.choice(nodes)
456
+ # Enforce no self-loops or multiple edges
457
+ while w == u or G.has_edge(u, w):
458
+ w = seed.choice(nodes)
459
+ if G.degree(u) >= n - 1:
460
+ break # skip this rewiring
461
+ else:
462
+ G.remove_edge(u, v)
463
+ G.add_edge(u, w)
464
+ return G
465
+
466
+
467
+ @py_random_state(4)
468
+ @nx._dispatchable(graphs=None, returns_graph=True)
469
+ def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None, *, create_using=None):
470
+ """Returns a connected Watts–Strogatz small-world graph.
471
+
472
+ Attempts to generate a connected graph by repeated generation of
473
+ Watts–Strogatz small-world graphs. An exception is raised if the maximum
474
+ number of tries is exceeded.
475
+
476
+ Parameters
477
+ ----------
478
+ n : int
479
+ The number of nodes
480
+ k : int
481
+ Each node is joined with its `k` nearest neighbors in a ring
482
+ topology.
483
+ p : float
484
+ The probability of rewiring each edge
485
+ tries : int
486
+ Number of attempts to generate a connected graph.
487
+ seed : integer, random_state, or None (default)
488
+ Indicator of random number generation state.
489
+ See :ref:`Randomness<randomness>`.
490
+ create_using : Graph constructor, optional (default=nx.Graph)
491
+ Graph type to create. If graph instance, then cleared before populated.
492
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
493
+
494
+ Notes
495
+ -----
496
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
497
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
498
+ Then shortcuts are created by replacing some edges as follows: for each
499
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
500
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
501
+ random choice of existing node $w$.
502
+ The entire process is repeated until a connected graph results.
503
+
504
+ See Also
505
+ --------
506
+ newman_watts_strogatz_graph
507
+ watts_strogatz_graph
508
+
509
+ References
510
+ ----------
511
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
512
+ Collective dynamics of small-world networks,
513
+ Nature, 393, pp. 440--442, 1998.
514
+ """
515
+ for i in range(tries):
516
+ # seed is an RNG so should change sequence each call
517
+ G = watts_strogatz_graph(n, k, p, seed, create_using=create_using)
518
+ if nx.is_connected(G):
519
+ return G
520
+ raise nx.NetworkXError("Maximum number of tries exceeded")
521
+
522
+
523
+ @py_random_state(2)
524
+ @nx._dispatchable(graphs=None, returns_graph=True)
525
+ def random_regular_graph(d, n, seed=None, *, create_using=None):
526
+ r"""Returns a random $d$-regular graph on $n$ nodes.
527
+
528
+ A regular graph is a graph where each node has the same number of neighbors.
529
+
530
+ The resulting graph has no self-loops or parallel edges.
531
+
532
+ Parameters
533
+ ----------
534
+ d : int
535
+ The degree of each node.
536
+ n : integer
537
+ The number of nodes. The value of $n \times d$ must be even.
538
+ seed : integer, random_state, or None (default)
539
+ Indicator of random number generation state.
540
+ See :ref:`Randomness<randomness>`.
541
+ create_using : Graph constructor, optional (default=nx.Graph)
542
+ Graph type to create. If graph instance, then cleared before populated.
543
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
544
+
545
+ Notes
546
+ -----
547
+ The nodes are numbered from $0$ to $n - 1$.
548
+
549
+ Kim and Vu's paper [2]_ shows that this algorithm samples in an
550
+ asymptotically uniform way from the space of random graphs when
551
+ $d = O(n^{1 / 3 - \epsilon})$.
552
+
553
+ Raises
554
+ ------
555
+
556
+ NetworkXError
557
+ If $n \times d$ is odd or $d$ is greater than or equal to $n$.
558
+
559
+ References
560
+ ----------
561
+ .. [1] A. Steger and N. Wormald,
562
+ Generating random regular graphs quickly,
563
+ Probability and Computing 8 (1999), 377-396, 1999.
564
+ https://doi.org/10.1017/S0963548399003867
565
+
566
+ .. [2] Jeong Han Kim and Van H. Vu,
567
+ Generating random regular graphs,
568
+ Proceedings of the thirty-fifth ACM symposium on Theory of computing,
569
+ San Diego, CA, USA, pp 213--222, 2003.
570
+ http://portal.acm.org/citation.cfm?id=780542.780576
571
+ """
572
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
573
+ if (n * d) % 2 != 0:
574
+ raise nx.NetworkXError("n * d must be even")
575
+
576
+ if not 0 <= d < n:
577
+ raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
578
+
579
+ G = nx.empty_graph(n, create_using=create_using)
580
+
581
+ if d == 0:
582
+ return G
583
+
584
+ def _suitable(edges, potential_edges):
585
+ # Helper subroutine to check if there are suitable edges remaining
586
+ # If False, the generation of the graph has failed
587
+ if not potential_edges:
588
+ return True
589
+ for s1 in potential_edges:
590
+ for s2 in potential_edges:
591
+ # Two iterators on the same dictionary are guaranteed
592
+ # to visit it in the same order if there are no
593
+ # intervening modifications.
594
+ if s1 == s2:
595
+ # Only need to consider s1-s2 pair one time
596
+ break
597
+ if s1 > s2:
598
+ s1, s2 = s2, s1
599
+ if (s1, s2) not in edges:
600
+ return True
601
+ return False
602
+
603
+ def _try_creation():
604
+ # Attempt to create an edge set
605
+
606
+ edges = set()
607
+ stubs = list(range(n)) * d
608
+
609
+ while stubs:
610
+ potential_edges = defaultdict(lambda: 0)
611
+ seed.shuffle(stubs)
612
+ stubiter = iter(stubs)
613
+ for s1, s2 in zip(stubiter, stubiter):
614
+ if s1 > s2:
615
+ s1, s2 = s2, s1
616
+ if s1 != s2 and ((s1, s2) not in edges):
617
+ edges.add((s1, s2))
618
+ else:
619
+ potential_edges[s1] += 1
620
+ potential_edges[s2] += 1
621
+
622
+ if not _suitable(edges, potential_edges):
623
+ return None # failed to find suitable edge set
624
+
625
+ stubs = [
626
+ node
627
+ for node, potential in potential_edges.items()
628
+ for _ in range(potential)
629
+ ]
630
+ return edges
631
+
632
+ # Even though a suitable edge set exists,
633
+ # the generation of such a set is not guaranteed.
634
+ # Try repeatedly to find one.
635
+ edges = _try_creation()
636
+ while edges is None:
637
+ edges = _try_creation()
638
+ G.add_edges_from(edges)
639
+
640
+ return G
641
+
642
+
643
+ def _random_subset(seq, m, rng):
644
+ """Return m unique elements from seq.
645
+
646
+ This differs from random.sample which can return repeated
647
+ elements if seq holds repeated elements.
648
+
649
+ Note: rng is a random.Random or numpy.random.RandomState instance.
650
+ """
651
+ targets = set()
652
+ while len(targets) < m:
653
+ x = rng.choice(seq)
654
+ targets.add(x)
655
+ return targets
656
+
657
+
658
+ @py_random_state(2)
659
+ @nx._dispatchable(graphs=None, returns_graph=True)
660
+ def barabasi_albert_graph(n, m, seed=None, initial_graph=None, *, create_using=None):
661
+ """Returns a random graph using Barabási–Albert preferential attachment
662
+
663
+ A graph of $n$ nodes is grown by attaching new nodes each with $m$
664
+ edges that are preferentially attached to existing nodes with high degree.
665
+
666
+ Parameters
667
+ ----------
668
+ n : int
669
+ Number of nodes
670
+ m : int
671
+ Number of edges to attach from a new node to existing nodes
672
+ seed : integer, random_state, or None (default)
673
+ Indicator of random number generation state.
674
+ See :ref:`Randomness<randomness>`.
675
+ initial_graph : Graph or None (default)
676
+ Initial network for Barabási–Albert algorithm.
677
+ It should be a connected graph for most use cases.
678
+ A copy of `initial_graph` is used.
679
+ If None, starts from a star graph on (m+1) nodes.
680
+ create_using : Graph constructor, optional (default=nx.Graph)
681
+ Graph type to create. If graph instance, then cleared before populated.
682
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
683
+
684
+ Returns
685
+ -------
686
+ G : Graph
687
+
688
+ Raises
689
+ ------
690
+ NetworkXError
691
+ If `m` does not satisfy ``1 <= m < n``, or
692
+ the initial graph number of nodes m0 does not satisfy ``m <= m0 <= n``.
693
+
694
+ References
695
+ ----------
696
+ .. [1] A. L. Barabási and R. Albert "Emergence of scaling in
697
+ random networks", Science 286, pp 509-512, 1999.
698
+ """
699
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
700
+ if m < 1 or m >= n:
701
+ raise nx.NetworkXError(
702
+ f"Barabási–Albert network must have m >= 1 and m < n, m = {m}, n = {n}"
703
+ )
704
+
705
+ if initial_graph is None:
706
+ # Default initial graph : star graph on (m + 1) nodes
707
+ G = star_graph(m, create_using)
708
+ else:
709
+ if len(initial_graph) < m or len(initial_graph) > n:
710
+ raise nx.NetworkXError(
711
+ f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
712
+ )
713
+ G = initial_graph.copy()
714
+
715
+ # List of existing nodes, with nodes repeated once for each adjacent edge
716
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
717
+ # Start adding the other n - m0 nodes.
718
+ source = len(G)
719
+ while source < n:
720
+ # Now choose m unique nodes from the existing nodes
721
+ # Pick uniformly from repeated_nodes (preferential attachment)
722
+ targets = _random_subset(repeated_nodes, m, seed)
723
+ # Add edges to m nodes from the source.
724
+ G.add_edges_from(zip([source] * m, targets))
725
+ # Add one node to the list for each new edge just created.
726
+ repeated_nodes.extend(targets)
727
+ # And the new node "source" has m edges to add to the list.
728
+ repeated_nodes.extend([source] * m)
729
+
730
+ source += 1
731
+ return G
732
+
733
+
734
+ @py_random_state(4)
735
+ @nx._dispatchable(graphs=None, returns_graph=True)
736
+ def dual_barabasi_albert_graph(
737
+ n, m1, m2, p, seed=None, initial_graph=None, *, create_using=None
738
+ ):
739
+ """Returns a random graph using dual Barabási–Albert preferential attachment
740
+
741
+ A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
742
+ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
743
+ are preferentially attached to existing nodes with high degree.
744
+
745
+ Parameters
746
+ ----------
747
+ n : int
748
+ Number of nodes
749
+ m1 : int
750
+ Number of edges to link each new node to existing nodes with probability $p$
751
+ m2 : int
752
+ Number of edges to link each new node to existing nodes with probability $1-p$
753
+ p : float
754
+ The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
755
+ seed : integer, random_state, or None (default)
756
+ Indicator of random number generation state.
757
+ See :ref:`Randomness<randomness>`.
758
+ initial_graph : Graph or None (default)
759
+ Initial network for Barabási–Albert algorithm.
760
+ A copy of `initial_graph` is used.
761
+ It should be connected for most use cases.
762
+ If None, starts from an star graph on max(m1, m2) + 1 nodes.
763
+ create_using : Graph constructor, optional (default=nx.Graph)
764
+ Graph type to create. If graph instance, then cleared before populated.
765
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
766
+
767
+ Returns
768
+ -------
769
+ G : Graph
770
+
771
+ Raises
772
+ ------
773
+ NetworkXError
774
+ If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
775
+ `p` does not satisfy ``0 <= p <= 1``, or
776
+ the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
777
+
778
+ References
779
+ ----------
780
+ .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
781
+ """
782
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
783
+ if m1 < 1 or m1 >= n:
784
+ raise nx.NetworkXError(
785
+ f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
786
+ )
787
+ if m2 < 1 or m2 >= n:
788
+ raise nx.NetworkXError(
789
+ f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
790
+ )
791
+ if p < 0 or p > 1:
792
+ raise nx.NetworkXError(
793
+ f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
794
+ )
795
+
796
+ # For simplicity, if p == 0 or 1, just return BA
797
+ if p == 1:
798
+ return barabasi_albert_graph(n, m1, seed, create_using=create_using)
799
+ elif p == 0:
800
+ return barabasi_albert_graph(n, m2, seed, create_using=create_using)
801
+
802
+ if initial_graph is None:
803
+ # Default initial graph : star graph on max(m1, m2) nodes
804
+ G = star_graph(max(m1, m2), create_using)
805
+ else:
806
+ if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
807
+ raise nx.NetworkXError(
808
+ f"Barabási–Albert initial graph must have between "
809
+ f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
810
+ )
811
+ G = initial_graph.copy()
812
+
813
+ # Target nodes for new edges
814
+ targets = list(G)
815
+ # List of existing nodes, with nodes repeated once for each adjacent edge
816
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
817
+ # Start adding the remaining nodes.
818
+ source = len(G)
819
+ while source < n:
820
+ # Pick which m to use (m1 or m2)
821
+ if seed.random() < p:
822
+ m = m1
823
+ else:
824
+ m = m2
825
+ # Now choose m unique nodes from the existing nodes
826
+ # Pick uniformly from repeated_nodes (preferential attachment)
827
+ targets = _random_subset(repeated_nodes, m, seed)
828
+ # Add edges to m nodes from the source.
829
+ G.add_edges_from(zip([source] * m, targets))
830
+ # Add one node to the list for each new edge just created.
831
+ repeated_nodes.extend(targets)
832
+ # And the new node "source" has m edges to add to the list.
833
+ repeated_nodes.extend([source] * m)
834
+
835
+ source += 1
836
+ return G
837
+
838
+
839
+ @py_random_state(4)
840
+ @nx._dispatchable(graphs=None, returns_graph=True)
841
+ def extended_barabasi_albert_graph(n, m, p, q, seed=None, *, create_using=None):
842
+ """Returns an extended Barabási–Albert model graph.
843
+
844
+ An extended Barabási–Albert model graph is a random graph constructed
845
+ using preferential attachment. The extended model allows new edges,
846
+ rewired edges or new nodes. Based on the probabilities $p$ and $q$
847
+ with $p + q < 1$, the growing behavior of the graph is determined as:
848
+
849
+ 1) With $p$ probability, $m$ new edges are added to the graph,
850
+ starting from randomly chosen existing nodes and attached preferentially at the
851
+ other end.
852
+
853
+ 2) With $q$ probability, $m$ existing edges are rewired
854
+ by randomly choosing an edge and rewiring one end to a preferentially chosen node.
855
+
856
+ 3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
857
+ with edges attached preferentially.
858
+
859
+ When $p = q = 0$, the model behaves just like the Barabási–Alber model.
860
+
861
+ Parameters
862
+ ----------
863
+ n : int
864
+ Number of nodes
865
+ m : int
866
+ Number of edges with which a new node attaches to existing nodes
867
+ p : float
868
+ Probability value for adding an edge between existing nodes. p + q < 1
869
+ q : float
870
+ Probability value of rewiring of existing edges. p + q < 1
871
+ seed : integer, random_state, or None (default)
872
+ Indicator of random number generation state.
873
+ See :ref:`Randomness<randomness>`.
874
+ create_using : Graph constructor, optional (default=nx.Graph)
875
+ Graph type to create. If graph instance, then cleared before populated.
876
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
877
+
878
+ Returns
879
+ -------
880
+ G : Graph
881
+
882
+ Raises
883
+ ------
884
+ NetworkXError
885
+ If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
886
+
887
+ References
888
+ ----------
889
+ .. [1] Albert, R., & Barabási, A. L. (2000)
890
+ Topology of evolving networks: local events and universality
891
+ Physical review letters, 85(24), 5234.
892
+ """
893
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
894
+ if m < 1 or m >= n:
895
+ msg = f"Extended Barabasi-Albert network needs m>=1 and m<n, m={m}, n={n}"
896
+ raise nx.NetworkXError(msg)
897
+ if p + q >= 1:
898
+ msg = f"Extended Barabasi-Albert network needs p + q <= 1, p={p}, q={q}"
899
+ raise nx.NetworkXError(msg)
900
+
901
+ # Add m initial nodes (m0 in barabasi-speak)
902
+ G = empty_graph(m, create_using)
903
+
904
+ # List of nodes to represent the preferential attachment random selection.
905
+ # At the creation of the graph, all nodes are added to the list
906
+ # so that even nodes that are not connected have a chance to get selected,
907
+ # for rewiring and adding of edges.
908
+ # With each new edge, nodes at the ends of the edge are added to the list.
909
+ attachment_preference = []
910
+ attachment_preference.extend(range(m))
911
+
912
+ # Start adding the other n-m nodes. The first node is m.
913
+ new_node = m
914
+ while new_node < n:
915
+ a_probability = seed.random()
916
+
917
+ # Total number of edges of a Clique of all the nodes
918
+ clique_degree = len(G) - 1
919
+ clique_size = (len(G) * clique_degree) / 2
920
+
921
+ # Adding m new edges, if there is room to add them
922
+ if a_probability < p and G.size() <= clique_size - m:
923
+ # Select the nodes where an edge can be added
924
+ eligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
925
+ for i in range(m):
926
+ # Choosing a random source node from eligible_nodes
927
+ src_node = seed.choice(eligible_nodes)
928
+
929
+ # Picking a possible node that is not 'src_node' or
930
+ # neighbor with 'src_node', with preferential attachment
931
+ prohibited_nodes = list(G[src_node])
932
+ prohibited_nodes.append(src_node)
933
+ # This will raise an exception if the sequence is empty
934
+ dest_node = seed.choice(
935
+ [nd for nd in attachment_preference if nd not in prohibited_nodes]
936
+ )
937
+ # Adding the new edge
938
+ G.add_edge(src_node, dest_node)
939
+
940
+ # Appending both nodes to add to their preferential attachment
941
+ attachment_preference.append(src_node)
942
+ attachment_preference.append(dest_node)
943
+
944
+ # Adjusting the eligible nodes. Degree may be saturated.
945
+ if G.degree(src_node) == clique_degree:
946
+ eligible_nodes.remove(src_node)
947
+ if G.degree(dest_node) == clique_degree and dest_node in eligible_nodes:
948
+ eligible_nodes.remove(dest_node)
949
+
950
+ # Rewiring m edges, if there are enough edges
951
+ elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
952
+ # Selecting nodes that have at least 1 edge but that are not
953
+ # fully connected to ALL other nodes (center of star).
954
+ # These nodes are the pivot nodes of the edges to rewire
955
+ eligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
956
+ for i in range(m):
957
+ # Choosing a random source node
958
+ node = seed.choice(eligible_nodes)
959
+
960
+ # The available nodes do have a neighbor at least.
961
+ nbr_nodes = list(G[node])
962
+
963
+ # Choosing the other end that will get detached
964
+ src_node = seed.choice(nbr_nodes)
965
+
966
+ # Picking a target node that is not 'node' or
967
+ # neighbor with 'node', with preferential attachment
968
+ nbr_nodes.append(node)
969
+ dest_node = seed.choice(
970
+ [nd for nd in attachment_preference if nd not in nbr_nodes]
971
+ )
972
+ # Rewire
973
+ G.remove_edge(node, src_node)
974
+ G.add_edge(node, dest_node)
975
+
976
+ # Adjusting the preferential attachment list
977
+ attachment_preference.remove(src_node)
978
+ attachment_preference.append(dest_node)
979
+
980
+ # Adjusting the eligible nodes.
981
+ # nodes may be saturated or isolated.
982
+ if G.degree(src_node) == 0 and src_node in eligible_nodes:
983
+ eligible_nodes.remove(src_node)
984
+ if dest_node in eligible_nodes:
985
+ if G.degree(dest_node) == clique_degree:
986
+ eligible_nodes.remove(dest_node)
987
+ else:
988
+ if G.degree(dest_node) == 1:
989
+ eligible_nodes.append(dest_node)
990
+
991
+ # Adding new node with m edges
992
+ else:
993
+ # Select the edges' nodes by preferential attachment
994
+ targets = _random_subset(attachment_preference, m, seed)
995
+ G.add_edges_from(zip([new_node] * m, targets))
996
+
997
+ # Add one node to the list for each new edge just created.
998
+ attachment_preference.extend(targets)
999
+ # The new node has m edges to it, plus itself: m + 1
1000
+ attachment_preference.extend([new_node] * (m + 1))
1001
+ new_node += 1
1002
+ return G
1003
+
1004
+
1005
+ @py_random_state(3)
1006
+ @nx._dispatchable(graphs=None, returns_graph=True)
1007
+ def powerlaw_cluster_graph(n, m, p, seed=None, *, create_using=None):
1008
+ """Holme and Kim algorithm for growing graphs with powerlaw
1009
+ degree distribution and approximate average clustering.
1010
+
1011
+ Parameters
1012
+ ----------
1013
+ n : int
1014
+ the number of nodes
1015
+ m : int
1016
+ the number of random edges to add for each new node
1017
+ p : float,
1018
+ Probability of adding a triangle after adding a random edge
1019
+ seed : integer, random_state, or None (default)
1020
+ Indicator of random number generation state.
1021
+ See :ref:`Randomness<randomness>`.
1022
+ create_using : Graph constructor, optional (default=nx.Graph)
1023
+ Graph type to create. If graph instance, then cleared before populated.
1024
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1025
+
1026
+ Notes
1027
+ -----
1028
+ The average clustering has a hard time getting above a certain
1029
+ cutoff that depends on `m`. This cutoff is often quite low. The
1030
+ transitivity (fraction of triangles to possible triangles) seems to
1031
+ decrease with network size.
1032
+
1033
+ It is essentially the Barabási–Albert (BA) growth model with an
1034
+ extra step that each random edge is followed by a chance of
1035
+ making an edge to one of its neighbors too (and thus a triangle).
1036
+
1037
+ This algorithm improves on BA in the sense that it enables a
1038
+ higher average clustering to be attained if desired.
1039
+
1040
+ It seems possible to have a disconnected graph with this algorithm
1041
+ since the initial `m` nodes may not be all linked to a new node
1042
+ on the first iteration like the BA model.
1043
+
1044
+ Raises
1045
+ ------
1046
+ NetworkXError
1047
+ If `m` does not satisfy ``1 <= m <= n`` or `p` does not
1048
+ satisfy ``0 <= p <= 1``.
1049
+
1050
+ References
1051
+ ----------
1052
+ .. [1] P. Holme and B. J. Kim,
1053
+ "Growing scale-free networks with tunable clustering",
1054
+ Phys. Rev. E, 65, 026107, 2002.
1055
+ """
1056
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1057
+ if m < 1 or n < m:
1058
+ raise nx.NetworkXError(f"NetworkXError must have m>1 and m<n, m={m},n={n}")
1059
+
1060
+ if p > 1 or p < 0:
1061
+ raise nx.NetworkXError(f"NetworkXError p must be in [0,1], p={p}")
1062
+
1063
+ G = empty_graph(m, create_using) # add m initial nodes (m0 in barabasi-speak)
1064
+ repeated_nodes = list(G) # list of existing nodes to sample from
1065
+ # with nodes repeated once for each adjacent edge
1066
+ source = m # next node is m
1067
+ while source < n: # Now add the other n-1 nodes
1068
+ possible_targets = _random_subset(repeated_nodes, m, seed)
1069
+ # do one preferential attachment for new node
1070
+ target = possible_targets.pop()
1071
+ G.add_edge(source, target)
1072
+ repeated_nodes.append(target) # add one node to list for each new link
1073
+ count = 1
1074
+ while count < m: # add m-1 more new links
1075
+ if seed.random() < p: # clustering step: add triangle
1076
+ neighborhood = [
1077
+ nbr
1078
+ for nbr in G.neighbors(target)
1079
+ if not G.has_edge(source, nbr) and nbr != source
1080
+ ]
1081
+ if neighborhood: # if there is a neighbor without a link
1082
+ nbr = seed.choice(neighborhood)
1083
+ G.add_edge(source, nbr) # add triangle
1084
+ repeated_nodes.append(nbr)
1085
+ count = count + 1
1086
+ continue # go to top of while loop
1087
+ # else do preferential attachment step if above fails
1088
+ target = possible_targets.pop()
1089
+ G.add_edge(source, target)
1090
+ repeated_nodes.append(target)
1091
+ count = count + 1
1092
+
1093
+ repeated_nodes.extend([source] * m) # add source node to list m times
1094
+ source += 1
1095
+ return G
1096
+
1097
+
1098
+ @py_random_state(3)
1099
+ @nx._dispatchable(graphs=None, returns_graph=True)
1100
+ def random_lobster(n, p1, p2, seed=None, *, create_using=None):
1101
+ """Returns a random lobster graph.
1102
+
1103
+ A lobster is a tree that reduces to a caterpillar when pruning all
1104
+ leaf nodes. A caterpillar is a tree that reduces to a path graph
1105
+ when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
1106
+
1107
+ This implementation iterates on the probabilities `p1` and `p2` to add
1108
+ edges at levels 1 and 2, respectively. Graphs are therefore constructed
1109
+ iteratively with uniform randomness at each level rather than being selected
1110
+ uniformly at random from the set of all possible lobsters.
1111
+
1112
+ Parameters
1113
+ ----------
1114
+ n : int
1115
+ The expected number of nodes in the backbone
1116
+ p1 : float
1117
+ Probability of adding an edge to the backbone
1118
+ p2 : float
1119
+ Probability of adding an edge one level beyond backbone
1120
+ seed : integer, random_state, or None (default)
1121
+ Indicator of random number generation state.
1122
+ See :ref:`Randomness<randomness>`.
1123
+ create_using : Graph constructor, optional (default=nx.Grap)
1124
+ Graph type to create. If graph instance, then cleared before populated.
1125
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1126
+
1127
+ Raises
1128
+ ------
1129
+ NetworkXError
1130
+ If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
1131
+ """
1132
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1133
+ p1, p2 = abs(p1), abs(p2)
1134
+ if any(p >= 1 for p in [p1, p2]):
1135
+ raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
1136
+
1137
+ # a necessary ingredient in any self-respecting graph library
1138
+ llen = int(2 * seed.random() * n + 0.5)
1139
+ L = path_graph(llen, create_using)
1140
+ # build caterpillar: add edges to path graph with probability p1
1141
+ current_node = llen - 1
1142
+ for n in range(llen):
1143
+ while seed.random() < p1: # add fuzzy caterpillar parts
1144
+ current_node += 1
1145
+ L.add_edge(n, current_node)
1146
+ cat_node = current_node
1147
+ while seed.random() < p2: # add crunchy lobster bits
1148
+ current_node += 1
1149
+ L.add_edge(cat_node, current_node)
1150
+ return L # voila, un lobster!
1151
+
1152
+
1153
+ @py_random_state(1)
1154
+ @nx._dispatchable(graphs=None, returns_graph=True)
1155
+ def random_shell_graph(constructor, seed=None, *, create_using=None):
1156
+ """Returns a random shell graph for the constructor given.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ constructor : list of three-tuples
1161
+ Represents the parameters for a shell, starting at the center
1162
+ shell. Each element of the list must be of the form `(n, m,
1163
+ d)`, where `n` is the number of nodes in the shell, `m` is
1164
+ the number of edges in the shell, and `d` is the ratio of
1165
+ inter-shell (next) edges to intra-shell edges. If `d` is zero,
1166
+ there will be no intra-shell edges, and if `d` is one there
1167
+ will be all possible intra-shell edges.
1168
+ seed : integer, random_state, or None (default)
1169
+ Indicator of random number generation state.
1170
+ See :ref:`Randomness<randomness>`.
1171
+ create_using : Graph constructor, optional (default=nx.Graph)
1172
+ Graph type to create. Graph instances are not supported.
1173
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1174
+
1175
+ Examples
1176
+ --------
1177
+ >>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
1178
+ >>> G = nx.random_shell_graph(constructor)
1179
+
1180
+ """
1181
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1182
+ G = empty_graph(0, create_using)
1183
+
1184
+ glist = []
1185
+ intra_edges = []
1186
+ nnodes = 0
1187
+ # create gnm graphs for each shell
1188
+ for n, m, d in constructor:
1189
+ inter_edges = int(m * d)
1190
+ intra_edges.append(m - inter_edges)
1191
+ g = nx.convert_node_labels_to_integers(
1192
+ gnm_random_graph(n, inter_edges, seed=seed, create_using=G.__class__),
1193
+ first_label=nnodes,
1194
+ )
1195
+ glist.append(g)
1196
+ nnodes += n
1197
+ G = nx.operators.union(G, g)
1198
+
1199
+ # connect the shells randomly
1200
+ for gi in range(len(glist) - 1):
1201
+ nlist1 = list(glist[gi])
1202
+ nlist2 = list(glist[gi + 1])
1203
+ total_edges = intra_edges[gi]
1204
+ edge_count = 0
1205
+ while edge_count < total_edges:
1206
+ u = seed.choice(nlist1)
1207
+ v = seed.choice(nlist2)
1208
+ if u == v or G.has_edge(u, v):
1209
+ continue
1210
+ else:
1211
+ G.add_edge(u, v)
1212
+ edge_count = edge_count + 1
1213
+ return G
1214
+
1215
+
1216
+ @py_random_state(2)
1217
+ @nx._dispatchable(graphs=None, returns_graph=True)
1218
+ def random_powerlaw_tree(n, gamma=3, seed=None, tries=100, *, create_using=None):
1219
+ """Returns a tree with a power law degree distribution.
1220
+
1221
+ Parameters
1222
+ ----------
1223
+ n : int
1224
+ The number of nodes.
1225
+ gamma : float
1226
+ Exponent of the power law.
1227
+ seed : integer, random_state, or None (default)
1228
+ Indicator of random number generation state.
1229
+ See :ref:`Randomness<randomness>`.
1230
+ tries : int
1231
+ Number of attempts to adjust the sequence to make it a tree.
1232
+ create_using : Graph constructor, optional (default=nx.Graph)
1233
+ Graph type to create. If graph instance, then cleared before populated.
1234
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1235
+
1236
+ Raises
1237
+ ------
1238
+ NetworkXError
1239
+ If no valid sequence is found within the maximum number of
1240
+ attempts.
1241
+
1242
+ Notes
1243
+ -----
1244
+ A trial power law degree sequence is chosen and then elements are
1245
+ swapped with new elements from a powerlaw distribution until the
1246
+ sequence makes a tree (by checking, for example, that the number of
1247
+ edges is one smaller than the number of nodes).
1248
+
1249
+ """
1250
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1251
+ # This call may raise a NetworkXError if the number of tries is succeeded.
1252
+ seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
1253
+ G = degree_sequence_tree(seq, create_using)
1254
+ return G
1255
+
1256
+
1257
+ @py_random_state(2)
1258
+ @nx._dispatchable(graphs=None)
1259
+ def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
1260
+ """Returns a degree sequence for a tree with a power law distribution.
1261
+
1262
+ Parameters
1263
+ ----------
1264
+ n : int,
1265
+ The number of nodes.
1266
+ gamma : float
1267
+ Exponent of the power law.
1268
+ seed : integer, random_state, or None (default)
1269
+ Indicator of random number generation state.
1270
+ See :ref:`Randomness<randomness>`.
1271
+ tries : int
1272
+ Number of attempts to adjust the sequence to make it a tree.
1273
+
1274
+ Raises
1275
+ ------
1276
+ NetworkXError
1277
+ If no valid sequence is found within the maximum number of
1278
+ attempts.
1279
+
1280
+ Notes
1281
+ -----
1282
+ A trial power law degree sequence is chosen and then elements are
1283
+ swapped with new elements from a power law distribution until
1284
+ the sequence makes a tree (by checking, for example, that the number of
1285
+ edges is one smaller than the number of nodes).
1286
+
1287
+ """
1288
+ # get trial sequence
1289
+ z = nx.utils.powerlaw_sequence(n, exponent=gamma, seed=seed)
1290
+ # round to integer values in the range [0,n]
1291
+ zseq = [min(n, max(round(s), 0)) for s in z]
1292
+
1293
+ # another sequence to swap values from
1294
+ z = nx.utils.powerlaw_sequence(tries, exponent=gamma, seed=seed)
1295
+ # round to integer values in the range [0,n]
1296
+ swap = [min(n, max(round(s), 0)) for s in z]
1297
+
1298
+ for deg in swap:
1299
+ # If this degree sequence can be the degree sequence of a tree, return
1300
+ # it. It can be a tree if the number of edges is one fewer than the
1301
+ # number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
1302
+ # use an equivalent condition below that avoids floating point
1303
+ # operations.
1304
+ if 2 * n - sum(zseq) == 2:
1305
+ return zseq
1306
+ index = seed.randint(0, n - 1)
1307
+ zseq[index] = swap.pop()
1308
+
1309
+ raise nx.NetworkXError(
1310
+ f"Exceeded max ({tries}) attempts for a valid tree sequence."
1311
+ )
1312
+
1313
+
1314
+ @py_random_state(3)
1315
+ @nx._dispatchable(graphs=None, returns_graph=True)
1316
+ def random_kernel_graph(
1317
+ n, kernel_integral, kernel_root=None, seed=None, *, create_using=None
1318
+ ):
1319
+ r"""Returns an random graph based on the specified kernel.
1320
+
1321
+ The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
1322
+ probability specified by a kernel $\kappa(x,y)$ [1]_. The kernel
1323
+ $\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
1324
+ bounded function.
1325
+
1326
+ Parameters
1327
+ ----------
1328
+ n : int
1329
+ The number of nodes
1330
+ kernel_integral : function
1331
+ Function that returns the definite integral of the kernel $\kappa(x,y)$,
1332
+ $F(y,a,b) := \int_a^b \kappa(x,y)dx$
1333
+ kernel_root: function (optional)
1334
+ Function that returns the root $b$ of the equation $F(y,a,b) = r$.
1335
+ If None, the root is found using :func:`scipy.optimize.brentq`
1336
+ (this requires SciPy).
1337
+ seed : integer, random_state, or None (default)
1338
+ Indicator of random number generation state.
1339
+ See :ref:`Randomness<randomness>`.
1340
+ create_using : Graph constructor, optional (default=nx.Graph)
1341
+ Graph type to create. If graph instance, then cleared before populated.
1342
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1343
+
1344
+ Notes
1345
+ -----
1346
+ The kernel is specified through its definite integral which must be
1347
+ provided as one of the arguments. If the integral and root of the
1348
+ kernel integral can be found in $O(1)$ time then this algorithm runs in
1349
+ time $O(n+m)$ where m is the expected number of edges [2]_.
1350
+
1351
+ The nodes are set to integers from $0$ to $n-1$.
1352
+
1353
+ Examples
1354
+ --------
1355
+ Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
1356
+ $\kappa(x,y)=c$ where $c$ is the mean expected degree.
1357
+
1358
+ >>> def integral(u, w, z):
1359
+ ... return c * (z - w)
1360
+ >>> def root(u, w, r):
1361
+ ... return r / c + w
1362
+ >>> c = 1
1363
+ >>> graph = nx.random_kernel_graph(1000, integral, root)
1364
+
1365
+ See Also
1366
+ --------
1367
+ gnp_random_graph
1368
+ expected_degree_graph
1369
+
1370
+ References
1371
+ ----------
1372
+ .. [1] Bollobás, Béla, Janson, S. and Riordan, O.
1373
+ "The phase transition in inhomogeneous random graphs",
1374
+ *Random Structures Algorithms*, 31, 3--122, 2007.
1375
+
1376
+ .. [2] Hagberg A, Lemons N (2015),
1377
+ "Fast Generation of Sparse Random Kernel Graphs".
1378
+ PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
1379
+ """
1380
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1381
+ if kernel_root is None:
1382
+ import scipy as sp
1383
+
1384
+ def kernel_root(y, a, r):
1385
+ def my_function(b):
1386
+ return kernel_integral(y, a, b) - r
1387
+
1388
+ return sp.optimize.brentq(my_function, a, 1)
1389
+
1390
+ graph = nx.empty_graph(create_using=create_using)
1391
+ graph.add_nodes_from(range(n))
1392
+ (i, j) = (1, 1)
1393
+ while i < n:
1394
+ r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
1395
+ if kernel_integral(i / n, j / n, 1) <= r:
1396
+ i, j = i + 1, i + 1
1397
+ else:
1398
+ j = math.ceil(n * kernel_root(i / n, j / n, r))
1399
+ graph.add_edge(i - 1, j - 1)
1400
+ return graph
janus/lib/python3.10/site-packages/networkx/generators/social.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Famous social networks.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "karate_club_graph",
9
+ "davis_southern_women_graph",
10
+ "florentine_families_graph",
11
+ "les_miserables_graph",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(graphs=None, returns_graph=True)
16
+ def karate_club_graph():
17
+ """Returns Zachary's Karate Club graph.
18
+
19
+ Each node in the returned graph has a node attribute 'club' that
20
+ indicates the name of the club to which the member represented by that node
21
+ belongs, either 'Mr. Hi' or 'Officer'. Each edge has a weight based on the
22
+ number of contexts in which that edge's incident node members interacted.
23
+
24
+ The dataset is derived from the 'Club After Split From Data' column of Table 3 in [1]_.
25
+ This was in turn derived from the 'Club After Fission' column of Table 1 in the
26
+ same paper. Note that the nodes are 0-indexed in NetworkX, but 1-indexed in the
27
+ paper (the 'Individual Number in Matrix C' column of Table 3 starts at 1). This
28
+ means, for example, that ``G.nodes[9]["club"]`` returns 'Officer', which
29
+ corresponds to row 10 of Table 3 in the paper.
30
+
31
+ Examples
32
+ --------
33
+ To get the name of the club to which a node belongs::
34
+
35
+ >>> G = nx.karate_club_graph()
36
+ >>> G.nodes[5]["club"]
37
+ 'Mr. Hi'
38
+ >>> G.nodes[9]["club"]
39
+ 'Officer'
40
+
41
+ References
42
+ ----------
43
+ .. [1] Zachary, Wayne W.
44
+ "An Information Flow Model for Conflict and Fission in Small Groups."
45
+ *Journal of Anthropological Research*, 33, 452--473, (1977).
46
+ """
47
+ # Create the set of all members, and the members of each club.
48
+ all_members = set(range(34))
49
+ club1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21}
50
+ # club2 = all_members - club1
51
+
52
+ G = nx.Graph()
53
+ G.add_nodes_from(all_members)
54
+ G.name = "Zachary's Karate Club"
55
+
56
+ zacharydat = """\
57
+ 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
58
+ 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
59
+ 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
60
+ 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
61
+ 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
62
+ 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
63
+ 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
64
+ 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
65
+ 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
66
+ 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
67
+ 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
68
+ 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
69
+ 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
70
+ 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
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 3 2
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 0 0 0 0 0 0 0 3 4
73
+ 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
74
+ 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
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 0 0 0 1 2
76
+ 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
77
+ 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
78
+ 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
79
+ 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
80
+ 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
81
+ 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
82
+ 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
83
+ 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
84
+ 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
85
+ 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
86
+ 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
87
+ 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
88
+ 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
89
+ 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
90
+ 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"""
91
+
92
+ for row, line in enumerate(zacharydat.split("\n")):
93
+ thisrow = [int(b) for b in line.split()]
94
+ for col, entry in enumerate(thisrow):
95
+ if entry >= 1:
96
+ G.add_edge(row, col, weight=entry)
97
+
98
+ # Add the name of each member's club as a node attribute.
99
+ for v in G:
100
+ G.nodes[v]["club"] = "Mr. Hi" if v in club1 else "Officer"
101
+ return G
102
+
103
+
104
+ @nx._dispatchable(graphs=None, returns_graph=True)
105
+ def davis_southern_women_graph():
106
+ """Returns Davis Southern women social network.
107
+
108
+ This is a bipartite graph.
109
+
110
+ References
111
+ ----------
112
+ .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.
113
+ University of Chicago Press, Chicago, IL.
114
+ """
115
+ G = nx.Graph()
116
+ # Top nodes
117
+ women = [
118
+ "Evelyn Jefferson",
119
+ "Laura Mandeville",
120
+ "Theresa Anderson",
121
+ "Brenda Rogers",
122
+ "Charlotte McDowd",
123
+ "Frances Anderson",
124
+ "Eleanor Nye",
125
+ "Pearl Oglethorpe",
126
+ "Ruth DeSand",
127
+ "Verne Sanderson",
128
+ "Myra Liddel",
129
+ "Katherina Rogers",
130
+ "Sylvia Avondale",
131
+ "Nora Fayette",
132
+ "Helen Lloyd",
133
+ "Dorothy Murchison",
134
+ "Olivia Carleton",
135
+ "Flora Price",
136
+ ]
137
+ G.add_nodes_from(women, bipartite=0)
138
+ # Bottom nodes
139
+ events = [
140
+ "E1",
141
+ "E2",
142
+ "E3",
143
+ "E4",
144
+ "E5",
145
+ "E6",
146
+ "E7",
147
+ "E8",
148
+ "E9",
149
+ "E10",
150
+ "E11",
151
+ "E12",
152
+ "E13",
153
+ "E14",
154
+ ]
155
+ G.add_nodes_from(events, bipartite=1)
156
+
157
+ G.add_edges_from(
158
+ [
159
+ ("Evelyn Jefferson", "E1"),
160
+ ("Evelyn Jefferson", "E2"),
161
+ ("Evelyn Jefferson", "E3"),
162
+ ("Evelyn Jefferson", "E4"),
163
+ ("Evelyn Jefferson", "E5"),
164
+ ("Evelyn Jefferson", "E6"),
165
+ ("Evelyn Jefferson", "E8"),
166
+ ("Evelyn Jefferson", "E9"),
167
+ ("Laura Mandeville", "E1"),
168
+ ("Laura Mandeville", "E2"),
169
+ ("Laura Mandeville", "E3"),
170
+ ("Laura Mandeville", "E5"),
171
+ ("Laura Mandeville", "E6"),
172
+ ("Laura Mandeville", "E7"),
173
+ ("Laura Mandeville", "E8"),
174
+ ("Theresa Anderson", "E2"),
175
+ ("Theresa Anderson", "E3"),
176
+ ("Theresa Anderson", "E4"),
177
+ ("Theresa Anderson", "E5"),
178
+ ("Theresa Anderson", "E6"),
179
+ ("Theresa Anderson", "E7"),
180
+ ("Theresa Anderson", "E8"),
181
+ ("Theresa Anderson", "E9"),
182
+ ("Brenda Rogers", "E1"),
183
+ ("Brenda Rogers", "E3"),
184
+ ("Brenda Rogers", "E4"),
185
+ ("Brenda Rogers", "E5"),
186
+ ("Brenda Rogers", "E6"),
187
+ ("Brenda Rogers", "E7"),
188
+ ("Brenda Rogers", "E8"),
189
+ ("Charlotte McDowd", "E3"),
190
+ ("Charlotte McDowd", "E4"),
191
+ ("Charlotte McDowd", "E5"),
192
+ ("Charlotte McDowd", "E7"),
193
+ ("Frances Anderson", "E3"),
194
+ ("Frances Anderson", "E5"),
195
+ ("Frances Anderson", "E6"),
196
+ ("Frances Anderson", "E8"),
197
+ ("Eleanor Nye", "E5"),
198
+ ("Eleanor Nye", "E6"),
199
+ ("Eleanor Nye", "E7"),
200
+ ("Eleanor Nye", "E8"),
201
+ ("Pearl Oglethorpe", "E6"),
202
+ ("Pearl Oglethorpe", "E8"),
203
+ ("Pearl Oglethorpe", "E9"),
204
+ ("Ruth DeSand", "E5"),
205
+ ("Ruth DeSand", "E7"),
206
+ ("Ruth DeSand", "E8"),
207
+ ("Ruth DeSand", "E9"),
208
+ ("Verne Sanderson", "E7"),
209
+ ("Verne Sanderson", "E8"),
210
+ ("Verne Sanderson", "E9"),
211
+ ("Verne Sanderson", "E12"),
212
+ ("Myra Liddel", "E8"),
213
+ ("Myra Liddel", "E9"),
214
+ ("Myra Liddel", "E10"),
215
+ ("Myra Liddel", "E12"),
216
+ ("Katherina Rogers", "E8"),
217
+ ("Katherina Rogers", "E9"),
218
+ ("Katherina Rogers", "E10"),
219
+ ("Katherina Rogers", "E12"),
220
+ ("Katherina Rogers", "E13"),
221
+ ("Katherina Rogers", "E14"),
222
+ ("Sylvia Avondale", "E7"),
223
+ ("Sylvia Avondale", "E8"),
224
+ ("Sylvia Avondale", "E9"),
225
+ ("Sylvia Avondale", "E10"),
226
+ ("Sylvia Avondale", "E12"),
227
+ ("Sylvia Avondale", "E13"),
228
+ ("Sylvia Avondale", "E14"),
229
+ ("Nora Fayette", "E6"),
230
+ ("Nora Fayette", "E7"),
231
+ ("Nora Fayette", "E9"),
232
+ ("Nora Fayette", "E10"),
233
+ ("Nora Fayette", "E11"),
234
+ ("Nora Fayette", "E12"),
235
+ ("Nora Fayette", "E13"),
236
+ ("Nora Fayette", "E14"),
237
+ ("Helen Lloyd", "E7"),
238
+ ("Helen Lloyd", "E8"),
239
+ ("Helen Lloyd", "E10"),
240
+ ("Helen Lloyd", "E11"),
241
+ ("Helen Lloyd", "E12"),
242
+ ("Dorothy Murchison", "E8"),
243
+ ("Dorothy Murchison", "E9"),
244
+ ("Olivia Carleton", "E9"),
245
+ ("Olivia Carleton", "E11"),
246
+ ("Flora Price", "E9"),
247
+ ("Flora Price", "E11"),
248
+ ]
249
+ )
250
+ G.graph["top"] = women
251
+ G.graph["bottom"] = events
252
+ return G
253
+
254
+
255
+ @nx._dispatchable(graphs=None, returns_graph=True)
256
+ def florentine_families_graph():
257
+ """Returns Florentine families graph.
258
+
259
+ References
260
+ ----------
261
+ .. [1] Ronald L. Breiger and Philippa E. Pattison
262
+ Cumulated social roles: The duality of persons and their algebras,1
263
+ Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
264
+ """
265
+ G = nx.Graph()
266
+ G.add_edge("Acciaiuoli", "Medici")
267
+ G.add_edge("Castellani", "Peruzzi")
268
+ G.add_edge("Castellani", "Strozzi")
269
+ G.add_edge("Castellani", "Barbadori")
270
+ G.add_edge("Medici", "Barbadori")
271
+ G.add_edge("Medici", "Ridolfi")
272
+ G.add_edge("Medici", "Tornabuoni")
273
+ G.add_edge("Medici", "Albizzi")
274
+ G.add_edge("Medici", "Salviati")
275
+ G.add_edge("Salviati", "Pazzi")
276
+ G.add_edge("Peruzzi", "Strozzi")
277
+ G.add_edge("Peruzzi", "Bischeri")
278
+ G.add_edge("Strozzi", "Ridolfi")
279
+ G.add_edge("Strozzi", "Bischeri")
280
+ G.add_edge("Ridolfi", "Tornabuoni")
281
+ G.add_edge("Tornabuoni", "Guadagni")
282
+ G.add_edge("Albizzi", "Ginori")
283
+ G.add_edge("Albizzi", "Guadagni")
284
+ G.add_edge("Bischeri", "Guadagni")
285
+ G.add_edge("Guadagni", "Lamberteschi")
286
+ return G
287
+
288
+
289
+ @nx._dispatchable(graphs=None, returns_graph=True)
290
+ def les_miserables_graph():
291
+ """Returns coappearance network of characters in the novel Les Miserables.
292
+
293
+ References
294
+ ----------
295
+ .. [1] D. E. Knuth, 1993.
296
+ The Stanford GraphBase: a platform for combinatorial computing,
297
+ pp. 74-87. New York: AcM Press.
298
+ """
299
+ G = nx.Graph()
300
+ G.add_edge("Napoleon", "Myriel", weight=1)
301
+ G.add_edge("MlleBaptistine", "Myriel", weight=8)
302
+ G.add_edge("MmeMagloire", "Myriel", weight=10)
303
+ G.add_edge("MmeMagloire", "MlleBaptistine", weight=6)
304
+ G.add_edge("CountessDeLo", "Myriel", weight=1)
305
+ G.add_edge("Geborand", "Myriel", weight=1)
306
+ G.add_edge("Champtercier", "Myriel", weight=1)
307
+ G.add_edge("Cravatte", "Myriel", weight=1)
308
+ G.add_edge("Count", "Myriel", weight=2)
309
+ G.add_edge("OldMan", "Myriel", weight=1)
310
+ G.add_edge("Valjean", "Labarre", weight=1)
311
+ G.add_edge("Valjean", "MmeMagloire", weight=3)
312
+ G.add_edge("Valjean", "MlleBaptistine", weight=3)
313
+ G.add_edge("Valjean", "Myriel", weight=5)
314
+ G.add_edge("Marguerite", "Valjean", weight=1)
315
+ G.add_edge("MmeDeR", "Valjean", weight=1)
316
+ G.add_edge("Isabeau", "Valjean", weight=1)
317
+ G.add_edge("Gervais", "Valjean", weight=1)
318
+ G.add_edge("Listolier", "Tholomyes", weight=4)
319
+ G.add_edge("Fameuil", "Tholomyes", weight=4)
320
+ G.add_edge("Fameuil", "Listolier", weight=4)
321
+ G.add_edge("Blacheville", "Tholomyes", weight=4)
322
+ G.add_edge("Blacheville", "Listolier", weight=4)
323
+ G.add_edge("Blacheville", "Fameuil", weight=4)
324
+ G.add_edge("Favourite", "Tholomyes", weight=3)
325
+ G.add_edge("Favourite", "Listolier", weight=3)
326
+ G.add_edge("Favourite", "Fameuil", weight=3)
327
+ G.add_edge("Favourite", "Blacheville", weight=4)
328
+ G.add_edge("Dahlia", "Tholomyes", weight=3)
329
+ G.add_edge("Dahlia", "Listolier", weight=3)
330
+ G.add_edge("Dahlia", "Fameuil", weight=3)
331
+ G.add_edge("Dahlia", "Blacheville", weight=3)
332
+ G.add_edge("Dahlia", "Favourite", weight=5)
333
+ G.add_edge("Zephine", "Tholomyes", weight=3)
334
+ G.add_edge("Zephine", "Listolier", weight=3)
335
+ G.add_edge("Zephine", "Fameuil", weight=3)
336
+ G.add_edge("Zephine", "Blacheville", weight=3)
337
+ G.add_edge("Zephine", "Favourite", weight=4)
338
+ G.add_edge("Zephine", "Dahlia", weight=4)
339
+ G.add_edge("Fantine", "Tholomyes", weight=3)
340
+ G.add_edge("Fantine", "Listolier", weight=3)
341
+ G.add_edge("Fantine", "Fameuil", weight=3)
342
+ G.add_edge("Fantine", "Blacheville", weight=3)
343
+ G.add_edge("Fantine", "Favourite", weight=4)
344
+ G.add_edge("Fantine", "Dahlia", weight=4)
345
+ G.add_edge("Fantine", "Zephine", weight=4)
346
+ G.add_edge("Fantine", "Marguerite", weight=2)
347
+ G.add_edge("Fantine", "Valjean", weight=9)
348
+ G.add_edge("MmeThenardier", "Fantine", weight=2)
349
+ G.add_edge("MmeThenardier", "Valjean", weight=7)
350
+ G.add_edge("Thenardier", "MmeThenardier", weight=13)
351
+ G.add_edge("Thenardier", "Fantine", weight=1)
352
+ G.add_edge("Thenardier", "Valjean", weight=12)
353
+ G.add_edge("Cosette", "MmeThenardier", weight=4)
354
+ G.add_edge("Cosette", "Valjean", weight=31)
355
+ G.add_edge("Cosette", "Tholomyes", weight=1)
356
+ G.add_edge("Cosette", "Thenardier", weight=1)
357
+ G.add_edge("Javert", "Valjean", weight=17)
358
+ G.add_edge("Javert", "Fantine", weight=5)
359
+ G.add_edge("Javert", "Thenardier", weight=5)
360
+ G.add_edge("Javert", "MmeThenardier", weight=1)
361
+ G.add_edge("Javert", "Cosette", weight=1)
362
+ G.add_edge("Fauchelevent", "Valjean", weight=8)
363
+ G.add_edge("Fauchelevent", "Javert", weight=1)
364
+ G.add_edge("Bamatabois", "Fantine", weight=1)
365
+ G.add_edge("Bamatabois", "Javert", weight=1)
366
+ G.add_edge("Bamatabois", "Valjean", weight=2)
367
+ G.add_edge("Perpetue", "Fantine", weight=1)
368
+ G.add_edge("Simplice", "Perpetue", weight=2)
369
+ G.add_edge("Simplice", "Valjean", weight=3)
370
+ G.add_edge("Simplice", "Fantine", weight=2)
371
+ G.add_edge("Simplice", "Javert", weight=1)
372
+ G.add_edge("Scaufflaire", "Valjean", weight=1)
373
+ G.add_edge("Woman1", "Valjean", weight=2)
374
+ G.add_edge("Woman1", "Javert", weight=1)
375
+ G.add_edge("Judge", "Valjean", weight=3)
376
+ G.add_edge("Judge", "Bamatabois", weight=2)
377
+ G.add_edge("Champmathieu", "Valjean", weight=3)
378
+ G.add_edge("Champmathieu", "Judge", weight=3)
379
+ G.add_edge("Champmathieu", "Bamatabois", weight=2)
380
+ G.add_edge("Brevet", "Judge", weight=2)
381
+ G.add_edge("Brevet", "Champmathieu", weight=2)
382
+ G.add_edge("Brevet", "Valjean", weight=2)
383
+ G.add_edge("Brevet", "Bamatabois", weight=1)
384
+ G.add_edge("Chenildieu", "Judge", weight=2)
385
+ G.add_edge("Chenildieu", "Champmathieu", weight=2)
386
+ G.add_edge("Chenildieu", "Brevet", weight=2)
387
+ G.add_edge("Chenildieu", "Valjean", weight=2)
388
+ G.add_edge("Chenildieu", "Bamatabois", weight=1)
389
+ G.add_edge("Cochepaille", "Judge", weight=2)
390
+ G.add_edge("Cochepaille", "Champmathieu", weight=2)
391
+ G.add_edge("Cochepaille", "Brevet", weight=2)
392
+ G.add_edge("Cochepaille", "Chenildieu", weight=2)
393
+ G.add_edge("Cochepaille", "Valjean", weight=2)
394
+ G.add_edge("Cochepaille", "Bamatabois", weight=1)
395
+ G.add_edge("Pontmercy", "Thenardier", weight=1)
396
+ G.add_edge("Boulatruelle", "Thenardier", weight=1)
397
+ G.add_edge("Eponine", "MmeThenardier", weight=2)
398
+ G.add_edge("Eponine", "Thenardier", weight=3)
399
+ G.add_edge("Anzelma", "Eponine", weight=2)
400
+ G.add_edge("Anzelma", "Thenardier", weight=2)
401
+ G.add_edge("Anzelma", "MmeThenardier", weight=1)
402
+ G.add_edge("Woman2", "Valjean", weight=3)
403
+ G.add_edge("Woman2", "Cosette", weight=1)
404
+ G.add_edge("Woman2", "Javert", weight=1)
405
+ G.add_edge("MotherInnocent", "Fauchelevent", weight=3)
406
+ G.add_edge("MotherInnocent", "Valjean", weight=1)
407
+ G.add_edge("Gribier", "Fauchelevent", weight=2)
408
+ G.add_edge("MmeBurgon", "Jondrette", weight=1)
409
+ G.add_edge("Gavroche", "MmeBurgon", weight=2)
410
+ G.add_edge("Gavroche", "Thenardier", weight=1)
411
+ G.add_edge("Gavroche", "Javert", weight=1)
412
+ G.add_edge("Gavroche", "Valjean", weight=1)
413
+ G.add_edge("Gillenormand", "Cosette", weight=3)
414
+ G.add_edge("Gillenormand", "Valjean", weight=2)
415
+ G.add_edge("Magnon", "Gillenormand", weight=1)
416
+ G.add_edge("Magnon", "MmeThenardier", weight=1)
417
+ G.add_edge("MlleGillenormand", "Gillenormand", weight=9)
418
+ G.add_edge("MlleGillenormand", "Cosette", weight=2)
419
+ G.add_edge("MlleGillenormand", "Valjean", weight=2)
420
+ G.add_edge("MmePontmercy", "MlleGillenormand", weight=1)
421
+ G.add_edge("MmePontmercy", "Pontmercy", weight=1)
422
+ G.add_edge("MlleVaubois", "MlleGillenormand", weight=1)
423
+ G.add_edge("LtGillenormand", "MlleGillenormand", weight=2)
424
+ G.add_edge("LtGillenormand", "Gillenormand", weight=1)
425
+ G.add_edge("LtGillenormand", "Cosette", weight=1)
426
+ G.add_edge("Marius", "MlleGillenormand", weight=6)
427
+ G.add_edge("Marius", "Gillenormand", weight=12)
428
+ G.add_edge("Marius", "Pontmercy", weight=1)
429
+ G.add_edge("Marius", "LtGillenormand", weight=1)
430
+ G.add_edge("Marius", "Cosette", weight=21)
431
+ G.add_edge("Marius", "Valjean", weight=19)
432
+ G.add_edge("Marius", "Tholomyes", weight=1)
433
+ G.add_edge("Marius", "Thenardier", weight=2)
434
+ G.add_edge("Marius", "Eponine", weight=5)
435
+ G.add_edge("Marius", "Gavroche", weight=4)
436
+ G.add_edge("BaronessT", "Gillenormand", weight=1)
437
+ G.add_edge("BaronessT", "Marius", weight=1)
438
+ G.add_edge("Mabeuf", "Marius", weight=1)
439
+ G.add_edge("Mabeuf", "Eponine", weight=1)
440
+ G.add_edge("Mabeuf", "Gavroche", weight=1)
441
+ G.add_edge("Enjolras", "Marius", weight=7)
442
+ G.add_edge("Enjolras", "Gavroche", weight=7)
443
+ G.add_edge("Enjolras", "Javert", weight=6)
444
+ G.add_edge("Enjolras", "Mabeuf", weight=1)
445
+ G.add_edge("Enjolras", "Valjean", weight=4)
446
+ G.add_edge("Combeferre", "Enjolras", weight=15)
447
+ G.add_edge("Combeferre", "Marius", weight=5)
448
+ G.add_edge("Combeferre", "Gavroche", weight=6)
449
+ G.add_edge("Combeferre", "Mabeuf", weight=2)
450
+ G.add_edge("Prouvaire", "Gavroche", weight=1)
451
+ G.add_edge("Prouvaire", "Enjolras", weight=4)
452
+ G.add_edge("Prouvaire", "Combeferre", weight=2)
453
+ G.add_edge("Feuilly", "Gavroche", weight=2)
454
+ G.add_edge("Feuilly", "Enjolras", weight=6)
455
+ G.add_edge("Feuilly", "Prouvaire", weight=2)
456
+ G.add_edge("Feuilly", "Combeferre", weight=5)
457
+ G.add_edge("Feuilly", "Mabeuf", weight=1)
458
+ G.add_edge("Feuilly", "Marius", weight=1)
459
+ G.add_edge("Courfeyrac", "Marius", weight=9)
460
+ G.add_edge("Courfeyrac", "Enjolras", weight=17)
461
+ G.add_edge("Courfeyrac", "Combeferre", weight=13)
462
+ G.add_edge("Courfeyrac", "Gavroche", weight=7)
463
+ G.add_edge("Courfeyrac", "Mabeuf", weight=2)
464
+ G.add_edge("Courfeyrac", "Eponine", weight=1)
465
+ G.add_edge("Courfeyrac", "Feuilly", weight=6)
466
+ G.add_edge("Courfeyrac", "Prouvaire", weight=3)
467
+ G.add_edge("Bahorel", "Combeferre", weight=5)
468
+ G.add_edge("Bahorel", "Gavroche", weight=5)
469
+ G.add_edge("Bahorel", "Courfeyrac", weight=6)
470
+ G.add_edge("Bahorel", "Mabeuf", weight=2)
471
+ G.add_edge("Bahorel", "Enjolras", weight=4)
472
+ G.add_edge("Bahorel", "Feuilly", weight=3)
473
+ G.add_edge("Bahorel", "Prouvaire", weight=2)
474
+ G.add_edge("Bahorel", "Marius", weight=1)
475
+ G.add_edge("Bossuet", "Marius", weight=5)
476
+ G.add_edge("Bossuet", "Courfeyrac", weight=12)
477
+ G.add_edge("Bossuet", "Gavroche", weight=5)
478
+ G.add_edge("Bossuet", "Bahorel", weight=4)
479
+ G.add_edge("Bossuet", "Enjolras", weight=10)
480
+ G.add_edge("Bossuet", "Feuilly", weight=6)
481
+ G.add_edge("Bossuet", "Prouvaire", weight=2)
482
+ G.add_edge("Bossuet", "Combeferre", weight=9)
483
+ G.add_edge("Bossuet", "Mabeuf", weight=1)
484
+ G.add_edge("Bossuet", "Valjean", weight=1)
485
+ G.add_edge("Joly", "Bahorel", weight=5)
486
+ G.add_edge("Joly", "Bossuet", weight=7)
487
+ G.add_edge("Joly", "Gavroche", weight=3)
488
+ G.add_edge("Joly", "Courfeyrac", weight=5)
489
+ G.add_edge("Joly", "Enjolras", weight=5)
490
+ G.add_edge("Joly", "Feuilly", weight=5)
491
+ G.add_edge("Joly", "Prouvaire", weight=2)
492
+ G.add_edge("Joly", "Combeferre", weight=5)
493
+ G.add_edge("Joly", "Mabeuf", weight=1)
494
+ G.add_edge("Joly", "Marius", weight=2)
495
+ G.add_edge("Grantaire", "Bossuet", weight=3)
496
+ G.add_edge("Grantaire", "Enjolras", weight=3)
497
+ G.add_edge("Grantaire", "Combeferre", weight=1)
498
+ G.add_edge("Grantaire", "Courfeyrac", weight=2)
499
+ G.add_edge("Grantaire", "Joly", weight=2)
500
+ G.add_edge("Grantaire", "Gavroche", weight=1)
501
+ G.add_edge("Grantaire", "Bahorel", weight=1)
502
+ G.add_edge("Grantaire", "Feuilly", weight=1)
503
+ G.add_edge("Grantaire", "Prouvaire", weight=1)
504
+ G.add_edge("MotherPlutarch", "Mabeuf", weight=3)
505
+ G.add_edge("Gueulemer", "Thenardier", weight=5)
506
+ G.add_edge("Gueulemer", "Valjean", weight=1)
507
+ G.add_edge("Gueulemer", "MmeThenardier", weight=1)
508
+ G.add_edge("Gueulemer", "Javert", weight=1)
509
+ G.add_edge("Gueulemer", "Gavroche", weight=1)
510
+ G.add_edge("Gueulemer", "Eponine", weight=1)
511
+ G.add_edge("Babet", "Thenardier", weight=6)
512
+ G.add_edge("Babet", "Gueulemer", weight=6)
513
+ G.add_edge("Babet", "Valjean", weight=1)
514
+ G.add_edge("Babet", "MmeThenardier", weight=1)
515
+ G.add_edge("Babet", "Javert", weight=2)
516
+ G.add_edge("Babet", "Gavroche", weight=1)
517
+ G.add_edge("Babet", "Eponine", weight=1)
518
+ G.add_edge("Claquesous", "Thenardier", weight=4)
519
+ G.add_edge("Claquesous", "Babet", weight=4)
520
+ G.add_edge("Claquesous", "Gueulemer", weight=4)
521
+ G.add_edge("Claquesous", "Valjean", weight=1)
522
+ G.add_edge("Claquesous", "MmeThenardier", weight=1)
523
+ G.add_edge("Claquesous", "Javert", weight=1)
524
+ G.add_edge("Claquesous", "Eponine", weight=1)
525
+ G.add_edge("Claquesous", "Enjolras", weight=1)
526
+ G.add_edge("Montparnasse", "Javert", weight=1)
527
+ G.add_edge("Montparnasse", "Babet", weight=2)
528
+ G.add_edge("Montparnasse", "Gueulemer", weight=2)
529
+ G.add_edge("Montparnasse", "Claquesous", weight=2)
530
+ G.add_edge("Montparnasse", "Valjean", weight=1)
531
+ G.add_edge("Montparnasse", "Gavroche", weight=1)
532
+ G.add_edge("Montparnasse", "Eponine", weight=1)
533
+ G.add_edge("Montparnasse", "Thenardier", weight=1)
534
+ G.add_edge("Toussaint", "Cosette", weight=2)
535
+ G.add_edge("Toussaint", "Javert", weight=1)
536
+ G.add_edge("Toussaint", "Valjean", weight=1)
537
+ G.add_edge("Child1", "Gavroche", weight=2)
538
+ G.add_edge("Child2", "Gavroche", weight=2)
539
+ G.add_edge("Child2", "Child1", weight=3)
540
+ G.add_edge("Brujon", "Babet", weight=3)
541
+ G.add_edge("Brujon", "Gueulemer", weight=3)
542
+ G.add_edge("Brujon", "Thenardier", weight=3)
543
+ G.add_edge("Brujon", "Gavroche", weight=1)
544
+ G.add_edge("Brujon", "Eponine", weight=1)
545
+ G.add_edge("Brujon", "Claquesous", weight=1)
546
+ G.add_edge("Brujon", "Montparnasse", weight=1)
547
+ G.add_edge("MmeHucheloup", "Bossuet", weight=1)
548
+ G.add_edge("MmeHucheloup", "Joly", weight=1)
549
+ G.add_edge("MmeHucheloup", "Grantaire", weight=1)
550
+ G.add_edge("MmeHucheloup", "Bahorel", weight=1)
551
+ G.add_edge("MmeHucheloup", "Courfeyrac", weight=1)
552
+ G.add_edge("MmeHucheloup", "Gavroche", weight=1)
553
+ G.add_edge("MmeHucheloup", "Enjolras", weight=1)
554
+ return G
janus/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
janus/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
janus/lib/python3.10/site-packages/networkx/generators/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc ADDED
Binary file (7 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc ADDED
Binary file (5.83 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc ADDED
Binary file (4.81 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc ADDED
Binary file (4.17 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-310.pyc ADDED
Binary file (2.51 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc ADDED
Binary file (3.25 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc ADDED
Binary file (2.17 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-310.pyc ADDED
Binary file (1.77 kB). View file
 
janus/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-310.pyc ADDED
Binary file (2.63 kB). View file