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

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-310.pyc +0 -0
  2. wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py +565 -0
  3. wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc +0 -0
  4. wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc +0 -0
  5. wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc +0 -0
  6. wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc +0 -0
  7. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  8. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc +0 -0
  9. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_biconnected.cpython-310.pyc +0 -0
  10. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py +248 -0
  11. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py +138 -0
  12. wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py +96 -0
  13. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__init__.py +4 -0
  14. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc +0 -0
  15. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/binary.cpython-310.pyc +0 -0
  16. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc +0 -0
  17. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/all.py +321 -0
  18. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/binary.py +450 -0
  19. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/product.py +633 -0
  20. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py +0 -0
  21. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  22. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_all.cpython-310.pyc +0 -0
  23. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_binary.cpython-310.pyc +0 -0
  24. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_product.cpython-310.pyc +0 -0
  25. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_unary.cpython-310.pyc +0 -0
  26. wemm/lib/python3.10/site-packages/networkx/algorithms/operators/unary.py +77 -0
  27. wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc +0 -0
  28. wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc +0 -0
  29. wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc +0 -0
  30. wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc +0 -0
  31. wemm/lib/python3.10/site-packages/networkx/drawing/layout.py +1630 -0
  32. wemm/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py +352 -0
  33. wemm/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py +1979 -0
  34. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  35. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc +0 -0
  36. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc +0 -0
  37. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc +0 -0
  38. wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc +0 -0
  39. wemm/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png +3 -0
  40. wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py +241 -0
  41. wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py +146 -0
  42. wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py +1029 -0
  43. wemm/lib/python3.10/site-packages/networkx/generators/__init__.py +34 -0
  44. wemm/lib/python3.10/site-packages/networkx/generators/classic.py +1068 -0
  45. wemm/lib/python3.10/site-packages/networkx/generators/degree_seq.py +867 -0
  46. wemm/lib/python3.10/site-packages/networkx/generators/expanders.py +474 -0
  47. wemm/lib/python3.10/site-packages/networkx/generators/mycielski.py +110 -0
  48. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-310.pyc +0 -0
  49. wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-310.pyc +0 -0
  50. wemm/lib/python3.10/site-packages/networkx/generators/tests/test_cographs.py +18 -0
wemm/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-310.pyc ADDED
Binary file (7.59 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Greedy graph coloring using various strategies.
3
+ """
4
+
5
+ import itertools
6
+ from collections import defaultdict, deque
7
+
8
+ import networkx as nx
9
+ from networkx.utils import arbitrary_element, py_random_state
10
+
11
+ __all__ = [
12
+ "greedy_color",
13
+ "strategy_connected_sequential",
14
+ "strategy_connected_sequential_bfs",
15
+ "strategy_connected_sequential_dfs",
16
+ "strategy_independent_set",
17
+ "strategy_largest_first",
18
+ "strategy_random_sequential",
19
+ "strategy_saturation_largest_first",
20
+ "strategy_smallest_last",
21
+ ]
22
+
23
+
24
+ def strategy_largest_first(G, colors):
25
+ """Returns a list of the nodes of ``G`` in decreasing order by
26
+ degree.
27
+
28
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
29
+
30
+ """
31
+ return sorted(G, key=G.degree, reverse=True)
32
+
33
+
34
+ @py_random_state(2)
35
+ def strategy_random_sequential(G, colors, seed=None):
36
+ """Returns a random permutation of the nodes of ``G`` as a list.
37
+
38
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
39
+
40
+ seed : integer, random_state, or None (default)
41
+ Indicator of random number generation state.
42
+ See :ref:`Randomness<randomness>`.
43
+ """
44
+ nodes = list(G)
45
+ seed.shuffle(nodes)
46
+ return nodes
47
+
48
+
49
+ def strategy_smallest_last(G, colors):
50
+ """Returns a deque of the nodes of ``G``, "smallest" last.
51
+
52
+ Specifically, the degrees of each node are tracked in a bucket queue.
53
+ From this, the node of minimum degree is repeatedly popped from the
54
+ graph, updating its neighbors' degrees.
55
+
56
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
57
+
58
+ This implementation of the strategy runs in $O(n + m)$ time
59
+ (ignoring polylogarithmic factors), where $n$ is the number of nodes
60
+ and $m$ is the number of edges.
61
+
62
+ This strategy is related to :func:`strategy_independent_set`: if we
63
+ interpret each node removed as an independent set of size one, then
64
+ this strategy chooses an independent set of size one instead of a
65
+ maximal independent set.
66
+
67
+ """
68
+ H = G.copy()
69
+ result = deque()
70
+
71
+ # Build initial degree list (i.e. the bucket queue data structure)
72
+ degrees = defaultdict(set) # set(), for fast random-access removals
73
+ lbound = float("inf")
74
+ for node, d in H.degree():
75
+ degrees[d].add(node)
76
+ lbound = min(lbound, d) # Lower bound on min-degree.
77
+
78
+ def find_min_degree():
79
+ # Save time by starting the iterator at `lbound`, not 0.
80
+ # The value that we find will be our new `lbound`, which we set later.
81
+ return next(d for d in itertools.count(lbound) if d in degrees)
82
+
83
+ for _ in G:
84
+ # Pop a min-degree node and add it to the list.
85
+ min_degree = find_min_degree()
86
+ u = degrees[min_degree].pop()
87
+ if not degrees[min_degree]: # Clean up the degree list.
88
+ del degrees[min_degree]
89
+ result.appendleft(u)
90
+
91
+ # Update degrees of removed node's neighbors.
92
+ for v in H[u]:
93
+ degree = H.degree(v)
94
+ degrees[degree].remove(v)
95
+ if not degrees[degree]: # Clean up the degree list.
96
+ del degrees[degree]
97
+ degrees[degree - 1].add(v)
98
+
99
+ # Finally, remove the node.
100
+ H.remove_node(u)
101
+ lbound = min_degree - 1 # Subtract 1 in case of tied neighbors.
102
+
103
+ return result
104
+
105
+
106
+ def _maximal_independent_set(G):
107
+ """Returns a maximal independent set of nodes in ``G`` by repeatedly
108
+ choosing an independent node of minimum degree (with respect to the
109
+ subgraph of unchosen nodes).
110
+
111
+ """
112
+ result = set()
113
+ remaining = set(G)
114
+ while remaining:
115
+ G = G.subgraph(remaining)
116
+ v = min(remaining, key=G.degree)
117
+ result.add(v)
118
+ remaining -= set(G[v]) | {v}
119
+ return result
120
+
121
+
122
+ def strategy_independent_set(G, colors):
123
+ """Uses a greedy independent set removal strategy to determine the
124
+ colors.
125
+
126
+ This function updates ``colors`` **in-place** and return ``None``,
127
+ unlike the other strategy functions in this module.
128
+
129
+ This algorithm repeatedly finds and removes a maximal independent
130
+ set, assigning each node in the set an unused color.
131
+
132
+ ``G`` is a NetworkX graph.
133
+
134
+ This strategy is related to :func:`strategy_smallest_last`: in that
135
+ strategy, an independent set of size one is chosen at each step
136
+ instead of a maximal independent set.
137
+
138
+ """
139
+ remaining_nodes = set(G)
140
+ while len(remaining_nodes) > 0:
141
+ nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
142
+ remaining_nodes -= nodes
143
+ yield from nodes
144
+
145
+
146
+ def strategy_connected_sequential_bfs(G, colors):
147
+ """Returns an iterable over nodes in ``G`` in the order given by a
148
+ breadth-first traversal.
149
+
150
+ The generated sequence has the property that for each node except
151
+ the first, at least one neighbor appeared earlier in the sequence.
152
+
153
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
154
+
155
+ """
156
+ return strategy_connected_sequential(G, colors, "bfs")
157
+
158
+
159
+ def strategy_connected_sequential_dfs(G, colors):
160
+ """Returns an iterable over nodes in ``G`` in the order given by a
161
+ depth-first traversal.
162
+
163
+ The generated sequence has the property that for each node except
164
+ the first, at least one neighbor appeared earlier in the sequence.
165
+
166
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
167
+
168
+ """
169
+ return strategy_connected_sequential(G, colors, "dfs")
170
+
171
+
172
+ def strategy_connected_sequential(G, colors, traversal="bfs"):
173
+ """Returns an iterable over nodes in ``G`` in the order given by a
174
+ breadth-first or depth-first traversal.
175
+
176
+ ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
177
+ representing depth-first traversal or breadth-first traversal,
178
+ respectively.
179
+
180
+ The generated sequence has the property that for each node except
181
+ the first, at least one neighbor appeared earlier in the sequence.
182
+
183
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
184
+
185
+ """
186
+ if traversal == "bfs":
187
+ traverse = nx.bfs_edges
188
+ elif traversal == "dfs":
189
+ traverse = nx.dfs_edges
190
+ else:
191
+ raise nx.NetworkXError(
192
+ "Please specify one of the strings 'bfs' or"
193
+ " 'dfs' for connected sequential ordering"
194
+ )
195
+ for component in nx.connected_components(G):
196
+ source = arbitrary_element(component)
197
+ # Yield the source node, then all the nodes in the specified
198
+ # traversal order.
199
+ yield source
200
+ for _, end in traverse(G.subgraph(component), source):
201
+ yield end
202
+
203
+
204
+ def strategy_saturation_largest_first(G, colors):
205
+ """Iterates over all the nodes of ``G`` in "saturation order" (also
206
+ known as "DSATUR").
207
+
208
+ ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
209
+ ``G`` to colors, for those nodes that have already been colored.
210
+
211
+ """
212
+ distinct_colors = {v: set() for v in G}
213
+
214
+ # Add the node color assignments given in colors to the
215
+ # distinct colors set for each neighbor of that node
216
+ for node, color in colors.items():
217
+ for neighbor in G[node]:
218
+ distinct_colors[neighbor].add(color)
219
+
220
+ # Check that the color assignments in colors are valid
221
+ # i.e. no neighboring nodes have the same color
222
+ if len(colors) >= 2:
223
+ for node, color in colors.items():
224
+ if color in distinct_colors[node]:
225
+ raise nx.NetworkXError("Neighboring nodes must have different colors")
226
+
227
+ # If 0 nodes have been colored, simply choose the node of highest degree.
228
+ if not colors:
229
+ node = max(G, key=G.degree)
230
+ yield node
231
+ # Add the color 0 to the distinct colors set for each
232
+ # neighbor of that node.
233
+ for v in G[node]:
234
+ distinct_colors[v].add(0)
235
+
236
+ while len(G) != len(colors):
237
+ # Update the distinct color sets for the neighbors.
238
+ for node, color in colors.items():
239
+ for neighbor in G[node]:
240
+ distinct_colors[neighbor].add(color)
241
+
242
+ # Compute the maximum saturation and the set of nodes that
243
+ # achieve that saturation.
244
+ saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}
245
+ # Yield the node with the highest saturation, and break ties by
246
+ # degree.
247
+ node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
248
+ yield node
249
+
250
+
251
+ #: Dictionary mapping name of a strategy as a string to the strategy function.
252
+ STRATEGIES = {
253
+ "largest_first": strategy_largest_first,
254
+ "random_sequential": strategy_random_sequential,
255
+ "smallest_last": strategy_smallest_last,
256
+ "independent_set": strategy_independent_set,
257
+ "connected_sequential_bfs": strategy_connected_sequential_bfs,
258
+ "connected_sequential_dfs": strategy_connected_sequential_dfs,
259
+ "connected_sequential": strategy_connected_sequential,
260
+ "saturation_largest_first": strategy_saturation_largest_first,
261
+ "DSATUR": strategy_saturation_largest_first,
262
+ }
263
+
264
+
265
+ @nx._dispatchable
266
+ def greedy_color(G, strategy="largest_first", interchange=False):
267
+ """Color a graph using various strategies of greedy graph coloring.
268
+
269
+ Attempts to color a graph using as few colors as possible, where no
270
+ neighbors of a node can have same color as the node itself. The
271
+ given strategy determines the order in which nodes are colored.
272
+
273
+ The strategies are described in [1]_, and smallest-last is based on
274
+ [2]_.
275
+
276
+ Parameters
277
+ ----------
278
+ G : NetworkX graph
279
+
280
+ strategy : string or function(G, colors)
281
+ A function (or a string representing a function) that provides
282
+ the coloring strategy, by returning nodes in the ordering they
283
+ should be colored. ``G`` is the graph, and ``colors`` is a
284
+ dictionary of the currently assigned colors, keyed by nodes. The
285
+ function must return an iterable over all the nodes in ``G``.
286
+
287
+ If the strategy function is an iterator generator (that is, a
288
+ function with ``yield`` statements), keep in mind that the
289
+ ``colors`` dictionary will be updated after each ``yield``, since
290
+ this function chooses colors greedily.
291
+
292
+ If ``strategy`` is a string, it must be one of the following,
293
+ each of which represents one of the built-in strategy functions.
294
+
295
+ * ``'largest_first'``
296
+ * ``'random_sequential'``
297
+ * ``'smallest_last'``
298
+ * ``'independent_set'``
299
+ * ``'connected_sequential_bfs'``
300
+ * ``'connected_sequential_dfs'``
301
+ * ``'connected_sequential'`` (alias for the previous strategy)
302
+ * ``'saturation_largest_first'``
303
+ * ``'DSATUR'`` (alias for the previous strategy)
304
+
305
+ interchange: bool
306
+ Will use the color interchange algorithm described by [3]_ if set
307
+ to ``True``.
308
+
309
+ Note that ``saturation_largest_first`` and ``independent_set``
310
+ do not work with interchange. Furthermore, if you use
311
+ interchange with your own strategy function, you cannot rely
312
+ on the values in the ``colors`` argument.
313
+
314
+ Returns
315
+ -------
316
+ A dictionary with keys representing nodes and values representing
317
+ corresponding coloring.
318
+
319
+ Examples
320
+ --------
321
+ >>> G = nx.cycle_graph(4)
322
+ >>> d = nx.coloring.greedy_color(G, strategy="largest_first")
323
+ >>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
324
+ True
325
+
326
+ Raises
327
+ ------
328
+ NetworkXPointlessConcept
329
+ If ``strategy`` is ``saturation_largest_first`` or
330
+ ``independent_set`` and ``interchange`` is ``True``.
331
+
332
+ References
333
+ ----------
334
+ .. [1] Adrian Kosowski, and Krzysztof Manuszewski,
335
+ Classical Coloring of Graphs, Graph Colorings, 2-19, 2004.
336
+ ISBN 0-8218-3458-4.
337
+ .. [2] David W. Matula, and Leland L. Beck, "Smallest-last
338
+ ordering and clustering and graph coloring algorithms." *J. ACM* 30,
339
+ 3 (July 1983), 417–427. <https://doi.org/10.1145/2402.322385>
340
+ .. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik,
341
+ Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
342
+ ISBN 0-486-45353-7.
343
+
344
+ """
345
+ if len(G) == 0:
346
+ return {}
347
+ # Determine the strategy provided by the caller.
348
+ strategy = STRATEGIES.get(strategy, strategy)
349
+ if not callable(strategy):
350
+ raise nx.NetworkXError(
351
+ f"strategy must be callable or a valid string. {strategy} not valid."
352
+ )
353
+ # Perform some validation on the arguments before executing any
354
+ # strategy functions.
355
+ if interchange:
356
+ if strategy is strategy_independent_set:
357
+ msg = "interchange cannot be used with independent_set"
358
+ raise nx.NetworkXPointlessConcept(msg)
359
+ if strategy is strategy_saturation_largest_first:
360
+ msg = "interchange cannot be used with" " saturation_largest_first"
361
+ raise nx.NetworkXPointlessConcept(msg)
362
+ colors = {}
363
+ nodes = strategy(G, colors)
364
+ if interchange:
365
+ return _greedy_coloring_with_interchange(G, nodes)
366
+ for u in nodes:
367
+ # Set to keep track of colors of neighbors
368
+ nbr_colors = {colors[v] for v in G[u] if v in colors}
369
+ # Find the first unused color.
370
+ for color in itertools.count():
371
+ if color not in nbr_colors:
372
+ break
373
+ # Assign the new color to the current node.
374
+ colors[u] = color
375
+ return colors
376
+
377
+
378
+ # Tools for coloring with interchanges
379
+ class _Node:
380
+ __slots__ = ["node_id", "color", "adj_list", "adj_color"]
381
+
382
+ def __init__(self, node_id, n):
383
+ self.node_id = node_id
384
+ self.color = -1
385
+ self.adj_list = None
386
+ self.adj_color = [None for _ in range(n)]
387
+
388
+ def __repr__(self):
389
+ return (
390
+ f"Node_id: {self.node_id}, Color: {self.color}, "
391
+ f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})"
392
+ )
393
+
394
+ def assign_color(self, adj_entry, color):
395
+ adj_entry.col_prev = None
396
+ adj_entry.col_next = self.adj_color[color]
397
+ self.adj_color[color] = adj_entry
398
+ if adj_entry.col_next is not None:
399
+ adj_entry.col_next.col_prev = adj_entry
400
+
401
+ def clear_color(self, adj_entry, color):
402
+ if adj_entry.col_prev is None:
403
+ self.adj_color[color] = adj_entry.col_next
404
+ else:
405
+ adj_entry.col_prev.col_next = adj_entry.col_next
406
+ if adj_entry.col_next is not None:
407
+ adj_entry.col_next.col_prev = adj_entry.col_prev
408
+
409
+ def iter_neighbors(self):
410
+ adj_node = self.adj_list
411
+ while adj_node is not None:
412
+ yield adj_node
413
+ adj_node = adj_node.next
414
+
415
+ def iter_neighbors_color(self, color):
416
+ adj_color_node = self.adj_color[color]
417
+ while adj_color_node is not None:
418
+ yield adj_color_node.node_id
419
+ adj_color_node = adj_color_node.col_next
420
+
421
+
422
+ class _AdjEntry:
423
+ __slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
424
+
425
+ def __init__(self, node_id):
426
+ self.node_id = node_id
427
+ self.next = None
428
+ self.mate = None
429
+ self.col_next = None
430
+ self.col_prev = None
431
+
432
+ def __repr__(self):
433
+ col_next = None if self.col_next is None else self.col_next.node_id
434
+ col_prev = None if self.col_prev is None else self.col_prev.node_id
435
+ return (
436
+ f"Node_id: {self.node_id}, Next: ({self.next}), "
437
+ f"Mate: ({self.mate.node_id}), "
438
+ f"col_next: ({col_next}), col_prev: ({col_prev})"
439
+ )
440
+
441
+
442
+ def _greedy_coloring_with_interchange(G, nodes):
443
+ """Return a coloring for `original_graph` using interchange approach
444
+
445
+ This procedure is an adaption of the algorithm described by [1]_,
446
+ and is an implementation of coloring with interchange. Please be
447
+ advised, that the datastructures used are rather complex because
448
+ they are optimized to minimize the time spent identifying
449
+ subcomponents of the graph, which are possible candidates for color
450
+ interchange.
451
+
452
+ Parameters
453
+ ----------
454
+ G : NetworkX graph
455
+ The graph to be colored
456
+
457
+ nodes : list
458
+ nodes ordered using the strategy of choice
459
+
460
+ Returns
461
+ -------
462
+ dict :
463
+ A dictionary keyed by node to a color value
464
+
465
+ References
466
+ ----------
467
+ .. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik,
468
+ Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
469
+ ISBN 0-486-45353-7.
470
+ """
471
+ n = len(G)
472
+
473
+ graph = {node: _Node(node, n) for node in G}
474
+
475
+ for node1, node2 in G.edges():
476
+ adj_entry1 = _AdjEntry(node2)
477
+ adj_entry2 = _AdjEntry(node1)
478
+ adj_entry1.mate = adj_entry2
479
+ adj_entry2.mate = adj_entry1
480
+ node1_head = graph[node1].adj_list
481
+ adj_entry1.next = node1_head
482
+ graph[node1].adj_list = adj_entry1
483
+ node2_head = graph[node2].adj_list
484
+ adj_entry2.next = node2_head
485
+ graph[node2].adj_list = adj_entry2
486
+
487
+ k = 0
488
+ for node in nodes:
489
+ # Find the smallest possible, unused color
490
+ neighbors = graph[node].iter_neighbors()
491
+ col_used = {graph[adj_node.node_id].color for adj_node in neighbors}
492
+ col_used.discard(-1)
493
+ k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
494
+
495
+ # k1 is now the lowest available color
496
+ if k1 > k:
497
+ connected = True
498
+ visited = set()
499
+ col1 = -1
500
+ col2 = -1
501
+ while connected and col1 < k:
502
+ col1 += 1
503
+ neighbor_cols = graph[node].iter_neighbors_color(col1)
504
+ col1_adj = list(neighbor_cols)
505
+
506
+ col2 = col1
507
+ while connected and col2 < k:
508
+ col2 += 1
509
+ visited = set(col1_adj)
510
+ frontier = list(col1_adj)
511
+ i = 0
512
+ while i < len(frontier):
513
+ search_node = frontier[i]
514
+ i += 1
515
+ col_opp = col2 if graph[search_node].color == col1 else col1
516
+ neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
517
+
518
+ for neighbor in neighbor_cols:
519
+ if neighbor not in visited:
520
+ visited.add(neighbor)
521
+ frontier.append(neighbor)
522
+
523
+ # Search if node is not adj to any col2 vertex
524
+ connected = (
525
+ len(
526
+ visited.intersection(graph[node].iter_neighbors_color(col2))
527
+ )
528
+ > 0
529
+ )
530
+
531
+ # If connected is false then we can swap !!!
532
+ if not connected:
533
+ # Update all the nodes in the component
534
+ for search_node in visited:
535
+ graph[search_node].color = (
536
+ col2 if graph[search_node].color == col1 else col1
537
+ )
538
+ col2_adj = graph[search_node].adj_color[col2]
539
+ graph[search_node].adj_color[col2] = graph[search_node].adj_color[
540
+ col1
541
+ ]
542
+ graph[search_node].adj_color[col1] = col2_adj
543
+
544
+ # Update all the neighboring nodes
545
+ for search_node in visited:
546
+ col = graph[search_node].color
547
+ col_opp = col1 if col == col2 else col2
548
+ for adj_node in graph[search_node].iter_neighbors():
549
+ if graph[adj_node.node_id].color != col_opp:
550
+ # Direct reference to entry
551
+ adj_mate = adj_node.mate
552
+ graph[adj_node.node_id].clear_color(adj_mate, col_opp)
553
+ graph[adj_node.node_id].assign_color(adj_mate, col)
554
+ k1 = col1
555
+
556
+ # We can color this node color k1
557
+ graph[node].color = k1
558
+ k = max(k1, k)
559
+
560
+ # Update the neighbors of this node
561
+ for adj_node in graph[node].iter_neighbors():
562
+ adj_mate = adj_node.mate
563
+ graph[adj_node.node_id].assign_color(adj_mate, k1)
564
+
565
+ return {node.node_id: node.color for node in graph.values()}
wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc ADDED
Binary file (4.83 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc ADDED
Binary file (2.4 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc ADDED
Binary file (4.5 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc ADDED
Binary file (2.74 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_biconnected.cpython-310.pyc ADDED
Binary file (6.7 kB). View file
 
wemm/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)
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+ from networkx import convert_node_labels_to_integers as cnlti
6
+ from networkx.classes.tests import dispatch_interface
7
+
8
+
9
+ class TestConnected:
10
+ @classmethod
11
+ def setup_class(cls):
12
+ G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
13
+ G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
14
+ G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
15
+ cls.G = nx.union(G1, G2)
16
+ cls.G = nx.union(cls.G, G3)
17
+ cls.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
18
+ cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)
19
+
20
+ cls.gc = []
21
+ G = nx.DiGraph()
22
+ G.add_edges_from(
23
+ [
24
+ (1, 2),
25
+ (2, 3),
26
+ (2, 8),
27
+ (3, 4),
28
+ (3, 7),
29
+ (4, 5),
30
+ (5, 3),
31
+ (5, 6),
32
+ (7, 4),
33
+ (7, 6),
34
+ (8, 1),
35
+ (8, 7),
36
+ ]
37
+ )
38
+ C = [[3, 4, 5, 7], [1, 2, 8], [6]]
39
+ cls.gc.append((G, C))
40
+
41
+ G = nx.DiGraph()
42
+ G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
43
+ C = [[2, 3, 4], [1]]
44
+ cls.gc.append((G, C))
45
+
46
+ G = nx.DiGraph()
47
+ G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
48
+ C = [[1, 2, 3]]
49
+ cls.gc.append((G, C))
50
+
51
+ # Eppstein's tests
52
+ G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
53
+ C = [[0], [1], [2], [3], [4], [5], [6]]
54
+ cls.gc.append((G, C))
55
+
56
+ G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
57
+ C = [[0, 1, 2], [3, 4]]
58
+ cls.gc.append((G, C))
59
+
60
+ G = nx.DiGraph()
61
+ C = []
62
+ cls.gc.append((G, C))
63
+
64
+ def test_connected_components(self):
65
+ # Test duplicated below
66
+ cc = nx.connected_components
67
+ G = self.G
68
+ C = {
69
+ frozenset([0, 1, 2, 3]),
70
+ frozenset([4, 5, 6, 7, 8, 9]),
71
+ frozenset([10, 11, 12, 13, 14]),
72
+ }
73
+ assert {frozenset(g) for g in cc(G)} == C
74
+
75
+ def test_connected_components_nx_loopback(self):
76
+ # This tests the @nx._dispatchable mechanism, treating nx.connected_components
77
+ # as if it were a re-implementation from another package.
78
+ # Test duplicated from above
79
+ cc = nx.connected_components
80
+ G = dispatch_interface.convert(self.G)
81
+ C = {
82
+ frozenset([0, 1, 2, 3]),
83
+ frozenset([4, 5, 6, 7, 8, 9]),
84
+ frozenset([10, 11, 12, 13, 14]),
85
+ }
86
+ if "nx_loopback" in nx.config.backends or not nx.config.backends:
87
+ # If `nx.config.backends` is empty, then `_dispatchable.__call__` takes a
88
+ # "fast path" and does not check graph inputs, so using an unknown backend
89
+ # here will still work.
90
+ assert {frozenset(g) for g in cc(G)} == C
91
+ else:
92
+ # This raises, because "nx_loopback" is not registered as a backend.
93
+ with pytest.raises(
94
+ ImportError, match="'nx_loopback' backend is not installed"
95
+ ):
96
+ cc(G)
97
+
98
+ def test_number_connected_components(self):
99
+ ncc = nx.number_connected_components
100
+ assert ncc(self.G) == 3
101
+
102
+ def test_number_connected_components2(self):
103
+ ncc = nx.number_connected_components
104
+ assert ncc(self.grid) == 1
105
+
106
+ def test_connected_components2(self):
107
+ cc = nx.connected_components
108
+ G = self.grid
109
+ C = {frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])}
110
+ assert {frozenset(g) for g in cc(G)} == C
111
+
112
+ def test_node_connected_components(self):
113
+ ncc = nx.node_connected_component
114
+ G = self.grid
115
+ C = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
116
+ assert ncc(G, 1) == C
117
+
118
+ def test_is_connected(self):
119
+ assert nx.is_connected(self.grid)
120
+ G = nx.Graph()
121
+ G.add_nodes_from([1, 2])
122
+ assert not nx.is_connected(G)
123
+
124
+ def test_connected_raise(self):
125
+ with pytest.raises(NetworkXNotImplemented):
126
+ next(nx.connected_components(self.DG))
127
+ pytest.raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
128
+ pytest.raises(NetworkXNotImplemented, nx.node_connected_component, self.DG, 1)
129
+ pytest.raises(NetworkXNotImplemented, nx.is_connected, self.DG)
130
+ pytest.raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
131
+
132
+ def test_connected_mutability(self):
133
+ G = self.grid
134
+ seen = set()
135
+ for component in nx.connected_components(G):
136
+ assert len(seen & component) == 0
137
+ seen.update(component)
138
+ component.clear()
wemm/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx import NetworkXNotImplemented
5
+
6
+
7
+ class TestWeaklyConnected:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ cls.gc = []
11
+ G = nx.DiGraph()
12
+ G.add_edges_from(
13
+ [
14
+ (1, 2),
15
+ (2, 3),
16
+ (2, 8),
17
+ (3, 4),
18
+ (3, 7),
19
+ (4, 5),
20
+ (5, 3),
21
+ (5, 6),
22
+ (7, 4),
23
+ (7, 6),
24
+ (8, 1),
25
+ (8, 7),
26
+ ]
27
+ )
28
+ C = [[3, 4, 5, 7], [1, 2, 8], [6]]
29
+ cls.gc.append((G, C))
30
+
31
+ G = nx.DiGraph()
32
+ G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
33
+ C = [[2, 3, 4], [1]]
34
+ cls.gc.append((G, C))
35
+
36
+ G = nx.DiGraph()
37
+ G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
38
+ C = [[1, 2, 3]]
39
+ cls.gc.append((G, C))
40
+
41
+ # Eppstein's tests
42
+ G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
43
+ C = [[0], [1], [2], [3], [4], [5], [6]]
44
+ cls.gc.append((G, C))
45
+
46
+ G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
47
+ C = [[0, 1, 2], [3, 4]]
48
+ cls.gc.append((G, C))
49
+
50
+ def test_weakly_connected_components(self):
51
+ for G, C in self.gc:
52
+ U = G.to_undirected()
53
+ w = {frozenset(g) for g in nx.weakly_connected_components(G)}
54
+ c = {frozenset(g) for g in nx.connected_components(U)}
55
+ assert w == c
56
+
57
+ def test_number_weakly_connected_components(self):
58
+ for G, C in self.gc:
59
+ U = G.to_undirected()
60
+ w = nx.number_weakly_connected_components(G)
61
+ c = nx.number_connected_components(U)
62
+ assert w == c
63
+
64
+ def test_is_weakly_connected(self):
65
+ for G, C in self.gc:
66
+ U = G.to_undirected()
67
+ assert nx.is_weakly_connected(G) == nx.is_connected(U)
68
+
69
+ def test_null_graph(self):
70
+ G = nx.DiGraph()
71
+ assert list(nx.weakly_connected_components(G)) == []
72
+ assert nx.number_weakly_connected_components(G) == 0
73
+ with pytest.raises(nx.NetworkXPointlessConcept):
74
+ next(nx.is_weakly_connected(G))
75
+
76
+ def test_connected_raise(self):
77
+ G = nx.Graph()
78
+ with pytest.raises(NetworkXNotImplemented):
79
+ next(nx.weakly_connected_components(G))
80
+ pytest.raises(NetworkXNotImplemented, nx.number_weakly_connected_components, G)
81
+ pytest.raises(NetworkXNotImplemented, nx.is_weakly_connected, G)
82
+
83
+ def test_connected_mutability(self):
84
+ DG = nx.path_graph(5, create_using=nx.DiGraph)
85
+ G = nx.disjoint_union(DG, DG)
86
+ seen = set()
87
+ for component in nx.weakly_connected_components(G):
88
+ assert len(seen & component) == 0
89
+ seen.update(component)
90
+ component.clear()
91
+
92
+
93
+ def test_is_weakly_connected_empty_graph_raises():
94
+ G = nx.DiGraph()
95
+ with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
96
+ nx.is_weakly_connected(G)
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from networkx.algorithms.operators.all import *
2
+ from networkx.algorithms.operators.binary import *
3
+ from networkx.algorithms.operators.product import *
4
+ from networkx.algorithms.operators.unary import *
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (373 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/binary.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/all.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Operations on many graphs."""
2
+
3
+ from itertools import chain, repeat
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["union_all", "compose_all", "disjoint_union_all", "intersection_all"]
8
+
9
+
10
+ @nx._dispatchable(graphs="[graphs]", preserve_all_attrs=True, returns_graph=True)
11
+ def union_all(graphs, rename=()):
12
+ """Returns the union of all graphs.
13
+
14
+ The graphs must be disjoint, otherwise an exception is raised.
15
+
16
+ Parameters
17
+ ----------
18
+ graphs : iterable
19
+ Iterable of NetworkX graphs
20
+
21
+ rename : iterable , optional
22
+ Node names of graphs can be changed by specifying the tuple
23
+ rename=('G-','H-') (for example). Node "u" in G is then renamed
24
+ "G-u" and "v" in H is renamed "H-v". Infinite generators (like itertools.count)
25
+ are also supported.
26
+
27
+ Returns
28
+ -------
29
+ U : a graph with the same type as the first graph in list
30
+
31
+ Raises
32
+ ------
33
+ ValueError
34
+ If `graphs` is an empty list.
35
+
36
+ NetworkXError
37
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
38
+
39
+ Notes
40
+ -----
41
+ For operating on mixed type graphs, they should be converted to the same type.
42
+ >>> G = nx.Graph()
43
+ >>> H = nx.DiGraph()
44
+ >>> GH = union_all([nx.DiGraph(G), H])
45
+
46
+ To force a disjoint union with node relabeling, use
47
+ disjoint_union_all(G,H) or convert_node_labels_to integers().
48
+
49
+ Graph, edge, and node attributes are propagated to the union graph.
50
+ If a graph attribute is present in multiple graphs, then the value
51
+ from the last graph in the list with that attribute is used.
52
+
53
+ Examples
54
+ --------
55
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
56
+ >>> G2 = nx.Graph([(4, 5), (5, 6)])
57
+ >>> result_graph = nx.union_all([G1, G2])
58
+ >>> result_graph.nodes()
59
+ NodeView((1, 2, 3, 4, 5, 6))
60
+ >>> result_graph.edges()
61
+ EdgeView([(1, 2), (2, 3), (4, 5), (5, 6)])
62
+
63
+ See Also
64
+ --------
65
+ union
66
+ disjoint_union_all
67
+ """
68
+ R = None
69
+ seen_nodes = set()
70
+
71
+ # rename graph to obtain disjoint node labels
72
+ def add_prefix(graph, prefix):
73
+ if prefix is None:
74
+ return graph
75
+
76
+ def label(x):
77
+ return f"{prefix}{x}"
78
+
79
+ return nx.relabel_nodes(graph, label)
80
+
81
+ rename = chain(rename, repeat(None))
82
+ graphs = (add_prefix(G, name) for G, name in zip(graphs, rename))
83
+
84
+ for i, G in enumerate(graphs):
85
+ G_nodes_set = set(G.nodes)
86
+ if i == 0:
87
+ # Union is the same type as first graph
88
+ R = G.__class__()
89
+ elif G.is_directed() != R.is_directed():
90
+ raise nx.NetworkXError("All graphs must be directed or undirected.")
91
+ elif G.is_multigraph() != R.is_multigraph():
92
+ raise nx.NetworkXError("All graphs must be graphs or multigraphs.")
93
+ elif not seen_nodes.isdisjoint(G_nodes_set):
94
+ raise nx.NetworkXError(
95
+ "The node sets of the graphs are not disjoint.\n"
96
+ "Use `rename` to specify prefixes for the graphs or use\n"
97
+ "disjoint_union(G1, G2, ..., GN)."
98
+ )
99
+
100
+ seen_nodes |= G_nodes_set
101
+ R.graph.update(G.graph)
102
+ R.add_nodes_from(G.nodes(data=True))
103
+ R.add_edges_from(
104
+ G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
105
+ )
106
+
107
+ if R is None:
108
+ raise ValueError("cannot apply union_all to an empty list")
109
+
110
+ return R
111
+
112
+
113
+ @nx._dispatchable(graphs="[graphs]", preserve_all_attrs=True, returns_graph=True)
114
+ def disjoint_union_all(graphs):
115
+ """Returns the disjoint union of all graphs.
116
+
117
+ This operation forces distinct integer node labels starting with 0
118
+ for the first graph in the list and numbering consecutively.
119
+
120
+ Parameters
121
+ ----------
122
+ graphs : iterable
123
+ Iterable of NetworkX graphs
124
+
125
+ Returns
126
+ -------
127
+ U : A graph with the same type as the first graph in list
128
+
129
+ Raises
130
+ ------
131
+ ValueError
132
+ If `graphs` is an empty list.
133
+
134
+ NetworkXError
135
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
136
+
137
+ Examples
138
+ --------
139
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
140
+ >>> G2 = nx.Graph([(4, 5), (5, 6)])
141
+ >>> U = nx.disjoint_union_all([G1, G2])
142
+ >>> list(U.nodes())
143
+ [0, 1, 2, 3, 4, 5]
144
+ >>> list(U.edges())
145
+ [(0, 1), (1, 2), (3, 4), (4, 5)]
146
+
147
+ Notes
148
+ -----
149
+ For operating on mixed type graphs, they should be converted to the same type.
150
+
151
+ Graph, edge, and node attributes are propagated to the union graph.
152
+ If a graph attribute is present in multiple graphs, then the value
153
+ from the last graph in the list with that attribute is used.
154
+ """
155
+
156
+ def yield_relabeled(graphs):
157
+ first_label = 0
158
+ for G in graphs:
159
+ yield nx.convert_node_labels_to_integers(G, first_label=first_label)
160
+ first_label += len(G)
161
+
162
+ R = union_all(yield_relabeled(graphs))
163
+
164
+ return R
165
+
166
+
167
+ @nx._dispatchable(graphs="[graphs]", preserve_all_attrs=True, returns_graph=True)
168
+ def compose_all(graphs):
169
+ """Returns the composition of all graphs.
170
+
171
+ Composition is the simple union of the node sets and edge sets.
172
+ The node sets of the supplied graphs need not be disjoint.
173
+
174
+ Parameters
175
+ ----------
176
+ graphs : iterable
177
+ Iterable of NetworkX graphs
178
+
179
+ Returns
180
+ -------
181
+ C : A graph with the same type as the first graph in list
182
+
183
+ Raises
184
+ ------
185
+ ValueError
186
+ If `graphs` is an empty list.
187
+
188
+ NetworkXError
189
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
190
+
191
+ Examples
192
+ --------
193
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
194
+ >>> G2 = nx.Graph([(3, 4), (5, 6)])
195
+ >>> C = nx.compose_all([G1, G2])
196
+ >>> list(C.nodes())
197
+ [1, 2, 3, 4, 5, 6]
198
+ >>> list(C.edges())
199
+ [(1, 2), (2, 3), (3, 4), (5, 6)]
200
+
201
+ Notes
202
+ -----
203
+ For operating on mixed type graphs, they should be converted to the same type.
204
+
205
+ Graph, edge, and node attributes are propagated to the union graph.
206
+ If a graph attribute is present in multiple graphs, then the value
207
+ from the last graph in the list with that attribute is used.
208
+ """
209
+ R = None
210
+
211
+ # add graph attributes, H attributes take precedent over G attributes
212
+ for i, G in enumerate(graphs):
213
+ if i == 0:
214
+ # create new graph
215
+ R = G.__class__()
216
+ elif G.is_directed() != R.is_directed():
217
+ raise nx.NetworkXError("All graphs must be directed or undirected.")
218
+ elif G.is_multigraph() != R.is_multigraph():
219
+ raise nx.NetworkXError("All graphs must be graphs or multigraphs.")
220
+
221
+ R.graph.update(G.graph)
222
+ R.add_nodes_from(G.nodes(data=True))
223
+ R.add_edges_from(
224
+ G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
225
+ )
226
+
227
+ if R is None:
228
+ raise ValueError("cannot apply compose_all to an empty list")
229
+
230
+ return R
231
+
232
+
233
+ @nx._dispatchable(graphs="[graphs]", returns_graph=True)
234
+ def intersection_all(graphs):
235
+ """Returns a new graph that contains only the nodes and the edges that exist in
236
+ all graphs.
237
+
238
+ Parameters
239
+ ----------
240
+ graphs : iterable
241
+ Iterable of NetworkX graphs
242
+
243
+ Returns
244
+ -------
245
+ R : A new graph with the same type as the first graph in list
246
+
247
+ Raises
248
+ ------
249
+ ValueError
250
+ If `graphs` is an empty list.
251
+
252
+ NetworkXError
253
+ In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs.
254
+
255
+ Notes
256
+ -----
257
+ For operating on mixed type graphs, they should be converted to the same type.
258
+
259
+ Attributes from the graph, nodes, and edges are not copied to the new
260
+ graph.
261
+
262
+ The resulting graph can be updated with attributes if desired. For example, code which adds the minimum attribute for each node across all graphs could work.
263
+ >>> g = nx.Graph()
264
+ >>> g.add_node(0, capacity=4)
265
+ >>> g.add_node(1, capacity=3)
266
+ >>> g.add_edge(0, 1)
267
+
268
+ >>> h = g.copy()
269
+ >>> h.nodes[0]["capacity"] = 2
270
+
271
+ >>> gh = nx.intersection_all([g, h])
272
+
273
+ >>> new_node_attr = {
274
+ ... n: min(*(anyG.nodes[n].get("capacity", float("inf")) for anyG in [g, h]))
275
+ ... for n in gh
276
+ ... }
277
+ >>> nx.set_node_attributes(gh, new_node_attr, "new_capacity")
278
+ >>> gh.nodes(data=True)
279
+ NodeDataView({0: {'new_capacity': 2}, 1: {'new_capacity': 3}})
280
+
281
+ Examples
282
+ --------
283
+ >>> G1 = nx.Graph([(1, 2), (2, 3)])
284
+ >>> G2 = nx.Graph([(2, 3), (3, 4)])
285
+ >>> R = nx.intersection_all([G1, G2])
286
+ >>> list(R.nodes())
287
+ [2, 3]
288
+ >>> list(R.edges())
289
+ [(2, 3)]
290
+
291
+ """
292
+ R = None
293
+
294
+ for i, G in enumerate(graphs):
295
+ G_nodes_set = set(G.nodes)
296
+ G_edges_set = set(G.edges)
297
+ if not G.is_directed():
298
+ if G.is_multigraph():
299
+ G_edges_set.update((v, u, k) for u, v, k in list(G_edges_set))
300
+ else:
301
+ G_edges_set.update((v, u) for u, v in list(G_edges_set))
302
+ if i == 0:
303
+ # create new graph
304
+ R = G.__class__()
305
+ node_intersection = G_nodes_set
306
+ edge_intersection = G_edges_set
307
+ elif G.is_directed() != R.is_directed():
308
+ raise nx.NetworkXError("All graphs must be directed or undirected.")
309
+ elif G.is_multigraph() != R.is_multigraph():
310
+ raise nx.NetworkXError("All graphs must be graphs or multigraphs.")
311
+ else:
312
+ node_intersection &= G_nodes_set
313
+ edge_intersection &= G_edges_set
314
+
315
+ if R is None:
316
+ raise ValueError("cannot apply intersection_all to an empty list")
317
+
318
+ R.add_nodes_from(node_intersection)
319
+ R.add_edges_from(edge_intersection)
320
+
321
+ return R
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/binary.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Operations on graphs including union, intersection, difference.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "union",
9
+ "compose",
10
+ "disjoint_union",
11
+ "intersection",
12
+ "difference",
13
+ "symmetric_difference",
14
+ "full_join",
15
+ ]
16
+ _G_H = {"G": 0, "H": 1}
17
+
18
+
19
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
20
+ def union(G, H, rename=()):
21
+ """Combine graphs G and H. The names of nodes must be unique.
22
+
23
+ A name collision between the graphs will raise an exception.
24
+
25
+ A renaming facility is provided to avoid name collisions.
26
+
27
+
28
+ Parameters
29
+ ----------
30
+ G, H : graph
31
+ A NetworkX graph
32
+
33
+ rename : iterable , optional
34
+ Node names of G and H can be changed by specifying the tuple
35
+ rename=('G-','H-') (for example). Node "u" in G is then renamed
36
+ "G-u" and "v" in H is renamed "H-v".
37
+
38
+ Returns
39
+ -------
40
+ U : A union graph with the same type as G.
41
+
42
+ See Also
43
+ --------
44
+ compose
45
+ :func:`~networkx.Graph.update`
46
+ disjoint_union
47
+
48
+ Notes
49
+ -----
50
+ To combine graphs that have common nodes, consider compose(G, H)
51
+ or the method, Graph.update().
52
+
53
+ disjoint_union() is similar to union() except that it avoids name clashes
54
+ by relabeling the nodes with sequential integers.
55
+
56
+ Edge and node attributes are propagated from G and H to the union graph.
57
+ Graph attributes are also propagated, but if they are present in both G and H,
58
+ then the value from H is used.
59
+
60
+ Examples
61
+ --------
62
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
63
+ >>> H = nx.Graph([(0, 1), (0, 3), (1, 3), (1, 2)])
64
+ >>> U = nx.union(G, H, rename=("G", "H"))
65
+ >>> U.nodes
66
+ NodeView(('G0', 'G1', 'G2', 'H0', 'H1', 'H3', 'H2'))
67
+ >>> U.edges
68
+ EdgeView([('G0', 'G1'), ('G0', 'G2'), ('G1', 'G2'), ('H0', 'H1'), ('H0', 'H3'), ('H1', 'H3'), ('H1', 'H2')])
69
+
70
+
71
+ """
72
+ return nx.union_all([G, H], rename)
73
+
74
+
75
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
76
+ def disjoint_union(G, H):
77
+ """Combine graphs G and H. The nodes are assumed to be unique (disjoint).
78
+
79
+ This algorithm automatically relabels nodes to avoid name collisions.
80
+
81
+ Parameters
82
+ ----------
83
+ G,H : graph
84
+ A NetworkX graph
85
+
86
+ Returns
87
+ -------
88
+ U : A union graph with the same type as G.
89
+
90
+ See Also
91
+ --------
92
+ union
93
+ compose
94
+ :func:`~networkx.Graph.update`
95
+
96
+ Notes
97
+ -----
98
+ A new graph is created, of the same class as G. It is recommended
99
+ that G and H be either both directed or both undirected.
100
+
101
+ The nodes of G are relabeled 0 to len(G)-1, and the nodes of H are
102
+ relabeled len(G) to len(G)+len(H)-1.
103
+
104
+ Renumbering forces G and H to be disjoint, so no exception is ever raised for a name collision.
105
+ To preserve the check for common nodes, use union().
106
+
107
+ Edge and node attributes are propagated from G and H to the union graph.
108
+ Graph attributes are also propagated, but if they are present in both G and H,
109
+ then the value from H is used.
110
+
111
+ To combine graphs that have common nodes, consider compose(G, H)
112
+ or the method, Graph.update().
113
+
114
+ Examples
115
+ --------
116
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
117
+ >>> H = nx.Graph([(0, 3), (1, 2), (2, 3)])
118
+ >>> G.nodes[0]["key1"] = 5
119
+ >>> H.nodes[0]["key2"] = 10
120
+ >>> U = nx.disjoint_union(G, H)
121
+ >>> U.nodes(data=True)
122
+ NodeDataView({0: {'key1': 5}, 1: {}, 2: {}, 3: {'key2': 10}, 4: {}, 5: {}, 6: {}})
123
+ >>> U.edges
124
+ EdgeView([(0, 1), (0, 2), (1, 2), (3, 4), (4, 6), (5, 6)])
125
+ """
126
+ return nx.disjoint_union_all([G, H])
127
+
128
+
129
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
130
+ def intersection(G, H):
131
+ """Returns a new graph that contains only the nodes and the edges that exist in
132
+ both G and H.
133
+
134
+ Parameters
135
+ ----------
136
+ G,H : graph
137
+ A NetworkX graph. G and H can have different node sets but must be both graphs or both multigraphs.
138
+
139
+ Raises
140
+ ------
141
+ NetworkXError
142
+ If one is a MultiGraph and the other one is a graph.
143
+
144
+ Returns
145
+ -------
146
+ GH : A new graph with the same type as G.
147
+
148
+ Notes
149
+ -----
150
+ Attributes from the graph, nodes, and edges are not copied to the new
151
+ graph. If you want a new graph of the intersection of G and H
152
+ with the attributes (including edge data) from G use remove_nodes_from()
153
+ as follows
154
+
155
+ >>> G = nx.path_graph(3)
156
+ >>> H = nx.path_graph(5)
157
+ >>> R = G.copy()
158
+ >>> R.remove_nodes_from(n for n in G if n not in H)
159
+ >>> R.remove_edges_from(e for e in G.edges if e not in H.edges)
160
+
161
+ Examples
162
+ --------
163
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
164
+ >>> H = nx.Graph([(0, 3), (1, 2), (2, 3)])
165
+ >>> R = nx.intersection(G, H)
166
+ >>> R.nodes
167
+ NodeView((0, 1, 2))
168
+ >>> R.edges
169
+ EdgeView([(1, 2)])
170
+ """
171
+ return nx.intersection_all([G, H])
172
+
173
+
174
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
175
+ def difference(G, H):
176
+ """Returns a new graph that contains the edges that exist in G but not in H.
177
+
178
+ The node sets of H and G must be the same.
179
+
180
+ Parameters
181
+ ----------
182
+ G,H : graph
183
+ A NetworkX graph. G and H must have the same node sets.
184
+
185
+ Returns
186
+ -------
187
+ D : A new graph with the same type as G.
188
+
189
+ Notes
190
+ -----
191
+ Attributes from the graph, nodes, and edges are not copied to the new
192
+ graph. If you want a new graph of the difference of G and H with
193
+ the attributes (including edge data) from G use remove_nodes_from()
194
+ as follows:
195
+
196
+ >>> G = nx.path_graph(3)
197
+ >>> H = nx.path_graph(5)
198
+ >>> R = G.copy()
199
+ >>> R.remove_nodes_from(n for n in G if n in H)
200
+
201
+ Examples
202
+ --------
203
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3)])
204
+ >>> H = nx.Graph([(0, 1), (1, 2), (0, 3)])
205
+ >>> R = nx.difference(G, H)
206
+ >>> R.nodes
207
+ NodeView((0, 1, 2, 3))
208
+ >>> R.edges
209
+ EdgeView([(0, 2), (1, 3)])
210
+ """
211
+ # create new graph
212
+ if not G.is_multigraph() == H.is_multigraph():
213
+ raise nx.NetworkXError("G and H must both be graphs or multigraphs.")
214
+ R = nx.create_empty_copy(G, with_data=False)
215
+
216
+ if set(G) != set(H):
217
+ raise nx.NetworkXError("Node sets of graphs not equal")
218
+
219
+ if G.is_multigraph():
220
+ edges = G.edges(keys=True)
221
+ else:
222
+ edges = G.edges()
223
+ for e in edges:
224
+ if not H.has_edge(*e):
225
+ R.add_edge(*e)
226
+ return R
227
+
228
+
229
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
230
+ def symmetric_difference(G, H):
231
+ """Returns new graph with edges that exist in either G or H but not both.
232
+
233
+ The node sets of H and G must be the same.
234
+
235
+ Parameters
236
+ ----------
237
+ G,H : graph
238
+ A NetworkX graph. G and H must have the same node sets.
239
+
240
+ Returns
241
+ -------
242
+ D : A new graph with the same type as G.
243
+
244
+ Notes
245
+ -----
246
+ Attributes from the graph, nodes, and edges are not copied to the new
247
+ graph.
248
+
249
+ Examples
250
+ --------
251
+ >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3)])
252
+ >>> H = nx.Graph([(0, 1), (1, 2), (0, 3)])
253
+ >>> R = nx.symmetric_difference(G, H)
254
+ >>> R.nodes
255
+ NodeView((0, 1, 2, 3))
256
+ >>> R.edges
257
+ EdgeView([(0, 2), (0, 3), (1, 3)])
258
+ """
259
+ # create new graph
260
+ if not G.is_multigraph() == H.is_multigraph():
261
+ raise nx.NetworkXError("G and H must both be graphs or multigraphs.")
262
+ R = nx.create_empty_copy(G, with_data=False)
263
+
264
+ if set(G) != set(H):
265
+ raise nx.NetworkXError("Node sets of graphs not equal")
266
+
267
+ gnodes = set(G) # set of nodes in G
268
+ hnodes = set(H) # set of nodes in H
269
+ nodes = gnodes.symmetric_difference(hnodes)
270
+ R.add_nodes_from(nodes)
271
+
272
+ if G.is_multigraph():
273
+ edges = G.edges(keys=True)
274
+ else:
275
+ edges = G.edges()
276
+ # we could copy the data here but then this function doesn't
277
+ # match intersection and difference
278
+ for e in edges:
279
+ if not H.has_edge(*e):
280
+ R.add_edge(*e)
281
+
282
+ if H.is_multigraph():
283
+ edges = H.edges(keys=True)
284
+ else:
285
+ edges = H.edges()
286
+ for e in edges:
287
+ if not G.has_edge(*e):
288
+ R.add_edge(*e)
289
+ return R
290
+
291
+
292
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
293
+ def compose(G, H):
294
+ """Compose graph G with H by combining nodes and edges into a single graph.
295
+
296
+ The node sets and edges sets do not need to be disjoint.
297
+
298
+ Composing preserves the attributes of nodes and edges.
299
+ Attribute values from H take precedent over attribute values from G.
300
+
301
+ Parameters
302
+ ----------
303
+ G, H : graph
304
+ A NetworkX graph
305
+
306
+ Returns
307
+ -------
308
+ C: A new graph with the same type as G
309
+
310
+ See Also
311
+ --------
312
+ :func:`~networkx.Graph.update`
313
+ union
314
+ disjoint_union
315
+
316
+ Notes
317
+ -----
318
+ It is recommended that G and H be either both directed or both undirected.
319
+
320
+ For MultiGraphs, the edges are identified by incident nodes AND edge-key.
321
+ This can cause surprises (i.e., edge `(1, 2)` may or may not be the same
322
+ in two graphs) if you use MultiGraph without keeping track of edge keys.
323
+
324
+ If combining the attributes of common nodes is not desired, consider union(),
325
+ which raises an exception for name collisions.
326
+
327
+ Examples
328
+ --------
329
+ >>> G = nx.Graph([(0, 1), (0, 2)])
330
+ >>> H = nx.Graph([(0, 1), (1, 2)])
331
+ >>> R = nx.compose(G, H)
332
+ >>> R.nodes
333
+ NodeView((0, 1, 2))
334
+ >>> R.edges
335
+ EdgeView([(0, 1), (0, 2), (1, 2)])
336
+
337
+ By default, the attributes from `H` take precedent over attributes from `G`.
338
+ If you prefer another way of combining attributes, you can update them after the compose operation:
339
+
340
+ >>> G = nx.Graph([(0, 1, {"weight": 2.0}), (3, 0, {"weight": 100.0})])
341
+ >>> H = nx.Graph([(0, 1, {"weight": 10.0}), (1, 2, {"weight": -1.0})])
342
+ >>> nx.set_node_attributes(G, {0: "dark", 1: "light", 3: "black"}, name="color")
343
+ >>> nx.set_node_attributes(H, {0: "green", 1: "orange", 2: "yellow"}, name="color")
344
+ >>> GcomposeH = nx.compose(G, H)
345
+
346
+ Normally, color attribute values of nodes of GcomposeH come from H. We can workaround this as follows:
347
+
348
+ >>> node_data = {
349
+ ... n: G.nodes[n]["color"] + " " + H.nodes[n]["color"]
350
+ ... for n in G.nodes & H.nodes
351
+ ... }
352
+ >>> nx.set_node_attributes(GcomposeH, node_data, "color")
353
+ >>> print(GcomposeH.nodes[0]["color"])
354
+ dark green
355
+
356
+ >>> print(GcomposeH.nodes[3]["color"])
357
+ black
358
+
359
+ Similarly, we can update edge attributes after the compose operation in a way we prefer:
360
+
361
+ >>> edge_data = {
362
+ ... e: G.edges[e]["weight"] * H.edges[e]["weight"] for e in G.edges & H.edges
363
+ ... }
364
+ >>> nx.set_edge_attributes(GcomposeH, edge_data, "weight")
365
+ >>> print(GcomposeH.edges[(0, 1)]["weight"])
366
+ 20.0
367
+
368
+ >>> print(GcomposeH.edges[(3, 0)]["weight"])
369
+ 100.0
370
+ """
371
+ return nx.compose_all([G, H])
372
+
373
+
374
+ @nx._dispatchable(graphs=_G_H, preserve_all_attrs=True, returns_graph=True)
375
+ def full_join(G, H, rename=(None, None)):
376
+ """Returns the full join of graphs G and H.
377
+
378
+ Full join is the union of G and H in which all edges between
379
+ G and H are added.
380
+ The node sets of G and H must be disjoint,
381
+ otherwise an exception is raised.
382
+
383
+ Parameters
384
+ ----------
385
+ G, H : graph
386
+ A NetworkX graph
387
+
388
+ rename : tuple , default=(None, None)
389
+ Node names of G and H can be changed by specifying the tuple
390
+ rename=('G-','H-') (for example). Node "u" in G is then renamed
391
+ "G-u" and "v" in H is renamed "H-v".
392
+
393
+ Returns
394
+ -------
395
+ U : The full join graph with the same type as G.
396
+
397
+ Notes
398
+ -----
399
+ It is recommended that G and H be either both directed or both undirected.
400
+
401
+ If G is directed, then edges from G to H are added as well as from H to G.
402
+
403
+ Note that full_join() does not produce parallel edges for MultiGraphs.
404
+
405
+ The full join operation of graphs G and H is the same as getting
406
+ their complement, performing a disjoint union, and finally getting
407
+ the complement of the resulting graph.
408
+
409
+ Graph, edge, and node attributes are propagated from G and H
410
+ to the union graph. If a graph attribute is present in both
411
+ G and H the value from H is used.
412
+
413
+ Examples
414
+ --------
415
+ >>> G = nx.Graph([(0, 1), (0, 2)])
416
+ >>> H = nx.Graph([(3, 4)])
417
+ >>> R = nx.full_join(G, H, rename=("G", "H"))
418
+ >>> R.nodes
419
+ NodeView(('G0', 'G1', 'G2', 'H3', 'H4'))
420
+ >>> R.edges
421
+ EdgeView([('G0', 'G1'), ('G0', 'G2'), ('G0', 'H3'), ('G0', 'H4'), ('G1', 'H3'), ('G1', 'H4'), ('G2', 'H3'), ('G2', 'H4'), ('H3', 'H4')])
422
+
423
+ See Also
424
+ --------
425
+ union
426
+ disjoint_union
427
+ """
428
+ R = union(G, H, rename)
429
+
430
+ def add_prefix(graph, prefix):
431
+ if prefix is None:
432
+ return graph
433
+
434
+ def label(x):
435
+ return f"{prefix}{x}"
436
+
437
+ return nx.relabel_nodes(graph, label)
438
+
439
+ G = add_prefix(G, rename[0])
440
+ H = add_prefix(H, rename[1])
441
+
442
+ for i in G:
443
+ for j in H:
444
+ R.add_edge(i, j)
445
+ if R.is_directed():
446
+ for i in H:
447
+ for j in G:
448
+ R.add_edge(i, j)
449
+
450
+ return R
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/product.py ADDED
@@ -0,0 +1,633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Graph products.
3
+ """
4
+
5
+ from itertools import product
6
+
7
+ import networkx as nx
8
+ from networkx.utils import not_implemented_for
9
+
10
+ __all__ = [
11
+ "tensor_product",
12
+ "cartesian_product",
13
+ "lexicographic_product",
14
+ "strong_product",
15
+ "power",
16
+ "rooted_product",
17
+ "corona_product",
18
+ "modular_product",
19
+ ]
20
+ _G_H = {"G": 0, "H": 1}
21
+
22
+
23
+ def _dict_product(d1, d2):
24
+ return {k: (d1.get(k), d2.get(k)) for k in set(d1) | set(d2)}
25
+
26
+
27
+ # Generators for producing graph products
28
+ def _node_product(G, H):
29
+ for u, v in product(G, H):
30
+ yield ((u, v), _dict_product(G.nodes[u], H.nodes[v]))
31
+
32
+
33
+ def _directed_edges_cross_edges(G, H):
34
+ if not G.is_multigraph() and not H.is_multigraph():
35
+ for u, v, c in G.edges(data=True):
36
+ for x, y, d in H.edges(data=True):
37
+ yield (u, x), (v, y), _dict_product(c, d)
38
+ if not G.is_multigraph() and H.is_multigraph():
39
+ for u, v, c in G.edges(data=True):
40
+ for x, y, k, d in H.edges(data=True, keys=True):
41
+ yield (u, x), (v, y), k, _dict_product(c, d)
42
+ if G.is_multigraph() and not H.is_multigraph():
43
+ for u, v, k, c in G.edges(data=True, keys=True):
44
+ for x, y, d in H.edges(data=True):
45
+ yield (u, x), (v, y), k, _dict_product(c, d)
46
+ if G.is_multigraph() and H.is_multigraph():
47
+ for u, v, j, c in G.edges(data=True, keys=True):
48
+ for x, y, k, d in H.edges(data=True, keys=True):
49
+ yield (u, x), (v, y), (j, k), _dict_product(c, d)
50
+
51
+
52
+ def _undirected_edges_cross_edges(G, H):
53
+ if not G.is_multigraph() and not H.is_multigraph():
54
+ for u, v, c in G.edges(data=True):
55
+ for x, y, d in H.edges(data=True):
56
+ yield (v, x), (u, y), _dict_product(c, d)
57
+ if not G.is_multigraph() and H.is_multigraph():
58
+ for u, v, c in G.edges(data=True):
59
+ for x, y, k, d in H.edges(data=True, keys=True):
60
+ yield (v, x), (u, y), k, _dict_product(c, d)
61
+ if G.is_multigraph() and not H.is_multigraph():
62
+ for u, v, k, c in G.edges(data=True, keys=True):
63
+ for x, y, d in H.edges(data=True):
64
+ yield (v, x), (u, y), k, _dict_product(c, d)
65
+ if G.is_multigraph() and H.is_multigraph():
66
+ for u, v, j, c in G.edges(data=True, keys=True):
67
+ for x, y, k, d in H.edges(data=True, keys=True):
68
+ yield (v, x), (u, y), (j, k), _dict_product(c, d)
69
+
70
+
71
+ def _edges_cross_nodes(G, H):
72
+ if G.is_multigraph():
73
+ for u, v, k, d in G.edges(data=True, keys=True):
74
+ for x in H:
75
+ yield (u, x), (v, x), k, d
76
+ else:
77
+ for u, v, d in G.edges(data=True):
78
+ for x in H:
79
+ if H.is_multigraph():
80
+ yield (u, x), (v, x), None, d
81
+ else:
82
+ yield (u, x), (v, x), d
83
+
84
+
85
+ def _nodes_cross_edges(G, H):
86
+ if H.is_multigraph():
87
+ for x in G:
88
+ for u, v, k, d in H.edges(data=True, keys=True):
89
+ yield (x, u), (x, v), k, d
90
+ else:
91
+ for x in G:
92
+ for u, v, d in H.edges(data=True):
93
+ if G.is_multigraph():
94
+ yield (x, u), (x, v), None, d
95
+ else:
96
+ yield (x, u), (x, v), d
97
+
98
+
99
+ def _edges_cross_nodes_and_nodes(G, H):
100
+ if G.is_multigraph():
101
+ for u, v, k, d in G.edges(data=True, keys=True):
102
+ for x in H:
103
+ for y in H:
104
+ yield (u, x), (v, y), k, d
105
+ else:
106
+ for u, v, d in G.edges(data=True):
107
+ for x in H:
108
+ for y in H:
109
+ if H.is_multigraph():
110
+ yield (u, x), (v, y), None, d
111
+ else:
112
+ yield (u, x), (v, y), d
113
+
114
+
115
+ def _init_product_graph(G, H):
116
+ if G.is_directed() != H.is_directed():
117
+ msg = "G and H must be both directed or both undirected"
118
+ raise nx.NetworkXError(msg)
119
+ if G.is_multigraph() or H.is_multigraph():
120
+ GH = nx.MultiGraph()
121
+ else:
122
+ GH = nx.Graph()
123
+ if G.is_directed():
124
+ GH = GH.to_directed()
125
+ return GH
126
+
127
+
128
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
129
+ def tensor_product(G, H):
130
+ r"""Returns the tensor product of G and H.
131
+
132
+ The tensor product $P$ of the graphs $G$ and $H$ has a node set that
133
+ is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
134
+ $P$ has an edge $((u,v), (x,y))$ if and only if $(u,x)$ is an edge in $G$
135
+ and $(v,y)$ is an edge in $H$.
136
+
137
+ Tensor product is sometimes also referred to as the categorical product,
138
+ direct product, cardinal product or conjunction.
139
+
140
+
141
+ Parameters
142
+ ----------
143
+ G, H: graphs
144
+ Networkx graphs.
145
+
146
+ Returns
147
+ -------
148
+ P: NetworkX graph
149
+ The tensor product of G and H. P will be a multi-graph if either G
150
+ or H is a multi-graph, will be a directed if G and H are directed,
151
+ and undirected if G and H are undirected.
152
+
153
+ Raises
154
+ ------
155
+ NetworkXError
156
+ If G and H are not both directed or both undirected.
157
+
158
+ Notes
159
+ -----
160
+ Node attributes in P are two-tuple of the G and H node attributes.
161
+ Missing attributes are assigned None.
162
+
163
+ Examples
164
+ --------
165
+ >>> G = nx.Graph()
166
+ >>> H = nx.Graph()
167
+ >>> G.add_node(0, a1=True)
168
+ >>> H.add_node("a", a2="Spam")
169
+ >>> P = nx.tensor_product(G, H)
170
+ >>> list(P)
171
+ [(0, 'a')]
172
+
173
+ Edge attributes and edge keys (for multigraphs) are also copied to the
174
+ new product graph
175
+ """
176
+ GH = _init_product_graph(G, H)
177
+ GH.add_nodes_from(_node_product(G, H))
178
+ GH.add_edges_from(_directed_edges_cross_edges(G, H))
179
+ if not GH.is_directed():
180
+ GH.add_edges_from(_undirected_edges_cross_edges(G, H))
181
+ return GH
182
+
183
+
184
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
185
+ def cartesian_product(G, H):
186
+ r"""Returns the Cartesian product of G and H.
187
+
188
+ The Cartesian product $P$ of the graphs $G$ and $H$ has a node set that
189
+ is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
190
+ $P$ has an edge $((u,v),(x,y))$ if and only if either $u$ is equal to $x$
191
+ and both $v$ and $y$ are adjacent in $H$ or if $v$ is equal to $y$ and
192
+ both $u$ and $x$ are adjacent in $G$.
193
+
194
+ Parameters
195
+ ----------
196
+ G, H: graphs
197
+ Networkx graphs.
198
+
199
+ Returns
200
+ -------
201
+ P: NetworkX graph
202
+ The Cartesian product of G and H. P will be a multi-graph if either G
203
+ or H is a multi-graph. Will be a directed if G and H are directed,
204
+ and undirected if G and H are undirected.
205
+
206
+ Raises
207
+ ------
208
+ NetworkXError
209
+ If G and H are not both directed or both undirected.
210
+
211
+ Notes
212
+ -----
213
+ Node attributes in P are two-tuple of the G and H node attributes.
214
+ Missing attributes are assigned None.
215
+
216
+ Examples
217
+ --------
218
+ >>> G = nx.Graph()
219
+ >>> H = nx.Graph()
220
+ >>> G.add_node(0, a1=True)
221
+ >>> H.add_node("a", a2="Spam")
222
+ >>> P = nx.cartesian_product(G, H)
223
+ >>> list(P)
224
+ [(0, 'a')]
225
+
226
+ Edge attributes and edge keys (for multigraphs) are also copied to the
227
+ new product graph
228
+ """
229
+ GH = _init_product_graph(G, H)
230
+ GH.add_nodes_from(_node_product(G, H))
231
+ GH.add_edges_from(_edges_cross_nodes(G, H))
232
+ GH.add_edges_from(_nodes_cross_edges(G, H))
233
+ return GH
234
+
235
+
236
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
237
+ def lexicographic_product(G, H):
238
+ r"""Returns the lexicographic product of G and H.
239
+
240
+ The lexicographical product $P$ of the graphs $G$ and $H$ has a node set
241
+ that is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
242
+ $P$ has an edge $((u,v), (x,y))$ if and only if $(u,v)$ is an edge in $G$
243
+ or $u==v$ and $(x,y)$ is an edge in $H$.
244
+
245
+ Parameters
246
+ ----------
247
+ G, H: graphs
248
+ Networkx graphs.
249
+
250
+ Returns
251
+ -------
252
+ P: NetworkX graph
253
+ The Cartesian product of G and H. P will be a multi-graph if either G
254
+ or H is a multi-graph. Will be a directed if G and H are directed,
255
+ and undirected if G and H are undirected.
256
+
257
+ Raises
258
+ ------
259
+ NetworkXError
260
+ If G and H are not both directed or both undirected.
261
+
262
+ Notes
263
+ -----
264
+ Node attributes in P are two-tuple of the G and H node attributes.
265
+ Missing attributes are assigned None.
266
+
267
+ Examples
268
+ --------
269
+ >>> G = nx.Graph()
270
+ >>> H = nx.Graph()
271
+ >>> G.add_node(0, a1=True)
272
+ >>> H.add_node("a", a2="Spam")
273
+ >>> P = nx.lexicographic_product(G, H)
274
+ >>> list(P)
275
+ [(0, 'a')]
276
+
277
+ Edge attributes and edge keys (for multigraphs) are also copied to the
278
+ new product graph
279
+ """
280
+ GH = _init_product_graph(G, H)
281
+ GH.add_nodes_from(_node_product(G, H))
282
+ # Edges in G regardless of H designation
283
+ GH.add_edges_from(_edges_cross_nodes_and_nodes(G, H))
284
+ # For each x in G, only if there is an edge in H
285
+ GH.add_edges_from(_nodes_cross_edges(G, H))
286
+ return GH
287
+
288
+
289
+ @nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
290
+ def strong_product(G, H):
291
+ r"""Returns the strong product of G and H.
292
+
293
+ The strong product $P$ of the graphs $G$ and $H$ has a node set that
294
+ is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
295
+ $P$ has an edge $((u,x), (v,y))$ if any of the following conditions
296
+ are met:
297
+
298
+ - $u=v$ and $(x,y)$ is an edge in $H$
299
+ - $x=y$ and $(u,v)$ is an edge in $G$
300
+ - $(u,v)$ is an edge in $G$ and $(x,y)$ is an edge in $H$
301
+
302
+ Parameters
303
+ ----------
304
+ G, H: graphs
305
+ Networkx graphs.
306
+
307
+ Returns
308
+ -------
309
+ P: NetworkX graph
310
+ The Cartesian product of G and H. P will be a multi-graph if either G
311
+ or H is a multi-graph. Will be a directed if G and H are directed,
312
+ and undirected if G and H are undirected.
313
+
314
+ Raises
315
+ ------
316
+ NetworkXError
317
+ If G and H are not both directed or both undirected.
318
+
319
+ Notes
320
+ -----
321
+ Node attributes in P are two-tuple of the G and H node attributes.
322
+ Missing attributes are assigned None.
323
+
324
+ Examples
325
+ --------
326
+ >>> G = nx.Graph()
327
+ >>> H = nx.Graph()
328
+ >>> G.add_node(0, a1=True)
329
+ >>> H.add_node("a", a2="Spam")
330
+ >>> P = nx.strong_product(G, H)
331
+ >>> list(P)
332
+ [(0, 'a')]
333
+
334
+ Edge attributes and edge keys (for multigraphs) are also copied to the
335
+ new product graph
336
+ """
337
+ GH = _init_product_graph(G, H)
338
+ GH.add_nodes_from(_node_product(G, H))
339
+ GH.add_edges_from(_nodes_cross_edges(G, H))
340
+ GH.add_edges_from(_edges_cross_nodes(G, H))
341
+ GH.add_edges_from(_directed_edges_cross_edges(G, H))
342
+ if not GH.is_directed():
343
+ GH.add_edges_from(_undirected_edges_cross_edges(G, H))
344
+ return GH
345
+
346
+
347
+ @not_implemented_for("directed")
348
+ @not_implemented_for("multigraph")
349
+ @nx._dispatchable(returns_graph=True)
350
+ def power(G, k):
351
+ """Returns the specified power of a graph.
352
+
353
+ The $k$th power of a simple graph $G$, denoted $G^k$, is a
354
+ graph on the same set of nodes in which two distinct nodes $u$ and
355
+ $v$ are adjacent in $G^k$ if and only if the shortest path
356
+ distance between $u$ and $v$ in $G$ is at most $k$.
357
+
358
+ Parameters
359
+ ----------
360
+ G : graph
361
+ A NetworkX simple graph object.
362
+
363
+ k : positive integer
364
+ The power to which to raise the graph `G`.
365
+
366
+ Returns
367
+ -------
368
+ NetworkX simple graph
369
+ `G` to the power `k`.
370
+
371
+ Raises
372
+ ------
373
+ ValueError
374
+ If the exponent `k` is not positive.
375
+
376
+ NetworkXNotImplemented
377
+ If `G` is not a simple graph.
378
+
379
+ Examples
380
+ --------
381
+ The number of edges will never decrease when taking successive
382
+ powers:
383
+
384
+ >>> G = nx.path_graph(4)
385
+ >>> list(nx.power(G, 2).edges)
386
+ [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
387
+ >>> list(nx.power(G, 3).edges)
388
+ [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
389
+
390
+ The `k` th power of a cycle graph on *n* nodes is the complete graph
391
+ on *n* nodes, if `k` is at least ``n // 2``:
392
+
393
+ >>> G = nx.cycle_graph(5)
394
+ >>> H = nx.complete_graph(5)
395
+ >>> nx.is_isomorphic(nx.power(G, 2), H)
396
+ True
397
+ >>> G = nx.cycle_graph(8)
398
+ >>> H = nx.complete_graph(8)
399
+ >>> nx.is_isomorphic(nx.power(G, 4), H)
400
+ True
401
+
402
+ References
403
+ ----------
404
+ .. [1] J. A. Bondy, U. S. R. Murty, *Graph Theory*. Springer, 2008.
405
+
406
+ Notes
407
+ -----
408
+ This definition of "power graph" comes from Exercise 3.1.6 of
409
+ *Graph Theory* by Bondy and Murty [1]_.
410
+
411
+ """
412
+ if k <= 0:
413
+ raise ValueError("k must be a positive integer")
414
+ H = nx.Graph()
415
+ H.add_nodes_from(G)
416
+ # update BFS code to ignore self loops.
417
+ for n in G:
418
+ seen = {} # level (number of hops) when seen in BFS
419
+ level = 1 # the current level
420
+ nextlevel = G[n]
421
+ while nextlevel:
422
+ thislevel = nextlevel # advance to next level
423
+ nextlevel = {} # and start a new list (fringe)
424
+ for v in thislevel:
425
+ if v == n: # avoid self loop
426
+ continue
427
+ if v not in seen:
428
+ seen[v] = level # set the level of vertex v
429
+ nextlevel.update(G[v]) # add neighbors of v
430
+ if k <= level:
431
+ break
432
+ level += 1
433
+ H.add_edges_from((n, nbr) for nbr in seen)
434
+ return H
435
+
436
+
437
+ @not_implemented_for("multigraph")
438
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
439
+ def rooted_product(G, H, root):
440
+ """Return the rooted product of graphs G and H rooted at root in H.
441
+
442
+ A new graph is constructed representing the rooted product of
443
+ the inputted graphs, G and H, with a root in H.
444
+ A rooted product duplicates H for each nodes in G with the root
445
+ of H corresponding to the node in G. Nodes are renamed as the direct
446
+ product of G and H. The result is a subgraph of the cartesian product.
447
+
448
+ Parameters
449
+ ----------
450
+ G,H : graph
451
+ A NetworkX graph
452
+ root : node
453
+ A node in H
454
+
455
+ Returns
456
+ -------
457
+ R : The rooted product of G and H with a specified root in H
458
+
459
+ Notes
460
+ -----
461
+ The nodes of R are the Cartesian Product of the nodes of G and H.
462
+ The nodes of G and H are not relabeled.
463
+ """
464
+ if root not in H:
465
+ raise nx.NodeNotFound("root must be a vertex in H")
466
+
467
+ R = nx.Graph()
468
+ R.add_nodes_from(product(G, H))
469
+
470
+ R.add_edges_from(((e[0], root), (e[1], root)) for e in G.edges())
471
+ R.add_edges_from(((g, e[0]), (g, e[1])) for g in G for e in H.edges())
472
+
473
+ return R
474
+
475
+
476
+ @not_implemented_for("directed")
477
+ @not_implemented_for("multigraph")
478
+ @nx._dispatchable(graphs=_G_H, returns_graph=True)
479
+ def corona_product(G, H):
480
+ r"""Returns the Corona product of G and H.
481
+
482
+ The corona product of $G$ and $H$ is the graph $C = G \circ H$ obtained by
483
+ taking one copy of $G$, called the center graph, $|V(G)|$ copies of $H$,
484
+ called the outer graph, and making the $i$-th vertex of $G$ adjacent to
485
+ every vertex of the $i$-th copy of $H$, where $1 ≤ i ≤ |V(G)|$.
486
+
487
+ Parameters
488
+ ----------
489
+ G, H: NetworkX graphs
490
+ The graphs to take the carona product of.
491
+ `G` is the center graph and `H` is the outer graph
492
+
493
+ Returns
494
+ -------
495
+ C: NetworkX graph
496
+ The Corona product of G and H.
497
+
498
+ Raises
499
+ ------
500
+ NetworkXError
501
+ If G and H are not both directed or both undirected.
502
+
503
+ Examples
504
+ --------
505
+ >>> G = nx.cycle_graph(4)
506
+ >>> H = nx.path_graph(2)
507
+ >>> C = nx.corona_product(G, H)
508
+ >>> list(C)
509
+ [0, 1, 2, 3, (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
510
+ >>> print(C)
511
+ Graph with 12 nodes and 16 edges
512
+
513
+ References
514
+ ----------
515
+ [1] M. Tavakoli, F. Rahbarnia, and A. R. Ashrafi,
516
+ "Studying the corona product of graphs under some graph invariants,"
517
+ Transactions on Combinatorics, vol. 3, no. 3, pp. 43–49, Sep. 2014,
518
+ doi: 10.22108/toc.2014.5542.
519
+ [2] A. Faraji, "Corona Product in Graph Theory," Ali Faraji, May 11, 2021.
520
+ https://blog.alifaraji.ir/math/graph-theory/corona-product.html (accessed Dec. 07, 2021).
521
+ """
522
+ GH = _init_product_graph(G, H)
523
+ GH.add_nodes_from(G)
524
+ GH.add_edges_from(G.edges)
525
+
526
+ for G_node in G:
527
+ # copy nodes of H in GH, call it H_i
528
+ GH.add_nodes_from((G_node, v) for v in H)
529
+
530
+ # copy edges of H_i based on H
531
+ GH.add_edges_from(
532
+ ((G_node, e0), (G_node, e1), d) for e0, e1, d in H.edges.data()
533
+ )
534
+
535
+ # creating new edges between H_i and a G's node
536
+ GH.add_edges_from((G_node, (G_node, H_node)) for H_node in H)
537
+
538
+ return GH
539
+
540
+
541
+ @nx._dispatchable(
542
+ graphs=_G_H, preserve_edge_attrs=True, preserve_node_attrs=True, returns_graph=True
543
+ )
544
+ def modular_product(G, H):
545
+ r"""Returns the Modular product of G and H.
546
+
547
+ The modular product of `G` and `H` is the graph $M = G \nabla H$,
548
+ consisting of the node set $V(M) = V(G) \times V(H)$ that is the Cartesian
549
+ product of the node sets of `G` and `H`. Further, M contains an edge ((u, v), (x, y)):
550
+
551
+ - if u is adjacent to x in `G` and v is adjacent to y in `H`, or
552
+ - if u is not adjacent to x in `G` and v is not adjacent to y in `H`.
553
+
554
+ More formally::
555
+
556
+ E(M) = {((u, v), (x, y)) | ((u, x) in E(G) and (v, y) in E(H)) or
557
+ ((u, x) not in E(G) and (v, y) not in E(H))}
558
+
559
+ Parameters
560
+ ----------
561
+ G, H: NetworkX graphs
562
+ The graphs to take the modular product of.
563
+
564
+ Returns
565
+ -------
566
+ M: NetworkX graph
567
+ The Modular product of `G` and `H`.
568
+
569
+ Raises
570
+ ------
571
+ NetworkXNotImplemented
572
+ If `G` is not a simple graph.
573
+
574
+ Examples
575
+ --------
576
+ >>> G = nx.cycle_graph(4)
577
+ >>> H = nx.path_graph(2)
578
+ >>> M = nx.modular_product(G, H)
579
+ >>> list(M)
580
+ [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
581
+ >>> print(M)
582
+ Graph with 8 nodes and 8 edges
583
+
584
+ Notes
585
+ -----
586
+ The *modular product* is defined in [1]_ and was first
587
+ introduced as the *weak modular product*.
588
+
589
+ The modular product reduces the problem of counting isomorphic subgraphs
590
+ in `G` and `H` to the problem of counting cliques in M. The subgraphs of
591
+ `G` and `H` that are induced by the nodes of a clique in M are
592
+ isomorphic [2]_ [3]_.
593
+
594
+ References
595
+ ----------
596
+ .. [1] R. Hammack, W. Imrich, and S. Klavžar,
597
+ "Handbook of Product Graphs", CRC Press, 2011.
598
+
599
+ .. [2] H. G. Barrow and R. M. Burstall,
600
+ "Subgraph isomorphism, matching relational structures and maximal
601
+ cliques", Information Processing Letters, vol. 4, issue 4, pp. 83-84,
602
+ 1976, https://doi.org/10.1016/0020-0190(76)90049-1.
603
+
604
+ .. [3] V. G. Vizing, "Reduction of the problem of isomorphism and isomorphic
605
+ entrance to the task of finding the nondensity of a graph." Proc. Third
606
+ All-Union Conference on Problems of Theoretical Cybernetics. 1974.
607
+ """
608
+ if G.is_directed() or H.is_directed():
609
+ raise nx.NetworkXNotImplemented(
610
+ "Modular product not implemented for directed graphs"
611
+ )
612
+ if G.is_multigraph() or H.is_multigraph():
613
+ raise nx.NetworkXNotImplemented(
614
+ "Modular product not implemented for multigraphs"
615
+ )
616
+
617
+ GH = _init_product_graph(G, H)
618
+ GH.add_nodes_from(_node_product(G, H))
619
+
620
+ for u, v, c in G.edges(data=True):
621
+ for x, y, d in H.edges(data=True):
622
+ GH.add_edge((u, x), (v, y), **_dict_product(c, d))
623
+ GH.add_edge((v, x), (u, y), **_dict_product(c, d))
624
+
625
+ G = nx.complement(G)
626
+ H = nx.complement(H)
627
+
628
+ for u, v, c in G.edges(data=True):
629
+ for x, y, d in H.edges(data=True):
630
+ GH.add_edge((u, x), (v, y), **_dict_product(c, d))
631
+ GH.add_edge((v, x), (u, y), **_dict_product(c, d))
632
+
633
+ return GH
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_all.cpython-310.pyc ADDED
Binary file (7.84 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_binary.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_product.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/test_unary.cpython-310.pyc ADDED
Binary file (1.39 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/algorithms/operators/unary.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unary operations on graphs"""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["complement", "reverse"]
6
+
7
+
8
+ @nx._dispatchable(returns_graph=True)
9
+ def complement(G):
10
+ """Returns the graph complement of G.
11
+
12
+ Parameters
13
+ ----------
14
+ G : graph
15
+ A NetworkX graph
16
+
17
+ Returns
18
+ -------
19
+ GC : A new graph.
20
+
21
+ Notes
22
+ -----
23
+ Note that `complement` does not create self-loops and also
24
+ does not produce parallel edges for MultiGraphs.
25
+
26
+ Graph, node, and edge data are not propagated to the new graph.
27
+
28
+ Examples
29
+ --------
30
+ >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
31
+ >>> G_complement = nx.complement(G)
32
+ >>> G_complement.edges() # This shows the edges of the complemented graph
33
+ EdgeView([(1, 4), (1, 5), (2, 4), (2, 5), (4, 5)])
34
+
35
+ """
36
+ R = G.__class__()
37
+ R.add_nodes_from(G)
38
+ R.add_edges_from(
39
+ ((n, n2) for n, nbrs in G.adjacency() for n2 in G if n2 not in nbrs if n != n2)
40
+ )
41
+ return R
42
+
43
+
44
+ @nx._dispatchable(returns_graph=True)
45
+ def reverse(G, copy=True):
46
+ """Returns the reverse directed graph of G.
47
+
48
+ Parameters
49
+ ----------
50
+ G : directed graph
51
+ A NetworkX directed graph
52
+ copy : bool
53
+ If True, then a new graph is returned. If False, then the graph is
54
+ reversed in place.
55
+
56
+ Returns
57
+ -------
58
+ H : directed graph
59
+ The reversed G.
60
+
61
+ Raises
62
+ ------
63
+ NetworkXError
64
+ If graph is undirected.
65
+
66
+ Examples
67
+ --------
68
+ >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
69
+ >>> G_reversed = nx.reverse(G)
70
+ >>> G_reversed.edges()
71
+ OutEdgeView([(2, 1), (3, 1), (3, 2), (4, 3), (5, 3)])
72
+
73
+ """
74
+ if not G.is_directed():
75
+ raise nx.NetworkXError("Cannot reverse an undirected graph.")
76
+ else:
77
+ return G.reverse(copy=copy)
wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (294 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc ADDED
Binary file (22.2 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/layout.py ADDED
@@ -0,0 +1,1630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ******
3
+ Layout
4
+ ******
5
+
6
+ Node positioning algorithms for graph drawing.
7
+
8
+ For `random_layout()` the possible resulting shape
9
+ is a square of side [0, scale] (default: [0, 1])
10
+ Changing `center` shifts the layout by that amount.
11
+
12
+ For the other layout routines, the extent is
13
+ [center - scale, center + scale] (default: [-1, 1]).
14
+
15
+ Warning: Most layout routines have only been tested in 2-dimensions.
16
+
17
+ """
18
+
19
+ import networkx as nx
20
+ from networkx.utils import np_random_state
21
+
22
+ __all__ = [
23
+ "bipartite_layout",
24
+ "circular_layout",
25
+ "forceatlas2_layout",
26
+ "kamada_kawai_layout",
27
+ "random_layout",
28
+ "rescale_layout",
29
+ "rescale_layout_dict",
30
+ "shell_layout",
31
+ "spring_layout",
32
+ "spectral_layout",
33
+ "planar_layout",
34
+ "fruchterman_reingold_layout",
35
+ "spiral_layout",
36
+ "multipartite_layout",
37
+ "bfs_layout",
38
+ "arf_layout",
39
+ ]
40
+
41
+
42
+ def _process_params(G, center, dim):
43
+ # Some boilerplate code.
44
+ import numpy as np
45
+
46
+ if not isinstance(G, nx.Graph):
47
+ empty_graph = nx.Graph()
48
+ empty_graph.add_nodes_from(G)
49
+ G = empty_graph
50
+
51
+ if center is None:
52
+ center = np.zeros(dim)
53
+ else:
54
+ center = np.asarray(center)
55
+
56
+ if len(center) != dim:
57
+ msg = "length of center coordinates must match dimension of layout"
58
+ raise ValueError(msg)
59
+
60
+ return G, center
61
+
62
+
63
+ @np_random_state(3)
64
+ def random_layout(G, center=None, dim=2, seed=None):
65
+ """Position nodes uniformly at random in the unit square.
66
+
67
+ For every node, a position is generated by choosing each of dim
68
+ coordinates uniformly at random on the interval [0.0, 1.0).
69
+
70
+ NumPy (http://scipy.org) is required for this function.
71
+
72
+ Parameters
73
+ ----------
74
+ G : NetworkX graph or list of nodes
75
+ A position will be assigned to every node in G.
76
+
77
+ center : array-like or None
78
+ Coordinate pair around which to center the layout.
79
+
80
+ dim : int
81
+ Dimension of layout.
82
+
83
+ seed : int, RandomState instance or None optional (default=None)
84
+ Set the random state for deterministic node layouts.
85
+ If int, `seed` is the seed used by the random number generator,
86
+ if numpy.random.RandomState instance, `seed` is the random
87
+ number generator,
88
+ if None, the random number generator is the RandomState instance used
89
+ by numpy.random.
90
+
91
+ Returns
92
+ -------
93
+ pos : dict
94
+ A dictionary of positions keyed by node
95
+
96
+ Examples
97
+ --------
98
+ >>> G = nx.lollipop_graph(4, 3)
99
+ >>> pos = nx.random_layout(G)
100
+
101
+ """
102
+ import numpy as np
103
+
104
+ G, center = _process_params(G, center, dim)
105
+ pos = seed.rand(len(G), dim) + center
106
+ pos = pos.astype(np.float32)
107
+ pos = dict(zip(G, pos))
108
+
109
+ return pos
110
+
111
+
112
+ def circular_layout(G, scale=1, center=None, dim=2):
113
+ # dim=2 only
114
+ """Position nodes on a circle.
115
+
116
+ Parameters
117
+ ----------
118
+ G : NetworkX graph or list of nodes
119
+ A position will be assigned to every node in G.
120
+
121
+ scale : number (default: 1)
122
+ Scale factor for positions.
123
+
124
+ center : array-like or None
125
+ Coordinate pair around which to center the layout.
126
+
127
+ dim : int
128
+ Dimension of layout.
129
+ If dim>2, the remaining dimensions are set to zero
130
+ in the returned positions.
131
+ If dim<2, a ValueError is raised.
132
+
133
+ Returns
134
+ -------
135
+ pos : dict
136
+ A dictionary of positions keyed by node
137
+
138
+ Raises
139
+ ------
140
+ ValueError
141
+ If dim < 2
142
+
143
+ Examples
144
+ --------
145
+ >>> G = nx.path_graph(4)
146
+ >>> pos = nx.circular_layout(G)
147
+
148
+ Notes
149
+ -----
150
+ This algorithm currently only works in two dimensions and does not
151
+ try to minimize edge crossings.
152
+
153
+ """
154
+ import numpy as np
155
+
156
+ if dim < 2:
157
+ raise ValueError("cannot handle dimensions < 2")
158
+
159
+ G, center = _process_params(G, center, dim)
160
+
161
+ paddims = max(0, (dim - 2))
162
+
163
+ if len(G) == 0:
164
+ pos = {}
165
+ elif len(G) == 1:
166
+ pos = {nx.utils.arbitrary_element(G): center}
167
+ else:
168
+ # Discard the extra angle since it matches 0 radians.
169
+ theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
170
+ theta = theta.astype(np.float32)
171
+ pos = np.column_stack(
172
+ [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
173
+ )
174
+ pos = rescale_layout(pos, scale=scale) + center
175
+ pos = dict(zip(G, pos))
176
+
177
+ return pos
178
+
179
+
180
+ def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2):
181
+ """Position nodes in concentric circles.
182
+
183
+ Parameters
184
+ ----------
185
+ G : NetworkX graph or list of nodes
186
+ A position will be assigned to every node in G.
187
+
188
+ nlist : list of lists
189
+ List of node lists for each shell.
190
+
191
+ rotate : angle in radians (default=pi/len(nlist))
192
+ Angle by which to rotate the starting position of each shell
193
+ relative to the starting position of the previous shell.
194
+ To recreate behavior before v2.5 use rotate=0.
195
+
196
+ scale : number (default: 1)
197
+ Scale factor for positions.
198
+
199
+ center : array-like or None
200
+ Coordinate pair around which to center the layout.
201
+
202
+ dim : int
203
+ Dimension of layout, currently only dim=2 is supported.
204
+ Other dimension values result in a ValueError.
205
+
206
+ Returns
207
+ -------
208
+ pos : dict
209
+ A dictionary of positions keyed by node
210
+
211
+ Raises
212
+ ------
213
+ ValueError
214
+ If dim != 2
215
+
216
+ Examples
217
+ --------
218
+ >>> G = nx.path_graph(4)
219
+ >>> shells = [[0], [1, 2, 3]]
220
+ >>> pos = nx.shell_layout(G, shells)
221
+
222
+ Notes
223
+ -----
224
+ This algorithm currently only works in two dimensions and does not
225
+ try to minimize edge crossings.
226
+
227
+ """
228
+ import numpy as np
229
+
230
+ if dim != 2:
231
+ raise ValueError("can only handle 2 dimensions")
232
+
233
+ G, center = _process_params(G, center, dim)
234
+
235
+ if len(G) == 0:
236
+ return {}
237
+ if len(G) == 1:
238
+ return {nx.utils.arbitrary_element(G): center}
239
+
240
+ if nlist is None:
241
+ # draw the whole graph in one shell
242
+ nlist = [list(G)]
243
+
244
+ radius_bump = scale / len(nlist)
245
+
246
+ if len(nlist[0]) == 1:
247
+ # single node at center
248
+ radius = 0.0
249
+ else:
250
+ # else start at r=1
251
+ radius = radius_bump
252
+
253
+ if rotate is None:
254
+ rotate = np.pi / len(nlist)
255
+ first_theta = rotate
256
+ npos = {}
257
+ for nodes in nlist:
258
+ # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
259
+ theta = (
260
+ np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
261
+ + first_theta
262
+ )
263
+ pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
264
+ npos.update(zip(nodes, pos))
265
+ radius += radius_bump
266
+ first_theta += rotate
267
+
268
+ return npos
269
+
270
+
271
+ def bipartite_layout(
272
+ G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3
273
+ ):
274
+ """Position nodes in two straight lines.
275
+
276
+ Parameters
277
+ ----------
278
+ G : NetworkX graph or list of nodes
279
+ A position will be assigned to every node in G.
280
+
281
+ nodes : list or container
282
+ Nodes in one node set of the bipartite graph.
283
+ This set will be placed on left or top.
284
+
285
+ align : string (default='vertical')
286
+ The alignment of nodes. Vertical or horizontal.
287
+
288
+ scale : number (default: 1)
289
+ Scale factor for positions.
290
+
291
+ center : array-like or None
292
+ Coordinate pair around which to center the layout.
293
+
294
+ aspect_ratio : number (default=4/3):
295
+ The ratio of the width to the height of the layout.
296
+
297
+ Returns
298
+ -------
299
+ pos : dict
300
+ A dictionary of positions keyed by node.
301
+
302
+ Examples
303
+ --------
304
+ >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
305
+ >>> top = nx.bipartite.sets(G)[0]
306
+ >>> pos = nx.bipartite_layout(G, top)
307
+
308
+ Notes
309
+ -----
310
+ This algorithm currently only works in two dimensions and does not
311
+ try to minimize edge crossings.
312
+
313
+ """
314
+
315
+ import numpy as np
316
+
317
+ if align not in ("vertical", "horizontal"):
318
+ msg = "align must be either vertical or horizontal."
319
+ raise ValueError(msg)
320
+
321
+ G, center = _process_params(G, center=center, dim=2)
322
+ if len(G) == 0:
323
+ return {}
324
+
325
+ height = 1
326
+ width = aspect_ratio * height
327
+ offset = (width / 2, height / 2)
328
+
329
+ top = dict.fromkeys(nodes)
330
+ bottom = [v for v in G if v not in top]
331
+ nodes = list(top) + bottom
332
+
333
+ left_xs = np.repeat(0, len(top))
334
+ right_xs = np.repeat(width, len(bottom))
335
+ left_ys = np.linspace(0, height, len(top))
336
+ right_ys = np.linspace(0, height, len(bottom))
337
+
338
+ top_pos = np.column_stack([left_xs, left_ys]) - offset
339
+ bottom_pos = np.column_stack([right_xs, right_ys]) - offset
340
+
341
+ pos = np.concatenate([top_pos, bottom_pos])
342
+ pos = rescale_layout(pos, scale=scale) + center
343
+ if align == "horizontal":
344
+ pos = pos[:, ::-1] # swap x and y coords
345
+ pos = dict(zip(nodes, pos))
346
+ return pos
347
+
348
+
349
+ @np_random_state(10)
350
+ def spring_layout(
351
+ G,
352
+ k=None,
353
+ pos=None,
354
+ fixed=None,
355
+ iterations=50,
356
+ threshold=1e-4,
357
+ weight="weight",
358
+ scale=1,
359
+ center=None,
360
+ dim=2,
361
+ seed=None,
362
+ ):
363
+ """Position nodes using Fruchterman-Reingold force-directed algorithm.
364
+
365
+ The algorithm simulates a force-directed representation of the network
366
+ treating edges as springs holding nodes close, while treating nodes
367
+ as repelling objects, sometimes called an anti-gravity force.
368
+ Simulation continues until the positions are close to an equilibrium.
369
+
370
+ There are some hard-coded values: minimal distance between
371
+ nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
372
+ During the simulation, `k` helps determine the distance between nodes,
373
+ though `scale` and `center` determine the size and place after
374
+ rescaling occurs at the end of the simulation.
375
+
376
+ Fixing some nodes doesn't allow them to move in the simulation.
377
+ It also turns off the rescaling feature at the simulation's end.
378
+ In addition, setting `scale` to `None` turns off rescaling.
379
+
380
+ Parameters
381
+ ----------
382
+ G : NetworkX graph or list of nodes
383
+ A position will be assigned to every node in G.
384
+
385
+ k : float (default=None)
386
+ Optimal distance between nodes. If None the distance is set to
387
+ 1/sqrt(n) where n is the number of nodes. Increase this value
388
+ to move nodes farther apart.
389
+
390
+ pos : dict or None optional (default=None)
391
+ Initial positions for nodes as a dictionary with node as keys
392
+ and values as a coordinate list or tuple. If None, then use
393
+ random initial positions.
394
+
395
+ fixed : list or None optional (default=None)
396
+ Nodes to keep fixed at initial position.
397
+ Nodes not in ``G.nodes`` are ignored.
398
+ ValueError raised if `fixed` specified and `pos` not.
399
+
400
+ iterations : int optional (default=50)
401
+ Maximum number of iterations taken
402
+
403
+ threshold: float optional (default = 1e-4)
404
+ Threshold for relative error in node position changes.
405
+ The iteration stops if the error is below this threshold.
406
+
407
+ weight : string or None optional (default='weight')
408
+ The edge attribute that holds the numerical value used for
409
+ the edge weight. Larger means a stronger attractive force.
410
+ If None, then all edge weights are 1.
411
+
412
+ scale : number or None (default: 1)
413
+ Scale factor for positions. Not used unless `fixed is None`.
414
+ If scale is None, no rescaling is performed.
415
+
416
+ center : array-like or None
417
+ Coordinate pair around which to center the layout.
418
+ Not used unless `fixed is None`.
419
+
420
+ dim : int
421
+ Dimension of layout.
422
+
423
+ seed : int, RandomState instance or None optional (default=None)
424
+ Used only for the initial positions in the algorithm.
425
+ Set the random state for deterministic node layouts.
426
+ If int, `seed` is the seed used by the random number generator,
427
+ if numpy.random.RandomState instance, `seed` is the random
428
+ number generator,
429
+ if None, the random number generator is the RandomState instance used
430
+ by numpy.random.
431
+
432
+ Returns
433
+ -------
434
+ pos : dict
435
+ A dictionary of positions keyed by node
436
+
437
+ Examples
438
+ --------
439
+ >>> G = nx.path_graph(4)
440
+ >>> pos = nx.spring_layout(G)
441
+
442
+ # The same using longer but equivalent function name
443
+ >>> pos = nx.fruchterman_reingold_layout(G)
444
+ """
445
+ import numpy as np
446
+
447
+ G, center = _process_params(G, center, dim)
448
+
449
+ if fixed is not None:
450
+ if pos is None:
451
+ raise ValueError("nodes are fixed without positions given")
452
+ for node in fixed:
453
+ if node not in pos:
454
+ raise ValueError("nodes are fixed without positions given")
455
+ nfixed = {node: i for i, node in enumerate(G)}
456
+ fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
457
+
458
+ if pos is not None:
459
+ # Determine size of existing domain to adjust initial positions
460
+ dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
461
+ if dom_size == 0:
462
+ dom_size = 1
463
+ pos_arr = seed.rand(len(G), dim) * dom_size + center
464
+
465
+ for i, n in enumerate(G):
466
+ if n in pos:
467
+ pos_arr[i] = np.asarray(pos[n])
468
+ else:
469
+ pos_arr = None
470
+ dom_size = 1
471
+
472
+ if len(G) == 0:
473
+ return {}
474
+ if len(G) == 1:
475
+ return {nx.utils.arbitrary_element(G.nodes()): center}
476
+
477
+ try:
478
+ # Sparse matrix
479
+ if len(G) < 500: # sparse solver for large graphs
480
+ raise ValueError
481
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
482
+ if k is None and fixed is not None:
483
+ # We must adjust k by domain size for layouts not near 1x1
484
+ nnodes, _ = A.shape
485
+ k = dom_size / np.sqrt(nnodes)
486
+ pos = _sparse_fruchterman_reingold(
487
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
488
+ )
489
+ except ValueError:
490
+ A = nx.to_numpy_array(G, weight=weight)
491
+ if k is None and fixed is not None:
492
+ # We must adjust k by domain size for layouts not near 1x1
493
+ nnodes, _ = A.shape
494
+ k = dom_size / np.sqrt(nnodes)
495
+ pos = _fruchterman_reingold(
496
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
497
+ )
498
+ if fixed is None and scale is not None:
499
+ pos = rescale_layout(pos, scale=scale) + center
500
+ pos = dict(zip(G, pos))
501
+ return pos
502
+
503
+
504
+ fruchterman_reingold_layout = spring_layout
505
+
506
+
507
+ @np_random_state(7)
508
+ def _fruchterman_reingold(
509
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
510
+ ):
511
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
512
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
513
+ import numpy as np
514
+
515
+ try:
516
+ nnodes, _ = A.shape
517
+ except AttributeError as err:
518
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
519
+ raise nx.NetworkXError(msg) from err
520
+
521
+ if pos is None:
522
+ # random initial positions
523
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
524
+ else:
525
+ # make sure positions are of same type as matrix
526
+ pos = pos.astype(A.dtype)
527
+
528
+ # optimal distance between nodes
529
+ if k is None:
530
+ k = np.sqrt(1.0 / nnodes)
531
+ # the initial "temperature" is about .1 of domain area (=1x1)
532
+ # this is the largest step allowed in the dynamics.
533
+ # We need to calculate this in case our fixed positions force our domain
534
+ # to be much bigger than 1x1
535
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
536
+ # simple cooling scheme.
537
+ # linearly step down by dt on each iteration so last iteration is size dt.
538
+ dt = t / (iterations + 1)
539
+ delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
540
+ # the inscrutable (but fast) version
541
+ # this is still O(V^2)
542
+ # could use multilevel methods to speed this up significantly
543
+ for iteration in range(iterations):
544
+ # matrix of difference between points
545
+ delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
546
+ # distance between points
547
+ distance = np.linalg.norm(delta, axis=-1)
548
+ # enforce minimum distance of 0.01
549
+ np.clip(distance, 0.01, None, out=distance)
550
+ # displacement "force"
551
+ displacement = np.einsum(
552
+ "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
553
+ )
554
+ # update positions
555
+ length = np.linalg.norm(displacement, axis=-1)
556
+ length = np.where(length < 0.01, 0.1, length)
557
+ delta_pos = np.einsum("ij,i->ij", displacement, t / length)
558
+ if fixed is not None:
559
+ # don't change positions of fixed nodes
560
+ delta_pos[fixed] = 0.0
561
+ pos += delta_pos
562
+ # cool temperature
563
+ t -= dt
564
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
565
+ break
566
+ return pos
567
+
568
+
569
+ @np_random_state(7)
570
+ def _sparse_fruchterman_reingold(
571
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
572
+ ):
573
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
574
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
575
+ # Sparse version
576
+ import numpy as np
577
+ import scipy as sp
578
+
579
+ try:
580
+ nnodes, _ = A.shape
581
+ except AttributeError as err:
582
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
583
+ raise nx.NetworkXError(msg) from err
584
+ # make sure we have a LIst of Lists representation
585
+ try:
586
+ A = A.tolil()
587
+ except AttributeError:
588
+ A = (sp.sparse.coo_array(A)).tolil()
589
+
590
+ if pos is None:
591
+ # random initial positions
592
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
593
+ else:
594
+ # make sure positions are of same type as matrix
595
+ pos = pos.astype(A.dtype)
596
+
597
+ # no fixed nodes
598
+ if fixed is None:
599
+ fixed = []
600
+
601
+ # optimal distance between nodes
602
+ if k is None:
603
+ k = np.sqrt(1.0 / nnodes)
604
+ # the initial "temperature" is about .1 of domain area (=1x1)
605
+ # this is the largest step allowed in the dynamics.
606
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
607
+ # simple cooling scheme.
608
+ # linearly step down by dt on each iteration so last iteration is size dt.
609
+ dt = t / (iterations + 1)
610
+
611
+ displacement = np.zeros((dim, nnodes))
612
+ for iteration in range(iterations):
613
+ displacement *= 0
614
+ # loop over rows
615
+ for i in range(A.shape[0]):
616
+ if i in fixed:
617
+ continue
618
+ # difference between this row's node position and all others
619
+ delta = (pos[i] - pos).T
620
+ # distance between points
621
+ distance = np.sqrt((delta**2).sum(axis=0))
622
+ # enforce minimum distance of 0.01
623
+ distance = np.where(distance < 0.01, 0.01, distance)
624
+ # the adjacency matrix row
625
+ Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
626
+ # displacement "force"
627
+ displacement[:, i] += (
628
+ delta * (k * k / distance**2 - Ai * distance / k)
629
+ ).sum(axis=1)
630
+ # update positions
631
+ length = np.sqrt((displacement**2).sum(axis=0))
632
+ length = np.where(length < 0.01, 0.1, length)
633
+ delta_pos = (displacement * t / length).T
634
+ pos += delta_pos
635
+ # cool temperature
636
+ t -= dt
637
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
638
+ break
639
+ return pos
640
+
641
+
642
+ def kamada_kawai_layout(
643
+ G, dist=None, pos=None, weight="weight", scale=1, center=None, dim=2
644
+ ):
645
+ """Position nodes using Kamada-Kawai path-length cost-function.
646
+
647
+ Parameters
648
+ ----------
649
+ G : NetworkX graph or list of nodes
650
+ A position will be assigned to every node in G.
651
+
652
+ dist : dict (default=None)
653
+ A two-level dictionary of optimal distances between nodes,
654
+ indexed by source and destination node.
655
+ If None, the distance is computed using shortest_path_length().
656
+
657
+ pos : dict or None optional (default=None)
658
+ Initial positions for nodes as a dictionary with node as keys
659
+ and values as a coordinate list or tuple. If None, then use
660
+ circular_layout() for dim >= 2 and a linear layout for dim == 1.
661
+
662
+ weight : string or None optional (default='weight')
663
+ The edge attribute that holds the numerical value used for
664
+ the edge weight. If None, then all edge weights are 1.
665
+
666
+ scale : number (default: 1)
667
+ Scale factor for positions.
668
+
669
+ center : array-like or None
670
+ Coordinate pair around which to center the layout.
671
+
672
+ dim : int
673
+ Dimension of layout.
674
+
675
+ Returns
676
+ -------
677
+ pos : dict
678
+ A dictionary of positions keyed by node
679
+
680
+ Examples
681
+ --------
682
+ >>> G = nx.path_graph(4)
683
+ >>> pos = nx.kamada_kawai_layout(G)
684
+ """
685
+ import numpy as np
686
+
687
+ G, center = _process_params(G, center, dim)
688
+ nNodes = len(G)
689
+ if nNodes == 0:
690
+ return {}
691
+
692
+ if dist is None:
693
+ dist = dict(nx.shortest_path_length(G, weight=weight))
694
+ dist_mtx = 1e6 * np.ones((nNodes, nNodes))
695
+ for row, nr in enumerate(G):
696
+ if nr not in dist:
697
+ continue
698
+ rdist = dist[nr]
699
+ for col, nc in enumerate(G):
700
+ if nc not in rdist:
701
+ continue
702
+ dist_mtx[row][col] = rdist[nc]
703
+
704
+ if pos is None:
705
+ if dim >= 3:
706
+ pos = random_layout(G, dim=dim)
707
+ elif dim == 2:
708
+ pos = circular_layout(G, dim=dim)
709
+ else:
710
+ pos = dict(zip(G, np.linspace(0, 1, len(G))))
711
+ pos_arr = np.array([pos[n] for n in G])
712
+
713
+ pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
714
+
715
+ pos = rescale_layout(pos, scale=scale) + center
716
+ return dict(zip(G, pos))
717
+
718
+
719
+ def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
720
+ # Anneal node locations based on the Kamada-Kawai cost-function,
721
+ # using the supplied matrix of preferred inter-node distances,
722
+ # and starting locations.
723
+
724
+ import numpy as np
725
+ import scipy as sp
726
+
727
+ meanwt = 1e-3
728
+ costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
729
+
730
+ optresult = sp.optimize.minimize(
731
+ _kamada_kawai_costfn,
732
+ pos_arr.ravel(),
733
+ method="L-BFGS-B",
734
+ args=costargs,
735
+ jac=True,
736
+ )
737
+
738
+ return optresult.x.reshape((-1, dim))
739
+
740
+
741
+ def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
742
+ # Cost-function and gradient for Kamada-Kawai layout algorithm
743
+ nNodes = invdist.shape[0]
744
+ pos_arr = pos_vec.reshape((nNodes, dim))
745
+
746
+ delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
747
+ nodesep = np.linalg.norm(delta, axis=-1)
748
+ direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
749
+
750
+ offset = nodesep * invdist - 1.0
751
+ offset[np.diag_indices(nNodes)] = 0
752
+
753
+ cost = 0.5 * np.sum(offset**2)
754
+ grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
755
+ "ij,ij,ijk->jk", invdist, offset, direction
756
+ )
757
+
758
+ # Additional parabolic term to encourage mean position to be near origin:
759
+ sumpos = np.sum(pos_arr, axis=0)
760
+ cost += 0.5 * meanweight * np.sum(sumpos**2)
761
+ grad += meanweight * sumpos
762
+
763
+ return (cost, grad.ravel())
764
+
765
+
766
+ def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
767
+ """Position nodes using the eigenvectors of the graph Laplacian.
768
+
769
+ Using the unnormalized Laplacian, the layout shows possible clusters of
770
+ nodes which are an approximation of the ratio cut. If dim is the number of
771
+ dimensions then the positions are the entries of the dim eigenvectors
772
+ corresponding to the ascending eigenvalues starting from the second one.
773
+
774
+ Parameters
775
+ ----------
776
+ G : NetworkX graph or list of nodes
777
+ A position will be assigned to every node in G.
778
+
779
+ weight : string or None optional (default='weight')
780
+ The edge attribute that holds the numerical value used for
781
+ the edge weight. If None, then all edge weights are 1.
782
+
783
+ scale : number (default: 1)
784
+ Scale factor for positions.
785
+
786
+ center : array-like or None
787
+ Coordinate pair around which to center the layout.
788
+
789
+ dim : int
790
+ Dimension of layout.
791
+
792
+ Returns
793
+ -------
794
+ pos : dict
795
+ A dictionary of positions keyed by node
796
+
797
+ Examples
798
+ --------
799
+ >>> G = nx.path_graph(4)
800
+ >>> pos = nx.spectral_layout(G)
801
+
802
+ Notes
803
+ -----
804
+ Directed graphs will be considered as undirected graphs when
805
+ positioning the nodes.
806
+
807
+ For larger graphs (>500 nodes) this will use the SciPy sparse
808
+ eigenvalue solver (ARPACK).
809
+ """
810
+ # handle some special cases that break the eigensolvers
811
+ import numpy as np
812
+
813
+ G, center = _process_params(G, center, dim)
814
+
815
+ if len(G) <= 2:
816
+ if len(G) == 0:
817
+ pos = np.array([])
818
+ elif len(G) == 1:
819
+ pos = np.array([center])
820
+ else:
821
+ pos = np.array([np.zeros(dim), np.array(center) * 2.0])
822
+ return dict(zip(G, pos))
823
+ try:
824
+ # Sparse matrix
825
+ if len(G) < 500: # dense solver is faster for small graphs
826
+ raise ValueError
827
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
828
+ # Symmetrize directed graphs
829
+ if G.is_directed():
830
+ A = A + np.transpose(A)
831
+ pos = _sparse_spectral(A, dim)
832
+ except (ImportError, ValueError):
833
+ # Dense matrix
834
+ A = nx.to_numpy_array(G, weight=weight)
835
+ # Symmetrize directed graphs
836
+ if G.is_directed():
837
+ A += A.T
838
+ pos = _spectral(A, dim)
839
+
840
+ pos = rescale_layout(pos, scale=scale) + center
841
+ pos = dict(zip(G, pos))
842
+ return pos
843
+
844
+
845
+ def _spectral(A, dim=2):
846
+ # Input adjacency matrix A
847
+ # Uses dense eigenvalue solver from numpy
848
+ import numpy as np
849
+
850
+ try:
851
+ nnodes, _ = A.shape
852
+ except AttributeError as err:
853
+ msg = "spectral() takes an adjacency matrix as input"
854
+ raise nx.NetworkXError(msg) from err
855
+
856
+ # form Laplacian matrix where D is diagonal of degrees
857
+ D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
858
+ L = D - A
859
+
860
+ eigenvalues, eigenvectors = np.linalg.eig(L)
861
+ # sort and keep smallest nonzero
862
+ index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
863
+ return np.real(eigenvectors[:, index])
864
+
865
+
866
+ def _sparse_spectral(A, dim=2):
867
+ # Input adjacency matrix A
868
+ # Uses sparse eigenvalue solver from scipy
869
+ # Could use multilevel methods here, see Koren "On spectral graph drawing"
870
+ import numpy as np
871
+ import scipy as sp
872
+
873
+ try:
874
+ nnodes, _ = A.shape
875
+ except AttributeError as err:
876
+ msg = "sparse_spectral() takes an adjacency matrix as input"
877
+ raise nx.NetworkXError(msg) from err
878
+
879
+ # form Laplacian matrix
880
+ # TODO: Rm csr_array wrapper in favor of spdiags array constructor when available
881
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, nnodes, nnodes))
882
+ L = D - A
883
+
884
+ k = dim + 1
885
+ # number of Lanczos vectors for ARPACK solver.What is the right scaling?
886
+ ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
887
+ # return smallest k eigenvalues and eigenvectors
888
+ eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
889
+ index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
890
+ return np.real(eigenvectors[:, index])
891
+
892
+
893
+ def planar_layout(G, scale=1, center=None, dim=2):
894
+ """Position nodes without edge intersections.
895
+
896
+ Parameters
897
+ ----------
898
+ G : NetworkX graph or list of nodes
899
+ A position will be assigned to every node in G. If G is of type
900
+ nx.PlanarEmbedding, the positions are selected accordingly.
901
+
902
+ scale : number (default: 1)
903
+ Scale factor for positions.
904
+
905
+ center : array-like or None
906
+ Coordinate pair around which to center the layout.
907
+
908
+ dim : int
909
+ Dimension of layout.
910
+
911
+ Returns
912
+ -------
913
+ pos : dict
914
+ A dictionary of positions keyed by node
915
+
916
+ Raises
917
+ ------
918
+ NetworkXException
919
+ If G is not planar
920
+
921
+ Examples
922
+ --------
923
+ >>> G = nx.path_graph(4)
924
+ >>> pos = nx.planar_layout(G)
925
+ """
926
+ import numpy as np
927
+
928
+ if dim != 2:
929
+ raise ValueError("can only handle 2 dimensions")
930
+
931
+ G, center = _process_params(G, center, dim)
932
+
933
+ if len(G) == 0:
934
+ return {}
935
+
936
+ if isinstance(G, nx.PlanarEmbedding):
937
+ embedding = G
938
+ else:
939
+ is_planar, embedding = nx.check_planarity(G)
940
+ if not is_planar:
941
+ raise nx.NetworkXException("G is not planar.")
942
+ pos = nx.combinatorial_embedding_to_pos(embedding)
943
+ node_list = list(embedding)
944
+ pos = np.vstack([pos[x] for x in node_list])
945
+ pos = pos.astype(np.float64)
946
+ pos = rescale_layout(pos, scale=scale) + center
947
+ return dict(zip(node_list, pos))
948
+
949
+
950
+ def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False):
951
+ """Position nodes in a spiral layout.
952
+
953
+ Parameters
954
+ ----------
955
+ G : NetworkX graph or list of nodes
956
+ A position will be assigned to every node in G.
957
+ scale : number (default: 1)
958
+ Scale factor for positions.
959
+ center : array-like or None
960
+ Coordinate pair around which to center the layout.
961
+ dim : int, default=2
962
+ Dimension of layout, currently only dim=2 is supported.
963
+ Other dimension values result in a ValueError.
964
+ resolution : float, default=0.35
965
+ The compactness of the spiral layout returned.
966
+ Lower values result in more compressed spiral layouts.
967
+ equidistant : bool, default=False
968
+ If True, nodes will be positioned equidistant from each other
969
+ by decreasing angle further from center.
970
+ If False, nodes will be positioned at equal angles
971
+ from each other by increasing separation further from center.
972
+
973
+ Returns
974
+ -------
975
+ pos : dict
976
+ A dictionary of positions keyed by node
977
+
978
+ Raises
979
+ ------
980
+ ValueError
981
+ If dim != 2
982
+
983
+ Examples
984
+ --------
985
+ >>> G = nx.path_graph(4)
986
+ >>> pos = nx.spiral_layout(G)
987
+ >>> nx.draw(G, pos=pos)
988
+
989
+ Notes
990
+ -----
991
+ This algorithm currently only works in two dimensions.
992
+
993
+ """
994
+ import numpy as np
995
+
996
+ if dim != 2:
997
+ raise ValueError("can only handle 2 dimensions")
998
+
999
+ G, center = _process_params(G, center, dim)
1000
+
1001
+ if len(G) == 0:
1002
+ return {}
1003
+ if len(G) == 1:
1004
+ return {nx.utils.arbitrary_element(G): center}
1005
+
1006
+ pos = []
1007
+ if equidistant:
1008
+ chord = 1
1009
+ step = 0.5
1010
+ theta = resolution
1011
+ theta += chord / (step * theta)
1012
+ for _ in range(len(G)):
1013
+ r = step * theta
1014
+ theta += chord / r
1015
+ pos.append([np.cos(theta) * r, np.sin(theta) * r])
1016
+
1017
+ else:
1018
+ dist = np.arange(len(G), dtype=float)
1019
+ angle = resolution * dist
1020
+ pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
1021
+
1022
+ pos = rescale_layout(np.array(pos), scale=scale) + center
1023
+
1024
+ pos = dict(zip(G, pos))
1025
+
1026
+ return pos
1027
+
1028
+
1029
+ def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
1030
+ """Position nodes in layers of straight lines.
1031
+
1032
+ Parameters
1033
+ ----------
1034
+ G : NetworkX graph or list of nodes
1035
+ A position will be assigned to every node in G.
1036
+
1037
+ subset_key : string or dict (default='subset')
1038
+ If a string, the key of node data in G that holds the node subset.
1039
+ If a dict, keyed by layer number to the nodes in that layer/subset.
1040
+
1041
+ align : string (default='vertical')
1042
+ The alignment of nodes. Vertical or horizontal.
1043
+
1044
+ scale : number (default: 1)
1045
+ Scale factor for positions.
1046
+
1047
+ center : array-like or None
1048
+ Coordinate pair around which to center the layout.
1049
+
1050
+ Returns
1051
+ -------
1052
+ pos : dict
1053
+ A dictionary of positions keyed by node.
1054
+
1055
+ Examples
1056
+ --------
1057
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1058
+ >>> pos = nx.multipartite_layout(G)
1059
+
1060
+ or use a dict to provide the layers of the layout
1061
+
1062
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
1063
+ >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
1064
+ >>> pos = nx.multipartite_layout(G, subset_key=layers)
1065
+
1066
+ Notes
1067
+ -----
1068
+ This algorithm currently only works in two dimensions and does not
1069
+ try to minimize edge crossings.
1070
+
1071
+ Network does not need to be a complete multipartite graph. As long as nodes
1072
+ have subset_key data, they will be placed in the corresponding layers.
1073
+
1074
+ """
1075
+ import numpy as np
1076
+
1077
+ if align not in ("vertical", "horizontal"):
1078
+ msg = "align must be either vertical or horizontal."
1079
+ raise ValueError(msg)
1080
+
1081
+ G, center = _process_params(G, center=center, dim=2)
1082
+ if len(G) == 0:
1083
+ return {}
1084
+
1085
+ try:
1086
+ # check if subset_key is dict-like
1087
+ if len(G) != sum(len(nodes) for nodes in subset_key.values()):
1088
+ raise nx.NetworkXError(
1089
+ "all nodes must be in one subset of `subset_key` dict"
1090
+ )
1091
+ except AttributeError:
1092
+ # subset_key is not a dict, hence a string
1093
+ node_to_subset = nx.get_node_attributes(G, subset_key)
1094
+ if len(node_to_subset) != len(G):
1095
+ raise nx.NetworkXError(
1096
+ f"all nodes need a subset_key attribute: {subset_key}"
1097
+ )
1098
+ subset_key = nx.utils.groups(node_to_subset)
1099
+
1100
+ # Sort by layer, if possible
1101
+ try:
1102
+ layers = dict(sorted(subset_key.items()))
1103
+ except TypeError:
1104
+ layers = subset_key
1105
+
1106
+ pos = None
1107
+ nodes = []
1108
+ width = len(layers)
1109
+ for i, layer in enumerate(layers.values()):
1110
+ height = len(layer)
1111
+ xs = np.repeat(i, height)
1112
+ ys = np.arange(0, height, dtype=float)
1113
+ offset = ((width - 1) / 2, (height - 1) / 2)
1114
+ layer_pos = np.column_stack([xs, ys]) - offset
1115
+ if pos is None:
1116
+ pos = layer_pos
1117
+ else:
1118
+ pos = np.concatenate([pos, layer_pos])
1119
+ nodes.extend(layer)
1120
+ pos = rescale_layout(pos, scale=scale) + center
1121
+ if align == "horizontal":
1122
+ pos = pos[:, ::-1] # swap x and y coords
1123
+ pos = dict(zip(nodes, pos))
1124
+ return pos
1125
+
1126
+
1127
+ @np_random_state("seed")
1128
+ def arf_layout(
1129
+ G,
1130
+ pos=None,
1131
+ scaling=1,
1132
+ a=1.1,
1133
+ etol=1e-6,
1134
+ dt=1e-3,
1135
+ max_iter=1000,
1136
+ *,
1137
+ seed=None,
1138
+ ):
1139
+ """Arf layout for networkx
1140
+
1141
+ The attractive and repulsive forces (arf) layout [1]
1142
+ improves the spring layout in three ways. First, it
1143
+ prevents congestion of highly connected nodes due to
1144
+ strong forcing between nodes. Second, it utilizes the
1145
+ layout space more effectively by preventing large gaps
1146
+ that spring layout tends to create. Lastly, the arf
1147
+ layout represents symmetries in the layout better than
1148
+ the default spring layout.
1149
+
1150
+ Parameters
1151
+ ----------
1152
+ G : nx.Graph or nx.DiGraph
1153
+ Networkx graph.
1154
+ pos : dict
1155
+ Initial position of the nodes. If set to None a
1156
+ random layout will be used.
1157
+ scaling : float
1158
+ Scales the radius of the circular layout space.
1159
+ a : float
1160
+ Strength of springs between connected nodes. Should be larger than 1. The greater a, the clearer the separation ofunconnected sub clusters.
1161
+ etol : float
1162
+ Gradient sum of spring forces must be larger than `etol` before successful termination.
1163
+ dt : float
1164
+ Time step for force differential equation simulations.
1165
+ max_iter : int
1166
+ Max iterations before termination of the algorithm.
1167
+ seed : int, RandomState instance or None optional (default=None)
1168
+ Set the random state for deterministic node layouts.
1169
+ If int, `seed` is the seed used by the random number generator,
1170
+ if numpy.random.RandomState instance, `seed` is the random
1171
+ number generator,
1172
+ if None, the random number generator is the RandomState instance used
1173
+ by numpy.random.
1174
+
1175
+ References
1176
+ .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
1177
+ International Journal of Modern Physics C, 2007, Vol 18, No 10, pp. 1537-1549.
1178
+ https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
1179
+
1180
+ Returns
1181
+ -------
1182
+ pos : dict
1183
+ A dictionary of positions keyed by node.
1184
+
1185
+ Examples
1186
+ --------
1187
+ >>> G = nx.grid_graph((5, 5))
1188
+ >>> pos = nx.arf_layout(G)
1189
+
1190
+ """
1191
+ import warnings
1192
+
1193
+ import numpy as np
1194
+
1195
+ if a <= 1:
1196
+ msg = "The parameter a should be larger than 1"
1197
+ raise ValueError(msg)
1198
+
1199
+ pos_tmp = nx.random_layout(G, seed=seed)
1200
+ if pos is None:
1201
+ pos = pos_tmp
1202
+ else:
1203
+ for node in G.nodes():
1204
+ if node not in pos:
1205
+ pos[node] = pos_tmp[node].copy()
1206
+
1207
+ # Initialize spring constant matrix
1208
+ N = len(G)
1209
+ # No nodes no computation
1210
+ if N == 0:
1211
+ return pos
1212
+
1213
+ # init force of springs
1214
+ K = np.ones((N, N)) - np.eye(N)
1215
+ node_order = {node: i for i, node in enumerate(G)}
1216
+ for x, y in G.edges():
1217
+ if x != y:
1218
+ idx, jdx = (node_order[i] for i in (x, y))
1219
+ K[idx, jdx] = a
1220
+
1221
+ # vectorize values
1222
+ p = np.asarray(list(pos.values()))
1223
+
1224
+ # equation 10 in [1]
1225
+ rho = scaling * np.sqrt(N)
1226
+
1227
+ # looping variables
1228
+ error = etol + 1
1229
+ n_iter = 0
1230
+ while error > etol:
1231
+ diff = p[:, np.newaxis] - p[np.newaxis]
1232
+ A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
1233
+ # attraction_force - repulsions force
1234
+ # suppress nans due to division; caused by diagonal set to zero.
1235
+ # Does not affect the computation due to nansum
1236
+ with warnings.catch_warnings():
1237
+ warnings.simplefilter("ignore")
1238
+ change = K[..., np.newaxis] * diff - rho / A * diff
1239
+ change = np.nansum(change, axis=0)
1240
+ p += change * dt
1241
+
1242
+ error = np.linalg.norm(change, axis=-1).sum()
1243
+ if n_iter > max_iter:
1244
+ break
1245
+ n_iter += 1
1246
+ return dict(zip(G.nodes(), p))
1247
+
1248
+
1249
+ @np_random_state("seed")
1250
+ def forceatlas2_layout(
1251
+ G,
1252
+ pos=None,
1253
+ *,
1254
+ max_iter=100,
1255
+ jitter_tolerance=1.0,
1256
+ scaling_ratio=2.0,
1257
+ gravity=1.0,
1258
+ distributed_action=False,
1259
+ strong_gravity=False,
1260
+ node_mass=None,
1261
+ node_size=None,
1262
+ weight=None,
1263
+ dissuade_hubs=False,
1264
+ linlog=False,
1265
+ seed=None,
1266
+ dim=2,
1267
+ ):
1268
+ """Position nodes using the ForceAtlas2 force-directed layout algorithm.
1269
+
1270
+ This function applies the ForceAtlas2 layout algorithm [1]_ to a NetworkX graph,
1271
+ positioning the nodes in a way that visually represents the structure of the graph.
1272
+ The algorithm uses physical simulation to minimize the energy of the system,
1273
+ resulting in a more readable layout.
1274
+
1275
+ Parameters
1276
+ ----------
1277
+ G : nx.Graph
1278
+ A NetworkX graph to be laid out.
1279
+ pos : dict or None, optional
1280
+ Initial positions of the nodes. If None, random initial positions are used.
1281
+ max_iter : int (default: 100)
1282
+ Number of iterations for the layout optimization.
1283
+ jitter_tolerance : float (default: 1.0)
1284
+ Controls the tolerance for adjusting the speed of layout generation.
1285
+ scaling_ratio : float (default: 2.0)
1286
+ Determines the scaling of attraction and repulsion forces.
1287
+ distributed_attraction : bool (default: False)
1288
+ Distributes the attraction force evenly among nodes.
1289
+ strong_gravity : bool (default: False)
1290
+ Applies a strong gravitational pull towards the center.
1291
+ node_mass : dict or None, optional
1292
+ Maps nodes to their masses, influencing the attraction to other nodes.
1293
+ node_size : dict or None, optional
1294
+ Maps nodes to their sizes, preventing crowding by creating a halo effect.
1295
+ dissuade_hubs : bool (default: False)
1296
+ Prevents the clustering of hub nodes.
1297
+ linlog : bool (default: False)
1298
+ Uses logarithmic attraction instead of linear.
1299
+ seed : int, RandomState instance or None optional (default=None)
1300
+ Used only for the initial positions in the algorithm.
1301
+ Set the random state for deterministic node layouts.
1302
+ If int, `seed` is the seed used by the random number generator,
1303
+ if numpy.random.RandomState instance, `seed` is the random
1304
+ number generator,
1305
+ if None, the random number generator is the RandomState instance used
1306
+ by numpy.random.
1307
+ dim : int (default: 2)
1308
+ Sets the dimensions for the layout. Ignored if `pos` is provided.
1309
+
1310
+ Examples
1311
+ --------
1312
+ >>> import networkx as nx
1313
+ >>> G = nx.florentine_families_graph()
1314
+ >>> pos = nx.forceatlas2_layout(G)
1315
+ >>> nx.draw(G, pos=pos)
1316
+
1317
+ References
1318
+ ----------
1319
+ .. [1] Jacomy, M., Venturini, T., Heymann, S., & Bastian, M. (2014).
1320
+ ForceAtlas2, a continuous graph layout algorithm for handy network
1321
+ visualization designed for the Gephi software. PloS one, 9(6), e98679.
1322
+ https://doi.org/10.1371/journal.pone.0098679
1323
+ """
1324
+ import numpy as np
1325
+
1326
+ if len(G) == 0:
1327
+ return {}
1328
+ # parse optional pos positions
1329
+ if pos is None:
1330
+ pos = nx.random_layout(G, dim=dim, seed=seed)
1331
+ pos_arr = np.array(list(pos.values()))
1332
+ else:
1333
+ # set default node interval within the initial pos values
1334
+ pos_init = np.array(list(pos.values()))
1335
+ max_pos = pos_init.max(axis=0)
1336
+ min_pos = pos_init.min(axis=0)
1337
+ dim = max_pos.size
1338
+ pos_arr = min_pos + seed.rand(len(G), dim) * (max_pos - min_pos)
1339
+ for idx, node in enumerate(G):
1340
+ if node in pos:
1341
+ pos_arr[idx] = pos[node].copy()
1342
+
1343
+ mass = np.zeros(len(G))
1344
+ size = np.zeros(len(G))
1345
+
1346
+ # Only adjust for size when the users specifies size other than default (1)
1347
+ adjust_sizes = False
1348
+ if node_size is None:
1349
+ node_size = {}
1350
+ else:
1351
+ adjust_sizes = True
1352
+
1353
+ if node_mass is None:
1354
+ node_mass = {}
1355
+
1356
+ for idx, node in enumerate(G):
1357
+ mass[idx] = node_mass.get(node, G.degree(node) + 1)
1358
+ size[idx] = node_size.get(node, 1)
1359
+
1360
+ n = len(G)
1361
+ gravities = np.zeros((n, dim))
1362
+ attraction = np.zeros((n, dim))
1363
+ repulsion = np.zeros((n, dim))
1364
+ A = nx.to_numpy_array(G, weight=weight)
1365
+
1366
+ def estimate_factor(n, swing, traction, speed, speed_efficiency, jitter_tolerance):
1367
+ """Computes the scaling factor for the force in the ForceAtlas2 layout algorithm.
1368
+
1369
+ This helper function adjusts the speed and
1370
+ efficiency of the layout generation based on the
1371
+ current state of the system, such as the number of
1372
+ nodes, current swing, and traction forces.
1373
+
1374
+ Parameters
1375
+ ----------
1376
+ n : int
1377
+ Number of nodes in the graph.
1378
+ swing : float
1379
+ The current swing, representing the oscillation of the nodes.
1380
+ traction : float
1381
+ The current traction force, representing the attraction between nodes.
1382
+ speed : float
1383
+ The current speed of the layout generation.
1384
+ speed_efficiency : float
1385
+ The efficiency of the current speed, influencing how fast the layout converges.
1386
+ jitter_tolerance : float
1387
+ The tolerance for jitter, affecting how much speed adjustment is allowed.
1388
+
1389
+ Returns
1390
+ -------
1391
+ tuple
1392
+ A tuple containing the updated speed and speed efficiency.
1393
+
1394
+ Notes
1395
+ -----
1396
+ This function is a part of the ForceAtlas2 layout algorithm and is used to dynamically adjust the
1397
+ layout parameters to achieve an optimal and stable visualization.
1398
+
1399
+ """
1400
+ import numpy as np
1401
+
1402
+ # estimate jitter
1403
+ opt_jitter = 0.05 * np.sqrt(n)
1404
+ min_jitter = np.sqrt(opt_jitter)
1405
+ max_jitter = 10
1406
+ min_speed_efficiency = 0.05
1407
+
1408
+ other = min(max_jitter, opt_jitter * traction / n**2)
1409
+ jitter = jitter_tolerance * max(min_jitter, other)
1410
+
1411
+ if swing / traction > 2.0:
1412
+ if speed_efficiency > min_speed_efficiency:
1413
+ speed_efficiency *= 0.5
1414
+ jitter = max(jitter, jitter_tolerance)
1415
+ if swing == 0:
1416
+ target_speed = np.inf
1417
+ else:
1418
+ target_speed = jitter * speed_efficiency * traction / swing
1419
+
1420
+ if swing > jitter * traction:
1421
+ if speed_efficiency > min_speed_efficiency:
1422
+ speed_efficiency *= 0.7
1423
+ elif speed < 1000:
1424
+ speed_efficiency *= 1.3
1425
+
1426
+ max_rise = 0.5
1427
+ speed = speed + min(target_speed - speed, max_rise * speed)
1428
+ return speed, speed_efficiency
1429
+
1430
+ speed = 1
1431
+ speed_efficiency = 1
1432
+ swing = 1
1433
+ traction = 1
1434
+ for _ in range(max_iter):
1435
+ # compute pairwise difference
1436
+ diff = pos_arr[:, None] - pos_arr[None]
1437
+ # compute pairwise distance
1438
+ distance = np.linalg.norm(diff, axis=-1)
1439
+
1440
+ # linear attraction
1441
+ if linlog:
1442
+ attraction = -np.log(1 + distance) / distance
1443
+ np.fill_diagonal(attraction, 0)
1444
+ attraction = np.einsum("ij, ij -> ij", attraction, A)
1445
+ attraction = np.einsum("ijk, ij -> ik", diff, attraction)
1446
+
1447
+ else:
1448
+ attraction = -np.einsum("ijk, ij -> ik", diff, A)
1449
+
1450
+ if distributed_action:
1451
+ attraction /= mass[:, None]
1452
+
1453
+ # repulsion
1454
+ tmp = mass[:, None] @ mass[None]
1455
+ if adjust_sizes:
1456
+ distance += -size[:, None] - size[None]
1457
+
1458
+ d2 = distance**2
1459
+ # remove self-interaction
1460
+ np.fill_diagonal(tmp, 0)
1461
+ np.fill_diagonal(d2, 1)
1462
+ factor = (tmp / d2) * scaling_ratio
1463
+ repulsion = np.einsum("ijk, ij -> ik", diff, factor)
1464
+
1465
+ # gravity
1466
+ gravities = (
1467
+ -gravity
1468
+ * mass[:, None]
1469
+ * pos_arr
1470
+ / np.linalg.norm(pos_arr, axis=-1)[:, None]
1471
+ )
1472
+
1473
+ if strong_gravity:
1474
+ gravities *= np.linalg.norm(pos_arr, axis=-1)[:, None]
1475
+ # total forces
1476
+ update = attraction + repulsion + gravities
1477
+
1478
+ # compute total swing and traction
1479
+ swing += (mass * np.linalg.norm(pos_arr - update, axis=-1)).sum()
1480
+ traction += (0.5 * mass * np.linalg.norm(pos_arr + update, axis=-1)).sum()
1481
+
1482
+ speed, speed_efficiency = estimate_factor(
1483
+ n,
1484
+ swing,
1485
+ traction,
1486
+ speed,
1487
+ speed_efficiency,
1488
+ jitter_tolerance,
1489
+ )
1490
+
1491
+ # update pos
1492
+ if adjust_sizes:
1493
+ swinging = mass * np.linalg.norm(update, axis=-1)
1494
+ factor = 0.1 * speed / (1 + np.sqrt(speed * swinging))
1495
+ df = np.linalg.norm(update, axis=-1)
1496
+ factor = np.minimum(factor * df, 10.0 * np.ones(df.shape)) / df
1497
+ else:
1498
+ swinging = mass * np.linalg.norm(update, axis=-1)
1499
+ factor = speed / (1 + np.sqrt(speed * swinging))
1500
+
1501
+ pos_arr += update * factor[:, None]
1502
+ if abs((update * factor[:, None]).sum()) < 1e-10:
1503
+ break
1504
+
1505
+ return dict(zip(G, pos_arr))
1506
+
1507
+
1508
+ def rescale_layout(pos, scale=1):
1509
+ """Returns scaled position array to (-scale, scale) in all axes.
1510
+
1511
+ The function acts on NumPy arrays which hold position information.
1512
+ Each position is one row of the array. The dimension of the space
1513
+ equals the number of columns. Each coordinate in one column.
1514
+
1515
+ To rescale, the mean (center) is subtracted from each axis separately.
1516
+ Then all values are scaled so that the largest magnitude value
1517
+ from all axes equals `scale` (thus, the aspect ratio is preserved).
1518
+ The resulting NumPy Array is returned (order of rows unchanged).
1519
+
1520
+ Parameters
1521
+ ----------
1522
+ pos : numpy array
1523
+ positions to be scaled. Each row is a position.
1524
+
1525
+ scale : number (default: 1)
1526
+ The size of the resulting extent in all directions.
1527
+
1528
+ Returns
1529
+ -------
1530
+ pos : numpy array
1531
+ scaled positions. Each row is a position.
1532
+
1533
+ See Also
1534
+ --------
1535
+ rescale_layout_dict
1536
+ """
1537
+ import numpy as np
1538
+
1539
+ # Find max length over all dimensions
1540
+ pos -= pos.mean(axis=0)
1541
+ lim = np.abs(pos).max() # max coordinate for all axes
1542
+ # rescale to (-scale, scale) in all directions, preserves aspect
1543
+ if lim > 0:
1544
+ pos *= scale / lim
1545
+ return pos
1546
+
1547
+
1548
+ def rescale_layout_dict(pos, scale=1):
1549
+ """Return a dictionary of scaled positions keyed by node
1550
+
1551
+ Parameters
1552
+ ----------
1553
+ pos : A dictionary of positions keyed by node
1554
+
1555
+ scale : number (default: 1)
1556
+ The size of the resulting extent in all directions.
1557
+
1558
+ Returns
1559
+ -------
1560
+ pos : A dictionary of positions keyed by node
1561
+
1562
+ Examples
1563
+ --------
1564
+ >>> import numpy as np
1565
+ >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
1566
+ >>> nx.rescale_layout_dict(pos)
1567
+ {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
1568
+
1569
+ >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
1570
+ >>> nx.rescale_layout_dict(pos, scale=2)
1571
+ {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
1572
+
1573
+ See Also
1574
+ --------
1575
+ rescale_layout
1576
+ """
1577
+ import numpy as np
1578
+
1579
+ if not pos: # empty_graph
1580
+ return {}
1581
+ pos_v = np.array(list(pos.values()))
1582
+ pos_v = rescale_layout(pos_v, scale=scale)
1583
+ return dict(zip(pos, pos_v))
1584
+
1585
+
1586
+ def bfs_layout(G, start, *, align="vertical", scale=1, center=None):
1587
+ """Position nodes according to breadth-first search algorithm.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ G : NetworkX graph
1592
+ A position will be assigned to every node in G.
1593
+
1594
+ start : node in `G`
1595
+ Starting node for bfs
1596
+
1597
+ center : array-like or None
1598
+ Coordinate pair around which to center the layout.
1599
+
1600
+ Returns
1601
+ -------
1602
+ pos : dict
1603
+ A dictionary of positions keyed by node.
1604
+
1605
+ Examples
1606
+ --------
1607
+ >>> G = nx.path_graph(4)
1608
+ >>> pos = nx.bfs_layout(G, 0)
1609
+
1610
+ Notes
1611
+ -----
1612
+ This algorithm currently only works in two dimensions and does not
1613
+ try to minimize edge crossings.
1614
+
1615
+ """
1616
+ G, center = _process_params(G, center, 2)
1617
+
1618
+ # Compute layers with BFS
1619
+ layers = dict(enumerate(nx.bfs_layers(G, start)))
1620
+
1621
+ if len(G) != sum(len(nodes) for nodes in layers.values()):
1622
+ raise nx.NetworkXError(
1623
+ "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
1624
+ " G.subgraph(nx.node_connected_component(G, start))"
1625
+ )
1626
+
1627
+ # Compute node positions with multipartite_layout
1628
+ return multipartite_layout(
1629
+ G, subset_key=layers, align=align, scale=scale, center=center
1630
+ )
wemm/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ *****
3
+ Pydot
4
+ *****
5
+
6
+ Import and export NetworkX graphs in Graphviz dot format using pydot.
7
+
8
+ Either this module or nx_agraph can be used to interface with graphviz.
9
+
10
+ Examples
11
+ --------
12
+ >>> G = nx.complete_graph(5)
13
+ >>> PG = nx.nx_pydot.to_pydot(G)
14
+ >>> H = nx.nx_pydot.from_pydot(PG)
15
+
16
+ See Also
17
+ --------
18
+ - pydot: https://github.com/erocarrera/pydot
19
+ - Graphviz: https://www.graphviz.org
20
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
21
+ """
22
+
23
+ from locale import getpreferredencoding
24
+
25
+ import networkx as nx
26
+ from networkx.utils import open_file
27
+
28
+ __all__ = [
29
+ "write_dot",
30
+ "read_dot",
31
+ "graphviz_layout",
32
+ "pydot_layout",
33
+ "to_pydot",
34
+ "from_pydot",
35
+ ]
36
+
37
+
38
+ @open_file(1, mode="w")
39
+ def write_dot(G, path):
40
+ """Write NetworkX graph G to Graphviz dot format on path.
41
+
42
+ Path can be a string or a file handle.
43
+ """
44
+ P = to_pydot(G)
45
+ path.write(P.to_string())
46
+ return
47
+
48
+
49
+ @open_file(0, mode="r")
50
+ @nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
51
+ def read_dot(path):
52
+ """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
53
+ dot file with the passed path.
54
+
55
+ If this file contains multiple graphs, only the first such graph is
56
+ returned. All graphs _except_ the first are silently ignored.
57
+
58
+ Parameters
59
+ ----------
60
+ path : str or file
61
+ Filename or file handle.
62
+
63
+ Returns
64
+ -------
65
+ G : MultiGraph or MultiDiGraph
66
+ A :class:`MultiGraph` or :class:`MultiDiGraph`.
67
+
68
+ Notes
69
+ -----
70
+ Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
71
+ :class:`MultiGraph`.
72
+ """
73
+ import pydot
74
+
75
+ data = path.read()
76
+
77
+ # List of one or more "pydot.Dot" instances deserialized from this file.
78
+ P_list = pydot.graph_from_dot_data(data)
79
+
80
+ # Convert only the first such instance into a NetworkX graph.
81
+ return from_pydot(P_list[0])
82
+
83
+
84
+ @nx._dispatchable(graphs=None, returns_graph=True)
85
+ def from_pydot(P):
86
+ """Returns a NetworkX graph from a Pydot graph.
87
+
88
+ Parameters
89
+ ----------
90
+ P : Pydot graph
91
+ A graph created with Pydot
92
+
93
+ Returns
94
+ -------
95
+ G : NetworkX multigraph
96
+ A MultiGraph or MultiDiGraph.
97
+
98
+ Examples
99
+ --------
100
+ >>> K5 = nx.complete_graph(5)
101
+ >>> A = nx.nx_pydot.to_pydot(K5)
102
+ >>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
103
+
104
+ # make a Graph instead of MultiGraph
105
+ >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
106
+
107
+ """
108
+
109
+ if P.get_strict(None): # pydot bug: get_strict() shouldn't take argument
110
+ multiedges = False
111
+ else:
112
+ multiedges = True
113
+
114
+ if P.get_type() == "graph": # undirected
115
+ if multiedges:
116
+ N = nx.MultiGraph()
117
+ else:
118
+ N = nx.Graph()
119
+ else:
120
+ if multiedges:
121
+ N = nx.MultiDiGraph()
122
+ else:
123
+ N = nx.DiGraph()
124
+
125
+ # assign defaults
126
+ name = P.get_name().strip('"')
127
+ if name != "":
128
+ N.name = name
129
+
130
+ # add nodes, attributes to N.node_attr
131
+ for p in P.get_node_list():
132
+ n = p.get_name().strip('"')
133
+ if n in ("node", "graph", "edge"):
134
+ continue
135
+ N.add_node(n, **p.get_attributes())
136
+
137
+ # add edges
138
+ for e in P.get_edge_list():
139
+ u = e.get_source()
140
+ v = e.get_destination()
141
+ attr = e.get_attributes()
142
+ s = []
143
+ d = []
144
+
145
+ if isinstance(u, str):
146
+ s.append(u.strip('"'))
147
+ else:
148
+ for unodes in u["nodes"]:
149
+ s.append(unodes.strip('"'))
150
+
151
+ if isinstance(v, str):
152
+ d.append(v.strip('"'))
153
+ else:
154
+ for vnodes in v["nodes"]:
155
+ d.append(vnodes.strip('"'))
156
+
157
+ for source_node in s:
158
+ for destination_node in d:
159
+ N.add_edge(source_node, destination_node, **attr)
160
+
161
+ # add default attributes for graph, nodes, edges
162
+ pattr = P.get_attributes()
163
+ if pattr:
164
+ N.graph["graph"] = pattr
165
+ try:
166
+ N.graph["node"] = P.get_node_defaults()[0]
167
+ except (IndexError, TypeError):
168
+ pass # N.graph['node']={}
169
+ try:
170
+ N.graph["edge"] = P.get_edge_defaults()[0]
171
+ except (IndexError, TypeError):
172
+ pass # N.graph['edge']={}
173
+ return N
174
+
175
+
176
+ def to_pydot(N):
177
+ """Returns a pydot graph from a NetworkX graph N.
178
+
179
+ Parameters
180
+ ----------
181
+ N : NetworkX graph
182
+ A graph created with NetworkX
183
+
184
+ Examples
185
+ --------
186
+ >>> K5 = nx.complete_graph(5)
187
+ >>> P = nx.nx_pydot.to_pydot(K5)
188
+
189
+ Notes
190
+ -----
191
+
192
+ """
193
+ import pydot
194
+
195
+ # set Graphviz graph type
196
+ if N.is_directed():
197
+ graph_type = "digraph"
198
+ else:
199
+ graph_type = "graph"
200
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
201
+
202
+ name = N.name
203
+ graph_defaults = N.graph.get("graph", {})
204
+ if name == "":
205
+ P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
206
+ else:
207
+ P = pydot.Dot(
208
+ f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
209
+ )
210
+ try:
211
+ P.set_node_defaults(**N.graph["node"])
212
+ except KeyError:
213
+ pass
214
+ try:
215
+ P.set_edge_defaults(**N.graph["edge"])
216
+ except KeyError:
217
+ pass
218
+
219
+ for n, nodedata in N.nodes(data=True):
220
+ str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
221
+ n = str(n)
222
+ p = pydot.Node(n, **str_nodedata)
223
+ P.add_node(p)
224
+
225
+ if N.is_multigraph():
226
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
227
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
228
+ u, v = str(u), str(v)
229
+ edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
230
+ P.add_edge(edge)
231
+
232
+ else:
233
+ for u, v, edgedata in N.edges(data=True):
234
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
235
+ u, v = str(u), str(v)
236
+ edge = pydot.Edge(u, v, **str_edgedata)
237
+ P.add_edge(edge)
238
+ return P
239
+
240
+
241
+ def graphviz_layout(G, prog="neato", root=None):
242
+ """Create node positions using Pydot and Graphviz.
243
+
244
+ Returns a dictionary of positions keyed by node.
245
+
246
+ Parameters
247
+ ----------
248
+ G : NetworkX Graph
249
+ The graph for which the layout is computed.
250
+ prog : string (default: 'neato')
251
+ The name of the GraphViz program to use for layout.
252
+ Options depend on GraphViz version but may include:
253
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
254
+ root : Node from G or None (default: None)
255
+ The node of G from which to start some layout algorithms.
256
+
257
+ Returns
258
+ -------
259
+ Dictionary of (x, y) positions keyed by node.
260
+
261
+ Examples
262
+ --------
263
+ >>> G = nx.complete_graph(4)
264
+ >>> pos = nx.nx_pydot.graphviz_layout(G)
265
+ >>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
266
+
267
+ Notes
268
+ -----
269
+ This is a wrapper for pydot_layout.
270
+ """
271
+ return pydot_layout(G=G, prog=prog, root=root)
272
+
273
+
274
+ def pydot_layout(G, prog="neato", root=None):
275
+ """Create node positions using :mod:`pydot` and Graphviz.
276
+
277
+ Parameters
278
+ ----------
279
+ G : Graph
280
+ NetworkX graph to be laid out.
281
+ prog : string (default: 'neato')
282
+ Name of the GraphViz command to use for layout.
283
+ Options depend on GraphViz version but may include:
284
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
285
+ root : Node from G or None (default: None)
286
+ The node of G from which to start some layout algorithms.
287
+
288
+ Returns
289
+ -------
290
+ dict
291
+ Dictionary of positions keyed by node.
292
+
293
+ Examples
294
+ --------
295
+ >>> G = nx.complete_graph(4)
296
+ >>> pos = nx.nx_pydot.pydot_layout(G)
297
+ >>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
298
+
299
+ Notes
300
+ -----
301
+ If you use complex node objects, they may have the same string
302
+ representation and GraphViz could treat them as the same node.
303
+ The layout may assign both nodes a single location. See Issue #1568
304
+ If this occurs in your case, consider relabeling the nodes just
305
+ for the layout computation using something similar to::
306
+
307
+ H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
308
+ H_layout = nx.nx_pydot.pydot_layout(H, prog="dot")
309
+ G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
310
+
311
+ """
312
+ import pydot
313
+
314
+ P = to_pydot(G)
315
+ if root is not None:
316
+ P.set("root", str(root))
317
+
318
+ # List of low-level bytes comprising a string in the dot language converted
319
+ # from the passed graph with the passed external GraphViz command.
320
+ D_bytes = P.create_dot(prog=prog)
321
+
322
+ # Unique string decoded from these bytes with the preferred locale encoding
323
+ D = str(D_bytes, encoding=getpreferredencoding())
324
+
325
+ if D == "": # no data returned
326
+ print(f"Graphviz layout with {prog} failed")
327
+ print()
328
+ print("To debug what happened try:")
329
+ print("P = nx.nx_pydot.to_pydot(G)")
330
+ print('P.write_dot("file.dot")')
331
+ print(f"And then run {prog} on file.dot")
332
+ return
333
+
334
+ # List of one or more "pydot.Dot" instances deserialized from this string.
335
+ Q_list = pydot.graph_from_dot_data(D)
336
+ assert len(Q_list) == 1
337
+
338
+ # The first and only such instance, as guaranteed by the above assertion.
339
+ Q = Q_list[0]
340
+
341
+ node_pos = {}
342
+ for n in G.nodes():
343
+ str_n = str(n)
344
+ node = Q.get_node(pydot.quote_id_if_necessary(str_n))
345
+
346
+ if isinstance(node, list):
347
+ node = node[0]
348
+ pos = node.get_pos()[1:-1] # strip leading and trailing double quotes
349
+ if pos is not None:
350
+ xx, yy = pos.split(",")
351
+ node_pos[n] = (float(xx), float(yy))
352
+ return node_pos
wemm/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py ADDED
@@ -0,0 +1,1979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **********
3
+ Matplotlib
4
+ **********
5
+
6
+ Draw networks with matplotlib.
7
+
8
+ Examples
9
+ --------
10
+ >>> G = nx.complete_graph(5)
11
+ >>> nx.draw(G)
12
+
13
+ See Also
14
+ --------
15
+ - :doc:`matplotlib <matplotlib:index>`
16
+ - :func:`matplotlib.pyplot.scatter`
17
+ - :obj:`matplotlib.patches.FancyArrowPatch`
18
+ """
19
+
20
+ import collections
21
+ import itertools
22
+ from numbers import Number
23
+
24
+ import networkx as nx
25
+ from networkx.drawing.layout import (
26
+ circular_layout,
27
+ forceatlas2_layout,
28
+ kamada_kawai_layout,
29
+ planar_layout,
30
+ random_layout,
31
+ shell_layout,
32
+ spectral_layout,
33
+ spring_layout,
34
+ )
35
+
36
+ __all__ = [
37
+ "draw",
38
+ "draw_networkx",
39
+ "draw_networkx_nodes",
40
+ "draw_networkx_edges",
41
+ "draw_networkx_labels",
42
+ "draw_networkx_edge_labels",
43
+ "draw_circular",
44
+ "draw_kamada_kawai",
45
+ "draw_random",
46
+ "draw_spectral",
47
+ "draw_spring",
48
+ "draw_planar",
49
+ "draw_shell",
50
+ "draw_forceatlas2",
51
+ ]
52
+
53
+
54
+ def draw(G, pos=None, ax=None, **kwds):
55
+ """Draw the graph G with Matplotlib.
56
+
57
+ Draw the graph as a simple representation with no node
58
+ labels or edge labels and using the full Matplotlib figure area
59
+ and no axis labels by default. See draw_networkx() for more
60
+ full-featured drawing that allows title, axis labels etc.
61
+
62
+ Parameters
63
+ ----------
64
+ G : graph
65
+ A networkx graph
66
+
67
+ pos : dictionary, optional
68
+ A dictionary with nodes as keys and positions as values.
69
+ If not specified a spring layout positioning will be computed.
70
+ See :py:mod:`networkx.drawing.layout` for functions that
71
+ compute node positions.
72
+
73
+ ax : Matplotlib Axes object, optional
74
+ Draw the graph in specified Matplotlib axes.
75
+
76
+ kwds : optional keywords
77
+ See networkx.draw_networkx() for a description of optional keywords.
78
+
79
+ Examples
80
+ --------
81
+ >>> G = nx.dodecahedral_graph()
82
+ >>> nx.draw(G)
83
+ >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
84
+
85
+ See Also
86
+ --------
87
+ draw_networkx
88
+ draw_networkx_nodes
89
+ draw_networkx_edges
90
+ draw_networkx_labels
91
+ draw_networkx_edge_labels
92
+
93
+ Notes
94
+ -----
95
+ This function has the same name as pylab.draw and pyplot.draw
96
+ so beware when using `from networkx import *`
97
+
98
+ since you might overwrite the pylab.draw function.
99
+
100
+ With pyplot use
101
+
102
+ >>> import matplotlib.pyplot as plt
103
+ >>> G = nx.dodecahedral_graph()
104
+ >>> nx.draw(G) # networkx draw()
105
+ >>> plt.draw() # pyplot draw()
106
+
107
+ Also see the NetworkX drawing examples at
108
+ https://networkx.org/documentation/latest/auto_examples/index.html
109
+ """
110
+ import matplotlib.pyplot as plt
111
+
112
+ if ax is None:
113
+ cf = plt.gcf()
114
+ else:
115
+ cf = ax.get_figure()
116
+ cf.set_facecolor("w")
117
+ if ax is None:
118
+ if cf.axes:
119
+ ax = cf.gca()
120
+ else:
121
+ ax = cf.add_axes((0, 0, 1, 1))
122
+
123
+ if "with_labels" not in kwds:
124
+ kwds["with_labels"] = "labels" in kwds
125
+
126
+ draw_networkx(G, pos=pos, ax=ax, **kwds)
127
+ ax.set_axis_off()
128
+ plt.draw_if_interactive()
129
+ return
130
+
131
+
132
+ def draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds):
133
+ r"""Draw the graph G using Matplotlib.
134
+
135
+ Draw the graph with Matplotlib with options for node positions,
136
+ labeling, titles, and many other drawing features.
137
+ See draw() for simple drawing without labels or axes.
138
+
139
+ Parameters
140
+ ----------
141
+ G : graph
142
+ A networkx graph
143
+
144
+ pos : dictionary, optional
145
+ A dictionary with nodes as keys and positions as values.
146
+ If not specified a spring layout positioning will be computed.
147
+ See :py:mod:`networkx.drawing.layout` for functions that
148
+ compute node positions.
149
+
150
+ arrows : bool or None, optional (default=None)
151
+ If `None`, directed graphs draw arrowheads with
152
+ `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
153
+ via `~matplotlib.collections.LineCollection` for speed.
154
+ If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
155
+ If `False`, draw edges using LineCollection (linear and fast).
156
+ For directed graphs, if True draw arrowheads.
157
+ Note: Arrows will be the same color as edges.
158
+
159
+ arrowstyle : str (default='-\|>' for directed graphs)
160
+ For directed graphs, choose the style of the arrowsheads.
161
+ For undirected graphs default to '-'
162
+
163
+ See `matplotlib.patches.ArrowStyle` for more options.
164
+
165
+ arrowsize : int or list (default=10)
166
+ For directed graphs, choose the size of the arrow head's length and
167
+ width. A list of values can be passed in to assign a different size for arrow head's length and width.
168
+ See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
169
+ for more info.
170
+
171
+ with_labels : bool (default=True)
172
+ Set to True to draw labels on the nodes.
173
+
174
+ ax : Matplotlib Axes object, optional
175
+ Draw the graph in the specified Matplotlib axes.
176
+
177
+ nodelist : list (default=list(G))
178
+ Draw only specified nodes
179
+
180
+ edgelist : list (default=list(G.edges()))
181
+ Draw only specified edges
182
+
183
+ node_size : scalar or array (default=300)
184
+ Size of nodes. If an array is specified it must be the
185
+ same length as nodelist.
186
+
187
+ node_color : color or array of colors (default='#1f78b4')
188
+ Node color. Can be a single color or a sequence of colors with the same
189
+ length as nodelist. Color can be string or rgb (or rgba) tuple of
190
+ floats from 0-1. If numeric values are specified they will be
191
+ mapped to colors using the cmap and vmin,vmax parameters. See
192
+ matplotlib.scatter for more details.
193
+
194
+ node_shape : string (default='o')
195
+ The shape of the node. Specification is as matplotlib.scatter
196
+ marker, one of 'so^>v<dph8'.
197
+
198
+ alpha : float or None (default=None)
199
+ The node and edge transparency
200
+
201
+ cmap : Matplotlib colormap, optional
202
+ Colormap for mapping intensities of nodes
203
+
204
+ vmin,vmax : float, optional
205
+ Minimum and maximum for node colormap scaling
206
+
207
+ linewidths : scalar or sequence (default=1.0)
208
+ Line width of symbol border
209
+
210
+ width : float or array of floats (default=1.0)
211
+ Line width of edges
212
+
213
+ edge_color : color or array of colors (default='k')
214
+ Edge color. Can be a single color or a sequence of colors with the same
215
+ length as edgelist. Color can be string or rgb (or rgba) tuple of
216
+ floats from 0-1. If numeric values are specified they will be
217
+ mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
218
+
219
+ edge_cmap : Matplotlib colormap, optional
220
+ Colormap for mapping intensities of edges
221
+
222
+ edge_vmin,edge_vmax : floats, optional
223
+ Minimum and maximum for edge colormap scaling
224
+
225
+ style : string (default=solid line)
226
+ Edge line style e.g.: '-', '--', '-.', ':'
227
+ or words like 'solid' or 'dashed'.
228
+ (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
229
+
230
+ labels : dictionary (default=None)
231
+ Node labels in a dictionary of text labels keyed by node
232
+
233
+ font_size : int (default=12 for nodes, 10 for edges)
234
+ Font size for text labels
235
+
236
+ font_color : color (default='k' black)
237
+ Font color string. Color can be string or rgb (or rgba) tuple of
238
+ floats from 0-1.
239
+
240
+ font_weight : string (default='normal')
241
+ Font weight
242
+
243
+ font_family : string (default='sans-serif')
244
+ Font family
245
+
246
+ label : string, optional
247
+ Label for graph legend
248
+
249
+ hide_ticks : bool, optional
250
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
251
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
252
+ use ``hide_ticks=False``.
253
+
254
+ kwds : optional keywords
255
+ See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
256
+ networkx.draw_networkx_labels() for a description of optional keywords.
257
+
258
+ Notes
259
+ -----
260
+ For directed graphs, arrows are drawn at the head end. Arrows can be
261
+ turned off with keyword arrows=False.
262
+
263
+ Examples
264
+ --------
265
+ >>> G = nx.dodecahedral_graph()
266
+ >>> nx.draw(G)
267
+ >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
268
+
269
+ >>> import matplotlib.pyplot as plt
270
+ >>> limits = plt.axis("off") # turn off axis
271
+
272
+ Also see the NetworkX drawing examples at
273
+ https://networkx.org/documentation/latest/auto_examples/index.html
274
+
275
+ See Also
276
+ --------
277
+ draw
278
+ draw_networkx_nodes
279
+ draw_networkx_edges
280
+ draw_networkx_labels
281
+ draw_networkx_edge_labels
282
+ """
283
+ from inspect import signature
284
+
285
+ import matplotlib.pyplot as plt
286
+
287
+ # Get all valid keywords by inspecting the signatures of draw_networkx_nodes,
288
+ # draw_networkx_edges, draw_networkx_labels
289
+
290
+ valid_node_kwds = signature(draw_networkx_nodes).parameters.keys()
291
+ valid_edge_kwds = signature(draw_networkx_edges).parameters.keys()
292
+ valid_label_kwds = signature(draw_networkx_labels).parameters.keys()
293
+
294
+ # Create a set with all valid keywords across the three functions and
295
+ # remove the arguments of this function (draw_networkx)
296
+ valid_kwds = (valid_node_kwds | valid_edge_kwds | valid_label_kwds) - {
297
+ "G",
298
+ "pos",
299
+ "arrows",
300
+ "with_labels",
301
+ }
302
+
303
+ if any(k not in valid_kwds for k in kwds):
304
+ invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
305
+ raise ValueError(f"Received invalid argument(s): {invalid_args}")
306
+
307
+ node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
308
+ edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
309
+ label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
310
+
311
+ if pos is None:
312
+ pos = nx.drawing.spring_layout(G) # default to spring layout
313
+
314
+ draw_networkx_nodes(G, pos, **node_kwds)
315
+ draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
316
+ if with_labels:
317
+ draw_networkx_labels(G, pos, **label_kwds)
318
+ plt.draw_if_interactive()
319
+
320
+
321
+ def draw_networkx_nodes(
322
+ G,
323
+ pos,
324
+ nodelist=None,
325
+ node_size=300,
326
+ node_color="#1f78b4",
327
+ node_shape="o",
328
+ alpha=None,
329
+ cmap=None,
330
+ vmin=None,
331
+ vmax=None,
332
+ ax=None,
333
+ linewidths=None,
334
+ edgecolors=None,
335
+ label=None,
336
+ margins=None,
337
+ hide_ticks=True,
338
+ ):
339
+ """Draw the nodes of the graph G.
340
+
341
+ This draws only the nodes of the graph G.
342
+
343
+ Parameters
344
+ ----------
345
+ G : graph
346
+ A networkx graph
347
+
348
+ pos : dictionary
349
+ A dictionary with nodes as keys and positions as values.
350
+ Positions should be sequences of length 2.
351
+
352
+ ax : Matplotlib Axes object, optional
353
+ Draw the graph in the specified Matplotlib axes.
354
+
355
+ nodelist : list (default list(G))
356
+ Draw only specified nodes
357
+
358
+ node_size : scalar or array (default=300)
359
+ Size of nodes. If an array it must be the same length as nodelist.
360
+
361
+ node_color : color or array of colors (default='#1f78b4')
362
+ Node color. Can be a single color or a sequence of colors with the same
363
+ length as nodelist. Color can be string or rgb (or rgba) tuple of
364
+ floats from 0-1. If numeric values are specified they will be
365
+ mapped to colors using the cmap and vmin,vmax parameters. See
366
+ matplotlib.scatter for more details.
367
+
368
+ node_shape : string (default='o')
369
+ The shape of the node. Specification is as matplotlib.scatter
370
+ marker, one of 'so^>v<dph8'.
371
+
372
+ alpha : float or array of floats (default=None)
373
+ The node transparency. This can be a single alpha value,
374
+ in which case it will be applied to all the nodes of color. Otherwise,
375
+ if it is an array, the elements of alpha will be applied to the colors
376
+ in order (cycling through alpha multiple times if necessary).
377
+
378
+ cmap : Matplotlib colormap (default=None)
379
+ Colormap for mapping intensities of nodes
380
+
381
+ vmin,vmax : floats or None (default=None)
382
+ Minimum and maximum for node colormap scaling
383
+
384
+ linewidths : [None | scalar | sequence] (default=1.0)
385
+ Line width of symbol border
386
+
387
+ edgecolors : [None | scalar | sequence] (default = node_color)
388
+ Colors of node borders. Can be a single color or a sequence of colors with the
389
+ same length as nodelist. Color can be string or rgb (or rgba) tuple of floats
390
+ from 0-1. If numeric values are specified they will be mapped to colors
391
+ using the cmap and vmin,vmax parameters. See `~matplotlib.pyplot.scatter` for more details.
392
+
393
+ label : [None | string]
394
+ Label for legend
395
+
396
+ margins : float or 2-tuple, optional
397
+ Sets the padding for axis autoscaling. Increase margin to prevent
398
+ clipping for nodes that are near the edges of an image. Values should
399
+ be in the range ``[0, 1]``. See :meth:`matplotlib.axes.Axes.margins`
400
+ for details. The default is `None`, which uses the Matplotlib default.
401
+
402
+ hide_ticks : bool, optional
403
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
404
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
405
+ use ``hide_ticks=False``.
406
+
407
+ Returns
408
+ -------
409
+ matplotlib.collections.PathCollection
410
+ `PathCollection` of the nodes.
411
+
412
+ Examples
413
+ --------
414
+ >>> G = nx.dodecahedral_graph()
415
+ >>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
416
+
417
+ Also see the NetworkX drawing examples at
418
+ https://networkx.org/documentation/latest/auto_examples/index.html
419
+
420
+ See Also
421
+ --------
422
+ draw
423
+ draw_networkx
424
+ draw_networkx_edges
425
+ draw_networkx_labels
426
+ draw_networkx_edge_labels
427
+ """
428
+ from collections.abc import Iterable
429
+
430
+ import matplotlib as mpl
431
+ import matplotlib.collections # call as mpl.collections
432
+ import matplotlib.pyplot as plt
433
+ import numpy as np
434
+
435
+ if ax is None:
436
+ ax = plt.gca()
437
+
438
+ if nodelist is None:
439
+ nodelist = list(G)
440
+
441
+ if len(nodelist) == 0: # empty nodelist, no drawing
442
+ return mpl.collections.PathCollection(None)
443
+
444
+ try:
445
+ xy = np.asarray([pos[v] for v in nodelist])
446
+ except KeyError as err:
447
+ raise nx.NetworkXError(f"Node {err} has no position.") from err
448
+
449
+ if isinstance(alpha, Iterable):
450
+ node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
451
+ alpha = None
452
+
453
+ if not isinstance(node_shape, np.ndarray) and not isinstance(node_shape, list):
454
+ node_shape = np.array([node_shape for _ in range(len(nodelist))])
455
+
456
+ for shape in np.unique(node_shape):
457
+ node_collection = ax.scatter(
458
+ xy[node_shape == shape, 0],
459
+ xy[node_shape == shape, 1],
460
+ s=node_size,
461
+ c=node_color,
462
+ marker=shape,
463
+ cmap=cmap,
464
+ vmin=vmin,
465
+ vmax=vmax,
466
+ alpha=alpha,
467
+ linewidths=linewidths,
468
+ edgecolors=edgecolors,
469
+ label=label,
470
+ )
471
+ if hide_ticks:
472
+ ax.tick_params(
473
+ axis="both",
474
+ which="both",
475
+ bottom=False,
476
+ left=False,
477
+ labelbottom=False,
478
+ labelleft=False,
479
+ )
480
+
481
+ if margins is not None:
482
+ if isinstance(margins, Iterable):
483
+ ax.margins(*margins)
484
+ else:
485
+ ax.margins(margins)
486
+
487
+ node_collection.set_zorder(2)
488
+ return node_collection
489
+
490
+
491
+ class FancyArrowFactory:
492
+ """Draw arrows with `matplotlib.patches.FancyarrowPatch`"""
493
+
494
+ class ConnectionStyleFactory:
495
+ def __init__(self, connectionstyles, selfloop_height, ax=None):
496
+ import matplotlib as mpl
497
+ import matplotlib.path # call as mpl.path
498
+ import numpy as np
499
+
500
+ self.ax = ax
501
+ self.mpl = mpl
502
+ self.np = np
503
+ self.base_connection_styles = [
504
+ mpl.patches.ConnectionStyle(cs) for cs in connectionstyles
505
+ ]
506
+ self.n = len(self.base_connection_styles)
507
+ self.selfloop_height = selfloop_height
508
+
509
+ def curved(self, edge_index):
510
+ return self.base_connection_styles[edge_index % self.n]
511
+
512
+ def self_loop(self, edge_index):
513
+ def self_loop_connection(posA, posB, *args, **kwargs):
514
+ if not self.np.all(posA == posB):
515
+ raise nx.NetworkXError(
516
+ "`self_loop` connection style method"
517
+ "is only to be used for self-loops"
518
+ )
519
+ # this is called with _screen space_ values
520
+ # so convert back to data space
521
+ data_loc = self.ax.transData.inverted().transform(posA)
522
+ v_shift = 0.1 * self.selfloop_height
523
+ h_shift = v_shift * 0.5
524
+ # put the top of the loop first so arrow is not hidden by node
525
+ path = self.np.asarray(
526
+ [
527
+ # 1
528
+ [0, v_shift],
529
+ # 4 4 4
530
+ [h_shift, v_shift],
531
+ [h_shift, 0],
532
+ [0, 0],
533
+ # 4 4 4
534
+ [-h_shift, 0],
535
+ [-h_shift, v_shift],
536
+ [0, v_shift],
537
+ ]
538
+ )
539
+ # Rotate self loop 90 deg. if more than 1
540
+ # This will allow for maximum of 4 visible self loops
541
+ if edge_index % 4:
542
+ x, y = path.T
543
+ for _ in range(edge_index % 4):
544
+ x, y = y, -x
545
+ path = self.np.array([x, y]).T
546
+ return self.mpl.path.Path(
547
+ self.ax.transData.transform(data_loc + path), [1, 4, 4, 4, 4, 4, 4]
548
+ )
549
+
550
+ return self_loop_connection
551
+
552
+ def __init__(
553
+ self,
554
+ edge_pos,
555
+ edgelist,
556
+ nodelist,
557
+ edge_indices,
558
+ node_size,
559
+ selfloop_height,
560
+ connectionstyle="arc3",
561
+ node_shape="o",
562
+ arrowstyle="-",
563
+ arrowsize=10,
564
+ edge_color="k",
565
+ alpha=None,
566
+ linewidth=1.0,
567
+ style="solid",
568
+ min_source_margin=0,
569
+ min_target_margin=0,
570
+ ax=None,
571
+ ):
572
+ import matplotlib as mpl
573
+ import matplotlib.patches # call as mpl.patches
574
+ import matplotlib.pyplot as plt
575
+ import numpy as np
576
+
577
+ if isinstance(connectionstyle, str):
578
+ connectionstyle = [connectionstyle]
579
+ elif np.iterable(connectionstyle):
580
+ connectionstyle = list(connectionstyle)
581
+ else:
582
+ msg = "ConnectionStyleFactory arg `connectionstyle` must be str or iterable"
583
+ raise nx.NetworkXError(msg)
584
+ self.ax = ax
585
+ self.mpl = mpl
586
+ self.np = np
587
+ self.edge_pos = edge_pos
588
+ self.edgelist = edgelist
589
+ self.nodelist = nodelist
590
+ self.node_shape = node_shape
591
+ self.min_source_margin = min_source_margin
592
+ self.min_target_margin = min_target_margin
593
+ self.edge_indices = edge_indices
594
+ self.node_size = node_size
595
+ self.connectionstyle_factory = self.ConnectionStyleFactory(
596
+ connectionstyle, selfloop_height, ax
597
+ )
598
+ self.arrowstyle = arrowstyle
599
+ self.arrowsize = arrowsize
600
+ self.arrow_colors = mpl.colors.colorConverter.to_rgba_array(edge_color, alpha)
601
+ self.linewidth = linewidth
602
+ self.style = style
603
+ if isinstance(arrowsize, list) and len(arrowsize) != len(edge_pos):
604
+ raise ValueError("arrowsize should have the same length as edgelist")
605
+
606
+ def __call__(self, i):
607
+ (x1, y1), (x2, y2) = self.edge_pos[i]
608
+ shrink_source = 0 # space from source to tail
609
+ shrink_target = 0 # space from head to target
610
+ if (
611
+ self.np.iterable(self.min_source_margin)
612
+ and not isinstance(self.min_source_margin, str)
613
+ and not isinstance(self.min_source_margin, tuple)
614
+ ):
615
+ min_source_margin = self.min_source_margin[i]
616
+ else:
617
+ min_source_margin = self.min_source_margin
618
+
619
+ if (
620
+ self.np.iterable(self.min_target_margin)
621
+ and not isinstance(self.min_target_margin, str)
622
+ and not isinstance(self.min_target_margin, tuple)
623
+ ):
624
+ min_target_margin = self.min_target_margin[i]
625
+ else:
626
+ min_target_margin = self.min_target_margin
627
+
628
+ if self.np.iterable(self.node_size): # many node sizes
629
+ source, target = self.edgelist[i][:2]
630
+ source_node_size = self.node_size[self.nodelist.index(source)]
631
+ target_node_size = self.node_size[self.nodelist.index(target)]
632
+ shrink_source = self.to_marker_edge(source_node_size, self.node_shape)
633
+ shrink_target = self.to_marker_edge(target_node_size, self.node_shape)
634
+ else:
635
+ shrink_source = self.to_marker_edge(self.node_size, self.node_shape)
636
+ shrink_target = shrink_source
637
+ shrink_source = max(shrink_source, min_source_margin)
638
+ shrink_target = max(shrink_target, min_target_margin)
639
+
640
+ # scale factor of arrow head
641
+ if isinstance(self.arrowsize, list):
642
+ mutation_scale = self.arrowsize[i]
643
+ else:
644
+ mutation_scale = self.arrowsize
645
+
646
+ if len(self.arrow_colors) > i:
647
+ arrow_color = self.arrow_colors[i]
648
+ elif len(self.arrow_colors) == 1:
649
+ arrow_color = self.arrow_colors[0]
650
+ else: # Cycle through colors
651
+ arrow_color = self.arrow_colors[i % len(self.arrow_colors)]
652
+
653
+ if self.np.iterable(self.linewidth):
654
+ if len(self.linewidth) > i:
655
+ linewidth = self.linewidth[i]
656
+ else:
657
+ linewidth = self.linewidth[i % len(self.linewidth)]
658
+ else:
659
+ linewidth = self.linewidth
660
+
661
+ if (
662
+ self.np.iterable(self.style)
663
+ and not isinstance(self.style, str)
664
+ and not isinstance(self.style, tuple)
665
+ ):
666
+ if len(self.style) > i:
667
+ linestyle = self.style[i]
668
+ else: # Cycle through styles
669
+ linestyle = self.style[i % len(self.style)]
670
+ else:
671
+ linestyle = self.style
672
+
673
+ if x1 == x2 and y1 == y2:
674
+ connectionstyle = self.connectionstyle_factory.self_loop(
675
+ self.edge_indices[i]
676
+ )
677
+ else:
678
+ connectionstyle = self.connectionstyle_factory.curved(self.edge_indices[i])
679
+
680
+ if (
681
+ self.np.iterable(self.arrowstyle)
682
+ and not isinstance(self.arrowstyle, str)
683
+ and not isinstance(self.arrowstyle, tuple)
684
+ ):
685
+ arrowstyle = self.arrowstyle[i]
686
+ else:
687
+ arrowstyle = self.arrowstyle
688
+
689
+ return self.mpl.patches.FancyArrowPatch(
690
+ (x1, y1),
691
+ (x2, y2),
692
+ arrowstyle=arrowstyle,
693
+ shrinkA=shrink_source,
694
+ shrinkB=shrink_target,
695
+ mutation_scale=mutation_scale,
696
+ color=arrow_color,
697
+ linewidth=linewidth,
698
+ connectionstyle=connectionstyle,
699
+ linestyle=linestyle,
700
+ zorder=1, # arrows go behind nodes
701
+ )
702
+
703
+ def to_marker_edge(self, marker_size, marker):
704
+ if marker in "s^>v<d": # `large` markers need extra space
705
+ return self.np.sqrt(2 * marker_size) / 2
706
+ else:
707
+ return self.np.sqrt(marker_size) / 2
708
+
709
+
710
+ def draw_networkx_edges(
711
+ G,
712
+ pos,
713
+ edgelist=None,
714
+ width=1.0,
715
+ edge_color="k",
716
+ style="solid",
717
+ alpha=None,
718
+ arrowstyle=None,
719
+ arrowsize=10,
720
+ edge_cmap=None,
721
+ edge_vmin=None,
722
+ edge_vmax=None,
723
+ ax=None,
724
+ arrows=None,
725
+ label=None,
726
+ node_size=300,
727
+ nodelist=None,
728
+ node_shape="o",
729
+ connectionstyle="arc3",
730
+ min_source_margin=0,
731
+ min_target_margin=0,
732
+ hide_ticks=True,
733
+ ):
734
+ r"""Draw the edges of the graph G.
735
+
736
+ This draws only the edges of the graph G.
737
+
738
+ Parameters
739
+ ----------
740
+ G : graph
741
+ A networkx graph
742
+
743
+ pos : dictionary
744
+ A dictionary with nodes as keys and positions as values.
745
+ Positions should be sequences of length 2.
746
+
747
+ edgelist : collection of edge tuples (default=G.edges())
748
+ Draw only specified edges
749
+
750
+ width : float or array of floats (default=1.0)
751
+ Line width of edges
752
+
753
+ edge_color : color or array of colors (default='k')
754
+ Edge color. Can be a single color or a sequence of colors with the same
755
+ length as edgelist. Color can be string or rgb (or rgba) tuple of
756
+ floats from 0-1. If numeric values are specified they will be
757
+ mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
758
+
759
+ style : string or array of strings (default='solid')
760
+ Edge line style e.g.: '-', '--', '-.', ':'
761
+ or words like 'solid' or 'dashed'.
762
+ Can be a single style or a sequence of styles with the same
763
+ length as the edge list.
764
+ If less styles than edges are given the styles will cycle.
765
+ If more styles than edges are given the styles will be used sequentially
766
+ and not be exhausted.
767
+ Also, `(offset, onoffseq)` tuples can be used as style instead of a strings.
768
+ (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
769
+
770
+ alpha : float or array of floats (default=None)
771
+ The edge transparency. This can be a single alpha value,
772
+ in which case it will be applied to all specified edges. Otherwise,
773
+ if it is an array, the elements of alpha will be applied to the colors
774
+ in order (cycling through alpha multiple times if necessary).
775
+
776
+ edge_cmap : Matplotlib colormap, optional
777
+ Colormap for mapping intensities of edges
778
+
779
+ edge_vmin,edge_vmax : floats, optional
780
+ Minimum and maximum for edge colormap scaling
781
+
782
+ ax : Matplotlib Axes object, optional
783
+ Draw the graph in the specified Matplotlib axes.
784
+
785
+ arrows : bool or None, optional (default=None)
786
+ If `None`, directed graphs draw arrowheads with
787
+ `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
788
+ via `~matplotlib.collections.LineCollection` for speed.
789
+ If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
790
+ If `False`, draw edges using LineCollection (linear and fast).
791
+
792
+ Note: Arrowheads will be the same color as edges.
793
+
794
+ arrowstyle : str or list of strs (default='-\|>' for directed graphs)
795
+ For directed graphs and `arrows==True` defaults to '-\|>',
796
+ For undirected graphs default to '-'.
797
+
798
+ See `matplotlib.patches.ArrowStyle` for more options.
799
+
800
+ arrowsize : int or list of ints(default=10)
801
+ For directed graphs, choose the size of the arrow head's length and
802
+ width. See `matplotlib.patches.FancyArrowPatch` for attribute
803
+ `mutation_scale` for more info.
804
+
805
+ connectionstyle : string or iterable of strings (default="arc3")
806
+ Pass the connectionstyle parameter to create curved arc of rounding
807
+ radius rad. For example, connectionstyle='arc3,rad=0.2'.
808
+ See `matplotlib.patches.ConnectionStyle` and
809
+ `matplotlib.patches.FancyArrowPatch` for more info.
810
+ If Iterable, index indicates i'th edge key of MultiGraph
811
+
812
+ node_size : scalar or array (default=300)
813
+ Size of nodes. Though the nodes are not drawn with this function, the
814
+ node size is used in determining edge positioning.
815
+
816
+ nodelist : list, optional (default=G.nodes())
817
+ This provides the node order for the `node_size` array (if it is an array).
818
+
819
+ node_shape : string (default='o')
820
+ The marker used for nodes, used in determining edge positioning.
821
+ Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v<dph8'.
822
+
823
+ label : None or string
824
+ Label for legend
825
+
826
+ min_source_margin : int or list of ints (default=0)
827
+ The minimum margin (gap) at the beginning of the edge at the source.
828
+
829
+ min_target_margin : int or list of ints (default=0)
830
+ The minimum margin (gap) at the end of the edge at the target.
831
+
832
+ hide_ticks : bool, optional
833
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
834
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
835
+ use ``hide_ticks=False``.
836
+
837
+ Returns
838
+ -------
839
+ matplotlib.collections.LineCollection or a list of matplotlib.patches.FancyArrowPatch
840
+ If ``arrows=True``, a list of FancyArrowPatches is returned.
841
+ If ``arrows=False``, a LineCollection is returned.
842
+ If ``arrows=None`` (the default), then a LineCollection is returned if
843
+ `G` is undirected, otherwise returns a list of FancyArrowPatches.
844
+
845
+ Notes
846
+ -----
847
+ For directed graphs, arrows are drawn at the head end. Arrows can be
848
+ turned off with keyword arrows=False or by passing an arrowstyle without
849
+ an arrow on the end.
850
+
851
+ Be sure to include `node_size` as a keyword argument; arrows are
852
+ drawn considering the size of nodes.
853
+
854
+ Self-loops are always drawn with `~matplotlib.patches.FancyArrowPatch`
855
+ regardless of the value of `arrows` or whether `G` is directed.
856
+ When ``arrows=False`` or ``arrows=None`` and `G` is undirected, the
857
+ FancyArrowPatches corresponding to the self-loops are not explicitly
858
+ returned. They should instead be accessed via the ``Axes.patches``
859
+ attribute (see examples).
860
+
861
+ Examples
862
+ --------
863
+ >>> G = nx.dodecahedral_graph()
864
+ >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
865
+
866
+ >>> G = nx.DiGraph()
867
+ >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
868
+ >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
869
+ >>> alphas = [0.3, 0.4, 0.5]
870
+ >>> for i, arc in enumerate(arcs): # change alpha values of arcs
871
+ ... arc.set_alpha(alphas[i])
872
+
873
+ The FancyArrowPatches corresponding to self-loops are not always
874
+ returned, but can always be accessed via the ``patches`` attribute of the
875
+ `matplotlib.Axes` object.
876
+
877
+ >>> import matplotlib.pyplot as plt
878
+ >>> fig, ax = plt.subplots()
879
+ >>> G = nx.Graph([(0, 1), (0, 0)]) # Self-loop at node 0
880
+ >>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
881
+ >>> self_loop_fap = ax.patches[0]
882
+
883
+ Also see the NetworkX drawing examples at
884
+ https://networkx.org/documentation/latest/auto_examples/index.html
885
+
886
+ See Also
887
+ --------
888
+ draw
889
+ draw_networkx
890
+ draw_networkx_nodes
891
+ draw_networkx_labels
892
+ draw_networkx_edge_labels
893
+
894
+ """
895
+ import warnings
896
+
897
+ import matplotlib as mpl
898
+ import matplotlib.collections # call as mpl.collections
899
+ import matplotlib.colors # call as mpl.colors
900
+ import matplotlib.pyplot as plt
901
+ import numpy as np
902
+
903
+ # The default behavior is to use LineCollection to draw edges for
904
+ # undirected graphs (for performance reasons) and use FancyArrowPatches
905
+ # for directed graphs.
906
+ # The `arrows` keyword can be used to override the default behavior
907
+ if arrows is None:
908
+ use_linecollection = not (G.is_directed() or G.is_multigraph())
909
+ else:
910
+ if not isinstance(arrows, bool):
911
+ raise TypeError("Argument `arrows` must be of type bool or None")
912
+ use_linecollection = not arrows
913
+
914
+ if isinstance(connectionstyle, str):
915
+ connectionstyle = [connectionstyle]
916
+ elif np.iterable(connectionstyle):
917
+ connectionstyle = list(connectionstyle)
918
+ else:
919
+ msg = "draw_networkx_edges arg `connectionstyle` must be str or iterable"
920
+ raise nx.NetworkXError(msg)
921
+
922
+ # Some kwargs only apply to FancyArrowPatches. Warn users when they use
923
+ # non-default values for these kwargs when LineCollection is being used
924
+ # instead of silently ignoring the specified option
925
+ if use_linecollection:
926
+ msg = (
927
+ "\n\nThe {0} keyword argument is not applicable when drawing edges\n"
928
+ "with LineCollection.\n\n"
929
+ "To make this warning go away, either specify `arrows=True` to\n"
930
+ "force FancyArrowPatches or use the default values.\n"
931
+ "Note that using FancyArrowPatches may be slow for large graphs.\n"
932
+ )
933
+ if arrowstyle is not None:
934
+ warnings.warn(msg.format("arrowstyle"), category=UserWarning, stacklevel=2)
935
+ if arrowsize != 10:
936
+ warnings.warn(msg.format("arrowsize"), category=UserWarning, stacklevel=2)
937
+ if min_source_margin != 0:
938
+ warnings.warn(
939
+ msg.format("min_source_margin"), category=UserWarning, stacklevel=2
940
+ )
941
+ if min_target_margin != 0:
942
+ warnings.warn(
943
+ msg.format("min_target_margin"), category=UserWarning, stacklevel=2
944
+ )
945
+ if any(cs != "arc3" for cs in connectionstyle):
946
+ warnings.warn(
947
+ msg.format("connectionstyle"), category=UserWarning, stacklevel=2
948
+ )
949
+
950
+ # NOTE: Arrowstyle modification must occur after the warnings section
951
+ if arrowstyle is None:
952
+ arrowstyle = "-|>" if G.is_directed() else "-"
953
+
954
+ if ax is None:
955
+ ax = plt.gca()
956
+
957
+ if edgelist is None:
958
+ edgelist = list(G.edges) # (u, v, k) for multigraph (u, v) otherwise
959
+
960
+ if len(edgelist):
961
+ if G.is_multigraph():
962
+ key_count = collections.defaultdict(lambda: itertools.count(0))
963
+ edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
964
+ else:
965
+ edge_indices = [0] * len(edgelist)
966
+ else: # no edges!
967
+ return []
968
+
969
+ if nodelist is None:
970
+ nodelist = list(G.nodes())
971
+
972
+ # FancyArrowPatch handles color=None different from LineCollection
973
+ if edge_color is None:
974
+ edge_color = "k"
975
+
976
+ # set edge positions
977
+ edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
978
+
979
+ # Check if edge_color is an array of floats and map to edge_cmap.
980
+ # This is the only case handled differently from matplotlib
981
+ if (
982
+ np.iterable(edge_color)
983
+ and (len(edge_color) == len(edge_pos))
984
+ and np.all([isinstance(c, Number) for c in edge_color])
985
+ ):
986
+ if edge_cmap is not None:
987
+ assert isinstance(edge_cmap, mpl.colors.Colormap)
988
+ else:
989
+ edge_cmap = plt.get_cmap()
990
+ if edge_vmin is None:
991
+ edge_vmin = min(edge_color)
992
+ if edge_vmax is None:
993
+ edge_vmax = max(edge_color)
994
+ color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax)
995
+ edge_color = [edge_cmap(color_normal(e)) for e in edge_color]
996
+
997
+ # compute initial view
998
+ minx = np.amin(np.ravel(edge_pos[:, :, 0]))
999
+ maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
1000
+ miny = np.amin(np.ravel(edge_pos[:, :, 1]))
1001
+ maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
1002
+ w = maxx - minx
1003
+ h = maxy - miny
1004
+
1005
+ # Self-loops are scaled by view extent, except in cases the extent
1006
+ # is 0, e.g. for a single node. In this case, fall back to scaling
1007
+ # by the maximum node size
1008
+ selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
1009
+ fancy_arrow_factory = FancyArrowFactory(
1010
+ edge_pos,
1011
+ edgelist,
1012
+ nodelist,
1013
+ edge_indices,
1014
+ node_size,
1015
+ selfloop_height,
1016
+ connectionstyle,
1017
+ node_shape,
1018
+ arrowstyle,
1019
+ arrowsize,
1020
+ edge_color,
1021
+ alpha,
1022
+ width,
1023
+ style,
1024
+ min_source_margin,
1025
+ min_target_margin,
1026
+ ax=ax,
1027
+ )
1028
+
1029
+ # Draw the edges
1030
+ if use_linecollection:
1031
+ edge_collection = mpl.collections.LineCollection(
1032
+ edge_pos,
1033
+ colors=edge_color,
1034
+ linewidths=width,
1035
+ antialiaseds=(1,),
1036
+ linestyle=style,
1037
+ alpha=alpha,
1038
+ )
1039
+ edge_collection.set_cmap(edge_cmap)
1040
+ edge_collection.set_clim(edge_vmin, edge_vmax)
1041
+ edge_collection.set_zorder(1) # edges go behind nodes
1042
+ edge_collection.set_label(label)
1043
+ ax.add_collection(edge_collection)
1044
+ edge_viz_obj = edge_collection
1045
+
1046
+ # Make sure selfloop edges are also drawn
1047
+ # ---------------------------------------
1048
+ selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
1049
+ if selfloops_to_draw:
1050
+ edgelist_tuple = list(map(tuple, edgelist))
1051
+ arrow_collection = []
1052
+ for loop in selfloops_to_draw:
1053
+ i = edgelist_tuple.index(loop)
1054
+ arrow = fancy_arrow_factory(i)
1055
+ arrow_collection.append(arrow)
1056
+ ax.add_patch(arrow)
1057
+ else:
1058
+ edge_viz_obj = []
1059
+ for i in range(len(edgelist)):
1060
+ arrow = fancy_arrow_factory(i)
1061
+ ax.add_patch(arrow)
1062
+ edge_viz_obj.append(arrow)
1063
+
1064
+ # update view after drawing
1065
+ padx, pady = 0.05 * w, 0.05 * h
1066
+ corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
1067
+ ax.update_datalim(corners)
1068
+ ax.autoscale_view()
1069
+
1070
+ if hide_ticks:
1071
+ ax.tick_params(
1072
+ axis="both",
1073
+ which="both",
1074
+ bottom=False,
1075
+ left=False,
1076
+ labelbottom=False,
1077
+ labelleft=False,
1078
+ )
1079
+
1080
+ return edge_viz_obj
1081
+
1082
+
1083
+ def draw_networkx_labels(
1084
+ G,
1085
+ pos,
1086
+ labels=None,
1087
+ font_size=12,
1088
+ font_color="k",
1089
+ font_family="sans-serif",
1090
+ font_weight="normal",
1091
+ alpha=None,
1092
+ bbox=None,
1093
+ horizontalalignment="center",
1094
+ verticalalignment="center",
1095
+ ax=None,
1096
+ clip_on=True,
1097
+ hide_ticks=True,
1098
+ ):
1099
+ """Draw node labels on the graph G.
1100
+
1101
+ Parameters
1102
+ ----------
1103
+ G : graph
1104
+ A networkx graph
1105
+
1106
+ pos : dictionary
1107
+ A dictionary with nodes as keys and positions as values.
1108
+ Positions should be sequences of length 2.
1109
+
1110
+ labels : dictionary (default={n: n for n in G})
1111
+ Node labels in a dictionary of text labels keyed by node.
1112
+ Node-keys in labels should appear as keys in `pos`.
1113
+ If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
1114
+
1115
+ font_size : int or dictionary of nodes to ints (default=12)
1116
+ Font size for text labels.
1117
+
1118
+ font_color : color or dictionary of nodes to colors (default='k' black)
1119
+ Font color string. Color can be string or rgb (or rgba) tuple of
1120
+ floats from 0-1.
1121
+
1122
+ font_weight : string or dictionary of nodes to strings (default='normal')
1123
+ Font weight.
1124
+
1125
+ font_family : string or dictionary of nodes to strings (default='sans-serif')
1126
+ Font family.
1127
+
1128
+ alpha : float or None or dictionary of nodes to floats (default=None)
1129
+ The text transparency.
1130
+
1131
+ bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
1132
+ Specify text box properties (e.g. shape, color etc.) for node labels.
1133
+
1134
+ horizontalalignment : string or array of strings (default='center')
1135
+ Horizontal alignment {'center', 'right', 'left'}. If an array is
1136
+ specified it must be the same length as `nodelist`.
1137
+
1138
+ verticalalignment : string (default='center')
1139
+ Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}.
1140
+ If an array is specified it must be the same length as `nodelist`.
1141
+
1142
+ ax : Matplotlib Axes object, optional
1143
+ Draw the graph in the specified Matplotlib axes.
1144
+
1145
+ clip_on : bool (default=True)
1146
+ Turn on clipping of node labels at axis boundaries
1147
+
1148
+ hide_ticks : bool, optional
1149
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
1150
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
1151
+ use ``hide_ticks=False``.
1152
+
1153
+ Returns
1154
+ -------
1155
+ dict
1156
+ `dict` of labels keyed on the nodes
1157
+
1158
+ Examples
1159
+ --------
1160
+ >>> G = nx.dodecahedral_graph()
1161
+ >>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
1162
+
1163
+ Also see the NetworkX drawing examples at
1164
+ https://networkx.org/documentation/latest/auto_examples/index.html
1165
+
1166
+ See Also
1167
+ --------
1168
+ draw
1169
+ draw_networkx
1170
+ draw_networkx_nodes
1171
+ draw_networkx_edges
1172
+ draw_networkx_edge_labels
1173
+ """
1174
+ import matplotlib.pyplot as plt
1175
+
1176
+ if ax is None:
1177
+ ax = plt.gca()
1178
+
1179
+ if labels is None:
1180
+ labels = {n: n for n in G.nodes()}
1181
+
1182
+ individual_params = set()
1183
+
1184
+ def check_individual_params(p_value, p_name):
1185
+ if isinstance(p_value, dict):
1186
+ if len(p_value) != len(labels):
1187
+ raise ValueError(f"{p_name} must have the same length as labels.")
1188
+ individual_params.add(p_name)
1189
+
1190
+ def get_param_value(node, p_value, p_name):
1191
+ if p_name in individual_params:
1192
+ return p_value[node]
1193
+ return p_value
1194
+
1195
+ check_individual_params(font_size, "font_size")
1196
+ check_individual_params(font_color, "font_color")
1197
+ check_individual_params(font_weight, "font_weight")
1198
+ check_individual_params(font_family, "font_family")
1199
+ check_individual_params(alpha, "alpha")
1200
+
1201
+ text_items = {} # there is no text collection so we'll fake one
1202
+ for n, label in labels.items():
1203
+ (x, y) = pos[n]
1204
+ if not isinstance(label, str):
1205
+ label = str(label) # this makes "1" and 1 labeled the same
1206
+ t = ax.text(
1207
+ x,
1208
+ y,
1209
+ label,
1210
+ size=get_param_value(n, font_size, "font_size"),
1211
+ color=get_param_value(n, font_color, "font_color"),
1212
+ family=get_param_value(n, font_family, "font_family"),
1213
+ weight=get_param_value(n, font_weight, "font_weight"),
1214
+ alpha=get_param_value(n, alpha, "alpha"),
1215
+ horizontalalignment=horizontalalignment,
1216
+ verticalalignment=verticalalignment,
1217
+ transform=ax.transData,
1218
+ bbox=bbox,
1219
+ clip_on=clip_on,
1220
+ )
1221
+ text_items[n] = t
1222
+
1223
+ if hide_ticks:
1224
+ ax.tick_params(
1225
+ axis="both",
1226
+ which="both",
1227
+ bottom=False,
1228
+ left=False,
1229
+ labelbottom=False,
1230
+ labelleft=False,
1231
+ )
1232
+
1233
+ return text_items
1234
+
1235
+
1236
+ def draw_networkx_edge_labels(
1237
+ G,
1238
+ pos,
1239
+ edge_labels=None,
1240
+ label_pos=0.5,
1241
+ font_size=10,
1242
+ font_color="k",
1243
+ font_family="sans-serif",
1244
+ font_weight="normal",
1245
+ alpha=None,
1246
+ bbox=None,
1247
+ horizontalalignment="center",
1248
+ verticalalignment="center",
1249
+ ax=None,
1250
+ rotate=True,
1251
+ clip_on=True,
1252
+ node_size=300,
1253
+ nodelist=None,
1254
+ connectionstyle="arc3",
1255
+ hide_ticks=True,
1256
+ ):
1257
+ """Draw edge labels.
1258
+
1259
+ Parameters
1260
+ ----------
1261
+ G : graph
1262
+ A networkx graph
1263
+
1264
+ pos : dictionary
1265
+ A dictionary with nodes as keys and positions as values.
1266
+ Positions should be sequences of length 2.
1267
+
1268
+ edge_labels : dictionary (default=None)
1269
+ Edge labels in a dictionary of labels keyed by edge two-tuple.
1270
+ Only labels for the keys in the dictionary are drawn.
1271
+
1272
+ label_pos : float (default=0.5)
1273
+ Position of edge label along edge (0=head, 0.5=center, 1=tail)
1274
+
1275
+ font_size : int (default=10)
1276
+ Font size for text labels
1277
+
1278
+ font_color : color (default='k' black)
1279
+ Font color string. Color can be string or rgb (or rgba) tuple of
1280
+ floats from 0-1.
1281
+
1282
+ font_weight : string (default='normal')
1283
+ Font weight
1284
+
1285
+ font_family : string (default='sans-serif')
1286
+ Font family
1287
+
1288
+ alpha : float or None (default=None)
1289
+ The text transparency
1290
+
1291
+ bbox : Matplotlib bbox, optional
1292
+ Specify text box properties (e.g. shape, color etc.) for edge labels.
1293
+ Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
1294
+
1295
+ horizontalalignment : string (default='center')
1296
+ Horizontal alignment {'center', 'right', 'left'}
1297
+
1298
+ verticalalignment : string (default='center')
1299
+ Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
1300
+
1301
+ ax : Matplotlib Axes object, optional
1302
+ Draw the graph in the specified Matplotlib axes.
1303
+
1304
+ rotate : bool (default=True)
1305
+ Rotate edge labels to lie parallel to edges
1306
+
1307
+ clip_on : bool (default=True)
1308
+ Turn on clipping of edge labels at axis boundaries
1309
+
1310
+ node_size : scalar or array (default=300)
1311
+ Size of nodes. If an array it must be the same length as nodelist.
1312
+
1313
+ nodelist : list, optional (default=G.nodes())
1314
+ This provides the node order for the `node_size` array (if it is an array).
1315
+
1316
+ connectionstyle : string or iterable of strings (default="arc3")
1317
+ Pass the connectionstyle parameter to create curved arc of rounding
1318
+ radius rad. For example, connectionstyle='arc3,rad=0.2'.
1319
+ See `matplotlib.patches.ConnectionStyle` and
1320
+ `matplotlib.patches.FancyArrowPatch` for more info.
1321
+ If Iterable, index indicates i'th edge key of MultiGraph
1322
+
1323
+ hide_ticks : bool, optional
1324
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
1325
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
1326
+ use ``hide_ticks=False``.
1327
+
1328
+ Returns
1329
+ -------
1330
+ dict
1331
+ `dict` of labels keyed by edge
1332
+
1333
+ Examples
1334
+ --------
1335
+ >>> G = nx.dodecahedral_graph()
1336
+ >>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
1337
+
1338
+ Also see the NetworkX drawing examples at
1339
+ https://networkx.org/documentation/latest/auto_examples/index.html
1340
+
1341
+ See Also
1342
+ --------
1343
+ draw
1344
+ draw_networkx
1345
+ draw_networkx_nodes
1346
+ draw_networkx_edges
1347
+ draw_networkx_labels
1348
+ """
1349
+ import matplotlib as mpl
1350
+ import matplotlib.pyplot as plt
1351
+ import numpy as np
1352
+
1353
+ class CurvedArrowText(mpl.text.Text):
1354
+ def __init__(
1355
+ self,
1356
+ arrow,
1357
+ *args,
1358
+ label_pos=0.5,
1359
+ labels_horizontal=False,
1360
+ ax=None,
1361
+ **kwargs,
1362
+ ):
1363
+ # Bind to FancyArrowPatch
1364
+ self.arrow = arrow
1365
+ # how far along the text should be on the curve,
1366
+ # 0 is at start, 1 is at end etc.
1367
+ self.label_pos = label_pos
1368
+ self.labels_horizontal = labels_horizontal
1369
+ if ax is None:
1370
+ ax = plt.gca()
1371
+ self.ax = ax
1372
+ self.x, self.y, self.angle = self._update_text_pos_angle(arrow)
1373
+
1374
+ # Create text object
1375
+ super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
1376
+ # Bind to axis
1377
+ self.ax.add_artist(self)
1378
+
1379
+ def _get_arrow_path_disp(self, arrow):
1380
+ """
1381
+ This is part of FancyArrowPatch._get_path_in_displaycoord
1382
+ It omits the second part of the method where path is converted
1383
+ to polygon based on width
1384
+ The transform is taken from ax, not the object, as the object
1385
+ has not been added yet, and doesn't have transform
1386
+ """
1387
+ dpi_cor = arrow._dpi_cor
1388
+ # trans_data = arrow.get_transform()
1389
+ trans_data = self.ax.transData
1390
+ if arrow._posA_posB is not None:
1391
+ posA = arrow._convert_xy_units(arrow._posA_posB[0])
1392
+ posB = arrow._convert_xy_units(arrow._posA_posB[1])
1393
+ (posA, posB) = trans_data.transform((posA, posB))
1394
+ _path = arrow.get_connectionstyle()(
1395
+ posA,
1396
+ posB,
1397
+ patchA=arrow.patchA,
1398
+ patchB=arrow.patchB,
1399
+ shrinkA=arrow.shrinkA * dpi_cor,
1400
+ shrinkB=arrow.shrinkB * dpi_cor,
1401
+ )
1402
+ else:
1403
+ _path = trans_data.transform_path(arrow._path_original)
1404
+ # Return is in display coordinates
1405
+ return _path
1406
+
1407
+ def _update_text_pos_angle(self, arrow):
1408
+ # Fractional label position
1409
+ path_disp = self._get_arrow_path_disp(arrow)
1410
+ (x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
1411
+ # Text position at a proportion t along the line in display coords
1412
+ # default is 0.5 so text appears at the halfway point
1413
+ t = self.label_pos
1414
+ tt = 1 - t
1415
+ x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
1416
+ y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
1417
+ if self.labels_horizontal:
1418
+ # Horizontal text labels
1419
+ angle = 0
1420
+ else:
1421
+ # Labels parallel to curve
1422
+ change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
1423
+ change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
1424
+ angle = (np.arctan2(change_y, change_x) / (2 * np.pi)) * 360
1425
+ # Text is "right way up"
1426
+ if angle > 90:
1427
+ angle -= 180
1428
+ if angle < -90:
1429
+ angle += 180
1430
+ (x, y) = self.ax.transData.inverted().transform((x, y))
1431
+ return x, y, angle
1432
+
1433
+ def draw(self, renderer):
1434
+ # recalculate the text position and angle
1435
+ self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
1436
+ self.set_position((self.x, self.y))
1437
+ self.set_rotation(self.angle)
1438
+ # redraw text
1439
+ super().draw(renderer)
1440
+
1441
+ # use default box of white with white border
1442
+ if bbox is None:
1443
+ bbox = {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
1444
+
1445
+ if isinstance(connectionstyle, str):
1446
+ connectionstyle = [connectionstyle]
1447
+ elif np.iterable(connectionstyle):
1448
+ connectionstyle = list(connectionstyle)
1449
+ else:
1450
+ raise nx.NetworkXError(
1451
+ "draw_networkx_edges arg `connectionstyle` must be"
1452
+ "string or iterable of strings"
1453
+ )
1454
+
1455
+ if ax is None:
1456
+ ax = plt.gca()
1457
+
1458
+ if edge_labels is None:
1459
+ kwds = {"keys": True} if G.is_multigraph() else {}
1460
+ edge_labels = {tuple(edge): d for *edge, d in G.edges(data=True, **kwds)}
1461
+ # NOTHING TO PLOT
1462
+ if not edge_labels:
1463
+ return {}
1464
+ edgelist, labels = zip(*edge_labels.items())
1465
+
1466
+ if nodelist is None:
1467
+ nodelist = list(G.nodes())
1468
+
1469
+ # set edge positions
1470
+ edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
1471
+
1472
+ if G.is_multigraph():
1473
+ key_count = collections.defaultdict(lambda: itertools.count(0))
1474
+ edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
1475
+ else:
1476
+ edge_indices = [0] * len(edgelist)
1477
+
1478
+ # Used to determine self loop mid-point
1479
+ # Note, that this will not be accurate,
1480
+ # if not drawing edge_labels for all edges drawn
1481
+ h = 0
1482
+ if edge_labels:
1483
+ miny = np.amin(np.ravel(edge_pos[:, :, 1]))
1484
+ maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
1485
+ h = maxy - miny
1486
+ selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
1487
+ fancy_arrow_factory = FancyArrowFactory(
1488
+ edge_pos,
1489
+ edgelist,
1490
+ nodelist,
1491
+ edge_indices,
1492
+ node_size,
1493
+ selfloop_height,
1494
+ connectionstyle,
1495
+ ax=ax,
1496
+ )
1497
+
1498
+ individual_params = {}
1499
+
1500
+ def check_individual_params(p_value, p_name):
1501
+ # TODO should this be list or array (as in a numpy array)?
1502
+ if isinstance(p_value, list):
1503
+ if len(p_value) != len(edgelist):
1504
+ raise ValueError(f"{p_name} must have the same length as edgelist.")
1505
+ individual_params[p_name] = p_value.iter()
1506
+
1507
+ # Don't need to pass in an edge because these are lists, not dicts
1508
+ def get_param_value(p_value, p_name):
1509
+ if p_name in individual_params:
1510
+ return next(individual_params[p_name])
1511
+ return p_value
1512
+
1513
+ check_individual_params(font_size, "font_size")
1514
+ check_individual_params(font_color, "font_color")
1515
+ check_individual_params(font_weight, "font_weight")
1516
+ check_individual_params(alpha, "alpha")
1517
+ check_individual_params(horizontalalignment, "horizontalalignment")
1518
+ check_individual_params(verticalalignment, "verticalalignment")
1519
+ check_individual_params(rotate, "rotate")
1520
+ check_individual_params(label_pos, "label_pos")
1521
+
1522
+ text_items = {}
1523
+ for i, (edge, label) in enumerate(zip(edgelist, labels)):
1524
+ if not isinstance(label, str):
1525
+ label = str(label) # this makes "1" and 1 labeled the same
1526
+
1527
+ n1, n2 = edge[:2]
1528
+ arrow = fancy_arrow_factory(i)
1529
+ if n1 == n2:
1530
+ connectionstyle_obj = arrow.get_connectionstyle()
1531
+ posA = ax.transData.transform(pos[n1])
1532
+ path_disp = connectionstyle_obj(posA, posA)
1533
+ path_data = ax.transData.inverted().transform_path(path_disp)
1534
+ x, y = path_data.vertices[0]
1535
+ text_items[edge] = ax.text(
1536
+ x,
1537
+ y,
1538
+ label,
1539
+ size=get_param_value(font_size, "font_size"),
1540
+ color=get_param_value(font_color, "font_color"),
1541
+ family=get_param_value(font_family, "font_family"),
1542
+ weight=get_param_value(font_weight, "font_weight"),
1543
+ alpha=get_param_value(alpha, "alpha"),
1544
+ horizontalalignment=get_param_value(
1545
+ horizontalalignment, "horizontalalignment"
1546
+ ),
1547
+ verticalalignment=get_param_value(
1548
+ verticalalignment, "verticalalignment"
1549
+ ),
1550
+ rotation=0,
1551
+ transform=ax.transData,
1552
+ bbox=bbox,
1553
+ zorder=1,
1554
+ clip_on=clip_on,
1555
+ )
1556
+ else:
1557
+ text_items[edge] = CurvedArrowText(
1558
+ arrow,
1559
+ label,
1560
+ size=get_param_value(font_size, "font_size"),
1561
+ color=get_param_value(font_color, "font_color"),
1562
+ family=get_param_value(font_family, "font_family"),
1563
+ weight=get_param_value(font_weight, "font_weight"),
1564
+ alpha=get_param_value(alpha, "alpha"),
1565
+ horizontalalignment=get_param_value(
1566
+ horizontalalignment, "horizontalalignment"
1567
+ ),
1568
+ verticalalignment=get_param_value(
1569
+ verticalalignment, "verticalalignment"
1570
+ ),
1571
+ transform=ax.transData,
1572
+ bbox=bbox,
1573
+ zorder=1,
1574
+ clip_on=clip_on,
1575
+ label_pos=get_param_value(label_pos, "label_pos"),
1576
+ labels_horizontal=not get_param_value(rotate, "rotate"),
1577
+ ax=ax,
1578
+ )
1579
+
1580
+ if hide_ticks:
1581
+ ax.tick_params(
1582
+ axis="both",
1583
+ which="both",
1584
+ bottom=False,
1585
+ left=False,
1586
+ labelbottom=False,
1587
+ labelleft=False,
1588
+ )
1589
+
1590
+ return text_items
1591
+
1592
+
1593
+ def draw_circular(G, **kwargs):
1594
+ """Draw the graph `G` with a circular layout.
1595
+
1596
+ This is a convenience function equivalent to::
1597
+
1598
+ nx.draw(G, pos=nx.circular_layout(G), **kwargs)
1599
+
1600
+ Parameters
1601
+ ----------
1602
+ G : graph
1603
+ A networkx graph
1604
+
1605
+ kwargs : optional keywords
1606
+ See `draw_networkx` for a description of optional keywords.
1607
+
1608
+ Notes
1609
+ -----
1610
+ The layout is computed each time this function is called. For
1611
+ repeated drawing it is much more efficient to call
1612
+ `~networkx.drawing.layout.circular_layout` directly and reuse the result::
1613
+
1614
+ >>> G = nx.complete_graph(5)
1615
+ >>> pos = nx.circular_layout(G)
1616
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1617
+ >>> # Draw a subgraph, reusing the same node positions
1618
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1619
+
1620
+ Examples
1621
+ --------
1622
+ >>> G = nx.path_graph(5)
1623
+ >>> nx.draw_circular(G)
1624
+
1625
+ See Also
1626
+ --------
1627
+ :func:`~networkx.drawing.layout.circular_layout`
1628
+ """
1629
+ draw(G, circular_layout(G), **kwargs)
1630
+
1631
+
1632
+ def draw_kamada_kawai(G, **kwargs):
1633
+ """Draw the graph `G` with a Kamada-Kawai force-directed layout.
1634
+
1635
+ This is a convenience function equivalent to::
1636
+
1637
+ nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
1638
+
1639
+ Parameters
1640
+ ----------
1641
+ G : graph
1642
+ A networkx graph
1643
+
1644
+ kwargs : optional keywords
1645
+ See `draw_networkx` for a description of optional keywords.
1646
+
1647
+ Notes
1648
+ -----
1649
+ The layout is computed each time this function is called.
1650
+ For repeated drawing it is much more efficient to call
1651
+ `~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
1652
+ result::
1653
+
1654
+ >>> G = nx.complete_graph(5)
1655
+ >>> pos = nx.kamada_kawai_layout(G)
1656
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1657
+ >>> # Draw a subgraph, reusing the same node positions
1658
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1659
+
1660
+ Examples
1661
+ --------
1662
+ >>> G = nx.path_graph(5)
1663
+ >>> nx.draw_kamada_kawai(G)
1664
+
1665
+ See Also
1666
+ --------
1667
+ :func:`~networkx.drawing.layout.kamada_kawai_layout`
1668
+ """
1669
+ draw(G, kamada_kawai_layout(G), **kwargs)
1670
+
1671
+
1672
+ def draw_random(G, **kwargs):
1673
+ """Draw the graph `G` with a random layout.
1674
+
1675
+ This is a convenience function equivalent to::
1676
+
1677
+ nx.draw(G, pos=nx.random_layout(G), **kwargs)
1678
+
1679
+ Parameters
1680
+ ----------
1681
+ G : graph
1682
+ A networkx graph
1683
+
1684
+ kwargs : optional keywords
1685
+ See `draw_networkx` for a description of optional keywords.
1686
+
1687
+ Notes
1688
+ -----
1689
+ The layout is computed each time this function is called.
1690
+ For repeated drawing it is much more efficient to call
1691
+ `~networkx.drawing.layout.random_layout` directly and reuse the result::
1692
+
1693
+ >>> G = nx.complete_graph(5)
1694
+ >>> pos = nx.random_layout(G)
1695
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1696
+ >>> # Draw a subgraph, reusing the same node positions
1697
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1698
+
1699
+ Examples
1700
+ --------
1701
+ >>> G = nx.lollipop_graph(4, 3)
1702
+ >>> nx.draw_random(G)
1703
+
1704
+ See Also
1705
+ --------
1706
+ :func:`~networkx.drawing.layout.random_layout`
1707
+ """
1708
+ draw(G, random_layout(G), **kwargs)
1709
+
1710
+
1711
+ def draw_spectral(G, **kwargs):
1712
+ """Draw the graph `G` with a spectral 2D layout.
1713
+
1714
+ This is a convenience function equivalent to::
1715
+
1716
+ nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
1717
+
1718
+ For more information about how node positions are determined, see
1719
+ `~networkx.drawing.layout.spectral_layout`.
1720
+
1721
+ Parameters
1722
+ ----------
1723
+ G : graph
1724
+ A networkx graph
1725
+
1726
+ kwargs : optional keywords
1727
+ See `draw_networkx` for a description of optional keywords.
1728
+
1729
+ Notes
1730
+ -----
1731
+ The layout is computed each time this function is called.
1732
+ For repeated drawing it is much more efficient to call
1733
+ `~networkx.drawing.layout.spectral_layout` directly and reuse the result::
1734
+
1735
+ >>> G = nx.complete_graph(5)
1736
+ >>> pos = nx.spectral_layout(G)
1737
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1738
+ >>> # Draw a subgraph, reusing the same node positions
1739
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1740
+
1741
+ Examples
1742
+ --------
1743
+ >>> G = nx.path_graph(5)
1744
+ >>> nx.draw_spectral(G)
1745
+
1746
+ See Also
1747
+ --------
1748
+ :func:`~networkx.drawing.layout.spectral_layout`
1749
+ """
1750
+ draw(G, spectral_layout(G), **kwargs)
1751
+
1752
+
1753
+ def draw_spring(G, **kwargs):
1754
+ """Draw the graph `G` with a spring layout.
1755
+
1756
+ This is a convenience function equivalent to::
1757
+
1758
+ nx.draw(G, pos=nx.spring_layout(G), **kwargs)
1759
+
1760
+ Parameters
1761
+ ----------
1762
+ G : graph
1763
+ A networkx graph
1764
+
1765
+ kwargs : optional keywords
1766
+ See `draw_networkx` for a description of optional keywords.
1767
+
1768
+ Notes
1769
+ -----
1770
+ `~networkx.drawing.layout.spring_layout` is also the default layout for
1771
+ `draw`, so this function is equivalent to `draw`.
1772
+
1773
+ The layout is computed each time this function is called.
1774
+ For repeated drawing it is much more efficient to call
1775
+ `~networkx.drawing.layout.spring_layout` directly and reuse the result::
1776
+
1777
+ >>> G = nx.complete_graph(5)
1778
+ >>> pos = nx.spring_layout(G)
1779
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1780
+ >>> # Draw a subgraph, reusing the same node positions
1781
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1782
+
1783
+ Examples
1784
+ --------
1785
+ >>> G = nx.path_graph(20)
1786
+ >>> nx.draw_spring(G)
1787
+
1788
+ See Also
1789
+ --------
1790
+ draw
1791
+ :func:`~networkx.drawing.layout.spring_layout`
1792
+ """
1793
+ draw(G, spring_layout(G), **kwargs)
1794
+
1795
+
1796
+ def draw_shell(G, nlist=None, **kwargs):
1797
+ """Draw networkx graph `G` with shell layout.
1798
+
1799
+ This is a convenience function equivalent to::
1800
+
1801
+ nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
1802
+
1803
+ Parameters
1804
+ ----------
1805
+ G : graph
1806
+ A networkx graph
1807
+
1808
+ nlist : list of list of nodes, optional
1809
+ A list containing lists of nodes representing the shells.
1810
+ Default is `None`, meaning all nodes are in a single shell.
1811
+ See `~networkx.drawing.layout.shell_layout` for details.
1812
+
1813
+ kwargs : optional keywords
1814
+ See `draw_networkx` for a description of optional keywords.
1815
+
1816
+ Notes
1817
+ -----
1818
+ The layout is computed each time this function is called.
1819
+ For repeated drawing it is much more efficient to call
1820
+ `~networkx.drawing.layout.shell_layout` directly and reuse the result::
1821
+
1822
+ >>> G = nx.complete_graph(5)
1823
+ >>> pos = nx.shell_layout(G)
1824
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1825
+ >>> # Draw a subgraph, reusing the same node positions
1826
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1827
+
1828
+ Examples
1829
+ --------
1830
+ >>> G = nx.path_graph(4)
1831
+ >>> shells = [[0], [1, 2, 3]]
1832
+ >>> nx.draw_shell(G, nlist=shells)
1833
+
1834
+ See Also
1835
+ --------
1836
+ :func:`~networkx.drawing.layout.shell_layout`
1837
+ """
1838
+ draw(G, shell_layout(G, nlist=nlist), **kwargs)
1839
+
1840
+
1841
+ def draw_planar(G, **kwargs):
1842
+ """Draw a planar networkx graph `G` with planar layout.
1843
+
1844
+ This is a convenience function equivalent to::
1845
+
1846
+ nx.draw(G, pos=nx.planar_layout(G), **kwargs)
1847
+
1848
+ Parameters
1849
+ ----------
1850
+ G : graph
1851
+ A planar networkx graph
1852
+
1853
+ kwargs : optional keywords
1854
+ See `draw_networkx` for a description of optional keywords.
1855
+
1856
+ Raises
1857
+ ------
1858
+ NetworkXException
1859
+ When `G` is not planar
1860
+
1861
+ Notes
1862
+ -----
1863
+ The layout is computed each time this function is called.
1864
+ For repeated drawing it is much more efficient to call
1865
+ `~networkx.drawing.layout.planar_layout` directly and reuse the result::
1866
+
1867
+ >>> G = nx.path_graph(5)
1868
+ >>> pos = nx.planar_layout(G)
1869
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1870
+ >>> # Draw a subgraph, reusing the same node positions
1871
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1872
+
1873
+ Examples
1874
+ --------
1875
+ >>> G = nx.path_graph(4)
1876
+ >>> nx.draw_planar(G)
1877
+
1878
+ See Also
1879
+ --------
1880
+ :func:`~networkx.drawing.layout.planar_layout`
1881
+ """
1882
+ draw(G, planar_layout(G), **kwargs)
1883
+
1884
+
1885
+ def draw_forceatlas2(G, **kwargs):
1886
+ """Draw a networkx graph with forceatlas2 layout.
1887
+
1888
+ This is a convenience function equivalent to::
1889
+
1890
+ nx.draw(G, pos=nx.forceatlas2_layout(G), **kwargs)
1891
+
1892
+ Parameters
1893
+ ----------
1894
+ G : graph
1895
+ A networkx graph
1896
+
1897
+ kwargs : optional keywords
1898
+ See networkx.draw_networkx() for a description of optional keywords,
1899
+ with the exception of the pos parameter which is not used by this
1900
+ function.
1901
+ """
1902
+ draw(G, forceatlas2_layout(G), **kwargs)
1903
+
1904
+
1905
+ def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
1906
+ """Apply an alpha (or list of alphas) to the colors provided.
1907
+
1908
+ Parameters
1909
+ ----------
1910
+
1911
+ colors : color string or array of floats (default='r')
1912
+ Color of element. Can be a single color format string,
1913
+ or a sequence of colors with the same length as nodelist.
1914
+ If numeric values are specified they will be mapped to
1915
+ colors using the cmap and vmin,vmax parameters. See
1916
+ matplotlib.scatter for more details.
1917
+
1918
+ alpha : float or array of floats
1919
+ Alpha values for elements. This can be a single alpha value, in
1920
+ which case it will be applied to all the elements of color. Otherwise,
1921
+ if it is an array, the elements of alpha will be applied to the colors
1922
+ in order (cycling through alpha multiple times if necessary).
1923
+
1924
+ elem_list : array of networkx objects
1925
+ The list of elements which are being colored. These could be nodes,
1926
+ edges or labels.
1927
+
1928
+ cmap : matplotlib colormap
1929
+ Color map for use if colors is a list of floats corresponding to points
1930
+ on a color mapping.
1931
+
1932
+ vmin, vmax : float
1933
+ Minimum and maximum values for normalizing colors if a colormap is used
1934
+
1935
+ Returns
1936
+ -------
1937
+
1938
+ rgba_colors : numpy ndarray
1939
+ Array containing RGBA format values for each of the node colours.
1940
+
1941
+ """
1942
+ from itertools import cycle, islice
1943
+
1944
+ import matplotlib as mpl
1945
+ import matplotlib.cm # call as mpl.cm
1946
+ import matplotlib.colors # call as mpl.colors
1947
+ import numpy as np
1948
+
1949
+ # If we have been provided with a list of numbers as long as elem_list,
1950
+ # apply the color mapping.
1951
+ if len(colors) == len(elem_list) and isinstance(colors[0], Number):
1952
+ mapper = mpl.cm.ScalarMappable(cmap=cmap)
1953
+ mapper.set_clim(vmin, vmax)
1954
+ rgba_colors = mapper.to_rgba(colors)
1955
+ # Otherwise, convert colors to matplotlib's RGB using the colorConverter
1956
+ # object. These are converted to numpy ndarrays to be consistent with the
1957
+ # to_rgba method of ScalarMappable.
1958
+ else:
1959
+ try:
1960
+ rgba_colors = np.array([mpl.colors.colorConverter.to_rgba(colors)])
1961
+ except ValueError:
1962
+ rgba_colors = np.array(
1963
+ [mpl.colors.colorConverter.to_rgba(color) for color in colors]
1964
+ )
1965
+ # Set the final column of the rgba_colors to have the relevant alpha values
1966
+ try:
1967
+ # If alpha is longer than the number of colors, resize to the number of
1968
+ # elements. Also, if rgba_colors.size (the number of elements of
1969
+ # rgba_colors) is the same as the number of elements, resize the array,
1970
+ # to avoid it being interpreted as a colormap by scatter()
1971
+ if len(alpha) > len(rgba_colors) or rgba_colors.size == len(elem_list):
1972
+ rgba_colors = np.resize(rgba_colors, (len(elem_list), 4))
1973
+ rgba_colors[1:, 0] = rgba_colors[0, 0]
1974
+ rgba_colors[1:, 1] = rgba_colors[0, 1]
1975
+ rgba_colors[1:, 2] = rgba_colors[0, 2]
1976
+ rgba_colors[:, 3] = list(islice(cycle(alpha), len(rgba_colors)))
1977
+ except TypeError:
1978
+ rgba_colors[:, -1] = alpha
1979
+ return rgba_colors
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (172 Bytes). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc ADDED
Binary file (9.74 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc ADDED
Binary file (4.34 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc ADDED
Binary file (31 kB). View file
 
wemm/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
wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for PyGraphviz interface."""
2
+
3
+ import warnings
4
+
5
+ import pytest
6
+
7
+ pygraphviz = pytest.importorskip("pygraphviz")
8
+
9
+
10
+ import networkx as nx
11
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
12
+
13
+
14
+ class TestAGraph:
15
+ def build_graph(self, G):
16
+ edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")]
17
+ G.add_edges_from(edges)
18
+ G.add_node("E")
19
+ G.graph["metal"] = "bronze"
20
+ return G
21
+
22
+ def assert_equal(self, G1, G2):
23
+ assert nodes_equal(G1.nodes(), G2.nodes())
24
+ assert edges_equal(G1.edges(), G2.edges())
25
+ assert G1.graph["metal"] == G2.graph["metal"]
26
+
27
+ @pytest.mark.parametrize(
28
+ "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
29
+ )
30
+ def test_agraph_roundtripping(self, G, tmp_path):
31
+ G = self.build_graph(G)
32
+ A = nx.nx_agraph.to_agraph(G)
33
+ H = nx.nx_agraph.from_agraph(A)
34
+ self.assert_equal(G, H)
35
+
36
+ fname = tmp_path / "test.dot"
37
+ nx.drawing.nx_agraph.write_dot(H, fname)
38
+ Hin = nx.nx_agraph.read_dot(fname)
39
+ self.assert_equal(H, Hin)
40
+
41
+ fname = tmp_path / "fh_test.dot"
42
+ with open(fname, "w") as fh:
43
+ nx.drawing.nx_agraph.write_dot(H, fh)
44
+
45
+ with open(fname) as fh:
46
+ Hin = nx.nx_agraph.read_dot(fh)
47
+ self.assert_equal(H, Hin)
48
+
49
+ def test_from_agraph_name(self):
50
+ G = nx.Graph(name="test")
51
+ A = nx.nx_agraph.to_agraph(G)
52
+ H = nx.nx_agraph.from_agraph(A)
53
+ assert G.name == "test"
54
+
55
+ @pytest.mark.parametrize(
56
+ "graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
57
+ )
58
+ def test_from_agraph_create_using(self, graph_class):
59
+ G = nx.path_graph(3)
60
+ A = nx.nx_agraph.to_agraph(G)
61
+ H = nx.nx_agraph.from_agraph(A, create_using=graph_class)
62
+ assert isinstance(H, graph_class)
63
+
64
+ def test_from_agraph_named_edges(self):
65
+ # Create an AGraph from an existing (non-multi) Graph
66
+ G = nx.Graph()
67
+ G.add_nodes_from([0, 1])
68
+ A = nx.nx_agraph.to_agraph(G)
69
+ # Add edge (+ name, given by key) to the AGraph
70
+ A.add_edge(0, 1, key="foo")
71
+ # Verify a.name roundtrips out to 'key' in from_agraph
72
+ H = nx.nx_agraph.from_agraph(A)
73
+ assert isinstance(H, nx.Graph)
74
+ assert ("0", "1", {"key": "foo"}) in H.edges(data=True)
75
+
76
+ def test_to_agraph_with_nodedata(self):
77
+ G = nx.Graph()
78
+ G.add_node(1, color="red")
79
+ A = nx.nx_agraph.to_agraph(G)
80
+ assert dict(A.nodes()[0].attr) == {"color": "red"}
81
+
82
+ @pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph))
83
+ def test_to_agraph_with_edgedata(self, graph_class):
84
+ G = graph_class()
85
+ G.add_nodes_from([0, 1])
86
+ G.add_edge(0, 1, color="yellow")
87
+ A = nx.nx_agraph.to_agraph(G)
88
+ assert dict(A.edges()[0].attr) == {"color": "yellow"}
89
+
90
+ def test_view_pygraphviz_path(self, tmp_path):
91
+ G = nx.complete_graph(3)
92
+ input_path = str(tmp_path / "graph.png")
93
+ out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False)
94
+ assert out_path == input_path
95
+ # Ensure file is not empty
96
+ with open(input_path, "rb") as fh:
97
+ data = fh.read()
98
+ assert len(data) > 0
99
+
100
+ def test_view_pygraphviz_file_suffix(self, tmp_path):
101
+ G = nx.complete_graph(3)
102
+ path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False)
103
+ assert path[-6:] == "_1.png"
104
+
105
+ def test_view_pygraphviz(self):
106
+ G = nx.Graph() # "An empty graph cannot be drawn."
107
+ pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
108
+ G = nx.barbell_graph(4, 6)
109
+ nx.nx_agraph.view_pygraphviz(G, show=False)
110
+
111
+ def test_view_pygraphviz_edgelabel(self):
112
+ G = nx.Graph()
113
+ G.add_edge(1, 2, weight=7)
114
+ G.add_edge(2, 3, weight=8)
115
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False)
116
+ for edge in A.edges():
117
+ assert edge.attr["weight"] in ("7", "8")
118
+
119
+ def test_view_pygraphviz_callable_edgelabel(self):
120
+ G = nx.complete_graph(3)
121
+
122
+ def foo_label(data):
123
+ return "foo"
124
+
125
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False)
126
+ for edge in A.edges():
127
+ assert edge.attr["label"] == "foo"
128
+
129
+ def test_view_pygraphviz_multigraph_edgelabels(self):
130
+ G = nx.MultiGraph()
131
+ G.add_edge(0, 1, key=0, name="left_fork")
132
+ G.add_edge(0, 1, key=1, name="right_fork")
133
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False)
134
+ edges = A.edges()
135
+ assert len(edges) == 2
136
+ for edge in edges:
137
+ assert edge.attr["label"].strip() in ("left_fork", "right_fork")
138
+
139
+ def test_graph_with_reserved_keywords(self):
140
+ # test attribute/keyword clash case for #1582
141
+ # node: n
142
+ # edges: u,v
143
+ G = nx.Graph()
144
+ G = self.build_graph(G)
145
+ G.nodes["E"]["n"] = "keyword"
146
+ G.edges[("A", "B")]["u"] = "keyword"
147
+ G.edges[("A", "B")]["v"] = "keyword"
148
+ A = nx.nx_agraph.to_agraph(G)
149
+
150
+ def test_view_pygraphviz_no_added_attrs_to_input(self):
151
+ G = nx.complete_graph(2)
152
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
153
+ assert G.graph == {}
154
+
155
+ @pytest.mark.xfail(reason="known bug in clean_attrs")
156
+ def test_view_pygraphviz_leaves_input_graph_unmodified(self):
157
+ G = nx.complete_graph(2)
158
+ # Add entries to graph dict that to_agraph handles specially
159
+ G.graph["node"] = {"width": "0.80"}
160
+ G.graph["edge"] = {"fontsize": "14"}
161
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
162
+ assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}}
163
+
164
+ def test_graph_with_AGraph_attrs(self):
165
+ G = nx.complete_graph(2)
166
+ # Add entries to graph dict that to_agraph handles specially
167
+ G.graph["node"] = {"width": "0.80"}
168
+ G.graph["edge"] = {"fontsize": "14"}
169
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
170
+ # Ensure user-specified values are not lost
171
+ assert dict(A.node_attr)["width"] == "0.80"
172
+ assert dict(A.edge_attr)["fontsize"] == "14"
173
+
174
+ def test_round_trip_empty_graph(self):
175
+ G = nx.Graph()
176
+ A = nx.nx_agraph.to_agraph(G)
177
+ H = nx.nx_agraph.from_agraph(A)
178
+ # assert graphs_equal(G, H)
179
+ AA = nx.nx_agraph.to_agraph(H)
180
+ HH = nx.nx_agraph.from_agraph(AA)
181
+ assert graphs_equal(H, HH)
182
+ G.graph["graph"] = {}
183
+ G.graph["node"] = {}
184
+ G.graph["edge"] = {}
185
+ assert graphs_equal(G, HH)
186
+
187
+ @pytest.mark.xfail(reason="integer->string node conversion in round trip")
188
+ def test_round_trip_integer_nodes(self):
189
+ G = nx.complete_graph(3)
190
+ A = nx.nx_agraph.to_agraph(G)
191
+ H = nx.nx_agraph.from_agraph(A)
192
+ assert graphs_equal(G, H)
193
+
194
+ def test_graphviz_alias(self):
195
+ G = self.build_graph(nx.Graph())
196
+ pos_graphviz = nx.nx_agraph.graphviz_layout(G)
197
+ pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G)
198
+ assert pos_graphviz == pos_pygraphviz
199
+
200
+ @pytest.mark.parametrize("root", range(5))
201
+ def test_pygraphviz_layout_root(self, root):
202
+ # NOTE: test depends on layout prog being deterministic
203
+ G = nx.complete_graph(5)
204
+ A = nx.nx_agraph.to_agraph(G)
205
+ # Get layout with root arg is not None
206
+ pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root)
207
+ # Equivalent layout directly on AGraph
208
+ A.layout(args=f"-Groot={root}", prog="circo")
209
+ # Parse AGraph layout
210
+ a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(","))
211
+ assert pygv_layout[1] == a1_pos
212
+
213
+ def test_2d_layout(self):
214
+ G = nx.Graph()
215
+ G = self.build_graph(G)
216
+ G.graph["dimen"] = 2
217
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
218
+ pos = list(pos.values())
219
+ assert len(pos) == 5
220
+ assert len(pos[0]) == 2
221
+
222
+ def test_3d_layout(self):
223
+ G = nx.Graph()
224
+ G = self.build_graph(G)
225
+ G.graph["dimen"] = 3
226
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
227
+ pos = list(pos.values())
228
+ assert len(pos) == 5
229
+ assert len(pos[0]) == 3
230
+
231
+ def test_no_warnings_raised(self):
232
+ # Test that no warnings are raised when Networkx graph
233
+ # is converted to Pygraphviz graph and 'pos'
234
+ # attribute is given
235
+ G = nx.Graph()
236
+ G.add_node(0, pos=(0, 0))
237
+ G.add_node(1, pos=(1, 1))
238
+ A = nx.nx_agraph.to_agraph(G)
239
+ with warnings.catch_warnings(record=True) as record:
240
+ A.layout()
241
+ assert len(record) == 0
wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for pydot drawing functions."""
2
+
3
+ from io import StringIO
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.utils import graphs_equal
9
+
10
+ pydot = pytest.importorskip("pydot")
11
+
12
+
13
+ class TestPydot:
14
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
15
+ @pytest.mark.parametrize("prog", ("neato", "dot"))
16
+ def test_pydot(self, G, prog, tmp_path):
17
+ """
18
+ Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
19
+ passed basename of an external GraphViz command (e.g., `dot`, `neato`).
20
+ """
21
+
22
+ # Set the name of this graph to... "G". Failing to do so will
23
+ # subsequently trip an assertion expecting this name.
24
+ G.graph["name"] = "G"
25
+
26
+ # Add arbitrary nodes and edges to the passed empty graph.
27
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
28
+ G.add_node("E")
29
+
30
+ # Validate layout of this graph with the passed GraphViz command.
31
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
32
+ assert isinstance(graph_layout, dict)
33
+
34
+ # Convert this graph into a "pydot.Dot" instance.
35
+ P = nx.nx_pydot.to_pydot(G)
36
+
37
+ # Convert this "pydot.Dot" instance back into a graph of the same type.
38
+ G2 = G.__class__(nx.nx_pydot.from_pydot(P))
39
+
40
+ # Validate the original and resulting graphs to be the same.
41
+ assert graphs_equal(G, G2)
42
+
43
+ fname = tmp_path / "out.dot"
44
+
45
+ # Serialize this "pydot.Dot" instance to a temporary file in dot format
46
+ P.write_raw(fname)
47
+
48
+ # Deserialize a list of new "pydot.Dot" instances back from this file.
49
+ Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")
50
+
51
+ # Validate this file to contain only one graph.
52
+ assert len(Pin_list) == 1
53
+
54
+ # The single "pydot.Dot" instance deserialized from this file.
55
+ Pin = Pin_list[0]
56
+
57
+ # Sorted list of all nodes in the original "pydot.Dot" instance.
58
+ n1 = sorted(p.get_name() for p in P.get_node_list())
59
+
60
+ # Sorted list of all nodes in the deserialized "pydot.Dot" instance.
61
+ n2 = sorted(p.get_name() for p in Pin.get_node_list())
62
+
63
+ # Validate these instances to contain the same nodes.
64
+ assert n1 == n2
65
+
66
+ # Sorted list of all edges in the original "pydot.Dot" instance.
67
+ e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list())
68
+
69
+ # Sorted list of all edges in the original "pydot.Dot" instance.
70
+ e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list())
71
+
72
+ # Validate these instances to contain the same edges.
73
+ assert e1 == e2
74
+
75
+ # Deserialize a new graph of the same type back from this file.
76
+ Hin = nx.nx_pydot.read_dot(fname)
77
+ Hin = G.__class__(Hin)
78
+
79
+ # Validate the original and resulting graphs to be the same.
80
+ assert graphs_equal(G, Hin)
81
+
82
+ def test_read_write(self):
83
+ G = nx.MultiGraph()
84
+ G.graph["name"] = "G"
85
+ G.add_edge("1", "2", key="0") # read assumes strings
86
+ fh = StringIO()
87
+ nx.nx_pydot.write_dot(G, fh)
88
+ fh.seek(0)
89
+ H = nx.nx_pydot.read_dot(fh)
90
+ assert graphs_equal(G, H)
91
+
92
+
93
+ def test_pydot_issue_7581(tmp_path):
94
+ """Validate that `nx_pydot.pydot_layout` handles nodes
95
+ with characters like "\n", " ".
96
+
97
+ Those characters cause `pydot` to escape and quote them on output,
98
+ which caused #7581.
99
+ """
100
+ G = nx.Graph()
101
+ G.add_edges_from([("A\nbig test", "B"), ("A\nbig test", "C"), ("B", "C")])
102
+
103
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
104
+ assert isinstance(graph_layout, dict)
105
+
106
+ # Convert the graph to pydot and back into a graph. There should be no difference.
107
+ P = nx.nx_pydot.to_pydot(G)
108
+ G2 = nx.Graph(nx.nx_pydot.from_pydot(P))
109
+ assert graphs_equal(G, G2)
110
+
111
+
112
+ @pytest.mark.parametrize(
113
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
114
+ )
115
+ def test_hashable_pydot(graph_type):
116
+ # gh-5790
117
+ G = graph_type()
118
+ G.add_edge("5", frozenset([1]), t='"Example:A"', l=False)
119
+ G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"]))
120
+ G.add_edge("node", (3, 3), w="string")
121
+
122
+ assert [
123
+ {"t": '"Example:A"', "l": "False"},
124
+ {"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"},
125
+ {"w": "string"},
126
+ ] == [
127
+ attr
128
+ for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
129
+ ]
130
+
131
+ assert {str(i) for i in G.nodes()} == set(
132
+ nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes
133
+ )
134
+
135
+
136
+ def test_pydot_numerical_name():
137
+ G = nx.Graph()
138
+ G.add_edges_from([("A", "B"), (0, 1)])
139
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
140
+ assert isinstance(graph_layout, dict)
141
+ assert "0" not in graph_layout
142
+ assert 0 in graph_layout
143
+ assert "1" not in graph_layout
144
+ assert 1 in graph_layout
145
+ assert "A" in graph_layout
146
+ assert "B" in graph_layout
wemm/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py ADDED
@@ -0,0 +1,1029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for matplotlib drawing functions."""
2
+
3
+ import itertools
4
+ import os
5
+ import warnings
6
+
7
+ import pytest
8
+
9
+ mpl = pytest.importorskip("matplotlib")
10
+ np = pytest.importorskip("numpy")
11
+ mpl.use("PS")
12
+ plt = pytest.importorskip("matplotlib.pyplot")
13
+ plt.rcParams["text.usetex"] = False
14
+
15
+
16
+ import networkx as nx
17
+
18
+ barbell = nx.barbell_graph(4, 6)
19
+
20
+
21
+ def test_draw():
22
+ try:
23
+ functions = [
24
+ nx.draw_circular,
25
+ nx.draw_kamada_kawai,
26
+ nx.draw_planar,
27
+ nx.draw_random,
28
+ nx.draw_spectral,
29
+ nx.draw_spring,
30
+ nx.draw_shell,
31
+ ]
32
+ options = [{"node_color": "black", "node_size": 100, "width": 3}]
33
+ for function, option in itertools.product(functions, options):
34
+ function(barbell, **option)
35
+ plt.savefig("test.ps")
36
+ except ModuleNotFoundError: # draw_kamada_kawai requires scipy
37
+ pass
38
+ finally:
39
+ try:
40
+ os.unlink("test.ps")
41
+ except OSError:
42
+ pass
43
+
44
+
45
+ def test_draw_shell_nlist():
46
+ try:
47
+ nlist = [list(range(4)), list(range(4, 10)), list(range(10, 14))]
48
+ nx.draw_shell(barbell, nlist=nlist)
49
+ plt.savefig("test.ps")
50
+ finally:
51
+ try:
52
+ os.unlink("test.ps")
53
+ except OSError:
54
+ pass
55
+
56
+
57
+ def test_edge_colormap():
58
+ colors = range(barbell.number_of_edges())
59
+ nx.draw_spring(
60
+ barbell, edge_color=colors, width=4, edge_cmap=plt.cm.Blues, with_labels=True
61
+ )
62
+ # plt.show()
63
+
64
+
65
+ def test_arrows():
66
+ nx.draw_spring(barbell.to_directed())
67
+ # plt.show()
68
+
69
+
70
+ @pytest.mark.parametrize(
71
+ ("edge_color", "expected"),
72
+ (
73
+ (None, "black"), # Default
74
+ ("r", "red"), # Non-default color string
75
+ (["r"], "red"), # Single non-default color in a list
76
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
77
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
78
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
79
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
80
+ ("#0000ff", "blue"), # single color hex code
81
+ (["#0000ff"], "blue"), # hex code in list
82
+ ),
83
+ )
84
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
85
+ def test_single_edge_color_undirected(edge_color, expected, edgelist):
86
+ """Tests ways of specifying all edges have a single color for edges
87
+ drawn with a LineCollection"""
88
+
89
+ G = nx.path_graph(3)
90
+ drawn_edges = nx.draw_networkx_edges(
91
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
92
+ )
93
+ assert mpl.colors.same_color(drawn_edges.get_color(), expected)
94
+
95
+
96
+ @pytest.mark.parametrize(
97
+ ("edge_color", "expected"),
98
+ (
99
+ (None, "black"), # Default
100
+ ("r", "red"), # Non-default color string
101
+ (["r"], "red"), # Single non-default color in a list
102
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
103
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
104
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
105
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
106
+ ("#0000ff", "blue"), # single color hex code
107
+ (["#0000ff"], "blue"), # hex code in list
108
+ ),
109
+ )
110
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
111
+ def test_single_edge_color_directed(edge_color, expected, edgelist):
112
+ """Tests ways of specifying all edges have a single color for edges drawn
113
+ with FancyArrowPatches"""
114
+
115
+ G = nx.path_graph(3, create_using=nx.DiGraph)
116
+ drawn_edges = nx.draw_networkx_edges(
117
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
118
+ )
119
+ for fap in drawn_edges:
120
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
121
+
122
+
123
+ def test_edge_color_tuple_interpretation():
124
+ """If edge_color is a sequence with the same length as edgelist, then each
125
+ value in edge_color is mapped onto each edge via colormap."""
126
+ G = nx.path_graph(6, create_using=nx.DiGraph)
127
+ pos = {n: (n, n) for n in range(len(G))}
128
+
129
+ # num edges != 3 or 4 --> edge_color interpreted as rgb(a)
130
+ for ec in ((0, 0, 1), (0, 0, 1, 1)):
131
+ # More than 4 edges
132
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=ec)
133
+ for fap in drawn_edges:
134
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
135
+ # Fewer than 3 edges
136
+ drawn_edges = nx.draw_networkx_edges(
137
+ G, pos, edgelist=[(0, 1), (1, 2)], edge_color=ec
138
+ )
139
+ for fap in drawn_edges:
140
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
141
+
142
+ # num edges == 3, len(edge_color) == 4: interpreted as rgba
143
+ drawn_edges = nx.draw_networkx_edges(
144
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1, 1)
145
+ )
146
+ for fap in drawn_edges:
147
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
148
+
149
+ # num edges == 4, len(edge_color) == 3: interpreted as rgb
150
+ drawn_edges = nx.draw_networkx_edges(
151
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1)
152
+ )
153
+ for fap in drawn_edges:
154
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
155
+
156
+ # num edges == len(edge_color) == 3: interpreted with cmap, *not* as rgb
157
+ drawn_edges = nx.draw_networkx_edges(
158
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1)
159
+ )
160
+ assert mpl.colors.same_color(
161
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
162
+ )
163
+ for fap in drawn_edges:
164
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
165
+
166
+ # num edges == len(edge_color) == 4: interpreted with cmap, *not* as rgba
167
+ drawn_edges = nx.draw_networkx_edges(
168
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1, 1)
169
+ )
170
+ assert mpl.colors.same_color(
171
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
172
+ )
173
+ assert mpl.colors.same_color(
174
+ drawn_edges[2].get_edgecolor(), drawn_edges[3].get_edgecolor()
175
+ )
176
+ for fap in drawn_edges:
177
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
178
+
179
+
180
+ def test_fewer_edge_colors_than_num_edges_directed():
181
+ """Test that the edge colors are cycled when there are fewer specified
182
+ colors than edges."""
183
+ G = barbell.to_directed()
184
+ pos = nx.random_layout(barbell)
185
+ edgecolors = ("r", "g", "b")
186
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
187
+ for fap, expected in zip(drawn_edges, itertools.cycle(edgecolors)):
188
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
189
+
190
+
191
+ def test_more_edge_colors_than_num_edges_directed():
192
+ """Test that extra edge colors are ignored when there are more specified
193
+ colors than edges."""
194
+ G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges
195
+ pos = nx.random_layout(barbell)
196
+ edgecolors = ("r", "g", "b", "c") # 4 edge colors
197
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
198
+ for fap, expected in zip(drawn_edges, edgecolors[:-1]):
199
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
200
+
201
+
202
+ def test_edge_color_string_with_global_alpha_undirected():
203
+ edge_collection = nx.draw_networkx_edges(
204
+ barbell,
205
+ pos=nx.random_layout(barbell),
206
+ edgelist=[(0, 1), (1, 2)],
207
+ edge_color="purple",
208
+ alpha=0.2,
209
+ )
210
+ ec = edge_collection.get_color().squeeze() # as rgba tuple
211
+ assert len(edge_collection.get_paths()) == 2
212
+ assert mpl.colors.same_color(ec[:-1], "purple")
213
+ assert ec[-1] == 0.2
214
+
215
+
216
+ def test_edge_color_string_with_global_alpha_directed():
217
+ drawn_edges = nx.draw_networkx_edges(
218
+ barbell.to_directed(),
219
+ pos=nx.random_layout(barbell),
220
+ edgelist=[(0, 1), (1, 2)],
221
+ edge_color="purple",
222
+ alpha=0.2,
223
+ )
224
+ assert len(drawn_edges) == 2
225
+ for fap in drawn_edges:
226
+ ec = fap.get_edgecolor() # As rgba tuple
227
+ assert mpl.colors.same_color(ec[:-1], "purple")
228
+ assert ec[-1] == 0.2
229
+
230
+
231
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
232
+ def test_edge_width_default_value(graph_type):
233
+ """Test the default linewidth for edges drawn either via LineCollection or
234
+ FancyArrowPatches."""
235
+ G = nx.path_graph(2, create_using=graph_type)
236
+ pos = {n: (n, n) for n in range(len(G))}
237
+ drawn_edges = nx.draw_networkx_edges(G, pos)
238
+ if isinstance(drawn_edges, list): # directed case: list of FancyArrowPatch
239
+ drawn_edges = drawn_edges[0]
240
+ assert drawn_edges.get_linewidth() == 1
241
+
242
+
243
+ @pytest.mark.parametrize(
244
+ ("edgewidth", "expected"),
245
+ (
246
+ (3, 3), # single-value, non-default
247
+ ([3], 3), # Single value as a list
248
+ ),
249
+ )
250
+ def test_edge_width_single_value_undirected(edgewidth, expected):
251
+ G = nx.path_graph(4)
252
+ pos = {n: (n, n) for n in range(len(G))}
253
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
254
+ assert len(drawn_edges.get_paths()) == 3
255
+ assert drawn_edges.get_linewidth() == expected
256
+
257
+
258
+ @pytest.mark.parametrize(
259
+ ("edgewidth", "expected"),
260
+ (
261
+ (3, 3), # single-value, non-default
262
+ ([3], 3), # Single value as a list
263
+ ),
264
+ )
265
+ def test_edge_width_single_value_directed(edgewidth, expected):
266
+ G = nx.path_graph(4, create_using=nx.DiGraph)
267
+ pos = {n: (n, n) for n in range(len(G))}
268
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
269
+ assert len(drawn_edges) == 3
270
+ for fap in drawn_edges:
271
+ assert fap.get_linewidth() == expected
272
+
273
+
274
+ @pytest.mark.parametrize(
275
+ "edgelist",
276
+ (
277
+ [(0, 1), (1, 2), (2, 3)], # one width specification per edge
278
+ None, # fewer widths than edges - widths cycle
279
+ [(0, 1), (1, 2)], # More widths than edges - unused widths ignored
280
+ ),
281
+ )
282
+ def test_edge_width_sequence(edgelist):
283
+ G = barbell.to_directed()
284
+ pos = nx.random_layout(G)
285
+ widths = (0.5, 2.0, 12.0)
286
+ drawn_edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, width=widths)
287
+ for fap, expected_width in zip(drawn_edges, itertools.cycle(widths)):
288
+ assert fap.get_linewidth() == expected_width
289
+
290
+
291
+ def test_edge_color_with_edge_vmin_vmax():
292
+ """Test that edge_vmin and edge_vmax properly set the dynamic range of the
293
+ color map when num edges == len(edge_colors)."""
294
+ G = nx.path_graph(3, create_using=nx.DiGraph)
295
+ pos = nx.random_layout(G)
296
+ # Extract colors from the original (unscaled) colormap
297
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=[0, 1.0])
298
+ orig_colors = [e.get_edgecolor() for e in drawn_edges]
299
+ # Colors from scaled colormap
300
+ drawn_edges = nx.draw_networkx_edges(
301
+ G, pos, edge_color=[0.2, 0.8], edge_vmin=0.2, edge_vmax=0.8
302
+ )
303
+ scaled_colors = [e.get_edgecolor() for e in drawn_edges]
304
+ assert mpl.colors.same_color(orig_colors, scaled_colors)
305
+
306
+
307
+ def test_directed_edges_linestyle_default():
308
+ """Test default linestyle for edges drawn with FancyArrowPatches."""
309
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
310
+ pos = {n: (n, n) for n in range(len(G))}
311
+
312
+ # edge with default style
313
+ drawn_edges = nx.draw_networkx_edges(G, pos)
314
+ assert len(drawn_edges) == 3
315
+ for fap in drawn_edges:
316
+ assert fap.get_linestyle() == "solid"
317
+
318
+
319
+ @pytest.mark.parametrize(
320
+ "style",
321
+ (
322
+ "dashed", # edge with string style
323
+ "--", # edge with simplified string style
324
+ (1, (1, 1)), # edge with (offset, onoffseq) style
325
+ ),
326
+ )
327
+ def test_directed_edges_linestyle_single_value(style):
328
+ """Tests support for specifying linestyles with a single value to be applied to
329
+ all edges in ``draw_networkx_edges`` for FancyArrowPatch outputs
330
+ (e.g. directed edges)."""
331
+
332
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
333
+ pos = {n: (n, n) for n in range(len(G))}
334
+
335
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style)
336
+ assert len(drawn_edges) == 3
337
+ for fap in drawn_edges:
338
+ assert fap.get_linestyle() == style
339
+
340
+
341
+ @pytest.mark.parametrize(
342
+ "style_seq",
343
+ (
344
+ ["dashed"], # edge with string style in list
345
+ ["--"], # edge with simplified string style in list
346
+ [(1, (1, 1))], # edge with (offset, onoffseq) style in list
347
+ ["--", "-", ":"], # edges with styles for each edge
348
+ ["--", "-"], # edges with fewer styles than edges (styles cycle)
349
+ ["--", "-", ":", "-."], # edges with more styles than edges (extra unused)
350
+ ),
351
+ )
352
+ def test_directed_edges_linestyle_sequence(style_seq):
353
+ """Tests support for specifying linestyles with sequences in
354
+ ``draw_networkx_edges`` for FancyArrowPatch outputs (e.g. directed edges)."""
355
+
356
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
357
+ pos = {n: (n, n) for n in range(len(G))}
358
+
359
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style_seq)
360
+ assert len(drawn_edges) == 3
361
+ for fap, style in zip(drawn_edges, itertools.cycle(style_seq)):
362
+ assert fap.get_linestyle() == style
363
+
364
+
365
+ def test_return_types():
366
+ from matplotlib.collections import LineCollection, PathCollection
367
+ from matplotlib.patches import FancyArrowPatch
368
+
369
+ G = nx.cubical_graph(nx.Graph)
370
+ dG = nx.cubical_graph(nx.DiGraph)
371
+ pos = nx.spring_layout(G)
372
+ dpos = nx.spring_layout(dG)
373
+ # nodes
374
+ nodes = nx.draw_networkx_nodes(G, pos)
375
+ assert isinstance(nodes, PathCollection)
376
+ # edges
377
+ edges = nx.draw_networkx_edges(dG, dpos, arrows=True)
378
+ assert isinstance(edges, list)
379
+ if len(edges) > 0:
380
+ assert isinstance(edges[0], FancyArrowPatch)
381
+ edges = nx.draw_networkx_edges(dG, dpos, arrows=False)
382
+ assert isinstance(edges, LineCollection)
383
+ edges = nx.draw_networkx_edges(G, dpos, arrows=None)
384
+ assert isinstance(edges, LineCollection)
385
+ edges = nx.draw_networkx_edges(dG, pos, arrows=None)
386
+ assert isinstance(edges, list)
387
+ if len(edges) > 0:
388
+ assert isinstance(edges[0], FancyArrowPatch)
389
+
390
+
391
+ def test_labels_and_colors():
392
+ G = nx.cubical_graph()
393
+ pos = nx.spring_layout(G) # positions for all nodes
394
+ # nodes
395
+ nx.draw_networkx_nodes(
396
+ G, pos, nodelist=[0, 1, 2, 3], node_color="r", node_size=500, alpha=0.75
397
+ )
398
+ nx.draw_networkx_nodes(
399
+ G,
400
+ pos,
401
+ nodelist=[4, 5, 6, 7],
402
+ node_color="b",
403
+ node_size=500,
404
+ alpha=[0.25, 0.5, 0.75, 1.0],
405
+ )
406
+ # edges
407
+ nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
408
+ nx.draw_networkx_edges(
409
+ G,
410
+ pos,
411
+ edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
412
+ width=8,
413
+ alpha=0.5,
414
+ edge_color="r",
415
+ )
416
+ nx.draw_networkx_edges(
417
+ G,
418
+ pos,
419
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
420
+ width=8,
421
+ alpha=0.5,
422
+ edge_color="b",
423
+ )
424
+ nx.draw_networkx_edges(
425
+ G,
426
+ pos,
427
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
428
+ arrows=True,
429
+ min_source_margin=0.5,
430
+ min_target_margin=0.75,
431
+ width=8,
432
+ edge_color="b",
433
+ )
434
+ # some math labels
435
+ labels = {}
436
+ labels[0] = r"$a$"
437
+ labels[1] = r"$b$"
438
+ labels[2] = r"$c$"
439
+ labels[3] = r"$d$"
440
+ labels[4] = r"$\alpha$"
441
+ labels[5] = r"$\beta$"
442
+ labels[6] = r"$\gamma$"
443
+ labels[7] = r"$\delta$"
444
+ colors = {n: "k" if n % 2 == 0 else "r" for n in range(8)}
445
+ nx.draw_networkx_labels(G, pos, labels, font_size=16)
446
+ nx.draw_networkx_labels(G, pos, labels, font_size=16, font_color=colors)
447
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=None, rotate=False)
448
+ nx.draw_networkx_edge_labels(G, pos, edge_labels={(4, 5): "4-5"})
449
+ # plt.show()
450
+
451
+
452
+ @pytest.mark.mpl_image_compare
453
+ def test_house_with_colors():
454
+ G = nx.house_graph()
455
+ # explicitly set positions
456
+ fig, ax = plt.subplots()
457
+ pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
458
+
459
+ # Plot nodes with different properties for the "wall" and "roof" nodes
460
+ nx.draw_networkx_nodes(
461
+ G,
462
+ pos,
463
+ node_size=3000,
464
+ nodelist=[0, 1, 2, 3],
465
+ node_color="tab:blue",
466
+ )
467
+ nx.draw_networkx_nodes(
468
+ G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
469
+ )
470
+ nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
471
+ # Customize axes
472
+ ax.margins(0.11)
473
+ plt.tight_layout()
474
+ plt.axis("off")
475
+ return fig
476
+
477
+
478
+ def test_axes():
479
+ fig, ax = plt.subplots()
480
+ nx.draw(barbell, ax=ax)
481
+ nx.draw_networkx_edge_labels(barbell, nx.circular_layout(barbell), ax=ax)
482
+
483
+
484
+ def test_empty_graph():
485
+ G = nx.Graph()
486
+ nx.draw(G)
487
+
488
+
489
+ def test_draw_empty_nodes_return_values():
490
+ # See Issue #3833
491
+ import matplotlib.collections # call as mpl.collections
492
+
493
+ G = nx.Graph([(1, 2), (2, 3)])
494
+ DG = nx.DiGraph([(1, 2), (2, 3)])
495
+ pos = nx.circular_layout(G)
496
+ assert isinstance(
497
+ nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection
498
+ )
499
+ assert isinstance(
500
+ nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection
501
+ )
502
+
503
+ # drawing empty edges used to return an empty LineCollection or empty list.
504
+ # Now it is always an empty list (because edges are now lists of FancyArrows)
505
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=True) == []
506
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=False) == []
507
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=False) == []
508
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=True) == []
509
+
510
+
511
+ def test_multigraph_edgelist_tuples():
512
+ # See Issue #3295
513
+ G = nx.path_graph(3, create_using=nx.MultiDiGraph)
514
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)])
515
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20, 0])
516
+
517
+
518
+ def test_alpha_iter():
519
+ pos = nx.random_layout(barbell)
520
+ fig = plt.figure()
521
+ # with fewer alpha elements than nodes
522
+ fig.add_subplot(131) # Each test in a new axis object
523
+ nx.draw_networkx_nodes(barbell, pos, alpha=[0.1, 0.2])
524
+ # with equal alpha elements and nodes
525
+ num_nodes = len(barbell.nodes)
526
+ alpha = [x / num_nodes for x in range(num_nodes)]
527
+ colors = range(num_nodes)
528
+ fig.add_subplot(132)
529
+ nx.draw_networkx_nodes(barbell, pos, node_color=colors, alpha=alpha)
530
+ # with more alpha elements than nodes
531
+ alpha.append(1)
532
+ fig.add_subplot(133)
533
+ nx.draw_networkx_nodes(barbell, pos, alpha=alpha)
534
+
535
+
536
+ def test_multiple_node_shapes():
537
+ G = nx.path_graph(4)
538
+ ax = plt.figure().add_subplot(111)
539
+ nx.draw(G, node_shape=["o", "h", "s", "^"], ax=ax)
540
+ scatters = [
541
+ s for s in ax.get_children() if isinstance(s, mpl.collections.PathCollection)
542
+ ]
543
+ assert len(scatters) == 4
544
+
545
+
546
+ def test_individualized_font_attributes():
547
+ G = nx.karate_club_graph()
548
+ ax = plt.figure().add_subplot(111)
549
+ nx.draw(
550
+ G,
551
+ ax=ax,
552
+ font_color={n: "k" if n % 2 else "r" for n in G.nodes()},
553
+ font_size={n: int(n / (34 / 15) + 5) for n in G.nodes()},
554
+ )
555
+ for n, t in zip(
556
+ G.nodes(),
557
+ [
558
+ t
559
+ for t in ax.get_children()
560
+ if isinstance(t, mpl.text.Text) and len(t.get_text()) > 0
561
+ ],
562
+ ):
563
+ expected = "black" if n % 2 else "red"
564
+
565
+ assert mpl.colors.same_color(t.get_color(), expected)
566
+ assert int(n / (34 / 15) + 5) == t.get_size()
567
+
568
+
569
+ def test_individualized_edge_attributes():
570
+ G = nx.karate_club_graph()
571
+ ax = plt.figure().add_subplot(111)
572
+ arrowstyles = ["-|>" if (u + v) % 2 == 0 else "-[" for u, v in G.edges()]
573
+ arrowsizes = [10 * (u % 2 + v % 2) + 10 for u, v in G.edges()]
574
+ nx.draw(G, ax=ax, arrows=True, arrowstyle=arrowstyles, arrowsize=arrowsizes)
575
+ arrows = [
576
+ f for f in ax.get_children() if isinstance(f, mpl.patches.FancyArrowPatch)
577
+ ]
578
+ for e, a in zip(G.edges(), arrows):
579
+ assert a.get_mutation_scale() == 10 * (e[0] % 2 + e[1] % 2) + 10
580
+ expected = (
581
+ mpl.patches.ArrowStyle.BracketB
582
+ if sum(e) % 2
583
+ else mpl.patches.ArrowStyle.CurveFilledB
584
+ )
585
+ assert isinstance(a.get_arrowstyle(), expected)
586
+
587
+
588
+ def test_error_invalid_kwds():
589
+ with pytest.raises(ValueError, match="Received invalid argument"):
590
+ nx.draw(barbell, foo="bar")
591
+
592
+
593
+ def test_draw_networkx_arrowsize_incorrect_size():
594
+ G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 3)])
595
+ arrowsize = [1, 2, 3]
596
+ with pytest.raises(
597
+ ValueError, match="arrowsize should have the same length as edgelist"
598
+ ):
599
+ nx.draw(G, arrowsize=arrowsize)
600
+
601
+
602
+ @pytest.mark.parametrize("arrowsize", (30, [10, 20, 30]))
603
+ def test_draw_edges_arrowsize(arrowsize):
604
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
605
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
606
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowsize=arrowsize)
607
+
608
+ arrowsize = itertools.repeat(arrowsize) if isinstance(arrowsize, int) else arrowsize
609
+
610
+ for fap, expected in zip(edges, arrowsize):
611
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
612
+ assert fap.get_mutation_scale() == expected
613
+
614
+
615
+ @pytest.mark.parametrize("arrowstyle", ("-|>", ["-|>", "-[", "<|-|>"]))
616
+ def test_draw_edges_arrowstyle(arrowstyle):
617
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
618
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
619
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowstyle=arrowstyle)
620
+
621
+ arrowstyle = (
622
+ itertools.repeat(arrowstyle) if isinstance(arrowstyle, str) else arrowstyle
623
+ )
624
+
625
+ arrow_objects = {
626
+ "-|>": mpl.patches.ArrowStyle.CurveFilledB,
627
+ "-[": mpl.patches.ArrowStyle.BracketB,
628
+ "<|-|>": mpl.patches.ArrowStyle.CurveFilledAB,
629
+ }
630
+
631
+ for fap, expected in zip(edges, arrowstyle):
632
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
633
+ assert isinstance(fap.get_arrowstyle(), arrow_objects[expected])
634
+
635
+
636
+ def test_np_edgelist():
637
+ # see issue #4129
638
+ nx.draw_networkx(barbell, edgelist=np.array([(0, 2), (0, 3)]))
639
+
640
+
641
+ def test_draw_nodes_missing_node_from_position():
642
+ G = nx.path_graph(3)
643
+ pos = {0: (0, 0), 1: (1, 1)} # No position for node 2
644
+ with pytest.raises(nx.NetworkXError, match="has no position"):
645
+ nx.draw_networkx_nodes(G, pos)
646
+
647
+
648
+ # NOTE: parametrizing on marker to test both branches of internal
649
+ # nx.draw_networkx_edges.to_marker_edge function
650
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
651
+ def test_draw_edges_min_source_target_margins(node_shape):
652
+ """Test that there is a wider gap between the node and the start of an
653
+ incident edge when min_source_margin is specified.
654
+
655
+ This test checks that the use of min_{source/target}_margin kwargs result
656
+ in shorter (more padding) between the edges and source and target nodes.
657
+ As a crude visual example, let 's' and 't' represent source and target
658
+ nodes, respectively:
659
+
660
+ Default:
661
+ s-----------------------------t
662
+
663
+ With margins:
664
+ s ----------------------- t
665
+
666
+ """
667
+ # Create a single axis object to get consistent pixel coords across
668
+ # multiple draws
669
+ fig, ax = plt.subplots()
670
+ G = nx.DiGraph([(0, 1)])
671
+ pos = {0: (0, 0), 1: (1, 0)} # horizontal layout
672
+ # Get leftmost and rightmost points of the FancyArrowPatch object
673
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
674
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)[0]
675
+ default_extent = default_patch.get_extents().corners()[::2, 0]
676
+ # Now, do the same but with "padding" for the source and target via the
677
+ # min_{source/target}_margin kwargs
678
+ padded_patch = nx.draw_networkx_edges(
679
+ G,
680
+ pos,
681
+ ax=ax,
682
+ node_shape=node_shape,
683
+ min_source_margin=100,
684
+ min_target_margin=100,
685
+ )[0]
686
+ padded_extent = padded_patch.get_extents().corners()[::2, 0]
687
+
688
+ # With padding, the left-most extent of the edge should be further to the
689
+ # right
690
+ assert padded_extent[0] > default_extent[0]
691
+ # And the rightmost extent of the edge, further to the left
692
+ assert padded_extent[1] < default_extent[1]
693
+
694
+
695
+ # NOTE: parametrizing on marker to test both branches of internal
696
+ # nx.draw_networkx_edges.to_marker_edge function
697
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
698
+ def test_draw_edges_min_source_target_margins_individual(node_shape):
699
+ """Test that there is a wider gap between the node and the start of an
700
+ incident edge when min_source_margin is specified.
701
+
702
+ This test checks that the use of min_{source/target}_margin kwargs result
703
+ in shorter (more padding) between the edges and source and target nodes.
704
+ As a crude visual example, let 's' and 't' represent source and target
705
+ nodes, respectively:
706
+
707
+ Default:
708
+ s-----------------------------t
709
+
710
+ With margins:
711
+ s ----------------------- t
712
+
713
+ """
714
+ # Create a single axis object to get consistent pixel coords across
715
+ # multiple draws
716
+ fig, ax = plt.subplots()
717
+ G = nx.DiGraph([(0, 1), (1, 2)])
718
+ pos = {0: (0, 0), 1: (1, 0), 2: (2, 0)} # horizontal layout
719
+ # Get leftmost and rightmost points of the FancyArrowPatch object
720
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
721
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)
722
+ default_extent = [d.get_extents().corners()[::2, 0] for d in default_patch]
723
+ # Now, do the same but with "padding" for the source and target via the
724
+ # min_{source/target}_margin kwargs
725
+ padded_patch = nx.draw_networkx_edges(
726
+ G,
727
+ pos,
728
+ ax=ax,
729
+ node_shape=node_shape,
730
+ min_source_margin=[98, 102],
731
+ min_target_margin=[98, 102],
732
+ )
733
+ padded_extent = [p.get_extents().corners()[::2, 0] for p in padded_patch]
734
+ for d, p in zip(default_extent, padded_extent):
735
+ print(f"{p=}, {d=}")
736
+ # With padding, the left-most extent of the edge should be further to the
737
+ # right
738
+ assert p[0] > d[0]
739
+ # And the rightmost extent of the edge, further to the left
740
+ assert p[1] < d[1]
741
+
742
+
743
+ def test_nonzero_selfloop_with_single_node():
744
+ """Ensure that selfloop extent is non-zero when there is only one node."""
745
+ # Create explicit axis object for test
746
+ fig, ax = plt.subplots()
747
+ # Graph with single node + self loop
748
+ G = nx.DiGraph()
749
+ G.add_node(0)
750
+ G.add_edge(0, 0)
751
+ # Draw
752
+ patch = nx.draw_networkx_edges(G, {0: (0, 0)})[0]
753
+ # The resulting patch must have non-zero extent
754
+ bbox = patch.get_extents()
755
+ assert bbox.width > 0 and bbox.height > 0
756
+ # Cleanup
757
+ plt.delaxes(ax)
758
+ plt.close()
759
+
760
+
761
+ def test_nonzero_selfloop_with_single_edge_in_edgelist():
762
+ """Ensure that selfloop extent is non-zero when only a single edge is
763
+ specified in the edgelist.
764
+ """
765
+ # Create explicit axis object for test
766
+ fig, ax = plt.subplots()
767
+ # Graph with selfloop
768
+ G = nx.path_graph(2, create_using=nx.DiGraph)
769
+ G.add_edge(1, 1)
770
+ pos = {n: (n, n) for n in G.nodes}
771
+ # Draw only the selfloop edge via the `edgelist` kwarg
772
+ patch = nx.draw_networkx_edges(G, pos, edgelist=[(1, 1)])[0]
773
+ # The resulting patch must have non-zero extent
774
+ bbox = patch.get_extents()
775
+ assert bbox.width > 0 and bbox.height > 0
776
+ # Cleanup
777
+ plt.delaxes(ax)
778
+ plt.close()
779
+
780
+
781
+ def test_apply_alpha():
782
+ """Test apply_alpha when there is a mismatch between the number of
783
+ supplied colors and elements.
784
+ """
785
+ nodelist = [0, 1, 2]
786
+ colorlist = ["r", "g", "b"]
787
+ alpha = 0.5
788
+ rgba_colors = nx.drawing.nx_pylab.apply_alpha(colorlist, alpha, nodelist)
789
+ assert all(rgba_colors[:, -1] == alpha)
790
+
791
+
792
+ def test_draw_edges_toggling_with_arrows_kwarg():
793
+ """
794
+ The `arrows` keyword argument is used as a 3-way switch to select which
795
+ type of object to use for drawing edges:
796
+ - ``arrows=None`` -> default (FancyArrowPatches for directed, else LineCollection)
797
+ - ``arrows=True`` -> FancyArrowPatches
798
+ - ``arrows=False`` -> LineCollection
799
+ """
800
+ import matplotlib.collections
801
+ import matplotlib.patches
802
+
803
+ UG = nx.path_graph(3)
804
+ DG = nx.path_graph(3, create_using=nx.DiGraph)
805
+ pos = {n: (n, n) for n in UG}
806
+
807
+ # Use FancyArrowPatches when arrows=True, regardless of graph type
808
+ for G in (UG, DG):
809
+ edges = nx.draw_networkx_edges(G, pos, arrows=True)
810
+ assert len(edges) == len(G.edges)
811
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
812
+
813
+ # Use LineCollection when arrows=False, regardless of graph type
814
+ for G in (UG, DG):
815
+ edges = nx.draw_networkx_edges(G, pos, arrows=False)
816
+ assert isinstance(edges, mpl.collections.LineCollection)
817
+
818
+ # Default behavior when arrows=None: FAPs for directed, LC's for undirected
819
+ edges = nx.draw_networkx_edges(UG, pos)
820
+ assert isinstance(edges, mpl.collections.LineCollection)
821
+ edges = nx.draw_networkx_edges(DG, pos)
822
+ assert len(edges) == len(G.edges)
823
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
824
+
825
+
826
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
827
+ def test_draw_networkx_arrows_default_undirected(drawing_func):
828
+ import matplotlib.collections
829
+
830
+ G = nx.path_graph(3)
831
+ fig, ax = plt.subplots()
832
+ drawing_func(G, ax=ax)
833
+ assert any(isinstance(c, mpl.collections.LineCollection) for c in ax.collections)
834
+ assert not ax.patches
835
+ plt.delaxes(ax)
836
+ plt.close()
837
+
838
+
839
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
840
+ def test_draw_networkx_arrows_default_directed(drawing_func):
841
+ import matplotlib.collections
842
+
843
+ G = nx.path_graph(3, create_using=nx.DiGraph)
844
+ fig, ax = plt.subplots()
845
+ drawing_func(G, ax=ax)
846
+ assert not any(
847
+ isinstance(c, mpl.collections.LineCollection) for c in ax.collections
848
+ )
849
+ assert ax.patches
850
+ plt.delaxes(ax)
851
+ plt.close()
852
+
853
+
854
+ def test_edgelist_kwarg_not_ignored():
855
+ # See gh-4994
856
+ G = nx.path_graph(3)
857
+ G.add_edge(0, 0)
858
+ fig, ax = plt.subplots()
859
+ nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax) # Exclude self-loop from edgelist
860
+ assert not ax.patches
861
+ plt.delaxes(ax)
862
+ plt.close()
863
+
864
+
865
+ @pytest.mark.parametrize(
866
+ ("G", "expected_n_edges"),
867
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
868
+ )
869
+ def test_draw_networkx_edges_multiedge_connectionstyle(G, expected_n_edges):
870
+ """Draws edges correctly for 3 types of graphs and checks for valid length"""
871
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
872
+ G.add_edge(u, v, weight=round(i / 3, 2))
873
+ pos = {n: (n, n) for n in G}
874
+ # Raises on insufficient connectionstyle length
875
+ for conn_style in [
876
+ "arc3,rad=0.1",
877
+ ["arc3,rad=0.1", "arc3,rad=0.1"],
878
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.2"],
879
+ ]:
880
+ nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
881
+ arrows = nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
882
+ assert len(arrows) == expected_n_edges
883
+
884
+
885
+ @pytest.mark.parametrize(
886
+ ("G", "expected_n_edges"),
887
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
888
+ )
889
+ def test_draw_networkx_edge_labels_multiedge_connectionstyle(G, expected_n_edges):
890
+ """Draws labels correctly for 3 types of graphs and checks for valid length and class names"""
891
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
892
+ G.add_edge(u, v, weight=round(i / 3, 2))
893
+ pos = {n: (n, n) for n in G}
894
+ # Raises on insufficient connectionstyle length
895
+ arrows = nx.draw_networkx_edges(
896
+ G, pos, connectionstyle=["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"]
897
+ )
898
+ for conn_style in [
899
+ "arc3,rad=0.1",
900
+ ["arc3,rad=0.1", "arc3,rad=0.2"],
901
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"],
902
+ ]:
903
+ text_items = nx.draw_networkx_edge_labels(G, pos, connectionstyle=conn_style)
904
+ assert len(text_items) == expected_n_edges
905
+ for ti in text_items.values():
906
+ assert ti.__class__.__name__ == "CurvedArrowText"
907
+
908
+
909
+ def test_draw_networkx_edge_label_multiedge():
910
+ G = nx.MultiGraph()
911
+ G.add_edge(0, 1, weight=10)
912
+ G.add_edge(0, 1, weight=20)
913
+ edge_labels = nx.get_edge_attributes(G, "weight") # Includes edge keys
914
+ pos = {n: (n, n) for n in G}
915
+ text_items = nx.draw_networkx_edge_labels(
916
+ G,
917
+ pos,
918
+ edge_labels=edge_labels,
919
+ connectionstyle=["arc3,rad=0.1", "arc3,rad=0.2"],
920
+ )
921
+ assert len(text_items) == 2
922
+
923
+
924
+ def test_draw_networkx_edge_label_empty_dict():
925
+ """Regression test for draw_networkx_edge_labels with empty dict. See
926
+ gh-5372."""
927
+ G = nx.path_graph(3)
928
+ pos = {n: (n, n) for n in G.nodes}
929
+ assert nx.draw_networkx_edge_labels(G, pos, edge_labels={}) == {}
930
+
931
+
932
+ def test_draw_networkx_edges_undirected_selfloop_colors():
933
+ """When an edgelist is supplied along with a sequence of colors, check that
934
+ the self-loops have the correct colors."""
935
+ fig, ax = plt.subplots()
936
+ # Edge list and corresponding colors
937
+ edgelist = [(1, 3), (1, 2), (2, 3), (1, 1), (3, 3), (2, 2)]
938
+ edge_colors = ["pink", "cyan", "black", "red", "blue", "green"]
939
+
940
+ G = nx.Graph(edgelist)
941
+ pos = {n: (n, n) for n in G.nodes}
942
+ nx.draw_networkx_edges(G, pos, ax=ax, edgelist=edgelist, edge_color=edge_colors)
943
+
944
+ # Verify that there are three fancy arrow patches (1 per self loop)
945
+ assert len(ax.patches) == 3
946
+
947
+ # These are points that should be contained in the self loops. For example,
948
+ # sl_points[0] will be (1, 1.1), which is inside the "path" of the first
949
+ # self-loop but outside the others
950
+ sl_points = np.array(edgelist[-3:]) + np.array([0, 0.1])
951
+
952
+ # Check that the mapping between self-loop locations and their colors is
953
+ # correct
954
+ for fap, clr, slp in zip(ax.patches, edge_colors[-3:], sl_points):
955
+ assert fap.get_path().contains_point(slp)
956
+ assert mpl.colors.same_color(fap.get_edgecolor(), clr)
957
+ plt.delaxes(ax)
958
+ plt.close()
959
+
960
+
961
+ @pytest.mark.parametrize(
962
+ "fap_only_kwarg", # Non-default values for kwargs that only apply to FAPs
963
+ (
964
+ {"arrowstyle": "-"},
965
+ {"arrowsize": 20},
966
+ {"connectionstyle": "arc3,rad=0.2"},
967
+ {"min_source_margin": 10},
968
+ {"min_target_margin": 10},
969
+ ),
970
+ )
971
+ def test_user_warnings_for_unused_edge_drawing_kwargs(fap_only_kwarg):
972
+ """Users should get a warning when they specify a non-default value for
973
+ one of the kwargs that applies only to edges drawn with FancyArrowPatches,
974
+ but FancyArrowPatches aren't being used under the hood."""
975
+ G = nx.path_graph(3)
976
+ pos = {n: (n, n) for n in G}
977
+ fig, ax = plt.subplots()
978
+ # By default, an undirected graph will use LineCollection to represent
979
+ # the edges
980
+ kwarg_name = list(fap_only_kwarg.keys())[0]
981
+ with pytest.warns(
982
+ UserWarning, match=f"\n\nThe {kwarg_name} keyword argument is not applicable"
983
+ ):
984
+ nx.draw_networkx_edges(G, pos, ax=ax, **fap_only_kwarg)
985
+ # FancyArrowPatches are always used when `arrows=True` is specified.
986
+ # Check that warnings are *not* raised in this case
987
+ with warnings.catch_warnings():
988
+ # Escalate warnings -> errors so tests fail if warnings are raised
989
+ warnings.simplefilter("error")
990
+ nx.draw_networkx_edges(G, pos, ax=ax, arrows=True, **fap_only_kwarg)
991
+
992
+ plt.delaxes(ax)
993
+ plt.close()
994
+
995
+
996
+ @pytest.mark.parametrize("draw_fn", (nx.draw, nx.draw_circular))
997
+ def test_no_warning_on_default_draw_arrowstyle(draw_fn):
998
+ # See gh-7284
999
+ fig, ax = plt.subplots()
1000
+ G = nx.cycle_graph(5)
1001
+ with warnings.catch_warnings(record=True) as w:
1002
+ draw_fn(G, ax=ax)
1003
+ assert len(w) == 0
1004
+
1005
+ plt.delaxes(ax)
1006
+ plt.close()
1007
+
1008
+
1009
+ @pytest.mark.parametrize("hide_ticks", [False, True])
1010
+ @pytest.mark.parametrize(
1011
+ "method",
1012
+ [
1013
+ nx.draw_networkx,
1014
+ nx.draw_networkx_edge_labels,
1015
+ nx.draw_networkx_edges,
1016
+ nx.draw_networkx_labels,
1017
+ nx.draw_networkx_nodes,
1018
+ ],
1019
+ )
1020
+ def test_hide_ticks(method, hide_ticks):
1021
+ G = nx.path_graph(3)
1022
+ pos = {n: (n, n) for n in G.nodes}
1023
+ _, ax = plt.subplots()
1024
+ method(G, pos=pos, ax=ax, hide_ticks=hide_ticks)
1025
+ for axis in [ax.xaxis, ax.yaxis]:
1026
+ assert bool(axis.get_ticklabels()) != hide_ticks
1027
+
1028
+ plt.delaxes(ax)
1029
+ plt.close()
wemm/lib/python3.10/site-packages/networkx/generators/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A package for generating various graphs in networkx.
3
+
4
+ """
5
+
6
+ from networkx.generators.atlas import *
7
+ from networkx.generators.classic import *
8
+ from networkx.generators.cographs import *
9
+ from networkx.generators.community import *
10
+ from networkx.generators.degree_seq import *
11
+ from networkx.generators.directed import *
12
+ from networkx.generators.duplication import *
13
+ from networkx.generators.ego import *
14
+ from networkx.generators.expanders import *
15
+ from networkx.generators.geometric import *
16
+ from networkx.generators.harary_graph import *
17
+ from networkx.generators.internet_as_graphs import *
18
+ from networkx.generators.intersection import *
19
+ from networkx.generators.interval_graph import *
20
+ from networkx.generators.joint_degree_seq import *
21
+ from networkx.generators.lattice import *
22
+ from networkx.generators.line import *
23
+ from networkx.generators.mycielski import *
24
+ from networkx.generators.nonisomorphic_trees import *
25
+ from networkx.generators.random_clustered import *
26
+ from networkx.generators.random_graphs import *
27
+ from networkx.generators.small import *
28
+ from networkx.generators.social import *
29
+ from networkx.generators.spectral_graph_forge import *
30
+ from networkx.generators.stochastic import *
31
+ from networkx.generators.sudoku import *
32
+ from networkx.generators.time_series import *
33
+ from networkx.generators.trees import *
34
+ from networkx.generators.triads import *
wemm/lib/python3.10/site-packages/networkx/generators/classic.py ADDED
@@ -0,0 +1,1068 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for some classic graphs.
2
+
3
+ The typical graph builder function is called as follows:
4
+
5
+ >>> G = nx.complete_graph(100)
6
+
7
+ returning the complete graph on n nodes labeled 0, .., 99
8
+ as a simple graph. Except for `empty_graph`, all the functions
9
+ in this module return a Graph class (i.e. a simple, undirected graph).
10
+
11
+ """
12
+
13
+ import itertools
14
+ import numbers
15
+
16
+ import networkx as nx
17
+ from networkx.classes import Graph
18
+ from networkx.exception import NetworkXError
19
+ from networkx.utils import nodes_or_number, pairwise
20
+
21
+ __all__ = [
22
+ "balanced_tree",
23
+ "barbell_graph",
24
+ "binomial_tree",
25
+ "complete_graph",
26
+ "complete_multipartite_graph",
27
+ "circular_ladder_graph",
28
+ "circulant_graph",
29
+ "cycle_graph",
30
+ "dorogovtsev_goltsev_mendes_graph",
31
+ "empty_graph",
32
+ "full_rary_tree",
33
+ "kneser_graph",
34
+ "ladder_graph",
35
+ "lollipop_graph",
36
+ "null_graph",
37
+ "path_graph",
38
+ "star_graph",
39
+ "tadpole_graph",
40
+ "trivial_graph",
41
+ "turan_graph",
42
+ "wheel_graph",
43
+ ]
44
+
45
+
46
+ # -------------------------------------------------------------------
47
+ # Some Classic Graphs
48
+ # -------------------------------------------------------------------
49
+
50
+
51
+ def _tree_edges(n, r):
52
+ if n == 0:
53
+ return
54
+ # helper function for trees
55
+ # yields edges in rooted tree at 0 with n nodes and branching ratio r
56
+ nodes = iter(range(n))
57
+ parents = [next(nodes)] # stack of max length r
58
+ while parents:
59
+ source = parents.pop(0)
60
+ for i in range(r):
61
+ try:
62
+ target = next(nodes)
63
+ parents.append(target)
64
+ yield source, target
65
+ except StopIteration:
66
+ break
67
+
68
+
69
+ @nx._dispatchable(graphs=None, returns_graph=True)
70
+ def full_rary_tree(r, n, create_using=None):
71
+ """Creates a full r-ary tree of `n` nodes.
72
+
73
+ Sometimes called a k-ary, n-ary, or m-ary tree.
74
+ "... all non-leaf nodes have exactly r children and all levels
75
+ are full except for some rightmost position of the bottom level
76
+ (if a leaf at the bottom level is missing, then so are all of the
77
+ leaves to its right." [1]_
78
+
79
+ .. plot::
80
+
81
+ >>> nx.draw(nx.full_rary_tree(2, 10))
82
+
83
+ Parameters
84
+ ----------
85
+ r : int
86
+ branching factor of the tree
87
+ n : int
88
+ Number of nodes in the tree
89
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
90
+ Graph type to create. If graph instance, then cleared before populated.
91
+
92
+ Returns
93
+ -------
94
+ G : networkx Graph
95
+ An r-ary tree with n nodes
96
+
97
+ References
98
+ ----------
99
+ .. [1] An introduction to data structures and algorithms,
100
+ James Andrew Storer, Birkhauser Boston 2001, (page 225).
101
+ """
102
+ G = empty_graph(n, create_using)
103
+ G.add_edges_from(_tree_edges(n, r))
104
+ return G
105
+
106
+
107
+ @nx._dispatchable(graphs=None, returns_graph=True)
108
+ def kneser_graph(n, k):
109
+ """Returns the Kneser Graph with parameters `n` and `k`.
110
+
111
+ The Kneser Graph has nodes that are k-tuples (subsets) of the integers
112
+ between 0 and ``n-1``. Nodes are adjacent if their corresponding sets are disjoint.
113
+
114
+ Parameters
115
+ ----------
116
+ n: int
117
+ Number of integers from which to make node subsets.
118
+ Subsets are drawn from ``set(range(n))``.
119
+ k: int
120
+ Size of the subsets.
121
+
122
+ Returns
123
+ -------
124
+ G : NetworkX Graph
125
+
126
+ Examples
127
+ --------
128
+ >>> G = nx.kneser_graph(5, 2)
129
+ >>> G.number_of_nodes()
130
+ 10
131
+ >>> G.number_of_edges()
132
+ 15
133
+ >>> nx.is_isomorphic(G, nx.petersen_graph())
134
+ True
135
+ """
136
+ if n <= 0:
137
+ raise NetworkXError("n should be greater than zero")
138
+ if k <= 0 or k > n:
139
+ raise NetworkXError("k should be greater than zero and smaller than n")
140
+
141
+ G = nx.Graph()
142
+ # Create all k-subsets of [0, 1, ..., n-1]
143
+ subsets = list(itertools.combinations(range(n), k))
144
+
145
+ if 2 * k > n:
146
+ G.add_nodes_from(subsets)
147
+
148
+ universe = set(range(n))
149
+ comb = itertools.combinations # only to make it all fit on one line
150
+ G.add_edges_from((s, t) for s in subsets for t in comb(universe - set(s), k))
151
+ return G
152
+
153
+
154
+ @nx._dispatchable(graphs=None, returns_graph=True)
155
+ def balanced_tree(r, h, create_using=None):
156
+ """Returns the perfectly balanced `r`-ary tree of height `h`.
157
+
158
+ .. plot::
159
+
160
+ >>> nx.draw(nx.balanced_tree(2, 3))
161
+
162
+ Parameters
163
+ ----------
164
+ r : int
165
+ Branching factor of the tree; each node will have `r`
166
+ children.
167
+
168
+ h : int
169
+ Height of the tree.
170
+
171
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
172
+ Graph type to create. If graph instance, then cleared before populated.
173
+
174
+ Returns
175
+ -------
176
+ G : NetworkX graph
177
+ A balanced `r`-ary tree of height `h`.
178
+
179
+ Notes
180
+ -----
181
+ This is the rooted tree where all leaves are at distance `h` from
182
+ the root. The root has degree `r` and all other internal nodes
183
+ have degree `r + 1`.
184
+
185
+ Node labels are integers, starting from zero.
186
+
187
+ A balanced tree is also known as a *complete r-ary tree*.
188
+
189
+ """
190
+ # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
191
+ # which is computed by using the closed-form formula for a geometric
192
+ # sum with ratio `r`. In the special case that `r` is 1, the number
193
+ # of nodes is simply `h + 1` (since the tree is actually a path
194
+ # graph).
195
+ if r == 1:
196
+ n = h + 1
197
+ else:
198
+ # This must be an integer if both `r` and `h` are integers. If
199
+ # they are not, we force integer division anyway.
200
+ n = (1 - r ** (h + 1)) // (1 - r)
201
+ return full_rary_tree(r, n, create_using=create_using)
202
+
203
+
204
+ @nx._dispatchable(graphs=None, returns_graph=True)
205
+ def barbell_graph(m1, m2, create_using=None):
206
+ """Returns the Barbell Graph: two complete graphs connected by a path.
207
+
208
+ .. plot::
209
+
210
+ >>> nx.draw(nx.barbell_graph(4, 2))
211
+
212
+ Parameters
213
+ ----------
214
+ m1 : int
215
+ Size of the left and right barbells, must be greater than 2.
216
+
217
+ m2 : int
218
+ Length of the path connecting the barbells.
219
+
220
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
221
+ Graph type to create. If graph instance, then cleared before populated.
222
+ Only undirected Graphs are supported.
223
+
224
+ Returns
225
+ -------
226
+ G : NetworkX graph
227
+ A barbell graph.
228
+
229
+ Notes
230
+ -----
231
+
232
+
233
+ Two identical complete graphs $K_{m1}$ form the left and right bells,
234
+ and are connected by a path $P_{m2}$.
235
+
236
+ The `2*m1+m2` nodes are numbered
237
+ `0, ..., m1-1` for the left barbell,
238
+ `m1, ..., m1+m2-1` for the path,
239
+ and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
240
+
241
+ The 3 subgraphs are joined via the edges `(m1-1, m1)` and
242
+ `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
243
+ graphs joined together.
244
+
245
+ This graph is an extremal example in David Aldous
246
+ and Jim Fill's e-text on Random Walks on Graphs.
247
+
248
+ """
249
+ if m1 < 2:
250
+ raise NetworkXError("Invalid graph description, m1 should be >=2")
251
+ if m2 < 0:
252
+ raise NetworkXError("Invalid graph description, m2 should be >=0")
253
+
254
+ # left barbell
255
+ G = complete_graph(m1, create_using)
256
+ if G.is_directed():
257
+ raise NetworkXError("Directed Graph not supported")
258
+
259
+ # connecting path
260
+ G.add_nodes_from(range(m1, m1 + m2 - 1))
261
+ if m2 > 1:
262
+ G.add_edges_from(pairwise(range(m1, m1 + m2)))
263
+
264
+ # right barbell
265
+ G.add_edges_from(
266
+ (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
267
+ )
268
+
269
+ # connect it up
270
+ G.add_edge(m1 - 1, m1)
271
+ if m2 > 0:
272
+ G.add_edge(m1 + m2 - 1, m1 + m2)
273
+
274
+ return G
275
+
276
+
277
+ @nx._dispatchable(graphs=None, returns_graph=True)
278
+ def binomial_tree(n, create_using=None):
279
+ """Returns the Binomial Tree of order n.
280
+
281
+ The binomial tree of order 0 consists of a single node. A binomial tree of order k
282
+ is defined recursively by linking two binomial trees of order k-1: the root of one is
283
+ the leftmost child of the root of the other.
284
+
285
+ .. plot::
286
+
287
+ >>> nx.draw(nx.binomial_tree(3))
288
+
289
+ Parameters
290
+ ----------
291
+ n : int
292
+ Order of the binomial tree.
293
+
294
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
295
+ Graph type to create. If graph instance, then cleared before populated.
296
+
297
+ Returns
298
+ -------
299
+ G : NetworkX graph
300
+ A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
301
+
302
+ """
303
+ G = nx.empty_graph(1, create_using)
304
+
305
+ N = 1
306
+ for i in range(n):
307
+ # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
308
+ edges = [(u + N, v + N) for (u, v) in G.edges()]
309
+ G.add_edges_from(edges)
310
+ G.add_edge(0, N)
311
+ N *= 2
312
+ return G
313
+
314
+
315
+ @nx._dispatchable(graphs=None, returns_graph=True)
316
+ @nodes_or_number(0)
317
+ def complete_graph(n, create_using=None):
318
+ """Return the complete graph `K_n` with n nodes.
319
+
320
+ A complete graph on `n` nodes means that all pairs
321
+ of distinct nodes have an edge connecting them.
322
+
323
+ .. plot::
324
+
325
+ >>> nx.draw(nx.complete_graph(5))
326
+
327
+ Parameters
328
+ ----------
329
+ n : int or iterable container of nodes
330
+ If n is an integer, nodes are from range(n).
331
+ If n is a container of nodes, those nodes appear in the graph.
332
+ Warning: n is not checked for duplicates and if present the
333
+ resulting graph may not be as desired. Make sure you have no duplicates.
334
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
335
+ Graph type to create. If graph instance, then cleared before populated.
336
+
337
+ Examples
338
+ --------
339
+ >>> G = nx.complete_graph(9)
340
+ >>> len(G)
341
+ 9
342
+ >>> G.size()
343
+ 36
344
+ >>> G = nx.complete_graph(range(11, 14))
345
+ >>> list(G.nodes())
346
+ [11, 12, 13]
347
+ >>> G = nx.complete_graph(4, nx.DiGraph())
348
+ >>> G.is_directed()
349
+ True
350
+
351
+ """
352
+ _, nodes = n
353
+ G = empty_graph(nodes, create_using)
354
+ if len(nodes) > 1:
355
+ if G.is_directed():
356
+ edges = itertools.permutations(nodes, 2)
357
+ else:
358
+ edges = itertools.combinations(nodes, 2)
359
+ G.add_edges_from(edges)
360
+ return G
361
+
362
+
363
+ @nx._dispatchable(graphs=None, returns_graph=True)
364
+ def circular_ladder_graph(n, create_using=None):
365
+ """Returns the circular ladder graph $CL_n$ of length n.
366
+
367
+ $CL_n$ consists of two concentric n-cycles in which
368
+ each of the n pairs of concentric nodes are joined by an edge.
369
+
370
+ Node labels are the integers 0 to n-1
371
+
372
+ .. plot::
373
+
374
+ >>> nx.draw(nx.circular_ladder_graph(5))
375
+
376
+ """
377
+ G = ladder_graph(n, create_using)
378
+ G.add_edge(0, n - 1)
379
+ G.add_edge(n, 2 * n - 1)
380
+ return G
381
+
382
+
383
+ @nx._dispatchable(graphs=None, returns_graph=True)
384
+ def circulant_graph(n, offsets, create_using=None):
385
+ r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
386
+
387
+ The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
388
+ such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
389
+ for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
390
+
391
+ .. plot::
392
+
393
+ >>> nx.draw(nx.circulant_graph(10, [1]))
394
+
395
+ Parameters
396
+ ----------
397
+ n : integer
398
+ The number of nodes in the graph.
399
+ offsets : list of integers
400
+ A list of node offsets, $x_1$ up to $x_m$, as described above.
401
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
402
+ Graph type to create. If graph instance, then cleared before populated.
403
+
404
+ Returns
405
+ -------
406
+ NetworkX Graph of type create_using
407
+
408
+ Examples
409
+ --------
410
+ Many well-known graph families are subfamilies of the circulant graphs;
411
+ for example, to create the cycle graph on n points, we connect every
412
+ node to nodes on either side (with offset plus or minus one). For n = 10,
413
+
414
+ >>> G = nx.circulant_graph(10, [1])
415
+ >>> edges = [
416
+ ... (0, 9),
417
+ ... (0, 1),
418
+ ... (1, 2),
419
+ ... (2, 3),
420
+ ... (3, 4),
421
+ ... (4, 5),
422
+ ... (5, 6),
423
+ ... (6, 7),
424
+ ... (7, 8),
425
+ ... (8, 9),
426
+ ... ]
427
+ >>> sorted(edges) == sorted(G.edges())
428
+ True
429
+
430
+ Similarly, we can create the complete graph
431
+ on 5 points with the set of offsets [1, 2]:
432
+
433
+ >>> G = nx.circulant_graph(5, [1, 2])
434
+ >>> edges = [
435
+ ... (0, 1),
436
+ ... (0, 2),
437
+ ... (0, 3),
438
+ ... (0, 4),
439
+ ... (1, 2),
440
+ ... (1, 3),
441
+ ... (1, 4),
442
+ ... (2, 3),
443
+ ... (2, 4),
444
+ ... (3, 4),
445
+ ... ]
446
+ >>> sorted(edges) == sorted(G.edges())
447
+ True
448
+
449
+ """
450
+ G = empty_graph(n, create_using)
451
+ for i in range(n):
452
+ for j in offsets:
453
+ G.add_edge(i, (i - j) % n)
454
+ G.add_edge(i, (i + j) % n)
455
+ return G
456
+
457
+
458
+ @nx._dispatchable(graphs=None, returns_graph=True)
459
+ @nodes_or_number(0)
460
+ def cycle_graph(n, create_using=None):
461
+ """Returns the cycle graph $C_n$ of cyclically connected nodes.
462
+
463
+ $C_n$ is a path with its two end-nodes connected.
464
+
465
+ .. plot::
466
+
467
+ >>> nx.draw(nx.cycle_graph(5))
468
+
469
+ Parameters
470
+ ----------
471
+ n : int or iterable container of nodes
472
+ If n is an integer, nodes are from `range(n)`.
473
+ If n is a container of nodes, those nodes appear in the graph.
474
+ Warning: n is not checked for duplicates and if present the
475
+ resulting graph may not be as desired. Make sure you have no duplicates.
476
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
477
+ Graph type to create. If graph instance, then cleared before populated.
478
+
479
+ Notes
480
+ -----
481
+ If create_using is directed, the direction is in increasing order.
482
+
483
+ """
484
+ _, nodes = n
485
+ G = empty_graph(nodes, create_using)
486
+ G.add_edges_from(pairwise(nodes, cyclic=True))
487
+ return G
488
+
489
+
490
+ @nx._dispatchable(graphs=None, returns_graph=True)
491
+ def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
492
+ """Returns the hierarchically constructed Dorogovtsev--Goltsev--Mendes graph.
493
+
494
+ The Dorogovtsev--Goltsev--Mendes [1]_ procedure deterministically produces a
495
+ scale-free graph with ``3/2 * (3**(n-1) + 1)`` nodes
496
+ and ``3**n`` edges for a given `n`.
497
+
498
+ Note that `n` denotes the number of times the state transition is applied,
499
+ starting from the base graph with ``n = 0`` (no transitions), as in [2]_.
500
+ This is different from the parameter ``t = n - 1`` in [1]_.
501
+
502
+ .. plot::
503
+
504
+ >>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
505
+
506
+ Parameters
507
+ ----------
508
+ n : integer
509
+ The generation number.
510
+
511
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
512
+ Graph type to create. Directed graphs and multigraphs are not supported.
513
+
514
+ Returns
515
+ -------
516
+ G : NetworkX `Graph`
517
+
518
+ Raises
519
+ ------
520
+ NetworkXError
521
+ If `n` is less than zero.
522
+
523
+ If `create_using` is a directed graph or multigraph.
524
+
525
+ Examples
526
+ --------
527
+ >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
528
+ >>> G.number_of_nodes()
529
+ 15
530
+ >>> G.number_of_edges()
531
+ 27
532
+ >>> nx.is_planar(G)
533
+ True
534
+
535
+ References
536
+ ----------
537
+ .. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
538
+ "Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
539
+ https://arxiv.org/pdf/cond-mat/0112143.pdf
540
+ .. [2] Weisstein, Eric W. "Dorogovtsev--Goltsev--Mendes Graph".
541
+ From MathWorld--A Wolfram Web Resource.
542
+ https://mathworld.wolfram.com/Dorogovtsev-Goltsev-MendesGraph.html
543
+ """
544
+ if n < 0:
545
+ raise NetworkXError("n must be greater than or equal to 0")
546
+
547
+ G = empty_graph(0, create_using)
548
+ if G.is_directed():
549
+ raise NetworkXError("directed graph not supported")
550
+ if G.is_multigraph():
551
+ raise NetworkXError("multigraph not supported")
552
+
553
+ G.add_edge(0, 1)
554
+ new_node = 2 # next node to be added
555
+ for _ in range(n): # iterate over number of generations.
556
+ new_edges = []
557
+ for u, v in G.edges():
558
+ new_edges.append((u, new_node))
559
+ new_edges.append((v, new_node))
560
+ new_node += 1
561
+
562
+ G.add_edges_from(new_edges)
563
+ return G
564
+
565
+
566
+ @nx._dispatchable(graphs=None, returns_graph=True)
567
+ @nodes_or_number(0)
568
+ def empty_graph(n=0, create_using=None, default=Graph):
569
+ """Returns the empty graph with n nodes and zero edges.
570
+
571
+ .. plot::
572
+
573
+ >>> nx.draw(nx.empty_graph(5))
574
+
575
+ Parameters
576
+ ----------
577
+ n : int or iterable container of nodes (default = 0)
578
+ If n is an integer, nodes are from `range(n)`.
579
+ If n is a container of nodes, those nodes appear in the graph.
580
+ create_using : Graph Instance, Constructor or None
581
+ Indicator of type of graph to return.
582
+ If a Graph-type instance, then clear and use it.
583
+ If None, use the `default` constructor.
584
+ If a constructor, call it to create an empty graph.
585
+ default : Graph constructor (optional, default = nx.Graph)
586
+ The constructor to use if create_using is None.
587
+ If None, then nx.Graph is used.
588
+ This is used when passing an unknown `create_using` value
589
+ through your home-grown function to `empty_graph` and
590
+ you want a default constructor other than nx.Graph.
591
+
592
+ Examples
593
+ --------
594
+ >>> G = nx.empty_graph(10)
595
+ >>> G.number_of_nodes()
596
+ 10
597
+ >>> G.number_of_edges()
598
+ 0
599
+ >>> G = nx.empty_graph("ABC")
600
+ >>> G.number_of_nodes()
601
+ 3
602
+ >>> sorted(G)
603
+ ['A', 'B', 'C']
604
+
605
+ Notes
606
+ -----
607
+ The variable create_using should be a Graph Constructor or a
608
+ "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
609
+ will be used to create the returned graph. "graph"-like objects
610
+ will be cleared (nodes and edges will be removed) and refitted as
611
+ an empty "graph" with nodes specified in n. This capability
612
+ is useful for specifying the class-nature of the resulting empty
613
+ "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
614
+
615
+ The variable create_using has three main uses:
616
+ Firstly, the variable create_using can be used to create an
617
+ empty digraph, multigraph, etc. For example,
618
+
619
+ >>> n = 10
620
+ >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
621
+
622
+ will create an empty digraph on n nodes.
623
+
624
+ Secondly, one can pass an existing graph (digraph, multigraph,
625
+ etc.) via create_using. For example, if G is an existing graph
626
+ (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
627
+ will empty G (i.e. delete all nodes and edges using G.clear())
628
+ and then add n nodes and zero edges, and return the modified graph.
629
+
630
+ Thirdly, when constructing your home-grown graph creation function
631
+ you can use empty_graph to construct the graph by passing a user
632
+ defined create_using to empty_graph. In this case, if you want the
633
+ default constructor to be other than nx.Graph, specify `default`.
634
+
635
+ >>> def mygraph(n, create_using=None):
636
+ ... G = nx.empty_graph(n, create_using, nx.MultiGraph)
637
+ ... G.add_edges_from([(0, 1), (0, 1)])
638
+ ... return G
639
+ >>> G = mygraph(3)
640
+ >>> G.is_multigraph()
641
+ True
642
+ >>> G = mygraph(3, nx.Graph)
643
+ >>> G.is_multigraph()
644
+ False
645
+
646
+ See also create_empty_copy(G).
647
+
648
+ """
649
+ if create_using is None:
650
+ G = default()
651
+ elif isinstance(create_using, type):
652
+ G = create_using()
653
+ elif not hasattr(create_using, "adj"):
654
+ raise TypeError("create_using is not a valid NetworkX graph type or instance")
655
+ else:
656
+ # create_using is a NetworkX style Graph
657
+ create_using.clear()
658
+ G = create_using
659
+
660
+ _, nodes = n
661
+ G.add_nodes_from(nodes)
662
+ return G
663
+
664
+
665
+ @nx._dispatchable(graphs=None, returns_graph=True)
666
+ def ladder_graph(n, create_using=None):
667
+ """Returns the Ladder graph of length n.
668
+
669
+ This is two paths of n nodes, with
670
+ each pair connected by a single edge.
671
+
672
+ Node labels are the integers 0 to 2*n - 1.
673
+
674
+ .. plot::
675
+
676
+ >>> nx.draw(nx.ladder_graph(5))
677
+
678
+ """
679
+ G = empty_graph(2 * n, create_using)
680
+ if G.is_directed():
681
+ raise NetworkXError("Directed Graph not supported")
682
+ G.add_edges_from(pairwise(range(n)))
683
+ G.add_edges_from(pairwise(range(n, 2 * n)))
684
+ G.add_edges_from((v, v + n) for v in range(n))
685
+ return G
686
+
687
+
688
+ @nx._dispatchable(graphs=None, returns_graph=True)
689
+ @nodes_or_number([0, 1])
690
+ def lollipop_graph(m, n, create_using=None):
691
+ """Returns the Lollipop Graph; ``K_m`` connected to ``P_n``.
692
+
693
+ This is the Barbell Graph without the right barbell.
694
+
695
+ .. plot::
696
+
697
+ >>> nx.draw(nx.lollipop_graph(3, 4))
698
+
699
+ Parameters
700
+ ----------
701
+ m, n : int or iterable container of nodes
702
+ If an integer, nodes are from ``range(m)`` and ``range(m, m+n)``.
703
+ If a container of nodes, those nodes appear in the graph.
704
+ Warning: `m` and `n` are not checked for duplicates and if present the
705
+ resulting graph may not be as desired. Make sure you have no duplicates.
706
+
707
+ The nodes for `m` appear in the complete graph $K_m$ and the nodes
708
+ for `n` appear in the path $P_n$
709
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
710
+ Graph type to create. If graph instance, then cleared before populated.
711
+
712
+ Returns
713
+ -------
714
+ Networkx graph
715
+ A complete graph with `m` nodes connected to a path of length `n`.
716
+
717
+ Notes
718
+ -----
719
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
720
+ If ``n=0``, this is merely a complete graph.
721
+
722
+ (This graph is an extremal example in David Aldous and Jim
723
+ Fill's etext on Random Walks on Graphs.)
724
+
725
+ """
726
+ m, m_nodes = m
727
+ M = len(m_nodes)
728
+ if M < 2:
729
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
730
+
731
+ n, n_nodes = n
732
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
733
+ n_nodes = list(range(M, M + n))
734
+ N = len(n_nodes)
735
+
736
+ # the ball
737
+ G = complete_graph(m_nodes, create_using)
738
+ if G.is_directed():
739
+ raise NetworkXError("Directed Graph not supported")
740
+
741
+ # the stick
742
+ G.add_nodes_from(n_nodes)
743
+ if N > 1:
744
+ G.add_edges_from(pairwise(n_nodes))
745
+
746
+ if len(G) != M + N:
747
+ raise NetworkXError("Nodes must be distinct in containers m and n")
748
+
749
+ # connect ball to stick
750
+ if M > 0 and N > 0:
751
+ G.add_edge(m_nodes[-1], n_nodes[0])
752
+ return G
753
+
754
+
755
+ @nx._dispatchable(graphs=None, returns_graph=True)
756
+ def null_graph(create_using=None):
757
+ """Returns the Null graph with no nodes or edges.
758
+
759
+ See empty_graph for the use of create_using.
760
+
761
+ """
762
+ G = empty_graph(0, create_using)
763
+ return G
764
+
765
+
766
+ @nx._dispatchable(graphs=None, returns_graph=True)
767
+ @nodes_or_number(0)
768
+ def path_graph(n, create_using=None):
769
+ """Returns the Path graph `P_n` of linearly connected nodes.
770
+
771
+ .. plot::
772
+
773
+ >>> nx.draw(nx.path_graph(5))
774
+
775
+ Parameters
776
+ ----------
777
+ n : int or iterable
778
+ If an integer, nodes are 0 to n - 1.
779
+ If an iterable of nodes, in the order they appear in the path.
780
+ Warning: n is not checked for duplicates and if present the
781
+ resulting graph may not be as desired. Make sure you have no duplicates.
782
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
783
+ Graph type to create. If graph instance, then cleared before populated.
784
+
785
+ """
786
+ _, nodes = n
787
+ G = empty_graph(nodes, create_using)
788
+ G.add_edges_from(pairwise(nodes))
789
+ return G
790
+
791
+
792
+ @nx._dispatchable(graphs=None, returns_graph=True)
793
+ @nodes_or_number(0)
794
+ def star_graph(n, create_using=None):
795
+ """Return the star graph
796
+
797
+ The star graph consists of one center node connected to n outer nodes.
798
+
799
+ .. plot::
800
+
801
+ >>> nx.draw(nx.star_graph(6))
802
+
803
+ Parameters
804
+ ----------
805
+ n : int or iterable
806
+ If an integer, node labels are 0 to n with center 0.
807
+ If an iterable of nodes, the center is the first.
808
+ Warning: n is not checked for duplicates and if present the
809
+ resulting graph may not be as desired. Make sure you have no duplicates.
810
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
811
+ Graph type to create. If graph instance, then cleared before populated.
812
+
813
+ Notes
814
+ -----
815
+ The graph has n+1 nodes for integer n.
816
+ So star_graph(3) is the same as star_graph(range(4)).
817
+ """
818
+ n, nodes = n
819
+ if isinstance(n, numbers.Integral):
820
+ nodes.append(int(n)) # there should be n+1 nodes
821
+ G = empty_graph(nodes, create_using)
822
+ if G.is_directed():
823
+ raise NetworkXError("Directed Graph not supported")
824
+
825
+ if len(nodes) > 1:
826
+ hub, *spokes = nodes
827
+ G.add_edges_from((hub, node) for node in spokes)
828
+ return G
829
+
830
+
831
+ @nx._dispatchable(graphs=None, returns_graph=True)
832
+ @nodes_or_number([0, 1])
833
+ def tadpole_graph(m, n, create_using=None):
834
+ """Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``.
835
+
836
+ This graph on m+n nodes connects a cycle of size `m` to a path of length `n`.
837
+ It looks like a tadpole. It is also called a kite graph or a dragon graph.
838
+
839
+ .. plot::
840
+
841
+ >>> nx.draw(nx.tadpole_graph(3, 5))
842
+
843
+ Parameters
844
+ ----------
845
+ m, n : int or iterable container of nodes
846
+ If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``.
847
+ If a container of nodes, those nodes appear in the graph.
848
+ Warning: `m` and `n` are not checked for duplicates and if present the
849
+ resulting graph may not be as desired.
850
+
851
+ The nodes for `m` appear in the cycle graph $C_m$ and the nodes
852
+ for `n` appear in the path $P_n$.
853
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
854
+ Graph type to create. If graph instance, then cleared before populated.
855
+
856
+ Returns
857
+ -------
858
+ Networkx graph
859
+ A cycle of size `m` connected to a path of length `n`.
860
+
861
+ Raises
862
+ ------
863
+ NetworkXError
864
+ If ``m < 2``. The tadpole graph is undefined for ``m<2``.
865
+
866
+ Notes
867
+ -----
868
+ The 2 subgraphs are joined via an edge ``(m-1, m)``.
869
+ If ``n=0``, this is a cycle graph.
870
+ `m` and/or `n` can be a container of nodes instead of an integer.
871
+
872
+ """
873
+ m, m_nodes = m
874
+ M = len(m_nodes)
875
+ if M < 2:
876
+ raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
877
+
878
+ n, n_nodes = n
879
+ if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
880
+ n_nodes = list(range(M, M + n))
881
+
882
+ # the circle
883
+ G = cycle_graph(m_nodes, create_using)
884
+ if G.is_directed():
885
+ raise NetworkXError("Directed Graph not supported")
886
+
887
+ # the stick
888
+ nx.add_path(G, [m_nodes[-1]] + list(n_nodes))
889
+
890
+ return G
891
+
892
+
893
+ @nx._dispatchable(graphs=None, returns_graph=True)
894
+ def trivial_graph(create_using=None):
895
+ """Return the Trivial graph with one node (with label 0) and no edges.
896
+
897
+ .. plot::
898
+
899
+ >>> nx.draw(nx.trivial_graph(), with_labels=True)
900
+
901
+ """
902
+ G = empty_graph(1, create_using)
903
+ return G
904
+
905
+
906
+ @nx._dispatchable(graphs=None, returns_graph=True)
907
+ def turan_graph(n, r):
908
+ r"""Return the Turan Graph
909
+
910
+ The Turan Graph is a complete multipartite graph on $n$ nodes
911
+ with $r$ disjoint subsets. That is, edges connect each node to
912
+ every node not in its subset.
913
+
914
+ Given $n$ and $r$, we create a complete multipartite graph with
915
+ $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
916
+ $n \mod r$ partitions of size $n/r+1$, rounded down.
917
+
918
+ .. plot::
919
+
920
+ >>> nx.draw(nx.turan_graph(6, 2))
921
+
922
+ Parameters
923
+ ----------
924
+ n : int
925
+ The number of nodes.
926
+ r : int
927
+ The number of partitions.
928
+ Must be less than or equal to n.
929
+
930
+ Notes
931
+ -----
932
+ Must satisfy $1 <= r <= n$.
933
+ The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
934
+ """
935
+
936
+ if not 1 <= r <= n:
937
+ raise NetworkXError("Must satisfy 1 <= r <= n")
938
+
939
+ partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
940
+ G = complete_multipartite_graph(*partitions)
941
+ return G
942
+
943
+
944
+ @nx._dispatchable(graphs=None, returns_graph=True)
945
+ @nodes_or_number(0)
946
+ def wheel_graph(n, create_using=None):
947
+ """Return the wheel graph
948
+
949
+ The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
950
+
951
+ .. plot::
952
+
953
+ >>> nx.draw(nx.wheel_graph(5))
954
+
955
+ Parameters
956
+ ----------
957
+ n : int or iterable
958
+ If an integer, node labels are 0 to n with center 0.
959
+ If an iterable of nodes, the center is the first.
960
+ Warning: n is not checked for duplicates and if present the
961
+ resulting graph may not be as desired. Make sure you have no duplicates.
962
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
963
+ Graph type to create. If graph instance, then cleared before populated.
964
+
965
+ Node labels are the integers 0 to n - 1.
966
+ """
967
+ _, nodes = n
968
+ G = empty_graph(nodes, create_using)
969
+ if G.is_directed():
970
+ raise NetworkXError("Directed Graph not supported")
971
+
972
+ if len(nodes) > 1:
973
+ hub, *rim = nodes
974
+ G.add_edges_from((hub, node) for node in rim)
975
+ if len(rim) > 1:
976
+ G.add_edges_from(pairwise(rim, cyclic=True))
977
+ return G
978
+
979
+
980
+ @nx._dispatchable(graphs=None, returns_graph=True)
981
+ def complete_multipartite_graph(*subset_sizes):
982
+ """Returns the complete multipartite graph with the specified subset sizes.
983
+
984
+ .. plot::
985
+
986
+ >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3))
987
+
988
+ Parameters
989
+ ----------
990
+ subset_sizes : tuple of integers or tuple of node iterables
991
+ The arguments can either all be integer number of nodes or they
992
+ can all be iterables of nodes. If integers, they represent the
993
+ number of nodes in each subset of the multipartite graph.
994
+ If iterables, each is used to create the nodes for that subset.
995
+ The length of subset_sizes is the number of subsets.
996
+
997
+ Returns
998
+ -------
999
+ G : NetworkX Graph
1000
+ Returns the complete multipartite graph with the specified subsets.
1001
+
1002
+ For each node, the node attribute 'subset' is an integer
1003
+ indicating which subset contains the node.
1004
+
1005
+ Examples
1006
+ --------
1007
+ Creating a complete tripartite graph, with subsets of one, two, and three
1008
+ nodes, respectively.
1009
+
1010
+ >>> G = nx.complete_multipartite_graph(1, 2, 3)
1011
+ >>> [G.nodes[u]["subset"] for u in G]
1012
+ [0, 1, 1, 2, 2, 2]
1013
+ >>> list(G.edges(0))
1014
+ [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
1015
+ >>> list(G.edges(2))
1016
+ [(2, 0), (2, 3), (2, 4), (2, 5)]
1017
+ >>> list(G.edges(4))
1018
+ [(4, 0), (4, 1), (4, 2)]
1019
+
1020
+ >>> G = nx.complete_multipartite_graph("a", "bc", "def")
1021
+ >>> [G.nodes[u]["subset"] for u in sorted(G)]
1022
+ [0, 1, 1, 2, 2, 2]
1023
+
1024
+ Notes
1025
+ -----
1026
+ This function generalizes several other graph builder functions.
1027
+
1028
+ - If no subset sizes are given, this returns the null graph.
1029
+ - If a single subset size `n` is given, this returns the empty graph on
1030
+ `n` nodes.
1031
+ - If two subset sizes `m` and `n` are given, this returns the complete
1032
+ bipartite graph on `m + n` nodes.
1033
+ - If subset sizes `1` and `n` are given, this returns the star graph on
1034
+ `n + 1` nodes.
1035
+
1036
+ See also
1037
+ --------
1038
+ complete_bipartite_graph
1039
+ """
1040
+ # The complete multipartite graph is an undirected simple graph.
1041
+ G = Graph()
1042
+
1043
+ if len(subset_sizes) == 0:
1044
+ return G
1045
+
1046
+ # set up subsets of nodes
1047
+ try:
1048
+ extents = pairwise(itertools.accumulate((0,) + subset_sizes))
1049
+ subsets = [range(start, end) for start, end in extents]
1050
+ except TypeError:
1051
+ subsets = subset_sizes
1052
+ else:
1053
+ if any(size < 0 for size in subset_sizes):
1054
+ raise NetworkXError(f"Negative number of nodes not valid: {subset_sizes}")
1055
+
1056
+ # add nodes with subset attribute
1057
+ # while checking that ints are not mixed with iterables
1058
+ try:
1059
+ for i, subset in enumerate(subsets):
1060
+ G.add_nodes_from(subset, subset=i)
1061
+ except TypeError as err:
1062
+ raise NetworkXError("Arguments must be all ints or all iterables") from err
1063
+
1064
+ # Across subsets, all nodes should be adjacent.
1065
+ # We can use itertools.combinations() because undirected.
1066
+ for subset1, subset2 in itertools.combinations(subsets, 2):
1067
+ G.add_edges_from(itertools.product(subset1, subset2))
1068
+ return G
wemm/lib/python3.10/site-packages/networkx/generators/degree_seq.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given degree sequence or expected degree sequence."""
2
+
3
+ import heapq
4
+ import math
5
+ from itertools import chain, combinations, zip_longest
6
+ from operator import itemgetter
7
+
8
+ import networkx as nx
9
+ from networkx.utils import py_random_state, random_weighted_sample
10
+
11
+ __all__ = [
12
+ "configuration_model",
13
+ "directed_configuration_model",
14
+ "expected_degree_graph",
15
+ "havel_hakimi_graph",
16
+ "directed_havel_hakimi_graph",
17
+ "degree_sequence_tree",
18
+ "random_degree_sequence_graph",
19
+ ]
20
+
21
+ chaini = chain.from_iterable
22
+
23
+
24
+ def _to_stublist(degree_sequence):
25
+ """Returns a list of degree-repeated node numbers.
26
+
27
+ ``degree_sequence`` is a list of nonnegative integers representing
28
+ the degrees of nodes in a graph.
29
+
30
+ This function returns a list of node numbers with multiplicities
31
+ according to the given degree sequence. For example, if the first
32
+ element of ``degree_sequence`` is ``3``, then the first node number,
33
+ ``0``, will appear at the head of the returned list three times. The
34
+ node numbers are assumed to be the numbers zero through
35
+ ``len(degree_sequence) - 1``.
36
+
37
+ Examples
38
+ --------
39
+
40
+ >>> degree_sequence = [1, 2, 3]
41
+ >>> _to_stublist(degree_sequence)
42
+ [0, 1, 1, 2, 2, 2]
43
+
44
+ If a zero appears in the sequence, that means the node exists but
45
+ has degree zero, so that number will be skipped in the returned
46
+ list::
47
+
48
+ >>> degree_sequence = [2, 0, 1]
49
+ >>> _to_stublist(degree_sequence)
50
+ [0, 0, 2]
51
+
52
+ """
53
+ return list(chaini([n] * d for n, d in enumerate(degree_sequence)))
54
+
55
+
56
+ def _configuration_model(
57
+ deg_sequence, create_using, directed=False, in_deg_sequence=None, seed=None
58
+ ):
59
+ """Helper function for generating either undirected or directed
60
+ configuration model graphs.
61
+
62
+ ``deg_sequence`` is a list of nonnegative integers representing the
63
+ degree of the node whose label is the index of the list element.
64
+
65
+ ``create_using`` see :func:`~networkx.empty_graph`.
66
+
67
+ ``directed`` and ``in_deg_sequence`` are required if you want the
68
+ returned graph to be generated using the directed configuration
69
+ model algorithm. If ``directed`` is ``False``, then ``deg_sequence``
70
+ is interpreted as the degree sequence of an undirected graph and
71
+ ``in_deg_sequence`` is ignored. Otherwise, if ``directed`` is
72
+ ``True``, then ``deg_sequence`` is interpreted as the out-degree
73
+ sequence and ``in_deg_sequence`` as the in-degree sequence of a
74
+ directed graph.
75
+
76
+ .. note::
77
+
78
+ ``deg_sequence`` and ``in_deg_sequence`` need not be the same
79
+ length.
80
+
81
+ ``seed`` is a random.Random or numpy.random.RandomState instance
82
+
83
+ This function returns a graph, directed if and only if ``directed``
84
+ is ``True``, generated according to the configuration model
85
+ algorithm. For more information on the algorithm, see the
86
+ :func:`configuration_model` or :func:`directed_configuration_model`
87
+ functions.
88
+
89
+ """
90
+ n = len(deg_sequence)
91
+ G = nx.empty_graph(n, create_using)
92
+ # If empty, return the null graph immediately.
93
+ if n == 0:
94
+ return G
95
+ # Build a list of available degree-repeated nodes. For example,
96
+ # for degree sequence [3, 2, 1, 1, 1], the "stub list" is
97
+ # initially [0, 0, 0, 1, 1, 2, 3, 4], that is, node 0 has degree
98
+ # 3 and thus is repeated 3 times, etc.
99
+ #
100
+ # Also, shuffle the stub list in order to get a random sequence of
101
+ # node pairs.
102
+ if directed:
103
+ pairs = zip_longest(deg_sequence, in_deg_sequence, fillvalue=0)
104
+ # Unzip the list of pairs into a pair of lists.
105
+ out_deg, in_deg = zip(*pairs)
106
+
107
+ out_stublist = _to_stublist(out_deg)
108
+ in_stublist = _to_stublist(in_deg)
109
+
110
+ seed.shuffle(out_stublist)
111
+ seed.shuffle(in_stublist)
112
+ else:
113
+ stublist = _to_stublist(deg_sequence)
114
+ # Choose a random balanced bipartition of the stublist, which
115
+ # gives a random pairing of nodes. In this implementation, we
116
+ # shuffle the list and then split it in half.
117
+ n = len(stublist)
118
+ half = n // 2
119
+ seed.shuffle(stublist)
120
+ out_stublist, in_stublist = stublist[:half], stublist[half:]
121
+ G.add_edges_from(zip(out_stublist, in_stublist))
122
+ return G
123
+
124
+
125
+ @py_random_state(2)
126
+ @nx._dispatchable(graphs=None, returns_graph=True)
127
+ def configuration_model(deg_sequence, create_using=None, seed=None):
128
+ """Returns a random graph with the given degree sequence.
129
+
130
+ The configuration model generates a random pseudograph (graph with
131
+ parallel edges and self loops) by randomly assigning edges to
132
+ match the given degree sequence.
133
+
134
+ Parameters
135
+ ----------
136
+ deg_sequence : list of nonnegative integers
137
+ Each list entry corresponds to the degree of a node.
138
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
139
+ Graph type to create. If graph instance, then cleared before populated.
140
+ seed : integer, random_state, or None (default)
141
+ Indicator of random number generation state.
142
+ See :ref:`Randomness<randomness>`.
143
+
144
+ Returns
145
+ -------
146
+ G : MultiGraph
147
+ A graph with the specified degree sequence.
148
+ Nodes are labeled starting at 0 with an index
149
+ corresponding to the position in deg_sequence.
150
+
151
+ Raises
152
+ ------
153
+ NetworkXError
154
+ If the degree sequence does not have an even sum.
155
+
156
+ See Also
157
+ --------
158
+ is_graphical
159
+
160
+ Notes
161
+ -----
162
+ As described by Newman [1]_.
163
+
164
+ A non-graphical degree sequence (not realizable by some simple
165
+ graph) is allowed since this function returns graphs with self
166
+ loops and parallel edges. An exception is raised if the degree
167
+ sequence does not have an even sum.
168
+
169
+ This configuration model construction process can lead to
170
+ duplicate edges and loops. You can remove the self-loops and
171
+ parallel edges (see below) which will likely result in a graph
172
+ that doesn't have the exact degree sequence specified.
173
+
174
+ The density of self-loops and parallel edges tends to decrease as
175
+ the number of nodes increases. However, typically the number of
176
+ self-loops will approach a Poisson distribution with a nonzero mean,
177
+ and similarly for the number of parallel edges. Consider a node
178
+ with *k* stubs. The probability of being joined to another stub of
179
+ the same node is basically (*k* - *1*) / *N*, where *k* is the
180
+ degree and *N* is the number of nodes. So the probability of a
181
+ self-loop scales like *c* / *N* for some constant *c*. As *N* grows,
182
+ this means we expect *c* self-loops. Similarly for parallel edges.
183
+
184
+ References
185
+ ----------
186
+ .. [1] M.E.J. Newman, "The structure and function of complex networks",
187
+ SIAM REVIEW 45-2, pp 167-256, 2003.
188
+
189
+ Examples
190
+ --------
191
+ You can create a degree sequence following a particular distribution
192
+ by using the one of the distribution functions in
193
+ :mod:`~networkx.utils.random_sequence` (or one of your own). For
194
+ example, to create an undirected multigraph on one hundred nodes
195
+ with degree sequence chosen from the power law distribution:
196
+
197
+ >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000)
198
+ >>> G = nx.configuration_model(sequence)
199
+ >>> len(G)
200
+ 100
201
+ >>> actual_degrees = [d for v, d in G.degree()]
202
+ >>> actual_degrees == sequence
203
+ True
204
+
205
+ The returned graph is a multigraph, which may have parallel
206
+ edges. To remove any parallel edges from the returned graph:
207
+
208
+ >>> G = nx.Graph(G)
209
+
210
+ Similarly, to remove self-loops:
211
+
212
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
213
+
214
+ """
215
+ if sum(deg_sequence) % 2 != 0:
216
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
217
+ raise nx.NetworkXError(msg)
218
+
219
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
220
+ if G.is_directed():
221
+ raise nx.NetworkXNotImplemented("not implemented for directed graphs")
222
+
223
+ G = _configuration_model(deg_sequence, G, seed=seed)
224
+
225
+ return G
226
+
227
+
228
+ @py_random_state(3)
229
+ @nx._dispatchable(graphs=None, returns_graph=True)
230
+ def directed_configuration_model(
231
+ in_degree_sequence, out_degree_sequence, create_using=None, seed=None
232
+ ):
233
+ """Returns a directed_random graph with the given degree sequences.
234
+
235
+ The configuration model generates a random directed pseudograph
236
+ (graph with parallel edges and self loops) by randomly assigning
237
+ edges to match the given degree sequences.
238
+
239
+ Parameters
240
+ ----------
241
+ in_degree_sequence : list of nonnegative integers
242
+ Each list entry corresponds to the in-degree of a node.
243
+ out_degree_sequence : list of nonnegative integers
244
+ Each list entry corresponds to the out-degree of a node.
245
+ create_using : NetworkX graph constructor, optional (default MultiDiGraph)
246
+ Graph type to create. If graph instance, then cleared before populated.
247
+ seed : integer, random_state, or None (default)
248
+ Indicator of random number generation state.
249
+ See :ref:`Randomness<randomness>`.
250
+
251
+ Returns
252
+ -------
253
+ G : MultiDiGraph
254
+ A graph with the specified degree sequences.
255
+ Nodes are labeled starting at 0 with an index
256
+ corresponding to the position in deg_sequence.
257
+
258
+ Raises
259
+ ------
260
+ NetworkXError
261
+ If the degree sequences do not have the same sum.
262
+
263
+ See Also
264
+ --------
265
+ configuration_model
266
+
267
+ Notes
268
+ -----
269
+ Algorithm as described by Newman [1]_.
270
+
271
+ A non-graphical degree sequence (not realizable by some simple
272
+ graph) is allowed since this function returns graphs with self
273
+ loops and parallel edges. An exception is raised if the degree
274
+ sequences does not have the same sum.
275
+
276
+ This configuration model construction process can lead to
277
+ duplicate edges and loops. You can remove the self-loops and
278
+ parallel edges (see below) which will likely result in a graph
279
+ that doesn't have the exact degree sequence specified. This
280
+ "finite-size effect" decreases as the size of the graph increases.
281
+
282
+ References
283
+ ----------
284
+ .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
285
+ Random graphs with arbitrary degree distributions and their applications
286
+ Phys. Rev. E, 64, 026118 (2001)
287
+
288
+ Examples
289
+ --------
290
+ One can modify the in- and out-degree sequences from an existing
291
+ directed graph in order to create a new directed graph. For example,
292
+ here we modify the directed path graph:
293
+
294
+ >>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
295
+ >>> din = list(d for n, d in D.in_degree())
296
+ >>> dout = list(d for n, d in D.out_degree())
297
+ >>> din.append(1)
298
+ >>> dout[0] = 2
299
+ >>> # We now expect an edge from node 0 to a new node, node 3.
300
+ ... D = nx.directed_configuration_model(din, dout)
301
+
302
+ The returned graph is a directed multigraph, which may have parallel
303
+ edges. To remove any parallel edges from the returned graph:
304
+
305
+ >>> D = nx.DiGraph(D)
306
+
307
+ Similarly, to remove self-loops:
308
+
309
+ >>> D.remove_edges_from(nx.selfloop_edges(D))
310
+
311
+ """
312
+ if sum(in_degree_sequence) != sum(out_degree_sequence):
313
+ msg = "Invalid degree sequences: sequences must have equal sums"
314
+ raise nx.NetworkXError(msg)
315
+
316
+ if create_using is None:
317
+ create_using = nx.MultiDiGraph
318
+
319
+ G = _configuration_model(
320
+ out_degree_sequence,
321
+ create_using,
322
+ directed=True,
323
+ in_deg_sequence=in_degree_sequence,
324
+ seed=seed,
325
+ )
326
+
327
+ name = "directed configuration_model {} nodes {} edges"
328
+ return G
329
+
330
+
331
+ @py_random_state(1)
332
+ @nx._dispatchable(graphs=None, returns_graph=True)
333
+ def expected_degree_graph(w, seed=None, selfloops=True):
334
+ r"""Returns a random graph with given expected degrees.
335
+
336
+ Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$
337
+ of length $n$ this algorithm assigns an edge between node $u$ and
338
+ node $v$ with probability
339
+
340
+ .. math::
341
+
342
+ p_{uv} = \frac{w_u w_v}{\sum_k w_k} .
343
+
344
+ Parameters
345
+ ----------
346
+ w : list
347
+ The list of expected degrees.
348
+ selfloops: bool (default=True)
349
+ Set to False to remove the possibility of self-loop edges.
350
+ seed : integer, random_state, or None (default)
351
+ Indicator of random number generation state.
352
+ See :ref:`Randomness<randomness>`.
353
+
354
+ Returns
355
+ -------
356
+ Graph
357
+
358
+ Examples
359
+ --------
360
+ >>> z = [10 for i in range(100)]
361
+ >>> G = nx.expected_degree_graph(z)
362
+
363
+ Notes
364
+ -----
365
+ The nodes have integer labels corresponding to index of expected degrees
366
+ input sequence.
367
+
368
+ The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the
369
+ number of nodes and $m$ is the expected number of edges.
370
+
371
+ The model in [1]_ includes the possibility of self-loop edges.
372
+ Set selfloops=False to produce a graph without self loops.
373
+
374
+ For finite graphs this model doesn't produce exactly the given
375
+ expected degree sequence. Instead the expected degrees are as
376
+ follows.
377
+
378
+ For the case without self loops (selfloops=False),
379
+
380
+ .. math::
381
+
382
+ E[deg(u)] = \sum_{v \ne u} p_{uv}
383
+ = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .
384
+
385
+
386
+ NetworkX uses the standard convention that a self-loop edge counts 2
387
+ in the degree of a node, so with self loops (selfloops=True),
388
+
389
+ .. math::
390
+
391
+ E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}
392
+ = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .
393
+
394
+ References
395
+ ----------
396
+ .. [1] Fan Chung and L. Lu, Connected components in random graphs with
397
+ given expected degree sequences, Ann. Combinatorics, 6,
398
+ pp. 125-145, 2002.
399
+ .. [2] Joel Miller and Aric Hagberg,
400
+ Efficient generation of networks with given expected degrees,
401
+ in Algorithms and Models for the Web-Graph (WAW 2011),
402
+ Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
403
+ pp. 115-126, 2011.
404
+ """
405
+ n = len(w)
406
+ G = nx.empty_graph(n)
407
+
408
+ # If there are no nodes are no edges in the graph, return the empty graph.
409
+ if n == 0 or max(w) == 0:
410
+ return G
411
+
412
+ rho = 1 / sum(w)
413
+ # Sort the weights in decreasing order. The original order of the
414
+ # weights dictates the order of the (integer) node labels, so we
415
+ # need to remember the permutation applied in the sorting.
416
+ order = sorted(enumerate(w), key=itemgetter(1), reverse=True)
417
+ mapping = {c: u for c, (u, v) in enumerate(order)}
418
+ seq = [v for u, v in order]
419
+ last = n
420
+ if not selfloops:
421
+ last -= 1
422
+ for u in range(last):
423
+ v = u
424
+ if not selfloops:
425
+ v += 1
426
+ factor = seq[u] * rho
427
+ p = min(seq[v] * factor, 1)
428
+ while v < n and p > 0:
429
+ if p != 1:
430
+ r = seed.random()
431
+ v += math.floor(math.log(r, 1 - p))
432
+ if v < n:
433
+ q = min(seq[v] * factor, 1)
434
+ if seed.random() < q / p:
435
+ G.add_edge(mapping[u], mapping[v])
436
+ v += 1
437
+ p = q
438
+ return G
439
+
440
+
441
+ @nx._dispatchable(graphs=None, returns_graph=True)
442
+ def havel_hakimi_graph(deg_sequence, create_using=None):
443
+ """Returns a simple graph with given degree sequence constructed
444
+ using the Havel-Hakimi algorithm.
445
+
446
+ Parameters
447
+ ----------
448
+ deg_sequence: list of integers
449
+ Each integer corresponds to the degree of a node (need not be sorted).
450
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
451
+ Graph type to create. If graph instance, then cleared before populated.
452
+ Directed graphs are not allowed.
453
+
454
+ Raises
455
+ ------
456
+ NetworkXException
457
+ For a non-graphical degree sequence (i.e. one
458
+ not realizable by some simple graph).
459
+
460
+ Notes
461
+ -----
462
+ The Havel-Hakimi algorithm constructs a simple graph by
463
+ successively connecting the node of highest degree to other nodes
464
+ of highest degree, resorting remaining nodes by degree, and
465
+ repeating the process. The resulting graph has a high
466
+ degree-associativity. Nodes are labeled 1,.., len(deg_sequence),
467
+ corresponding to their position in deg_sequence.
468
+
469
+ The basic algorithm is from Hakimi [1]_ and was generalized by
470
+ Kleitman and Wang [2]_.
471
+
472
+ References
473
+ ----------
474
+ .. [1] Hakimi S., On Realizability of a Set of Integers as
475
+ Degrees of the Vertices of a Linear Graph. I,
476
+ Journal of SIAM, 10(3), pp. 496-506 (1962)
477
+ .. [2] Kleitman D.J. and Wang D.L.
478
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
479
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
480
+ """
481
+ if not nx.is_graphical(deg_sequence):
482
+ raise nx.NetworkXError("Invalid degree sequence")
483
+
484
+ p = len(deg_sequence)
485
+ G = nx.empty_graph(p, create_using)
486
+ if G.is_directed():
487
+ raise nx.NetworkXError("Directed graphs are not supported")
488
+ num_degs = [[] for i in range(p)]
489
+ dmax, dsum, n = 0, 0, 0
490
+ for d in deg_sequence:
491
+ # Process only the non-zero integers
492
+ if d > 0:
493
+ num_degs[d].append(n)
494
+ dmax, dsum, n = max(dmax, d), dsum + d, n + 1
495
+ # Return graph if no edges
496
+ if n == 0:
497
+ return G
498
+
499
+ modstubs = [(0, 0)] * (dmax + 1)
500
+ # Successively reduce degree sequence by removing the maximum degree
501
+ while n > 0:
502
+ # Retrieve the maximum degree in the sequence
503
+ while len(num_degs[dmax]) == 0:
504
+ dmax -= 1
505
+ # If there are not enough stubs to connect to, then the sequence is
506
+ # not graphical
507
+ if dmax > n - 1:
508
+ raise nx.NetworkXError("Non-graphical integer sequence")
509
+
510
+ # Remove largest stub in list
511
+ source = num_degs[dmax].pop()
512
+ n -= 1
513
+ # Reduce the next dmax largest stubs
514
+ mslen = 0
515
+ k = dmax
516
+ for i in range(dmax):
517
+ while len(num_degs[k]) == 0:
518
+ k -= 1
519
+ target = num_degs[k].pop()
520
+ G.add_edge(source, target)
521
+ n -= 1
522
+ if k > 1:
523
+ modstubs[mslen] = (k - 1, target)
524
+ mslen += 1
525
+ # Add back to the list any nonzero stubs that were removed
526
+ for i in range(mslen):
527
+ (stubval, stubtarget) = modstubs[i]
528
+ num_degs[stubval].append(stubtarget)
529
+ n += 1
530
+
531
+ return G
532
+
533
+
534
+ @nx._dispatchable(graphs=None, returns_graph=True)
535
+ def directed_havel_hakimi_graph(in_deg_sequence, out_deg_sequence, create_using=None):
536
+ """Returns a directed graph with the given degree sequences.
537
+
538
+ Parameters
539
+ ----------
540
+ in_deg_sequence : list of integers
541
+ Each list entry corresponds to the in-degree of a node.
542
+ out_deg_sequence : list of integers
543
+ Each list entry corresponds to the out-degree of a node.
544
+ create_using : NetworkX graph constructor, optional (default DiGraph)
545
+ Graph type to create. If graph instance, then cleared before populated.
546
+
547
+ Returns
548
+ -------
549
+ G : DiGraph
550
+ A graph with the specified degree sequences.
551
+ Nodes are labeled starting at 0 with an index
552
+ corresponding to the position in deg_sequence
553
+
554
+ Raises
555
+ ------
556
+ NetworkXError
557
+ If the degree sequences are not digraphical.
558
+
559
+ See Also
560
+ --------
561
+ configuration_model
562
+
563
+ Notes
564
+ -----
565
+ Algorithm as described by Kleitman and Wang [1]_.
566
+
567
+ References
568
+ ----------
569
+ .. [1] D.J. Kleitman and D.L. Wang
570
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
571
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
572
+ """
573
+ in_deg_sequence = nx.utils.make_list_of_ints(in_deg_sequence)
574
+ out_deg_sequence = nx.utils.make_list_of_ints(out_deg_sequence)
575
+
576
+ # Process the sequences and form two heaps to store degree pairs with
577
+ # either zero or nonzero out degrees
578
+ sumin, sumout = 0, 0
579
+ nin, nout = len(in_deg_sequence), len(out_deg_sequence)
580
+ maxn = max(nin, nout)
581
+ G = nx.empty_graph(maxn, create_using, default=nx.DiGraph)
582
+ if maxn == 0:
583
+ return G
584
+ maxin = 0
585
+ stubheap, zeroheap = [], []
586
+ for n in range(maxn):
587
+ in_deg, out_deg = 0, 0
588
+ if n < nout:
589
+ out_deg = out_deg_sequence[n]
590
+ if n < nin:
591
+ in_deg = in_deg_sequence[n]
592
+ if in_deg < 0 or out_deg < 0:
593
+ raise nx.NetworkXError(
594
+ "Invalid degree sequences. Sequence values must be positive."
595
+ )
596
+ sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
597
+ if in_deg > 0:
598
+ stubheap.append((-1 * out_deg, -1 * in_deg, n))
599
+ elif out_deg > 0:
600
+ zeroheap.append((-1 * out_deg, n))
601
+ if sumin != sumout:
602
+ raise nx.NetworkXError(
603
+ "Invalid degree sequences. Sequences must have equal sums."
604
+ )
605
+ heapq.heapify(stubheap)
606
+ heapq.heapify(zeroheap)
607
+
608
+ modstubs = [(0, 0, 0)] * (maxin + 1)
609
+ # Successively reduce degree sequence by removing the maximum
610
+ while stubheap:
611
+ # Remove first value in the sequence with a non-zero in degree
612
+ (freeout, freein, target) = heapq.heappop(stubheap)
613
+ freein *= -1
614
+ if freein > len(stubheap) + len(zeroheap):
615
+ raise nx.NetworkXError("Non-digraphical integer sequence")
616
+
617
+ # Attach arcs from the nodes with the most stubs
618
+ mslen = 0
619
+ for i in range(freein):
620
+ if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]):
621
+ (stubout, stubsource) = heapq.heappop(zeroheap)
622
+ stubin = 0
623
+ else:
624
+ (stubout, stubin, stubsource) = heapq.heappop(stubheap)
625
+ if stubout == 0:
626
+ raise nx.NetworkXError("Non-digraphical integer sequence")
627
+ G.add_edge(stubsource, target)
628
+ # Check if source is now totally connected
629
+ if stubout + 1 < 0 or stubin < 0:
630
+ modstubs[mslen] = (stubout + 1, stubin, stubsource)
631
+ mslen += 1
632
+
633
+ # Add the nodes back to the heaps that still have available stubs
634
+ for i in range(mslen):
635
+ stub = modstubs[i]
636
+ if stub[1] < 0:
637
+ heapq.heappush(stubheap, stub)
638
+ else:
639
+ heapq.heappush(zeroheap, (stub[0], stub[2]))
640
+ if freeout < 0:
641
+ heapq.heappush(zeroheap, (freeout, target))
642
+
643
+ return G
644
+
645
+
646
+ @nx._dispatchable(graphs=None, returns_graph=True)
647
+ def degree_sequence_tree(deg_sequence, create_using=None):
648
+ """Make a tree for the given degree sequence.
649
+
650
+ A tree has #nodes-#edges=1 so
651
+ the degree sequence must have
652
+ len(deg_sequence)-sum(deg_sequence)/2=1
653
+ """
654
+ # The sum of the degree sequence must be even (for any undirected graph).
655
+ degree_sum = sum(deg_sequence)
656
+ if degree_sum % 2 != 0:
657
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
658
+ raise nx.NetworkXError(msg)
659
+ if len(deg_sequence) - degree_sum // 2 != 1:
660
+ msg = (
661
+ "Invalid degree sequence: tree must have number of nodes equal"
662
+ " to one less than the number of edges"
663
+ )
664
+ raise nx.NetworkXError(msg)
665
+ G = nx.empty_graph(0, create_using)
666
+ if G.is_directed():
667
+ raise nx.NetworkXError("Directed Graph not supported")
668
+
669
+ # Sort all degrees greater than 1 in decreasing order.
670
+ #
671
+ # TODO Does this need to be sorted in reverse order?
672
+ deg = sorted((s for s in deg_sequence if s > 1), reverse=True)
673
+
674
+ # make path graph as backbone
675
+ n = len(deg) + 2
676
+ nx.add_path(G, range(n))
677
+ last = n
678
+
679
+ # add the leaves
680
+ for source in range(1, n - 1):
681
+ nedges = deg.pop() - 2
682
+ for target in range(last, last + nedges):
683
+ G.add_edge(source, target)
684
+ last += nedges
685
+
686
+ # in case we added one too many
687
+ if len(G) > len(deg_sequence):
688
+ G.remove_node(0)
689
+ return G
690
+
691
+
692
+ @py_random_state(1)
693
+ @nx._dispatchable(graphs=None, returns_graph=True)
694
+ def random_degree_sequence_graph(sequence, seed=None, tries=10):
695
+ r"""Returns a simple random graph with the given degree sequence.
696
+
697
+ If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the
698
+ algorithm produces almost uniform random graphs in $O(m d_m)$ time
699
+ where $m$ is the number of edges.
700
+
701
+ Parameters
702
+ ----------
703
+ sequence : list of integers
704
+ Sequence of degrees
705
+ seed : integer, random_state, or None (default)
706
+ Indicator of random number generation state.
707
+ See :ref:`Randomness<randomness>`.
708
+ tries : int, optional
709
+ Maximum number of tries to create a graph
710
+
711
+ Returns
712
+ -------
713
+ G : Graph
714
+ A graph with the specified degree sequence.
715
+ Nodes are labeled starting at 0 with an index
716
+ corresponding to the position in the sequence.
717
+
718
+ Raises
719
+ ------
720
+ NetworkXUnfeasible
721
+ If the degree sequence is not graphical.
722
+ NetworkXError
723
+ If a graph is not produced in specified number of tries
724
+
725
+ See Also
726
+ --------
727
+ is_graphical, configuration_model
728
+
729
+ Notes
730
+ -----
731
+ The generator algorithm [1]_ is not guaranteed to produce a graph.
732
+
733
+ References
734
+ ----------
735
+ .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
736
+ A sequential algorithm for generating random graphs.
737
+ Algorithmica, Volume 58, Number 4, 860-910,
738
+ DOI: 10.1007/s00453-009-9340-1
739
+
740
+ Examples
741
+ --------
742
+ >>> sequence = [1, 2, 2, 3]
743
+ >>> G = nx.random_degree_sequence_graph(sequence, seed=42)
744
+ >>> sorted(d for n, d in G.degree())
745
+ [1, 2, 2, 3]
746
+ """
747
+ DSRG = DegreeSequenceRandomGraph(sequence, seed)
748
+ for try_n in range(tries):
749
+ try:
750
+ return DSRG.generate()
751
+ except nx.NetworkXUnfeasible:
752
+ pass
753
+ raise nx.NetworkXError(f"failed to generate graph in {tries} tries")
754
+
755
+
756
+ class DegreeSequenceRandomGraph:
757
+ # class to generate random graphs with a given degree sequence
758
+ # use random_degree_sequence_graph()
759
+ def __init__(self, degree, rng):
760
+ if not nx.is_graphical(degree):
761
+ raise nx.NetworkXUnfeasible("degree sequence is not graphical")
762
+ self.rng = rng
763
+ self.degree = list(degree)
764
+ # node labels are integers 0,...,n-1
765
+ self.m = sum(self.degree) / 2.0 # number of edges
766
+ try:
767
+ self.dmax = max(self.degree) # maximum degree
768
+ except ValueError:
769
+ self.dmax = 0
770
+
771
+ def generate(self):
772
+ # remaining_degree is mapping from int->remaining degree
773
+ self.remaining_degree = dict(enumerate(self.degree))
774
+ # add all nodes to make sure we get isolated nodes
775
+ self.graph = nx.Graph()
776
+ self.graph.add_nodes_from(self.remaining_degree)
777
+ # remove zero degree nodes
778
+ for n, d in list(self.remaining_degree.items()):
779
+ if d == 0:
780
+ del self.remaining_degree[n]
781
+ if len(self.remaining_degree) > 0:
782
+ # build graph in three phases according to how many unmatched edges
783
+ self.phase1()
784
+ self.phase2()
785
+ self.phase3()
786
+ return self.graph
787
+
788
+ def update_remaining(self, u, v, aux_graph=None):
789
+ # decrement remaining nodes, modify auxiliary graph if in phase3
790
+ if aux_graph is not None:
791
+ # remove edges from auxiliary graph
792
+ aux_graph.remove_edge(u, v)
793
+ if self.remaining_degree[u] == 1:
794
+ del self.remaining_degree[u]
795
+ if aux_graph is not None:
796
+ aux_graph.remove_node(u)
797
+ else:
798
+ self.remaining_degree[u] -= 1
799
+ if self.remaining_degree[v] == 1:
800
+ del self.remaining_degree[v]
801
+ if aux_graph is not None:
802
+ aux_graph.remove_node(v)
803
+ else:
804
+ self.remaining_degree[v] -= 1
805
+
806
+ def p(self, u, v):
807
+ # degree probability
808
+ return 1 - self.degree[u] * self.degree[v] / (4.0 * self.m)
809
+
810
+ def q(self, u, v):
811
+ # remaining degree probability
812
+ norm = max(self.remaining_degree.values()) ** 2
813
+ return self.remaining_degree[u] * self.remaining_degree[v] / norm
814
+
815
+ def suitable_edge(self):
816
+ """Returns True if and only if an arbitrary remaining node can
817
+ potentially be joined with some other remaining node.
818
+
819
+ """
820
+ nodes = iter(self.remaining_degree)
821
+ u = next(nodes)
822
+ return any(v not in self.graph[u] for v in nodes)
823
+
824
+ def phase1(self):
825
+ # choose node pairs from (degree) weighted distribution
826
+ rem_deg = self.remaining_degree
827
+ while sum(rem_deg.values()) >= 2 * self.dmax**2:
828
+ u, v = sorted(random_weighted_sample(rem_deg, 2, self.rng))
829
+ if self.graph.has_edge(u, v):
830
+ continue
831
+ if self.rng.random() < self.p(u, v): # accept edge
832
+ self.graph.add_edge(u, v)
833
+ self.update_remaining(u, v)
834
+
835
+ def phase2(self):
836
+ # choose remaining nodes uniformly at random and use rejection sampling
837
+ remaining_deg = self.remaining_degree
838
+ rng = self.rng
839
+ while len(remaining_deg) >= 2 * self.dmax:
840
+ while True:
841
+ u, v = sorted(rng.sample(list(remaining_deg.keys()), 2))
842
+ if self.graph.has_edge(u, v):
843
+ continue
844
+ if rng.random() < self.q(u, v):
845
+ break
846
+ if rng.random() < self.p(u, v): # accept edge
847
+ self.graph.add_edge(u, v)
848
+ self.update_remaining(u, v)
849
+
850
+ def phase3(self):
851
+ # build potential remaining edges and choose with rejection sampling
852
+ potential_edges = combinations(self.remaining_degree, 2)
853
+ # build auxiliary graph of potential edges not already in graph
854
+ H = nx.Graph(
855
+ [(u, v) for (u, v) in potential_edges if not self.graph.has_edge(u, v)]
856
+ )
857
+ rng = self.rng
858
+ while self.remaining_degree:
859
+ if not self.suitable_edge():
860
+ raise nx.NetworkXUnfeasible("no suitable edges left")
861
+ while True:
862
+ u, v = sorted(rng.choice(list(H.edges())))
863
+ if rng.random() < self.q(u, v):
864
+ break
865
+ if rng.random() < self.p(u, v): # accept edge
866
+ self.graph.add_edge(u, v)
867
+ self.update_remaining(u, v, aux_graph=H)
wemm/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
wemm/lib/python3.10/site-packages/networkx/generators/mycielski.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to the Mycielski Operation and the Mycielskian family
2
+ of graphs.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for
8
+
9
+ __all__ = ["mycielskian", "mycielski_graph"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ @nx._dispatchable(returns_graph=True)
15
+ def mycielskian(G, iterations=1):
16
+ r"""Returns the Mycielskian of a simple, undirected graph G
17
+
18
+ The Mycielskian of graph preserves a graph's triangle free
19
+ property while increasing the chromatic number by 1.
20
+
21
+ The Mycielski Operation on a graph, :math:`G=(V, E)`, constructs a new
22
+ graph with :math:`2|V| + 1` nodes and :math:`3|E| + |V|` edges.
23
+
24
+ The construction is as follows:
25
+
26
+ Let :math:`V = {0, ..., n-1}`. Construct another vertex set
27
+ :math:`U = {n, ..., 2n}` and a vertex, `w`.
28
+ Construct a new graph, `M`, with vertices :math:`U \bigcup V \bigcup w`.
29
+ For edges, :math:`(u, v) \in E` add edges :math:`(u, v), (u, v + n)`, and
30
+ :math:`(u + n, v)` to M. Finally, for all vertices :math:`u \in U`, add
31
+ edge :math:`(u, w)` to M.
32
+
33
+ The Mycielski Operation can be done multiple times by repeating the above
34
+ process iteratively.
35
+
36
+ More information can be found at https://en.wikipedia.org/wiki/Mycielskian
37
+
38
+ Parameters
39
+ ----------
40
+ G : graph
41
+ A simple, undirected NetworkX graph
42
+ iterations : int
43
+ The number of iterations of the Mycielski operation to
44
+ perform on G. Defaults to 1. Must be a non-negative integer.
45
+
46
+ Returns
47
+ -------
48
+ M : graph
49
+ The Mycielskian of G after the specified number of iterations.
50
+
51
+ Notes
52
+ -----
53
+ Graph, node, and edge data are not necessarily propagated to the new graph.
54
+
55
+ """
56
+
57
+ M = nx.convert_node_labels_to_integers(G)
58
+
59
+ for i in range(iterations):
60
+ n = M.number_of_nodes()
61
+ M.add_nodes_from(range(n, 2 * n))
62
+ old_edges = list(M.edges())
63
+ M.add_edges_from((u, v + n) for u, v in old_edges)
64
+ M.add_edges_from((u + n, v) for u, v in old_edges)
65
+ M.add_node(2 * n)
66
+ M.add_edges_from((u + n, 2 * n) for u in range(n))
67
+
68
+ return M
69
+
70
+
71
+ @nx._dispatchable(graphs=None, returns_graph=True)
72
+ def mycielski_graph(n):
73
+ """Generator for the n_th Mycielski Graph.
74
+
75
+ The Mycielski family of graphs is an infinite set of graphs.
76
+ :math:`M_1` is the singleton graph, :math:`M_2` is two vertices with an
77
+ edge, and, for :math:`i > 2`, :math:`M_i` is the Mycielskian of
78
+ :math:`M_{i-1}`.
79
+
80
+ More information can be found at
81
+ http://mathworld.wolfram.com/MycielskiGraph.html
82
+
83
+ Parameters
84
+ ----------
85
+ n : int
86
+ The desired Mycielski Graph.
87
+
88
+ Returns
89
+ -------
90
+ M : graph
91
+ The n_th Mycielski Graph
92
+
93
+ Notes
94
+ -----
95
+ The first graph in the Mycielski sequence is the singleton graph.
96
+ The Mycielskian of this graph is not the :math:`P_2` graph, but rather the
97
+ :math:`P_2` graph with an extra, isolated vertex. The second Mycielski
98
+ graph is the :math:`P_2` graph, so the first two are hard coded.
99
+ The remaining graphs are generated using the Mycielski operation.
100
+
101
+ """
102
+
103
+ if n < 1:
104
+ raise nx.NetworkXError("must satisfy n >= 1")
105
+
106
+ if n == 1:
107
+ return nx.empty_graph(1)
108
+
109
+ else:
110
+ return mycielskian(nx.path_graph(2), n - 2)
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-310.pyc ADDED
Binary file (2.84 kB). View file
 
wemm/lib/python3.10/site-packages/networkx/generators/tests/test_cographs.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.cographs` module."""
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_random_cograph():
7
+ n = 3
8
+ G = nx.random_cograph(n)
9
+
10
+ assert len(G) == 2**n
11
+
12
+ # Every connected subgraph of G has diameter <= 2
13
+ if nx.is_connected(G):
14
+ assert nx.diameter(G) <= 2
15
+ else:
16
+ components = nx.connected_components(G)
17
+ for component in components:
18
+ assert nx.diameter(G.subgraph(component)) <= 2