applied-ai-018 commited on
Commit
64564c8
·
verified ·
1 Parent(s): 5e419fc

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. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/coreviews.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/digraph.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/filters.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/function.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/graph.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/graphviews.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/multidigraph.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/multigraph.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/reportviews.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/networkx/classes/function.py +1335 -0
  12. llmeval-env/lib/python3.10/site-packages/networkx/classes/graphviews.py +269 -0
  13. llmeval-env/lib/python3.10/site-packages/networkx/classes/multigraph.py +1282 -0
  14. llmeval-env/lib/python3.10/site-packages/networkx/classes/reportviews.py +1438 -0
  15. llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__init__.py +0 -0
  16. llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_graph.py +920 -0
  17. llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_special.py +131 -0
  18. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__init__.py +7 -0
  19. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/networkx/drawing/layout.py +1358 -0
  26. llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py +465 -0
  27. llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_latex.py +571 -0
  28. llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py +411 -0
  29. llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py +1871 -0
  30. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py +0 -0
  31. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py +240 -0
  34. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py +292 -0
  35. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py +515 -0
  36. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py +180 -0
  37. llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py +879 -0
  38. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/edgelist.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/leda.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/sparse6.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/text.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (593 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/coreviews.cpython-310.pyc ADDED
Binary file (16.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/digraph.cpython-310.pyc ADDED
Binary file (46.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/filters.cpython-310.pyc ADDED
Binary file (4.72 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/function.cpython-310.pyc ADDED
Binary file (37.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/graph.cpython-310.pyc ADDED
Binary file (69.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/graphviews.cpython-310.pyc ADDED
Binary file (8.21 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/multidigraph.cpython-310.pyc ADDED
Binary file (36 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/multigraph.cpython-310.pyc ADDED
Binary file (46.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/__pycache__/reportviews.cpython-310.pyc ADDED
Binary file (49.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/classes/function.py ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functional interface to graph methods and assorted utilities.
2
+ """
3
+
4
+ from collections import Counter
5
+ from itertools import chain
6
+
7
+ import networkx as nx
8
+ from networkx.utils import not_implemented_for, pairwise
9
+
10
+ __all__ = [
11
+ "nodes",
12
+ "edges",
13
+ "degree",
14
+ "degree_histogram",
15
+ "neighbors",
16
+ "number_of_nodes",
17
+ "number_of_edges",
18
+ "density",
19
+ "is_directed",
20
+ "freeze",
21
+ "is_frozen",
22
+ "subgraph",
23
+ "induced_subgraph",
24
+ "edge_subgraph",
25
+ "restricted_view",
26
+ "to_directed",
27
+ "to_undirected",
28
+ "add_star",
29
+ "add_path",
30
+ "add_cycle",
31
+ "create_empty_copy",
32
+ "set_node_attributes",
33
+ "get_node_attributes",
34
+ "set_edge_attributes",
35
+ "get_edge_attributes",
36
+ "all_neighbors",
37
+ "non_neighbors",
38
+ "non_edges",
39
+ "common_neighbors",
40
+ "is_weighted",
41
+ "is_negatively_weighted",
42
+ "is_empty",
43
+ "selfloop_edges",
44
+ "nodes_with_selfloops",
45
+ "number_of_selfloops",
46
+ "path_weight",
47
+ "is_path",
48
+ ]
49
+
50
+
51
+ def nodes(G):
52
+ """Returns a NodeView over the graph nodes.
53
+
54
+ This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
55
+ """
56
+ return G.nodes()
57
+
58
+
59
+ def edges(G, nbunch=None):
60
+ """Returns an edge view of edges incident to nodes in nbunch.
61
+
62
+ Return all edges if nbunch is unspecified or nbunch=None.
63
+
64
+ For digraphs, edges=out_edges
65
+
66
+ This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
67
+ """
68
+ return G.edges(nbunch)
69
+
70
+
71
+ def degree(G, nbunch=None, weight=None):
72
+ """Returns a degree view of single node or of nbunch of nodes.
73
+ If nbunch is omitted, then return degrees of *all* nodes.
74
+
75
+ This function wraps the :func:`G.degree <networkx.Graph.degree>` property.
76
+ """
77
+ return G.degree(nbunch, weight)
78
+
79
+
80
+ def neighbors(G, n):
81
+ """Returns an iterator over all neighbors of node n.
82
+
83
+ This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
84
+ """
85
+ return G.neighbors(n)
86
+
87
+
88
+ def number_of_nodes(G):
89
+ """Returns the number of nodes in the graph.
90
+
91
+ This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
92
+ """
93
+ return G.number_of_nodes()
94
+
95
+
96
+ def number_of_edges(G):
97
+ """Returns the number of edges in the graph.
98
+
99
+ This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
100
+ """
101
+ return G.number_of_edges()
102
+
103
+
104
+ def density(G):
105
+ r"""Returns the density of a graph.
106
+
107
+ The density for undirected graphs is
108
+
109
+ .. math::
110
+
111
+ d = \frac{2m}{n(n-1)},
112
+
113
+ and for directed graphs is
114
+
115
+ .. math::
116
+
117
+ d = \frac{m}{n(n-1)},
118
+
119
+ where `n` is the number of nodes and `m` is the number of edges in `G`.
120
+
121
+ Notes
122
+ -----
123
+ The density is 0 for a graph without edges and 1 for a complete graph.
124
+ The density of multigraphs can be higher than 1.
125
+
126
+ Self loops are counted in the total number of edges so graphs with self
127
+ loops can have density higher than 1.
128
+ """
129
+ n = number_of_nodes(G)
130
+ m = number_of_edges(G)
131
+ if m == 0 or n <= 1:
132
+ return 0
133
+ d = m / (n * (n - 1))
134
+ if not G.is_directed():
135
+ d *= 2
136
+ return d
137
+
138
+
139
+ def degree_histogram(G):
140
+ """Returns a list of the frequency of each degree value.
141
+
142
+ Parameters
143
+ ----------
144
+ G : Networkx graph
145
+ A graph
146
+
147
+ Returns
148
+ -------
149
+ hist : list
150
+ A list of frequencies of degrees.
151
+ The degree values are the index in the list.
152
+
153
+ Notes
154
+ -----
155
+ Note: the bins are width one, hence len(list) can be large
156
+ (Order(number_of_edges))
157
+ """
158
+ counts = Counter(d for n, d in G.degree())
159
+ return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
160
+
161
+
162
+ def is_directed(G):
163
+ """Return True if graph is directed."""
164
+ return G.is_directed()
165
+
166
+
167
+ def frozen(*args, **kwargs):
168
+ """Dummy method for raising errors when trying to modify frozen graphs"""
169
+ raise nx.NetworkXError("Frozen graph can't be modified")
170
+
171
+
172
+ def freeze(G):
173
+ """Modify graph to prevent further change by adding or removing
174
+ nodes or edges.
175
+
176
+ Node and edge data can still be modified.
177
+
178
+ Parameters
179
+ ----------
180
+ G : graph
181
+ A NetworkX graph
182
+
183
+ Examples
184
+ --------
185
+ >>> G = nx.path_graph(4)
186
+ >>> G = nx.freeze(G)
187
+ >>> try:
188
+ ... G.add_edge(4, 5)
189
+ ... except nx.NetworkXError as err:
190
+ ... print(str(err))
191
+ Frozen graph can't be modified
192
+
193
+ Notes
194
+ -----
195
+ To "unfreeze" a graph you must make a copy by creating a new graph object:
196
+
197
+ >>> graph = nx.path_graph(4)
198
+ >>> frozen_graph = nx.freeze(graph)
199
+ >>> unfrozen_graph = nx.Graph(frozen_graph)
200
+ >>> nx.is_frozen(unfrozen_graph)
201
+ False
202
+
203
+ See Also
204
+ --------
205
+ is_frozen
206
+ """
207
+ G.add_node = frozen
208
+ G.add_nodes_from = frozen
209
+ G.remove_node = frozen
210
+ G.remove_nodes_from = frozen
211
+ G.add_edge = frozen
212
+ G.add_edges_from = frozen
213
+ G.add_weighted_edges_from = frozen
214
+ G.remove_edge = frozen
215
+ G.remove_edges_from = frozen
216
+ G.clear = frozen
217
+ G.clear_edges = frozen
218
+ G.frozen = True
219
+ return G
220
+
221
+
222
+ def is_frozen(G):
223
+ """Returns True if graph is frozen.
224
+
225
+ Parameters
226
+ ----------
227
+ G : graph
228
+ A NetworkX graph
229
+
230
+ See Also
231
+ --------
232
+ freeze
233
+ """
234
+ try:
235
+ return G.frozen
236
+ except AttributeError:
237
+ return False
238
+
239
+
240
+ def add_star(G_to_add_to, nodes_for_star, **attr):
241
+ """Add a star to Graph G_to_add_to.
242
+
243
+ The first node in `nodes_for_star` is the middle of the star.
244
+ It is connected to all other nodes.
245
+
246
+ Parameters
247
+ ----------
248
+ G_to_add_to : graph
249
+ A NetworkX graph
250
+ nodes_for_star : iterable container
251
+ A container of nodes.
252
+ attr : keyword arguments, optional (default= no attributes)
253
+ Attributes to add to every edge in star.
254
+
255
+ See Also
256
+ --------
257
+ add_path, add_cycle
258
+
259
+ Examples
260
+ --------
261
+ >>> G = nx.Graph()
262
+ >>> nx.add_star(G, [0, 1, 2, 3])
263
+ >>> nx.add_star(G, [10, 11, 12], weight=2)
264
+ """
265
+ nlist = iter(nodes_for_star)
266
+ try:
267
+ v = next(nlist)
268
+ except StopIteration:
269
+ return
270
+ G_to_add_to.add_node(v)
271
+ edges = ((v, n) for n in nlist)
272
+ G_to_add_to.add_edges_from(edges, **attr)
273
+
274
+
275
+ def add_path(G_to_add_to, nodes_for_path, **attr):
276
+ """Add a path to the Graph G_to_add_to.
277
+
278
+ Parameters
279
+ ----------
280
+ G_to_add_to : graph
281
+ A NetworkX graph
282
+ nodes_for_path : iterable container
283
+ A container of nodes. A path will be constructed from
284
+ the nodes (in order) and added to the graph.
285
+ attr : keyword arguments, optional (default= no attributes)
286
+ Attributes to add to every edge in path.
287
+
288
+ See Also
289
+ --------
290
+ add_star, add_cycle
291
+
292
+ Examples
293
+ --------
294
+ >>> G = nx.Graph()
295
+ >>> nx.add_path(G, [0, 1, 2, 3])
296
+ >>> nx.add_path(G, [10, 11, 12], weight=7)
297
+ """
298
+ nlist = iter(nodes_for_path)
299
+ try:
300
+ first_node = next(nlist)
301
+ except StopIteration:
302
+ return
303
+ G_to_add_to.add_node(first_node)
304
+ G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
305
+
306
+
307
+ def add_cycle(G_to_add_to, nodes_for_cycle, **attr):
308
+ """Add a cycle to the Graph G_to_add_to.
309
+
310
+ Parameters
311
+ ----------
312
+ G_to_add_to : graph
313
+ A NetworkX graph
314
+ nodes_for_cycle: iterable container
315
+ A container of nodes. A cycle will be constructed from
316
+ the nodes (in order) and added to the graph.
317
+ attr : keyword arguments, optional (default= no attributes)
318
+ Attributes to add to every edge in cycle.
319
+
320
+ See Also
321
+ --------
322
+ add_path, add_star
323
+
324
+ Examples
325
+ --------
326
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
327
+ >>> nx.add_cycle(G, [0, 1, 2, 3])
328
+ >>> nx.add_cycle(G, [10, 11, 12], weight=7)
329
+ """
330
+ nlist = iter(nodes_for_cycle)
331
+ try:
332
+ first_node = next(nlist)
333
+ except StopIteration:
334
+ return
335
+ G_to_add_to.add_node(first_node)
336
+ G_to_add_to.add_edges_from(
337
+ pairwise(chain((first_node,), nlist), cyclic=True), **attr
338
+ )
339
+
340
+
341
+ def subgraph(G, nbunch):
342
+ """Returns the subgraph induced on nodes in nbunch.
343
+
344
+ Parameters
345
+ ----------
346
+ G : graph
347
+ A NetworkX graph
348
+
349
+ nbunch : list, iterable
350
+ A container of nodes that will be iterated through once (thus
351
+ it should be an iterator or be iterable). Each element of the
352
+ container should be a valid node type: any hashable type except
353
+ None. If nbunch is None, return all edges data in the graph.
354
+ Nodes in nbunch that are not in the graph will be (quietly)
355
+ ignored.
356
+
357
+ Notes
358
+ -----
359
+ subgraph(G) calls G.subgraph()
360
+ """
361
+ return G.subgraph(nbunch)
362
+
363
+
364
+ def induced_subgraph(G, nbunch):
365
+ """Returns a SubGraph view of `G` showing only nodes in nbunch.
366
+
367
+ The induced subgraph of a graph on a set of nodes N is the
368
+ graph with nodes N and edges from G which have both ends in N.
369
+
370
+ Parameters
371
+ ----------
372
+ G : NetworkX Graph
373
+ nbunch : node, container of nodes or None (for all nodes)
374
+
375
+ Returns
376
+ -------
377
+ subgraph : SubGraph View
378
+ A read-only view of the subgraph in `G` induced by the nodes.
379
+ Changes to the graph `G` will be reflected in the view.
380
+
381
+ Notes
382
+ -----
383
+ To create a mutable subgraph with its own copies of nodes
384
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
385
+
386
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
387
+ `G.remove_nodes_from(n in G if n not in set(nbunch))`
388
+
389
+ If you are going to compute subgraphs of your subgraphs you could
390
+ end up with a chain of views that can be very slow once the chain
391
+ has about 15 views in it. If they are all induced subgraphs, you
392
+ can short-cut the chain by making them all subgraphs of the original
393
+ graph. The graph class method `G.subgraph` does this when `G` is
394
+ a subgraph. In contrast, this function allows you to choose to build
395
+ chains or not, as you wish. The returned subgraph is a view on `G`.
396
+
397
+ Examples
398
+ --------
399
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
400
+ >>> H = nx.induced_subgraph(G, [0, 1, 3])
401
+ >>> list(H.edges)
402
+ [(0, 1)]
403
+ >>> list(H.nodes)
404
+ [0, 1, 3]
405
+ """
406
+ induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
407
+ return nx.subgraph_view(G, filter_node=induced_nodes)
408
+
409
+
410
+ def edge_subgraph(G, edges):
411
+ """Returns a view of the subgraph induced by the specified edges.
412
+
413
+ The induced subgraph contains each edge in `edges` and each
414
+ node incident to any of those edges.
415
+
416
+ Parameters
417
+ ----------
418
+ G : NetworkX Graph
419
+ edges : iterable
420
+ An iterable of edges. Edges not present in `G` are ignored.
421
+
422
+ Returns
423
+ -------
424
+ subgraph : SubGraph View
425
+ A read-only edge-induced subgraph of `G`.
426
+ Changes to `G` are reflected in the view.
427
+
428
+ Notes
429
+ -----
430
+ To create a mutable subgraph with its own copies of nodes
431
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
432
+
433
+ If you create a subgraph of a subgraph recursively you can end up
434
+ with a chain of subgraphs that becomes very slow with about 15
435
+ nested subgraph views. Luckily the edge_subgraph filter nests
436
+ nicely so you can use the original graph as G in this function
437
+ to avoid chains. We do not rule out chains programmatically so
438
+ that odd cases like an `edge_subgraph` of a `restricted_view`
439
+ can be created.
440
+
441
+ Examples
442
+ --------
443
+ >>> G = nx.path_graph(5)
444
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
445
+ >>> list(H.nodes)
446
+ [0, 1, 3, 4]
447
+ >>> list(H.edges)
448
+ [(0, 1), (3, 4)]
449
+ """
450
+ nxf = nx.filters
451
+ edges = set(edges)
452
+ nodes = set()
453
+ for e in edges:
454
+ nodes.update(e[:2])
455
+ induced_nodes = nxf.show_nodes(nodes)
456
+ if G.is_multigraph():
457
+ if G.is_directed():
458
+ induced_edges = nxf.show_multidiedges(edges)
459
+ else:
460
+ induced_edges = nxf.show_multiedges(edges)
461
+ else:
462
+ if G.is_directed():
463
+ induced_edges = nxf.show_diedges(edges)
464
+ else:
465
+ induced_edges = nxf.show_edges(edges)
466
+ return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
467
+
468
+
469
+ def restricted_view(G, nodes, edges):
470
+ """Returns a view of `G` with hidden nodes and edges.
471
+
472
+ The resulting subgraph filters out node `nodes` and edges `edges`.
473
+ Filtered out nodes also filter out any of their edges.
474
+
475
+ Parameters
476
+ ----------
477
+ G : NetworkX Graph
478
+ nodes : iterable
479
+ An iterable of nodes. Nodes not present in `G` are ignored.
480
+ edges : iterable
481
+ An iterable of edges. Edges not present in `G` are ignored.
482
+
483
+ Returns
484
+ -------
485
+ subgraph : SubGraph View
486
+ A read-only restricted view of `G` filtering out nodes and edges.
487
+ Changes to `G` are reflected in the view.
488
+
489
+ Notes
490
+ -----
491
+ To create a mutable subgraph with its own copies of nodes
492
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
493
+
494
+ If you create a subgraph of a subgraph recursively you may end up
495
+ with a chain of subgraph views. Such chains can get quite slow
496
+ for lengths near 15. To avoid long chains, try to make your subgraph
497
+ based on the original graph. We do not rule out chains programmatically
498
+ so that odd cases like an `edge_subgraph` of a `restricted_view`
499
+ can be created.
500
+
501
+ Examples
502
+ --------
503
+ >>> G = nx.path_graph(5)
504
+ >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)])
505
+ >>> list(H.nodes)
506
+ [1, 2, 3, 4]
507
+ >>> list(H.edges)
508
+ [(2, 3)]
509
+ """
510
+ nxf = nx.filters
511
+ hide_nodes = nxf.hide_nodes(nodes)
512
+ if G.is_multigraph():
513
+ if G.is_directed():
514
+ hide_edges = nxf.hide_multidiedges(edges)
515
+ else:
516
+ hide_edges = nxf.hide_multiedges(edges)
517
+ else:
518
+ if G.is_directed():
519
+ hide_edges = nxf.hide_diedges(edges)
520
+ else:
521
+ hide_edges = nxf.hide_edges(edges)
522
+ return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
523
+
524
+
525
+ def to_directed(graph):
526
+ """Returns a directed view of the graph `graph`.
527
+
528
+ Identical to graph.to_directed(as_view=True)
529
+ Note that graph.to_directed defaults to `as_view=False`
530
+ while this function always provides a view.
531
+ """
532
+ return graph.to_directed(as_view=True)
533
+
534
+
535
+ def to_undirected(graph):
536
+ """Returns an undirected view of the graph `graph`.
537
+
538
+ Identical to graph.to_undirected(as_view=True)
539
+ Note that graph.to_undirected defaults to `as_view=False`
540
+ while this function always provides a view.
541
+ """
542
+ return graph.to_undirected(as_view=True)
543
+
544
+
545
+ def create_empty_copy(G, with_data=True):
546
+ """Returns a copy of the graph G with all of the edges removed.
547
+
548
+ Parameters
549
+ ----------
550
+ G : graph
551
+ A NetworkX graph
552
+
553
+ with_data : bool (default=True)
554
+ Propagate Graph and Nodes data to the new graph.
555
+
556
+ See Also
557
+ --------
558
+ empty_graph
559
+
560
+ """
561
+ H = G.__class__()
562
+ H.add_nodes_from(G.nodes(data=with_data))
563
+ if with_data:
564
+ H.graph.update(G.graph)
565
+ return H
566
+
567
+
568
+ def set_node_attributes(G, values, name=None):
569
+ """Sets node attributes from a given value or dictionary of values.
570
+
571
+ .. Warning:: The call order of arguments `values` and `name`
572
+ switched between v1.x & v2.x.
573
+
574
+ Parameters
575
+ ----------
576
+ G : NetworkX Graph
577
+
578
+ values : scalar value, dict-like
579
+ What the node attribute should be set to. If `values` is
580
+ not a dictionary, then it is treated as a single attribute value
581
+ that is then applied to every node in `G`. This means that if
582
+ you provide a mutable object, like a list, updates to that object
583
+ will be reflected in the node attribute for every node.
584
+ The attribute name will be `name`.
585
+
586
+ If `values` is a dict or a dict of dict, it should be keyed
587
+ by node to either an attribute value or a dict of attribute key/value
588
+ pairs used to update the node's attributes.
589
+
590
+ name : string (optional, default=None)
591
+ Name of the node attribute to set if values is a scalar.
592
+
593
+ Examples
594
+ --------
595
+ After computing some property of the nodes of a graph, you may want
596
+ to assign a node attribute to store the value of that property for
597
+ each node::
598
+
599
+ >>> G = nx.path_graph(3)
600
+ >>> bb = nx.betweenness_centrality(G)
601
+ >>> isinstance(bb, dict)
602
+ True
603
+ >>> nx.set_node_attributes(G, bb, "betweenness")
604
+ >>> G.nodes[1]["betweenness"]
605
+ 1.0
606
+
607
+ If you provide a list as the second argument, updates to the list
608
+ will be reflected in the node attribute for each node::
609
+
610
+ >>> G = nx.path_graph(3)
611
+ >>> labels = []
612
+ >>> nx.set_node_attributes(G, labels, "labels")
613
+ >>> labels.append("foo")
614
+ >>> G.nodes[0]["labels"]
615
+ ['foo']
616
+ >>> G.nodes[1]["labels"]
617
+ ['foo']
618
+ >>> G.nodes[2]["labels"]
619
+ ['foo']
620
+
621
+ If you provide a dictionary of dictionaries as the second argument,
622
+ the outer dictionary is assumed to be keyed by node to an inner
623
+ dictionary of node attributes for that node::
624
+
625
+ >>> G = nx.path_graph(3)
626
+ >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}}
627
+ >>> nx.set_node_attributes(G, attrs)
628
+ >>> G.nodes[0]["attr1"]
629
+ 20
630
+ >>> G.nodes[0]["attr2"]
631
+ 'nothing'
632
+ >>> G.nodes[1]["attr2"]
633
+ 3
634
+ >>> G.nodes[2]
635
+ {}
636
+
637
+ Note that if the dictionary contains nodes that are not in `G`, the
638
+ values are silently ignored::
639
+
640
+ >>> G = nx.Graph()
641
+ >>> G.add_node(0)
642
+ >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color")
643
+ >>> G.nodes[0]["color"]
644
+ 'red'
645
+ >>> 1 in G.nodes
646
+ False
647
+
648
+ """
649
+ # Set node attributes based on type of `values`
650
+ if name is not None: # `values` must not be a dict of dict
651
+ try: # `values` is a dict
652
+ for n, v in values.items():
653
+ try:
654
+ G.nodes[n][name] = values[n]
655
+ except KeyError:
656
+ pass
657
+ except AttributeError: # `values` is a constant
658
+ for n in G:
659
+ G.nodes[n][name] = values
660
+ else: # `values` must be dict of dict
661
+ for n, d in values.items():
662
+ try:
663
+ G.nodes[n].update(d)
664
+ except KeyError:
665
+ pass
666
+ nx._clear_cache(G)
667
+
668
+
669
+ def get_node_attributes(G, name, default=None):
670
+ """Get node attributes from graph
671
+
672
+ Parameters
673
+ ----------
674
+ G : NetworkX Graph
675
+
676
+ name : string
677
+ Attribute name
678
+
679
+ default: object (default=None)
680
+ Default value of the node attribute if there is no value set for that
681
+ node in graph. If `None` then nodes without this attribute are not
682
+ included in the returned dict.
683
+
684
+ Returns
685
+ -------
686
+ Dictionary of attributes keyed by node.
687
+
688
+ Examples
689
+ --------
690
+ >>> G = nx.Graph()
691
+ >>> G.add_nodes_from([1, 2, 3], color="red")
692
+ >>> color = nx.get_node_attributes(G, "color")
693
+ >>> color[1]
694
+ 'red'
695
+ >>> G.add_node(4)
696
+ >>> color = nx.get_node_attributes(G, "color", default="yellow")
697
+ >>> color[4]
698
+ 'yellow'
699
+ """
700
+ if default is not None:
701
+ return {n: d.get(name, default) for n, d in G.nodes.items()}
702
+ return {n: d[name] for n, d in G.nodes.items() if name in d}
703
+
704
+
705
+ def set_edge_attributes(G, values, name=None):
706
+ """Sets edge attributes from a given value or dictionary of values.
707
+
708
+ .. Warning:: The call order of arguments `values` and `name`
709
+ switched between v1.x & v2.x.
710
+
711
+ Parameters
712
+ ----------
713
+ G : NetworkX Graph
714
+
715
+ values : scalar value, dict-like
716
+ What the edge attribute should be set to. If `values` is
717
+ not a dictionary, then it is treated as a single attribute value
718
+ that is then applied to every edge in `G`. This means that if
719
+ you provide a mutable object, like a list, updates to that object
720
+ will be reflected in the edge attribute for each edge. The attribute
721
+ name will be `name`.
722
+
723
+ If `values` is a dict or a dict of dict, it should be keyed
724
+ by edge tuple to either an attribute value or a dict of attribute
725
+ key/value pairs used to update the edge's attributes.
726
+ For multigraphs, the edge tuples must be of the form ``(u, v, key)``,
727
+ where `u` and `v` are nodes and `key` is the edge key.
728
+ For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
729
+
730
+ name : string (optional, default=None)
731
+ Name of the edge attribute to set if values is a scalar.
732
+
733
+ Examples
734
+ --------
735
+ After computing some property of the edges of a graph, you may want
736
+ to assign a edge attribute to store the value of that property for
737
+ each edge::
738
+
739
+ >>> G = nx.path_graph(3)
740
+ >>> bb = nx.edge_betweenness_centrality(G, normalized=False)
741
+ >>> nx.set_edge_attributes(G, bb, "betweenness")
742
+ >>> G.edges[1, 2]["betweenness"]
743
+ 2.0
744
+
745
+ If you provide a list as the second argument, updates to the list
746
+ will be reflected in the edge attribute for each edge::
747
+
748
+ >>> labels = []
749
+ >>> nx.set_edge_attributes(G, labels, "labels")
750
+ >>> labels.append("foo")
751
+ >>> G.edges[0, 1]["labels"]
752
+ ['foo']
753
+ >>> G.edges[1, 2]["labels"]
754
+ ['foo']
755
+
756
+ If you provide a dictionary of dictionaries as the second argument,
757
+ the entire dictionary will be used to update edge attributes::
758
+
759
+ >>> G = nx.path_graph(3)
760
+ >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}}
761
+ >>> nx.set_edge_attributes(G, attrs)
762
+ >>> G[0][1]["attr1"]
763
+ 20
764
+ >>> G[0][1]["attr2"]
765
+ 'nothing'
766
+ >>> G[1][2]["attr2"]
767
+ 3
768
+
769
+ The attributes of one Graph can be used to set those of another.
770
+
771
+ >>> H = nx.path_graph(3)
772
+ >>> nx.set_edge_attributes(H, G.edges)
773
+
774
+ Note that if the dict contains edges that are not in `G`, they are
775
+ silently ignored::
776
+
777
+ >>> G = nx.Graph([(0, 1)])
778
+ >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}})
779
+ >>> (1, 2) in G.edges()
780
+ False
781
+
782
+ For multigraphs, the `values` dict is expected to be keyed by 3-tuples
783
+ including the edge key::
784
+
785
+ >>> MG = nx.MultiGraph()
786
+ >>> edges = [(0, 1), (0, 1)]
787
+ >>> MG.add_edges_from(edges) # Returns list of edge keys
788
+ [0, 1]
789
+ >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
790
+ >>> nx.set_edge_attributes(MG, attributes)
791
+ >>> MG[0][1][0]["cost"]
792
+ 21
793
+ >>> MG[0][1][1]["cost"]
794
+ 7
795
+
796
+ If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
797
+ multiedge to a 2-tuple edge and the last multiedge's attribute value will
798
+ overwrite the previous values. Continuing from the previous case we get::
799
+
800
+ >>> H = nx.path_graph([0, 1, 2])
801
+ >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
802
+ >>> nx.get_edge_attributes(H, "cost")
803
+ {(0, 1): 7}
804
+
805
+ """
806
+ if name is not None:
807
+ # `values` does not contain attribute names
808
+ try:
809
+ # if `values` is a dict using `.items()` => {edge: value}
810
+ if G.is_multigraph():
811
+ for (u, v, key), value in values.items():
812
+ try:
813
+ G._adj[u][v][key][name] = value
814
+ except KeyError:
815
+ pass
816
+ else:
817
+ for (u, v), value in values.items():
818
+ try:
819
+ G._adj[u][v][name] = value
820
+ except KeyError:
821
+ pass
822
+ except AttributeError:
823
+ # treat `values` as a constant
824
+ for u, v, data in G.edges(data=True):
825
+ data[name] = values
826
+ else:
827
+ # `values` consists of doct-of-dict {edge: {attr: value}} shape
828
+ if G.is_multigraph():
829
+ for (u, v, key), d in values.items():
830
+ try:
831
+ G._adj[u][v][key].update(d)
832
+ except KeyError:
833
+ pass
834
+ else:
835
+ for (u, v), d in values.items():
836
+ try:
837
+ G._adj[u][v].update(d)
838
+ except KeyError:
839
+ pass
840
+ nx._clear_cache(G)
841
+
842
+
843
+ def get_edge_attributes(G, name, default=None):
844
+ """Get edge attributes from graph
845
+
846
+ Parameters
847
+ ----------
848
+ G : NetworkX Graph
849
+
850
+ name : string
851
+ Attribute name
852
+
853
+ default: object (default=None)
854
+ Default value of the edge attribute if there is no value set for that
855
+ edge in graph. If `None` then edges without this attribute are not
856
+ included in the returned dict.
857
+
858
+ Returns
859
+ -------
860
+ Dictionary of attributes keyed by edge. For (di)graphs, the keys are
861
+ 2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
862
+ the form: (u, v, key).
863
+
864
+ Examples
865
+ --------
866
+ >>> G = nx.Graph()
867
+ >>> nx.add_path(G, [1, 2, 3], color="red")
868
+ >>> color = nx.get_edge_attributes(G, "color")
869
+ >>> color[(1, 2)]
870
+ 'red'
871
+ >>> G.add_edge(3, 4)
872
+ >>> color = nx.get_edge_attributes(G, "color", default="yellow")
873
+ >>> color[(3, 4)]
874
+ 'yellow'
875
+ """
876
+ if G.is_multigraph():
877
+ edges = G.edges(keys=True, data=True)
878
+ else:
879
+ edges = G.edges(data=True)
880
+ if default is not None:
881
+ return {x[:-1]: x[-1].get(name, default) for x in edges}
882
+ return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
883
+
884
+
885
+ def all_neighbors(graph, node):
886
+ """Returns all of the neighbors of a node in the graph.
887
+
888
+ If the graph is directed returns predecessors as well as successors.
889
+
890
+ Parameters
891
+ ----------
892
+ graph : NetworkX graph
893
+ Graph to find neighbors.
894
+
895
+ node : node
896
+ The node whose neighbors will be returned.
897
+
898
+ Returns
899
+ -------
900
+ neighbors : iterator
901
+ Iterator of neighbors
902
+ """
903
+ if graph.is_directed():
904
+ values = chain(graph.predecessors(node), graph.successors(node))
905
+ else:
906
+ values = graph.neighbors(node)
907
+ return values
908
+
909
+
910
+ def non_neighbors(graph, node):
911
+ """Returns the non-neighbors of the node in the graph.
912
+
913
+ Parameters
914
+ ----------
915
+ graph : NetworkX graph
916
+ Graph to find neighbors.
917
+
918
+ node : node
919
+ The node whose neighbors will be returned.
920
+
921
+ Returns
922
+ -------
923
+ non_neighbors : set
924
+ Set of nodes in the graph that are not neighbors of the node.
925
+ """
926
+ return graph._adj.keys() - graph._adj[node].keys() - {node}
927
+
928
+
929
+ def non_edges(graph):
930
+ """Returns the nonexistent edges in the graph.
931
+
932
+ Parameters
933
+ ----------
934
+ graph : NetworkX graph.
935
+ Graph to find nonexistent edges.
936
+
937
+ Returns
938
+ -------
939
+ non_edges : iterator
940
+ Iterator of edges that are not in the graph.
941
+ """
942
+ if graph.is_directed():
943
+ for u in graph:
944
+ for v in non_neighbors(graph, u):
945
+ yield (u, v)
946
+ else:
947
+ nodes = set(graph)
948
+ while nodes:
949
+ u = nodes.pop()
950
+ for v in nodes - set(graph[u]):
951
+ yield (u, v)
952
+
953
+
954
+ @not_implemented_for("directed")
955
+ def common_neighbors(G, u, v):
956
+ """Returns the common neighbors of two nodes in a graph.
957
+
958
+ Parameters
959
+ ----------
960
+ G : graph
961
+ A NetworkX undirected graph.
962
+
963
+ u, v : nodes
964
+ Nodes in the graph.
965
+
966
+ Returns
967
+ -------
968
+ cnbors : set
969
+ Set of common neighbors of u and v in the graph.
970
+
971
+ Raises
972
+ ------
973
+ NetworkXError
974
+ If u or v is not a node in the graph.
975
+
976
+ Examples
977
+ --------
978
+ >>> G = nx.complete_graph(5)
979
+ >>> sorted(nx.common_neighbors(G, 0, 1))
980
+ [2, 3, 4]
981
+ """
982
+ if u not in G:
983
+ raise nx.NetworkXError("u is not in the graph.")
984
+ if v not in G:
985
+ raise nx.NetworkXError("v is not in the graph.")
986
+
987
+ return G._adj[u].keys() & G._adj[v].keys() - {u, v}
988
+
989
+
990
+ def is_weighted(G, edge=None, weight="weight"):
991
+ """Returns True if `G` has weighted edges.
992
+
993
+ Parameters
994
+ ----------
995
+ G : graph
996
+ A NetworkX graph.
997
+
998
+ edge : tuple, optional
999
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1000
+ None, then every edge in `G` is tested.
1001
+
1002
+ weight: string, optional
1003
+ The attribute name used to query for edge weights.
1004
+
1005
+ Returns
1006
+ -------
1007
+ bool
1008
+ A boolean signifying if `G`, or the specified edge, is weighted.
1009
+
1010
+ Raises
1011
+ ------
1012
+ NetworkXError
1013
+ If the specified edge does not exist.
1014
+
1015
+ Examples
1016
+ --------
1017
+ >>> G = nx.path_graph(4)
1018
+ >>> nx.is_weighted(G)
1019
+ False
1020
+ >>> nx.is_weighted(G, (2, 3))
1021
+ False
1022
+
1023
+ >>> G = nx.DiGraph()
1024
+ >>> G.add_edge(1, 2, weight=1)
1025
+ >>> nx.is_weighted(G)
1026
+ True
1027
+
1028
+ """
1029
+ if edge is not None:
1030
+ data = G.get_edge_data(*edge)
1031
+ if data is None:
1032
+ msg = f"Edge {edge!r} does not exist."
1033
+ raise nx.NetworkXError(msg)
1034
+ return weight in data
1035
+
1036
+ if is_empty(G):
1037
+ # Special handling required since: all([]) == True
1038
+ return False
1039
+
1040
+ return all(weight in data for u, v, data in G.edges(data=True))
1041
+
1042
+
1043
+ @nx._dispatchable(edge_attrs="weight")
1044
+ def is_negatively_weighted(G, edge=None, weight="weight"):
1045
+ """Returns True if `G` has negatively weighted edges.
1046
+
1047
+ Parameters
1048
+ ----------
1049
+ G : graph
1050
+ A NetworkX graph.
1051
+
1052
+ edge : tuple, optional
1053
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1054
+ None, then every edge in `G` is tested.
1055
+
1056
+ weight: string, optional
1057
+ The attribute name used to query for edge weights.
1058
+
1059
+ Returns
1060
+ -------
1061
+ bool
1062
+ A boolean signifying if `G`, or the specified edge, is negatively
1063
+ weighted.
1064
+
1065
+ Raises
1066
+ ------
1067
+ NetworkXError
1068
+ If the specified edge does not exist.
1069
+
1070
+ Examples
1071
+ --------
1072
+ >>> G = nx.Graph()
1073
+ >>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
1074
+ >>> G.add_edge(1, 2, weight=4)
1075
+ >>> nx.is_negatively_weighted(G, (1, 2))
1076
+ False
1077
+ >>> G[2][4]["weight"] = -2
1078
+ >>> nx.is_negatively_weighted(G)
1079
+ True
1080
+ >>> G = nx.DiGraph()
1081
+ >>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)]
1082
+ >>> G.add_weighted_edges_from(edges)
1083
+ >>> nx.is_negatively_weighted(G)
1084
+ True
1085
+
1086
+ """
1087
+ if edge is not None:
1088
+ data = G.get_edge_data(*edge)
1089
+ if data is None:
1090
+ msg = f"Edge {edge!r} does not exist."
1091
+ raise nx.NetworkXError(msg)
1092
+ return weight in data and data[weight] < 0
1093
+
1094
+ return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
1095
+
1096
+
1097
+ def is_empty(G):
1098
+ """Returns True if `G` has no edges.
1099
+
1100
+ Parameters
1101
+ ----------
1102
+ G : graph
1103
+ A NetworkX graph.
1104
+
1105
+ Returns
1106
+ -------
1107
+ bool
1108
+ True if `G` has no edges, and False otherwise.
1109
+
1110
+ Notes
1111
+ -----
1112
+ An empty graph can have nodes but not edges. The empty graph with zero
1113
+ nodes is known as the null graph. This is an $O(n)$ operation where n
1114
+ is the number of nodes in the graph.
1115
+
1116
+ """
1117
+ return not any(G._adj.values())
1118
+
1119
+
1120
+ def nodes_with_selfloops(G):
1121
+ """Returns an iterator over nodes with self loops.
1122
+
1123
+ A node with a self loop has an edge with both ends adjacent
1124
+ to that node.
1125
+
1126
+ Returns
1127
+ -------
1128
+ nodelist : iterator
1129
+ A iterator over nodes with self loops.
1130
+
1131
+ See Also
1132
+ --------
1133
+ selfloop_edges, number_of_selfloops
1134
+
1135
+ Examples
1136
+ --------
1137
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1138
+ >>> G.add_edge(1, 1)
1139
+ >>> G.add_edge(1, 2)
1140
+ >>> list(nx.nodes_with_selfloops(G))
1141
+ [1]
1142
+
1143
+ """
1144
+ return (n for n, nbrs in G._adj.items() if n in nbrs)
1145
+
1146
+
1147
+ def selfloop_edges(G, data=False, keys=False, default=None):
1148
+ """Returns an iterator over selfloop edges.
1149
+
1150
+ A selfloop edge has the same node at both ends.
1151
+
1152
+ Parameters
1153
+ ----------
1154
+ G : graph
1155
+ A NetworkX graph.
1156
+ data : string or bool, optional (default=False)
1157
+ Return selfloop edges as two tuples (u, v) (data=False)
1158
+ or three-tuples (u, v, datadict) (data=True)
1159
+ or three-tuples (u, v, datavalue) (data='attrname')
1160
+ keys : bool, optional (default=False)
1161
+ If True, return edge keys with each edge.
1162
+ default : value, optional (default=None)
1163
+ Value used for edges that don't have the requested attribute.
1164
+ Only relevant if data is not True or False.
1165
+
1166
+ Returns
1167
+ -------
1168
+ edgeiter : iterator over edge tuples
1169
+ An iterator over all selfloop edges.
1170
+
1171
+ See Also
1172
+ --------
1173
+ nodes_with_selfloops, number_of_selfloops
1174
+
1175
+ Examples
1176
+ --------
1177
+ >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc
1178
+ >>> ekey = G.add_edge(1, 1)
1179
+ >>> ekey = G.add_edge(1, 2)
1180
+ >>> list(nx.selfloop_edges(G))
1181
+ [(1, 1)]
1182
+ >>> list(nx.selfloop_edges(G, data=True))
1183
+ [(1, 1, {})]
1184
+ >>> list(nx.selfloop_edges(G, keys=True))
1185
+ [(1, 1, 0)]
1186
+ >>> list(nx.selfloop_edges(G, keys=True, data=True))
1187
+ [(1, 1, 0, {})]
1188
+ """
1189
+ if data is True:
1190
+ if G.is_multigraph():
1191
+ if keys is True:
1192
+ return (
1193
+ (n, n, k, d)
1194
+ for n, nbrs in G._adj.items()
1195
+ if n in nbrs
1196
+ for k, d in nbrs[n].items()
1197
+ )
1198
+ else:
1199
+ return (
1200
+ (n, n, d)
1201
+ for n, nbrs in G._adj.items()
1202
+ if n in nbrs
1203
+ for d in nbrs[n].values()
1204
+ )
1205
+ else:
1206
+ return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs)
1207
+ elif data is not False:
1208
+ if G.is_multigraph():
1209
+ if keys is True:
1210
+ return (
1211
+ (n, n, k, d.get(data, default))
1212
+ for n, nbrs in G._adj.items()
1213
+ if n in nbrs
1214
+ for k, d in nbrs[n].items()
1215
+ )
1216
+ else:
1217
+ return (
1218
+ (n, n, d.get(data, default))
1219
+ for n, nbrs in G._adj.items()
1220
+ if n in nbrs
1221
+ for d in nbrs[n].values()
1222
+ )
1223
+ else:
1224
+ return (
1225
+ (n, n, nbrs[n].get(data, default))
1226
+ for n, nbrs in G._adj.items()
1227
+ if n in nbrs
1228
+ )
1229
+ else:
1230
+ if G.is_multigraph():
1231
+ if keys is True:
1232
+ return (
1233
+ (n, n, k)
1234
+ for n, nbrs in G._adj.items()
1235
+ if n in nbrs
1236
+ for k in nbrs[n]
1237
+ )
1238
+ else:
1239
+ return (
1240
+ (n, n)
1241
+ for n, nbrs in G._adj.items()
1242
+ if n in nbrs
1243
+ for i in range(len(nbrs[n])) # for easy edge removal (#4068)
1244
+ )
1245
+ else:
1246
+ return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
1247
+
1248
+
1249
+ def number_of_selfloops(G):
1250
+ """Returns the number of selfloop edges.
1251
+
1252
+ A selfloop edge has the same node at both ends.
1253
+
1254
+ Returns
1255
+ -------
1256
+ nloops : int
1257
+ The number of selfloops.
1258
+
1259
+ See Also
1260
+ --------
1261
+ nodes_with_selfloops, selfloop_edges
1262
+
1263
+ Examples
1264
+ --------
1265
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1266
+ >>> G.add_edge(1, 1)
1267
+ >>> G.add_edge(1, 2)
1268
+ >>> nx.number_of_selfloops(G)
1269
+ 1
1270
+ """
1271
+ return sum(1 for _ in nx.selfloop_edges(G))
1272
+
1273
+
1274
+ def is_path(G, path):
1275
+ """Returns whether or not the specified path exists.
1276
+
1277
+ For it to return True, every node on the path must exist and
1278
+ each consecutive pair must be connected via one or more edges.
1279
+
1280
+ Parameters
1281
+ ----------
1282
+ G : graph
1283
+ A NetworkX graph.
1284
+
1285
+ path : list
1286
+ A list of nodes which defines the path to traverse
1287
+
1288
+ Returns
1289
+ -------
1290
+ bool
1291
+ True if `path` is a valid path in `G`
1292
+
1293
+ """
1294
+ try:
1295
+ return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path))
1296
+ except (KeyError, TypeError):
1297
+ return False
1298
+
1299
+
1300
+ def path_weight(G, path, weight):
1301
+ """Returns total cost associated with specified path and weight
1302
+
1303
+ Parameters
1304
+ ----------
1305
+ G : graph
1306
+ A NetworkX graph.
1307
+
1308
+ path: list
1309
+ A list of node labels which defines the path to traverse
1310
+
1311
+ weight: string
1312
+ A string indicating which edge attribute to use for path cost
1313
+
1314
+ Returns
1315
+ -------
1316
+ cost: int or float
1317
+ An integer or a float representing the total cost with respect to the
1318
+ specified weight of the specified path
1319
+
1320
+ Raises
1321
+ ------
1322
+ NetworkXNoPath
1323
+ If the specified edge does not exist.
1324
+ """
1325
+ multigraph = G.is_multigraph()
1326
+ cost = 0
1327
+
1328
+ if not nx.is_path(G, path):
1329
+ raise nx.NetworkXNoPath("path does not exist")
1330
+ for node, nbr in nx.utils.pairwise(path):
1331
+ if multigraph:
1332
+ cost += min(v[weight] for v in G._adj[node][nbr].values())
1333
+ else:
1334
+ cost += G._adj[node][nbr][weight]
1335
+ return cost
llmeval-env/lib/python3.10/site-packages/networkx/classes/graphviews.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """View of Graphs as SubGraph, Reverse, Directed, Undirected.
2
+
3
+ In some algorithms it is convenient to temporarily morph
4
+ a graph to exclude some nodes or edges. It should be better
5
+ to do that via a view than to remove and then re-add.
6
+ In other algorithms it is convenient to temporarily morph
7
+ a graph to reverse directed edges, or treat a directed graph
8
+ as undirected, etc. This module provides those graph views.
9
+
10
+ The resulting views are essentially read-only graphs that
11
+ report data from the original graph object. We provide an
12
+ attribute G._graph which points to the underlying graph object.
13
+
14
+ Note: Since graphviews look like graphs, one can end up with
15
+ view-of-view-of-view chains. Be careful with chains because
16
+ they become very slow with about 15 nested views.
17
+ For the common simple case of node induced subgraphs created
18
+ from the graph class, we short-cut the chain by returning a
19
+ subgraph of the original graph directly rather than a subgraph
20
+ of a subgraph. We are careful not to disrupt any edge filter in
21
+ the middle subgraph. In general, determining how to short-cut
22
+ the chain is tricky and much harder with restricted_views than
23
+ with induced subgraphs.
24
+ Often it is easiest to use .copy() to avoid chains.
25
+ """
26
+ import networkx as nx
27
+ from networkx.classes.coreviews import (
28
+ FilterAdjacency,
29
+ FilterAtlas,
30
+ FilterMultiAdjacency,
31
+ UnionAdjacency,
32
+ UnionMultiAdjacency,
33
+ )
34
+ from networkx.classes.filters import no_filter
35
+ from networkx.exception import NetworkXError
36
+ from networkx.utils import deprecate_positional_args, not_implemented_for
37
+
38
+ __all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
39
+
40
+
41
+ def generic_graph_view(G, create_using=None):
42
+ """Returns a read-only view of `G`.
43
+
44
+ The graph `G` and its attributes are not copied but viewed through the new graph object
45
+ of the same class as `G` (or of the class specified in `create_using`).
46
+
47
+ Parameters
48
+ ----------
49
+ G : graph
50
+ A directed/undirected graph/multigraph.
51
+
52
+ create_using : NetworkX graph constructor, optional (default=None)
53
+ Graph type to create. If graph instance, then cleared before populated.
54
+ If `None`, then the appropriate Graph type is inferred from `G`.
55
+
56
+ Returns
57
+ -------
58
+ newG : graph
59
+ A view of the input graph `G` and its attributes as viewed through
60
+ the `create_using` class.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXError
65
+ If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
66
+
67
+ Notes
68
+ -----
69
+ The returned graph view is read-only (cannot modify the graph).
70
+ Yet the view reflects any changes in `G`. The intent is to mimic dict views.
71
+
72
+ Examples
73
+ --------
74
+ >>> G = nx.Graph()
75
+ >>> G.add_edge(1, 2, weight=0.3)
76
+ >>> G.add_edge(2, 3, weight=0.5)
77
+ >>> G.edges(data=True)
78
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
79
+
80
+ The view exposes the attributes from the original graph.
81
+
82
+ >>> viewG = nx.graphviews.generic_graph_view(G)
83
+ >>> viewG.edges(data=True)
84
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
85
+
86
+ Changes to `G` are reflected in `viewG`.
87
+
88
+ >>> G.remove_edge(2, 3)
89
+ >>> G.edges(data=True)
90
+ EdgeDataView([(1, 2, {'weight': 0.3})])
91
+
92
+ >>> viewG.edges(data=True)
93
+ EdgeDataView([(1, 2, {'weight': 0.3})])
94
+
95
+ We can change the graph type with the `create_using` parameter.
96
+
97
+ >>> type(G)
98
+ <class 'networkx.classes.graph.Graph'>
99
+ >>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph)
100
+ >>> type(viewDG)
101
+ <class 'networkx.classes.digraph.DiGraph'>
102
+ """
103
+ if create_using is None:
104
+ newG = G.__class__()
105
+ else:
106
+ newG = nx.empty_graph(0, create_using)
107
+ if G.is_multigraph() != newG.is_multigraph():
108
+ raise NetworkXError("Multigraph for G must agree with create_using")
109
+ newG = nx.freeze(newG)
110
+
111
+ # create view by assigning attributes from G
112
+ newG._graph = G
113
+ newG.graph = G.graph
114
+
115
+ newG._node = G._node
116
+ if newG.is_directed():
117
+ if G.is_directed():
118
+ newG._succ = G._succ
119
+ newG._pred = G._pred
120
+ # newG._adj is synced with _succ
121
+ else:
122
+ newG._succ = G._adj
123
+ newG._pred = G._adj
124
+ # newG._adj is synced with _succ
125
+ elif G.is_directed():
126
+ if G.is_multigraph():
127
+ newG._adj = UnionMultiAdjacency(G._succ, G._pred)
128
+ else:
129
+ newG._adj = UnionAdjacency(G._succ, G._pred)
130
+ else:
131
+ newG._adj = G._adj
132
+ return newG
133
+
134
+
135
+ @deprecate_positional_args(version="3.4")
136
+ def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter):
137
+ """View of `G` applying a filter on nodes and edges.
138
+
139
+ `subgraph_view` provides a read-only view of the input graph that excludes
140
+ nodes and edges based on the outcome of two filter functions `filter_node`
141
+ and `filter_edge`.
142
+
143
+ The `filter_node` function takes one argument --- the node --- and returns
144
+ `True` if the node should be included in the subgraph, and `False` if it
145
+ should not be included.
146
+
147
+ The `filter_edge` function takes two (or three arguments if `G` is a
148
+ multi-graph) --- the nodes describing an edge, plus the edge-key if
149
+ parallel edges are possible --- and returns `True` if the edge should be
150
+ included in the subgraph, and `False` if it should not be included.
151
+
152
+ Both node and edge filter functions are called on graph elements as they
153
+ are queried, meaning there is no up-front cost to creating the view.
154
+
155
+ Parameters
156
+ ----------
157
+ G : networkx.Graph
158
+ A directed/undirected graph/multigraph
159
+
160
+ filter_node : callable, optional
161
+ A function taking a node as input, which returns `True` if the node
162
+ should appear in the view.
163
+
164
+ filter_edge : callable, optional
165
+ A function taking as input the two nodes describing an edge (plus the
166
+ edge-key if `G` is a multi-graph), which returns `True` if the edge
167
+ should appear in the view.
168
+
169
+ Returns
170
+ -------
171
+ graph : networkx.Graph
172
+ A read-only graph view of the input graph.
173
+
174
+ Examples
175
+ --------
176
+ >>> G = nx.path_graph(6)
177
+
178
+ Filter functions operate on the node, and return `True` if the node should
179
+ appear in the view:
180
+
181
+ >>> def filter_node(n1):
182
+ ... return n1 != 5
183
+ >>> view = nx.subgraph_view(G, filter_node=filter_node)
184
+ >>> view.nodes()
185
+ NodeView((0, 1, 2, 3, 4))
186
+
187
+ We can use a closure pattern to filter graph elements based on additional
188
+ data --- for example, filtering on edge data attached to the graph:
189
+
190
+ >>> G[3][4]["cross_me"] = False
191
+ >>> def filter_edge(n1, n2):
192
+ ... return G[n1][n2].get("cross_me", True)
193
+ >>> view = nx.subgraph_view(G, filter_edge=filter_edge)
194
+ >>> view.edges()
195
+ EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
196
+
197
+ >>> view = nx.subgraph_view(
198
+ ... G,
199
+ ... filter_node=filter_node,
200
+ ... filter_edge=filter_edge,
201
+ ... )
202
+ >>> view.nodes()
203
+ NodeView((0, 1, 2, 3, 4))
204
+ >>> view.edges()
205
+ EdgeView([(0, 1), (1, 2), (2, 3)])
206
+ """
207
+ newG = nx.freeze(G.__class__())
208
+ newG._NODE_OK = filter_node
209
+ newG._EDGE_OK = filter_edge
210
+
211
+ # create view by assigning attributes from G
212
+ newG._graph = G
213
+ newG.graph = G.graph
214
+
215
+ newG._node = FilterAtlas(G._node, filter_node)
216
+ if G.is_multigraph():
217
+ Adj = FilterMultiAdjacency
218
+
219
+ def reverse_edge(u, v, k=None):
220
+ return filter_edge(v, u, k)
221
+
222
+ else:
223
+ Adj = FilterAdjacency
224
+
225
+ def reverse_edge(u, v, k=None):
226
+ return filter_edge(v, u)
227
+
228
+ if G.is_directed():
229
+ newG._succ = Adj(G._succ, filter_node, filter_edge)
230
+ newG._pred = Adj(G._pred, filter_node, reverse_edge)
231
+ # newG._adj is synced with _succ
232
+ else:
233
+ newG._adj = Adj(G._adj, filter_node, filter_edge)
234
+ return newG
235
+
236
+
237
+ @not_implemented_for("undirected")
238
+ def reverse_view(G):
239
+ """View of `G` with edge directions reversed
240
+
241
+ `reverse_view` returns a read-only view of the input graph where
242
+ edge directions are reversed.
243
+
244
+ Identical to digraph.reverse(copy=False)
245
+
246
+ Parameters
247
+ ----------
248
+ G : networkx.DiGraph
249
+
250
+ Returns
251
+ -------
252
+ graph : networkx.DiGraph
253
+
254
+ Examples
255
+ --------
256
+ >>> G = nx.DiGraph()
257
+ >>> G.add_edge(1, 2)
258
+ >>> G.add_edge(2, 3)
259
+ >>> G.edges()
260
+ OutEdgeView([(1, 2), (2, 3)])
261
+
262
+ >>> view = nx.reverse_view(G)
263
+ >>> view.edges()
264
+ OutEdgeView([(2, 1), (3, 2)])
265
+ """
266
+ newG = generic_graph_view(G)
267
+ newG._succ, newG._pred = G._pred, G._succ
268
+ # newG._adj is synced with _succ
269
+ return newG
llmeval-env/lib/python3.10/site-packages/networkx/classes/multigraph.py ADDED
@@ -0,0 +1,1282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiGraph."""
2
+ from copy import deepcopy
3
+ from functools import cached_property
4
+
5
+ import networkx as nx
6
+ from networkx import NetworkXError, convert
7
+ from networkx.classes.coreviews import MultiAdjacencyView
8
+ from networkx.classes.graph import Graph
9
+ from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
10
+
11
+ __all__ = ["MultiGraph"]
12
+
13
+
14
+ class MultiGraph(Graph):
15
+ """
16
+ An undirected graph class that can store multiedges.
17
+
18
+ Multiedges are multiple edges between two nodes. Each edge
19
+ can hold optional data or attributes.
20
+
21
+ A MultiGraph holds undirected edges. Self loops are allowed.
22
+
23
+ Nodes can be arbitrary (hashable) Python objects with optional
24
+ key/value attributes. By convention `None` is not used as a node.
25
+
26
+ Edges are represented as links between nodes with optional
27
+ key/value attributes, in a MultiGraph each edge has a key to
28
+ distinguish between multiple edges that have the same source and
29
+ destination nodes.
30
+
31
+ Parameters
32
+ ----------
33
+ incoming_graph_data : input graph (optional, default: None)
34
+ Data to initialize graph. If None (default) an empty
35
+ graph is created. The data can be any format that is supported
36
+ by the to_networkx_graph() function, currently including edge list,
37
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
38
+ SciPy sparse array, or PyGraphviz graph.
39
+
40
+ multigraph_input : bool or None (default None)
41
+ Note: Only used when `incoming_graph_data` is a dict.
42
+ If True, `incoming_graph_data` is assumed to be a
43
+ dict-of-dict-of-dict-of-dict structure keyed by
44
+ node to neighbor to edge keys to edge data for multi-edges.
45
+ A NetworkXError is raised if this is not the case.
46
+ If False, :func:`to_networkx_graph` is used to try to determine
47
+ the dict's graph data structure as either a dict-of-dict-of-dict
48
+ keyed by node to neighbor to edge data, or a dict-of-iterable
49
+ keyed by node to neighbors.
50
+ If None, the treatment for True is tried, but if it fails,
51
+ the treatment for False is tried.
52
+
53
+ attr : keyword arguments, optional (default= no attributes)
54
+ Attributes to add to graph as key=value pairs.
55
+
56
+ See Also
57
+ --------
58
+ Graph
59
+ DiGraph
60
+ MultiDiGraph
61
+
62
+ Examples
63
+ --------
64
+ Create an empty graph structure (a "null graph") with no nodes and
65
+ no edges.
66
+
67
+ >>> G = nx.MultiGraph()
68
+
69
+ G can be grown in several ways.
70
+
71
+ **Nodes:**
72
+
73
+ Add one node at a time:
74
+
75
+ >>> G.add_node(1)
76
+
77
+ Add the nodes from any container (a list, dict, set or
78
+ even the lines from a file or the nodes from another graph).
79
+
80
+ >>> G.add_nodes_from([2, 3])
81
+ >>> G.add_nodes_from(range(100, 110))
82
+ >>> H = nx.path_graph(10)
83
+ >>> G.add_nodes_from(H)
84
+
85
+ In addition to strings and integers any hashable Python object
86
+ (except None) can represent a node, e.g. a customized node object,
87
+ or even another Graph.
88
+
89
+ >>> G.add_node(H)
90
+
91
+ **Edges:**
92
+
93
+ G can also be grown by adding edges.
94
+
95
+ Add one edge,
96
+
97
+ >>> key = G.add_edge(1, 2)
98
+
99
+ a list of edges,
100
+
101
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
102
+
103
+ or a collection of edges,
104
+
105
+ >>> keys = G.add_edges_from(H.edges)
106
+
107
+ If some edges connect nodes not yet in the graph, the nodes
108
+ are added automatically. If an edge already exists, an additional
109
+ edge is created and stored using a key to identify the edge.
110
+ By default the key is the lowest unused integer.
111
+
112
+ >>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
113
+ >>> G[4]
114
+ AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
115
+
116
+ **Attributes:**
117
+
118
+ Each graph, node, and edge can hold key/value attribute pairs
119
+ in an associated attribute dictionary (the keys must be hashable).
120
+ By default these are empty, but can be added or changed using
121
+ add_edge, add_node or direct manipulation of the attribute
122
+ dictionaries named graph, node and edge respectively.
123
+
124
+ >>> G = nx.MultiGraph(day="Friday")
125
+ >>> G.graph
126
+ {'day': 'Friday'}
127
+
128
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
129
+
130
+ >>> G.add_node(1, time="5pm")
131
+ >>> G.add_nodes_from([3], time="2pm")
132
+ >>> G.nodes[1]
133
+ {'time': '5pm'}
134
+ >>> G.nodes[1]["room"] = 714
135
+ >>> del G.nodes[1]["room"] # remove attribute
136
+ >>> list(G.nodes(data=True))
137
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
138
+
139
+ Add edge attributes using add_edge(), add_edges_from(), subscript
140
+ notation, or G.edges.
141
+
142
+ >>> key = G.add_edge(1, 2, weight=4.7)
143
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
144
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
145
+ >>> G[1][2][0]["weight"] = 4.7
146
+ >>> G.edges[1, 2, 0]["weight"] = 4
147
+
148
+ Warning: we protect the graph data structure by making `G.edges[1,
149
+ 2, 0]` a read-only dict-like structure. However, you can assign to
150
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
151
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
152
+
153
+ **Shortcuts:**
154
+
155
+ Many common graph features allow python syntax to speed reporting.
156
+
157
+ >>> 1 in G # check if node in graph
158
+ True
159
+ >>> [n for n in G if n < 3] # iterate through nodes
160
+ [1, 2]
161
+ >>> len(G) # number of nodes in graph
162
+ 5
163
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
164
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
165
+
166
+ Often the best way to traverse all edges of a graph is via the neighbors.
167
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
168
+
169
+ >>> for n, nbrsdict in G.adjacency():
170
+ ... for nbr, keydict in nbrsdict.items():
171
+ ... for key, eattr in keydict.items():
172
+ ... if "weight" in eattr:
173
+ ... # Do something useful with the edges
174
+ ... pass
175
+
176
+ But the edges() method is often more convenient:
177
+
178
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
179
+ ... if weight is not None:
180
+ ... # Do something useful with the edges
181
+ ... pass
182
+
183
+ **Reporting:**
184
+
185
+ Simple graph information is obtained using methods and object-attributes.
186
+ Reporting usually provides views instead of containers to reduce memory
187
+ usage. The views update as the graph is updated similarly to dict-views.
188
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
189
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
190
+ (e.g. `nodes.items()`, `nodes.data('color')`,
191
+ `nodes.data('color', default='blue')` and similarly for `edges`)
192
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
193
+
194
+ For details on these and other miscellaneous methods, see below.
195
+
196
+ **Subclasses (Advanced):**
197
+
198
+ The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
199
+ The outer dict (node_dict) holds adjacency information keyed by node.
200
+ The next dict (adjlist_dict) represents the adjacency information
201
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
202
+ each edge_attr dict keyed by edge key. The inner dict
203
+ (edge_attr_dict) represents the edge data and holds edge attribute
204
+ values keyed by attribute names.
205
+
206
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
207
+ structure can be replaced by a user defined dict-like object.
208
+ In general, the dict-like features should be maintained but
209
+ extra features can be added. To replace one of the dicts create
210
+ a new graph class by changing the class(!) variable holding the
211
+ factory for that dict-like structure. The variable names are
212
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
213
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
214
+ and graph_attr_dict_factory.
215
+
216
+ node_dict_factory : function, (default: dict)
217
+ Factory function to be used to create the dict containing node
218
+ attributes, keyed by node id.
219
+ It should require no arguments and return a dict-like object
220
+
221
+ node_attr_dict_factory: function, (default: dict)
222
+ Factory function to be used to create the node attribute
223
+ dict which holds attribute values keyed by attribute name.
224
+ It should require no arguments and return a dict-like object
225
+
226
+ adjlist_outer_dict_factory : function, (default: dict)
227
+ Factory function to be used to create the outer-most dict
228
+ in the data structure that holds adjacency info keyed by node.
229
+ It should require no arguments and return a dict-like object.
230
+
231
+ adjlist_inner_dict_factory : function, (default: dict)
232
+ Factory function to be used to create the adjacency list
233
+ dict which holds multiedge key dicts keyed by neighbor.
234
+ It should require no arguments and return a dict-like object.
235
+
236
+ edge_key_dict_factory : function, (default: dict)
237
+ Factory function to be used to create the edge key dict
238
+ which holds edge data keyed by edge key.
239
+ It should require no arguments and return a dict-like object.
240
+
241
+ edge_attr_dict_factory : function, (default: dict)
242
+ Factory function to be used to create the edge attribute
243
+ dict which holds attribute values keyed by attribute name.
244
+ It should require no arguments and return a dict-like object.
245
+
246
+ graph_attr_dict_factory : function, (default: dict)
247
+ Factory function to be used to create the graph attribute
248
+ dict which holds attribute values keyed by attribute name.
249
+ It should require no arguments and return a dict-like object.
250
+
251
+ Typically, if your extension doesn't impact the data structure all
252
+ methods will inherited without issue except: `to_directed/to_undirected`.
253
+ By default these methods create a DiGraph/Graph class and you probably
254
+ want them to create your extension of a DiGraph/Graph. To facilitate
255
+ this we define two class variables that you can set in your subclass.
256
+
257
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
258
+ Class to create a new graph structure in the `to_directed` method.
259
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
260
+
261
+ to_undirected_class : callable, (default: Graph or MultiGraph)
262
+ Class to create a new graph structure in the `to_undirected` method.
263
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
264
+
265
+ **Subclassing Example**
266
+
267
+ Create a low memory graph class that effectively disallows edge
268
+ attributes by using a single attribute dict for all edges.
269
+ This reduces the memory used, but you lose edge attributes.
270
+
271
+ >>> class ThinGraph(nx.Graph):
272
+ ... all_edge_dict = {"weight": 1}
273
+ ...
274
+ ... def single_edge_dict(self):
275
+ ... return self.all_edge_dict
276
+ ...
277
+ ... edge_attr_dict_factory = single_edge_dict
278
+ >>> G = ThinGraph()
279
+ >>> G.add_edge(2, 1)
280
+ >>> G[2][1]
281
+ {'weight': 1}
282
+ >>> G.add_edge(2, 2)
283
+ >>> G[2][1] is G[2][2]
284
+ True
285
+ """
286
+
287
+ # node_dict_factory = dict # already assigned in Graph
288
+ # adjlist_outer_dict_factory = dict
289
+ # adjlist_inner_dict_factory = dict
290
+ edge_key_dict_factory = dict
291
+ # edge_attr_dict_factory = dict
292
+
293
+ def to_directed_class(self):
294
+ """Returns the class to use for empty directed copies.
295
+
296
+ If you subclass the base classes, use this to designate
297
+ what directed class to use for `to_directed()` copies.
298
+ """
299
+ return nx.MultiDiGraph
300
+
301
+ def to_undirected_class(self):
302
+ """Returns the class to use for empty undirected copies.
303
+
304
+ If you subclass the base classes, use this to designate
305
+ what directed class to use for `to_directed()` copies.
306
+ """
307
+ return MultiGraph
308
+
309
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
310
+ """Initialize a graph with edges, name, or graph attributes.
311
+
312
+ Parameters
313
+ ----------
314
+ incoming_graph_data : input graph
315
+ Data to initialize graph. If incoming_graph_data=None (default)
316
+ an empty graph is created. The data can be an edge list, or any
317
+ NetworkX graph object. If the corresponding optional Python
318
+ packages are installed the data can also be a 2D NumPy array, a
319
+ SciPy sparse array, or a PyGraphviz graph.
320
+
321
+ multigraph_input : bool or None (default None)
322
+ Note: Only used when `incoming_graph_data` is a dict.
323
+ If True, `incoming_graph_data` is assumed to be a
324
+ dict-of-dict-of-dict-of-dict structure keyed by
325
+ node to neighbor to edge keys to edge data for multi-edges.
326
+ A NetworkXError is raised if this is not the case.
327
+ If False, :func:`to_networkx_graph` is used to try to determine
328
+ the dict's graph data structure as either a dict-of-dict-of-dict
329
+ keyed by node to neighbor to edge data, or a dict-of-iterable
330
+ keyed by node to neighbors.
331
+ If None, the treatment for True is tried, but if it fails,
332
+ the treatment for False is tried.
333
+
334
+ attr : keyword arguments, optional (default= no attributes)
335
+ Attributes to add to graph as key=value pairs.
336
+
337
+ See Also
338
+ --------
339
+ convert
340
+
341
+ Examples
342
+ --------
343
+ >>> G = nx.MultiGraph()
344
+ >>> G = nx.MultiGraph(name="my graph")
345
+ >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
346
+ >>> G = nx.MultiGraph(e)
347
+
348
+ Arbitrary graph attribute pairs (key=value) may be assigned
349
+
350
+ >>> G = nx.MultiGraph(e, day="Friday")
351
+ >>> G.graph
352
+ {'day': 'Friday'}
353
+
354
+ """
355
+ # multigraph_input can be None/True/False. So check "is not False"
356
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
357
+ Graph.__init__(self)
358
+ try:
359
+ convert.from_dict_of_dicts(
360
+ incoming_graph_data, create_using=self, multigraph_input=True
361
+ )
362
+ self.graph.update(attr)
363
+ except Exception as err:
364
+ if multigraph_input is True:
365
+ raise nx.NetworkXError(
366
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
367
+ )
368
+ Graph.__init__(self, incoming_graph_data, **attr)
369
+ else:
370
+ Graph.__init__(self, incoming_graph_data, **attr)
371
+
372
+ @cached_property
373
+ def adj(self):
374
+ """Graph adjacency object holding the neighbors of each node.
375
+
376
+ This object is a read-only dict-like structure with node keys
377
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
378
+ to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
379
+ the color of the edge `(3, 2, 0)` to `"blue"`.
380
+
381
+ Iterating over G.adj behaves like a dict. Useful idioms include
382
+ `for nbr, edgesdict in G.adj[n].items():`.
383
+
384
+ The neighbor information is also provided by subscripting the graph.
385
+
386
+ Examples
387
+ --------
388
+ >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
389
+ >>> G = nx.MultiGraph(e)
390
+ >>> G.edges[1, 2, 0]["weight"] = 3
391
+ >>> result = set()
392
+ >>> for edgekey, data in G[1][2].items():
393
+ ... result.add(data.get("weight", 1))
394
+ >>> result
395
+ {1, 3}
396
+
397
+ For directed graphs, `G.adj` holds outgoing (successor) info.
398
+ """
399
+ return MultiAdjacencyView(self._adj)
400
+
401
+ def new_edge_key(self, u, v):
402
+ """Returns an unused key for edges between nodes `u` and `v`.
403
+
404
+ The nodes `u` and `v` do not need to be already in the graph.
405
+
406
+ Notes
407
+ -----
408
+ In the standard MultiGraph class the new key is the number of existing
409
+ edges between `u` and `v` (increased if necessary to ensure unused).
410
+ The first edge will have key 0, then 1, etc. If an edge is removed
411
+ further new_edge_keys may not be in this order.
412
+
413
+ Parameters
414
+ ----------
415
+ u, v : nodes
416
+
417
+ Returns
418
+ -------
419
+ key : int
420
+ """
421
+ try:
422
+ keydict = self._adj[u][v]
423
+ except KeyError:
424
+ return 0
425
+ key = len(keydict)
426
+ while key in keydict:
427
+ key += 1
428
+ return key
429
+
430
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
431
+ """Add an edge between u and v.
432
+
433
+ The nodes u and v will be automatically added if they are
434
+ not already in the graph.
435
+
436
+ Edge attributes can be specified with keywords or by directly
437
+ accessing the edge's attribute dictionary. See examples below.
438
+
439
+ Parameters
440
+ ----------
441
+ u_for_edge, v_for_edge : nodes
442
+ Nodes can be, for example, strings or numbers.
443
+ Nodes must be hashable (and not None) Python objects.
444
+ key : hashable identifier, optional (default=lowest unused integer)
445
+ Used to distinguish multiedges between a pair of nodes.
446
+ attr : keyword arguments, optional
447
+ Edge data (or labels or objects) can be assigned using
448
+ keyword arguments.
449
+
450
+ Returns
451
+ -------
452
+ The edge key assigned to the edge.
453
+
454
+ See Also
455
+ --------
456
+ add_edges_from : add a collection of edges
457
+
458
+ Notes
459
+ -----
460
+ To replace/update edge data, use the optional key argument
461
+ to identify a unique edge. Otherwise a new edge will be created.
462
+
463
+ NetworkX algorithms designed for weighted graphs cannot use
464
+ multigraphs directly because it is not clear how to handle
465
+ multiedge weights. Convert to Graph using edge attribute
466
+ 'weight' to enable weighted graph algorithms.
467
+
468
+ Default keys are generated using the method `new_edge_key()`.
469
+ This method can be overridden by subclassing the base class and
470
+ providing a custom `new_edge_key()` method.
471
+
472
+ Examples
473
+ --------
474
+ The following each add an additional edge e=(1, 2) to graph G:
475
+
476
+ >>> G = nx.MultiGraph()
477
+ >>> e = (1, 2)
478
+ >>> ekey = G.add_edge(1, 2) # explicit two-node form
479
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
480
+ 1
481
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
482
+ [2]
483
+
484
+ Associate data to edges using keywords:
485
+
486
+ >>> ekey = G.add_edge(1, 2, weight=3)
487
+ >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
488
+ >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
489
+
490
+ For non-string attribute keys, use subscript notation.
491
+
492
+ >>> ekey = G.add_edge(1, 2)
493
+ >>> G[1][2][0].update({0: 5})
494
+ >>> G.edges[1, 2, 0].update({0: 5})
495
+ """
496
+ u, v = u_for_edge, v_for_edge
497
+ # add nodes
498
+ if u not in self._adj:
499
+ if u is None:
500
+ raise ValueError("None cannot be a node")
501
+ self._adj[u] = self.adjlist_inner_dict_factory()
502
+ self._node[u] = self.node_attr_dict_factory()
503
+ if v not in self._adj:
504
+ if v is None:
505
+ raise ValueError("None cannot be a node")
506
+ self._adj[v] = self.adjlist_inner_dict_factory()
507
+ self._node[v] = self.node_attr_dict_factory()
508
+ if key is None:
509
+ key = self.new_edge_key(u, v)
510
+ if v in self._adj[u]:
511
+ keydict = self._adj[u][v]
512
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
513
+ datadict.update(attr)
514
+ keydict[key] = datadict
515
+ else:
516
+ # selfloops work this way without special treatment
517
+ datadict = self.edge_attr_dict_factory()
518
+ datadict.update(attr)
519
+ keydict = self.edge_key_dict_factory()
520
+ keydict[key] = datadict
521
+ self._adj[u][v] = keydict
522
+ self._adj[v][u] = keydict
523
+ nx._clear_cache(self)
524
+ return key
525
+
526
+ def add_edges_from(self, ebunch_to_add, **attr):
527
+ """Add all the edges in ebunch_to_add.
528
+
529
+ Parameters
530
+ ----------
531
+ ebunch_to_add : container of edges
532
+ Each edge given in the container will be added to the
533
+ graph. The edges can be:
534
+
535
+ - 2-tuples (u, v) or
536
+ - 3-tuples (u, v, d) for an edge data dict d, or
537
+ - 3-tuples (u, v, k) for not iterable key k, or
538
+ - 4-tuples (u, v, k, d) for an edge with data and key k
539
+
540
+ attr : keyword arguments, optional
541
+ Edge data (or labels or objects) can be assigned using
542
+ keyword arguments.
543
+
544
+ Returns
545
+ -------
546
+ A list of edge keys assigned to the edges in `ebunch`.
547
+
548
+ See Also
549
+ --------
550
+ add_edge : add a single edge
551
+ add_weighted_edges_from : convenient way to add weighted edges
552
+
553
+ Notes
554
+ -----
555
+ Adding the same edge twice has no effect but any edge data
556
+ will be updated when each duplicate edge is added.
557
+
558
+ Edge attributes specified in an ebunch take precedence over
559
+ attributes specified via keyword arguments.
560
+
561
+ Default keys are generated using the method ``new_edge_key()``.
562
+ This method can be overridden by subclassing the base class and
563
+ providing a custom ``new_edge_key()`` method.
564
+
565
+ When adding edges from an iterator over the graph you are changing,
566
+ a `RuntimeError` can be raised with message:
567
+ `RuntimeError: dictionary changed size during iteration`. This
568
+ happens when the graph's underlying dictionary is modified during
569
+ iteration. To avoid this error, evaluate the iterator into a separate
570
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
571
+ object to `G.add_edges_from`.
572
+
573
+ Examples
574
+ --------
575
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
576
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
577
+ >>> e = zip(range(0, 3), range(1, 4))
578
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
579
+
580
+ Associate data to edges
581
+
582
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
583
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
584
+
585
+ Evaluate an iterator over a graph if using it to modify the same graph
586
+
587
+ >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
588
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
589
+ >>> # wrong way - will raise RuntimeError
590
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
591
+ >>> # right way - note that there will be no self-edge for node 5
592
+ >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
593
+ """
594
+ keylist = []
595
+ for e in ebunch_to_add:
596
+ ne = len(e)
597
+ if ne == 4:
598
+ u, v, key, dd = e
599
+ elif ne == 3:
600
+ u, v, dd = e
601
+ key = None
602
+ elif ne == 2:
603
+ u, v = e
604
+ dd = {}
605
+ key = None
606
+ else:
607
+ msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
608
+ raise NetworkXError(msg)
609
+ ddd = {}
610
+ ddd.update(attr)
611
+ try:
612
+ ddd.update(dd)
613
+ except (TypeError, ValueError):
614
+ if ne != 3:
615
+ raise
616
+ key = dd # ne == 3 with 3rd value not dict, must be a key
617
+ key = self.add_edge(u, v, key)
618
+ self[u][v][key].update(ddd)
619
+ keylist.append(key)
620
+ nx._clear_cache(self)
621
+ return keylist
622
+
623
+ def remove_edge(self, u, v, key=None):
624
+ """Remove an edge between u and v.
625
+
626
+ Parameters
627
+ ----------
628
+ u, v : nodes
629
+ Remove an edge between nodes u and v.
630
+ key : hashable identifier, optional (default=None)
631
+ Used to distinguish multiple edges between a pair of nodes.
632
+ If None, remove a single edge between u and v. If there are
633
+ multiple edges, removes the last edge added in terms of
634
+ insertion order.
635
+
636
+ Raises
637
+ ------
638
+ NetworkXError
639
+ If there is not an edge between u and v, or
640
+ if there is no edge with the specified key.
641
+
642
+ See Also
643
+ --------
644
+ remove_edges_from : remove a collection of edges
645
+
646
+ Examples
647
+ --------
648
+ >>> G = nx.MultiGraph()
649
+ >>> nx.add_path(G, [0, 1, 2, 3])
650
+ >>> G.remove_edge(0, 1)
651
+ >>> e = (1, 2)
652
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
653
+
654
+ For multiple edges
655
+
656
+ >>> G = nx.MultiGraph() # or MultiDiGraph, etc
657
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
658
+ [0, 1, 2]
659
+
660
+ When ``key=None`` (the default), edges are removed in the opposite
661
+ order that they were added:
662
+
663
+ >>> G.remove_edge(1, 2)
664
+ >>> G.edges(keys=True)
665
+ MultiEdgeView([(1, 2, 0), (1, 2, 1)])
666
+ >>> G.remove_edge(2, 1) # edges are not directed
667
+ >>> G.edges(keys=True)
668
+ MultiEdgeView([(1, 2, 0)])
669
+
670
+ For edges with keys
671
+
672
+ >>> G = nx.MultiGraph()
673
+ >>> G.add_edge(1, 2, key="first")
674
+ 'first'
675
+ >>> G.add_edge(1, 2, key="second")
676
+ 'second'
677
+ >>> G.remove_edge(1, 2, key="first")
678
+ >>> G.edges(keys=True)
679
+ MultiEdgeView([(1, 2, 'second')])
680
+
681
+ """
682
+ try:
683
+ d = self._adj[u][v]
684
+ except KeyError as err:
685
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
686
+ # remove the edge with specified data
687
+ if key is None:
688
+ d.popitem()
689
+ else:
690
+ try:
691
+ del d[key]
692
+ except KeyError as err:
693
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
694
+ raise NetworkXError(msg) from err
695
+ if len(d) == 0:
696
+ # remove the key entries if last edge
697
+ del self._adj[u][v]
698
+ if u != v: # check for selfloop
699
+ del self._adj[v][u]
700
+ nx._clear_cache(self)
701
+
702
+ def remove_edges_from(self, ebunch):
703
+ """Remove all edges specified in ebunch.
704
+
705
+ Parameters
706
+ ----------
707
+ ebunch: list or container of edge tuples
708
+ Each edge given in the list or container will be removed
709
+ from the graph. The edges can be:
710
+
711
+ - 2-tuples (u, v) A single edge between u and v is removed.
712
+ - 3-tuples (u, v, key) The edge identified by key is removed.
713
+ - 4-tuples (u, v, key, data) where data is ignored.
714
+
715
+ See Also
716
+ --------
717
+ remove_edge : remove a single edge
718
+
719
+ Notes
720
+ -----
721
+ Will fail silently if an edge in ebunch is not in the graph.
722
+
723
+ Examples
724
+ --------
725
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
726
+ >>> ebunch = [(1, 2), (2, 3)]
727
+ >>> G.remove_edges_from(ebunch)
728
+
729
+ Removing multiple copies of edges
730
+
731
+ >>> G = nx.MultiGraph()
732
+ >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
733
+ >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
734
+ >>> list(G.edges())
735
+ [(1, 2)]
736
+ >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
737
+ >>> list(G.edges) # now empty graph
738
+ []
739
+
740
+ When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
741
+ u and v in the graph, the most recent edge (in terms of insertion
742
+ order) is removed.
743
+
744
+ >>> G = nx.MultiGraph()
745
+ >>> for key in ("x", "y", "a"):
746
+ ... k = G.add_edge(0, 1, key=key)
747
+ >>> G.edges(keys=True)
748
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
749
+ >>> G.remove_edges_from([(0, 1)])
750
+ >>> G.edges(keys=True)
751
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
752
+
753
+ """
754
+ for e in ebunch:
755
+ try:
756
+ self.remove_edge(*e[:3])
757
+ except NetworkXError:
758
+ pass
759
+ nx._clear_cache(self)
760
+
761
+ def has_edge(self, u, v, key=None):
762
+ """Returns True if the graph has an edge between nodes u and v.
763
+
764
+ This is the same as `v in G[u] or key in G[u][v]`
765
+ without KeyError exceptions.
766
+
767
+ Parameters
768
+ ----------
769
+ u, v : nodes
770
+ Nodes can be, for example, strings or numbers.
771
+
772
+ key : hashable identifier, optional (default=None)
773
+ If specified return True only if the edge with
774
+ key is found.
775
+
776
+ Returns
777
+ -------
778
+ edge_ind : bool
779
+ True if edge is in the graph, False otherwise.
780
+
781
+ Examples
782
+ --------
783
+ Can be called either using two nodes u, v, an edge tuple (u, v),
784
+ or an edge tuple (u, v, key).
785
+
786
+ >>> G = nx.MultiGraph() # or MultiDiGraph
787
+ >>> nx.add_path(G, [0, 1, 2, 3])
788
+ >>> G.has_edge(0, 1) # using two nodes
789
+ True
790
+ >>> e = (0, 1)
791
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
792
+ True
793
+ >>> G.add_edge(0, 1, key="a")
794
+ 'a'
795
+ >>> G.has_edge(0, 1, key="a") # specify key
796
+ True
797
+ >>> G.has_edge(1, 0, key="a") # edges aren't directed
798
+ True
799
+ >>> e = (0, 1, "a")
800
+ >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
801
+ True
802
+
803
+ The following syntax are equivalent:
804
+
805
+ >>> G.has_edge(0, 1)
806
+ True
807
+ >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
808
+ True
809
+ >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
810
+ True
811
+
812
+ """
813
+ try:
814
+ if key is None:
815
+ return v in self._adj[u]
816
+ else:
817
+ return key in self._adj[u][v]
818
+ except KeyError:
819
+ return False
820
+
821
+ @cached_property
822
+ def edges(self):
823
+ """Returns an iterator over the edges.
824
+
825
+ edges(self, nbunch=None, data=False, keys=False, default=None)
826
+
827
+ The MultiEdgeView provides set-like operations on the edge-tuples
828
+ as well as edge attribute lookup. When called, it also provides
829
+ an EdgeDataView object which allows control of access to edge
830
+ attributes (but does not provide set-like operations).
831
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
832
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
833
+ ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
834
+ iterates through all the edges yielding the color attribute with
835
+ default `'red'` if no color attribute exists.
836
+
837
+ Edges are returned as tuples with optional data and keys
838
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
839
+ provided, the tuples will just be (node, neighbor, data), but
840
+ multiple tuples with the same node and neighbor will be generated
841
+ when multiple edges exist between two nodes.
842
+
843
+ Parameters
844
+ ----------
845
+ nbunch : single node, container, or all nodes (default= all nodes)
846
+ The view will only report edges from these nodes.
847
+ data : string or bool, optional (default=False)
848
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
849
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
850
+ If False, return 2-tuple (u, v).
851
+ keys : bool, optional (default=False)
852
+ If True, return edge keys with each edge, creating (u, v, k)
853
+ tuples or (u, v, k, d) tuples if data is also requested.
854
+ default : value, optional (default=None)
855
+ Value used for edges that don't have the requested attribute.
856
+ Only relevant if data is not True or False.
857
+
858
+ Returns
859
+ -------
860
+ edges : MultiEdgeView
861
+ A view of edge attributes, usually it iterates over (u, v)
862
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
863
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
864
+
865
+ Notes
866
+ -----
867
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
868
+ For directed graphs this returns the out-edges.
869
+
870
+ Examples
871
+ --------
872
+ >>> G = nx.MultiGraph()
873
+ >>> nx.add_path(G, [0, 1, 2])
874
+ >>> key = G.add_edge(2, 3, weight=5)
875
+ >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
876
+ >>> [e for e in G.edges()]
877
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
878
+ >>> G.edges.data() # default data is {} (empty dict)
879
+ MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
880
+ >>> G.edges.data("weight", default=1)
881
+ MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
882
+ >>> G.edges(keys=True) # default keys are integers
883
+ MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
884
+ >>> G.edges.data(keys=True)
885
+ MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
886
+ >>> G.edges.data("weight", default=1, keys=True)
887
+ MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
888
+ >>> G.edges([0, 3]) # Note ordering of tuples from listed sources
889
+ MultiEdgeDataView([(0, 1), (3, 2)])
890
+ >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
891
+ MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
892
+ >>> G.edges(0)
893
+ MultiEdgeDataView([(0, 1)])
894
+ """
895
+ return MultiEdgeView(self)
896
+
897
+ def get_edge_data(self, u, v, key=None, default=None):
898
+ """Returns the attribute dictionary associated with edge (u, v,
899
+ key).
900
+
901
+ If a key is not provided, returns a dictionary mapping edge keys
902
+ to attribute dictionaries for each edge between u and v.
903
+
904
+ This is identical to `G[u][v][key]` except the default is returned
905
+ instead of an exception is the edge doesn't exist.
906
+
907
+ Parameters
908
+ ----------
909
+ u, v : nodes
910
+
911
+ default : any Python object (default=None)
912
+ Value to return if the specific edge (u, v, key) is not
913
+ found, OR if there are no edges between u and v and no key
914
+ is specified.
915
+
916
+ key : hashable identifier, optional (default=None)
917
+ Return data only for the edge with specified key, as an
918
+ attribute dictionary (rather than a dictionary mapping keys
919
+ to attribute dictionaries).
920
+
921
+ Returns
922
+ -------
923
+ edge_dict : dictionary
924
+ The edge attribute dictionary, OR a dictionary mapping edge
925
+ keys to attribute dictionaries for each of those edges if no
926
+ specific key is provided (even if there's only one edge
927
+ between u and v).
928
+
929
+ Examples
930
+ --------
931
+ >>> G = nx.MultiGraph() # or MultiDiGraph
932
+ >>> key = G.add_edge(0, 1, key="a", weight=7)
933
+ >>> G[0][1]["a"] # key='a'
934
+ {'weight': 7}
935
+ >>> G.edges[0, 1, "a"] # key='a'
936
+ {'weight': 7}
937
+
938
+ Warning: we protect the graph data structure by making
939
+ `G.edges` and `G[1][2]` read-only dict-like structures.
940
+ However, you can assign values to attributes in e.g.
941
+ `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
942
+ bracket as shown next. You need to specify all edge info
943
+ to assign to the edge data associated with an edge.
944
+
945
+ >>> G[0][1]["a"]["weight"] = 10
946
+ >>> G.edges[0, 1, "a"]["weight"] = 10
947
+ >>> G[0][1]["a"]["weight"]
948
+ 10
949
+ >>> G.edges[1, 0, "a"]["weight"]
950
+ 10
951
+
952
+ >>> G = nx.MultiGraph() # or MultiDiGraph
953
+ >>> nx.add_path(G, [0, 1, 2, 3])
954
+ >>> G.edges[0, 1, 0]["weight"] = 5
955
+ >>> G.get_edge_data(0, 1)
956
+ {0: {'weight': 5}}
957
+ >>> e = (0, 1)
958
+ >>> G.get_edge_data(*e) # tuple form
959
+ {0: {'weight': 5}}
960
+ >>> G.get_edge_data(3, 0) # edge not in graph, returns None
961
+ >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
962
+ 0
963
+ >>> G.get_edge_data(1, 0, 0) # specific key gives back
964
+ {'weight': 5}
965
+ """
966
+ try:
967
+ if key is None:
968
+ return self._adj[u][v]
969
+ else:
970
+ return self._adj[u][v][key]
971
+ except KeyError:
972
+ return default
973
+
974
+ @cached_property
975
+ def degree(self):
976
+ """A DegreeView for the Graph as G.degree or G.degree().
977
+
978
+ The node degree is the number of edges adjacent to the node.
979
+ The weighted node degree is the sum of the edge weights for
980
+ edges incident to that node.
981
+
982
+ This object provides an iterator for (node, degree) as well as
983
+ lookup for the degree for a single node.
984
+
985
+ Parameters
986
+ ----------
987
+ nbunch : single node, container, or all nodes (default= all nodes)
988
+ The view will only report edges incident to these nodes.
989
+
990
+ weight : string or None, optional (default=None)
991
+ The name of an edge attribute that holds the numerical value used
992
+ as a weight. If None, then each edge has weight 1.
993
+ The degree is the sum of the edge weights adjacent to the node.
994
+
995
+ Returns
996
+ -------
997
+ MultiDegreeView or int
998
+ If multiple nodes are requested (the default), returns a `MultiDegreeView`
999
+ mapping nodes to their degree.
1000
+ If a single node is requested, returns the degree of the node as an integer.
1001
+
1002
+ Examples
1003
+ --------
1004
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1005
+ >>> nx.add_path(G, [0, 1, 2, 3])
1006
+ >>> G.degree(0) # node 0 with degree 1
1007
+ 1
1008
+ >>> list(G.degree([0, 1]))
1009
+ [(0, 1), (1, 2)]
1010
+
1011
+ """
1012
+ return MultiDegreeView(self)
1013
+
1014
+ def is_multigraph(self):
1015
+ """Returns True if graph is a multigraph, False otherwise."""
1016
+ return True
1017
+
1018
+ def is_directed(self):
1019
+ """Returns True if graph is directed, False otherwise."""
1020
+ return False
1021
+
1022
+ def copy(self, as_view=False):
1023
+ """Returns a copy of the graph.
1024
+
1025
+ The copy method by default returns an independent shallow copy
1026
+ of the graph and attributes. That is, if an attribute is a
1027
+ container, that container is shared by the original an the copy.
1028
+ Use Python's `copy.deepcopy` for new containers.
1029
+
1030
+ If `as_view` is True then a view is returned instead of a copy.
1031
+
1032
+ Notes
1033
+ -----
1034
+ All copies reproduce the graph structure, but data attributes
1035
+ may be handled in different ways. There are four types of copies
1036
+ of a graph that people might want.
1037
+
1038
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1039
+ all data attributes and any objects they might contain.
1040
+ The entire graph object is new so that changes in the copy
1041
+ do not affect the original object. (see Python's copy.deepcopy)
1042
+
1043
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1044
+ is copied but the edge, node and graph attribute dicts are
1045
+ references to those in the original graph. This saves
1046
+ time and memory but could cause confusion if you change an attribute
1047
+ in one graph and it changes the attribute in the other.
1048
+ NetworkX does not provide this level of shallow copy.
1049
+
1050
+ Independent Shallow -- This copy creates new independent attribute
1051
+ dicts and then does a shallow copy of the attributes. That is, any
1052
+ attributes that are containers are shared between the new graph
1053
+ and the original. This is exactly what `dict.copy()` provides.
1054
+ You can obtain this style copy using:
1055
+
1056
+ >>> G = nx.path_graph(5)
1057
+ >>> H = G.copy()
1058
+ >>> H = G.copy(as_view=False)
1059
+ >>> H = nx.Graph(G)
1060
+ >>> H = G.__class__(G)
1061
+
1062
+ Fresh Data -- For fresh data, the graph structure is copied while
1063
+ new empty data attribute dicts are created. The resulting graph
1064
+ is independent of the original and it has no edge, node or graph
1065
+ attributes. Fresh copies are not enabled. Instead use:
1066
+
1067
+ >>> H = G.__class__()
1068
+ >>> H.add_nodes_from(G)
1069
+ >>> H.add_edges_from(G.edges)
1070
+
1071
+ View -- Inspired by dict-views, graph-views act like read-only
1072
+ versions of the original graph, providing a copy of the original
1073
+ structure without requiring any memory for copying the information.
1074
+
1075
+ See the Python copy module for more information on shallow
1076
+ and deep copies, https://docs.python.org/3/library/copy.html.
1077
+
1078
+ Parameters
1079
+ ----------
1080
+ as_view : bool, optional (default=False)
1081
+ If True, the returned graph-view provides a read-only view
1082
+ of the original graph without actually copying any data.
1083
+
1084
+ Returns
1085
+ -------
1086
+ G : Graph
1087
+ A copy of the graph.
1088
+
1089
+ See Also
1090
+ --------
1091
+ to_directed: return a directed copy of the graph.
1092
+
1093
+ Examples
1094
+ --------
1095
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1096
+ >>> H = G.copy()
1097
+
1098
+ """
1099
+ if as_view is True:
1100
+ return nx.graphviews.generic_graph_view(self)
1101
+ G = self.__class__()
1102
+ G.graph.update(self.graph)
1103
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1104
+ G.add_edges_from(
1105
+ (u, v, key, datadict.copy())
1106
+ for u, nbrs in self._adj.items()
1107
+ for v, keydict in nbrs.items()
1108
+ for key, datadict in keydict.items()
1109
+ )
1110
+ return G
1111
+
1112
+ def to_directed(self, as_view=False):
1113
+ """Returns a directed representation of the graph.
1114
+
1115
+ Returns
1116
+ -------
1117
+ G : MultiDiGraph
1118
+ A directed graph with the same name, same nodes, and with
1119
+ each edge (u, v, k, data) replaced by two directed edges
1120
+ (u, v, k, data) and (v, u, k, data).
1121
+
1122
+ Notes
1123
+ -----
1124
+ This returns a "deepcopy" of the edge, node, and
1125
+ graph attributes which attempts to completely copy
1126
+ all of the data and references.
1127
+
1128
+ This is in contrast to the similar D=MultiDiGraph(G) which
1129
+ returns a shallow copy of the data.
1130
+
1131
+ See the Python copy module for more information on shallow
1132
+ and deep copies, https://docs.python.org/3/library/copy.html.
1133
+
1134
+ Warning: If you have subclassed MultiGraph to use dict-like objects
1135
+ in the data structure, those changes do not transfer to the
1136
+ MultiDiGraph created by this method.
1137
+
1138
+ Examples
1139
+ --------
1140
+ >>> G = nx.MultiGraph()
1141
+ >>> G.add_edge(0, 1)
1142
+ 0
1143
+ >>> G.add_edge(0, 1)
1144
+ 1
1145
+ >>> H = G.to_directed()
1146
+ >>> list(H.edges)
1147
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
1148
+
1149
+ If already directed, return a (deep) copy
1150
+
1151
+ >>> G = nx.MultiDiGraph()
1152
+ >>> G.add_edge(0, 1)
1153
+ 0
1154
+ >>> H = G.to_directed()
1155
+ >>> list(H.edges)
1156
+ [(0, 1, 0)]
1157
+ """
1158
+ graph_class = self.to_directed_class()
1159
+ if as_view is True:
1160
+ return nx.graphviews.generic_graph_view(self, graph_class)
1161
+ # deepcopy when not a view
1162
+ G = graph_class()
1163
+ G.graph.update(deepcopy(self.graph))
1164
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1165
+ G.add_edges_from(
1166
+ (u, v, key, deepcopy(datadict))
1167
+ for u, nbrs in self.adj.items()
1168
+ for v, keydict in nbrs.items()
1169
+ for key, datadict in keydict.items()
1170
+ )
1171
+ return G
1172
+
1173
+ def to_undirected(self, as_view=False):
1174
+ """Returns an undirected copy of the graph.
1175
+
1176
+ Returns
1177
+ -------
1178
+ G : Graph/MultiGraph
1179
+ A deepcopy of the graph.
1180
+
1181
+ See Also
1182
+ --------
1183
+ copy, add_edge, add_edges_from
1184
+
1185
+ Notes
1186
+ -----
1187
+ This returns a "deepcopy" of the edge, node, and
1188
+ graph attributes which attempts to completely copy
1189
+ all of the data and references.
1190
+
1191
+ This is in contrast to the similar `G = nx.MultiGraph(D)`
1192
+ which returns a shallow copy of the data.
1193
+
1194
+ See the Python copy module for more information on shallow
1195
+ and deep copies, https://docs.python.org/3/library/copy.html.
1196
+
1197
+ Warning: If you have subclassed MultiGraph to use dict-like
1198
+ objects in the data structure, those changes do not transfer
1199
+ to the MultiGraph created by this method.
1200
+
1201
+ Examples
1202
+ --------
1203
+ >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
1204
+ >>> H = G.to_directed()
1205
+ >>> list(H.edges)
1206
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
1207
+ >>> G2 = H.to_undirected()
1208
+ >>> list(G2.edges)
1209
+ [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
1210
+ """
1211
+ graph_class = self.to_undirected_class()
1212
+ if as_view is True:
1213
+ return nx.graphviews.generic_graph_view(self, graph_class)
1214
+ # deepcopy when not a view
1215
+ G = graph_class()
1216
+ G.graph.update(deepcopy(self.graph))
1217
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1218
+ G.add_edges_from(
1219
+ (u, v, key, deepcopy(datadict))
1220
+ for u, nbrs in self._adj.items()
1221
+ for v, keydict in nbrs.items()
1222
+ for key, datadict in keydict.items()
1223
+ )
1224
+ return G
1225
+
1226
+ def number_of_edges(self, u=None, v=None):
1227
+ """Returns the number of edges between two nodes.
1228
+
1229
+ Parameters
1230
+ ----------
1231
+ u, v : nodes, optional (Default=all edges)
1232
+ If u and v are specified, return the number of edges between
1233
+ u and v. Otherwise return the total number of all edges.
1234
+
1235
+ Returns
1236
+ -------
1237
+ nedges : int
1238
+ The number of edges in the graph. If nodes `u` and `v` are
1239
+ specified return the number of edges between those nodes. If
1240
+ the graph is directed, this only returns the number of edges
1241
+ from `u` to `v`.
1242
+
1243
+ See Also
1244
+ --------
1245
+ size
1246
+
1247
+ Examples
1248
+ --------
1249
+ For undirected multigraphs, this method counts the total number
1250
+ of edges in the graph::
1251
+
1252
+ >>> G = nx.MultiGraph()
1253
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
1254
+ [0, 1, 0]
1255
+ >>> G.number_of_edges()
1256
+ 3
1257
+
1258
+ If you specify two nodes, this counts the total number of edges
1259
+ joining the two nodes::
1260
+
1261
+ >>> G.number_of_edges(0, 1)
1262
+ 2
1263
+
1264
+ For directed multigraphs, this method can count the total number
1265
+ of directed edges from `u` to `v`::
1266
+
1267
+ >>> G = nx.MultiDiGraph()
1268
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
1269
+ [0, 1, 0]
1270
+ >>> G.number_of_edges(0, 1)
1271
+ 2
1272
+ >>> G.number_of_edges(1, 0)
1273
+ 1
1274
+
1275
+ """
1276
+ if u is None:
1277
+ return self.size()
1278
+ try:
1279
+ edgedata = self._adj[u][v]
1280
+ except KeyError:
1281
+ return 0 # no such edge
1282
+ return len(edgedata)
llmeval-env/lib/python3.10/site-packages/networkx/classes/reportviews.py ADDED
@@ -0,0 +1,1438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ View Classes provide node, edge and degree "views" of a graph.
3
+
4
+ Views for nodes, edges and degree are provided for all base graph classes.
5
+ A view means a read-only object that is quick to create, automatically
6
+ updated when the graph changes, and provides basic access like `n in V`,
7
+ `for n in V`, `V[n]` and sometimes set operations.
8
+
9
+ The views are read-only iterable containers that are updated as the
10
+ graph is updated. As with dicts, the graph should not be updated
11
+ while iterating through the view. Views can be iterated multiple times.
12
+
13
+ Edge and Node views also allow data attribute lookup.
14
+ The resulting attribute dict is writable as `G.edges[3, 4]['color']='red'`
15
+ Degree views allow lookup of degree values for single nodes.
16
+ Weighted degree is supported with the `weight` argument.
17
+
18
+ NodeView
19
+ ========
20
+
21
+ `V = G.nodes` (or `V = G.nodes()`) allows `len(V)`, `n in V`, set
22
+ operations e.g. "G.nodes & H.nodes", and `dd = G.nodes[n]`, where
23
+ `dd` is the node data dict. Iteration is over the nodes by default.
24
+
25
+ NodeDataView
26
+ ============
27
+
28
+ To iterate over (node, data) pairs, use arguments to `G.nodes()`
29
+ to create a DataView e.g. `DV = G.nodes(data='color', default='red')`.
30
+ The DataView iterates as `for n, color in DV` and allows
31
+ `(n, 'red') in DV`. Using `DV = G.nodes(data=True)`, the DataViews
32
+ use the full datadict in writeable form also allowing contain testing as
33
+ `(n, {'color': 'red'}) in VD`. DataViews allow set operations when
34
+ data attributes are hashable.
35
+
36
+ DegreeView
37
+ ==========
38
+
39
+ `V = G.degree` allows iteration over (node, degree) pairs as well
40
+ as lookup: `deg=V[n]`. There are many flavors of DegreeView
41
+ for In/Out/Directed/Multi. For Directed Graphs, `G.degree`
42
+ counts both in and out going edges. `G.out_degree` and
43
+ `G.in_degree` count only specific directions.
44
+ Weighted degree using edge data attributes is provide via
45
+ `V = G.degree(weight='attr_name')` where any string with the
46
+ attribute name can be used. `weight=None` is the default.
47
+ No set operations are implemented for degrees, use NodeView.
48
+
49
+ The argument `nbunch` restricts iteration to nodes in nbunch.
50
+ The DegreeView can still lookup any node even if nbunch is specified.
51
+
52
+ EdgeView
53
+ ========
54
+
55
+ `V = G.edges` or `V = G.edges()` allows iteration over edges as well as
56
+ `e in V`, set operations and edge data lookup `dd = G.edges[2, 3]`.
57
+ Iteration is over 2-tuples `(u, v)` for Graph/DiGraph. For multigraphs
58
+ edges 3-tuples `(u, v, key)` are the default but 2-tuples can be obtained
59
+ via `V = G.edges(keys=False)`.
60
+
61
+ Set operations for directed graphs treat the edges as a set of 2-tuples.
62
+ For undirected graphs, 2-tuples are not a unique representation of edges.
63
+ So long as the set being compared to contains unique representations
64
+ of its edges, the set operations will act as expected. If the other
65
+ set contains both `(0, 1)` and `(1, 0)` however, the result of set
66
+ operations may contain both representations of the same edge.
67
+
68
+ EdgeDataView
69
+ ============
70
+
71
+ Edge data can be reported using an EdgeDataView typically created
72
+ by calling an EdgeView: `DV = G.edges(data='weight', default=1)`.
73
+ The EdgeDataView allows iteration over edge tuples, membership checking
74
+ but no set operations.
75
+
76
+ Iteration depends on `data` and `default` and for multigraph `keys`
77
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
78
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
79
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
80
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key`
81
+ to create 3-tuples and 4-tuples.
82
+
83
+ The argument `nbunch` restricts edges to those incident to nodes in nbunch.
84
+ """
85
+ from collections.abc import Mapping, Set
86
+
87
+ import networkx as nx
88
+
89
+ __all__ = [
90
+ "NodeView",
91
+ "NodeDataView",
92
+ "EdgeView",
93
+ "OutEdgeView",
94
+ "InEdgeView",
95
+ "EdgeDataView",
96
+ "OutEdgeDataView",
97
+ "InEdgeDataView",
98
+ "MultiEdgeView",
99
+ "OutMultiEdgeView",
100
+ "InMultiEdgeView",
101
+ "MultiEdgeDataView",
102
+ "OutMultiEdgeDataView",
103
+ "InMultiEdgeDataView",
104
+ "DegreeView",
105
+ "DiDegreeView",
106
+ "InDegreeView",
107
+ "OutDegreeView",
108
+ "MultiDegreeView",
109
+ "DiMultiDegreeView",
110
+ "InMultiDegreeView",
111
+ "OutMultiDegreeView",
112
+ ]
113
+
114
+
115
+ # NodeViews
116
+ class NodeView(Mapping, Set):
117
+ """A NodeView class to act as G.nodes for a NetworkX Graph
118
+
119
+ Set operations act on the nodes without considering data.
120
+ Iteration is over nodes. Node data can be looked up like a dict.
121
+ Use NodeDataView to iterate over node data or to specify a data
122
+ attribute for lookup. NodeDataView is created by calling the NodeView.
123
+
124
+ Parameters
125
+ ----------
126
+ graph : NetworkX graph-like class
127
+
128
+ Examples
129
+ --------
130
+ >>> G = nx.path_graph(3)
131
+ >>> NV = G.nodes()
132
+ >>> 2 in NV
133
+ True
134
+ >>> for n in NV:
135
+ ... print(n)
136
+ 0
137
+ 1
138
+ 2
139
+ >>> assert NV & {1, 2, 3} == {1, 2}
140
+
141
+ >>> G.add_node(2, color="blue")
142
+ >>> NV[2]
143
+ {'color': 'blue'}
144
+ >>> G.add_node(8, color="red")
145
+ >>> NDV = G.nodes(data=True)
146
+ >>> (2, NV[2]) in NDV
147
+ True
148
+ >>> for n, dd in NDV:
149
+ ... print((n, dd.get("color", "aqua")))
150
+ (0, 'aqua')
151
+ (1, 'aqua')
152
+ (2, 'blue')
153
+ (8, 'red')
154
+ >>> NDV[2] == NV[2]
155
+ True
156
+
157
+ >>> NVdata = G.nodes(data="color", default="aqua")
158
+ >>> (2, NVdata[2]) in NVdata
159
+ True
160
+ >>> for n, dd in NVdata:
161
+ ... print((n, dd))
162
+ (0, 'aqua')
163
+ (1, 'aqua')
164
+ (2, 'blue')
165
+ (8, 'red')
166
+ >>> NVdata[2] == NV[2] # NVdata gets 'color', NV gets datadict
167
+ False
168
+ """
169
+
170
+ __slots__ = ("_nodes",)
171
+
172
+ def __getstate__(self):
173
+ return {"_nodes": self._nodes}
174
+
175
+ def __setstate__(self, state):
176
+ self._nodes = state["_nodes"]
177
+
178
+ def __init__(self, graph):
179
+ self._nodes = graph._node
180
+
181
+ # Mapping methods
182
+ def __len__(self):
183
+ return len(self._nodes)
184
+
185
+ def __iter__(self):
186
+ return iter(self._nodes)
187
+
188
+ def __getitem__(self, n):
189
+ if isinstance(n, slice):
190
+ raise nx.NetworkXError(
191
+ f"{type(self).__name__} does not support slicing, "
192
+ f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]"
193
+ )
194
+ return self._nodes[n]
195
+
196
+ # Set methods
197
+ def __contains__(self, n):
198
+ return n in self._nodes
199
+
200
+ @classmethod
201
+ def _from_iterable(cls, it):
202
+ return set(it)
203
+
204
+ # DataView method
205
+ def __call__(self, data=False, default=None):
206
+ if data is False:
207
+ return self
208
+ return NodeDataView(self._nodes, data, default)
209
+
210
+ def data(self, data=True, default=None):
211
+ """
212
+ Return a read-only view of node data.
213
+
214
+ Parameters
215
+ ----------
216
+ data : bool or node data key, default=True
217
+ If ``data=True`` (the default), return a `NodeDataView` object that
218
+ maps each node to *all* of its attributes. `data` may also be an
219
+ arbitrary key, in which case the `NodeDataView` maps each node to
220
+ the value for the keyed attribute. In this case, if a node does
221
+ not have the `data` attribute, the `default` value is used.
222
+ default : object, default=None
223
+ The value used when a node does not have a specific attribute.
224
+
225
+ Returns
226
+ -------
227
+ NodeDataView
228
+ The layout of the returned NodeDataView depends on the value of the
229
+ `data` parameter.
230
+
231
+ Notes
232
+ -----
233
+ If ``data=False``, returns a `NodeView` object without data.
234
+
235
+ See Also
236
+ --------
237
+ NodeDataView
238
+
239
+ Examples
240
+ --------
241
+ >>> G = nx.Graph()
242
+ >>> G.add_nodes_from(
243
+ ... [
244
+ ... (0, {"color": "red", "weight": 10}),
245
+ ... (1, {"color": "blue"}),
246
+ ... (2, {"color": "yellow", "weight": 2}),
247
+ ... ]
248
+ ... )
249
+
250
+ Accessing node data with ``data=True`` (the default) returns a
251
+ NodeDataView mapping each node to all of its attributes:
252
+
253
+ >>> G.nodes.data()
254
+ NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}})
255
+
256
+ If `data` represents a key in the node attribute dict, a NodeDataView mapping
257
+ the nodes to the value for that specific key is returned:
258
+
259
+ >>> G.nodes.data("color")
260
+ NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color')
261
+
262
+ If a specific key is not found in an attribute dict, the value specified
263
+ by `default` is returned:
264
+
265
+ >>> G.nodes.data("weight", default=-999)
266
+ NodeDataView({0: 10, 1: -999, 2: 2}, data='weight')
267
+
268
+ Note that there is no check that the `data` key is in any of the
269
+ node attribute dictionaries:
270
+
271
+ >>> G.nodes.data("height")
272
+ NodeDataView({0: None, 1: None, 2: None}, data='height')
273
+ """
274
+ if data is False:
275
+ return self
276
+ return NodeDataView(self._nodes, data, default)
277
+
278
+ def __str__(self):
279
+ return str(list(self))
280
+
281
+ def __repr__(self):
282
+ return f"{self.__class__.__name__}({tuple(self)})"
283
+
284
+
285
+ class NodeDataView(Set):
286
+ """A DataView class for nodes of a NetworkX Graph
287
+
288
+ The main use for this class is to iterate through node-data pairs.
289
+ The data can be the entire data-dictionary for each node, or it
290
+ can be a specific attribute (with default) for each node.
291
+ Set operations are enabled with NodeDataView, but don't work in
292
+ cases where the data is not hashable. Use with caution.
293
+ Typically, set operations on nodes use NodeView, not NodeDataView.
294
+ That is, they use `G.nodes` instead of `G.nodes(data='foo')`.
295
+
296
+ Parameters
297
+ ==========
298
+ graph : NetworkX graph-like class
299
+ data : bool or string (default=False)
300
+ default : object (default=None)
301
+ """
302
+
303
+ __slots__ = ("_nodes", "_data", "_default")
304
+
305
+ def __getstate__(self):
306
+ return {"_nodes": self._nodes, "_data": self._data, "_default": self._default}
307
+
308
+ def __setstate__(self, state):
309
+ self._nodes = state["_nodes"]
310
+ self._data = state["_data"]
311
+ self._default = state["_default"]
312
+
313
+ def __init__(self, nodedict, data=False, default=None):
314
+ self._nodes = nodedict
315
+ self._data = data
316
+ self._default = default
317
+
318
+ @classmethod
319
+ def _from_iterable(cls, it):
320
+ try:
321
+ return set(it)
322
+ except TypeError as err:
323
+ if "unhashable" in str(err):
324
+ msg = " : Could be b/c data=True or your values are unhashable"
325
+ raise TypeError(str(err) + msg) from err
326
+ raise
327
+
328
+ def __len__(self):
329
+ return len(self._nodes)
330
+
331
+ def __iter__(self):
332
+ data = self._data
333
+ if data is False:
334
+ return iter(self._nodes)
335
+ if data is True:
336
+ return iter(self._nodes.items())
337
+ return (
338
+ (n, dd[data] if data in dd else self._default)
339
+ for n, dd in self._nodes.items()
340
+ )
341
+
342
+ def __contains__(self, n):
343
+ try:
344
+ node_in = n in self._nodes
345
+ except TypeError:
346
+ n, d = n
347
+ return n in self._nodes and self[n] == d
348
+ if node_in is True:
349
+ return node_in
350
+ try:
351
+ n, d = n
352
+ except (TypeError, ValueError):
353
+ return False
354
+ return n in self._nodes and self[n] == d
355
+
356
+ def __getitem__(self, n):
357
+ if isinstance(n, slice):
358
+ raise nx.NetworkXError(
359
+ f"{type(self).__name__} does not support slicing, "
360
+ f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]"
361
+ )
362
+ ddict = self._nodes[n]
363
+ data = self._data
364
+ if data is False or data is True:
365
+ return ddict
366
+ return ddict[data] if data in ddict else self._default
367
+
368
+ def __str__(self):
369
+ return str(list(self))
370
+
371
+ def __repr__(self):
372
+ name = self.__class__.__name__
373
+ if self._data is False:
374
+ return f"{name}({tuple(self)})"
375
+ if self._data is True:
376
+ return f"{name}({dict(self)})"
377
+ return f"{name}({dict(self)}, data={self._data!r})"
378
+
379
+
380
+ # DegreeViews
381
+ class DiDegreeView:
382
+ """A View class for degree of nodes in a NetworkX Graph
383
+
384
+ The functionality is like dict.items() with (node, degree) pairs.
385
+ Additional functionality includes read-only lookup of node degree,
386
+ and calling with optional features nbunch (for only a subset of nodes)
387
+ and weight (use edge weights to compute degree).
388
+
389
+ Parameters
390
+ ==========
391
+ graph : NetworkX graph-like class
392
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
393
+ weight : bool or string (default=None)
394
+
395
+ Notes
396
+ -----
397
+ DegreeView can still lookup any node even if nbunch is specified.
398
+
399
+ Examples
400
+ --------
401
+ >>> G = nx.path_graph(3)
402
+ >>> DV = G.degree()
403
+ >>> assert DV[2] == 1
404
+ >>> assert sum(deg for n, deg in DV) == 4
405
+
406
+ >>> DVweight = G.degree(weight="span")
407
+ >>> G.add_edge(1, 2, span=34)
408
+ >>> DVweight[2]
409
+ 34
410
+ >>> DVweight[0] # default edge weight is 1
411
+ 1
412
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
413
+ 70
414
+
415
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
416
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
417
+ """
418
+
419
+ def __init__(self, G, nbunch=None, weight=None):
420
+ self._graph = G
421
+ self._succ = G._succ if hasattr(G, "_succ") else G._adj
422
+ self._pred = G._pred if hasattr(G, "_pred") else G._adj
423
+ self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch))
424
+ self._weight = weight
425
+
426
+ def __call__(self, nbunch=None, weight=None):
427
+ if nbunch is None:
428
+ if weight == self._weight:
429
+ return self
430
+ return self.__class__(self._graph, None, weight)
431
+ try:
432
+ if nbunch in self._nodes:
433
+ if weight == self._weight:
434
+ return self[nbunch]
435
+ return self.__class__(self._graph, None, weight)[nbunch]
436
+ except TypeError:
437
+ pass
438
+ return self.__class__(self._graph, nbunch, weight)
439
+
440
+ def __getitem__(self, n):
441
+ weight = self._weight
442
+ succs = self._succ[n]
443
+ preds = self._pred[n]
444
+ if weight is None:
445
+ return len(succs) + len(preds)
446
+ return sum(dd.get(weight, 1) for dd in succs.values()) + sum(
447
+ dd.get(weight, 1) for dd in preds.values()
448
+ )
449
+
450
+ def __iter__(self):
451
+ weight = self._weight
452
+ if weight is None:
453
+ for n in self._nodes:
454
+ succs = self._succ[n]
455
+ preds = self._pred[n]
456
+ yield (n, len(succs) + len(preds))
457
+ else:
458
+ for n in self._nodes:
459
+ succs = self._succ[n]
460
+ preds = self._pred[n]
461
+ deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum(
462
+ dd.get(weight, 1) for dd in preds.values()
463
+ )
464
+ yield (n, deg)
465
+
466
+ def __len__(self):
467
+ return len(self._nodes)
468
+
469
+ def __str__(self):
470
+ return str(list(self))
471
+
472
+ def __repr__(self):
473
+ return f"{self.__class__.__name__}({dict(self)})"
474
+
475
+
476
+ class DegreeView(DiDegreeView):
477
+ """A DegreeView class to act as G.degree for a NetworkX Graph
478
+
479
+ Typical usage focuses on iteration over `(node, degree)` pairs.
480
+ The degree is by default the number of edges incident to the node.
481
+ Optional argument `weight` enables weighted degree using the edge
482
+ attribute named in the `weight` argument. Reporting and iteration
483
+ can also be restricted to a subset of nodes using `nbunch`.
484
+
485
+ Additional functionality include node lookup so that `G.degree[n]`
486
+ reported the (possibly weighted) degree of node `n`. Calling the
487
+ view creates a view with different arguments `nbunch` or `weight`.
488
+
489
+ Parameters
490
+ ==========
491
+ graph : NetworkX graph-like class
492
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
493
+ weight : string or None (default=None)
494
+
495
+ Notes
496
+ -----
497
+ DegreeView can still lookup any node even if nbunch is specified.
498
+
499
+ Examples
500
+ --------
501
+ >>> G = nx.path_graph(3)
502
+ >>> DV = G.degree()
503
+ >>> assert DV[2] == 1
504
+ >>> assert G.degree[2] == 1
505
+ >>> assert sum(deg for n, deg in DV) == 4
506
+
507
+ >>> DVweight = G.degree(weight="span")
508
+ >>> G.add_edge(1, 2, span=34)
509
+ >>> DVweight[2]
510
+ 34
511
+ >>> DVweight[0] # default edge weight is 1
512
+ 1
513
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
514
+ 70
515
+
516
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
517
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
518
+ """
519
+
520
+ def __getitem__(self, n):
521
+ weight = self._weight
522
+ nbrs = self._succ[n]
523
+ if weight is None:
524
+ return len(nbrs) + (n in nbrs)
525
+ return sum(dd.get(weight, 1) for dd in nbrs.values()) + (
526
+ n in nbrs and nbrs[n].get(weight, 1)
527
+ )
528
+
529
+ def __iter__(self):
530
+ weight = self._weight
531
+ if weight is None:
532
+ for n in self._nodes:
533
+ nbrs = self._succ[n]
534
+ yield (n, len(nbrs) + (n in nbrs))
535
+ else:
536
+ for n in self._nodes:
537
+ nbrs = self._succ[n]
538
+ deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + (
539
+ n in nbrs and nbrs[n].get(weight, 1)
540
+ )
541
+ yield (n, deg)
542
+
543
+
544
+ class OutDegreeView(DiDegreeView):
545
+ """A DegreeView class to report out_degree for a DiGraph; See DegreeView"""
546
+
547
+ def __getitem__(self, n):
548
+ weight = self._weight
549
+ nbrs = self._succ[n]
550
+ if self._weight is None:
551
+ return len(nbrs)
552
+ return sum(dd.get(self._weight, 1) for dd in nbrs.values())
553
+
554
+ def __iter__(self):
555
+ weight = self._weight
556
+ if weight is None:
557
+ for n in self._nodes:
558
+ succs = self._succ[n]
559
+ yield (n, len(succs))
560
+ else:
561
+ for n in self._nodes:
562
+ succs = self._succ[n]
563
+ deg = sum(dd.get(weight, 1) for dd in succs.values())
564
+ yield (n, deg)
565
+
566
+
567
+ class InDegreeView(DiDegreeView):
568
+ """A DegreeView class to report in_degree for a DiGraph; See DegreeView"""
569
+
570
+ def __getitem__(self, n):
571
+ weight = self._weight
572
+ nbrs = self._pred[n]
573
+ if weight is None:
574
+ return len(nbrs)
575
+ return sum(dd.get(weight, 1) for dd in nbrs.values())
576
+
577
+ def __iter__(self):
578
+ weight = self._weight
579
+ if weight is None:
580
+ for n in self._nodes:
581
+ preds = self._pred[n]
582
+ yield (n, len(preds))
583
+ else:
584
+ for n in self._nodes:
585
+ preds = self._pred[n]
586
+ deg = sum(dd.get(weight, 1) for dd in preds.values())
587
+ yield (n, deg)
588
+
589
+
590
+ class MultiDegreeView(DiDegreeView):
591
+ """A DegreeView class for undirected multigraphs; See DegreeView"""
592
+
593
+ def __getitem__(self, n):
594
+ weight = self._weight
595
+ nbrs = self._succ[n]
596
+ if weight is None:
597
+ return sum(len(keys) for keys in nbrs.values()) + (
598
+ n in nbrs and len(nbrs[n])
599
+ )
600
+ # edge weighted graph - degree is sum of nbr edge weights
601
+ deg = sum(
602
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
603
+ )
604
+ if n in nbrs:
605
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
606
+ return deg
607
+
608
+ def __iter__(self):
609
+ weight = self._weight
610
+ if weight is None:
611
+ for n in self._nodes:
612
+ nbrs = self._succ[n]
613
+ deg = sum(len(keys) for keys in nbrs.values()) + (
614
+ n in nbrs and len(nbrs[n])
615
+ )
616
+ yield (n, deg)
617
+ else:
618
+ for n in self._nodes:
619
+ nbrs = self._succ[n]
620
+ deg = sum(
621
+ d.get(weight, 1)
622
+ for key_dict in nbrs.values()
623
+ for d in key_dict.values()
624
+ )
625
+ if n in nbrs:
626
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
627
+ yield (n, deg)
628
+
629
+
630
+ class DiMultiDegreeView(DiDegreeView):
631
+ """A DegreeView class for MultiDiGraph; See DegreeView"""
632
+
633
+ def __getitem__(self, n):
634
+ weight = self._weight
635
+ succs = self._succ[n]
636
+ preds = self._pred[n]
637
+ if weight is None:
638
+ return sum(len(keys) for keys in succs.values()) + sum(
639
+ len(keys) for keys in preds.values()
640
+ )
641
+ # edge weighted graph - degree is sum of nbr edge weights
642
+ deg = sum(
643
+ d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values()
644
+ ) + sum(
645
+ d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values()
646
+ )
647
+ return deg
648
+
649
+ def __iter__(self):
650
+ weight = self._weight
651
+ if weight is None:
652
+ for n in self._nodes:
653
+ succs = self._succ[n]
654
+ preds = self._pred[n]
655
+ deg = sum(len(keys) for keys in succs.values()) + sum(
656
+ len(keys) for keys in preds.values()
657
+ )
658
+ yield (n, deg)
659
+ else:
660
+ for n in self._nodes:
661
+ succs = self._succ[n]
662
+ preds = self._pred[n]
663
+ deg = sum(
664
+ d.get(weight, 1)
665
+ for key_dict in succs.values()
666
+ for d in key_dict.values()
667
+ ) + sum(
668
+ d.get(weight, 1)
669
+ for key_dict in preds.values()
670
+ for d in key_dict.values()
671
+ )
672
+ yield (n, deg)
673
+
674
+
675
+ class InMultiDegreeView(DiDegreeView):
676
+ """A DegreeView class for inward degree of MultiDiGraph; See DegreeView"""
677
+
678
+ def __getitem__(self, n):
679
+ weight = self._weight
680
+ nbrs = self._pred[n]
681
+ if weight is None:
682
+ return sum(len(data) for data in nbrs.values())
683
+ # edge weighted graph - degree is sum of nbr edge weights
684
+ return sum(
685
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
686
+ )
687
+
688
+ def __iter__(self):
689
+ weight = self._weight
690
+ if weight is None:
691
+ for n in self._nodes:
692
+ nbrs = self._pred[n]
693
+ deg = sum(len(data) for data in nbrs.values())
694
+ yield (n, deg)
695
+ else:
696
+ for n in self._nodes:
697
+ nbrs = self._pred[n]
698
+ deg = sum(
699
+ d.get(weight, 1)
700
+ for key_dict in nbrs.values()
701
+ for d in key_dict.values()
702
+ )
703
+ yield (n, deg)
704
+
705
+
706
+ class OutMultiDegreeView(DiDegreeView):
707
+ """A DegreeView class for outward degree of MultiDiGraph; See DegreeView"""
708
+
709
+ def __getitem__(self, n):
710
+ weight = self._weight
711
+ nbrs = self._succ[n]
712
+ if weight is None:
713
+ return sum(len(data) for data in nbrs.values())
714
+ # edge weighted graph - degree is sum of nbr edge weights
715
+ return sum(
716
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
717
+ )
718
+
719
+ def __iter__(self):
720
+ weight = self._weight
721
+ if weight is None:
722
+ for n in self._nodes:
723
+ nbrs = self._succ[n]
724
+ deg = sum(len(data) for data in nbrs.values())
725
+ yield (n, deg)
726
+ else:
727
+ for n in self._nodes:
728
+ nbrs = self._succ[n]
729
+ deg = sum(
730
+ d.get(weight, 1)
731
+ for key_dict in nbrs.values()
732
+ for d in key_dict.values()
733
+ )
734
+ yield (n, deg)
735
+
736
+
737
+ # EdgeDataViews
738
+ class OutEdgeDataView:
739
+ """EdgeDataView for outward edges of DiGraph; See EdgeDataView"""
740
+
741
+ __slots__ = (
742
+ "_viewer",
743
+ "_nbunch",
744
+ "_data",
745
+ "_default",
746
+ "_adjdict",
747
+ "_nodes_nbrs",
748
+ "_report",
749
+ )
750
+
751
+ def __getstate__(self):
752
+ return {
753
+ "viewer": self._viewer,
754
+ "nbunch": self._nbunch,
755
+ "data": self._data,
756
+ "default": self._default,
757
+ }
758
+
759
+ def __setstate__(self, state):
760
+ self.__init__(**state)
761
+
762
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None):
763
+ self._viewer = viewer
764
+ adjdict = self._adjdict = viewer._adjdict
765
+ if nbunch is None:
766
+ self._nodes_nbrs = adjdict.items
767
+ else:
768
+ # dict retains order of nodes but acts like a set
769
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
770
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
771
+ self._nbunch = nbunch
772
+ self._data = data
773
+ self._default = default
774
+ # Set _report based on data and default
775
+ if data is True:
776
+ self._report = lambda n, nbr, dd: (n, nbr, dd)
777
+ elif data is False:
778
+ self._report = lambda n, nbr, dd: (n, nbr)
779
+ else: # data is attribute name
780
+ self._report = (
781
+ lambda n, nbr, dd: (n, nbr, dd[data])
782
+ if data in dd
783
+ else (n, nbr, default)
784
+ )
785
+
786
+ def __len__(self):
787
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
788
+
789
+ def __iter__(self):
790
+ return (
791
+ self._report(n, nbr, dd)
792
+ for n, nbrs in self._nodes_nbrs()
793
+ for nbr, dd in nbrs.items()
794
+ )
795
+
796
+ def __contains__(self, e):
797
+ u, v = e[:2]
798
+ if self._nbunch is not None and u not in self._nbunch:
799
+ return False # this edge doesn't start in nbunch
800
+ try:
801
+ ddict = self._adjdict[u][v]
802
+ except KeyError:
803
+ return False
804
+ return e == self._report(u, v, ddict)
805
+
806
+ def __str__(self):
807
+ return str(list(self))
808
+
809
+ def __repr__(self):
810
+ return f"{self.__class__.__name__}({list(self)})"
811
+
812
+
813
+ class EdgeDataView(OutEdgeDataView):
814
+ """A EdgeDataView class for edges of Graph
815
+
816
+ This view is primarily used to iterate over the edges reporting
817
+ edges as node-tuples with edge data optionally reported. The
818
+ argument `nbunch` allows restriction to edges incident to nodes
819
+ in that container/singleton. The default (nbunch=None)
820
+ reports all edges. The arguments `data` and `default` control
821
+ what edge data is reported. The default `data is False` reports
822
+ only node-tuples for each edge. If `data is True` the entire edge
823
+ data dict is returned. Otherwise `data` is assumed to hold the name
824
+ of the edge attribute to report with default `default` if that
825
+ edge attribute is not present.
826
+
827
+ Parameters
828
+ ----------
829
+ nbunch : container of nodes, node or None (default None)
830
+ data : False, True or string (default False)
831
+ default : default value (default None)
832
+
833
+ Examples
834
+ --------
835
+ >>> G = nx.path_graph(3)
836
+ >>> G.add_edge(1, 2, foo="bar")
837
+ >>> list(G.edges(data="foo", default="biz"))
838
+ [(0, 1, 'biz'), (1, 2, 'bar')]
839
+ >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz")
840
+ """
841
+
842
+ __slots__ = ()
843
+
844
+ def __len__(self):
845
+ return sum(1 for e in self)
846
+
847
+ def __iter__(self):
848
+ seen = {}
849
+ for n, nbrs in self._nodes_nbrs():
850
+ for nbr, dd in nbrs.items():
851
+ if nbr not in seen:
852
+ yield self._report(n, nbr, dd)
853
+ seen[n] = 1
854
+ del seen
855
+
856
+ def __contains__(self, e):
857
+ u, v = e[:2]
858
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
859
+ return False # this edge doesn't start and it doesn't end in nbunch
860
+ try:
861
+ ddict = self._adjdict[u][v]
862
+ except KeyError:
863
+ return False
864
+ return e == self._report(u, v, ddict)
865
+
866
+
867
+ class InEdgeDataView(OutEdgeDataView):
868
+ """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView"""
869
+
870
+ __slots__ = ()
871
+
872
+ def __iter__(self):
873
+ return (
874
+ self._report(nbr, n, dd)
875
+ for n, nbrs in self._nodes_nbrs()
876
+ for nbr, dd in nbrs.items()
877
+ )
878
+
879
+ def __contains__(self, e):
880
+ u, v = e[:2]
881
+ if self._nbunch is not None and v not in self._nbunch:
882
+ return False # this edge doesn't end in nbunch
883
+ try:
884
+ ddict = self._adjdict[v][u]
885
+ except KeyError:
886
+ return False
887
+ return e == self._report(u, v, ddict)
888
+
889
+
890
+ class OutMultiEdgeDataView(OutEdgeDataView):
891
+ """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
892
+
893
+ __slots__ = ("keys",)
894
+
895
+ def __getstate__(self):
896
+ return {
897
+ "viewer": self._viewer,
898
+ "nbunch": self._nbunch,
899
+ "keys": self.keys,
900
+ "data": self._data,
901
+ "default": self._default,
902
+ }
903
+
904
+ def __setstate__(self, state):
905
+ self.__init__(**state)
906
+
907
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None, keys=False):
908
+ self._viewer = viewer
909
+ adjdict = self._adjdict = viewer._adjdict
910
+ self.keys = keys
911
+ if nbunch is None:
912
+ self._nodes_nbrs = adjdict.items
913
+ else:
914
+ # dict retains order of nodes but acts like a set
915
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
916
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
917
+ self._nbunch = nbunch
918
+ self._data = data
919
+ self._default = default
920
+ # Set _report based on data and default
921
+ if data is True:
922
+ if keys is True:
923
+ self._report = lambda n, nbr, k, dd: (n, nbr, k, dd)
924
+ else:
925
+ self._report = lambda n, nbr, k, dd: (n, nbr, dd)
926
+ elif data is False:
927
+ if keys is True:
928
+ self._report = lambda n, nbr, k, dd: (n, nbr, k)
929
+ else:
930
+ self._report = lambda n, nbr, k, dd: (n, nbr)
931
+ else: # data is attribute name
932
+ if keys is True:
933
+ self._report = (
934
+ lambda n, nbr, k, dd: (n, nbr, k, dd[data])
935
+ if data in dd
936
+ else (n, nbr, k, default)
937
+ )
938
+ else:
939
+ self._report = (
940
+ lambda n, nbr, k, dd: (n, nbr, dd[data])
941
+ if data in dd
942
+ else (n, nbr, default)
943
+ )
944
+
945
+ def __len__(self):
946
+ return sum(1 for e in self)
947
+
948
+ def __iter__(self):
949
+ return (
950
+ self._report(n, nbr, k, dd)
951
+ for n, nbrs in self._nodes_nbrs()
952
+ for nbr, kd in nbrs.items()
953
+ for k, dd in kd.items()
954
+ )
955
+
956
+ def __contains__(self, e):
957
+ u, v = e[:2]
958
+ if self._nbunch is not None and u not in self._nbunch:
959
+ return False # this edge doesn't start in nbunch
960
+ try:
961
+ kdict = self._adjdict[u][v]
962
+ except KeyError:
963
+ return False
964
+ if self.keys is True:
965
+ k = e[2]
966
+ try:
967
+ dd = kdict[k]
968
+ except KeyError:
969
+ return False
970
+ return e == self._report(u, v, k, dd)
971
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
972
+
973
+
974
+ class MultiEdgeDataView(OutMultiEdgeDataView):
975
+ """An EdgeDataView class for edges of MultiGraph; See EdgeDataView"""
976
+
977
+ __slots__ = ()
978
+
979
+ def __iter__(self):
980
+ seen = {}
981
+ for n, nbrs in self._nodes_nbrs():
982
+ for nbr, kd in nbrs.items():
983
+ if nbr not in seen:
984
+ for k, dd in kd.items():
985
+ yield self._report(n, nbr, k, dd)
986
+ seen[n] = 1
987
+ del seen
988
+
989
+ def __contains__(self, e):
990
+ u, v = e[:2]
991
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
992
+ return False # this edge doesn't start and doesn't end in nbunch
993
+ try:
994
+ kdict = self._adjdict[u][v]
995
+ except KeyError:
996
+ try:
997
+ kdict = self._adjdict[v][u]
998
+ except KeyError:
999
+ return False
1000
+ if self.keys is True:
1001
+ k = e[2]
1002
+ try:
1003
+ dd = kdict[k]
1004
+ except KeyError:
1005
+ return False
1006
+ return e == self._report(u, v, k, dd)
1007
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1008
+
1009
+
1010
+ class InMultiEdgeDataView(OutMultiEdgeDataView):
1011
+ """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView"""
1012
+
1013
+ __slots__ = ()
1014
+
1015
+ def __iter__(self):
1016
+ return (
1017
+ self._report(nbr, n, k, dd)
1018
+ for n, nbrs in self._nodes_nbrs()
1019
+ for nbr, kd in nbrs.items()
1020
+ for k, dd in kd.items()
1021
+ )
1022
+
1023
+ def __contains__(self, e):
1024
+ u, v = e[:2]
1025
+ if self._nbunch is not None and v not in self._nbunch:
1026
+ return False # this edge doesn't end in nbunch
1027
+ try:
1028
+ kdict = self._adjdict[v][u]
1029
+ except KeyError:
1030
+ return False
1031
+ if self.keys is True:
1032
+ k = e[2]
1033
+ dd = kdict[k]
1034
+ return e == self._report(u, v, k, dd)
1035
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1036
+
1037
+
1038
+ # EdgeViews have set operations and no data reported
1039
+ class OutEdgeView(Set, Mapping):
1040
+ """A EdgeView class for outward edges of a DiGraph"""
1041
+
1042
+ __slots__ = ("_adjdict", "_graph", "_nodes_nbrs")
1043
+
1044
+ def __getstate__(self):
1045
+ return {"_graph": self._graph, "_adjdict": self._adjdict}
1046
+
1047
+ def __setstate__(self, state):
1048
+ self._graph = state["_graph"]
1049
+ self._adjdict = state["_adjdict"]
1050
+ self._nodes_nbrs = self._adjdict.items
1051
+
1052
+ @classmethod
1053
+ def _from_iterable(cls, it):
1054
+ return set(it)
1055
+
1056
+ dataview = OutEdgeDataView
1057
+
1058
+ def __init__(self, G):
1059
+ self._graph = G
1060
+ self._adjdict = G._succ if hasattr(G, "succ") else G._adj
1061
+ self._nodes_nbrs = self._adjdict.items
1062
+
1063
+ # Set methods
1064
+ def __len__(self):
1065
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
1066
+
1067
+ def __iter__(self):
1068
+ for n, nbrs in self._nodes_nbrs():
1069
+ for nbr in nbrs:
1070
+ yield (n, nbr)
1071
+
1072
+ def __contains__(self, e):
1073
+ try:
1074
+ u, v = e
1075
+ return v in self._adjdict[u]
1076
+ except KeyError:
1077
+ return False
1078
+
1079
+ # Mapping Methods
1080
+ def __getitem__(self, e):
1081
+ if isinstance(e, slice):
1082
+ raise nx.NetworkXError(
1083
+ f"{type(self).__name__} does not support slicing, "
1084
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1085
+ )
1086
+ u, v = e
1087
+ try:
1088
+ return self._adjdict[u][v]
1089
+ except KeyError as ex: # Customize msg to indicate exception origin
1090
+ raise KeyError(f"The edge {e} is not in the graph.")
1091
+
1092
+ # EdgeDataView methods
1093
+ def __call__(self, nbunch=None, data=False, *, default=None):
1094
+ if nbunch is None and data is False:
1095
+ return self
1096
+ return self.dataview(self, nbunch, data, default=default)
1097
+
1098
+ def data(self, data=True, default=None, nbunch=None):
1099
+ """
1100
+ Return a read-only view of edge data.
1101
+
1102
+ Parameters
1103
+ ----------
1104
+ data : bool or edge attribute key
1105
+ If ``data=True``, then the data view maps each edge to a dictionary
1106
+ containing all of its attributes. If `data` is a key in the edge
1107
+ dictionary, then the data view maps each edge to its value for
1108
+ the keyed attribute. In this case, if the edge doesn't have the
1109
+ attribute, the `default` value is returned.
1110
+ default : object, default=None
1111
+ The value used when an edge does not have a specific attribute
1112
+ nbunch : container of nodes, optional (default=None)
1113
+ Allows restriction to edges only involving certain nodes. All edges
1114
+ are considered by default.
1115
+
1116
+ Returns
1117
+ -------
1118
+ dataview
1119
+ Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView`
1120
+ for DiGraphs, `MultiEdgeDataView` for MultiGraphs and
1121
+ `OutMultiEdgeDataView` for MultiDiGraphs.
1122
+
1123
+ Notes
1124
+ -----
1125
+ If ``data=False``, returns an `EdgeView` without any edge data.
1126
+
1127
+ See Also
1128
+ --------
1129
+ EdgeDataView
1130
+ OutEdgeDataView
1131
+ MultiEdgeDataView
1132
+ OutMultiEdgeDataView
1133
+
1134
+ Examples
1135
+ --------
1136
+ >>> G = nx.Graph()
1137
+ >>> G.add_edges_from(
1138
+ ... [
1139
+ ... (0, 1, {"dist": 3, "capacity": 20}),
1140
+ ... (1, 2, {"dist": 4}),
1141
+ ... (2, 0, {"dist": 5}),
1142
+ ... ]
1143
+ ... )
1144
+
1145
+ Accessing edge data with ``data=True`` (the default) returns an
1146
+ edge data view object listing each edge with all of its attributes:
1147
+
1148
+ >>> G.edges.data()
1149
+ EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})])
1150
+
1151
+ If `data` represents a key in the edge attribute dict, a dataview listing
1152
+ each edge with its value for that specific key is returned:
1153
+
1154
+ >>> G.edges.data("dist")
1155
+ EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)])
1156
+
1157
+ `nbunch` can be used to limit the edges:
1158
+
1159
+ >>> G.edges.data("dist", nbunch=[0])
1160
+ EdgeDataView([(0, 1, 3), (0, 2, 5)])
1161
+
1162
+ If a specific key is not found in an edge attribute dict, the value
1163
+ specified by `default` is used:
1164
+
1165
+ >>> G.edges.data("capacity")
1166
+ EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)])
1167
+
1168
+ Note that there is no check that the `data` key is present in any of
1169
+ the edge attribute dictionaries:
1170
+
1171
+ >>> G.edges.data("speed")
1172
+ EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)])
1173
+ """
1174
+ if nbunch is None and data is False:
1175
+ return self
1176
+ return self.dataview(self, nbunch, data, default=default)
1177
+
1178
+ # String Methods
1179
+ def __str__(self):
1180
+ return str(list(self))
1181
+
1182
+ def __repr__(self):
1183
+ return f"{self.__class__.__name__}({list(self)})"
1184
+
1185
+
1186
+ class EdgeView(OutEdgeView):
1187
+ """A EdgeView class for edges of a Graph
1188
+
1189
+ This densely packed View allows iteration over edges, data lookup
1190
+ like a dict and set operations on edges represented by node-tuples.
1191
+ In addition, edge data can be controlled by calling this object
1192
+ possibly creating an EdgeDataView. Typically edges are iterated over
1193
+ and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples
1194
+ for multigraphs. Those edge representations can also be using to
1195
+ lookup the data dict for any edge. Set operations also are available
1196
+ where those tuples are the elements of the set.
1197
+ Calling this object with optional arguments `data`, `default` and `keys`
1198
+ controls the form of the tuple (see EdgeDataView). Optional argument
1199
+ `nbunch` allows restriction to edges only involving certain nodes.
1200
+
1201
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
1202
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
1203
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
1204
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above.
1205
+
1206
+ Parameters
1207
+ ==========
1208
+ graph : NetworkX graph-like class
1209
+ nbunch : (default= all nodes in graph) only report edges with these nodes
1210
+ keys : (only for MultiGraph. default=False) report edge key in tuple
1211
+ data : bool or string (default=False) see above
1212
+ default : object (default=None)
1213
+
1214
+ Examples
1215
+ ========
1216
+ >>> G = nx.path_graph(4)
1217
+ >>> EV = G.edges()
1218
+ >>> (2, 3) in EV
1219
+ True
1220
+ >>> for u, v in EV:
1221
+ ... print((u, v))
1222
+ (0, 1)
1223
+ (1, 2)
1224
+ (2, 3)
1225
+ >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)}
1226
+
1227
+ >>> EVdata = G.edges(data="color", default="aqua")
1228
+ >>> G.add_edge(2, 3, color="blue")
1229
+ >>> assert (2, 3, "blue") in EVdata
1230
+ >>> for u, v, c in EVdata:
1231
+ ... print(f"({u}, {v}) has color: {c}")
1232
+ (0, 1) has color: aqua
1233
+ (1, 2) has color: aqua
1234
+ (2, 3) has color: blue
1235
+
1236
+ >>> EVnbunch = G.edges(nbunch=2)
1237
+ >>> assert (2, 3) in EVnbunch
1238
+ >>> assert (0, 1) not in EVnbunch
1239
+ >>> for u, v in EVnbunch:
1240
+ ... assert u == 2 or v == 2
1241
+
1242
+ >>> MG = nx.path_graph(4, create_using=nx.MultiGraph)
1243
+ >>> EVmulti = MG.edges(keys=True)
1244
+ >>> (2, 3, 0) in EVmulti
1245
+ True
1246
+ >>> (2, 3) in EVmulti # 2-tuples work even when keys is True
1247
+ True
1248
+ >>> key = MG.add_edge(2, 3)
1249
+ >>> for u, v, k in EVmulti:
1250
+ ... print((u, v, k))
1251
+ (0, 1, 0)
1252
+ (1, 2, 0)
1253
+ (2, 3, 0)
1254
+ (2, 3, 1)
1255
+ """
1256
+
1257
+ __slots__ = ()
1258
+
1259
+ dataview = EdgeDataView
1260
+
1261
+ def __len__(self):
1262
+ num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs())
1263
+ return sum(num_nbrs) // 2
1264
+
1265
+ def __iter__(self):
1266
+ seen = {}
1267
+ for n, nbrs in self._nodes_nbrs():
1268
+ for nbr in list(nbrs):
1269
+ if nbr not in seen:
1270
+ yield (n, nbr)
1271
+ seen[n] = 1
1272
+ del seen
1273
+
1274
+ def __contains__(self, e):
1275
+ try:
1276
+ u, v = e[:2]
1277
+ return v in self._adjdict[u] or u in self._adjdict[v]
1278
+ except (KeyError, ValueError):
1279
+ return False
1280
+
1281
+
1282
+ class InEdgeView(OutEdgeView):
1283
+ """A EdgeView class for inward edges of a DiGraph"""
1284
+
1285
+ __slots__ = ()
1286
+
1287
+ def __setstate__(self, state):
1288
+ self._graph = state["_graph"]
1289
+ self._adjdict = state["_adjdict"]
1290
+ self._nodes_nbrs = self._adjdict.items
1291
+
1292
+ dataview = InEdgeDataView
1293
+
1294
+ def __init__(self, G):
1295
+ self._graph = G
1296
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1297
+ self._nodes_nbrs = self._adjdict.items
1298
+
1299
+ def __iter__(self):
1300
+ for n, nbrs in self._nodes_nbrs():
1301
+ for nbr in nbrs:
1302
+ yield (nbr, n)
1303
+
1304
+ def __contains__(self, e):
1305
+ try:
1306
+ u, v = e
1307
+ return u in self._adjdict[v]
1308
+ except KeyError:
1309
+ return False
1310
+
1311
+ def __getitem__(self, e):
1312
+ if isinstance(e, slice):
1313
+ raise nx.NetworkXError(
1314
+ f"{type(self).__name__} does not support slicing, "
1315
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1316
+ )
1317
+ u, v = e
1318
+ return self._adjdict[v][u]
1319
+
1320
+
1321
+ class OutMultiEdgeView(OutEdgeView):
1322
+ """A EdgeView class for outward edges of a MultiDiGraph"""
1323
+
1324
+ __slots__ = ()
1325
+
1326
+ dataview = OutMultiEdgeDataView
1327
+
1328
+ def __len__(self):
1329
+ return sum(
1330
+ len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items()
1331
+ )
1332
+
1333
+ def __iter__(self):
1334
+ for n, nbrs in self._nodes_nbrs():
1335
+ for nbr, kdict in nbrs.items():
1336
+ for key in kdict:
1337
+ yield (n, nbr, key)
1338
+
1339
+ def __contains__(self, e):
1340
+ N = len(e)
1341
+ if N == 3:
1342
+ u, v, k = e
1343
+ elif N == 2:
1344
+ u, v = e
1345
+ k = 0
1346
+ else:
1347
+ raise ValueError("MultiEdge must have length 2 or 3")
1348
+ try:
1349
+ return k in self._adjdict[u][v]
1350
+ except KeyError:
1351
+ return False
1352
+
1353
+ def __getitem__(self, e):
1354
+ if isinstance(e, slice):
1355
+ raise nx.NetworkXError(
1356
+ f"{type(self).__name__} does not support slicing, "
1357
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1358
+ )
1359
+ u, v, k = e
1360
+ return self._adjdict[u][v][k]
1361
+
1362
+ def __call__(self, nbunch=None, data=False, *, default=None, keys=False):
1363
+ if nbunch is None and data is False and keys is True:
1364
+ return self
1365
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1366
+
1367
+ def data(self, data=True, default=None, nbunch=None, keys=False):
1368
+ if nbunch is None and data is False and keys is True:
1369
+ return self
1370
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1371
+
1372
+
1373
+ class MultiEdgeView(OutMultiEdgeView):
1374
+ """A EdgeView class for edges of a MultiGraph"""
1375
+
1376
+ __slots__ = ()
1377
+
1378
+ dataview = MultiEdgeDataView
1379
+
1380
+ def __len__(self):
1381
+ return sum(1 for e in self)
1382
+
1383
+ def __iter__(self):
1384
+ seen = {}
1385
+ for n, nbrs in self._nodes_nbrs():
1386
+ for nbr, kd in nbrs.items():
1387
+ if nbr not in seen:
1388
+ for k, dd in kd.items():
1389
+ yield (n, nbr, k)
1390
+ seen[n] = 1
1391
+ del seen
1392
+
1393
+
1394
+ class InMultiEdgeView(OutMultiEdgeView):
1395
+ """A EdgeView class for inward edges of a MultiDiGraph"""
1396
+
1397
+ __slots__ = ()
1398
+
1399
+ def __setstate__(self, state):
1400
+ self._graph = state["_graph"]
1401
+ self._adjdict = state["_adjdict"]
1402
+ self._nodes_nbrs = self._adjdict.items
1403
+
1404
+ dataview = InMultiEdgeDataView
1405
+
1406
+ def __init__(self, G):
1407
+ self._graph = G
1408
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1409
+ self._nodes_nbrs = self._adjdict.items
1410
+
1411
+ def __iter__(self):
1412
+ for n, nbrs in self._nodes_nbrs():
1413
+ for nbr, kdict in nbrs.items():
1414
+ for key in kdict:
1415
+ yield (nbr, n, key)
1416
+
1417
+ def __contains__(self, e):
1418
+ N = len(e)
1419
+ if N == 3:
1420
+ u, v, k = e
1421
+ elif N == 2:
1422
+ u, v = e
1423
+ k = 0
1424
+ else:
1425
+ raise ValueError("MultiEdge must have length 2 or 3")
1426
+ try:
1427
+ return k in self._adjdict[v][u]
1428
+ except KeyError:
1429
+ return False
1430
+
1431
+ def __getitem__(self, e):
1432
+ if isinstance(e, slice):
1433
+ raise nx.NetworkXError(
1434
+ f"{type(self).__name__} does not support slicing, "
1435
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1436
+ )
1437
+ u, v, k = e
1438
+ return self._adjdict[v][u][k]
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_graph.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import pickle
3
+ import platform
4
+ import weakref
5
+
6
+ import pytest
7
+
8
+ import networkx as nx
9
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
10
+
11
+
12
+ class BaseGraphTester:
13
+ """Tests for data-structure independent graph class features."""
14
+
15
+ def test_contains(self):
16
+ G = self.K3
17
+ assert 1 in G
18
+ assert 4 not in G
19
+ assert "b" not in G
20
+ assert [] not in G # no exception for nonhashable
21
+ assert {1: 1} not in G # no exception for nonhashable
22
+
23
+ def test_order(self):
24
+ G = self.K3
25
+ assert len(G) == 3
26
+ assert G.order() == 3
27
+ assert G.number_of_nodes() == 3
28
+
29
+ def test_nodes(self):
30
+ G = self.K3
31
+ assert isinstance(G._node, G.node_dict_factory)
32
+ assert isinstance(G._adj, G.adjlist_outer_dict_factory)
33
+ assert all(
34
+ isinstance(adj, G.adjlist_inner_dict_factory) for adj in G._adj.values()
35
+ )
36
+ assert sorted(G.nodes()) == self.k3nodes
37
+ assert sorted(G.nodes(data=True)) == [(0, {}), (1, {}), (2, {})]
38
+
39
+ def test_none_node(self):
40
+ G = self.Graph()
41
+ with pytest.raises(ValueError):
42
+ G.add_node(None)
43
+ with pytest.raises(ValueError):
44
+ G.add_nodes_from([None])
45
+ with pytest.raises(ValueError):
46
+ G.add_edge(0, None)
47
+ with pytest.raises(ValueError):
48
+ G.add_edges_from([(0, None)])
49
+
50
+ def test_has_node(self):
51
+ G = self.K3
52
+ assert G.has_node(1)
53
+ assert not G.has_node(4)
54
+ assert not G.has_node([]) # no exception for nonhashable
55
+ assert not G.has_node({1: 1}) # no exception for nonhashable
56
+
57
+ def test_has_edge(self):
58
+ G = self.K3
59
+ assert G.has_edge(0, 1)
60
+ assert not G.has_edge(0, -1)
61
+
62
+ def test_neighbors(self):
63
+ G = self.K3
64
+ assert sorted(G.neighbors(0)) == [1, 2]
65
+ with pytest.raises(nx.NetworkXError):
66
+ G.neighbors(-1)
67
+
68
+ @pytest.mark.skipif(
69
+ platform.python_implementation() == "PyPy", reason="PyPy gc is different"
70
+ )
71
+ def test_memory_leak(self):
72
+ G = self.Graph()
73
+
74
+ def count_objects_of_type(_type):
75
+ # Iterating over all objects tracked by gc can include weak references
76
+ # whose weakly-referenced objects may no longer exist. Calling `isinstance`
77
+ # on such a weak reference will raise ReferenceError. There are at least
78
+ # three workarounds for this: one is to compare type names instead of using
79
+ # `isinstance` such as `type(obj).__name__ == typename`, another is to use
80
+ # `type(obj) == _type`, and the last is to ignore ProxyTypes as we do below.
81
+ # NOTE: even if this safeguard is deemed unnecessary to pass NetworkX tests,
82
+ # we should still keep it for maximum safety for other NetworkX backends.
83
+ return sum(
84
+ 1
85
+ for obj in gc.get_objects()
86
+ if not isinstance(obj, weakref.ProxyTypes) and isinstance(obj, _type)
87
+ )
88
+
89
+ gc.collect()
90
+ before = count_objects_of_type(self.Graph)
91
+ G.copy()
92
+ gc.collect()
93
+ after = count_objects_of_type(self.Graph)
94
+ assert before == after
95
+
96
+ # test a subgraph of the base class
97
+ class MyGraph(self.Graph):
98
+ pass
99
+
100
+ gc.collect()
101
+ G = MyGraph()
102
+ before = count_objects_of_type(MyGraph)
103
+ G.copy()
104
+ gc.collect()
105
+ after = count_objects_of_type(MyGraph)
106
+ assert before == after
107
+
108
+ def test_edges(self):
109
+ G = self.K3
110
+ assert isinstance(G._adj, G.adjlist_outer_dict_factory)
111
+ assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
112
+ assert edges_equal(G.edges(0), [(0, 1), (0, 2)])
113
+ assert edges_equal(G.edges([0, 1]), [(0, 1), (0, 2), (1, 2)])
114
+ with pytest.raises(nx.NetworkXError):
115
+ G.edges(-1)
116
+
117
+ def test_degree(self):
118
+ G = self.K3
119
+ assert sorted(G.degree()) == [(0, 2), (1, 2), (2, 2)]
120
+ assert dict(G.degree()) == {0: 2, 1: 2, 2: 2}
121
+ assert G.degree(0) == 2
122
+ with pytest.raises(nx.NetworkXError):
123
+ G.degree(-1) # node not in graph
124
+
125
+ def test_size(self):
126
+ G = self.K3
127
+ assert G.size() == 3
128
+ assert G.number_of_edges() == 3
129
+
130
+ def test_nbunch_iter(self):
131
+ G = self.K3
132
+ assert nodes_equal(G.nbunch_iter(), self.k3nodes) # all nodes
133
+ assert nodes_equal(G.nbunch_iter(0), [0]) # single node
134
+ assert nodes_equal(G.nbunch_iter([0, 1]), [0, 1]) # sequence
135
+ # sequence with none in graph
136
+ assert nodes_equal(G.nbunch_iter([-1]), [])
137
+ # string sequence with none in graph
138
+ assert nodes_equal(G.nbunch_iter("foo"), [])
139
+ # node not in graph doesn't get caught upon creation of iterator
140
+ bunch = G.nbunch_iter(-1)
141
+ # but gets caught when iterator used
142
+ with pytest.raises(nx.NetworkXError, match="is not a node or a sequence"):
143
+ list(bunch)
144
+ # unhashable doesn't get caught upon creation of iterator
145
+ bunch = G.nbunch_iter([0, 1, 2, {}])
146
+ # but gets caught when iterator hits the unhashable
147
+ with pytest.raises(
148
+ nx.NetworkXError, match="in sequence nbunch is not a valid node"
149
+ ):
150
+ list(bunch)
151
+
152
+ def test_nbunch_iter_node_format_raise(self):
153
+ # Tests that a node that would have failed string formatting
154
+ # doesn't cause an error when attempting to raise a
155
+ # :exc:`nx.NetworkXError`.
156
+
157
+ # For more information, see pull request #1813.
158
+ G = self.Graph()
159
+ nbunch = [("x", set())]
160
+ with pytest.raises(nx.NetworkXError):
161
+ list(G.nbunch_iter(nbunch))
162
+
163
+ def test_selfloop_degree(self):
164
+ G = self.Graph()
165
+ G.add_edge(1, 1)
166
+ assert sorted(G.degree()) == [(1, 2)]
167
+ assert dict(G.degree()) == {1: 2}
168
+ assert G.degree(1) == 2
169
+ assert sorted(G.degree([1])) == [(1, 2)]
170
+ assert G.degree(1, weight="weight") == 2
171
+
172
+ def test_selfloops(self):
173
+ G = self.K3.copy()
174
+ G.add_edge(0, 0)
175
+ assert nodes_equal(nx.nodes_with_selfloops(G), [0])
176
+ assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
177
+ assert nx.number_of_selfloops(G) == 1
178
+ G.remove_edge(0, 0)
179
+ G.add_edge(0, 0)
180
+ G.remove_edges_from([(0, 0)])
181
+ G.add_edge(1, 1)
182
+ G.remove_node(1)
183
+ G.add_edge(0, 0)
184
+ G.add_edge(1, 1)
185
+ G.remove_nodes_from([0, 1])
186
+
187
+ def test_cache_reset(self):
188
+ G = self.K3.copy()
189
+ old_adj = G.adj
190
+ assert id(G.adj) == id(old_adj)
191
+ G._adj = {}
192
+ assert id(G.adj) != id(old_adj)
193
+
194
+ old_nodes = G.nodes
195
+ assert id(G.nodes) == id(old_nodes)
196
+ G._node = {}
197
+ assert id(G.nodes) != id(old_nodes)
198
+
199
+ def test_attributes_cached(self):
200
+ G = self.K3.copy()
201
+ assert id(G.nodes) == id(G.nodes)
202
+ assert id(G.edges) == id(G.edges)
203
+ assert id(G.degree) == id(G.degree)
204
+ assert id(G.adj) == id(G.adj)
205
+
206
+
207
+ class BaseAttrGraphTester(BaseGraphTester):
208
+ """Tests of graph class attribute features."""
209
+
210
+ def test_weighted_degree(self):
211
+ G = self.Graph()
212
+ G.add_edge(1, 2, weight=2, other=3)
213
+ G.add_edge(2, 3, weight=3, other=4)
214
+ assert sorted(d for n, d in G.degree(weight="weight")) == [2, 3, 5]
215
+ assert dict(G.degree(weight="weight")) == {1: 2, 2: 5, 3: 3}
216
+ assert G.degree(1, weight="weight") == 2
217
+ assert nodes_equal((G.degree([1], weight="weight")), [(1, 2)])
218
+
219
+ assert nodes_equal((d for n, d in G.degree(weight="other")), [3, 7, 4])
220
+ assert dict(G.degree(weight="other")) == {1: 3, 2: 7, 3: 4}
221
+ assert G.degree(1, weight="other") == 3
222
+ assert edges_equal((G.degree([1], weight="other")), [(1, 3)])
223
+
224
+ def add_attributes(self, G):
225
+ G.graph["foo"] = []
226
+ G.nodes[0]["foo"] = []
227
+ G.remove_edge(1, 2)
228
+ ll = []
229
+ G.add_edge(1, 2, foo=ll)
230
+ G.add_edge(2, 1, foo=ll)
231
+
232
+ def test_name(self):
233
+ G = self.Graph(name="")
234
+ assert G.name == ""
235
+ G = self.Graph(name="test")
236
+ assert G.name == "test"
237
+
238
+ def test_str_unnamed(self):
239
+ G = self.Graph()
240
+ G.add_edges_from([(1, 2), (2, 3)])
241
+ assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges"
242
+
243
+ def test_str_named(self):
244
+ G = self.Graph(name="foo")
245
+ G.add_edges_from([(1, 2), (2, 3)])
246
+ assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges"
247
+
248
+ def test_graph_chain(self):
249
+ G = self.Graph([(0, 1), (1, 2)])
250
+ DG = G.to_directed(as_view=True)
251
+ SDG = DG.subgraph([0, 1])
252
+ RSDG = SDG.reverse(copy=False)
253
+ assert G is DG._graph
254
+ assert DG is SDG._graph
255
+ assert SDG is RSDG._graph
256
+
257
+ def test_copy(self):
258
+ G = self.Graph()
259
+ G.add_node(0)
260
+ G.add_edge(1, 2)
261
+ self.add_attributes(G)
262
+ # copy edge datadict but any container attr are same
263
+ H = G.copy()
264
+ self.graphs_equal(H, G)
265
+ self.different_attrdict(H, G)
266
+ self.shallow_copy_attrdict(H, G)
267
+
268
+ def test_class_copy(self):
269
+ G = self.Graph()
270
+ G.add_node(0)
271
+ G.add_edge(1, 2)
272
+ self.add_attributes(G)
273
+ # copy edge datadict but any container attr are same
274
+ H = G.__class__(G)
275
+ self.graphs_equal(H, G)
276
+ self.different_attrdict(H, G)
277
+ self.shallow_copy_attrdict(H, G)
278
+
279
+ def test_fresh_copy(self):
280
+ G = self.Graph()
281
+ G.add_node(0)
282
+ G.add_edge(1, 2)
283
+ self.add_attributes(G)
284
+ # copy graph structure but use fresh datadict
285
+ H = G.__class__()
286
+ H.add_nodes_from(G)
287
+ H.add_edges_from(G.edges())
288
+ assert len(G.nodes[0]) == 1
289
+ ddict = G.adj[1][2][0] if G.is_multigraph() else G.adj[1][2]
290
+ assert len(ddict) == 1
291
+ assert len(H.nodes[0]) == 0
292
+ ddict = H.adj[1][2][0] if H.is_multigraph() else H.adj[1][2]
293
+ assert len(ddict) == 0
294
+
295
+ def is_deepcopy(self, H, G):
296
+ self.graphs_equal(H, G)
297
+ self.different_attrdict(H, G)
298
+ self.deep_copy_attrdict(H, G)
299
+
300
+ def deep_copy_attrdict(self, H, G):
301
+ self.deepcopy_graph_attr(H, G)
302
+ self.deepcopy_node_attr(H, G)
303
+ self.deepcopy_edge_attr(H, G)
304
+
305
+ def deepcopy_graph_attr(self, H, G):
306
+ assert G.graph["foo"] == H.graph["foo"]
307
+ G.graph["foo"].append(1)
308
+ assert G.graph["foo"] != H.graph["foo"]
309
+
310
+ def deepcopy_node_attr(self, H, G):
311
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
312
+ G.nodes[0]["foo"].append(1)
313
+ assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
314
+
315
+ def deepcopy_edge_attr(self, H, G):
316
+ assert G[1][2]["foo"] == H[1][2]["foo"]
317
+ G[1][2]["foo"].append(1)
318
+ assert G[1][2]["foo"] != H[1][2]["foo"]
319
+
320
+ def is_shallow_copy(self, H, G):
321
+ self.graphs_equal(H, G)
322
+ self.shallow_copy_attrdict(H, G)
323
+
324
+ def shallow_copy_attrdict(self, H, G):
325
+ self.shallow_copy_graph_attr(H, G)
326
+ self.shallow_copy_node_attr(H, G)
327
+ self.shallow_copy_edge_attr(H, G)
328
+
329
+ def shallow_copy_graph_attr(self, H, G):
330
+ assert G.graph["foo"] == H.graph["foo"]
331
+ G.graph["foo"].append(1)
332
+ assert G.graph["foo"] == H.graph["foo"]
333
+
334
+ def shallow_copy_node_attr(self, H, G):
335
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
336
+ G.nodes[0]["foo"].append(1)
337
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
338
+
339
+ def shallow_copy_edge_attr(self, H, G):
340
+ assert G[1][2]["foo"] == H[1][2]["foo"]
341
+ G[1][2]["foo"].append(1)
342
+ assert G[1][2]["foo"] == H[1][2]["foo"]
343
+
344
+ def same_attrdict(self, H, G):
345
+ old_foo = H[1][2]["foo"]
346
+ H.adj[1][2]["foo"] = "baz"
347
+ assert G.edges == H.edges
348
+ H.adj[1][2]["foo"] = old_foo
349
+ assert G.edges == H.edges
350
+
351
+ old_foo = H.nodes[0]["foo"]
352
+ H.nodes[0]["foo"] = "baz"
353
+ assert G.nodes == H.nodes
354
+ H.nodes[0]["foo"] = old_foo
355
+ assert G.nodes == H.nodes
356
+
357
+ def different_attrdict(self, H, G):
358
+ old_foo = H[1][2]["foo"]
359
+ H.adj[1][2]["foo"] = "baz"
360
+ assert G._adj != H._adj
361
+ H.adj[1][2]["foo"] = old_foo
362
+ assert G._adj == H._adj
363
+
364
+ old_foo = H.nodes[0]["foo"]
365
+ H.nodes[0]["foo"] = "baz"
366
+ assert G._node != H._node
367
+ H.nodes[0]["foo"] = old_foo
368
+ assert G._node == H._node
369
+
370
+ def graphs_equal(self, H, G):
371
+ assert G._adj == H._adj
372
+ assert G._node == H._node
373
+ assert G.graph == H.graph
374
+ assert G.name == H.name
375
+ if not G.is_directed() and not H.is_directed():
376
+ assert H._adj[1][2] is H._adj[2][1]
377
+ assert G._adj[1][2] is G._adj[2][1]
378
+ else: # at least one is directed
379
+ if not G.is_directed():
380
+ G._pred = G._adj
381
+ G._succ = G._adj
382
+ if not H.is_directed():
383
+ H._pred = H._adj
384
+ H._succ = H._adj
385
+ assert G._pred == H._pred
386
+ assert G._succ == H._succ
387
+ assert H._succ[1][2] is H._pred[2][1]
388
+ assert G._succ[1][2] is G._pred[2][1]
389
+
390
+ def test_graph_attr(self):
391
+ G = self.K3.copy()
392
+ G.graph["foo"] = "bar"
393
+ assert isinstance(G.graph, G.graph_attr_dict_factory)
394
+ assert G.graph["foo"] == "bar"
395
+ del G.graph["foo"]
396
+ assert G.graph == {}
397
+ H = self.Graph(foo="bar")
398
+ assert H.graph["foo"] == "bar"
399
+
400
+ def test_node_attr(self):
401
+ G = self.K3.copy()
402
+ G.add_node(1, foo="bar")
403
+ assert all(
404
+ isinstance(d, G.node_attr_dict_factory) for u, d in G.nodes(data=True)
405
+ )
406
+ assert nodes_equal(G.nodes(), [0, 1, 2])
407
+ assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "bar"}), (2, {})])
408
+ G.nodes[1]["foo"] = "baz"
409
+ assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "baz"}), (2, {})])
410
+ assert nodes_equal(G.nodes(data="foo"), [(0, None), (1, "baz"), (2, None)])
411
+ assert nodes_equal(
412
+ G.nodes(data="foo", default="bar"), [(0, "bar"), (1, "baz"), (2, "bar")]
413
+ )
414
+
415
+ def test_node_attr2(self):
416
+ G = self.K3.copy()
417
+ a = {"foo": "bar"}
418
+ G.add_node(3, **a)
419
+ assert nodes_equal(G.nodes(), [0, 1, 2, 3])
420
+ assert nodes_equal(
421
+ G.nodes(data=True), [(0, {}), (1, {}), (2, {}), (3, {"foo": "bar"})]
422
+ )
423
+
424
+ def test_edge_lookup(self):
425
+ G = self.Graph()
426
+ G.add_edge(1, 2, foo="bar")
427
+ assert edges_equal(G.edges[1, 2], {"foo": "bar"})
428
+
429
+ def test_edge_attr(self):
430
+ G = self.Graph()
431
+ G.add_edge(1, 2, foo="bar")
432
+ assert all(
433
+ isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True)
434
+ )
435
+ assert edges_equal(G.edges(data=True), [(1, 2, {"foo": "bar"})])
436
+ assert edges_equal(G.edges(data="foo"), [(1, 2, "bar")])
437
+
438
+ def test_edge_attr2(self):
439
+ G = self.Graph()
440
+ G.add_edges_from([(1, 2), (3, 4)], foo="foo")
441
+ assert edges_equal(
442
+ G.edges(data=True), [(1, 2, {"foo": "foo"}), (3, 4, {"foo": "foo"})]
443
+ )
444
+ assert edges_equal(G.edges(data="foo"), [(1, 2, "foo"), (3, 4, "foo")])
445
+
446
+ def test_edge_attr3(self):
447
+ G = self.Graph()
448
+ G.add_edges_from([(1, 2, {"weight": 32}), (3, 4, {"weight": 64})], foo="foo")
449
+ assert edges_equal(
450
+ G.edges(data=True),
451
+ [
452
+ (1, 2, {"foo": "foo", "weight": 32}),
453
+ (3, 4, {"foo": "foo", "weight": 64}),
454
+ ],
455
+ )
456
+
457
+ G.remove_edges_from([(1, 2), (3, 4)])
458
+ G.add_edge(1, 2, data=7, spam="bar", bar="foo")
459
+ assert edges_equal(
460
+ G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
461
+ )
462
+
463
+ def test_edge_attr4(self):
464
+ G = self.Graph()
465
+ G.add_edge(1, 2, data=7, spam="bar", bar="foo")
466
+ assert edges_equal(
467
+ G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
468
+ )
469
+ G[1][2]["data"] = 10 # OK to set data like this
470
+ assert edges_equal(
471
+ G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
472
+ )
473
+
474
+ G.adj[1][2]["data"] = 20
475
+ assert edges_equal(
476
+ G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
477
+ )
478
+ G.edges[1, 2]["data"] = 21 # another spelling, "edge"
479
+ assert edges_equal(
480
+ G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
481
+ )
482
+ G.adj[1][2]["listdata"] = [20, 200]
483
+ G.adj[1][2]["weight"] = 20
484
+ dd = {
485
+ "data": 21,
486
+ "spam": "bar",
487
+ "bar": "foo",
488
+ "listdata": [20, 200],
489
+ "weight": 20,
490
+ }
491
+ assert edges_equal(G.edges(data=True), [(1, 2, dd)])
492
+
493
+ def test_to_undirected(self):
494
+ G = self.K3
495
+ self.add_attributes(G)
496
+ H = nx.Graph(G)
497
+ self.is_shallow_copy(H, G)
498
+ self.different_attrdict(H, G)
499
+ H = G.to_undirected()
500
+ self.is_deepcopy(H, G)
501
+
502
+ def test_to_directed_as_view(self):
503
+ H = nx.path_graph(2, create_using=self.Graph)
504
+ H2 = H.to_directed(as_view=True)
505
+ assert H is H2._graph
506
+ assert H2.has_edge(0, 1)
507
+ assert H2.has_edge(1, 0) or H.is_directed()
508
+ pytest.raises(nx.NetworkXError, H2.add_node, -1)
509
+ pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2)
510
+ H.add_edge(1, 2)
511
+ assert H2.has_edge(1, 2)
512
+ assert H2.has_edge(2, 1) or H.is_directed()
513
+
514
+ def test_to_undirected_as_view(self):
515
+ H = nx.path_graph(2, create_using=self.Graph)
516
+ H2 = H.to_undirected(as_view=True)
517
+ assert H is H2._graph
518
+ assert H2.has_edge(0, 1)
519
+ assert H2.has_edge(1, 0)
520
+ pytest.raises(nx.NetworkXError, H2.add_node, -1)
521
+ pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2)
522
+ H.add_edge(1, 2)
523
+ assert H2.has_edge(1, 2)
524
+ assert H2.has_edge(2, 1)
525
+
526
+ def test_directed_class(self):
527
+ G = self.Graph()
528
+
529
+ class newGraph(G.to_undirected_class()):
530
+ def to_directed_class(self):
531
+ return newDiGraph
532
+
533
+ def to_undirected_class(self):
534
+ return newGraph
535
+
536
+ class newDiGraph(G.to_directed_class()):
537
+ def to_directed_class(self):
538
+ return newDiGraph
539
+
540
+ def to_undirected_class(self):
541
+ return newGraph
542
+
543
+ G = newDiGraph() if G.is_directed() else newGraph()
544
+ H = G.to_directed()
545
+ assert isinstance(H, newDiGraph)
546
+ H = G.to_undirected()
547
+ assert isinstance(H, newGraph)
548
+
549
+ def test_to_directed(self):
550
+ G = self.K3
551
+ self.add_attributes(G)
552
+ H = nx.DiGraph(G)
553
+ self.is_shallow_copy(H, G)
554
+ self.different_attrdict(H, G)
555
+ H = G.to_directed()
556
+ self.is_deepcopy(H, G)
557
+
558
+ def test_subgraph(self):
559
+ G = self.K3
560
+ self.add_attributes(G)
561
+ H = G.subgraph([0, 1, 2, 5])
562
+ self.graphs_equal(H, G)
563
+ self.same_attrdict(H, G)
564
+ self.shallow_copy_attrdict(H, G)
565
+
566
+ H = G.subgraph(0)
567
+ assert H.adj == {0: {}}
568
+ H = G.subgraph([])
569
+ assert H.adj == {}
570
+ assert G.adj != {}
571
+
572
+ def test_selfloops_attr(self):
573
+ G = self.K3.copy()
574
+ G.add_edge(0, 0)
575
+ G.add_edge(1, 1, weight=2)
576
+ assert edges_equal(
577
+ nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
578
+ )
579
+ assert edges_equal(
580
+ nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)]
581
+ )
582
+
583
+
584
+ class TestGraph(BaseAttrGraphTester):
585
+ """Tests specific to dict-of-dict-of-dict graph data structure"""
586
+
587
+ def setup_method(self):
588
+ self.Graph = nx.Graph
589
+ # build dict-of-dict-of-dict K3
590
+ ed1, ed2, ed3 = ({}, {}, {})
591
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
592
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
593
+ self.k3nodes = [0, 1, 2]
594
+ self.K3 = self.Graph()
595
+ self.K3._adj = self.k3adj
596
+ self.K3._node = {}
597
+ self.K3._node[0] = {}
598
+ self.K3._node[1] = {}
599
+ self.K3._node[2] = {}
600
+
601
+ def test_pickle(self):
602
+ G = self.K3
603
+ pg = pickle.loads(pickle.dumps(G, -1))
604
+ self.graphs_equal(pg, G)
605
+ pg = pickle.loads(pickle.dumps(G))
606
+ self.graphs_equal(pg, G)
607
+
608
+ def test_data_input(self):
609
+ G = self.Graph({1: [2], 2: [1]}, name="test")
610
+ assert G.name == "test"
611
+ assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
612
+
613
+ def test_adjacency(self):
614
+ G = self.K3
615
+ assert dict(G.adjacency()) == {
616
+ 0: {1: {}, 2: {}},
617
+ 1: {0: {}, 2: {}},
618
+ 2: {0: {}, 1: {}},
619
+ }
620
+
621
+ def test_getitem(self):
622
+ G = self.K3
623
+ assert G.adj[0] == {1: {}, 2: {}}
624
+ assert G[0] == {1: {}, 2: {}}
625
+ with pytest.raises(KeyError):
626
+ G.__getitem__("j")
627
+ with pytest.raises(TypeError):
628
+ G.__getitem__(["A"])
629
+
630
+ def test_add_node(self):
631
+ G = self.Graph()
632
+ G.add_node(0)
633
+ assert G.adj == {0: {}}
634
+ # test add attributes
635
+ G.add_node(1, c="red")
636
+ G.add_node(2, c="blue")
637
+ G.add_node(3, c="red")
638
+ assert G.nodes[1]["c"] == "red"
639
+ assert G.nodes[2]["c"] == "blue"
640
+ assert G.nodes[3]["c"] == "red"
641
+ # test updating attributes
642
+ G.add_node(1, c="blue")
643
+ G.add_node(2, c="red")
644
+ G.add_node(3, c="blue")
645
+ assert G.nodes[1]["c"] == "blue"
646
+ assert G.nodes[2]["c"] == "red"
647
+ assert G.nodes[3]["c"] == "blue"
648
+
649
+ def test_add_nodes_from(self):
650
+ G = self.Graph()
651
+ G.add_nodes_from([0, 1, 2])
652
+ assert G.adj == {0: {}, 1: {}, 2: {}}
653
+ # test add attributes
654
+ G.add_nodes_from([0, 1, 2], c="red")
655
+ assert G.nodes[0]["c"] == "red"
656
+ assert G.nodes[2]["c"] == "red"
657
+ # test that attribute dicts are not the same
658
+ assert G.nodes[0] is not G.nodes[1]
659
+ # test updating attributes
660
+ G.add_nodes_from([0, 1, 2], c="blue")
661
+ assert G.nodes[0]["c"] == "blue"
662
+ assert G.nodes[2]["c"] == "blue"
663
+ assert G.nodes[0] is not G.nodes[1]
664
+ # test tuple input
665
+ H = self.Graph()
666
+ H.add_nodes_from(G.nodes(data=True))
667
+ assert H.nodes[0]["c"] == "blue"
668
+ assert H.nodes[2]["c"] == "blue"
669
+ assert H.nodes[0] is not H.nodes[1]
670
+ # specific overrides general
671
+ H.add_nodes_from([0, (1, {"c": "green"}), (3, {"c": "cyan"})], c="red")
672
+ assert H.nodes[0]["c"] == "red"
673
+ assert H.nodes[1]["c"] == "green"
674
+ assert H.nodes[2]["c"] == "blue"
675
+ assert H.nodes[3]["c"] == "cyan"
676
+
677
+ def test_remove_node(self):
678
+ G = self.K3.copy()
679
+ G.remove_node(0)
680
+ assert G.adj == {1: {2: {}}, 2: {1: {}}}
681
+ with pytest.raises(nx.NetworkXError):
682
+ G.remove_node(-1)
683
+
684
+ # generator here to implement list,set,string...
685
+
686
+ def test_remove_nodes_from(self):
687
+ G = self.K3.copy()
688
+ G.remove_nodes_from([0, 1])
689
+ assert G.adj == {2: {}}
690
+ G.remove_nodes_from([-1]) # silent fail
691
+
692
+ def test_add_edge(self):
693
+ G = self.Graph()
694
+ G.add_edge(0, 1)
695
+ assert G.adj == {0: {1: {}}, 1: {0: {}}}
696
+ G = self.Graph()
697
+ G.add_edge(*(0, 1))
698
+ assert G.adj == {0: {1: {}}, 1: {0: {}}}
699
+ G = self.Graph()
700
+ with pytest.raises(ValueError):
701
+ G.add_edge(None, "anything")
702
+
703
+ def test_add_edges_from(self):
704
+ G = self.Graph()
705
+ G.add_edges_from([(0, 1), (0, 2, {"weight": 3})])
706
+ assert G.adj == {
707
+ 0: {1: {}, 2: {"weight": 3}},
708
+ 1: {0: {}},
709
+ 2: {0: {"weight": 3}},
710
+ }
711
+ G = self.Graph()
712
+ G.add_edges_from([(0, 1), (0, 2, {"weight": 3}), (1, 2, {"data": 4})], data=2)
713
+ assert G.adj == {
714
+ 0: {1: {"data": 2}, 2: {"weight": 3, "data": 2}},
715
+ 1: {0: {"data": 2}, 2: {"data": 4}},
716
+ 2: {0: {"weight": 3, "data": 2}, 1: {"data": 4}},
717
+ }
718
+
719
+ with pytest.raises(nx.NetworkXError):
720
+ G.add_edges_from([(0,)]) # too few in tuple
721
+ with pytest.raises(nx.NetworkXError):
722
+ G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
723
+ with pytest.raises(TypeError):
724
+ G.add_edges_from([0]) # not a tuple
725
+ with pytest.raises(ValueError):
726
+ G.add_edges_from([(None, 3), (3, 2)]) # None cannot be a node
727
+
728
+ def test_remove_edge(self):
729
+ G = self.K3.copy()
730
+ G.remove_edge(0, 1)
731
+ assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
732
+ with pytest.raises(nx.NetworkXError):
733
+ G.remove_edge(-1, 0)
734
+
735
+ def test_remove_edges_from(self):
736
+ G = self.K3.copy()
737
+ G.remove_edges_from([(0, 1)])
738
+ assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
739
+ G.remove_edges_from([(0, 0)]) # silent fail
740
+
741
+ def test_clear(self):
742
+ G = self.K3.copy()
743
+ G.graph["name"] = "K3"
744
+ G.clear()
745
+ assert list(G.nodes) == []
746
+ assert G.adj == {}
747
+ assert G.graph == {}
748
+
749
+ def test_clear_edges(self):
750
+ G = self.K3.copy()
751
+ G.graph["name"] = "K3"
752
+ nodes = list(G.nodes)
753
+ G.clear_edges()
754
+ assert list(G.nodes) == nodes
755
+ assert G.adj == {0: {}, 1: {}, 2: {}}
756
+ assert list(G.edges) == []
757
+ assert G.graph["name"] == "K3"
758
+
759
+ def test_edges_data(self):
760
+ G = self.K3
761
+ all_edges = [(0, 1, {}), (0, 2, {}), (1, 2, {})]
762
+ assert edges_equal(G.edges(data=True), all_edges)
763
+ assert edges_equal(G.edges(0, data=True), [(0, 1, {}), (0, 2, {})])
764
+ assert edges_equal(G.edges([0, 1], data=True), all_edges)
765
+ with pytest.raises(nx.NetworkXError):
766
+ G.edges(-1, True)
767
+
768
+ def test_get_edge_data(self):
769
+ G = self.K3.copy()
770
+ assert G.get_edge_data(0, 1) == {}
771
+ assert G[0][1] == {}
772
+ assert G.get_edge_data(10, 20) is None
773
+ assert G.get_edge_data(-1, 0) is None
774
+ assert G.get_edge_data(-1, 0, default=1) == 1
775
+
776
+ def test_update(self):
777
+ # specify both edges and nodes
778
+ G = self.K3.copy()
779
+ G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})])
780
+ nlist = [
781
+ (0, {}),
782
+ (1, {}),
783
+ (2, {}),
784
+ (3, {}),
785
+ (4, {"size": 2}),
786
+ (5, {}),
787
+ (6, {}),
788
+ (7, {}),
789
+ ]
790
+ assert sorted(G.nodes.data()) == nlist
791
+ if G.is_directed():
792
+ elist = [
793
+ (0, 1, {}),
794
+ (0, 2, {}),
795
+ (1, 0, {}),
796
+ (1, 2, {}),
797
+ (2, 0, {}),
798
+ (2, 1, {}),
799
+ (4, 5, {}),
800
+ (6, 7, {"weight": 2}),
801
+ ]
802
+ else:
803
+ elist = [
804
+ (0, 1, {}),
805
+ (0, 2, {}),
806
+ (1, 2, {}),
807
+ (4, 5, {}),
808
+ (6, 7, {"weight": 2}),
809
+ ]
810
+ assert sorted(G.edges.data()) == elist
811
+ assert G.graph == {}
812
+
813
+ # no keywords -- order is edges, nodes
814
+ G = self.K3.copy()
815
+ G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})])
816
+ assert sorted(G.nodes.data()) == nlist
817
+ assert sorted(G.edges.data()) == elist
818
+ assert G.graph == {}
819
+
820
+ # update using only a graph
821
+ G = self.Graph()
822
+ G.graph["foo"] = "bar"
823
+ G.add_node(2, data=4)
824
+ G.add_edge(0, 1, weight=0.5)
825
+ GG = G.copy()
826
+ H = self.Graph()
827
+ GG.update(H)
828
+ assert graphs_equal(G, GG)
829
+ H.update(G)
830
+ assert graphs_equal(H, G)
831
+
832
+ # update nodes only
833
+ H = self.Graph()
834
+ H.update(nodes=[3, 4])
835
+ assert H.nodes ^ {3, 4} == set()
836
+ assert H.size() == 0
837
+
838
+ # update edges only
839
+ H = self.Graph()
840
+ H.update(edges=[(3, 4)])
841
+ assert sorted(H.edges.data()) == [(3, 4, {})]
842
+ assert H.size() == 1
843
+
844
+ # No inputs -> exception
845
+ with pytest.raises(nx.NetworkXError):
846
+ nx.Graph().update()
847
+
848
+
849
+ class TestEdgeSubgraph:
850
+ """Unit tests for the :meth:`Graph.edge_subgraph` method."""
851
+
852
+ def setup_method(self):
853
+ # Create a path graph on five nodes.
854
+ G = nx.path_graph(5)
855
+ # Add some node, edge, and graph attributes.
856
+ for i in range(5):
857
+ G.nodes[i]["name"] = f"node{i}"
858
+ G.edges[0, 1]["name"] = "edge01"
859
+ G.edges[3, 4]["name"] = "edge34"
860
+ G.graph["name"] = "graph"
861
+ # Get the subgraph induced by the first and last edges.
862
+ self.G = G
863
+ self.H = G.edge_subgraph([(0, 1), (3, 4)])
864
+
865
+ def test_correct_nodes(self):
866
+ """Tests that the subgraph has the correct nodes."""
867
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
868
+
869
+ def test_correct_edges(self):
870
+ """Tests that the subgraph has the correct edges."""
871
+ assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name"))
872
+
873
+ def test_add_node(self):
874
+ """Tests that adding a node to the original graph does not
875
+ affect the nodes of the subgraph.
876
+
877
+ """
878
+ self.G.add_node(5)
879
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
880
+
881
+ def test_remove_node(self):
882
+ """Tests that removing a node in the original graph does
883
+ affect the nodes of the subgraph.
884
+
885
+ """
886
+ self.G.remove_node(0)
887
+ assert [1, 3, 4] == sorted(self.H.nodes())
888
+
889
+ def test_node_attr_dict(self):
890
+ """Tests that the node attribute dictionary of the two graphs is
891
+ the same object.
892
+
893
+ """
894
+ for v in self.H:
895
+ assert self.G.nodes[v] == self.H.nodes[v]
896
+ # Making a change to G should make a change in H and vice versa.
897
+ self.G.nodes[0]["name"] = "foo"
898
+ assert self.G.nodes[0] == self.H.nodes[0]
899
+ self.H.nodes[1]["name"] = "bar"
900
+ assert self.G.nodes[1] == self.H.nodes[1]
901
+
902
+ def test_edge_attr_dict(self):
903
+ """Tests that the edge attribute dictionary of the two graphs is
904
+ the same object.
905
+
906
+ """
907
+ for u, v in self.H.edges():
908
+ assert self.G.edges[u, v] == self.H.edges[u, v]
909
+ # Making a change to G should make a change in H and vice versa.
910
+ self.G.edges[0, 1]["name"] = "foo"
911
+ assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
912
+ self.H.edges[3, 4]["name"] = "bar"
913
+ assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
914
+
915
+ def test_graph_attr_dict(self):
916
+ """Tests that the graph attribute dictionary of the two graphs
917
+ is the same object.
918
+
919
+ """
920
+ assert self.G.graph is self.H.graph
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_special.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ from .test_digraph import BaseDiGraphTester
4
+ from .test_digraph import TestDiGraph as _TestDiGraph
5
+ from .test_graph import BaseGraphTester
6
+ from .test_graph import TestGraph as _TestGraph
7
+ from .test_multidigraph import TestMultiDiGraph as _TestMultiDiGraph
8
+ from .test_multigraph import TestMultiGraph as _TestMultiGraph
9
+
10
+
11
+ def test_factories():
12
+ class mydict1(dict):
13
+ pass
14
+
15
+ class mydict2(dict):
16
+ pass
17
+
18
+ class mydict3(dict):
19
+ pass
20
+
21
+ class mydict4(dict):
22
+ pass
23
+
24
+ class mydict5(dict):
25
+ pass
26
+
27
+ for Graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):
28
+ # print("testing class: ", Graph.__name__)
29
+ class MyGraph(Graph):
30
+ node_dict_factory = mydict1
31
+ adjlist_outer_dict_factory = mydict2
32
+ adjlist_inner_dict_factory = mydict3
33
+ edge_key_dict_factory = mydict4
34
+ edge_attr_dict_factory = mydict5
35
+
36
+ G = MyGraph()
37
+ assert isinstance(G._node, mydict1)
38
+ assert isinstance(G._adj, mydict2)
39
+ G.add_node(1)
40
+ assert isinstance(G._adj[1], mydict3)
41
+ if G.is_directed():
42
+ assert isinstance(G._pred, mydict2)
43
+ assert isinstance(G._succ, mydict2)
44
+ assert isinstance(G._pred[1], mydict3)
45
+ G.add_edge(1, 2)
46
+ if G.is_multigraph():
47
+ assert isinstance(G._adj[1][2], mydict4)
48
+ assert isinstance(G._adj[1][2][0], mydict5)
49
+ else:
50
+ assert isinstance(G._adj[1][2], mydict5)
51
+
52
+
53
+ class TestSpecialGraph(_TestGraph):
54
+ def setup_method(self):
55
+ _TestGraph.setup_method(self)
56
+ self.Graph = nx.Graph
57
+
58
+
59
+ class TestThinGraph(BaseGraphTester):
60
+ def setup_method(self):
61
+ all_edge_dict = {"weight": 1}
62
+
63
+ class MyGraph(nx.Graph):
64
+ def edge_attr_dict_factory(self):
65
+ return all_edge_dict
66
+
67
+ self.Graph = MyGraph
68
+ # build dict-of-dict-of-dict K3
69
+ ed1, ed2, ed3 = (all_edge_dict, all_edge_dict, all_edge_dict)
70
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
71
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
72
+ self.k3nodes = [0, 1, 2]
73
+ self.K3 = self.Graph()
74
+ self.K3._adj = self.k3adj
75
+ self.K3._node = {}
76
+ self.K3._node[0] = {}
77
+ self.K3._node[1] = {}
78
+ self.K3._node[2] = {}
79
+
80
+
81
+ class TestSpecialDiGraph(_TestDiGraph):
82
+ def setup_method(self):
83
+ _TestDiGraph.setup_method(self)
84
+ self.Graph = nx.DiGraph
85
+
86
+
87
+ class TestThinDiGraph(BaseDiGraphTester):
88
+ def setup_method(self):
89
+ all_edge_dict = {"weight": 1}
90
+
91
+ class MyGraph(nx.DiGraph):
92
+ def edge_attr_dict_factory(self):
93
+ return all_edge_dict
94
+
95
+ self.Graph = MyGraph
96
+ # build dict-of-dict-of-dict K3
97
+ ed1, ed2, ed3 = (all_edge_dict, all_edge_dict, all_edge_dict)
98
+ ed4, ed5, ed6 = (all_edge_dict, all_edge_dict, all_edge_dict)
99
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
100
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
101
+ self.k3nodes = [0, 1, 2]
102
+ self.K3 = self.Graph()
103
+ self.K3._succ = self.k3adj
104
+ # K3._adj is synced with K3._succ
105
+ self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
106
+ self.K3._node = {}
107
+ self.K3._node[0] = {}
108
+ self.K3._node[1] = {}
109
+ self.K3._node[2] = {}
110
+
111
+ ed1, ed2 = (all_edge_dict, all_edge_dict)
112
+ self.P3 = self.Graph()
113
+ self.P3._succ = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
114
+ # P3._adj is synced with P3._succ
115
+ self.P3._pred = {0: {}, 1: {0: ed1}, 2: {1: ed2}}
116
+ self.P3._node = {}
117
+ self.P3._node[0] = {}
118
+ self.P3._node[1] = {}
119
+ self.P3._node[2] = {}
120
+
121
+
122
+ class TestSpecialMultiGraph(_TestMultiGraph):
123
+ def setup_method(self):
124
+ _TestMultiGraph.setup_method(self)
125
+ self.Graph = nx.MultiGraph
126
+
127
+
128
+ class TestSpecialMultiDiGraph(_TestMultiDiGraph):
129
+ def setup_method(self):
130
+ _TestMultiDiGraph.setup_method(self)
131
+ self.Graph = nx.MultiDiGraph
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # graph drawing and interface to graphviz
2
+
3
+ from .layout import *
4
+ from .nx_latex import *
5
+ from .nx_pylab import *
6
+ from . import nx_agraph
7
+ from . import nx_pydot
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (317 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc ADDED
Binary file (33.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc ADDED
Binary file (22.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc ADDED
Binary file (51.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/layout.py ADDED
@@ -0,0 +1,1358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ******
3
+ Layout
4
+ ******
5
+
6
+ Node positioning algorithms for graph drawing.
7
+
8
+ For `random_layout()` the possible resulting shape
9
+ is a square of side [0, scale] (default: [0, 1])
10
+ Changing `center` shifts the layout by that amount.
11
+
12
+ For the other layout routines, the extent is
13
+ [center - scale, center + scale] (default: [-1, 1]).
14
+
15
+ Warning: Most layout routines have only been tested in 2-dimensions.
16
+
17
+ """
18
+ import networkx as nx
19
+ from networkx.utils import np_random_state
20
+
21
+ __all__ = [
22
+ "bipartite_layout",
23
+ "circular_layout",
24
+ "kamada_kawai_layout",
25
+ "random_layout",
26
+ "rescale_layout",
27
+ "rescale_layout_dict",
28
+ "shell_layout",
29
+ "spring_layout",
30
+ "spectral_layout",
31
+ "planar_layout",
32
+ "fruchterman_reingold_layout",
33
+ "spiral_layout",
34
+ "multipartite_layout",
35
+ "bfs_layout",
36
+ "arf_layout",
37
+ ]
38
+
39
+
40
+ def _process_params(G, center, dim):
41
+ # Some boilerplate code.
42
+ import numpy as np
43
+
44
+ if not isinstance(G, nx.Graph):
45
+ empty_graph = nx.Graph()
46
+ empty_graph.add_nodes_from(G)
47
+ G = empty_graph
48
+
49
+ if center is None:
50
+ center = np.zeros(dim)
51
+ else:
52
+ center = np.asarray(center)
53
+
54
+ if len(center) != dim:
55
+ msg = "length of center coordinates must match dimension of layout"
56
+ raise ValueError(msg)
57
+
58
+ return G, center
59
+
60
+
61
+ @np_random_state(3)
62
+ def random_layout(G, center=None, dim=2, seed=None):
63
+ """Position nodes uniformly at random in the unit square.
64
+
65
+ For every node, a position is generated by choosing each of dim
66
+ coordinates uniformly at random on the interval [0.0, 1.0).
67
+
68
+ NumPy (http://scipy.org) is required for this function.
69
+
70
+ Parameters
71
+ ----------
72
+ G : NetworkX graph or list of nodes
73
+ A position will be assigned to every node in G.
74
+
75
+ center : array-like or None
76
+ Coordinate pair around which to center the layout.
77
+
78
+ dim : int
79
+ Dimension of layout.
80
+
81
+ seed : int, RandomState instance or None optional (default=None)
82
+ Set the random state for deterministic node layouts.
83
+ If int, `seed` is the seed used by the random number generator,
84
+ if numpy.random.RandomState instance, `seed` is the random
85
+ number generator,
86
+ if None, the random number generator is the RandomState instance used
87
+ by numpy.random.
88
+
89
+ Returns
90
+ -------
91
+ pos : dict
92
+ A dictionary of positions keyed by node
93
+
94
+ Examples
95
+ --------
96
+ >>> G = nx.lollipop_graph(4, 3)
97
+ >>> pos = nx.random_layout(G)
98
+
99
+ """
100
+ import numpy as np
101
+
102
+ G, center = _process_params(G, center, dim)
103
+ pos = seed.rand(len(G), dim) + center
104
+ pos = pos.astype(np.float32)
105
+ pos = dict(zip(G, pos))
106
+
107
+ return pos
108
+
109
+
110
+ def circular_layout(G, scale=1, center=None, dim=2):
111
+ # dim=2 only
112
+ """Position nodes on a circle.
113
+
114
+ Parameters
115
+ ----------
116
+ G : NetworkX graph or list of nodes
117
+ A position will be assigned to every node in G.
118
+
119
+ scale : number (default: 1)
120
+ Scale factor for positions.
121
+
122
+ center : array-like or None
123
+ Coordinate pair around which to center the layout.
124
+
125
+ dim : int
126
+ Dimension of layout.
127
+ If dim>2, the remaining dimensions are set to zero
128
+ in the returned positions.
129
+ If dim<2, a ValueError is raised.
130
+
131
+ Returns
132
+ -------
133
+ pos : dict
134
+ A dictionary of positions keyed by node
135
+
136
+ Raises
137
+ ------
138
+ ValueError
139
+ If dim < 2
140
+
141
+ Examples
142
+ --------
143
+ >>> G = nx.path_graph(4)
144
+ >>> pos = nx.circular_layout(G)
145
+
146
+ Notes
147
+ -----
148
+ This algorithm currently only works in two dimensions and does not
149
+ try to minimize edge crossings.
150
+
151
+ """
152
+ import numpy as np
153
+
154
+ if dim < 2:
155
+ raise ValueError("cannot handle dimensions < 2")
156
+
157
+ G, center = _process_params(G, center, dim)
158
+
159
+ paddims = max(0, (dim - 2))
160
+
161
+ if len(G) == 0:
162
+ pos = {}
163
+ elif len(G) == 1:
164
+ pos = {nx.utils.arbitrary_element(G): center}
165
+ else:
166
+ # Discard the extra angle since it matches 0 radians.
167
+ theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
168
+ theta = theta.astype(np.float32)
169
+ pos = np.column_stack(
170
+ [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
171
+ )
172
+ pos = rescale_layout(pos, scale=scale) + center
173
+ pos = dict(zip(G, pos))
174
+
175
+ return pos
176
+
177
+
178
+ def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2):
179
+ """Position nodes in concentric circles.
180
+
181
+ Parameters
182
+ ----------
183
+ G : NetworkX graph or list of nodes
184
+ A position will be assigned to every node in G.
185
+
186
+ nlist : list of lists
187
+ List of node lists for each shell.
188
+
189
+ rotate : angle in radians (default=pi/len(nlist))
190
+ Angle by which to rotate the starting position of each shell
191
+ relative to the starting position of the previous shell.
192
+ To recreate behavior before v2.5 use rotate=0.
193
+
194
+ scale : number (default: 1)
195
+ Scale factor for positions.
196
+
197
+ center : array-like or None
198
+ Coordinate pair around which to center the layout.
199
+
200
+ dim : int
201
+ Dimension of layout, currently only dim=2 is supported.
202
+ Other dimension values result in a ValueError.
203
+
204
+ Returns
205
+ -------
206
+ pos : dict
207
+ A dictionary of positions keyed by node
208
+
209
+ Raises
210
+ ------
211
+ ValueError
212
+ If dim != 2
213
+
214
+ Examples
215
+ --------
216
+ >>> G = nx.path_graph(4)
217
+ >>> shells = [[0], [1, 2, 3]]
218
+ >>> pos = nx.shell_layout(G, shells)
219
+
220
+ Notes
221
+ -----
222
+ This algorithm currently only works in two dimensions and does not
223
+ try to minimize edge crossings.
224
+
225
+ """
226
+ import numpy as np
227
+
228
+ if dim != 2:
229
+ raise ValueError("can only handle 2 dimensions")
230
+
231
+ G, center = _process_params(G, center, dim)
232
+
233
+ if len(G) == 0:
234
+ return {}
235
+ if len(G) == 1:
236
+ return {nx.utils.arbitrary_element(G): center}
237
+
238
+ if nlist is None:
239
+ # draw the whole graph in one shell
240
+ nlist = [list(G)]
241
+
242
+ radius_bump = scale / len(nlist)
243
+
244
+ if len(nlist[0]) == 1:
245
+ # single node at center
246
+ radius = 0.0
247
+ else:
248
+ # else start at r=1
249
+ radius = radius_bump
250
+
251
+ if rotate is None:
252
+ rotate = np.pi / len(nlist)
253
+ first_theta = rotate
254
+ npos = {}
255
+ for nodes in nlist:
256
+ # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
257
+ theta = (
258
+ np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
259
+ + first_theta
260
+ )
261
+ pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
262
+ npos.update(zip(nodes, pos))
263
+ radius += radius_bump
264
+ first_theta += rotate
265
+
266
+ return npos
267
+
268
+
269
+ def bipartite_layout(
270
+ G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3
271
+ ):
272
+ """Position nodes in two straight lines.
273
+
274
+ Parameters
275
+ ----------
276
+ G : NetworkX graph or list of nodes
277
+ A position will be assigned to every node in G.
278
+
279
+ nodes : list or container
280
+ Nodes in one node set of the bipartite graph.
281
+ This set will be placed on left or top.
282
+
283
+ align : string (default='vertical')
284
+ The alignment of nodes. Vertical or horizontal.
285
+
286
+ scale : number (default: 1)
287
+ Scale factor for positions.
288
+
289
+ center : array-like or None
290
+ Coordinate pair around which to center the layout.
291
+
292
+ aspect_ratio : number (default=4/3):
293
+ The ratio of the width to the height of the layout.
294
+
295
+ Returns
296
+ -------
297
+ pos : dict
298
+ A dictionary of positions keyed by node.
299
+
300
+ Examples
301
+ --------
302
+ >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
303
+ >>> top = nx.bipartite.sets(G)[0]
304
+ >>> pos = nx.bipartite_layout(G, top)
305
+
306
+ Notes
307
+ -----
308
+ This algorithm currently only works in two dimensions and does not
309
+ try to minimize edge crossings.
310
+
311
+ """
312
+
313
+ import numpy as np
314
+
315
+ if align not in ("vertical", "horizontal"):
316
+ msg = "align must be either vertical or horizontal."
317
+ raise ValueError(msg)
318
+
319
+ G, center = _process_params(G, center=center, dim=2)
320
+ if len(G) == 0:
321
+ return {}
322
+
323
+ height = 1
324
+ width = aspect_ratio * height
325
+ offset = (width / 2, height / 2)
326
+
327
+ top = dict.fromkeys(nodes)
328
+ bottom = [v for v in G if v not in top]
329
+ nodes = list(top) + bottom
330
+
331
+ left_xs = np.repeat(0, len(top))
332
+ right_xs = np.repeat(width, len(bottom))
333
+ left_ys = np.linspace(0, height, len(top))
334
+ right_ys = np.linspace(0, height, len(bottom))
335
+
336
+ top_pos = np.column_stack([left_xs, left_ys]) - offset
337
+ bottom_pos = np.column_stack([right_xs, right_ys]) - offset
338
+
339
+ pos = np.concatenate([top_pos, bottom_pos])
340
+ pos = rescale_layout(pos, scale=scale) + center
341
+ if align == "horizontal":
342
+ pos = pos[:, ::-1] # swap x and y coords
343
+ pos = dict(zip(nodes, pos))
344
+ return pos
345
+
346
+
347
+ @np_random_state(10)
348
+ def spring_layout(
349
+ G,
350
+ k=None,
351
+ pos=None,
352
+ fixed=None,
353
+ iterations=50,
354
+ threshold=1e-4,
355
+ weight="weight",
356
+ scale=1,
357
+ center=None,
358
+ dim=2,
359
+ seed=None,
360
+ ):
361
+ """Position nodes using Fruchterman-Reingold force-directed algorithm.
362
+
363
+ The algorithm simulates a force-directed representation of the network
364
+ treating edges as springs holding nodes close, while treating nodes
365
+ as repelling objects, sometimes called an anti-gravity force.
366
+ Simulation continues until the positions are close to an equilibrium.
367
+
368
+ There are some hard-coded values: minimal distance between
369
+ nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
370
+ During the simulation, `k` helps determine the distance between nodes,
371
+ though `scale` and `center` determine the size and place after
372
+ rescaling occurs at the end of the simulation.
373
+
374
+ Fixing some nodes doesn't allow them to move in the simulation.
375
+ It also turns off the rescaling feature at the simulation's end.
376
+ In addition, setting `scale` to `None` turns off rescaling.
377
+
378
+ Parameters
379
+ ----------
380
+ G : NetworkX graph or list of nodes
381
+ A position will be assigned to every node in G.
382
+
383
+ k : float (default=None)
384
+ Optimal distance between nodes. If None the distance is set to
385
+ 1/sqrt(n) where n is the number of nodes. Increase this value
386
+ to move nodes farther apart.
387
+
388
+ pos : dict or None optional (default=None)
389
+ Initial positions for nodes as a dictionary with node as keys
390
+ and values as a coordinate list or tuple. If None, then use
391
+ random initial positions.
392
+
393
+ fixed : list or None optional (default=None)
394
+ Nodes to keep fixed at initial position.
395
+ Nodes not in ``G.nodes`` are ignored.
396
+ ValueError raised if `fixed` specified and `pos` not.
397
+
398
+ iterations : int optional (default=50)
399
+ Maximum number of iterations taken
400
+
401
+ threshold: float optional (default = 1e-4)
402
+ Threshold for relative error in node position changes.
403
+ The iteration stops if the error is below this threshold.
404
+
405
+ weight : string or None optional (default='weight')
406
+ The edge attribute that holds the numerical value used for
407
+ the edge weight. Larger means a stronger attractive force.
408
+ If None, then all edge weights are 1.
409
+
410
+ scale : number or None (default: 1)
411
+ Scale factor for positions. Not used unless `fixed is None`.
412
+ If scale is None, no rescaling is performed.
413
+
414
+ center : array-like or None
415
+ Coordinate pair around which to center the layout.
416
+ Not used unless `fixed is None`.
417
+
418
+ dim : int
419
+ Dimension of layout.
420
+
421
+ seed : int, RandomState instance or None optional (default=None)
422
+ Set the random state for deterministic node layouts.
423
+ If int, `seed` is the seed used by the random number generator,
424
+ if numpy.random.RandomState instance, `seed` is the random
425
+ number generator,
426
+ if None, the random number generator is the RandomState instance used
427
+ by numpy.random.
428
+
429
+ Returns
430
+ -------
431
+ pos : dict
432
+ A dictionary of positions keyed by node
433
+
434
+ Examples
435
+ --------
436
+ >>> G = nx.path_graph(4)
437
+ >>> pos = nx.spring_layout(G)
438
+
439
+ # The same using longer but equivalent function name
440
+ >>> pos = nx.fruchterman_reingold_layout(G)
441
+ """
442
+ import numpy as np
443
+
444
+ G, center = _process_params(G, center, dim)
445
+
446
+ if fixed is not None:
447
+ if pos is None:
448
+ raise ValueError("nodes are fixed without positions given")
449
+ for node in fixed:
450
+ if node not in pos:
451
+ raise ValueError("nodes are fixed without positions given")
452
+ nfixed = {node: i for i, node in enumerate(G)}
453
+ fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
454
+
455
+ if pos is not None:
456
+ # Determine size of existing domain to adjust initial positions
457
+ dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
458
+ if dom_size == 0:
459
+ dom_size = 1
460
+ pos_arr = seed.rand(len(G), dim) * dom_size + center
461
+
462
+ for i, n in enumerate(G):
463
+ if n in pos:
464
+ pos_arr[i] = np.asarray(pos[n])
465
+ else:
466
+ pos_arr = None
467
+ dom_size = 1
468
+
469
+ if len(G) == 0:
470
+ return {}
471
+ if len(G) == 1:
472
+ return {nx.utils.arbitrary_element(G.nodes()): center}
473
+
474
+ try:
475
+ # Sparse matrix
476
+ if len(G) < 500: # sparse solver for large graphs
477
+ raise ValueError
478
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
479
+ if k is None and fixed is not None:
480
+ # We must adjust k by domain size for layouts not near 1x1
481
+ nnodes, _ = A.shape
482
+ k = dom_size / np.sqrt(nnodes)
483
+ pos = _sparse_fruchterman_reingold(
484
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
485
+ )
486
+ except ValueError:
487
+ A = nx.to_numpy_array(G, weight=weight)
488
+ if k is None and fixed is not None:
489
+ # We must adjust k by domain size for layouts not near 1x1
490
+ nnodes, _ = A.shape
491
+ k = dom_size / np.sqrt(nnodes)
492
+ pos = _fruchterman_reingold(
493
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
494
+ )
495
+ if fixed is None and scale is not None:
496
+ pos = rescale_layout(pos, scale=scale) + center
497
+ pos = dict(zip(G, pos))
498
+ return pos
499
+
500
+
501
+ fruchterman_reingold_layout = spring_layout
502
+
503
+
504
+ @np_random_state(7)
505
+ def _fruchterman_reingold(
506
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
507
+ ):
508
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
509
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
510
+ import numpy as np
511
+
512
+ try:
513
+ nnodes, _ = A.shape
514
+ except AttributeError as err:
515
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
516
+ raise nx.NetworkXError(msg) from err
517
+
518
+ if pos is None:
519
+ # random initial positions
520
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
521
+ else:
522
+ # make sure positions are of same type as matrix
523
+ pos = pos.astype(A.dtype)
524
+
525
+ # optimal distance between nodes
526
+ if k is None:
527
+ k = np.sqrt(1.0 / nnodes)
528
+ # the initial "temperature" is about .1 of domain area (=1x1)
529
+ # this is the largest step allowed in the dynamics.
530
+ # We need to calculate this in case our fixed positions force our domain
531
+ # to be much bigger than 1x1
532
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
533
+ # simple cooling scheme.
534
+ # linearly step down by dt on each iteration so last iteration is size dt.
535
+ dt = t / (iterations + 1)
536
+ delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
537
+ # the inscrutable (but fast) version
538
+ # this is still O(V^2)
539
+ # could use multilevel methods to speed this up significantly
540
+ for iteration in range(iterations):
541
+ # matrix of difference between points
542
+ delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
543
+ # distance between points
544
+ distance = np.linalg.norm(delta, axis=-1)
545
+ # enforce minimum distance of 0.01
546
+ np.clip(distance, 0.01, None, out=distance)
547
+ # displacement "force"
548
+ displacement = np.einsum(
549
+ "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
550
+ )
551
+ # update positions
552
+ length = np.linalg.norm(displacement, axis=-1)
553
+ length = np.where(length < 0.01, 0.1, length)
554
+ delta_pos = np.einsum("ij,i->ij", displacement, t / length)
555
+ if fixed is not None:
556
+ # don't change positions of fixed nodes
557
+ delta_pos[fixed] = 0.0
558
+ pos += delta_pos
559
+ # cool temperature
560
+ t -= dt
561
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
562
+ break
563
+ return pos
564
+
565
+
566
+ @np_random_state(7)
567
+ def _sparse_fruchterman_reingold(
568
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
569
+ ):
570
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
571
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
572
+ # Sparse version
573
+ import numpy as np
574
+ import scipy as sp
575
+
576
+ try:
577
+ nnodes, _ = A.shape
578
+ except AttributeError as err:
579
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
580
+ raise nx.NetworkXError(msg) from err
581
+ # make sure we have a LIst of Lists representation
582
+ try:
583
+ A = A.tolil()
584
+ except AttributeError:
585
+ A = (sp.sparse.coo_array(A)).tolil()
586
+
587
+ if pos is None:
588
+ # random initial positions
589
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
590
+ else:
591
+ # make sure positions are of same type as matrix
592
+ pos = pos.astype(A.dtype)
593
+
594
+ # no fixed nodes
595
+ if fixed is None:
596
+ fixed = []
597
+
598
+ # optimal distance between nodes
599
+ if k is None:
600
+ k = np.sqrt(1.0 / nnodes)
601
+ # the initial "temperature" is about .1 of domain area (=1x1)
602
+ # this is the largest step allowed in the dynamics.
603
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
604
+ # simple cooling scheme.
605
+ # linearly step down by dt on each iteration so last iteration is size dt.
606
+ dt = t / (iterations + 1)
607
+
608
+ displacement = np.zeros((dim, nnodes))
609
+ for iteration in range(iterations):
610
+ displacement *= 0
611
+ # loop over rows
612
+ for i in range(A.shape[0]):
613
+ if i in fixed:
614
+ continue
615
+ # difference between this row's node position and all others
616
+ delta = (pos[i] - pos).T
617
+ # distance between points
618
+ distance = np.sqrt((delta**2).sum(axis=0))
619
+ # enforce minimum distance of 0.01
620
+ distance = np.where(distance < 0.01, 0.01, distance)
621
+ # the adjacency matrix row
622
+ Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
623
+ # displacement "force"
624
+ displacement[:, i] += (
625
+ delta * (k * k / distance**2 - Ai * distance / k)
626
+ ).sum(axis=1)
627
+ # update positions
628
+ length = np.sqrt((displacement**2).sum(axis=0))
629
+ length = np.where(length < 0.01, 0.1, length)
630
+ delta_pos = (displacement * t / length).T
631
+ pos += delta_pos
632
+ # cool temperature
633
+ t -= dt
634
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
635
+ break
636
+ return pos
637
+
638
+
639
+ def kamada_kawai_layout(
640
+ G, dist=None, pos=None, weight="weight", scale=1, center=None, dim=2
641
+ ):
642
+ """Position nodes using Kamada-Kawai path-length cost-function.
643
+
644
+ Parameters
645
+ ----------
646
+ G : NetworkX graph or list of nodes
647
+ A position will be assigned to every node in G.
648
+
649
+ dist : dict (default=None)
650
+ A two-level dictionary of optimal distances between nodes,
651
+ indexed by source and destination node.
652
+ If None, the distance is computed using shortest_path_length().
653
+
654
+ pos : dict or None optional (default=None)
655
+ Initial positions for nodes as a dictionary with node as keys
656
+ and values as a coordinate list or tuple. If None, then use
657
+ circular_layout() for dim >= 2 and a linear layout for dim == 1.
658
+
659
+ weight : string or None optional (default='weight')
660
+ The edge attribute that holds the numerical value used for
661
+ the edge weight. If None, then all edge weights are 1.
662
+
663
+ scale : number (default: 1)
664
+ Scale factor for positions.
665
+
666
+ center : array-like or None
667
+ Coordinate pair around which to center the layout.
668
+
669
+ dim : int
670
+ Dimension of layout.
671
+
672
+ Returns
673
+ -------
674
+ pos : dict
675
+ A dictionary of positions keyed by node
676
+
677
+ Examples
678
+ --------
679
+ >>> G = nx.path_graph(4)
680
+ >>> pos = nx.kamada_kawai_layout(G)
681
+ """
682
+ import numpy as np
683
+
684
+ G, center = _process_params(G, center, dim)
685
+ nNodes = len(G)
686
+ if nNodes == 0:
687
+ return {}
688
+
689
+ if dist is None:
690
+ dist = dict(nx.shortest_path_length(G, weight=weight))
691
+ dist_mtx = 1e6 * np.ones((nNodes, nNodes))
692
+ for row, nr in enumerate(G):
693
+ if nr not in dist:
694
+ continue
695
+ rdist = dist[nr]
696
+ for col, nc in enumerate(G):
697
+ if nc not in rdist:
698
+ continue
699
+ dist_mtx[row][col] = rdist[nc]
700
+
701
+ if pos is None:
702
+ if dim >= 3:
703
+ pos = random_layout(G, dim=dim)
704
+ elif dim == 2:
705
+ pos = circular_layout(G, dim=dim)
706
+ else:
707
+ pos = dict(zip(G, np.linspace(0, 1, len(G))))
708
+ pos_arr = np.array([pos[n] for n in G])
709
+
710
+ pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
711
+
712
+ pos = rescale_layout(pos, scale=scale) + center
713
+ return dict(zip(G, pos))
714
+
715
+
716
+ def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
717
+ # Anneal node locations based on the Kamada-Kawai cost-function,
718
+ # using the supplied matrix of preferred inter-node distances,
719
+ # and starting locations.
720
+
721
+ import numpy as np
722
+ import scipy as sp
723
+
724
+ meanwt = 1e-3
725
+ costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
726
+
727
+ optresult = sp.optimize.minimize(
728
+ _kamada_kawai_costfn,
729
+ pos_arr.ravel(),
730
+ method="L-BFGS-B",
731
+ args=costargs,
732
+ jac=True,
733
+ )
734
+
735
+ return optresult.x.reshape((-1, dim))
736
+
737
+
738
+ def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
739
+ # Cost-function and gradient for Kamada-Kawai layout algorithm
740
+ nNodes = invdist.shape[0]
741
+ pos_arr = pos_vec.reshape((nNodes, dim))
742
+
743
+ delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
744
+ nodesep = np.linalg.norm(delta, axis=-1)
745
+ direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
746
+
747
+ offset = nodesep * invdist - 1.0
748
+ offset[np.diag_indices(nNodes)] = 0
749
+
750
+ cost = 0.5 * np.sum(offset**2)
751
+ grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
752
+ "ij,ij,ijk->jk", invdist, offset, direction
753
+ )
754
+
755
+ # Additional parabolic term to encourage mean position to be near origin:
756
+ sumpos = np.sum(pos_arr, axis=0)
757
+ cost += 0.5 * meanweight * np.sum(sumpos**2)
758
+ grad += meanweight * sumpos
759
+
760
+ return (cost, grad.ravel())
761
+
762
+
763
+ def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
764
+ """Position nodes using the eigenvectors of the graph Laplacian.
765
+
766
+ Using the unnormalized Laplacian, the layout shows possible clusters of
767
+ nodes which are an approximation of the ratio cut. If dim is the number of
768
+ dimensions then the positions are the entries of the dim eigenvectors
769
+ corresponding to the ascending eigenvalues starting from the second one.
770
+
771
+ Parameters
772
+ ----------
773
+ G : NetworkX graph or list of nodes
774
+ A position will be assigned to every node in G.
775
+
776
+ weight : string or None optional (default='weight')
777
+ The edge attribute that holds the numerical value used for
778
+ the edge weight. If None, then all edge weights are 1.
779
+
780
+ scale : number (default: 1)
781
+ Scale factor for positions.
782
+
783
+ center : array-like or None
784
+ Coordinate pair around which to center the layout.
785
+
786
+ dim : int
787
+ Dimension of layout.
788
+
789
+ Returns
790
+ -------
791
+ pos : dict
792
+ A dictionary of positions keyed by node
793
+
794
+ Examples
795
+ --------
796
+ >>> G = nx.path_graph(4)
797
+ >>> pos = nx.spectral_layout(G)
798
+
799
+ Notes
800
+ -----
801
+ Directed graphs will be considered as undirected graphs when
802
+ positioning the nodes.
803
+
804
+ For larger graphs (>500 nodes) this will use the SciPy sparse
805
+ eigenvalue solver (ARPACK).
806
+ """
807
+ # handle some special cases that break the eigensolvers
808
+ import numpy as np
809
+
810
+ G, center = _process_params(G, center, dim)
811
+
812
+ if len(G) <= 2:
813
+ if len(G) == 0:
814
+ pos = np.array([])
815
+ elif len(G) == 1:
816
+ pos = np.array([center])
817
+ else:
818
+ pos = np.array([np.zeros(dim), np.array(center) * 2.0])
819
+ return dict(zip(G, pos))
820
+ try:
821
+ # Sparse matrix
822
+ if len(G) < 500: # dense solver is faster for small graphs
823
+ raise ValueError
824
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
825
+ # Symmetrize directed graphs
826
+ if G.is_directed():
827
+ A = A + np.transpose(A)
828
+ pos = _sparse_spectral(A, dim)
829
+ except (ImportError, ValueError):
830
+ # Dense matrix
831
+ A = nx.to_numpy_array(G, weight=weight)
832
+ # Symmetrize directed graphs
833
+ if G.is_directed():
834
+ A += A.T
835
+ pos = _spectral(A, dim)
836
+
837
+ pos = rescale_layout(pos, scale=scale) + center
838
+ pos = dict(zip(G, pos))
839
+ return pos
840
+
841
+
842
+ def _spectral(A, dim=2):
843
+ # Input adjacency matrix A
844
+ # Uses dense eigenvalue solver from numpy
845
+ import numpy as np
846
+
847
+ try:
848
+ nnodes, _ = A.shape
849
+ except AttributeError as err:
850
+ msg = "spectral() takes an adjacency matrix as input"
851
+ raise nx.NetworkXError(msg) from err
852
+
853
+ # form Laplacian matrix where D is diagonal of degrees
854
+ D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
855
+ L = D - A
856
+
857
+ eigenvalues, eigenvectors = np.linalg.eig(L)
858
+ # sort and keep smallest nonzero
859
+ index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
860
+ return np.real(eigenvectors[:, index])
861
+
862
+
863
+ def _sparse_spectral(A, dim=2):
864
+ # Input adjacency matrix A
865
+ # Uses sparse eigenvalue solver from scipy
866
+ # Could use multilevel methods here, see Koren "On spectral graph drawing"
867
+ import numpy as np
868
+ import scipy as sp
869
+
870
+ try:
871
+ nnodes, _ = A.shape
872
+ except AttributeError as err:
873
+ msg = "sparse_spectral() takes an adjacency matrix as input"
874
+ raise nx.NetworkXError(msg) from err
875
+
876
+ # form Laplacian matrix
877
+ # TODO: Rm csr_array wrapper in favor of spdiags array constructor when available
878
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, nnodes, nnodes))
879
+ L = D - A
880
+
881
+ k = dim + 1
882
+ # number of Lanczos vectors for ARPACK solver.What is the right scaling?
883
+ ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
884
+ # return smallest k eigenvalues and eigenvectors
885
+ eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
886
+ index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
887
+ return np.real(eigenvectors[:, index])
888
+
889
+
890
+ def planar_layout(G, scale=1, center=None, dim=2):
891
+ """Position nodes without edge intersections.
892
+
893
+ Parameters
894
+ ----------
895
+ G : NetworkX graph or list of nodes
896
+ A position will be assigned to every node in G. If G is of type
897
+ nx.PlanarEmbedding, the positions are selected accordingly.
898
+
899
+ scale : number (default: 1)
900
+ Scale factor for positions.
901
+
902
+ center : array-like or None
903
+ Coordinate pair around which to center the layout.
904
+
905
+ dim : int
906
+ Dimension of layout.
907
+
908
+ Returns
909
+ -------
910
+ pos : dict
911
+ A dictionary of positions keyed by node
912
+
913
+ Raises
914
+ ------
915
+ NetworkXException
916
+ If G is not planar
917
+
918
+ Examples
919
+ --------
920
+ >>> G = nx.path_graph(4)
921
+ >>> pos = nx.planar_layout(G)
922
+ """
923
+ import numpy as np
924
+
925
+ if dim != 2:
926
+ raise ValueError("can only handle 2 dimensions")
927
+
928
+ G, center = _process_params(G, center, dim)
929
+
930
+ if len(G) == 0:
931
+ return {}
932
+
933
+ if isinstance(G, nx.PlanarEmbedding):
934
+ embedding = G
935
+ else:
936
+ is_planar, embedding = nx.check_planarity(G)
937
+ if not is_planar:
938
+ raise nx.NetworkXException("G is not planar.")
939
+ pos = nx.combinatorial_embedding_to_pos(embedding)
940
+ node_list = list(embedding)
941
+ pos = np.vstack([pos[x] for x in node_list])
942
+ pos = pos.astype(np.float64)
943
+ pos = rescale_layout(pos, scale=scale) + center
944
+ return dict(zip(node_list, pos))
945
+
946
+
947
+ def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False):
948
+ """Position nodes in a spiral layout.
949
+
950
+ Parameters
951
+ ----------
952
+ G : NetworkX graph or list of nodes
953
+ A position will be assigned to every node in G.
954
+ scale : number (default: 1)
955
+ Scale factor for positions.
956
+ center : array-like or None
957
+ Coordinate pair around which to center the layout.
958
+ dim : int, default=2
959
+ Dimension of layout, currently only dim=2 is supported.
960
+ Other dimension values result in a ValueError.
961
+ resolution : float, default=0.35
962
+ The compactness of the spiral layout returned.
963
+ Lower values result in more compressed spiral layouts.
964
+ equidistant : bool, default=False
965
+ If True, nodes will be positioned equidistant from each other
966
+ by decreasing angle further from center.
967
+ If False, nodes will be positioned at equal angles
968
+ from each other by increasing separation further from center.
969
+
970
+ Returns
971
+ -------
972
+ pos : dict
973
+ A dictionary of positions keyed by node
974
+
975
+ Raises
976
+ ------
977
+ ValueError
978
+ If dim != 2
979
+
980
+ Examples
981
+ --------
982
+ >>> G = nx.path_graph(4)
983
+ >>> pos = nx.spiral_layout(G)
984
+ >>> nx.draw(G, pos=pos)
985
+
986
+ Notes
987
+ -----
988
+ This algorithm currently only works in two dimensions.
989
+
990
+ """
991
+ import numpy as np
992
+
993
+ if dim != 2:
994
+ raise ValueError("can only handle 2 dimensions")
995
+
996
+ G, center = _process_params(G, center, dim)
997
+
998
+ if len(G) == 0:
999
+ return {}
1000
+ if len(G) == 1:
1001
+ return {nx.utils.arbitrary_element(G): center}
1002
+
1003
+ pos = []
1004
+ if equidistant:
1005
+ chord = 1
1006
+ step = 0.5
1007
+ theta = resolution
1008
+ theta += chord / (step * theta)
1009
+ for _ in range(len(G)):
1010
+ r = step * theta
1011
+ theta += chord / r
1012
+ pos.append([np.cos(theta) * r, np.sin(theta) * r])
1013
+
1014
+ else:
1015
+ dist = np.arange(len(G), dtype=float)
1016
+ angle = resolution * dist
1017
+ pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
1018
+
1019
+ pos = rescale_layout(np.array(pos), scale=scale) + center
1020
+
1021
+ pos = dict(zip(G, pos))
1022
+
1023
+ return pos
1024
+
1025
+
1026
+ def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
1027
+ """Position nodes in layers of straight lines.
1028
+
1029
+ Parameters
1030
+ ----------
1031
+ G : NetworkX graph or list of nodes
1032
+ A position will be assigned to every node in G.
1033
+
1034
+ subset_key : string or dict (default='subset')
1035
+ If a string, the key of node data in G that holds the node subset.
1036
+ If a dict, keyed by layer number to the nodes in that layer/subset.
1037
+
1038
+ align : string (default='vertical')
1039
+ The alignment of nodes. Vertical or horizontal.
1040
+
1041
+ scale : number (default: 1)
1042
+ Scale factor for positions.
1043
+
1044
+ center : array-like or None
1045
+ Coordinate pair around which to center the layout.
1046
+
1047
+ Returns
1048
+ -------
1049
+ pos : dict
1050
+ A dictionary of positions keyed by node.
1051
+
1052
+ Examples
1053
+ --------
1054
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1055
+ >>> pos = nx.multipartite_layout(G)
1056
+
1057
+ or use a dict to provide the layers of the layout
1058
+
1059
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
1060
+ >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
1061
+ >>> pos = nx.multipartite_layout(G, subset_key=layers)
1062
+
1063
+ Notes
1064
+ -----
1065
+ This algorithm currently only works in two dimensions and does not
1066
+ try to minimize edge crossings.
1067
+
1068
+ Network does not need to be a complete multipartite graph. As long as nodes
1069
+ have subset_key data, they will be placed in the corresponding layers.
1070
+
1071
+ """
1072
+ import numpy as np
1073
+
1074
+ if align not in ("vertical", "horizontal"):
1075
+ msg = "align must be either vertical or horizontal."
1076
+ raise ValueError(msg)
1077
+
1078
+ G, center = _process_params(G, center=center, dim=2)
1079
+ if len(G) == 0:
1080
+ return {}
1081
+
1082
+ try:
1083
+ # check if subset_key is dict-like
1084
+ if len(G) != sum(len(nodes) for nodes in subset_key.values()):
1085
+ raise nx.NetworkXError(
1086
+ "all nodes must be in one subset of `subset_key` dict"
1087
+ )
1088
+ except AttributeError:
1089
+ # subset_key is not a dict, hence a string
1090
+ node_to_subset = nx.get_node_attributes(G, subset_key)
1091
+ if len(node_to_subset) != len(G):
1092
+ raise nx.NetworkXError(
1093
+ f"all nodes need a subset_key attribute: {subset_key}"
1094
+ )
1095
+ subset_key = nx.utils.groups(node_to_subset)
1096
+
1097
+ # Sort by layer, if possible
1098
+ try:
1099
+ layers = dict(sorted(subset_key.items()))
1100
+ except TypeError:
1101
+ layers = subset_key
1102
+
1103
+ pos = None
1104
+ nodes = []
1105
+ width = len(layers)
1106
+ for i, layer in enumerate(layers.values()):
1107
+ height = len(layer)
1108
+ xs = np.repeat(i, height)
1109
+ ys = np.arange(0, height, dtype=float)
1110
+ offset = ((width - 1) / 2, (height - 1) / 2)
1111
+ layer_pos = np.column_stack([xs, ys]) - offset
1112
+ if pos is None:
1113
+ pos = layer_pos
1114
+ else:
1115
+ pos = np.concatenate([pos, layer_pos])
1116
+ nodes.extend(layer)
1117
+ pos = rescale_layout(pos, scale=scale) + center
1118
+ if align == "horizontal":
1119
+ pos = pos[:, ::-1] # swap x and y coords
1120
+ pos = dict(zip(nodes, pos))
1121
+ return pos
1122
+
1123
+
1124
+ def arf_layout(
1125
+ G,
1126
+ pos=None,
1127
+ scaling=1,
1128
+ a=1.1,
1129
+ etol=1e-6,
1130
+ dt=1e-3,
1131
+ max_iter=1000,
1132
+ ):
1133
+ """Arf layout for networkx
1134
+
1135
+ The attractive and repulsive forces (arf) layout [1]
1136
+ improves the spring layout in three ways. First, it
1137
+ prevents congestion of highly connected nodes due to
1138
+ strong forcing between nodes. Second, it utilizes the
1139
+ layout space more effectively by preventing large gaps
1140
+ that spring layout tends to create. Lastly, the arf
1141
+ layout represents symmetries in the layout better than
1142
+ the default spring layout.
1143
+
1144
+ Parameters
1145
+ ----------
1146
+ G : nx.Graph or nx.DiGraph
1147
+ Networkx graph.
1148
+ pos : dict
1149
+ Initial position of the nodes. If set to None a
1150
+ random layout will be used.
1151
+ scaling : float
1152
+ Scales the radius of the circular layout space.
1153
+ a : float
1154
+ Strength of springs between connected nodes. Should be larger than 1. The greater a, the clearer the separation ofunconnected sub clusters.
1155
+ etol : float
1156
+ Gradient sum of spring forces must be larger than `etol` before successful termination.
1157
+ dt : float
1158
+ Time step for force differential equation simulations.
1159
+ max_iter : int
1160
+ Max iterations before termination of the algorithm.
1161
+
1162
+ References
1163
+ .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
1164
+ International Journal of Modern Physics C, 2007, Vol 18, No 10, pp. 1537-1549.
1165
+ https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
1166
+
1167
+ Returns
1168
+ -------
1169
+ pos : dict
1170
+ A dictionary of positions keyed by node.
1171
+
1172
+ Examples
1173
+ --------
1174
+ >>> G = nx.grid_graph((5, 5))
1175
+ >>> pos = nx.arf_layout(G)
1176
+
1177
+ """
1178
+ import warnings
1179
+
1180
+ import numpy as np
1181
+
1182
+ if a <= 1:
1183
+ msg = "The parameter a should be larger than 1"
1184
+ raise ValueError(msg)
1185
+
1186
+ pos_tmp = nx.random_layout(G)
1187
+ if pos is None:
1188
+ pos = pos_tmp
1189
+ else:
1190
+ for node in G.nodes():
1191
+ if node not in pos:
1192
+ pos[node] = pos_tmp[node].copy()
1193
+
1194
+ # Initialize spring constant matrix
1195
+ N = len(G)
1196
+ # No nodes no computation
1197
+ if N == 0:
1198
+ return pos
1199
+
1200
+ # init force of springs
1201
+ K = np.ones((N, N)) - np.eye(N)
1202
+ node_order = {node: i for i, node in enumerate(G)}
1203
+ for x, y in G.edges():
1204
+ if x != y:
1205
+ idx, jdx = (node_order[i] for i in (x, y))
1206
+ K[idx, jdx] = a
1207
+
1208
+ # vectorize values
1209
+ p = np.asarray(list(pos.values()))
1210
+
1211
+ # equation 10 in [1]
1212
+ rho = scaling * np.sqrt(N)
1213
+
1214
+ # looping variables
1215
+ error = etol + 1
1216
+ n_iter = 0
1217
+ while error > etol:
1218
+ diff = p[:, np.newaxis] - p[np.newaxis]
1219
+ A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
1220
+ # attraction_force - repulsions force
1221
+ # suppress nans due to division; caused by diagonal set to zero.
1222
+ # Does not affect the computation due to nansum
1223
+ with warnings.catch_warnings():
1224
+ warnings.simplefilter("ignore")
1225
+ change = K[..., np.newaxis] * diff - rho / A * diff
1226
+ change = np.nansum(change, axis=0)
1227
+ p += change * dt
1228
+
1229
+ error = np.linalg.norm(change, axis=-1).sum()
1230
+ if n_iter > max_iter:
1231
+ break
1232
+ n_iter += 1
1233
+ return dict(zip(G.nodes(), p))
1234
+
1235
+
1236
+ def rescale_layout(pos, scale=1):
1237
+ """Returns scaled position array to (-scale, scale) in all axes.
1238
+
1239
+ The function acts on NumPy arrays which hold position information.
1240
+ Each position is one row of the array. The dimension of the space
1241
+ equals the number of columns. Each coordinate in one column.
1242
+
1243
+ To rescale, the mean (center) is subtracted from each axis separately.
1244
+ Then all values are scaled so that the largest magnitude value
1245
+ from all axes equals `scale` (thus, the aspect ratio is preserved).
1246
+ The resulting NumPy Array is returned (order of rows unchanged).
1247
+
1248
+ Parameters
1249
+ ----------
1250
+ pos : numpy array
1251
+ positions to be scaled. Each row is a position.
1252
+
1253
+ scale : number (default: 1)
1254
+ The size of the resulting extent in all directions.
1255
+
1256
+ Returns
1257
+ -------
1258
+ pos : numpy array
1259
+ scaled positions. Each row is a position.
1260
+
1261
+ See Also
1262
+ --------
1263
+ rescale_layout_dict
1264
+ """
1265
+ import numpy as np
1266
+
1267
+ # Find max length over all dimensions
1268
+ pos -= pos.mean(axis=0)
1269
+ lim = np.abs(pos).max() # max coordinate for all axes
1270
+ # rescale to (-scale, scale) in all directions, preserves aspect
1271
+ if lim > 0:
1272
+ pos *= scale / lim
1273
+ return pos
1274
+
1275
+
1276
+ def rescale_layout_dict(pos, scale=1):
1277
+ """Return a dictionary of scaled positions keyed by node
1278
+
1279
+ Parameters
1280
+ ----------
1281
+ pos : A dictionary of positions keyed by node
1282
+
1283
+ scale : number (default: 1)
1284
+ The size of the resulting extent in all directions.
1285
+
1286
+ Returns
1287
+ -------
1288
+ pos : A dictionary of positions keyed by node
1289
+
1290
+ Examples
1291
+ --------
1292
+ >>> import numpy as np
1293
+ >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
1294
+ >>> nx.rescale_layout_dict(pos)
1295
+ {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
1296
+
1297
+ >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
1298
+ >>> nx.rescale_layout_dict(pos, scale=2)
1299
+ {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
1300
+
1301
+ See Also
1302
+ --------
1303
+ rescale_layout
1304
+ """
1305
+ import numpy as np
1306
+
1307
+ if not pos: # empty_graph
1308
+ return {}
1309
+ pos_v = np.array(list(pos.values()))
1310
+ pos_v = rescale_layout(pos_v, scale=scale)
1311
+ return dict(zip(pos, pos_v))
1312
+
1313
+
1314
+ def bfs_layout(G, start, *, align="vertical", scale=1, center=None):
1315
+ """Position nodes according to breadth-first search algorithm.
1316
+
1317
+ Parameters
1318
+ ----------
1319
+ G : NetworkX graph
1320
+ A position will be assigned to every node in G.
1321
+
1322
+ start : node in `G`
1323
+ Starting node for bfs
1324
+
1325
+ center : array-like or None
1326
+ Coordinate pair around which to center the layout.
1327
+
1328
+ Returns
1329
+ -------
1330
+ pos : dict
1331
+ A dictionary of positions keyed by node.
1332
+
1333
+ Examples
1334
+ --------
1335
+ >>> G = nx.path_graph(4)
1336
+ >>> pos = nx.bfs_layout(G, 0)
1337
+
1338
+ Notes
1339
+ -----
1340
+ This algorithm currently only works in two dimensions and does not
1341
+ try to minimize edge crossings.
1342
+
1343
+ """
1344
+ G, center = _process_params(G, center, 2)
1345
+
1346
+ # Compute layers with BFS
1347
+ layers = dict(enumerate(nx.bfs_layers(G, start)))
1348
+
1349
+ if len(G) != sum(len(nodes) for nodes in layers.values()):
1350
+ raise nx.NetworkXError(
1351
+ "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
1352
+ " G.subgraph(nx.node_connected_component(G, start))"
1353
+ )
1354
+
1355
+ # Compute node positions with multipartite_layout
1356
+ return multipartite_layout(
1357
+ G, subset_key=layers, align=align, scale=scale, center=center
1358
+ )
llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ***************
3
+ Graphviz AGraph
4
+ ***************
5
+
6
+ Interface to pygraphviz AGraph class.
7
+
8
+ Examples
9
+ --------
10
+ >>> G = nx.complete_graph(5)
11
+ >>> A = nx.nx_agraph.to_agraph(G)
12
+ >>> H = nx.nx_agraph.from_agraph(A)
13
+
14
+ See Also
15
+ --------
16
+ - Pygraphviz: http://pygraphviz.github.io/
17
+ - Graphviz: https://www.graphviz.org
18
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
19
+ """
20
+ import os
21
+ import tempfile
22
+
23
+ import networkx as nx
24
+
25
+ __all__ = [
26
+ "from_agraph",
27
+ "to_agraph",
28
+ "write_dot",
29
+ "read_dot",
30
+ "graphviz_layout",
31
+ "pygraphviz_layout",
32
+ "view_pygraphviz",
33
+ ]
34
+
35
+
36
+ @nx._dispatchable(graphs=None, returns_graph=True)
37
+ def from_agraph(A, create_using=None):
38
+ """Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
39
+
40
+ Parameters
41
+ ----------
42
+ A : PyGraphviz AGraph
43
+ A graph created with PyGraphviz
44
+
45
+ create_using : NetworkX graph constructor, optional (default=None)
46
+ Graph type to create. If graph instance, then cleared before populated.
47
+ If `None`, then the appropriate Graph type is inferred from `A`.
48
+
49
+ Examples
50
+ --------
51
+ >>> K5 = nx.complete_graph(5)
52
+ >>> A = nx.nx_agraph.to_agraph(K5)
53
+ >>> G = nx.nx_agraph.from_agraph(A)
54
+
55
+ Notes
56
+ -----
57
+ The Graph G will have a dictionary G.graph_attr containing
58
+ the default graphviz attributes for graphs, nodes and edges.
59
+
60
+ Default node attributes will be in the dictionary G.node_attr
61
+ which is keyed by node.
62
+
63
+ Edge attributes will be returned as edge data in G. With
64
+ edge_attr=False the edge data will be the Graphviz edge weight
65
+ attribute or the value 1 if no edge weight attribute is found.
66
+
67
+ """
68
+ if create_using is None:
69
+ if A.is_directed():
70
+ if A.is_strict():
71
+ create_using = nx.DiGraph
72
+ else:
73
+ create_using = nx.MultiDiGraph
74
+ else:
75
+ if A.is_strict():
76
+ create_using = nx.Graph
77
+ else:
78
+ create_using = nx.MultiGraph
79
+
80
+ # assign defaults
81
+ N = nx.empty_graph(0, create_using)
82
+ if A.name is not None:
83
+ N.name = A.name
84
+
85
+ # add graph attributes
86
+ N.graph.update(A.graph_attr)
87
+
88
+ # add nodes, attributes to N.node_attr
89
+ for n in A.nodes():
90
+ str_attr = {str(k): v for k, v in n.attr.items()}
91
+ N.add_node(str(n), **str_attr)
92
+
93
+ # add edges, assign edge data as dictionary of attributes
94
+ for e in A.edges():
95
+ u, v = str(e[0]), str(e[1])
96
+ attr = dict(e.attr)
97
+ str_attr = {str(k): v for k, v in attr.items()}
98
+ if not N.is_multigraph():
99
+ if e.name is not None:
100
+ str_attr["key"] = e.name
101
+ N.add_edge(u, v, **str_attr)
102
+ else:
103
+ N.add_edge(u, v, key=e.name, **str_attr)
104
+
105
+ # add default attributes for graph, nodes, and edges
106
+ # hang them on N.graph_attr
107
+ N.graph["graph"] = dict(A.graph_attr)
108
+ N.graph["node"] = dict(A.node_attr)
109
+ N.graph["edge"] = dict(A.edge_attr)
110
+ return N
111
+
112
+
113
+ def to_agraph(N):
114
+ """Returns a pygraphviz graph from a NetworkX graph N.
115
+
116
+ Parameters
117
+ ----------
118
+ N : NetworkX graph
119
+ A graph created with NetworkX
120
+
121
+ Examples
122
+ --------
123
+ >>> K5 = nx.complete_graph(5)
124
+ >>> A = nx.nx_agraph.to_agraph(K5)
125
+
126
+ Notes
127
+ -----
128
+ If N has an dict N.graph_attr an attempt will be made first
129
+ to copy properties attached to the graph (see from_agraph)
130
+ and then updated with the calling arguments if any.
131
+
132
+ """
133
+ try:
134
+ import pygraphviz
135
+ except ImportError as err:
136
+ raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
137
+ directed = N.is_directed()
138
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
139
+
140
+ for node in N:
141
+ if "pos" in N.nodes[node]:
142
+ N.nodes[node]["pos"] = "{},{}!".format(
143
+ N.nodes[node]["pos"][0], N.nodes[node]["pos"][1]
144
+ )
145
+
146
+ A = pygraphviz.AGraph(name=N.name, strict=strict, directed=directed)
147
+
148
+ # default graph attributes
149
+ A.graph_attr.update(N.graph.get("graph", {}))
150
+ A.node_attr.update(N.graph.get("node", {}))
151
+ A.edge_attr.update(N.graph.get("edge", {}))
152
+
153
+ A.graph_attr.update(
154
+ (k, v) for k, v in N.graph.items() if k not in ("graph", "node", "edge")
155
+ )
156
+
157
+ # add nodes
158
+ for n, nodedata in N.nodes(data=True):
159
+ A.add_node(n)
160
+ # Add node data
161
+ a = A.get_node(n)
162
+ a.attr.update({k: str(v) for k, v in nodedata.items()})
163
+
164
+ # loop over edges
165
+ if N.is_multigraph():
166
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
167
+ str_edgedata = {k: str(v) for k, v in edgedata.items() if k != "key"}
168
+ A.add_edge(u, v, key=str(key))
169
+ # Add edge data
170
+ a = A.get_edge(u, v)
171
+ a.attr.update(str_edgedata)
172
+
173
+ else:
174
+ for u, v, edgedata in N.edges(data=True):
175
+ str_edgedata = {k: str(v) for k, v in edgedata.items()}
176
+ A.add_edge(u, v)
177
+ # Add edge data
178
+ a = A.get_edge(u, v)
179
+ a.attr.update(str_edgedata)
180
+
181
+ return A
182
+
183
+
184
+ def write_dot(G, path):
185
+ """Write NetworkX graph G to Graphviz dot format on path.
186
+
187
+ Parameters
188
+ ----------
189
+ G : graph
190
+ A networkx graph
191
+ path : filename
192
+ Filename or file handle to write
193
+
194
+ Notes
195
+ -----
196
+ To use a specific graph layout, call ``A.layout`` prior to `write_dot`.
197
+ Note that some graphviz layouts are not guaranteed to be deterministic,
198
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
199
+ """
200
+ A = to_agraph(G)
201
+ A.write(path)
202
+ A.clear()
203
+ return
204
+
205
+
206
+ @nx._dispatchable(name="agraph_read_dot", graphs=None, returns_graph=True)
207
+ def read_dot(path):
208
+ """Returns a NetworkX graph from a dot file on path.
209
+
210
+ Parameters
211
+ ----------
212
+ path : file or string
213
+ File name or file handle to read.
214
+ """
215
+ try:
216
+ import pygraphviz
217
+ except ImportError as err:
218
+ raise ImportError(
219
+ "read_dot() requires pygraphviz http://pygraphviz.github.io/"
220
+ ) from err
221
+ A = pygraphviz.AGraph(file=path)
222
+ gr = from_agraph(A)
223
+ A.clear()
224
+ return gr
225
+
226
+
227
+ def graphviz_layout(G, prog="neato", root=None, args=""):
228
+ """Create node positions for G using Graphviz.
229
+
230
+ Parameters
231
+ ----------
232
+ G : NetworkX graph
233
+ A graph created with NetworkX
234
+ prog : string
235
+ Name of Graphviz layout program
236
+ root : string, optional
237
+ Root node for twopi layout
238
+ args : string, optional
239
+ Extra arguments to Graphviz layout program
240
+
241
+ Returns
242
+ -------
243
+ Dictionary of x, y, positions keyed by node.
244
+
245
+ Examples
246
+ --------
247
+ >>> G = nx.petersen_graph()
248
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
249
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
250
+
251
+ Notes
252
+ -----
253
+ This is a wrapper for pygraphviz_layout.
254
+
255
+ Note that some graphviz layouts are not guaranteed to be deterministic,
256
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
257
+ """
258
+ return pygraphviz_layout(G, prog=prog, root=root, args=args)
259
+
260
+
261
+ def pygraphviz_layout(G, prog="neato", root=None, args=""):
262
+ """Create node positions for G using Graphviz.
263
+
264
+ Parameters
265
+ ----------
266
+ G : NetworkX graph
267
+ A graph created with NetworkX
268
+ prog : string
269
+ Name of Graphviz layout program
270
+ root : string, optional
271
+ Root node for twopi layout
272
+ args : string, optional
273
+ Extra arguments to Graphviz layout program
274
+
275
+ Returns
276
+ -------
277
+ node_pos : dict
278
+ Dictionary of x, y, positions keyed by node.
279
+
280
+ Examples
281
+ --------
282
+ >>> G = nx.petersen_graph()
283
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
284
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
285
+
286
+ Notes
287
+ -----
288
+ If you use complex node objects, they may have the same string
289
+ representation and GraphViz could treat them as the same node.
290
+ The layout may assign both nodes a single location. See Issue #1568
291
+ If this occurs in your case, consider relabeling the nodes just
292
+ for the layout computation using something similar to::
293
+
294
+ >>> H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
295
+ >>> H_layout = nx.nx_agraph.pygraphviz_layout(G, prog="dot")
296
+ >>> G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
297
+
298
+ Note that some graphviz layouts are not guaranteed to be deterministic,
299
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
300
+ """
301
+ try:
302
+ import pygraphviz
303
+ except ImportError as err:
304
+ raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
305
+ if root is not None:
306
+ args += f"-Groot={root}"
307
+ A = to_agraph(G)
308
+ A.layout(prog=prog, args=args)
309
+ node_pos = {}
310
+ for n in G:
311
+ node = pygraphviz.Node(A, n)
312
+ try:
313
+ xs = node.attr["pos"].split(",")
314
+ node_pos[n] = tuple(float(x) for x in xs)
315
+ except:
316
+ print("no position for node", n)
317
+ node_pos[n] = (0.0, 0.0)
318
+ return node_pos
319
+
320
+
321
+ @nx.utils.open_file(5, "w+b")
322
+ def view_pygraphviz(
323
+ G, edgelabel=None, prog="dot", args="", suffix="", path=None, show=True
324
+ ):
325
+ """Views the graph G using the specified layout algorithm.
326
+
327
+ Parameters
328
+ ----------
329
+ G : NetworkX graph
330
+ The machine to draw.
331
+ edgelabel : str, callable, None
332
+ If a string, then it specifies the edge attribute to be displayed
333
+ on the edge labels. If a callable, then it is called for each
334
+ edge and it should return the string to be displayed on the edges.
335
+ The function signature of `edgelabel` should be edgelabel(data),
336
+ where `data` is the edge attribute dictionary.
337
+ prog : string
338
+ Name of Graphviz layout program.
339
+ args : str
340
+ Additional arguments to pass to the Graphviz layout program.
341
+ suffix : str
342
+ If `filename` is None, we save to a temporary file. The value of
343
+ `suffix` will appear at the tail end of the temporary filename.
344
+ path : str, None
345
+ The filename used to save the image. If None, save to a temporary
346
+ file. File formats are the same as those from pygraphviz.agraph.draw.
347
+ show : bool, default = True
348
+ Whether to display the graph with :mod:`PIL.Image.show`,
349
+ default is `True`. If `False`, the rendered graph is still available
350
+ at `path`.
351
+
352
+ Returns
353
+ -------
354
+ path : str
355
+ The filename of the generated image.
356
+ A : PyGraphviz graph
357
+ The PyGraphviz graph instance used to generate the image.
358
+
359
+ Notes
360
+ -----
361
+ If this function is called in succession too quickly, sometimes the
362
+ image is not displayed. So you might consider time.sleep(.5) between
363
+ calls if you experience problems.
364
+
365
+ Note that some graphviz layouts are not guaranteed to be deterministic,
366
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
367
+
368
+ """
369
+ if not len(G):
370
+ raise nx.NetworkXException("An empty graph cannot be drawn.")
371
+
372
+ # If we are providing default values for graphviz, these must be set
373
+ # before any nodes or edges are added to the PyGraphviz graph object.
374
+ # The reason for this is that default values only affect incoming objects.
375
+ # If you change the default values after the objects have been added,
376
+ # then they inherit no value and are set only if explicitly set.
377
+
378
+ # to_agraph() uses these values.
379
+ attrs = ["edge", "node", "graph"]
380
+ for attr in attrs:
381
+ if attr not in G.graph:
382
+ G.graph[attr] = {}
383
+
384
+ # These are the default values.
385
+ edge_attrs = {"fontsize": "10"}
386
+ node_attrs = {
387
+ "style": "filled",
388
+ "fillcolor": "#0000FF40",
389
+ "height": "0.75",
390
+ "width": "0.75",
391
+ "shape": "circle",
392
+ }
393
+ graph_attrs = {}
394
+
395
+ def update_attrs(which, attrs):
396
+ # Update graph attributes. Return list of those which were added.
397
+ added = []
398
+ for k, v in attrs.items():
399
+ if k not in G.graph[which]:
400
+ G.graph[which][k] = v
401
+ added.append(k)
402
+
403
+ def clean_attrs(which, added):
404
+ # Remove added attributes
405
+ for attr in added:
406
+ del G.graph[which][attr]
407
+ if not G.graph[which]:
408
+ del G.graph[which]
409
+
410
+ # Update all default values
411
+ update_attrs("edge", edge_attrs)
412
+ update_attrs("node", node_attrs)
413
+ update_attrs("graph", graph_attrs)
414
+
415
+ # Convert to agraph, so we inherit default values
416
+ A = to_agraph(G)
417
+
418
+ # Remove the default values we added to the original graph.
419
+ clean_attrs("edge", edge_attrs)
420
+ clean_attrs("node", node_attrs)
421
+ clean_attrs("graph", graph_attrs)
422
+
423
+ # If the user passed in an edgelabel, we update the labels for all edges.
424
+ if edgelabel is not None:
425
+ if not callable(edgelabel):
426
+
427
+ def func(data):
428
+ return "".join([" ", str(data[edgelabel]), " "])
429
+
430
+ else:
431
+ func = edgelabel
432
+
433
+ # update all the edge labels
434
+ if G.is_multigraph():
435
+ for u, v, key, data in G.edges(keys=True, data=True):
436
+ # PyGraphviz doesn't convert the key to a string. See #339
437
+ edge = A.get_edge(u, v, str(key))
438
+ edge.attr["label"] = str(func(data))
439
+ else:
440
+ for u, v, data in G.edges(data=True):
441
+ edge = A.get_edge(u, v)
442
+ edge.attr["label"] = str(func(data))
443
+
444
+ if path is None:
445
+ ext = "png"
446
+ if suffix:
447
+ suffix = f"_{suffix}.{ext}"
448
+ else:
449
+ suffix = f".{ext}"
450
+ path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
451
+ else:
452
+ # Assume the decorator worked and it is a file-object.
453
+ pass
454
+
455
+ # Write graph to file
456
+ A.draw(path=path, format=None, prog=prog, args=args)
457
+ path.close()
458
+
459
+ # Show graph in a new window (depends on platform configuration)
460
+ if show:
461
+ from PIL import Image
462
+
463
+ Image.open(path.name).show()
464
+
465
+ return path.name, A
llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_latex.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ *****
3
+ LaTeX
4
+ *****
5
+
6
+ Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
7
+ Usually, you will want the drawing to appear in a figure environment so
8
+ you use ``to_latex(G, caption="A caption")``. If you want the raw
9
+ drawing commands without a figure environment use :func:`to_latex_raw`.
10
+ And if you want to write to a file instead of just returning the latex
11
+ code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
12
+
13
+ To construct a figure with subfigures for each graph to be shown, provide
14
+ ``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
15
+ and a number of rows of subfigures inside the figure.
16
+
17
+ To be able to refer to the figures or subfigures in latex using ``\\ref``,
18
+ the keyword ``latex_label`` is available for figures and `sub_labels` for
19
+ a list of labels, one for each subfigure.
20
+
21
+ We intend to eventually provide an interface to the TikZ Graph
22
+ features which include e.g. layout algorithms.
23
+
24
+ Let us know via github what you'd like to see available, or better yet
25
+ give us some code to do it, or even better make a github pull request
26
+ to add the feature.
27
+
28
+ The TikZ approach
29
+ =================
30
+ Drawing options can be stored on the graph as node/edge attributes, or
31
+ can be provided as dicts keyed by node/edge to a string of the options
32
+ for that node/edge. Similarly a label can be shown for each node/edge
33
+ by specifying the labels as graph node/edge attributes or by providing
34
+ a dict keyed by node/edge to the text to be written for that node/edge.
35
+
36
+ Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
37
+ via a keyword argument. Similarly default node and edge options can be
38
+ provided through keywords arguments. The default node options are applied
39
+ to the single TikZ "path" that draws all nodes (and no edges). The default edge
40
+ options are applied to a TikZ "scope" which contains a path for each edge.
41
+
42
+ Examples
43
+ ========
44
+ >>> G = nx.path_graph(3)
45
+ >>> nx.write_latex(G, "just_my_figure.tex", as_document=True)
46
+ >>> nx.write_latex(G, "my_figure.tex", caption="A path graph", latex_label="fig1")
47
+ >>> latex_code = nx.to_latex(G) # a string rather than a file
48
+
49
+ You can change many features of the nodes and edges.
50
+
51
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph)
52
+ >>> pos = {n: (n, n) for n in G} # nodes set on a line
53
+
54
+ >>> G.nodes[0]["style"] = "blue"
55
+ >>> G.nodes[2]["style"] = "line width=3,draw"
56
+ >>> G.nodes[3]["label"] = "Stop"
57
+ >>> G.edges[(0, 1)]["label"] = "1st Step"
58
+ >>> G.edges[(0, 1)]["label_opts"] = "near start"
59
+ >>> G.edges[(1, 2)]["style"] = "line width=3"
60
+ >>> G.edges[(1, 2)]["label"] = "2nd Step"
61
+ >>> G.edges[(2, 3)]["style"] = "green"
62
+ >>> G.edges[(2, 3)]["label"] = "3rd Step"
63
+ >>> G.edges[(2, 3)]["label_opts"] = "near end"
64
+
65
+ >>> nx.write_latex(G, "latex_graph.tex", pos=pos, as_document=True)
66
+
67
+ Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
68
+ and view the pdf file created: ``latex_graph.pdf``.
69
+
70
+ If you want **subfigures** each containing one graph, you can input a list of graphs.
71
+
72
+ >>> H1 = nx.path_graph(4)
73
+ >>> H2 = nx.complete_graph(4)
74
+ >>> H3 = nx.path_graph(8)
75
+ >>> H4 = nx.complete_graph(8)
76
+ >>> graphs = [H1, H2, H3, H4]
77
+ >>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
78
+ >>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
79
+ >>> nx.write_latex(graphs, "subfigs.tex", n_rows=2, sub_captions=caps, sub_labels=lbls)
80
+ >>> latex_code = nx.to_latex(graphs, n_rows=2, sub_captions=caps, sub_labels=lbls)
81
+
82
+ >>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
83
+ >>> edge_width = {e: "line width=1.5" for e in H3.edges}
84
+ >>> pos = nx.circular_layout(H3)
85
+ >>> latex_code = nx.to_latex(H3, pos, node_options=node_color, edge_options=edge_width)
86
+ >>> print(latex_code)
87
+ \documentclass{report}
88
+ \usepackage{tikz}
89
+ \usepackage{subcaption}
90
+ <BLANKLINE>
91
+ \begin{document}
92
+ \begin{figure}
93
+ \begin{tikzpicture}
94
+ \draw
95
+ (1.0, 0.0) node[red] (0){0}
96
+ (0.707, 0.707) node[orange] (1){1}
97
+ (-0.0, 1.0) node[blue] (2){2}
98
+ (-0.707, 0.707) node[gray!90] (3){3}
99
+ (-1.0, -0.0) node (4){4}
100
+ (-0.707, -0.707) node (5){5}
101
+ (0.0, -1.0) node (6){6}
102
+ (0.707, -0.707) node (7){7};
103
+ \begin{scope}[-]
104
+ \draw[line width=1.5] (0) to (1);
105
+ \draw[line width=1.5] (1) to (2);
106
+ \draw[line width=1.5] (2) to (3);
107
+ \draw[line width=1.5] (3) to (4);
108
+ \draw[line width=1.5] (4) to (5);
109
+ \draw[line width=1.5] (5) to (6);
110
+ \draw[line width=1.5] (6) to (7);
111
+ \end{scope}
112
+ \end{tikzpicture}
113
+ \end{figure}
114
+ \end{document}
115
+
116
+ Notes
117
+ -----
118
+ If you want to change the preamble/postamble of the figure/document/subfigure
119
+ environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
120
+ `subfigure_wrapper`. The default values are stored in private variables
121
+ e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
122
+
123
+ References
124
+ ----------
125
+ TikZ: https://tikz.dev/
126
+
127
+ TikZ options details: https://tikz.dev/tikz-actions
128
+ """
129
+ import numbers
130
+ import os
131
+
132
+ import networkx as nx
133
+
134
+ __all__ = [
135
+ "to_latex_raw",
136
+ "to_latex",
137
+ "write_latex",
138
+ ]
139
+
140
+
141
+ @nx.utils.not_implemented_for("multigraph")
142
+ def to_latex_raw(
143
+ G,
144
+ pos="pos",
145
+ tikz_options="",
146
+ default_node_options="",
147
+ node_options="node_options",
148
+ node_label="label",
149
+ default_edge_options="",
150
+ edge_options="edge_options",
151
+ edge_label="label",
152
+ edge_label_options="edge_label_options",
153
+ ):
154
+ """Return a string of the LaTeX/TikZ code to draw `G`
155
+
156
+ This function produces just the code for the tikzpicture
157
+ without any enclosing environment.
158
+
159
+ Parameters
160
+ ==========
161
+ G : NetworkX graph
162
+ The NetworkX graph to be drawn
163
+ pos : string or dict (default "pos")
164
+ The name of the node attribute on `G` that holds the position of each node.
165
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
166
+ They can also be strings to denote positions in TikZ style, such as (x, y)
167
+ or (angle:radius).
168
+ If a dict, it should be keyed by node to a position.
169
+ If an empty dict, a circular layout is computed by TikZ.
170
+ tikz_options : string
171
+ The tikzpicture options description defining the options for the picture.
172
+ Often large scale options like `[scale=2]`.
173
+ default_node_options : string
174
+ The draw options for a path of nodes. Individual node options override these.
175
+ node_options : string or dict
176
+ The name of the node attribute on `G` that holds the options for each node.
177
+ Or a dict keyed by node to a string holding the options for that node.
178
+ node_label : string or dict
179
+ The name of the node attribute on `G` that holds the node label (text)
180
+ displayed for each node. If the attribute is "" or not present, the node
181
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
182
+ Or a dict keyed by node to a string holding the label for that node.
183
+ default_edge_options : string
184
+ The options for the scope drawing all edges. The default is "[-]" for
185
+ undirected graphs and "[->]" for directed graphs.
186
+ edge_options : string or dict
187
+ The name of the edge attribute on `G` that holds the options for each edge.
188
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
189
+ "loop," is added to the options for the self-loop edge. Hence you can
190
+ use "[loop above]" explicitly, but the default is "[loop]".
191
+ Or a dict keyed by edge to a string holding the options for that edge.
192
+ edge_label : string or dict
193
+ The name of the edge attribute on `G` that holds the edge label (text)
194
+ displayed for each edge. If the attribute is "" or not present, no edge
195
+ label is drawn.
196
+ Or a dict keyed by edge to a string holding the label for that edge.
197
+ edge_label_options : string or dict
198
+ The name of the edge attribute on `G` that holds the label options for
199
+ each edge. For example, "[sloped,above,blue]". The default is no options.
200
+ Or a dict keyed by edge to a string holding the label options for that edge.
201
+
202
+ Returns
203
+ =======
204
+ latex_code : string
205
+ The text string which draws the desired graph(s) when compiled by LaTeX.
206
+
207
+ See Also
208
+ ========
209
+ to_latex
210
+ write_latex
211
+ """
212
+ i4 = "\n "
213
+ i8 = "\n "
214
+
215
+ # set up position dict
216
+ # TODO allow pos to be None and use a nice TikZ default
217
+ if not isinstance(pos, dict):
218
+ pos = nx.get_node_attributes(G, pos)
219
+ if not pos:
220
+ # circular layout with radius 2
221
+ pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
222
+ for node in G:
223
+ if node not in pos:
224
+ raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
225
+ posnode = pos[node]
226
+ if not isinstance(posnode, str):
227
+ try:
228
+ posx, posy = posnode
229
+ pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
230
+ except (TypeError, ValueError):
231
+ msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
232
+ raise nx.NetworkXError(msg)
233
+
234
+ # set up all the dicts
235
+ if not isinstance(node_options, dict):
236
+ node_options = nx.get_node_attributes(G, node_options)
237
+ if not isinstance(node_label, dict):
238
+ node_label = nx.get_node_attributes(G, node_label)
239
+ if not isinstance(edge_options, dict):
240
+ edge_options = nx.get_edge_attributes(G, edge_options)
241
+ if not isinstance(edge_label, dict):
242
+ edge_label = nx.get_edge_attributes(G, edge_label)
243
+ if not isinstance(edge_label_options, dict):
244
+ edge_label_options = nx.get_edge_attributes(G, edge_label_options)
245
+
246
+ # process default options (add brackets or not)
247
+ topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
248
+ defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
249
+ linestyle = f"{'->' if G.is_directed() else '-'}"
250
+ if default_edge_options == "":
251
+ defe = "[" + linestyle + "]"
252
+ elif "-" in default_edge_options:
253
+ defe = default_edge_options
254
+ else:
255
+ defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
256
+
257
+ # Construct the string line by line
258
+ result = " \\begin{tikzpicture}" + topts
259
+ result += i4 + " \\draw" + defn
260
+ # load the nodes
261
+ for n in G:
262
+ # node options goes inside square brackets
263
+ nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
264
+ # node text goes inside curly brackets {}
265
+ ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
266
+
267
+ result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
268
+ result += ";\n"
269
+
270
+ # load the edges
271
+ result += " \\begin{scope}" + defe
272
+ for edge in G.edges:
273
+ u, v = edge[:2]
274
+ e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
275
+ # add loop options for selfloops if not present
276
+ if u == v and "loop" not in e_opts:
277
+ e_opts = "loop," + e_opts
278
+ e_opts = f"[{e_opts}]" if e_opts != "" else ""
279
+ # TODO -- handle bending of multiedges
280
+
281
+ els = edge_label_options[edge] if edge in edge_label_options else ""
282
+ # edge label options goes inside square brackets []
283
+ els = f"[{els.strip('[]')}]"
284
+ # edge text is drawn using the TikZ node command inside curly brackets {}
285
+ e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
286
+
287
+ result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
288
+
289
+ result += "\n \\end{scope}\n \\end{tikzpicture}\n"
290
+ return result
291
+
292
+
293
+ _DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
294
+ \usepackage{{tikz}}
295
+ \usepackage{{subcaption}}
296
+
297
+ \begin{{document}}
298
+ {content}
299
+ \end{{document}}"""
300
+
301
+
302
+ _FIG_WRAPPER = r"""\begin{{figure}}
303
+ {content}{caption}{label}
304
+ \end{{figure}}"""
305
+
306
+
307
+ _SUBFIG_WRAPPER = r""" \begin{{subfigure}}{{{size}\textwidth}}
308
+ {content}{caption}{label}
309
+ \end{{subfigure}}"""
310
+
311
+
312
+ def to_latex(
313
+ Gbunch,
314
+ pos="pos",
315
+ tikz_options="",
316
+ default_node_options="",
317
+ node_options="node_options",
318
+ node_label="node_label",
319
+ default_edge_options="",
320
+ edge_options="edge_options",
321
+ edge_label="edge_label",
322
+ edge_label_options="edge_label_options",
323
+ caption="",
324
+ latex_label="",
325
+ sub_captions=None,
326
+ sub_labels=None,
327
+ n_rows=1,
328
+ as_document=True,
329
+ document_wrapper=_DOC_WRAPPER_TIKZ,
330
+ figure_wrapper=_FIG_WRAPPER,
331
+ subfigure_wrapper=_SUBFIG_WRAPPER,
332
+ ):
333
+ """Return latex code to draw the graph(s) in `Gbunch`
334
+
335
+ The TikZ drawing utility in LaTeX is used to draw the graph(s).
336
+ If `Gbunch` is a graph, it is drawn in a figure environment.
337
+ If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
338
+ within a single figure environment.
339
+
340
+ If `as_document` is True, the figure is wrapped inside a document environment
341
+ so that the resulting string is ready to be compiled by LaTeX. Otherwise,
342
+ the string is ready for inclusion in a larger tex document using ``\\include``
343
+ or ``\\input`` statements.
344
+
345
+ Parameters
346
+ ==========
347
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
348
+ The NetworkX graph to be drawn or an iterable of graphs
349
+ to be drawn inside subfigures of a single figure.
350
+ pos : string or list of strings
351
+ The name of the node attribute on `G` that holds the position of each node.
352
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
353
+ They can also be strings to denote positions in TikZ style, such as (x, y)
354
+ or (angle:radius).
355
+ If a dict, it should be keyed by node to a position.
356
+ If an empty dict, a circular layout is computed by TikZ.
357
+ If you are drawing many graphs in subfigures, use a list of position dicts.
358
+ tikz_options : string
359
+ The tikzpicture options description defining the options for the picture.
360
+ Often large scale options like `[scale=2]`.
361
+ default_node_options : string
362
+ The draw options for a path of nodes. Individual node options override these.
363
+ node_options : string or dict
364
+ The name of the node attribute on `G` that holds the options for each node.
365
+ Or a dict keyed by node to a string holding the options for that node.
366
+ node_label : string or dict
367
+ The name of the node attribute on `G` that holds the node label (text)
368
+ displayed for each node. If the attribute is "" or not present, the node
369
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
370
+ Or a dict keyed by node to a string holding the label for that node.
371
+ default_edge_options : string
372
+ The options for the scope drawing all edges. The default is "[-]" for
373
+ undirected graphs and "[->]" for directed graphs.
374
+ edge_options : string or dict
375
+ The name of the edge attribute on `G` that holds the options for each edge.
376
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
377
+ "loop," is added to the options for the self-loop edge. Hence you can
378
+ use "[loop above]" explicitly, but the default is "[loop]".
379
+ Or a dict keyed by edge to a string holding the options for that edge.
380
+ edge_label : string or dict
381
+ The name of the edge attribute on `G` that holds the edge label (text)
382
+ displayed for each edge. If the attribute is "" or not present, no edge
383
+ label is drawn.
384
+ Or a dict keyed by edge to a string holding the label for that edge.
385
+ edge_label_options : string or dict
386
+ The name of the edge attribute on `G` that holds the label options for
387
+ each edge. For example, "[sloped,above,blue]". The default is no options.
388
+ Or a dict keyed by edge to a string holding the label options for that edge.
389
+ caption : string
390
+ The caption string for the figure environment
391
+ latex_label : string
392
+ The latex label used for the figure for easy referral from the main text
393
+ sub_captions : list of strings
394
+ The sub_caption string for each subfigure in the figure
395
+ sub_latex_labels : list of strings
396
+ The latex label for each subfigure in the figure
397
+ n_rows : int
398
+ The number of rows of subfigures to arrange for multiple graphs
399
+ as_document : bool
400
+ Whether to wrap the latex code in a document environment for compiling
401
+ document_wrapper : formatted text string with variable ``content``.
402
+ This text is called to evaluate the content embedded in a document
403
+ environment with a preamble setting up TikZ.
404
+ figure_wrapper : formatted text string
405
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
406
+ It wraps the content and if a caption is provided, adds the latex code for
407
+ that caption, and if a label is provided, adds the latex code for a label.
408
+ subfigure_wrapper : formatted text string
409
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
410
+ It wraps the content and if a caption is provided, adds the latex code for
411
+ that caption, and if a label is provided, adds the latex code for a label.
412
+ The size is the vertical size of each row of subfigures as a fraction.
413
+
414
+ Returns
415
+ =======
416
+ latex_code : string
417
+ The text string which draws the desired graph(s) when compiled by LaTeX.
418
+
419
+ See Also
420
+ ========
421
+ write_latex
422
+ to_latex_raw
423
+ """
424
+ if hasattr(Gbunch, "adj"):
425
+ raw = to_latex_raw(
426
+ Gbunch,
427
+ pos,
428
+ tikz_options,
429
+ default_node_options,
430
+ node_options,
431
+ node_label,
432
+ default_edge_options,
433
+ edge_options,
434
+ edge_label,
435
+ edge_label_options,
436
+ )
437
+ else: # iterator of graphs
438
+ sbf = subfigure_wrapper
439
+ size = 1 / n_rows
440
+
441
+ N = len(Gbunch)
442
+ if isinstance(pos, str | dict):
443
+ pos = [pos] * N
444
+ if sub_captions is None:
445
+ sub_captions = [""] * N
446
+ if sub_labels is None:
447
+ sub_labels = [""] * N
448
+ if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
449
+ raise nx.NetworkXError(
450
+ "length of Gbunch, sub_captions and sub_figures must agree"
451
+ )
452
+
453
+ raw = ""
454
+ for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
455
+ subraw = to_latex_raw(
456
+ G,
457
+ pos,
458
+ tikz_options,
459
+ default_node_options,
460
+ node_options,
461
+ node_label,
462
+ default_edge_options,
463
+ edge_options,
464
+ edge_label,
465
+ edge_label_options,
466
+ )
467
+ cap = f" \\caption{{{subcap}}}" if subcap else ""
468
+ lbl = f"\\label{{{sublbl}}}" if sublbl else ""
469
+ raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
470
+ raw += "\n"
471
+
472
+ # put raw latex code into a figure environment and optionally into a document
473
+ raw = raw[:-1]
474
+ cap = f"\n \\caption{{{caption}}}" if caption else ""
475
+ lbl = f"\\label{{{latex_label}}}" if latex_label else ""
476
+ fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
477
+ if as_document:
478
+ return document_wrapper.format(content=fig)
479
+ return fig
480
+
481
+
482
+ @nx.utils.open_file(1, mode="w")
483
+ def write_latex(Gbunch, path, **options):
484
+ """Write the latex code to draw the graph(s) onto `path`.
485
+
486
+ This convenience function creates the latex drawing code as a string
487
+ and writes that to a file ready to be compiled when `as_document` is True
488
+ or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
489
+
490
+ The `path` argument can be a string filename or a file handle to write to.
491
+
492
+ Parameters
493
+ ----------
494
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
495
+ If Gbunch is a graph, it is drawn in a figure environment.
496
+ If Gbunch is an iterable of graphs, each is drawn in a subfigure
497
+ environment within a single figure environment.
498
+ path : filename
499
+ Filename or file handle to write to
500
+ options : dict
501
+ By default, TikZ is used with options: (others are ignored)::
502
+
503
+ pos : string or dict or list
504
+ The name of the node attribute on `G` that holds the position of each node.
505
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
506
+ They can also be strings to denote positions in TikZ style, such as (x, y)
507
+ or (angle:radius).
508
+ If a dict, it should be keyed by node to a position.
509
+ If an empty dict, a circular layout is computed by TikZ.
510
+ If you are drawing many graphs in subfigures, use a list of position dicts.
511
+ tikz_options : string
512
+ The tikzpicture options description defining the options for the picture.
513
+ Often large scale options like `[scale=2]`.
514
+ default_node_options : string
515
+ The draw options for a path of nodes. Individual node options override these.
516
+ node_options : string or dict
517
+ The name of the node attribute on `G` that holds the options for each node.
518
+ Or a dict keyed by node to a string holding the options for that node.
519
+ node_label : string or dict
520
+ The name of the node attribute on `G` that holds the node label (text)
521
+ displayed for each node. If the attribute is "" or not present, the node
522
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
523
+ Or a dict keyed by node to a string holding the label for that node.
524
+ default_edge_options : string
525
+ The options for the scope drawing all edges. The default is "[-]" for
526
+ undirected graphs and "[->]" for directed graphs.
527
+ edge_options : string or dict
528
+ The name of the edge attribute on `G` that holds the options for each edge.
529
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
530
+ "loop," is added to the options for the self-loop edge. Hence you can
531
+ use "[loop above]" explicitly, but the default is "[loop]".
532
+ Or a dict keyed by edge to a string holding the options for that edge.
533
+ edge_label : string or dict
534
+ The name of the edge attribute on `G` that holds the edge label (text)
535
+ displayed for each edge. If the attribute is "" or not present, no edge
536
+ label is drawn.
537
+ Or a dict keyed by edge to a string holding the label for that edge.
538
+ edge_label_options : string or dict
539
+ The name of the edge attribute on `G` that holds the label options for
540
+ each edge. For example, "[sloped,above,blue]". The default is no options.
541
+ Or a dict keyed by edge to a string holding the label options for that edge.
542
+ caption : string
543
+ The caption string for the figure environment
544
+ latex_label : string
545
+ The latex label used for the figure for easy referral from the main text
546
+ sub_captions : list of strings
547
+ The sub_caption string for each subfigure in the figure
548
+ sub_latex_labels : list of strings
549
+ The latex label for each subfigure in the figure
550
+ n_rows : int
551
+ The number of rows of subfigures to arrange for multiple graphs
552
+ as_document : bool
553
+ Whether to wrap the latex code in a document environment for compiling
554
+ document_wrapper : formatted text string with variable ``content``.
555
+ This text is called to evaluate the content embedded in a document
556
+ environment with a preamble setting up the TikZ syntax.
557
+ figure_wrapper : formatted text string
558
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
559
+ It wraps the content and if a caption is provided, adds the latex code for
560
+ that caption, and if a label is provided, adds the latex code for a label.
561
+ subfigure_wrapper : formatted text string
562
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
563
+ It wraps the content and if a caption is provided, adds the latex code for
564
+ that caption, and if a label is provided, adds the latex code for a label.
565
+ The size is the vertical size of each row of subfigures as a fraction.
566
+
567
+ See Also
568
+ ========
569
+ to_latex
570
+ """
571
+ path.write(to_latex(Gbunch, **options))
llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from locale import getpreferredencoding
23
+
24
+ import networkx as nx
25
+ from networkx.utils import open_file
26
+
27
+ __all__ = [
28
+ "write_dot",
29
+ "read_dot",
30
+ "graphviz_layout",
31
+ "pydot_layout",
32
+ "to_pydot",
33
+ "from_pydot",
34
+ ]
35
+
36
+
37
+ @open_file(1, mode="w")
38
+ def write_dot(G, path):
39
+ """Write NetworkX graph G to Graphviz dot format on path.
40
+
41
+ Path can be a string or a file handle.
42
+ """
43
+ P = to_pydot(G)
44
+ path.write(P.to_string())
45
+ return
46
+
47
+
48
+ @open_file(0, mode="r")
49
+ @nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
50
+ def read_dot(path):
51
+ """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
52
+ dot file with the passed path.
53
+
54
+ If this file contains multiple graphs, only the first such graph is
55
+ returned. All graphs _except_ the first are silently ignored.
56
+
57
+ Parameters
58
+ ----------
59
+ path : str or file
60
+ Filename or file handle.
61
+
62
+ Returns
63
+ -------
64
+ G : MultiGraph or MultiDiGraph
65
+ A :class:`MultiGraph` or :class:`MultiDiGraph`.
66
+
67
+ Notes
68
+ -----
69
+ Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
70
+ :class:`MultiGraph`.
71
+ """
72
+ import pydot
73
+
74
+ data = path.read()
75
+
76
+ # List of one or more "pydot.Dot" instances deserialized from this file.
77
+ P_list = pydot.graph_from_dot_data(data)
78
+
79
+ # Convert only the first such instance into a NetworkX graph.
80
+ return from_pydot(P_list[0])
81
+
82
+
83
+ @nx._dispatchable(graphs=None, returns_graph=True)
84
+ def from_pydot(P):
85
+ """Returns a NetworkX graph from a Pydot graph.
86
+
87
+ Parameters
88
+ ----------
89
+ P : Pydot graph
90
+ A graph created with Pydot
91
+
92
+ Returns
93
+ -------
94
+ G : NetworkX multigraph
95
+ A MultiGraph or MultiDiGraph.
96
+
97
+ Examples
98
+ --------
99
+ >>> K5 = nx.complete_graph(5)
100
+ >>> A = nx.nx_pydot.to_pydot(K5)
101
+ >>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
102
+
103
+ # make a Graph instead of MultiGraph
104
+ >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
105
+
106
+ """
107
+
108
+ if P.get_strict(None): # pydot bug: get_strict() shouldn't take argument
109
+ multiedges = False
110
+ else:
111
+ multiedges = True
112
+
113
+ if P.get_type() == "graph": # undirected
114
+ if multiedges:
115
+ N = nx.MultiGraph()
116
+ else:
117
+ N = nx.Graph()
118
+ else:
119
+ if multiedges:
120
+ N = nx.MultiDiGraph()
121
+ else:
122
+ N = nx.DiGraph()
123
+
124
+ # assign defaults
125
+ name = P.get_name().strip('"')
126
+ if name != "":
127
+ N.name = name
128
+
129
+ # add nodes, attributes to N.node_attr
130
+ for p in P.get_node_list():
131
+ n = p.get_name().strip('"')
132
+ if n in ("node", "graph", "edge"):
133
+ continue
134
+ N.add_node(n, **p.get_attributes())
135
+
136
+ # add edges
137
+ for e in P.get_edge_list():
138
+ u = e.get_source()
139
+ v = e.get_destination()
140
+ attr = e.get_attributes()
141
+ s = []
142
+ d = []
143
+
144
+ if isinstance(u, str):
145
+ s.append(u.strip('"'))
146
+ else:
147
+ for unodes in u["nodes"]:
148
+ s.append(unodes.strip('"'))
149
+
150
+ if isinstance(v, str):
151
+ d.append(v.strip('"'))
152
+ else:
153
+ for vnodes in v["nodes"]:
154
+ d.append(vnodes.strip('"'))
155
+
156
+ for source_node in s:
157
+ for destination_node in d:
158
+ N.add_edge(source_node, destination_node, **attr)
159
+
160
+ # add default attributes for graph, nodes, edges
161
+ pattr = P.get_attributes()
162
+ if pattr:
163
+ N.graph["graph"] = pattr
164
+ try:
165
+ N.graph["node"] = P.get_node_defaults()[0]
166
+ except (IndexError, TypeError):
167
+ pass # N.graph['node']={}
168
+ try:
169
+ N.graph["edge"] = P.get_edge_defaults()[0]
170
+ except (IndexError, TypeError):
171
+ pass # N.graph['edge']={}
172
+ return N
173
+
174
+
175
+ def _check_colon_quotes(s):
176
+ # A quick helper function to check if a string has a colon in it
177
+ # and if it is quoted properly with double quotes.
178
+ # refer https://github.com/pydot/pydot/issues/258
179
+ return ":" in s and (s[0] != '"' or s[-1] != '"')
180
+
181
+
182
+ def to_pydot(N):
183
+ """Returns a pydot graph from a NetworkX graph N.
184
+
185
+ Parameters
186
+ ----------
187
+ N : NetworkX graph
188
+ A graph created with NetworkX
189
+
190
+ Examples
191
+ --------
192
+ >>> K5 = nx.complete_graph(5)
193
+ >>> P = nx.nx_pydot.to_pydot(K5)
194
+
195
+ Notes
196
+ -----
197
+
198
+ """
199
+ import pydot
200
+
201
+ # set Graphviz graph type
202
+ if N.is_directed():
203
+ graph_type = "digraph"
204
+ else:
205
+ graph_type = "graph"
206
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
207
+
208
+ name = N.name
209
+ graph_defaults = N.graph.get("graph", {})
210
+ if name == "":
211
+ P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
212
+ else:
213
+ P = pydot.Dot(
214
+ f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
215
+ )
216
+ try:
217
+ P.set_node_defaults(**N.graph["node"])
218
+ except KeyError:
219
+ pass
220
+ try:
221
+ P.set_edge_defaults(**N.graph["edge"])
222
+ except KeyError:
223
+ pass
224
+
225
+ for n, nodedata in N.nodes(data=True):
226
+ str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
227
+ # Explicitly catch nodes with ":" in node names or nodedata.
228
+ n = str(n)
229
+ raise_error = _check_colon_quotes(n) or (
230
+ any(
231
+ (_check_colon_quotes(k) or _check_colon_quotes(v))
232
+ for k, v in str_nodedata.items()
233
+ )
234
+ )
235
+ if raise_error:
236
+ raise ValueError(
237
+ f'Node names and attributes should not contain ":" unless they are quoted with "".\
238
+ For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
239
+ Please refer https://github.com/pydot/pydot/issues/258'
240
+ )
241
+ p = pydot.Node(n, **str_nodedata)
242
+ P.add_node(p)
243
+
244
+ if N.is_multigraph():
245
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
246
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
247
+ u, v = str(u), str(v)
248
+ raise_error = (
249
+ _check_colon_quotes(u)
250
+ or _check_colon_quotes(v)
251
+ or (
252
+ any(
253
+ (_check_colon_quotes(k) or _check_colon_quotes(val))
254
+ for k, val in str_edgedata.items()
255
+ )
256
+ )
257
+ )
258
+ if raise_error:
259
+ raise ValueError(
260
+ f'Node names and attributes should not contain ":" unless they are quoted with "".\
261
+ For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
262
+ Please refer https://github.com/pydot/pydot/issues/258'
263
+ )
264
+ edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
265
+ P.add_edge(edge)
266
+
267
+ else:
268
+ for u, v, edgedata in N.edges(data=True):
269
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
270
+ u, v = str(u), str(v)
271
+ raise_error = (
272
+ _check_colon_quotes(u)
273
+ or _check_colon_quotes(v)
274
+ or (
275
+ any(
276
+ (_check_colon_quotes(k) or _check_colon_quotes(val))
277
+ for k, val in str_edgedata.items()
278
+ )
279
+ )
280
+ )
281
+ if raise_error:
282
+ raise ValueError(
283
+ f'Node names and attributes should not contain ":" unless they are quoted with "".\
284
+ For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
285
+ Please refer https://github.com/pydot/pydot/issues/258'
286
+ )
287
+ edge = pydot.Edge(u, v, **str_edgedata)
288
+ P.add_edge(edge)
289
+ return P
290
+
291
+
292
+ def graphviz_layout(G, prog="neato", root=None):
293
+ """Create node positions using Pydot and Graphviz.
294
+
295
+ Returns a dictionary of positions keyed by node.
296
+
297
+ Parameters
298
+ ----------
299
+ G : NetworkX Graph
300
+ The graph for which the layout is computed.
301
+ prog : string (default: 'neato')
302
+ The name of the GraphViz program to use for layout.
303
+ Options depend on GraphViz version but may include:
304
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
305
+ root : Node from G or None (default: None)
306
+ The node of G from which to start some layout algorithms.
307
+
308
+ Returns
309
+ -------
310
+ Dictionary of (x, y) positions keyed by node.
311
+
312
+ Examples
313
+ --------
314
+ >>> G = nx.complete_graph(4)
315
+ >>> pos = nx.nx_pydot.graphviz_layout(G)
316
+ >>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
317
+
318
+ Notes
319
+ -----
320
+ This is a wrapper for pydot_layout.
321
+ """
322
+ return pydot_layout(G=G, prog=prog, root=root)
323
+
324
+
325
+ def pydot_layout(G, prog="neato", root=None):
326
+ """Create node positions using :mod:`pydot` and Graphviz.
327
+
328
+ Parameters
329
+ ----------
330
+ G : Graph
331
+ NetworkX graph to be laid out.
332
+ prog : string (default: 'neato')
333
+ Name of the GraphViz command to use for layout.
334
+ Options depend on GraphViz version but may include:
335
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
336
+ root : Node from G or None (default: None)
337
+ The node of G from which to start some layout algorithms.
338
+
339
+ Returns
340
+ -------
341
+ dict
342
+ Dictionary of positions keyed by node.
343
+
344
+ Examples
345
+ --------
346
+ >>> G = nx.complete_graph(4)
347
+ >>> pos = nx.nx_pydot.pydot_layout(G)
348
+ >>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
349
+
350
+ Notes
351
+ -----
352
+ If you use complex node objects, they may have the same string
353
+ representation and GraphViz could treat them as the same node.
354
+ The layout may assign both nodes a single location. See Issue #1568
355
+ If this occurs in your case, consider relabeling the nodes just
356
+ for the layout computation using something similar to::
357
+
358
+ H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
359
+ H_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
360
+ G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
361
+
362
+ """
363
+ import pydot
364
+
365
+ P = to_pydot(G)
366
+ if root is not None:
367
+ P.set("root", str(root))
368
+
369
+ # List of low-level bytes comprising a string in the dot language converted
370
+ # from the passed graph with the passed external GraphViz command.
371
+ D_bytes = P.create_dot(prog=prog)
372
+
373
+ # Unique string decoded from these bytes with the preferred locale encoding
374
+ D = str(D_bytes, encoding=getpreferredencoding())
375
+
376
+ if D == "": # no data returned
377
+ print(f"Graphviz layout with {prog} failed")
378
+ print()
379
+ print("To debug what happened try:")
380
+ print("P = nx.nx_pydot.to_pydot(G)")
381
+ print('P.write_dot("file.dot")')
382
+ print(f"And then run {prog} on file.dot")
383
+ return
384
+
385
+ # List of one or more "pydot.Dot" instances deserialized from this string.
386
+ Q_list = pydot.graph_from_dot_data(D)
387
+ assert len(Q_list) == 1
388
+
389
+ # The first and only such instance, as guaranteed by the above assertion.
390
+ Q = Q_list[0]
391
+
392
+ node_pos = {}
393
+ for n in G.nodes():
394
+ str_n = str(n)
395
+ # Explicitly catch nodes with ":" in node names or nodedata.
396
+ if _check_colon_quotes(str_n):
397
+ raise ValueError(
398
+ f'Node names and node attributes should not contain ":" unless they are quoted with "".\
399
+ For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
400
+ Please refer https://github.com/pydot/pydot/issues/258'
401
+ )
402
+ pydot_node = pydot.Node(str_n).get_name()
403
+ node = Q.get_node(pydot_node)
404
+
405
+ if isinstance(node, list):
406
+ node = node[0]
407
+ pos = node.get_pos()[1:-1] # strip leading and trailing double quotes
408
+ if pos is not None:
409
+ xx, yy = pos.split(",")
410
+ node_pos[n] = (float(xx), float(yy))
411
+ return node_pos
llmeval-env/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py ADDED
@@ -0,0 +1,1871 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import collections
20
+ import itertools
21
+ from numbers import Number
22
+
23
+ import networkx as nx
24
+ from networkx.drawing.layout import (
25
+ circular_layout,
26
+ kamada_kawai_layout,
27
+ planar_layout,
28
+ random_layout,
29
+ shell_layout,
30
+ spectral_layout,
31
+ spring_layout,
32
+ )
33
+
34
+ __all__ = [
35
+ "draw",
36
+ "draw_networkx",
37
+ "draw_networkx_nodes",
38
+ "draw_networkx_edges",
39
+ "draw_networkx_labels",
40
+ "draw_networkx_edge_labels",
41
+ "draw_circular",
42
+ "draw_kamada_kawai",
43
+ "draw_random",
44
+ "draw_spectral",
45
+ "draw_spring",
46
+ "draw_planar",
47
+ "draw_shell",
48
+ ]
49
+
50
+
51
+ def draw(G, pos=None, ax=None, **kwds):
52
+ """Draw the graph G with Matplotlib.
53
+
54
+ Draw the graph as a simple representation with no node
55
+ labels or edge labels and using the full Matplotlib figure area
56
+ and no axis labels by default. See draw_networkx() for more
57
+ full-featured drawing that allows title, axis labels etc.
58
+
59
+ Parameters
60
+ ----------
61
+ G : graph
62
+ A networkx graph
63
+
64
+ pos : dictionary, optional
65
+ A dictionary with nodes as keys and positions as values.
66
+ If not specified a spring layout positioning will be computed.
67
+ See :py:mod:`networkx.drawing.layout` for functions that
68
+ compute node positions.
69
+
70
+ ax : Matplotlib Axes object, optional
71
+ Draw the graph in specified Matplotlib axes.
72
+
73
+ kwds : optional keywords
74
+ See networkx.draw_networkx() for a description of optional keywords.
75
+
76
+ Examples
77
+ --------
78
+ >>> G = nx.dodecahedral_graph()
79
+ >>> nx.draw(G)
80
+ >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
81
+
82
+ See Also
83
+ --------
84
+ draw_networkx
85
+ draw_networkx_nodes
86
+ draw_networkx_edges
87
+ draw_networkx_labels
88
+ draw_networkx_edge_labels
89
+
90
+ Notes
91
+ -----
92
+ This function has the same name as pylab.draw and pyplot.draw
93
+ so beware when using `from networkx import *`
94
+
95
+ since you might overwrite the pylab.draw function.
96
+
97
+ With pyplot use
98
+
99
+ >>> import matplotlib.pyplot as plt
100
+ >>> G = nx.dodecahedral_graph()
101
+ >>> nx.draw(G) # networkx draw()
102
+ >>> plt.draw() # pyplot draw()
103
+
104
+ Also see the NetworkX drawing examples at
105
+ https://networkx.org/documentation/latest/auto_examples/index.html
106
+ """
107
+ import matplotlib.pyplot as plt
108
+
109
+ if ax is None:
110
+ cf = plt.gcf()
111
+ else:
112
+ cf = ax.get_figure()
113
+ cf.set_facecolor("w")
114
+ if ax is None:
115
+ if cf.axes:
116
+ ax = cf.gca()
117
+ else:
118
+ ax = cf.add_axes((0, 0, 1, 1))
119
+
120
+ if "with_labels" not in kwds:
121
+ kwds["with_labels"] = "labels" in kwds
122
+
123
+ draw_networkx(G, pos=pos, ax=ax, **kwds)
124
+ ax.set_axis_off()
125
+ plt.draw_if_interactive()
126
+ return
127
+
128
+
129
+ def draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds):
130
+ r"""Draw the graph G using Matplotlib.
131
+
132
+ Draw the graph with Matplotlib with options for node positions,
133
+ labeling, titles, and many other drawing features.
134
+ See draw() for simple drawing without labels or axes.
135
+
136
+ Parameters
137
+ ----------
138
+ G : graph
139
+ A networkx graph
140
+
141
+ pos : dictionary, optional
142
+ A dictionary with nodes as keys and positions as values.
143
+ If not specified a spring layout positioning will be computed.
144
+ See :py:mod:`networkx.drawing.layout` for functions that
145
+ compute node positions.
146
+
147
+ arrows : bool or None, optional (default=None)
148
+ If `None`, directed graphs draw arrowheads with
149
+ `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
150
+ via `~matplotlib.collections.LineCollection` for speed.
151
+ If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
152
+ If `False`, draw edges using LineCollection (linear and fast).
153
+ For directed graphs, if True draw arrowheads.
154
+ Note: Arrows will be the same color as edges.
155
+
156
+ arrowstyle : str (default='-\|>' for directed graphs)
157
+ For directed graphs, choose the style of the arrowsheads.
158
+ For undirected graphs default to '-'
159
+
160
+ See `matplotlib.patches.ArrowStyle` for more options.
161
+
162
+ arrowsize : int or list (default=10)
163
+ For directed graphs, choose the size of the arrow head's length and
164
+ width. A list of values can be passed in to assign a different size for arrow head's length and width.
165
+ See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
166
+ for more info.
167
+
168
+ with_labels : bool (default=True)
169
+ Set to True to draw labels on the nodes.
170
+
171
+ ax : Matplotlib Axes object, optional
172
+ Draw the graph in the specified Matplotlib axes.
173
+
174
+ nodelist : list (default=list(G))
175
+ Draw only specified nodes
176
+
177
+ edgelist : list (default=list(G.edges()))
178
+ Draw only specified edges
179
+
180
+ node_size : scalar or array (default=300)
181
+ Size of nodes. If an array is specified it must be the
182
+ same length as nodelist.
183
+
184
+ node_color : color or array of colors (default='#1f78b4')
185
+ Node color. Can be a single color or a sequence of colors with the same
186
+ length as nodelist. Color can be string or rgb (or rgba) tuple of
187
+ floats from 0-1. If numeric values are specified they will be
188
+ mapped to colors using the cmap and vmin,vmax parameters. See
189
+ matplotlib.scatter for more details.
190
+
191
+ node_shape : string (default='o')
192
+ The shape of the node. Specification is as matplotlib.scatter
193
+ marker, one of 'so^>v<dph8'.
194
+
195
+ alpha : float or None (default=None)
196
+ The node and edge transparency
197
+
198
+ cmap : Matplotlib colormap, optional
199
+ Colormap for mapping intensities of nodes
200
+
201
+ vmin,vmax : float, optional
202
+ Minimum and maximum for node colormap scaling
203
+
204
+ linewidths : scalar or sequence (default=1.0)
205
+ Line width of symbol border
206
+
207
+ width : float or array of floats (default=1.0)
208
+ Line width of edges
209
+
210
+ edge_color : color or array of colors (default='k')
211
+ Edge color. Can be a single color or a sequence of colors with the same
212
+ length as edgelist. Color can be string or rgb (or rgba) tuple of
213
+ floats from 0-1. If numeric values are specified they will be
214
+ mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
215
+
216
+ edge_cmap : Matplotlib colormap, optional
217
+ Colormap for mapping intensities of edges
218
+
219
+ edge_vmin,edge_vmax : floats, optional
220
+ Minimum and maximum for edge colormap scaling
221
+
222
+ style : string (default=solid line)
223
+ Edge line style e.g.: '-', '--', '-.', ':'
224
+ or words like 'solid' or 'dashed'.
225
+ (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
226
+
227
+ labels : dictionary (default=None)
228
+ Node labels in a dictionary of text labels keyed by node
229
+
230
+ font_size : int (default=12 for nodes, 10 for edges)
231
+ Font size for text labels
232
+
233
+ font_color : color (default='k' black)
234
+ Font color string. Color can be string or rgb (or rgba) tuple of
235
+ floats from 0-1.
236
+
237
+ font_weight : string (default='normal')
238
+ Font weight
239
+
240
+ font_family : string (default='sans-serif')
241
+ Font family
242
+
243
+ label : string, optional
244
+ Label for graph legend
245
+
246
+ hide_ticks : bool, optional
247
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
248
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
249
+ use ``hide_ticks=False``.
250
+
251
+ kwds : optional keywords
252
+ See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
253
+ networkx.draw_networkx_labels() for a description of optional keywords.
254
+
255
+ Notes
256
+ -----
257
+ For directed graphs, arrows are drawn at the head end. Arrows can be
258
+ turned off with keyword arrows=False.
259
+
260
+ Examples
261
+ --------
262
+ >>> G = nx.dodecahedral_graph()
263
+ >>> nx.draw(G)
264
+ >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
265
+
266
+ >>> import matplotlib.pyplot as plt
267
+ >>> limits = plt.axis("off") # turn off axis
268
+
269
+ Also see the NetworkX drawing examples at
270
+ https://networkx.org/documentation/latest/auto_examples/index.html
271
+
272
+ See Also
273
+ --------
274
+ draw
275
+ draw_networkx_nodes
276
+ draw_networkx_edges
277
+ draw_networkx_labels
278
+ draw_networkx_edge_labels
279
+ """
280
+ from inspect import signature
281
+
282
+ import matplotlib.pyplot as plt
283
+
284
+ # Get all valid keywords by inspecting the signatures of draw_networkx_nodes,
285
+ # draw_networkx_edges, draw_networkx_labels
286
+
287
+ valid_node_kwds = signature(draw_networkx_nodes).parameters.keys()
288
+ valid_edge_kwds = signature(draw_networkx_edges).parameters.keys()
289
+ valid_label_kwds = signature(draw_networkx_labels).parameters.keys()
290
+
291
+ # Create a set with all valid keywords across the three functions and
292
+ # remove the arguments of this function (draw_networkx)
293
+ valid_kwds = (valid_node_kwds | valid_edge_kwds | valid_label_kwds) - {
294
+ "G",
295
+ "pos",
296
+ "arrows",
297
+ "with_labels",
298
+ }
299
+
300
+ if any(k not in valid_kwds for k in kwds):
301
+ invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
302
+ raise ValueError(f"Received invalid argument(s): {invalid_args}")
303
+
304
+ node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
305
+ edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
306
+ label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
307
+
308
+ if pos is None:
309
+ pos = nx.drawing.spring_layout(G) # default to spring layout
310
+
311
+ draw_networkx_nodes(G, pos, **node_kwds)
312
+ draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
313
+ if with_labels:
314
+ draw_networkx_labels(G, pos, **label_kwds)
315
+ plt.draw_if_interactive()
316
+
317
+
318
+ def draw_networkx_nodes(
319
+ G,
320
+ pos,
321
+ nodelist=None,
322
+ node_size=300,
323
+ node_color="#1f78b4",
324
+ node_shape="o",
325
+ alpha=None,
326
+ cmap=None,
327
+ vmin=None,
328
+ vmax=None,
329
+ ax=None,
330
+ linewidths=None,
331
+ edgecolors=None,
332
+ label=None,
333
+ margins=None,
334
+ hide_ticks=True,
335
+ ):
336
+ """Draw the nodes of the graph G.
337
+
338
+ This draws only the nodes of the graph G.
339
+
340
+ Parameters
341
+ ----------
342
+ G : graph
343
+ A networkx graph
344
+
345
+ pos : dictionary
346
+ A dictionary with nodes as keys and positions as values.
347
+ Positions should be sequences of length 2.
348
+
349
+ ax : Matplotlib Axes object, optional
350
+ Draw the graph in the specified Matplotlib axes.
351
+
352
+ nodelist : list (default list(G))
353
+ Draw only specified nodes
354
+
355
+ node_size : scalar or array (default=300)
356
+ Size of nodes. If an array it must be the same length as nodelist.
357
+
358
+ node_color : color or array of colors (default='#1f78b4')
359
+ Node color. Can be a single color or a sequence of colors with the same
360
+ length as nodelist. Color can be string or rgb (or rgba) tuple of
361
+ floats from 0-1. If numeric values are specified they will be
362
+ mapped to colors using the cmap and vmin,vmax parameters. See
363
+ matplotlib.scatter for more details.
364
+
365
+ node_shape : string (default='o')
366
+ The shape of the node. Specification is as matplotlib.scatter
367
+ marker, one of 'so^>v<dph8'.
368
+
369
+ alpha : float or array of floats (default=None)
370
+ The node transparency. This can be a single alpha value,
371
+ in which case it will be applied to all the nodes of color. Otherwise,
372
+ if it is an array, the elements of alpha will be applied to the colors
373
+ in order (cycling through alpha multiple times if necessary).
374
+
375
+ cmap : Matplotlib colormap (default=None)
376
+ Colormap for mapping intensities of nodes
377
+
378
+ vmin,vmax : floats or None (default=None)
379
+ Minimum and maximum for node colormap scaling
380
+
381
+ linewidths : [None | scalar | sequence] (default=1.0)
382
+ Line width of symbol border
383
+
384
+ edgecolors : [None | scalar | sequence] (default = node_color)
385
+ Colors of node borders. Can be a single color or a sequence of colors with the
386
+ same length as nodelist. Color can be string or rgb (or rgba) tuple of floats
387
+ from 0-1. If numeric values are specified they will be mapped to colors
388
+ using the cmap and vmin,vmax parameters. See `~matplotlib.pyplot.scatter` for more details.
389
+
390
+ label : [None | string]
391
+ Label for legend
392
+
393
+ margins : float or 2-tuple, optional
394
+ Sets the padding for axis autoscaling. Increase margin to prevent
395
+ clipping for nodes that are near the edges of an image. Values should
396
+ be in the range ``[0, 1]``. See :meth:`matplotlib.axes.Axes.margins`
397
+ for details. The default is `None`, which uses the Matplotlib default.
398
+
399
+ hide_ticks : bool, optional
400
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
401
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
402
+ use ``hide_ticks=False``.
403
+
404
+ Returns
405
+ -------
406
+ matplotlib.collections.PathCollection
407
+ `PathCollection` of the nodes.
408
+
409
+ Examples
410
+ --------
411
+ >>> G = nx.dodecahedral_graph()
412
+ >>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
413
+
414
+ Also see the NetworkX drawing examples at
415
+ https://networkx.org/documentation/latest/auto_examples/index.html
416
+
417
+ See Also
418
+ --------
419
+ draw
420
+ draw_networkx
421
+ draw_networkx_edges
422
+ draw_networkx_labels
423
+ draw_networkx_edge_labels
424
+ """
425
+ from collections.abc import Iterable
426
+
427
+ import matplotlib as mpl
428
+ import matplotlib.collections # call as mpl.collections
429
+ import matplotlib.pyplot as plt
430
+ import numpy as np
431
+
432
+ if ax is None:
433
+ ax = plt.gca()
434
+
435
+ if nodelist is None:
436
+ nodelist = list(G)
437
+
438
+ if len(nodelist) == 0: # empty nodelist, no drawing
439
+ return mpl.collections.PathCollection(None)
440
+
441
+ try:
442
+ xy = np.asarray([pos[v] for v in nodelist])
443
+ except KeyError as err:
444
+ raise nx.NetworkXError(f"Node {err} has no position.") from err
445
+
446
+ if isinstance(alpha, Iterable):
447
+ node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
448
+ alpha = None
449
+
450
+ node_collection = ax.scatter(
451
+ xy[:, 0],
452
+ xy[:, 1],
453
+ s=node_size,
454
+ c=node_color,
455
+ marker=node_shape,
456
+ cmap=cmap,
457
+ vmin=vmin,
458
+ vmax=vmax,
459
+ alpha=alpha,
460
+ linewidths=linewidths,
461
+ edgecolors=edgecolors,
462
+ label=label,
463
+ )
464
+ if hide_ticks:
465
+ ax.tick_params(
466
+ axis="both",
467
+ which="both",
468
+ bottom=False,
469
+ left=False,
470
+ labelbottom=False,
471
+ labelleft=False,
472
+ )
473
+
474
+ if margins is not None:
475
+ if isinstance(margins, Iterable):
476
+ ax.margins(*margins)
477
+ else:
478
+ ax.margins(margins)
479
+
480
+ node_collection.set_zorder(2)
481
+ return node_collection
482
+
483
+
484
+ class FancyArrowFactory:
485
+ """Draw arrows with `matplotlib.patches.FancyarrowPatch`"""
486
+
487
+ class ConnectionStyleFactory:
488
+ def __init__(self, connectionstyles, selfloop_height, ax=None):
489
+ import matplotlib as mpl
490
+ import matplotlib.path # call as mpl.path
491
+ import numpy as np
492
+
493
+ self.ax = ax
494
+ self.mpl = mpl
495
+ self.np = np
496
+ self.base_connection_styles = [
497
+ mpl.patches.ConnectionStyle(cs) for cs in connectionstyles
498
+ ]
499
+ self.n = len(self.base_connection_styles)
500
+ self.selfloop_height = selfloop_height
501
+
502
+ def curved(self, edge_index):
503
+ return self.base_connection_styles[edge_index % self.n]
504
+
505
+ def self_loop(self, edge_index):
506
+ def self_loop_connection(posA, posB, *args, **kwargs):
507
+ if not self.np.all(posA == posB):
508
+ raise nx.NetworkXError(
509
+ "`self_loop` connection style method"
510
+ "is only to be used for self-loops"
511
+ )
512
+ # this is called with _screen space_ values
513
+ # so convert back to data space
514
+ data_loc = self.ax.transData.inverted().transform(posA)
515
+ v_shift = 0.1 * self.selfloop_height
516
+ h_shift = v_shift * 0.5
517
+ # put the top of the loop first so arrow is not hidden by node
518
+ path = self.np.asarray(
519
+ [
520
+ # 1
521
+ [0, v_shift],
522
+ # 4 4 4
523
+ [h_shift, v_shift],
524
+ [h_shift, 0],
525
+ [0, 0],
526
+ # 4 4 4
527
+ [-h_shift, 0],
528
+ [-h_shift, v_shift],
529
+ [0, v_shift],
530
+ ]
531
+ )
532
+ # Rotate self loop 90 deg. if more than 1
533
+ # This will allow for maximum of 4 visible self loops
534
+ if edge_index % 4:
535
+ x, y = path.T
536
+ for _ in range(edge_index % 4):
537
+ x, y = y, -x
538
+ path = self.np.array([x, y]).T
539
+ return self.mpl.path.Path(
540
+ self.ax.transData.transform(data_loc + path), [1, 4, 4, 4, 4, 4, 4]
541
+ )
542
+
543
+ return self_loop_connection
544
+
545
+ def __init__(
546
+ self,
547
+ edge_pos,
548
+ edgelist,
549
+ nodelist,
550
+ edge_indices,
551
+ node_size,
552
+ selfloop_height,
553
+ connectionstyle="arc3",
554
+ node_shape="o",
555
+ arrowstyle="-",
556
+ arrowsize=10,
557
+ edge_color="k",
558
+ alpha=None,
559
+ linewidth=1.0,
560
+ style="solid",
561
+ min_source_margin=0,
562
+ min_target_margin=0,
563
+ ax=None,
564
+ ):
565
+ import matplotlib as mpl
566
+ import matplotlib.patches # call as mpl.patches
567
+ import matplotlib.pyplot as plt
568
+ import numpy as np
569
+
570
+ if isinstance(connectionstyle, str):
571
+ connectionstyle = [connectionstyle]
572
+ elif np.iterable(connectionstyle):
573
+ connectionstyle = list(connectionstyle)
574
+ else:
575
+ msg = "ConnectionStyleFactory arg `connectionstyle` must be str or iterable"
576
+ raise nx.NetworkXError(msg)
577
+ self.ax = ax
578
+ self.mpl = mpl
579
+ self.np = np
580
+ self.edge_pos = edge_pos
581
+ self.edgelist = edgelist
582
+ self.nodelist = nodelist
583
+ self.node_shape = node_shape
584
+ self.min_source_margin = min_source_margin
585
+ self.min_target_margin = min_target_margin
586
+ self.edge_indices = edge_indices
587
+ self.node_size = node_size
588
+ self.connectionstyle_factory = self.ConnectionStyleFactory(
589
+ connectionstyle, selfloop_height, ax
590
+ )
591
+ self.arrowstyle = arrowstyle
592
+ self.arrowsize = arrowsize
593
+ self.arrow_colors = mpl.colors.colorConverter.to_rgba_array(edge_color, alpha)
594
+ self.linewidth = linewidth
595
+ self.style = style
596
+ if isinstance(arrowsize, list) and len(arrowsize) != len(edge_pos):
597
+ raise ValueError("arrowsize should have the same length as edgelist")
598
+
599
+ def __call__(self, i):
600
+ (x1, y1), (x2, y2) = self.edge_pos[i]
601
+ shrink_source = 0 # space from source to tail
602
+ shrink_target = 0 # space from head to target
603
+ if self.np.iterable(self.node_size): # many node sizes
604
+ source, target = self.edgelist[i][:2]
605
+ source_node_size = self.node_size[self.nodelist.index(source)]
606
+ target_node_size = self.node_size[self.nodelist.index(target)]
607
+ shrink_source = self.to_marker_edge(source_node_size, self.node_shape)
608
+ shrink_target = self.to_marker_edge(target_node_size, self.node_shape)
609
+ else:
610
+ shrink_source = self.to_marker_edge(self.node_size, self.node_shape)
611
+ shrink_target = shrink_source
612
+ shrink_source = max(shrink_source, self.min_source_margin)
613
+ shrink_target = max(shrink_target, self.min_target_margin)
614
+
615
+ # scale factor of arrow head
616
+ if isinstance(self.arrowsize, list):
617
+ mutation_scale = self.arrowsize[i]
618
+ else:
619
+ mutation_scale = self.arrowsize
620
+
621
+ if len(self.arrow_colors) > i:
622
+ arrow_color = self.arrow_colors[i]
623
+ elif len(self.arrow_colors) == 1:
624
+ arrow_color = self.arrow_colors[0]
625
+ else: # Cycle through colors
626
+ arrow_color = self.arrow_colors[i % len(self.arrow_colors)]
627
+
628
+ if self.np.iterable(self.linewidth):
629
+ if len(self.linewidth) > i:
630
+ linewidth = self.linewidth[i]
631
+ else:
632
+ linewidth = self.linewidth[i % len(self.linewidth)]
633
+ else:
634
+ linewidth = self.linewidth
635
+
636
+ if (
637
+ self.np.iterable(self.style)
638
+ and not isinstance(self.style, str)
639
+ and not isinstance(self.style, tuple)
640
+ ):
641
+ if len(self.style) > i:
642
+ linestyle = self.style[i]
643
+ else: # Cycle through styles
644
+ linestyle = self.style[i % len(self.style)]
645
+ else:
646
+ linestyle = self.style
647
+
648
+ if x1 == x2 and y1 == y2:
649
+ connectionstyle = self.connectionstyle_factory.self_loop(
650
+ self.edge_indices[i]
651
+ )
652
+ else:
653
+ connectionstyle = self.connectionstyle_factory.curved(self.edge_indices[i])
654
+ return self.mpl.patches.FancyArrowPatch(
655
+ (x1, y1),
656
+ (x2, y2),
657
+ arrowstyle=self.arrowstyle,
658
+ shrinkA=shrink_source,
659
+ shrinkB=shrink_target,
660
+ mutation_scale=mutation_scale,
661
+ color=arrow_color,
662
+ linewidth=linewidth,
663
+ connectionstyle=connectionstyle,
664
+ linestyle=linestyle,
665
+ zorder=1, # arrows go behind nodes
666
+ )
667
+
668
+ def to_marker_edge(self, marker_size, marker):
669
+ if marker in "s^>v<d": # `large` markers need extra space
670
+ return self.np.sqrt(2 * marker_size) / 2
671
+ else:
672
+ return self.np.sqrt(marker_size) / 2
673
+
674
+
675
+ def draw_networkx_edges(
676
+ G,
677
+ pos,
678
+ edgelist=None,
679
+ width=1.0,
680
+ edge_color="k",
681
+ style="solid",
682
+ alpha=None,
683
+ arrowstyle=None,
684
+ arrowsize=10,
685
+ edge_cmap=None,
686
+ edge_vmin=None,
687
+ edge_vmax=None,
688
+ ax=None,
689
+ arrows=None,
690
+ label=None,
691
+ node_size=300,
692
+ nodelist=None,
693
+ node_shape="o",
694
+ connectionstyle="arc3",
695
+ min_source_margin=0,
696
+ min_target_margin=0,
697
+ hide_ticks=True,
698
+ ):
699
+ r"""Draw the edges of the graph G.
700
+
701
+ This draws only the edges of the graph G.
702
+
703
+ Parameters
704
+ ----------
705
+ G : graph
706
+ A networkx graph
707
+
708
+ pos : dictionary
709
+ A dictionary with nodes as keys and positions as values.
710
+ Positions should be sequences of length 2.
711
+
712
+ edgelist : collection of edge tuples (default=G.edges())
713
+ Draw only specified edges
714
+
715
+ width : float or array of floats (default=1.0)
716
+ Line width of edges
717
+
718
+ edge_color : color or array of colors (default='k')
719
+ Edge color. Can be a single color or a sequence of colors with the same
720
+ length as edgelist. Color can be string or rgb (or rgba) tuple of
721
+ floats from 0-1. If numeric values are specified they will be
722
+ mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
723
+
724
+ style : string or array of strings (default='solid')
725
+ Edge line style e.g.: '-', '--', '-.', ':'
726
+ or words like 'solid' or 'dashed'.
727
+ Can be a single style or a sequence of styles with the same
728
+ length as the edge list.
729
+ If less styles than edges are given the styles will cycle.
730
+ If more styles than edges are given the styles will be used sequentially
731
+ and not be exhausted.
732
+ Also, `(offset, onoffseq)` tuples can be used as style instead of a strings.
733
+ (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
734
+
735
+ alpha : float or array of floats (default=None)
736
+ The edge transparency. This can be a single alpha value,
737
+ in which case it will be applied to all specified edges. Otherwise,
738
+ if it is an array, the elements of alpha will be applied to the colors
739
+ in order (cycling through alpha multiple times if necessary).
740
+
741
+ edge_cmap : Matplotlib colormap, optional
742
+ Colormap for mapping intensities of edges
743
+
744
+ edge_vmin,edge_vmax : floats, optional
745
+ Minimum and maximum for edge colormap scaling
746
+
747
+ ax : Matplotlib Axes object, optional
748
+ Draw the graph in the specified Matplotlib axes.
749
+
750
+ arrows : bool or None, optional (default=None)
751
+ If `None`, directed graphs draw arrowheads with
752
+ `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
753
+ via `~matplotlib.collections.LineCollection` for speed.
754
+ If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
755
+ If `False`, draw edges using LineCollection (linear and fast).
756
+
757
+ Note: Arrowheads will be the same color as edges.
758
+
759
+ arrowstyle : str (default='-\|>' for directed graphs)
760
+ For directed graphs and `arrows==True` defaults to '-\|>',
761
+ For undirected graphs default to '-'.
762
+
763
+ See `matplotlib.patches.ArrowStyle` for more options.
764
+
765
+ arrowsize : int (default=10)
766
+ For directed graphs, choose the size of the arrow head's length and
767
+ width. See `matplotlib.patches.FancyArrowPatch` for attribute
768
+ `mutation_scale` for more info.
769
+
770
+ connectionstyle : string or iterable of strings (default="arc3")
771
+ Pass the connectionstyle parameter to create curved arc of rounding
772
+ radius rad. For example, connectionstyle='arc3,rad=0.2'.
773
+ See `matplotlib.patches.ConnectionStyle` and
774
+ `matplotlib.patches.FancyArrowPatch` for more info.
775
+ If Iterable, index indicates i'th edge key of MultiGraph
776
+
777
+ node_size : scalar or array (default=300)
778
+ Size of nodes. Though the nodes are not drawn with this function, the
779
+ node size is used in determining edge positioning.
780
+
781
+ nodelist : list, optional (default=G.nodes())
782
+ This provides the node order for the `node_size` array (if it is an array).
783
+
784
+ node_shape : string (default='o')
785
+ The marker used for nodes, used in determining edge positioning.
786
+ Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v<dph8'.
787
+
788
+ label : None or string
789
+ Label for legend
790
+
791
+ min_source_margin : int (default=0)
792
+ The minimum margin (gap) at the beginning of the edge at the source.
793
+
794
+ min_target_margin : int (default=0)
795
+ The minimum margin (gap) at the end of the edge at the target.
796
+
797
+ hide_ticks : bool, optional
798
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
799
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
800
+ use ``hide_ticks=False``.
801
+
802
+ Returns
803
+ -------
804
+ matplotlib.collections.LineCollection or a list of matplotlib.patches.FancyArrowPatch
805
+ If ``arrows=True``, a list of FancyArrowPatches is returned.
806
+ If ``arrows=False``, a LineCollection is returned.
807
+ If ``arrows=None`` (the default), then a LineCollection is returned if
808
+ `G` is undirected, otherwise returns a list of FancyArrowPatches.
809
+
810
+ Notes
811
+ -----
812
+ For directed graphs, arrows are drawn at the head end. Arrows can be
813
+ turned off with keyword arrows=False or by passing an arrowstyle without
814
+ an arrow on the end.
815
+
816
+ Be sure to include `node_size` as a keyword argument; arrows are
817
+ drawn considering the size of nodes.
818
+
819
+ Self-loops are always drawn with `~matplotlib.patches.FancyArrowPatch`
820
+ regardless of the value of `arrows` or whether `G` is directed.
821
+ When ``arrows=False`` or ``arrows=None`` and `G` is undirected, the
822
+ FancyArrowPatches corresponding to the self-loops are not explicitly
823
+ returned. They should instead be accessed via the ``Axes.patches``
824
+ attribute (see examples).
825
+
826
+ Examples
827
+ --------
828
+ >>> G = nx.dodecahedral_graph()
829
+ >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
830
+
831
+ >>> G = nx.DiGraph()
832
+ >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
833
+ >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
834
+ >>> alphas = [0.3, 0.4, 0.5]
835
+ >>> for i, arc in enumerate(arcs): # change alpha values of arcs
836
+ ... arc.set_alpha(alphas[i])
837
+
838
+ The FancyArrowPatches corresponding to self-loops are not always
839
+ returned, but can always be accessed via the ``patches`` attribute of the
840
+ `matplotlib.Axes` object.
841
+
842
+ >>> import matplotlib.pyplot as plt
843
+ >>> fig, ax = plt.subplots()
844
+ >>> G = nx.Graph([(0, 1), (0, 0)]) # Self-loop at node 0
845
+ >>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
846
+ >>> self_loop_fap = ax.patches[0]
847
+
848
+ Also see the NetworkX drawing examples at
849
+ https://networkx.org/documentation/latest/auto_examples/index.html
850
+
851
+ See Also
852
+ --------
853
+ draw
854
+ draw_networkx
855
+ draw_networkx_nodes
856
+ draw_networkx_labels
857
+ draw_networkx_edge_labels
858
+
859
+ """
860
+ import warnings
861
+
862
+ import matplotlib as mpl
863
+ import matplotlib.collections # call as mpl.collections
864
+ import matplotlib.colors # call as mpl.colors
865
+ import matplotlib.pyplot as plt
866
+ import numpy as np
867
+
868
+ # The default behavior is to use LineCollection to draw edges for
869
+ # undirected graphs (for performance reasons) and use FancyArrowPatches
870
+ # for directed graphs.
871
+ # The `arrows` keyword can be used to override the default behavior
872
+ if arrows is None:
873
+ use_linecollection = not (G.is_directed() or G.is_multigraph())
874
+ else:
875
+ if not isinstance(arrows, bool):
876
+ raise TypeError("Argument `arrows` must be of type bool or None")
877
+ use_linecollection = not arrows
878
+
879
+ if isinstance(connectionstyle, str):
880
+ connectionstyle = [connectionstyle]
881
+ elif np.iterable(connectionstyle):
882
+ connectionstyle = list(connectionstyle)
883
+ else:
884
+ msg = "draw_networkx_edges arg `connectionstyle` must be str or iterable"
885
+ raise nx.NetworkXError(msg)
886
+
887
+ # Some kwargs only apply to FancyArrowPatches. Warn users when they use
888
+ # non-default values for these kwargs when LineCollection is being used
889
+ # instead of silently ignoring the specified option
890
+ if use_linecollection:
891
+ msg = (
892
+ "\n\nThe {0} keyword argument is not applicable when drawing edges\n"
893
+ "with LineCollection.\n\n"
894
+ "To make this warning go away, either specify `arrows=True` to\n"
895
+ "force FancyArrowPatches or use the default values.\n"
896
+ "Note that using FancyArrowPatches may be slow for large graphs.\n"
897
+ )
898
+ if arrowstyle is not None:
899
+ warnings.warn(msg.format("arrowstyle"), category=UserWarning, stacklevel=2)
900
+ if arrowsize != 10:
901
+ warnings.warn(msg.format("arrowsize"), category=UserWarning, stacklevel=2)
902
+ if min_source_margin != 0:
903
+ warnings.warn(
904
+ msg.format("min_source_margin"), category=UserWarning, stacklevel=2
905
+ )
906
+ if min_target_margin != 0:
907
+ warnings.warn(
908
+ msg.format("min_target_margin"), category=UserWarning, stacklevel=2
909
+ )
910
+ if any(cs != "arc3" for cs in connectionstyle):
911
+ warnings.warn(
912
+ msg.format("connectionstyle"), category=UserWarning, stacklevel=2
913
+ )
914
+
915
+ # NOTE: Arrowstyle modification must occur after the warnings section
916
+ if arrowstyle is None:
917
+ arrowstyle = "-|>" if G.is_directed() else "-"
918
+
919
+ if ax is None:
920
+ ax = plt.gca()
921
+
922
+ if edgelist is None:
923
+ edgelist = list(G.edges) # (u, v, k) for multigraph (u, v) otherwise
924
+
925
+ if len(edgelist):
926
+ if G.is_multigraph():
927
+ key_count = collections.defaultdict(lambda: itertools.count(0))
928
+ edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
929
+ else:
930
+ edge_indices = [0] * len(edgelist)
931
+ else: # no edges!
932
+ return []
933
+
934
+ if nodelist is None:
935
+ nodelist = list(G.nodes())
936
+
937
+ # FancyArrowPatch handles color=None different from LineCollection
938
+ if edge_color is None:
939
+ edge_color = "k"
940
+
941
+ # set edge positions
942
+ edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
943
+
944
+ # Check if edge_color is an array of floats and map to edge_cmap.
945
+ # This is the only case handled differently from matplotlib
946
+ if (
947
+ np.iterable(edge_color)
948
+ and (len(edge_color) == len(edge_pos))
949
+ and np.all([isinstance(c, Number) for c in edge_color])
950
+ ):
951
+ if edge_cmap is not None:
952
+ assert isinstance(edge_cmap, mpl.colors.Colormap)
953
+ else:
954
+ edge_cmap = plt.get_cmap()
955
+ if edge_vmin is None:
956
+ edge_vmin = min(edge_color)
957
+ if edge_vmax is None:
958
+ edge_vmax = max(edge_color)
959
+ color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax)
960
+ edge_color = [edge_cmap(color_normal(e)) for e in edge_color]
961
+
962
+ # compute initial view
963
+ minx = np.amin(np.ravel(edge_pos[:, :, 0]))
964
+ maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
965
+ miny = np.amin(np.ravel(edge_pos[:, :, 1]))
966
+ maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
967
+ w = maxx - minx
968
+ h = maxy - miny
969
+
970
+ # Self-loops are scaled by view extent, except in cases the extent
971
+ # is 0, e.g. for a single node. In this case, fall back to scaling
972
+ # by the maximum node size
973
+ selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
974
+ fancy_arrow_factory = FancyArrowFactory(
975
+ edge_pos,
976
+ edgelist,
977
+ nodelist,
978
+ edge_indices,
979
+ node_size,
980
+ selfloop_height,
981
+ connectionstyle,
982
+ node_shape,
983
+ arrowstyle,
984
+ arrowsize,
985
+ edge_color,
986
+ alpha,
987
+ width,
988
+ style,
989
+ min_source_margin,
990
+ min_target_margin,
991
+ ax=ax,
992
+ )
993
+
994
+ # Draw the edges
995
+ if use_linecollection:
996
+ edge_collection = mpl.collections.LineCollection(
997
+ edge_pos,
998
+ colors=edge_color,
999
+ linewidths=width,
1000
+ antialiaseds=(1,),
1001
+ linestyle=style,
1002
+ alpha=alpha,
1003
+ )
1004
+ edge_collection.set_cmap(edge_cmap)
1005
+ edge_collection.set_clim(edge_vmin, edge_vmax)
1006
+ edge_collection.set_zorder(1) # edges go behind nodes
1007
+ edge_collection.set_label(label)
1008
+ ax.add_collection(edge_collection)
1009
+ edge_viz_obj = edge_collection
1010
+
1011
+ # Make sure selfloop edges are also drawn
1012
+ # ---------------------------------------
1013
+ selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
1014
+ if selfloops_to_draw:
1015
+ edgelist_tuple = list(map(tuple, edgelist))
1016
+ arrow_collection = []
1017
+ for loop in selfloops_to_draw:
1018
+ i = edgelist_tuple.index(loop)
1019
+ arrow = fancy_arrow_factory(i)
1020
+ arrow_collection.append(arrow)
1021
+ ax.add_patch(arrow)
1022
+ else:
1023
+ edge_viz_obj = []
1024
+ for i in range(len(edgelist)):
1025
+ arrow = fancy_arrow_factory(i)
1026
+ ax.add_patch(arrow)
1027
+ edge_viz_obj.append(arrow)
1028
+
1029
+ # update view after drawing
1030
+ padx, pady = 0.05 * w, 0.05 * h
1031
+ corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
1032
+ ax.update_datalim(corners)
1033
+ ax.autoscale_view()
1034
+
1035
+ if hide_ticks:
1036
+ ax.tick_params(
1037
+ axis="both",
1038
+ which="both",
1039
+ bottom=False,
1040
+ left=False,
1041
+ labelbottom=False,
1042
+ labelleft=False,
1043
+ )
1044
+
1045
+ return edge_viz_obj
1046
+
1047
+
1048
+ def draw_networkx_labels(
1049
+ G,
1050
+ pos,
1051
+ labels=None,
1052
+ font_size=12,
1053
+ font_color="k",
1054
+ font_family="sans-serif",
1055
+ font_weight="normal",
1056
+ alpha=None,
1057
+ bbox=None,
1058
+ horizontalalignment="center",
1059
+ verticalalignment="center",
1060
+ ax=None,
1061
+ clip_on=True,
1062
+ hide_ticks=True,
1063
+ ):
1064
+ """Draw node labels on the graph G.
1065
+
1066
+ Parameters
1067
+ ----------
1068
+ G : graph
1069
+ A networkx graph
1070
+
1071
+ pos : dictionary
1072
+ A dictionary with nodes as keys and positions as values.
1073
+ Positions should be sequences of length 2.
1074
+
1075
+ labels : dictionary (default={n: n for n in G})
1076
+ Node labels in a dictionary of text labels keyed by node.
1077
+ Node-keys in labels should appear as keys in `pos`.
1078
+ If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
1079
+
1080
+ font_size : int (default=12)
1081
+ Font size for text labels
1082
+
1083
+ font_color : color (default='k' black)
1084
+ Font color string. Color can be string or rgb (or rgba) tuple of
1085
+ floats from 0-1.
1086
+
1087
+ font_weight : string (default='normal')
1088
+ Font weight
1089
+
1090
+ font_family : string (default='sans-serif')
1091
+ Font family
1092
+
1093
+ alpha : float or None (default=None)
1094
+ The text transparency
1095
+
1096
+ bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
1097
+ Specify text box properties (e.g. shape, color etc.) for node labels.
1098
+
1099
+ horizontalalignment : string (default='center')
1100
+ Horizontal alignment {'center', 'right', 'left'}
1101
+
1102
+ verticalalignment : string (default='center')
1103
+ Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
1104
+
1105
+ ax : Matplotlib Axes object, optional
1106
+ Draw the graph in the specified Matplotlib axes.
1107
+
1108
+ clip_on : bool (default=True)
1109
+ Turn on clipping of node labels at axis boundaries
1110
+
1111
+ hide_ticks : bool, optional
1112
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
1113
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
1114
+ use ``hide_ticks=False``.
1115
+
1116
+ Returns
1117
+ -------
1118
+ dict
1119
+ `dict` of labels keyed on the nodes
1120
+
1121
+ Examples
1122
+ --------
1123
+ >>> G = nx.dodecahedral_graph()
1124
+ >>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
1125
+
1126
+ Also see the NetworkX drawing examples at
1127
+ https://networkx.org/documentation/latest/auto_examples/index.html
1128
+
1129
+ See Also
1130
+ --------
1131
+ draw
1132
+ draw_networkx
1133
+ draw_networkx_nodes
1134
+ draw_networkx_edges
1135
+ draw_networkx_edge_labels
1136
+ """
1137
+ import matplotlib.pyplot as plt
1138
+
1139
+ if ax is None:
1140
+ ax = plt.gca()
1141
+
1142
+ if labels is None:
1143
+ labels = {n: n for n in G.nodes()}
1144
+
1145
+ text_items = {} # there is no text collection so we'll fake one
1146
+ for n, label in labels.items():
1147
+ (x, y) = pos[n]
1148
+ if not isinstance(label, str):
1149
+ label = str(label) # this makes "1" and 1 labeled the same
1150
+ t = ax.text(
1151
+ x,
1152
+ y,
1153
+ label,
1154
+ size=font_size,
1155
+ color=font_color,
1156
+ family=font_family,
1157
+ weight=font_weight,
1158
+ alpha=alpha,
1159
+ horizontalalignment=horizontalalignment,
1160
+ verticalalignment=verticalalignment,
1161
+ transform=ax.transData,
1162
+ bbox=bbox,
1163
+ clip_on=clip_on,
1164
+ )
1165
+ text_items[n] = t
1166
+
1167
+ if hide_ticks:
1168
+ ax.tick_params(
1169
+ axis="both",
1170
+ which="both",
1171
+ bottom=False,
1172
+ left=False,
1173
+ labelbottom=False,
1174
+ labelleft=False,
1175
+ )
1176
+
1177
+ return text_items
1178
+
1179
+
1180
+ def draw_networkx_edge_labels(
1181
+ G,
1182
+ pos,
1183
+ edge_labels=None,
1184
+ label_pos=0.5,
1185
+ font_size=10,
1186
+ font_color="k",
1187
+ font_family="sans-serif",
1188
+ font_weight="normal",
1189
+ alpha=None,
1190
+ bbox=None,
1191
+ horizontalalignment="center",
1192
+ verticalalignment="center",
1193
+ ax=None,
1194
+ rotate=True,
1195
+ clip_on=True,
1196
+ node_size=300,
1197
+ nodelist=None,
1198
+ connectionstyle="arc3",
1199
+ hide_ticks=True,
1200
+ ):
1201
+ """Draw edge labels.
1202
+
1203
+ Parameters
1204
+ ----------
1205
+ G : graph
1206
+ A networkx graph
1207
+
1208
+ pos : dictionary
1209
+ A dictionary with nodes as keys and positions as values.
1210
+ Positions should be sequences of length 2.
1211
+
1212
+ edge_labels : dictionary (default=None)
1213
+ Edge labels in a dictionary of labels keyed by edge two-tuple.
1214
+ Only labels for the keys in the dictionary are drawn.
1215
+
1216
+ label_pos : float (default=0.5)
1217
+ Position of edge label along edge (0=head, 0.5=center, 1=tail)
1218
+
1219
+ font_size : int (default=10)
1220
+ Font size for text labels
1221
+
1222
+ font_color : color (default='k' black)
1223
+ Font color string. Color can be string or rgb (or rgba) tuple of
1224
+ floats from 0-1.
1225
+
1226
+ font_weight : string (default='normal')
1227
+ Font weight
1228
+
1229
+ font_family : string (default='sans-serif')
1230
+ Font family
1231
+
1232
+ alpha : float or None (default=None)
1233
+ The text transparency
1234
+
1235
+ bbox : Matplotlib bbox, optional
1236
+ Specify text box properties (e.g. shape, color etc.) for edge labels.
1237
+ Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
1238
+
1239
+ horizontalalignment : string (default='center')
1240
+ Horizontal alignment {'center', 'right', 'left'}
1241
+
1242
+ verticalalignment : string (default='center')
1243
+ Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
1244
+
1245
+ ax : Matplotlib Axes object, optional
1246
+ Draw the graph in the specified Matplotlib axes.
1247
+
1248
+ rotate : bool (default=True)
1249
+ Rotate edge labels to lie parallel to edges
1250
+
1251
+ clip_on : bool (default=True)
1252
+ Turn on clipping of edge labels at axis boundaries
1253
+
1254
+ node_size : scalar or array (default=300)
1255
+ Size of nodes. If an array it must be the same length as nodelist.
1256
+
1257
+ nodelist : list, optional (default=G.nodes())
1258
+ This provides the node order for the `node_size` array (if it is an array).
1259
+
1260
+ connectionstyle : string or iterable of strings (default="arc3")
1261
+ Pass the connectionstyle parameter to create curved arc of rounding
1262
+ radius rad. For example, connectionstyle='arc3,rad=0.2'.
1263
+ See `matplotlib.patches.ConnectionStyle` and
1264
+ `matplotlib.patches.FancyArrowPatch` for more info.
1265
+ If Iterable, index indicates i'th edge key of MultiGraph
1266
+
1267
+ hide_ticks : bool, optional
1268
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
1269
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
1270
+ use ``hide_ticks=False``.
1271
+
1272
+ Returns
1273
+ -------
1274
+ dict
1275
+ `dict` of labels keyed by edge
1276
+
1277
+ Examples
1278
+ --------
1279
+ >>> G = nx.dodecahedral_graph()
1280
+ >>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
1281
+
1282
+ Also see the NetworkX drawing examples at
1283
+ https://networkx.org/documentation/latest/auto_examples/index.html
1284
+
1285
+ See Also
1286
+ --------
1287
+ draw
1288
+ draw_networkx
1289
+ draw_networkx_nodes
1290
+ draw_networkx_edges
1291
+ draw_networkx_labels
1292
+ """
1293
+ import matplotlib as mpl
1294
+ import matplotlib.pyplot as plt
1295
+ import numpy as np
1296
+
1297
+ class CurvedArrowText(mpl.text.Text):
1298
+ def __init__(
1299
+ self,
1300
+ arrow,
1301
+ *args,
1302
+ label_pos=0.5,
1303
+ labels_horizontal=False,
1304
+ ax=None,
1305
+ **kwargs,
1306
+ ):
1307
+ # Bind to FancyArrowPatch
1308
+ self.arrow = arrow
1309
+ # how far along the text should be on the curve,
1310
+ # 0 is at start, 1 is at end etc.
1311
+ self.label_pos = label_pos
1312
+ self.labels_horizontal = labels_horizontal
1313
+ if ax is None:
1314
+ ax = plt.gca()
1315
+ self.ax = ax
1316
+ self.x, self.y, self.angle = self._update_text_pos_angle(arrow)
1317
+
1318
+ # Create text object
1319
+ super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
1320
+ # Bind to axis
1321
+ self.ax.add_artist(self)
1322
+
1323
+ def _get_arrow_path_disp(self, arrow):
1324
+ """
1325
+ This is part of FancyArrowPatch._get_path_in_displaycoord
1326
+ It omits the second part of the method where path is converted
1327
+ to polygon based on width
1328
+ The transform is taken from ax, not the object, as the object
1329
+ has not been added yet, and doesn't have transform
1330
+ """
1331
+ dpi_cor = arrow._dpi_cor
1332
+ # trans_data = arrow.get_transform()
1333
+ trans_data = self.ax.transData
1334
+ if arrow._posA_posB is not None:
1335
+ posA = arrow._convert_xy_units(arrow._posA_posB[0])
1336
+ posB = arrow._convert_xy_units(arrow._posA_posB[1])
1337
+ (posA, posB) = trans_data.transform((posA, posB))
1338
+ _path = arrow.get_connectionstyle()(
1339
+ posA,
1340
+ posB,
1341
+ patchA=arrow.patchA,
1342
+ patchB=arrow.patchB,
1343
+ shrinkA=arrow.shrinkA * dpi_cor,
1344
+ shrinkB=arrow.shrinkB * dpi_cor,
1345
+ )
1346
+ else:
1347
+ _path = trans_data.transform_path(arrow._path_original)
1348
+ # Return is in display coordinates
1349
+ return _path
1350
+
1351
+ def _update_text_pos_angle(self, arrow):
1352
+ # Fractional label position
1353
+ path_disp = self._get_arrow_path_disp(arrow)
1354
+ (x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
1355
+ # Text position at a proportion t along the line in display coords
1356
+ # default is 0.5 so text appears at the halfway point
1357
+ t = self.label_pos
1358
+ tt = 1 - t
1359
+ x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
1360
+ y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
1361
+ if self.labels_horizontal:
1362
+ # Horizontal text labels
1363
+ angle = 0
1364
+ else:
1365
+ # Labels parallel to curve
1366
+ change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
1367
+ change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
1368
+ angle = (np.arctan2(change_y, change_x) / (2 * np.pi)) * 360
1369
+ # Text is "right way up"
1370
+ if angle > 90:
1371
+ angle -= 180
1372
+ if angle < -90:
1373
+ angle += 180
1374
+ (x, y) = self.ax.transData.inverted().transform((x, y))
1375
+ return x, y, angle
1376
+
1377
+ def draw(self, renderer):
1378
+ # recalculate the text position and angle
1379
+ self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
1380
+ self.set_position((self.x, self.y))
1381
+ self.set_rotation(self.angle)
1382
+ # redraw text
1383
+ super().draw(renderer)
1384
+
1385
+ # use default box of white with white border
1386
+ if bbox is None:
1387
+ bbox = {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
1388
+
1389
+ if isinstance(connectionstyle, str):
1390
+ connectionstyle = [connectionstyle]
1391
+ elif np.iterable(connectionstyle):
1392
+ connectionstyle = list(connectionstyle)
1393
+ else:
1394
+ raise nx.NetworkXError(
1395
+ "draw_networkx_edges arg `connectionstyle` must be"
1396
+ "string or iterable of strings"
1397
+ )
1398
+
1399
+ if ax is None:
1400
+ ax = plt.gca()
1401
+
1402
+ if edge_labels is None:
1403
+ kwds = {"keys": True} if G.is_multigraph() else {}
1404
+ edge_labels = {tuple(edge): d for *edge, d in G.edges(data=True, **kwds)}
1405
+ # NOTHING TO PLOT
1406
+ if not edge_labels:
1407
+ return {}
1408
+ edgelist, labels = zip(*edge_labels.items())
1409
+
1410
+ if nodelist is None:
1411
+ nodelist = list(G.nodes())
1412
+
1413
+ # set edge positions
1414
+ edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
1415
+
1416
+ if G.is_multigraph():
1417
+ key_count = collections.defaultdict(lambda: itertools.count(0))
1418
+ edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
1419
+ else:
1420
+ edge_indices = [0] * len(edgelist)
1421
+
1422
+ # Used to determine self loop mid-point
1423
+ # Note, that this will not be accurate,
1424
+ # if not drawing edge_labels for all edges drawn
1425
+ h = 0
1426
+ if edge_labels:
1427
+ miny = np.amin(np.ravel(edge_pos[:, :, 1]))
1428
+ maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
1429
+ h = maxy - miny
1430
+ selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
1431
+ fancy_arrow_factory = FancyArrowFactory(
1432
+ edge_pos,
1433
+ edgelist,
1434
+ nodelist,
1435
+ edge_indices,
1436
+ node_size,
1437
+ selfloop_height,
1438
+ connectionstyle,
1439
+ ax=ax,
1440
+ )
1441
+
1442
+ text_items = {}
1443
+ for i, (edge, label) in enumerate(zip(edgelist, labels)):
1444
+ if not isinstance(label, str):
1445
+ label = str(label) # this makes "1" and 1 labeled the same
1446
+
1447
+ n1, n2 = edge[:2]
1448
+ arrow = fancy_arrow_factory(i)
1449
+ if n1 == n2:
1450
+ connectionstyle_obj = arrow.get_connectionstyle()
1451
+ posA = ax.transData.transform(pos[n1])
1452
+ path_disp = connectionstyle_obj(posA, posA)
1453
+ path_data = ax.transData.inverted().transform_path(path_disp)
1454
+ x, y = path_data.vertices[0]
1455
+ text_items[edge] = ax.text(
1456
+ x,
1457
+ y,
1458
+ label,
1459
+ size=font_size,
1460
+ color=font_color,
1461
+ family=font_family,
1462
+ weight=font_weight,
1463
+ alpha=alpha,
1464
+ horizontalalignment=horizontalalignment,
1465
+ verticalalignment=verticalalignment,
1466
+ rotation=0,
1467
+ transform=ax.transData,
1468
+ bbox=bbox,
1469
+ zorder=1,
1470
+ clip_on=clip_on,
1471
+ )
1472
+ else:
1473
+ text_items[edge] = CurvedArrowText(
1474
+ arrow,
1475
+ label,
1476
+ size=font_size,
1477
+ color=font_color,
1478
+ family=font_family,
1479
+ weight=font_weight,
1480
+ alpha=alpha,
1481
+ horizontalalignment=horizontalalignment,
1482
+ verticalalignment=verticalalignment,
1483
+ transform=ax.transData,
1484
+ bbox=bbox,
1485
+ zorder=1,
1486
+ clip_on=clip_on,
1487
+ label_pos=label_pos,
1488
+ labels_horizontal=not rotate,
1489
+ ax=ax,
1490
+ )
1491
+
1492
+ if hide_ticks:
1493
+ ax.tick_params(
1494
+ axis="both",
1495
+ which="both",
1496
+ bottom=False,
1497
+ left=False,
1498
+ labelbottom=False,
1499
+ labelleft=False,
1500
+ )
1501
+
1502
+ return text_items
1503
+
1504
+
1505
+ def draw_circular(G, **kwargs):
1506
+ """Draw the graph `G` with a circular layout.
1507
+
1508
+ This is a convenience function equivalent to::
1509
+
1510
+ nx.draw(G, pos=nx.circular_layout(G), **kwargs)
1511
+
1512
+ Parameters
1513
+ ----------
1514
+ G : graph
1515
+ A networkx graph
1516
+
1517
+ kwargs : optional keywords
1518
+ See `draw_networkx` for a description of optional keywords.
1519
+
1520
+ Notes
1521
+ -----
1522
+ The layout is computed each time this function is called. For
1523
+ repeated drawing it is much more efficient to call
1524
+ `~networkx.drawing.layout.circular_layout` directly and reuse the result::
1525
+
1526
+ >>> G = nx.complete_graph(5)
1527
+ >>> pos = nx.circular_layout(G)
1528
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1529
+ >>> # Draw a subgraph, reusing the same node positions
1530
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1531
+
1532
+ Examples
1533
+ --------
1534
+ >>> G = nx.path_graph(5)
1535
+ >>> nx.draw_circular(G)
1536
+
1537
+ See Also
1538
+ --------
1539
+ :func:`~networkx.drawing.layout.circular_layout`
1540
+ """
1541
+ draw(G, circular_layout(G), **kwargs)
1542
+
1543
+
1544
+ def draw_kamada_kawai(G, **kwargs):
1545
+ """Draw the graph `G` with a Kamada-Kawai force-directed layout.
1546
+
1547
+ This is a convenience function equivalent to::
1548
+
1549
+ nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
1550
+
1551
+ Parameters
1552
+ ----------
1553
+ G : graph
1554
+ A networkx graph
1555
+
1556
+ kwargs : optional keywords
1557
+ See `draw_networkx` for a description of optional keywords.
1558
+
1559
+ Notes
1560
+ -----
1561
+ The layout is computed each time this function is called.
1562
+ For repeated drawing it is much more efficient to call
1563
+ `~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
1564
+ result::
1565
+
1566
+ >>> G = nx.complete_graph(5)
1567
+ >>> pos = nx.kamada_kawai_layout(G)
1568
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1569
+ >>> # Draw a subgraph, reusing the same node positions
1570
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1571
+
1572
+ Examples
1573
+ --------
1574
+ >>> G = nx.path_graph(5)
1575
+ >>> nx.draw_kamada_kawai(G)
1576
+
1577
+ See Also
1578
+ --------
1579
+ :func:`~networkx.drawing.layout.kamada_kawai_layout`
1580
+ """
1581
+ draw(G, kamada_kawai_layout(G), **kwargs)
1582
+
1583
+
1584
+ def draw_random(G, **kwargs):
1585
+ """Draw the graph `G` with a random layout.
1586
+
1587
+ This is a convenience function equivalent to::
1588
+
1589
+ nx.draw(G, pos=nx.random_layout(G), **kwargs)
1590
+
1591
+ Parameters
1592
+ ----------
1593
+ G : graph
1594
+ A networkx graph
1595
+
1596
+ kwargs : optional keywords
1597
+ See `draw_networkx` for a description of optional keywords.
1598
+
1599
+ Notes
1600
+ -----
1601
+ The layout is computed each time this function is called.
1602
+ For repeated drawing it is much more efficient to call
1603
+ `~networkx.drawing.layout.random_layout` directly and reuse the result::
1604
+
1605
+ >>> G = nx.complete_graph(5)
1606
+ >>> pos = nx.random_layout(G)
1607
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1608
+ >>> # Draw a subgraph, reusing the same node positions
1609
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1610
+
1611
+ Examples
1612
+ --------
1613
+ >>> G = nx.lollipop_graph(4, 3)
1614
+ >>> nx.draw_random(G)
1615
+
1616
+ See Also
1617
+ --------
1618
+ :func:`~networkx.drawing.layout.random_layout`
1619
+ """
1620
+ draw(G, random_layout(G), **kwargs)
1621
+
1622
+
1623
+ def draw_spectral(G, **kwargs):
1624
+ """Draw the graph `G` with a spectral 2D layout.
1625
+
1626
+ This is a convenience function equivalent to::
1627
+
1628
+ nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
1629
+
1630
+ For more information about how node positions are determined, see
1631
+ `~networkx.drawing.layout.spectral_layout`.
1632
+
1633
+ Parameters
1634
+ ----------
1635
+ G : graph
1636
+ A networkx graph
1637
+
1638
+ kwargs : optional keywords
1639
+ See `draw_networkx` for a description of optional keywords.
1640
+
1641
+ Notes
1642
+ -----
1643
+ The layout is computed each time this function is called.
1644
+ For repeated drawing it is much more efficient to call
1645
+ `~networkx.drawing.layout.spectral_layout` directly and reuse the result::
1646
+
1647
+ >>> G = nx.complete_graph(5)
1648
+ >>> pos = nx.spectral_layout(G)
1649
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1650
+ >>> # Draw a subgraph, reusing the same node positions
1651
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1652
+
1653
+ Examples
1654
+ --------
1655
+ >>> G = nx.path_graph(5)
1656
+ >>> nx.draw_spectral(G)
1657
+
1658
+ See Also
1659
+ --------
1660
+ :func:`~networkx.drawing.layout.spectral_layout`
1661
+ """
1662
+ draw(G, spectral_layout(G), **kwargs)
1663
+
1664
+
1665
+ def draw_spring(G, **kwargs):
1666
+ """Draw the graph `G` with a spring layout.
1667
+
1668
+ This is a convenience function equivalent to::
1669
+
1670
+ nx.draw(G, pos=nx.spring_layout(G), **kwargs)
1671
+
1672
+ Parameters
1673
+ ----------
1674
+ G : graph
1675
+ A networkx graph
1676
+
1677
+ kwargs : optional keywords
1678
+ See `draw_networkx` for a description of optional keywords.
1679
+
1680
+ Notes
1681
+ -----
1682
+ `~networkx.drawing.layout.spring_layout` is also the default layout for
1683
+ `draw`, so this function is equivalent to `draw`.
1684
+
1685
+ The layout is computed each time this function is called.
1686
+ For repeated drawing it is much more efficient to call
1687
+ `~networkx.drawing.layout.spring_layout` directly and reuse the result::
1688
+
1689
+ >>> G = nx.complete_graph(5)
1690
+ >>> pos = nx.spring_layout(G)
1691
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1692
+ >>> # Draw a subgraph, reusing the same node positions
1693
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1694
+
1695
+ Examples
1696
+ --------
1697
+ >>> G = nx.path_graph(20)
1698
+ >>> nx.draw_spring(G)
1699
+
1700
+ See Also
1701
+ --------
1702
+ draw
1703
+ :func:`~networkx.drawing.layout.spring_layout`
1704
+ """
1705
+ draw(G, spring_layout(G), **kwargs)
1706
+
1707
+
1708
+ def draw_shell(G, nlist=None, **kwargs):
1709
+ """Draw networkx graph `G` with shell layout.
1710
+
1711
+ This is a convenience function equivalent to::
1712
+
1713
+ nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
1714
+
1715
+ Parameters
1716
+ ----------
1717
+ G : graph
1718
+ A networkx graph
1719
+
1720
+ nlist : list of list of nodes, optional
1721
+ A list containing lists of nodes representing the shells.
1722
+ Default is `None`, meaning all nodes are in a single shell.
1723
+ See `~networkx.drawing.layout.shell_layout` for details.
1724
+
1725
+ kwargs : optional keywords
1726
+ See `draw_networkx` for a description of optional keywords.
1727
+
1728
+ Notes
1729
+ -----
1730
+ The layout is computed each time this function is called.
1731
+ For repeated drawing it is much more efficient to call
1732
+ `~networkx.drawing.layout.shell_layout` directly and reuse the result::
1733
+
1734
+ >>> G = nx.complete_graph(5)
1735
+ >>> pos = nx.shell_layout(G)
1736
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1737
+ >>> # Draw a subgraph, reusing the same node positions
1738
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1739
+
1740
+ Examples
1741
+ --------
1742
+ >>> G = nx.path_graph(4)
1743
+ >>> shells = [[0], [1, 2, 3]]
1744
+ >>> nx.draw_shell(G, nlist=shells)
1745
+
1746
+ See Also
1747
+ --------
1748
+ :func:`~networkx.drawing.layout.shell_layout`
1749
+ """
1750
+ draw(G, shell_layout(G, nlist=nlist), **kwargs)
1751
+
1752
+
1753
+ def draw_planar(G, **kwargs):
1754
+ """Draw a planar networkx graph `G` with planar layout.
1755
+
1756
+ This is a convenience function equivalent to::
1757
+
1758
+ nx.draw(G, pos=nx.planar_layout(G), **kwargs)
1759
+
1760
+ Parameters
1761
+ ----------
1762
+ G : graph
1763
+ A planar networkx graph
1764
+
1765
+ kwargs : optional keywords
1766
+ See `draw_networkx` for a description of optional keywords.
1767
+
1768
+ Raises
1769
+ ------
1770
+ NetworkXException
1771
+ When `G` is not planar
1772
+
1773
+ Notes
1774
+ -----
1775
+ The layout is computed each time this function is called.
1776
+ For repeated drawing it is much more efficient to call
1777
+ `~networkx.drawing.layout.planar_layout` directly and reuse the result::
1778
+
1779
+ >>> G = nx.path_graph(5)
1780
+ >>> pos = nx.planar_layout(G)
1781
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1782
+ >>> # Draw a subgraph, reusing the same node positions
1783
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1784
+
1785
+ Examples
1786
+ --------
1787
+ >>> G = nx.path_graph(4)
1788
+ >>> nx.draw_planar(G)
1789
+
1790
+ See Also
1791
+ --------
1792
+ :func:`~networkx.drawing.layout.planar_layout`
1793
+ """
1794
+ draw(G, planar_layout(G), **kwargs)
1795
+
1796
+
1797
+ def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
1798
+ """Apply an alpha (or list of alphas) to the colors provided.
1799
+
1800
+ Parameters
1801
+ ----------
1802
+
1803
+ colors : color string or array of floats (default='r')
1804
+ Color of element. Can be a single color format string,
1805
+ or a sequence of colors with the same length as nodelist.
1806
+ If numeric values are specified they will be mapped to
1807
+ colors using the cmap and vmin,vmax parameters. See
1808
+ matplotlib.scatter for more details.
1809
+
1810
+ alpha : float or array of floats
1811
+ Alpha values for elements. This can be a single alpha value, in
1812
+ which case it will be applied to all the elements of color. Otherwise,
1813
+ if it is an array, the elements of alpha will be applied to the colors
1814
+ in order (cycling through alpha multiple times if necessary).
1815
+
1816
+ elem_list : array of networkx objects
1817
+ The list of elements which are being colored. These could be nodes,
1818
+ edges or labels.
1819
+
1820
+ cmap : matplotlib colormap
1821
+ Color map for use if colors is a list of floats corresponding to points
1822
+ on a color mapping.
1823
+
1824
+ vmin, vmax : float
1825
+ Minimum and maximum values for normalizing colors if a colormap is used
1826
+
1827
+ Returns
1828
+ -------
1829
+
1830
+ rgba_colors : numpy ndarray
1831
+ Array containing RGBA format values for each of the node colours.
1832
+
1833
+ """
1834
+ from itertools import cycle, islice
1835
+
1836
+ import matplotlib as mpl
1837
+ import matplotlib.cm # call as mpl.cm
1838
+ import matplotlib.colors # call as mpl.colors
1839
+ import numpy as np
1840
+
1841
+ # If we have been provided with a list of numbers as long as elem_list,
1842
+ # apply the color mapping.
1843
+ if len(colors) == len(elem_list) and isinstance(colors[0], Number):
1844
+ mapper = mpl.cm.ScalarMappable(cmap=cmap)
1845
+ mapper.set_clim(vmin, vmax)
1846
+ rgba_colors = mapper.to_rgba(colors)
1847
+ # Otherwise, convert colors to matplotlib's RGB using the colorConverter
1848
+ # object. These are converted to numpy ndarrays to be consistent with the
1849
+ # to_rgba method of ScalarMappable.
1850
+ else:
1851
+ try:
1852
+ rgba_colors = np.array([mpl.colors.colorConverter.to_rgba(colors)])
1853
+ except ValueError:
1854
+ rgba_colors = np.array(
1855
+ [mpl.colors.colorConverter.to_rgba(color) for color in colors]
1856
+ )
1857
+ # Set the final column of the rgba_colors to have the relevant alpha values
1858
+ try:
1859
+ # If alpha is longer than the number of colors, resize to the number of
1860
+ # elements. Also, if rgba_colors.size (the number of elements of
1861
+ # rgba_colors) is the same as the number of elements, resize the array,
1862
+ # to avoid it being interpreted as a colormap by scatter()
1863
+ if len(alpha) > len(rgba_colors) or rgba_colors.size == len(elem_list):
1864
+ rgba_colors = np.resize(rgba_colors, (len(elem_list), 4))
1865
+ rgba_colors[1:, 0] = rgba_colors[0, 0]
1866
+ rgba_colors[1:, 1] = rgba_colors[0, 1]
1867
+ rgba_colors[1:, 2] = rgba_colors[0, 2]
1868
+ rgba_colors[:, 3] = list(islice(cycle(alpha), len(rgba_colors)))
1869
+ except TypeError:
1870
+ rgba_colors[:, -1] = alpha
1871
+ return rgba_colors
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for PyGraphviz interface."""
2
+ import warnings
3
+
4
+ import pytest
5
+
6
+ pygraphviz = pytest.importorskip("pygraphviz")
7
+
8
+
9
+ import networkx as nx
10
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
11
+
12
+
13
+ class TestAGraph:
14
+ def build_graph(self, G):
15
+ edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")]
16
+ G.add_edges_from(edges)
17
+ G.add_node("E")
18
+ G.graph["metal"] = "bronze"
19
+ return G
20
+
21
+ def assert_equal(self, G1, G2):
22
+ assert nodes_equal(G1.nodes(), G2.nodes())
23
+ assert edges_equal(G1.edges(), G2.edges())
24
+ assert G1.graph["metal"] == G2.graph["metal"]
25
+
26
+ @pytest.mark.parametrize(
27
+ "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
28
+ )
29
+ def test_agraph_roundtripping(self, G, tmp_path):
30
+ G = self.build_graph(G)
31
+ A = nx.nx_agraph.to_agraph(G)
32
+ H = nx.nx_agraph.from_agraph(A)
33
+ self.assert_equal(G, H)
34
+
35
+ fname = tmp_path / "test.dot"
36
+ nx.drawing.nx_agraph.write_dot(H, fname)
37
+ Hin = nx.nx_agraph.read_dot(fname)
38
+ self.assert_equal(H, Hin)
39
+
40
+ fname = tmp_path / "fh_test.dot"
41
+ with open(fname, "w") as fh:
42
+ nx.drawing.nx_agraph.write_dot(H, fh)
43
+
44
+ with open(fname) as fh:
45
+ Hin = nx.nx_agraph.read_dot(fh)
46
+ self.assert_equal(H, Hin)
47
+
48
+ def test_from_agraph_name(self):
49
+ G = nx.Graph(name="test")
50
+ A = nx.nx_agraph.to_agraph(G)
51
+ H = nx.nx_agraph.from_agraph(A)
52
+ assert G.name == "test"
53
+
54
+ @pytest.mark.parametrize(
55
+ "graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
56
+ )
57
+ def test_from_agraph_create_using(self, graph_class):
58
+ G = nx.path_graph(3)
59
+ A = nx.nx_agraph.to_agraph(G)
60
+ H = nx.nx_agraph.from_agraph(A, create_using=graph_class)
61
+ assert isinstance(H, graph_class)
62
+
63
+ def test_from_agraph_named_edges(self):
64
+ # Create an AGraph from an existing (non-multi) Graph
65
+ G = nx.Graph()
66
+ G.add_nodes_from([0, 1])
67
+ A = nx.nx_agraph.to_agraph(G)
68
+ # Add edge (+ name, given by key) to the AGraph
69
+ A.add_edge(0, 1, key="foo")
70
+ # Verify a.name roundtrips out to 'key' in from_agraph
71
+ H = nx.nx_agraph.from_agraph(A)
72
+ assert isinstance(H, nx.Graph)
73
+ assert ("0", "1", {"key": "foo"}) in H.edges(data=True)
74
+
75
+ def test_to_agraph_with_nodedata(self):
76
+ G = nx.Graph()
77
+ G.add_node(1, color="red")
78
+ A = nx.nx_agraph.to_agraph(G)
79
+ assert dict(A.nodes()[0].attr) == {"color": "red"}
80
+
81
+ @pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph))
82
+ def test_to_agraph_with_edgedata(self, graph_class):
83
+ G = graph_class()
84
+ G.add_nodes_from([0, 1])
85
+ G.add_edge(0, 1, color="yellow")
86
+ A = nx.nx_agraph.to_agraph(G)
87
+ assert dict(A.edges()[0].attr) == {"color": "yellow"}
88
+
89
+ def test_view_pygraphviz_path(self, tmp_path):
90
+ G = nx.complete_graph(3)
91
+ input_path = str(tmp_path / "graph.png")
92
+ out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False)
93
+ assert out_path == input_path
94
+ # Ensure file is not empty
95
+ with open(input_path, "rb") as fh:
96
+ data = fh.read()
97
+ assert len(data) > 0
98
+
99
+ def test_view_pygraphviz_file_suffix(self, tmp_path):
100
+ G = nx.complete_graph(3)
101
+ path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False)
102
+ assert path[-6:] == "_1.png"
103
+
104
+ def test_view_pygraphviz(self):
105
+ G = nx.Graph() # "An empty graph cannot be drawn."
106
+ pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
107
+ G = nx.barbell_graph(4, 6)
108
+ nx.nx_agraph.view_pygraphviz(G, show=False)
109
+
110
+ def test_view_pygraphviz_edgelabel(self):
111
+ G = nx.Graph()
112
+ G.add_edge(1, 2, weight=7)
113
+ G.add_edge(2, 3, weight=8)
114
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False)
115
+ for edge in A.edges():
116
+ assert edge.attr["weight"] in ("7", "8")
117
+
118
+ def test_view_pygraphviz_callable_edgelabel(self):
119
+ G = nx.complete_graph(3)
120
+
121
+ def foo_label(data):
122
+ return "foo"
123
+
124
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False)
125
+ for edge in A.edges():
126
+ assert edge.attr["label"] == "foo"
127
+
128
+ def test_view_pygraphviz_multigraph_edgelabels(self):
129
+ G = nx.MultiGraph()
130
+ G.add_edge(0, 1, key=0, name="left_fork")
131
+ G.add_edge(0, 1, key=1, name="right_fork")
132
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False)
133
+ edges = A.edges()
134
+ assert len(edges) == 2
135
+ for edge in edges:
136
+ assert edge.attr["label"].strip() in ("left_fork", "right_fork")
137
+
138
+ def test_graph_with_reserved_keywords(self):
139
+ # test attribute/keyword clash case for #1582
140
+ # node: n
141
+ # edges: u,v
142
+ G = nx.Graph()
143
+ G = self.build_graph(G)
144
+ G.nodes["E"]["n"] = "keyword"
145
+ G.edges[("A", "B")]["u"] = "keyword"
146
+ G.edges[("A", "B")]["v"] = "keyword"
147
+ A = nx.nx_agraph.to_agraph(G)
148
+
149
+ def test_view_pygraphviz_no_added_attrs_to_input(self):
150
+ G = nx.complete_graph(2)
151
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
152
+ assert G.graph == {}
153
+
154
+ @pytest.mark.xfail(reason="known bug in clean_attrs")
155
+ def test_view_pygraphviz_leaves_input_graph_unmodified(self):
156
+ G = nx.complete_graph(2)
157
+ # Add entries to graph dict that to_agraph handles specially
158
+ G.graph["node"] = {"width": "0.80"}
159
+ G.graph["edge"] = {"fontsize": "14"}
160
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
161
+ assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}}
162
+
163
+ def test_graph_with_AGraph_attrs(self):
164
+ G = nx.complete_graph(2)
165
+ # Add entries to graph dict that to_agraph handles specially
166
+ G.graph["node"] = {"width": "0.80"}
167
+ G.graph["edge"] = {"fontsize": "14"}
168
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
169
+ # Ensure user-specified values are not lost
170
+ assert dict(A.node_attr)["width"] == "0.80"
171
+ assert dict(A.edge_attr)["fontsize"] == "14"
172
+
173
+ def test_round_trip_empty_graph(self):
174
+ G = nx.Graph()
175
+ A = nx.nx_agraph.to_agraph(G)
176
+ H = nx.nx_agraph.from_agraph(A)
177
+ # assert graphs_equal(G, H)
178
+ AA = nx.nx_agraph.to_agraph(H)
179
+ HH = nx.nx_agraph.from_agraph(AA)
180
+ assert graphs_equal(H, HH)
181
+ G.graph["graph"] = {}
182
+ G.graph["node"] = {}
183
+ G.graph["edge"] = {}
184
+ assert graphs_equal(G, HH)
185
+
186
+ @pytest.mark.xfail(reason="integer->string node conversion in round trip")
187
+ def test_round_trip_integer_nodes(self):
188
+ G = nx.complete_graph(3)
189
+ A = nx.nx_agraph.to_agraph(G)
190
+ H = nx.nx_agraph.from_agraph(A)
191
+ assert graphs_equal(G, H)
192
+
193
+ def test_graphviz_alias(self):
194
+ G = self.build_graph(nx.Graph())
195
+ pos_graphviz = nx.nx_agraph.graphviz_layout(G)
196
+ pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G)
197
+ assert pos_graphviz == pos_pygraphviz
198
+
199
+ @pytest.mark.parametrize("root", range(5))
200
+ def test_pygraphviz_layout_root(self, root):
201
+ # NOTE: test depends on layout prog being deterministic
202
+ G = nx.complete_graph(5)
203
+ A = nx.nx_agraph.to_agraph(G)
204
+ # Get layout with root arg is not None
205
+ pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root)
206
+ # Equivalent layout directly on AGraph
207
+ A.layout(args=f"-Groot={root}", prog="circo")
208
+ # Parse AGraph layout
209
+ a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(","))
210
+ assert pygv_layout[1] == a1_pos
211
+
212
+ def test_2d_layout(self):
213
+ G = nx.Graph()
214
+ G = self.build_graph(G)
215
+ G.graph["dimen"] = 2
216
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
217
+ pos = list(pos.values())
218
+ assert len(pos) == 5
219
+ assert len(pos[0]) == 2
220
+
221
+ def test_3d_layout(self):
222
+ G = nx.Graph()
223
+ G = self.build_graph(G)
224
+ G.graph["dimen"] = 3
225
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
226
+ pos = list(pos.values())
227
+ assert len(pos) == 5
228
+ assert len(pos[0]) == 3
229
+
230
+ def test_no_warnings_raised(self):
231
+ # Test that no warnings are raised when Networkx graph
232
+ # is converted to Pygraphviz graph and 'pos'
233
+ # attribute is given
234
+ G = nx.Graph()
235
+ G.add_node(0, pos=(0, 0))
236
+ G.add_node(1, pos=(1, 1))
237
+ A = nx.nx_agraph.to_agraph(G)
238
+ with warnings.catch_warnings(record=True) as record:
239
+ A.layout()
240
+ assert len(record) == 0
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_tikz_attributes():
7
+ G = nx.path_graph(4, create_using=nx.DiGraph)
8
+ pos = {n: (n, n) for n in G}
9
+
10
+ G.add_edge(0, 0)
11
+ G.edges[(0, 0)]["label"] = "Loop"
12
+ G.edges[(0, 0)]["label_options"] = "midway"
13
+
14
+ G.nodes[0]["style"] = "blue"
15
+ G.nodes[1]["style"] = "line width=3,draw"
16
+ G.nodes[2]["style"] = "circle,draw,blue!50"
17
+ G.nodes[3]["label"] = "Stop"
18
+ G.edges[(0, 1)]["label"] = "1st Step"
19
+ G.edges[(0, 1)]["label_options"] = "near end"
20
+ G.edges[(2, 3)]["label"] = "3rd Step"
21
+ G.edges[(2, 3)]["label_options"] = "near start"
22
+ G.edges[(2, 3)]["style"] = "bend left,green"
23
+ G.edges[(1, 2)]["label"] = "2nd"
24
+ G.edges[(1, 2)]["label_options"] = "pos=0.5"
25
+ G.edges[(1, 2)]["style"] = ">->,bend right,line width=3,green!90"
26
+
27
+ output_tex = nx.to_latex(
28
+ G,
29
+ pos=pos,
30
+ as_document=False,
31
+ tikz_options="[scale=3]",
32
+ node_options="style",
33
+ edge_options="style",
34
+ node_label="label",
35
+ edge_label="label",
36
+ edge_label_options="label_options",
37
+ )
38
+ expected_tex = r"""\begin{figure}
39
+ \begin{tikzpicture}[scale=3]
40
+ \draw
41
+ (0, 0) node[blue] (0){0}
42
+ (1, 1) node[line width=3,draw] (1){1}
43
+ (2, 2) node[circle,draw,blue!50] (2){2}
44
+ (3, 3) node (3){Stop};
45
+ \begin{scope}[->]
46
+ \draw (0) to node[near end] {1st Step} (1);
47
+ \draw[loop,] (0) to node[midway] {Loop} (0);
48
+ \draw[>->,bend right,line width=3,green!90] (1) to node[pos=0.5] {2nd} (2);
49
+ \draw[bend left,green] (2) to node[near start] {3rd Step} (3);
50
+ \end{scope}
51
+ \end{tikzpicture}
52
+ \end{figure}"""
53
+
54
+ assert output_tex == expected_tex
55
+ # print(output_tex)
56
+ # # Pretty way to assert that A.to_document() == expected_tex
57
+ # content_same = True
58
+ # for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
59
+ # if aa != bb:
60
+ # content_same = False
61
+ # print(f"-{aa}|\n+{bb}|")
62
+ # assert content_same
63
+
64
+
65
+ def test_basic_multiple_graphs():
66
+ H1 = nx.path_graph(4)
67
+ H2 = nx.complete_graph(4)
68
+ H3 = nx.path_graph(8)
69
+ H4 = nx.complete_graph(8)
70
+ captions = [
71
+ "Path on 4 nodes",
72
+ "Complete graph on 4 nodes",
73
+ "Path on 8 nodes",
74
+ "Complete graph on 8 nodes",
75
+ ]
76
+ labels = ["fig2a", "fig2b", "fig2c", "fig2d"]
77
+ latex_code = nx.to_latex(
78
+ [H1, H2, H3, H4],
79
+ n_rows=2,
80
+ sub_captions=captions,
81
+ sub_labels=labels,
82
+ )
83
+ # print(latex_code)
84
+ assert "begin{document}" in latex_code
85
+ assert "begin{figure}" in latex_code
86
+ assert latex_code.count("begin{subfigure}") == 4
87
+ assert latex_code.count("tikzpicture") == 8
88
+ assert latex_code.count("[-]") == 4
89
+
90
+
91
+ def test_basic_tikz():
92
+ expected_tex = r"""\documentclass{report}
93
+ \usepackage{tikz}
94
+ \usepackage{subcaption}
95
+
96
+ \begin{document}
97
+ \begin{figure}
98
+ \begin{subfigure}{0.5\textwidth}
99
+ \begin{tikzpicture}[scale=2]
100
+ \draw[gray!90]
101
+ (0.749, 0.702) node[red!90] (0){0}
102
+ (1.0, -0.014) node[red!90] (1){1}
103
+ (-0.777, -0.705) node (2){2}
104
+ (-0.984, 0.042) node (3){3}
105
+ (-0.028, 0.375) node[cyan!90] (4){4}
106
+ (-0.412, 0.888) node (5){5}
107
+ (0.448, -0.856) node (6){6}
108
+ (0.003, -0.431) node[cyan!90] (7){7};
109
+ \begin{scope}[->,gray!90]
110
+ \draw (0) to (4);
111
+ \draw (0) to (5);
112
+ \draw (0) to (6);
113
+ \draw (0) to (7);
114
+ \draw (1) to (4);
115
+ \draw (1) to (5);
116
+ \draw (1) to (6);
117
+ \draw (1) to (7);
118
+ \draw (2) to (4);
119
+ \draw (2) to (5);
120
+ \draw (2) to (6);
121
+ \draw (2) to (7);
122
+ \draw (3) to (4);
123
+ \draw (3) to (5);
124
+ \draw (3) to (6);
125
+ \draw (3) to (7);
126
+ \end{scope}
127
+ \end{tikzpicture}
128
+ \caption{My tikz number 1 of 2}\label{tikz_1_2}
129
+ \end{subfigure}
130
+ \begin{subfigure}{0.5\textwidth}
131
+ \begin{tikzpicture}[scale=2]
132
+ \draw[gray!90]
133
+ (0.749, 0.702) node[green!90] (0){0}
134
+ (1.0, -0.014) node[green!90] (1){1}
135
+ (-0.777, -0.705) node (2){2}
136
+ (-0.984, 0.042) node (3){3}
137
+ (-0.028, 0.375) node[purple!90] (4){4}
138
+ (-0.412, 0.888) node (5){5}
139
+ (0.448, -0.856) node (6){6}
140
+ (0.003, -0.431) node[purple!90] (7){7};
141
+ \begin{scope}[->,gray!90]
142
+ \draw (0) to (4);
143
+ \draw (0) to (5);
144
+ \draw (0) to (6);
145
+ \draw (0) to (7);
146
+ \draw (1) to (4);
147
+ \draw (1) to (5);
148
+ \draw (1) to (6);
149
+ \draw (1) to (7);
150
+ \draw (2) to (4);
151
+ \draw (2) to (5);
152
+ \draw (2) to (6);
153
+ \draw (2) to (7);
154
+ \draw (3) to (4);
155
+ \draw (3) to (5);
156
+ \draw (3) to (6);
157
+ \draw (3) to (7);
158
+ \end{scope}
159
+ \end{tikzpicture}
160
+ \caption{My tikz number 2 of 2}\label{tikz_2_2}
161
+ \end{subfigure}
162
+ \caption{A graph generated with python and latex.}
163
+ \end{figure}
164
+ \end{document}"""
165
+
166
+ edges = [
167
+ (0, 4),
168
+ (0, 5),
169
+ (0, 6),
170
+ (0, 7),
171
+ (1, 4),
172
+ (1, 5),
173
+ (1, 6),
174
+ (1, 7),
175
+ (2, 4),
176
+ (2, 5),
177
+ (2, 6),
178
+ (2, 7),
179
+ (3, 4),
180
+ (3, 5),
181
+ (3, 6),
182
+ (3, 7),
183
+ ]
184
+ G = nx.DiGraph()
185
+ G.add_nodes_from(range(8))
186
+ G.add_edges_from(edges)
187
+ pos = {
188
+ 0: (0.7490296171687696, 0.702353520257394),
189
+ 1: (1.0, -0.014221357723796535),
190
+ 2: (-0.7765783344161441, -0.7054170966808919),
191
+ 3: (-0.9842690223417624, 0.04177547602465483),
192
+ 4: (-0.02768523817180917, 0.3745724439551441),
193
+ 5: (-0.41154855146767433, 0.8880106515525136),
194
+ 6: (0.44780153389148264, -0.8561492709269164),
195
+ 7: (0.0032499953371383505, -0.43092436645809945),
196
+ }
197
+
198
+ rc_node_color = {0: "red!90", 1: "red!90", 4: "cyan!90", 7: "cyan!90"}
199
+ gp_node_color = {0: "green!90", 1: "green!90", 4: "purple!90", 7: "purple!90"}
200
+
201
+ H = G.copy()
202
+ nx.set_node_attributes(G, rc_node_color, "color")
203
+ nx.set_node_attributes(H, gp_node_color, "color")
204
+
205
+ sub_captions = ["My tikz number 1 of 2", "My tikz number 2 of 2"]
206
+ sub_labels = ["tikz_1_2", "tikz_2_2"]
207
+
208
+ output_tex = nx.to_latex(
209
+ [G, H],
210
+ [pos, pos],
211
+ tikz_options="[scale=2]",
212
+ default_node_options="gray!90",
213
+ default_edge_options="gray!90",
214
+ node_options="color",
215
+ sub_captions=sub_captions,
216
+ sub_labels=sub_labels,
217
+ caption="A graph generated with python and latex.",
218
+ n_rows=2,
219
+ as_document=True,
220
+ )
221
+
222
+ assert output_tex == expected_tex
223
+ # print(output_tex)
224
+ # # Pretty way to assert that A.to_document() == expected_tex
225
+ # content_same = True
226
+ # for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
227
+ # if aa != bb:
228
+ # content_same = False
229
+ # print(f"-{aa}|\n+{bb}|")
230
+ # assert content_same
231
+
232
+
233
+ def test_exception_pos_single_graph(to_latex=nx.to_latex):
234
+ # smoke test that pos can be a string
235
+ G = nx.path_graph(4)
236
+ to_latex(G, pos="pos")
237
+
238
+ # must include all nodes
239
+ pos = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
240
+ with pytest.raises(nx.NetworkXError):
241
+ to_latex(G, pos)
242
+
243
+ # must have 2 values
244
+ pos[3] = (1, 2, 3)
245
+ with pytest.raises(nx.NetworkXError):
246
+ to_latex(G, pos)
247
+ pos[3] = 2
248
+ with pytest.raises(nx.NetworkXError):
249
+ to_latex(G, pos)
250
+
251
+ # check that passes with 2 values
252
+ pos[3] = (3, 2)
253
+ to_latex(G, pos)
254
+
255
+
256
+ def test_exception_multiple_graphs(to_latex=nx.to_latex):
257
+ G = nx.path_graph(3)
258
+ pos_bad = {0: (1, 2), 1: (0, 1)}
259
+ pos_OK = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
260
+ fourG = [G, G, G, G]
261
+ fourpos = [pos_OK, pos_OK, pos_OK, pos_OK]
262
+
263
+ # input single dict to use for all graphs
264
+ to_latex(fourG, pos_OK)
265
+ with pytest.raises(nx.NetworkXError):
266
+ to_latex(fourG, pos_bad)
267
+
268
+ # input list of dicts to use for all graphs
269
+ to_latex(fourG, fourpos)
270
+ with pytest.raises(nx.NetworkXError):
271
+ to_latex(fourG, [pos_bad, pos_bad, pos_bad, pos_bad])
272
+
273
+ # every pos dict must include all nodes
274
+ with pytest.raises(nx.NetworkXError):
275
+ to_latex(fourG, [pos_OK, pos_OK, pos_bad, pos_OK])
276
+
277
+ # test sub_captions and sub_labels (len must match Gbunch)
278
+ with pytest.raises(nx.NetworkXError):
279
+ to_latex(fourG, fourpos, sub_captions=["hi", "hi"])
280
+
281
+ with pytest.raises(nx.NetworkXError):
282
+ to_latex(fourG, fourpos, sub_labels=["hi", "hi"])
283
+
284
+ # all pass
285
+ to_latex(fourG, fourpos, sub_captions=["hi"] * 4, sub_labels=["lbl"] * 4)
286
+
287
+
288
+ def test_exception_multigraph():
289
+ G = nx.path_graph(4, create_using=nx.MultiGraph)
290
+ G.add_edge(1, 2)
291
+ with pytest.raises(nx.NetworkXNotImplemented):
292
+ nx.to_latex(G)
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for layout functions."""
2
+ import pytest
3
+
4
+ import networkx as nx
5
+
6
+ np = pytest.importorskip("numpy")
7
+ pytest.importorskip("scipy")
8
+
9
+
10
+ class TestLayout:
11
+ @classmethod
12
+ def setup_class(cls):
13
+ cls.Gi = nx.grid_2d_graph(5, 5)
14
+ cls.Gs = nx.Graph()
15
+ nx.add_path(cls.Gs, "abcdef")
16
+ cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse
17
+
18
+ def test_spring_fixed_without_pos(self):
19
+ G = nx.path_graph(4)
20
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
21
+ pos = {0: (1, 1), 2: (0, 0)}
22
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
23
+ nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError
24
+
25
+ def test_spring_init_pos(self):
26
+ # Tests GH #2448
27
+ import math
28
+
29
+ G = nx.Graph()
30
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)])
31
+
32
+ init_pos = {0: (0.0, 0.0)}
33
+ fixed_pos = [0]
34
+ pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos)
35
+ has_nan = any(math.isnan(c) for coords in pos.values() for c in coords)
36
+ assert not has_nan, "values should not be nan"
37
+
38
+ def test_smoke_empty_graph(self):
39
+ G = []
40
+ nx.random_layout(G)
41
+ nx.circular_layout(G)
42
+ nx.planar_layout(G)
43
+ nx.spring_layout(G)
44
+ nx.fruchterman_reingold_layout(G)
45
+ nx.spectral_layout(G)
46
+ nx.shell_layout(G)
47
+ nx.bipartite_layout(G, G)
48
+ nx.spiral_layout(G)
49
+ nx.multipartite_layout(G)
50
+ nx.kamada_kawai_layout(G)
51
+
52
+ def test_smoke_int(self):
53
+ G = self.Gi
54
+ nx.random_layout(G)
55
+ nx.circular_layout(G)
56
+ nx.planar_layout(G)
57
+ nx.spring_layout(G)
58
+ nx.fruchterman_reingold_layout(G)
59
+ nx.fruchterman_reingold_layout(self.bigG)
60
+ nx.spectral_layout(G)
61
+ nx.spectral_layout(G.to_directed())
62
+ nx.spectral_layout(self.bigG)
63
+ nx.spectral_layout(self.bigG.to_directed())
64
+ nx.shell_layout(G)
65
+ nx.spiral_layout(G)
66
+ nx.kamada_kawai_layout(G)
67
+ nx.kamada_kawai_layout(G, dim=1)
68
+ nx.kamada_kawai_layout(G, dim=3)
69
+ nx.arf_layout(G)
70
+
71
+ def test_smoke_string(self):
72
+ G = self.Gs
73
+ nx.random_layout(G)
74
+ nx.circular_layout(G)
75
+ nx.planar_layout(G)
76
+ nx.spring_layout(G)
77
+ nx.fruchterman_reingold_layout(G)
78
+ nx.spectral_layout(G)
79
+ nx.shell_layout(G)
80
+ nx.spiral_layout(G)
81
+ nx.kamada_kawai_layout(G)
82
+ nx.kamada_kawai_layout(G, dim=1)
83
+ nx.kamada_kawai_layout(G, dim=3)
84
+ nx.arf_layout(G)
85
+
86
+ def check_scale_and_center(self, pos, scale, center):
87
+ center = np.array(center)
88
+ low = center - scale
89
+ hi = center + scale
90
+ vpos = np.array(list(pos.values()))
91
+ length = vpos.max(0) - vpos.min(0)
92
+ assert (length <= 2 * scale).all()
93
+ assert (vpos >= low).all()
94
+ assert (vpos <= hi).all()
95
+
96
+ def test_scale_and_center_arg(self):
97
+ sc = self.check_scale_and_center
98
+ c = (4, 5)
99
+ G = nx.complete_graph(9)
100
+ G.add_node(9)
101
+ sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
102
+ # rest can have 2*scale length: [-scale, scale]
103
+ sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
104
+ sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
105
+ sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
106
+ sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
107
+ sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
108
+ sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
109
+
110
+ c = (2, 3, 5)
111
+ sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c)
112
+
113
+ def test_planar_layout_non_planar_input(self):
114
+ G = nx.complete_graph(9)
115
+ pytest.raises(nx.NetworkXException, nx.planar_layout, G)
116
+
117
+ def test_smoke_planar_layout_embedding_input(self):
118
+ embedding = nx.PlanarEmbedding()
119
+ embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]})
120
+ nx.planar_layout(embedding)
121
+
122
+ def test_default_scale_and_center(self):
123
+ sc = self.check_scale_and_center
124
+ c = (0, 0)
125
+ G = nx.complete_graph(9)
126
+ G.add_node(9)
127
+ sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
128
+ sc(nx.spring_layout(G), scale=1, center=c)
129
+ sc(nx.spectral_layout(G), scale=1, center=c)
130
+ sc(nx.circular_layout(G), scale=1, center=c)
131
+ sc(nx.shell_layout(G), scale=1, center=c)
132
+ sc(nx.spiral_layout(G), scale=1, center=c)
133
+ sc(nx.kamada_kawai_layout(G), scale=1, center=c)
134
+
135
+ c = (0, 0, 0)
136
+ sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c)
137
+
138
+ def test_circular_planar_and_shell_dim_error(self):
139
+ G = nx.path_graph(4)
140
+ pytest.raises(ValueError, nx.circular_layout, G, dim=1)
141
+ pytest.raises(ValueError, nx.shell_layout, G, dim=1)
142
+ pytest.raises(ValueError, nx.shell_layout, G, dim=3)
143
+ pytest.raises(ValueError, nx.planar_layout, G, dim=1)
144
+ pytest.raises(ValueError, nx.planar_layout, G, dim=3)
145
+
146
+ def test_adjacency_interface_numpy(self):
147
+ A = nx.to_numpy_array(self.Gs)
148
+ pos = nx.drawing.layout._fruchterman_reingold(A)
149
+ assert pos.shape == (6, 2)
150
+ pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
151
+ assert pos.shape == (6, 3)
152
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
153
+ assert pos.shape == (6, 2)
154
+
155
+ def test_adjacency_interface_scipy(self):
156
+ A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
157
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
158
+ assert pos.shape == (6, 2)
159
+ pos = nx.drawing.layout._sparse_spectral(A)
160
+ assert pos.shape == (6, 2)
161
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
162
+ assert pos.shape == (6, 3)
163
+
164
+ def test_single_nodes(self):
165
+ G = nx.path_graph(1)
166
+ vpos = nx.shell_layout(G)
167
+ assert not vpos[0].any()
168
+ G = nx.path_graph(4)
169
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]])
170
+ assert not vpos[0].any()
171
+ assert vpos[3].any() # ensure node 3 not at origin (#3188)
172
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
173
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0)
174
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
175
+
176
+ def test_smoke_initial_pos_fruchterman_reingold(self):
177
+ pos = nx.circular_layout(self.Gi)
178
+ npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
179
+
180
+ def test_smoke_initial_pos_arf(self):
181
+ pos = nx.circular_layout(self.Gi)
182
+ npos = nx.arf_layout(self.Gi, pos=pos)
183
+
184
+ def test_fixed_node_fruchterman_reingold(self):
185
+ # Dense version (numpy based)
186
+ pos = nx.circular_layout(self.Gi)
187
+ npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)])
188
+ assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)])
189
+ # Sparse version (scipy based)
190
+ pos = nx.circular_layout(self.bigG)
191
+ npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)])
192
+ for axis in range(2):
193
+ assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7)
194
+
195
+ def test_center_parameter(self):
196
+ G = nx.path_graph(1)
197
+ nx.random_layout(G, center=(1, 1))
198
+ vpos = nx.circular_layout(G, center=(1, 1))
199
+ assert tuple(vpos[0]) == (1, 1)
200
+ vpos = nx.planar_layout(G, center=(1, 1))
201
+ assert tuple(vpos[0]) == (1, 1)
202
+ vpos = nx.spring_layout(G, center=(1, 1))
203
+ assert tuple(vpos[0]) == (1, 1)
204
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
205
+ assert tuple(vpos[0]) == (1, 1)
206
+ vpos = nx.spectral_layout(G, center=(1, 1))
207
+ assert tuple(vpos[0]) == (1, 1)
208
+ vpos = nx.shell_layout(G, center=(1, 1))
209
+ assert tuple(vpos[0]) == (1, 1)
210
+ vpos = nx.spiral_layout(G, center=(1, 1))
211
+ assert tuple(vpos[0]) == (1, 1)
212
+
213
+ def test_center_wrong_dimensions(self):
214
+ G = nx.path_graph(1)
215
+ assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout)
216
+ pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1))
217
+ pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1))
218
+ pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1))
219
+ pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1))
220
+ pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1))
221
+ pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1))
222
+ pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1))
223
+ pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
224
+ pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1))
225
+ pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1))
226
+
227
+ def test_empty_graph(self):
228
+ G = nx.empty_graph()
229
+ vpos = nx.random_layout(G, center=(1, 1))
230
+ assert vpos == {}
231
+ vpos = nx.circular_layout(G, center=(1, 1))
232
+ assert vpos == {}
233
+ vpos = nx.planar_layout(G, center=(1, 1))
234
+ assert vpos == {}
235
+ vpos = nx.bipartite_layout(G, G)
236
+ assert vpos == {}
237
+ vpos = nx.spring_layout(G, center=(1, 1))
238
+ assert vpos == {}
239
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
240
+ assert vpos == {}
241
+ vpos = nx.spectral_layout(G, center=(1, 1))
242
+ assert vpos == {}
243
+ vpos = nx.shell_layout(G, center=(1, 1))
244
+ assert vpos == {}
245
+ vpos = nx.spiral_layout(G, center=(1, 1))
246
+ assert vpos == {}
247
+ vpos = nx.multipartite_layout(G, center=(1, 1))
248
+ assert vpos == {}
249
+ vpos = nx.kamada_kawai_layout(G, center=(1, 1))
250
+ assert vpos == {}
251
+ vpos = nx.arf_layout(G)
252
+ assert vpos == {}
253
+
254
+ def test_bipartite_layout(self):
255
+ G = nx.complete_bipartite_graph(3, 5)
256
+ top, bottom = nx.bipartite.sets(G)
257
+
258
+ vpos = nx.bipartite_layout(G, top)
259
+ assert len(vpos) == len(G)
260
+
261
+ top_x = vpos[list(top)[0]][0]
262
+ bottom_x = vpos[list(bottom)[0]][0]
263
+ for node in top:
264
+ assert vpos[node][0] == top_x
265
+ for node in bottom:
266
+ assert vpos[node][0] == bottom_x
267
+
268
+ vpos = nx.bipartite_layout(
269
+ G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1
270
+ )
271
+ assert len(vpos) == len(G)
272
+
273
+ top_y = vpos[list(top)[0]][1]
274
+ bottom_y = vpos[list(bottom)[0]][1]
275
+ for node in top:
276
+ assert vpos[node][1] == top_y
277
+ for node in bottom:
278
+ assert vpos[node][1] == bottom_y
279
+
280
+ pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo")
281
+
282
+ def test_multipartite_layout(self):
283
+ sizes = (0, 5, 7, 2, 8)
284
+ G = nx.complete_multipartite_graph(*sizes)
285
+
286
+ vpos = nx.multipartite_layout(G)
287
+ assert len(vpos) == len(G)
288
+
289
+ start = 0
290
+ for n in sizes:
291
+ end = start + n
292
+ assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end))
293
+ start += n
294
+
295
+ vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2))
296
+ assert len(vpos) == len(G)
297
+
298
+ start = 0
299
+ for n in sizes:
300
+ end = start + n
301
+ assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end))
302
+ start += n
303
+
304
+ pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
305
+
306
+ def test_kamada_kawai_costfn_1d(self):
307
+ costfn = nx.drawing.layout._kamada_kawai_costfn
308
+
309
+ pos = np.array([4.0, 7.0])
310
+ invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]])
311
+
312
+ cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1)
313
+
314
+ assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7)
315
+ assert grad[0] == pytest.approx((-0.5), abs=1e-7)
316
+ assert grad[1] == pytest.approx(0.5, abs=1e-7)
317
+
318
+ def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim):
319
+ costfn = nx.drawing.layout._kamada_kawai_costfn
320
+
321
+ cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim)
322
+
323
+ expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2)
324
+ for i in range(pos.shape[0]):
325
+ for j in range(i + 1, pos.shape[0]):
326
+ diff = np.linalg.norm(pos[i] - pos[j])
327
+ expected_cost += (diff * invdist[i][j] - 1.0) ** 2
328
+
329
+ assert cost == pytest.approx(expected_cost, abs=1e-7)
330
+
331
+ dx = 1e-4
332
+ for nd in range(pos.shape[0]):
333
+ for dm in range(pos.shape[1]):
334
+ idx = nd * pos.shape[1] + dm
335
+ ps = pos.flatten()
336
+
337
+ ps[idx] += dx
338
+ cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
339
+
340
+ ps[idx] -= 2 * dx
341
+ cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
342
+
343
+ assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5)
344
+
345
+ def test_kamada_kawai_costfn(self):
346
+ invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]])
347
+ meanwt = 0.3
348
+
349
+ # 2d
350
+ pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]])
351
+
352
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2)
353
+
354
+ # 3d
355
+ pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]])
356
+
357
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3)
358
+
359
+ def test_spiral_layout(self):
360
+ G = self.Gs
361
+
362
+ # a lower value of resolution should result in a more compact layout
363
+ # intuitively, the total distance from the start and end nodes
364
+ # via each node in between (transiting through each) will be less,
365
+ # assuming rescaling does not occur on the computed node positions
366
+ pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values()))
367
+ pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values()))
368
+ distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1)
369
+ distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1)
370
+ assert sum(distances) > sum(distances_tighter)
371
+
372
+ # return near-equidistant points after the first value if set to true
373
+ pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values()))
374
+ distances_equidistant = np.linalg.norm(
375
+ pos_equidistant[:-1] - pos_equidistant[1:], axis=1
376
+ )
377
+ assert np.allclose(
378
+ distances_equidistant[1:], distances_equidistant[-1], atol=0.01
379
+ )
380
+
381
+ def test_spiral_layout_equidistant(self):
382
+ G = nx.path_graph(10)
383
+ pos = nx.spiral_layout(G, equidistant=True)
384
+ # Extract individual node positions as an array
385
+ p = np.array(list(pos.values()))
386
+ # Elementwise-distance between node positions
387
+ dist = np.linalg.norm(p[1:] - p[:-1], axis=1)
388
+ assert np.allclose(np.diff(dist), 0, atol=1e-3)
389
+
390
+ def test_rescale_layout_dict(self):
391
+ G = nx.empty_graph()
392
+ vpos = nx.random_layout(G, center=(1, 1))
393
+ assert nx.rescale_layout_dict(vpos) == {}
394
+
395
+ G = nx.empty_graph(2)
396
+ vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)}
397
+ s_vpos = nx.rescale_layout_dict(vpos)
398
+ assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6
399
+
400
+ G = nx.empty_graph(3)
401
+ vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)}
402
+ s_vpos = nx.rescale_layout_dict(vpos)
403
+
404
+ expectation = {
405
+ 0: np.array((-1, -1)),
406
+ 1: np.array((1, 1)),
407
+ 2: np.array((0, 0)),
408
+ }
409
+ for k, v in expectation.items():
410
+ assert (s_vpos[k] == v).all()
411
+ s_vpos = nx.rescale_layout_dict(vpos, scale=2)
412
+ expectation = {
413
+ 0: np.array((-2, -2)),
414
+ 1: np.array((2, 2)),
415
+ 2: np.array((0, 0)),
416
+ }
417
+ for k, v in expectation.items():
418
+ assert (s_vpos[k] == v).all()
419
+
420
+ def test_arf_layout_partial_input_test(self):
421
+ """
422
+ Checks whether partial pos input still returns a proper position.
423
+ """
424
+ G = self.Gs
425
+ node = nx.utils.arbitrary_element(G)
426
+ pos = nx.circular_layout(G)
427
+ del pos[node]
428
+ pos = nx.arf_layout(G, pos=pos)
429
+ assert len(pos) == len(G)
430
+
431
+ def test_arf_layout_negative_a_check(self):
432
+ """
433
+ Checks input parameters correctly raises errors. For example, `a` should be larger than 1
434
+ """
435
+ G = self.Gs
436
+ pytest.raises(ValueError, nx.arf_layout, G=G, a=-1)
437
+
438
+
439
+ def test_multipartite_layout_nonnumeric_partition_labels():
440
+ """See gh-5123."""
441
+ G = nx.Graph()
442
+ G.add_node(0, subset="s0")
443
+ G.add_node(1, subset="s0")
444
+ G.add_node(2, subset="s1")
445
+ G.add_node(3, subset="s1")
446
+ G.add_edges_from([(0, 2), (0, 3), (1, 2)])
447
+ pos = nx.multipartite_layout(G)
448
+ assert len(pos) == len(G)
449
+
450
+
451
+ def test_multipartite_layout_layer_order():
452
+ """Return the layers in sorted order if the layers of the multipartite
453
+ graph are sortable. See gh-5691"""
454
+ G = nx.Graph()
455
+ node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4)))
456
+ for node, layer in node_group.items():
457
+ G.add_node(node, subset=layer)
458
+
459
+ # Horizontal alignment, therefore y-coord determines layers
460
+ pos = nx.multipartite_layout(G, align="horizontal")
461
+
462
+ layers = nx.utils.groups(node_group)
463
+ pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers)
464
+ for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()):
465
+ assert n1 == n2 and (p1 == p2).all()
466
+
467
+ # Nodes "a" and "d" are in the same layer
468
+ assert pos["a"][-1] == pos["d"][-1]
469
+ # positions should be sorted according to layer
470
+ assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1]
471
+
472
+ # Make sure that multipartite_layout still works when layers are not sortable
473
+ G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints
474
+ pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise
475
+ assert pos_nosort.keys() == pos.keys()
476
+
477
+
478
+ def _num_nodes_per_bfs_layer(pos):
479
+ """Helper function to extract the number of nodes in each layer of bfs_layout"""
480
+ x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension
481
+ _, layer_count = np.unique(x, return_counts=True)
482
+ return layer_count
483
+
484
+
485
+ @pytest.mark.parametrize("n", range(2, 7))
486
+ def test_bfs_layout_complete_graph(n):
487
+ """The complete graph should result in two layers: the starting node and
488
+ a second layer containing all neighbors."""
489
+ G = nx.complete_graph(n)
490
+ pos = nx.bfs_layout(G, start=0)
491
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1])
492
+
493
+
494
+ def test_bfs_layout_barbell():
495
+ G = nx.barbell_graph(5, 3)
496
+ # Start in one of the "bells"
497
+ pos = nx.bfs_layout(G, start=0)
498
+ # start, bell-1, [1] * len(bar)+1, bell-1
499
+ expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4]
500
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
501
+ # Start in the other "bell" - expect same layer pattern
502
+ pos = nx.bfs_layout(G, start=12)
503
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
504
+ # Starting in the center of the bar, expect layers to be symmetric
505
+ pos = nx.bfs_layout(G, start=6)
506
+ # Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells}
507
+ expected_nodes_per_layer = [1, 2, 2, 8]
508
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
509
+
510
+
511
+ def test_bfs_layout_disconnected():
512
+ G = nx.complete_graph(5)
513
+ G.add_edges_from([(10, 11), (11, 12)])
514
+ with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"):
515
+ nx.bfs_layout(G, start=0)
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for pydot drawing functions."""
2
+ from io import StringIO
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.utils import graphs_equal
8
+
9
+ pydot = pytest.importorskip("pydot")
10
+
11
+
12
+ class TestPydot:
13
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
14
+ @pytest.mark.parametrize("prog", ("neato", "dot"))
15
+ def test_pydot(self, G, prog, tmp_path):
16
+ """
17
+ Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
18
+ passed basename of an external GraphViz command (e.g., `dot`, `neato`).
19
+ """
20
+
21
+ # Set the name of this graph to... "G". Failing to do so will
22
+ # subsequently trip an assertion expecting this name.
23
+ G.graph["name"] = "G"
24
+
25
+ # Add arbitrary nodes and edges to the passed empty graph.
26
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
27
+ G.add_node("E")
28
+
29
+ # Validate layout of this graph with the passed GraphViz command.
30
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
31
+ assert isinstance(graph_layout, dict)
32
+
33
+ # Convert this graph into a "pydot.Dot" instance.
34
+ P = nx.nx_pydot.to_pydot(G)
35
+
36
+ # Convert this "pydot.Dot" instance back into a graph of the same type.
37
+ G2 = G.__class__(nx.nx_pydot.from_pydot(P))
38
+
39
+ # Validate the original and resulting graphs to be the same.
40
+ assert graphs_equal(G, G2)
41
+
42
+ fname = tmp_path / "out.dot"
43
+
44
+ # Serialize this "pydot.Dot" instance to a temporary file in dot format
45
+ P.write_raw(fname)
46
+
47
+ # Deserialize a list of new "pydot.Dot" instances back from this file.
48
+ Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")
49
+
50
+ # Validate this file to contain only one graph.
51
+ assert len(Pin_list) == 1
52
+
53
+ # The single "pydot.Dot" instance deserialized from this file.
54
+ Pin = Pin_list[0]
55
+
56
+ # Sorted list of all nodes in the original "pydot.Dot" instance.
57
+ n1 = sorted(p.get_name() for p in P.get_node_list())
58
+
59
+ # Sorted list of all nodes in the deserialized "pydot.Dot" instance.
60
+ n2 = sorted(p.get_name() for p in Pin.get_node_list())
61
+
62
+ # Validate these instances to contain the same nodes.
63
+ assert n1 == n2
64
+
65
+ # Sorted list of all edges in the original "pydot.Dot" instance.
66
+ e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list())
67
+
68
+ # Sorted list of all edges in the original "pydot.Dot" instance.
69
+ e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list())
70
+
71
+ # Validate these instances to contain the same edges.
72
+ assert e1 == e2
73
+
74
+ # Deserialize a new graph of the same type back from this file.
75
+ Hin = nx.nx_pydot.read_dot(fname)
76
+ Hin = G.__class__(Hin)
77
+
78
+ # Validate the original and resulting graphs to be the same.
79
+ assert graphs_equal(G, Hin)
80
+
81
+ def test_read_write(self):
82
+ G = nx.MultiGraph()
83
+ G.graph["name"] = "G"
84
+ G.add_edge("1", "2", key="0") # read assumes strings
85
+ fh = StringIO()
86
+ nx.nx_pydot.write_dot(G, fh)
87
+ fh.seek(0)
88
+ H = nx.nx_pydot.read_dot(fh)
89
+ assert graphs_equal(G, H)
90
+
91
+
92
+ def test_pydot_issue_258():
93
+ G = nx.Graph([("Example:A", 1)])
94
+ with pytest.raises(ValueError):
95
+ nx.nx_pydot.to_pydot(G)
96
+ with pytest.raises(ValueError):
97
+ nx.nx_pydot.pydot_layout(G)
98
+
99
+ G = nx.Graph()
100
+ G.add_node("1.2", style="filled", fillcolor="red:yellow")
101
+ with pytest.raises(ValueError):
102
+ nx.nx_pydot.to_pydot(G)
103
+ G.remove_node("1.2")
104
+ G.add_node("1.2", style="filled", fillcolor='"red:yellow"')
105
+ assert (
106
+ G.nodes.data() == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes.data()
107
+ )
108
+
109
+ G = nx.DiGraph()
110
+ G.add_edge("1", "2", foo="bar:1")
111
+ with pytest.raises(ValueError):
112
+ nx.nx_pydot.to_pydot(G)
113
+ G = nx.DiGraph()
114
+ G.add_edge("1", "2", foo='"bar:1"')
115
+ assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"]
116
+
117
+ G = nx.MultiGraph()
118
+ G.add_edge("1", "2", foo="b:1")
119
+ G.add_edge("1", "2", bar="foo:foo")
120
+ with pytest.raises(ValueError):
121
+ nx.nx_pydot.to_pydot(G)
122
+ G = nx.MultiGraph()
123
+ G.add_edge("1", "2", foo='"b:1"')
124
+ G.add_edge("1", "2", bar='"foo:foo"')
125
+ # Keys as integers aren't preserved in the conversion. They are read as strings.
126
+ assert [attr for _, _, attr in G.edges.data()] == [
127
+ attr
128
+ for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
129
+ ]
130
+
131
+ G = nx.Graph()
132
+ G.add_edge("1", "2")
133
+ G["1"]["2"]["f:oo"] = "bar"
134
+ with pytest.raises(ValueError):
135
+ nx.nx_pydot.to_pydot(G)
136
+ G = nx.Graph()
137
+ G.add_edge("1", "2")
138
+ G["1"]["2"]['"f:oo"'] = "bar"
139
+ assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"]
140
+
141
+ G = nx.Graph([('"Example:A"', 1)])
142
+ layout = nx.nx_pydot.pydot_layout(G)
143
+ assert isinstance(layout, dict)
144
+
145
+
146
+ @pytest.mark.parametrize(
147
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
148
+ )
149
+ def test_hashable_pydot(graph_type):
150
+ # gh-5790
151
+ G = graph_type()
152
+ G.add_edge("5", frozenset([1]), t='"Example:A"', l=False)
153
+ G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"]))
154
+ G.add_edge("node", (3, 3), w="string")
155
+
156
+ assert [
157
+ {"t": '"Example:A"', "l": "False"},
158
+ {"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"},
159
+ {"w": "string"},
160
+ ] == [
161
+ attr
162
+ for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
163
+ ]
164
+
165
+ assert {str(i) for i in G.nodes()} == set(
166
+ nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes
167
+ )
168
+
169
+
170
+ def test_pydot_numerical_name():
171
+ G = nx.Graph()
172
+ G.add_edges_from([("A", "B"), (0, 1)])
173
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
174
+ assert isinstance(graph_layout, dict)
175
+ assert "0" not in graph_layout
176
+ assert 0 in graph_layout
177
+ assert "1" not in graph_layout
178
+ assert 1 in graph_layout
179
+ assert "A" in graph_layout
180
+ assert "B" in graph_layout
llmeval-env/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for matplotlib drawing functions."""
2
+ import itertools
3
+ import os
4
+ import warnings
5
+
6
+ import pytest
7
+
8
+ mpl = pytest.importorskip("matplotlib")
9
+ np = pytest.importorskip("numpy")
10
+ mpl.use("PS")
11
+ plt = pytest.importorskip("matplotlib.pyplot")
12
+ plt.rcParams["text.usetex"] = False
13
+
14
+
15
+ import networkx as nx
16
+
17
+ barbell = nx.barbell_graph(4, 6)
18
+
19
+
20
+ def test_draw():
21
+ try:
22
+ functions = [
23
+ nx.draw_circular,
24
+ nx.draw_kamada_kawai,
25
+ nx.draw_planar,
26
+ nx.draw_random,
27
+ nx.draw_spectral,
28
+ nx.draw_spring,
29
+ nx.draw_shell,
30
+ ]
31
+ options = [{"node_color": "black", "node_size": 100, "width": 3}]
32
+ for function, option in itertools.product(functions, options):
33
+ function(barbell, **option)
34
+ plt.savefig("test.ps")
35
+ except ModuleNotFoundError: # draw_kamada_kawai requires scipy
36
+ pass
37
+ finally:
38
+ try:
39
+ os.unlink("test.ps")
40
+ except OSError:
41
+ pass
42
+
43
+
44
+ def test_draw_shell_nlist():
45
+ try:
46
+ nlist = [list(range(4)), list(range(4, 10)), list(range(10, 14))]
47
+ nx.draw_shell(barbell, nlist=nlist)
48
+ plt.savefig("test.ps")
49
+ finally:
50
+ try:
51
+ os.unlink("test.ps")
52
+ except OSError:
53
+ pass
54
+
55
+
56
+ def test_edge_colormap():
57
+ colors = range(barbell.number_of_edges())
58
+ nx.draw_spring(
59
+ barbell, edge_color=colors, width=4, edge_cmap=plt.cm.Blues, with_labels=True
60
+ )
61
+ # plt.show()
62
+
63
+
64
+ def test_arrows():
65
+ nx.draw_spring(barbell.to_directed())
66
+ # plt.show()
67
+
68
+
69
+ @pytest.mark.parametrize(
70
+ ("edge_color", "expected"),
71
+ (
72
+ (None, "black"), # Default
73
+ ("r", "red"), # Non-default color string
74
+ (["r"], "red"), # Single non-default color in a list
75
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
76
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
77
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
78
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
79
+ ("#0000ff", "blue"), # single color hex code
80
+ (["#0000ff"], "blue"), # hex code in list
81
+ ),
82
+ )
83
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
84
+ def test_single_edge_color_undirected(edge_color, expected, edgelist):
85
+ """Tests ways of specifying all edges have a single color for edges
86
+ drawn with a LineCollection"""
87
+
88
+ G = nx.path_graph(3)
89
+ drawn_edges = nx.draw_networkx_edges(
90
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
91
+ )
92
+ assert mpl.colors.same_color(drawn_edges.get_color(), expected)
93
+
94
+
95
+ @pytest.mark.parametrize(
96
+ ("edge_color", "expected"),
97
+ (
98
+ (None, "black"), # Default
99
+ ("r", "red"), # Non-default color string
100
+ (["r"], "red"), # Single non-default color in a list
101
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
102
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
103
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
104
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
105
+ ("#0000ff", "blue"), # single color hex code
106
+ (["#0000ff"], "blue"), # hex code in list
107
+ ),
108
+ )
109
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
110
+ def test_single_edge_color_directed(edge_color, expected, edgelist):
111
+ """Tests ways of specifying all edges have a single color for edges drawn
112
+ with FancyArrowPatches"""
113
+
114
+ G = nx.path_graph(3, create_using=nx.DiGraph)
115
+ drawn_edges = nx.draw_networkx_edges(
116
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
117
+ )
118
+ for fap in drawn_edges:
119
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
120
+
121
+
122
+ def test_edge_color_tuple_interpretation():
123
+ """If edge_color is a sequence with the same length as edgelist, then each
124
+ value in edge_color is mapped onto each edge via colormap."""
125
+ G = nx.path_graph(6, create_using=nx.DiGraph)
126
+ pos = {n: (n, n) for n in range(len(G))}
127
+
128
+ # num edges != 3 or 4 --> edge_color interpreted as rgb(a)
129
+ for ec in ((0, 0, 1), (0, 0, 1, 1)):
130
+ # More than 4 edges
131
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=ec)
132
+ for fap in drawn_edges:
133
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
134
+ # Fewer than 3 edges
135
+ drawn_edges = nx.draw_networkx_edges(
136
+ G, pos, edgelist=[(0, 1), (1, 2)], edge_color=ec
137
+ )
138
+ for fap in drawn_edges:
139
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
140
+
141
+ # num edges == 3, len(edge_color) == 4: interpreted as rgba
142
+ drawn_edges = nx.draw_networkx_edges(
143
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1, 1)
144
+ )
145
+ for fap in drawn_edges:
146
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
147
+
148
+ # num edges == 4, len(edge_color) == 3: interpreted as rgb
149
+ drawn_edges = nx.draw_networkx_edges(
150
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1)
151
+ )
152
+ for fap in drawn_edges:
153
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
154
+
155
+ # num edges == len(edge_color) == 3: interpreted with cmap, *not* as rgb
156
+ drawn_edges = nx.draw_networkx_edges(
157
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1)
158
+ )
159
+ assert mpl.colors.same_color(
160
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
161
+ )
162
+ for fap in drawn_edges:
163
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
164
+
165
+ # num edges == len(edge_color) == 4: interpreted with cmap, *not* as rgba
166
+ drawn_edges = nx.draw_networkx_edges(
167
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1, 1)
168
+ )
169
+ assert mpl.colors.same_color(
170
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
171
+ )
172
+ assert mpl.colors.same_color(
173
+ drawn_edges[2].get_edgecolor(), drawn_edges[3].get_edgecolor()
174
+ )
175
+ for fap in drawn_edges:
176
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
177
+
178
+
179
+ def test_fewer_edge_colors_than_num_edges_directed():
180
+ """Test that the edge colors are cycled when there are fewer specified
181
+ colors than edges."""
182
+ G = barbell.to_directed()
183
+ pos = nx.random_layout(barbell)
184
+ edgecolors = ("r", "g", "b")
185
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
186
+ for fap, expected in zip(drawn_edges, itertools.cycle(edgecolors)):
187
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
188
+
189
+
190
+ def test_more_edge_colors_than_num_edges_directed():
191
+ """Test that extra edge colors are ignored when there are more specified
192
+ colors than edges."""
193
+ G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges
194
+ pos = nx.random_layout(barbell)
195
+ edgecolors = ("r", "g", "b", "c") # 4 edge colors
196
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
197
+ for fap, expected in zip(drawn_edges, edgecolors[:-1]):
198
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
199
+
200
+
201
+ def test_edge_color_string_with_global_alpha_undirected():
202
+ edge_collection = nx.draw_networkx_edges(
203
+ barbell,
204
+ pos=nx.random_layout(barbell),
205
+ edgelist=[(0, 1), (1, 2)],
206
+ edge_color="purple",
207
+ alpha=0.2,
208
+ )
209
+ ec = edge_collection.get_color().squeeze() # as rgba tuple
210
+ assert len(edge_collection.get_paths()) == 2
211
+ assert mpl.colors.same_color(ec[:-1], "purple")
212
+ assert ec[-1] == 0.2
213
+
214
+
215
+ def test_edge_color_string_with_global_alpha_directed():
216
+ drawn_edges = nx.draw_networkx_edges(
217
+ barbell.to_directed(),
218
+ pos=nx.random_layout(barbell),
219
+ edgelist=[(0, 1), (1, 2)],
220
+ edge_color="purple",
221
+ alpha=0.2,
222
+ )
223
+ assert len(drawn_edges) == 2
224
+ for fap in drawn_edges:
225
+ ec = fap.get_edgecolor() # As rgba tuple
226
+ assert mpl.colors.same_color(ec[:-1], "purple")
227
+ assert ec[-1] == 0.2
228
+
229
+
230
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
231
+ def test_edge_width_default_value(graph_type):
232
+ """Test the default linewidth for edges drawn either via LineCollection or
233
+ FancyArrowPatches."""
234
+ G = nx.path_graph(2, create_using=graph_type)
235
+ pos = {n: (n, n) for n in range(len(G))}
236
+ drawn_edges = nx.draw_networkx_edges(G, pos)
237
+ if isinstance(drawn_edges, list): # directed case: list of FancyArrowPatch
238
+ drawn_edges = drawn_edges[0]
239
+ assert drawn_edges.get_linewidth() == 1
240
+
241
+
242
+ @pytest.mark.parametrize(
243
+ ("edgewidth", "expected"),
244
+ (
245
+ (3, 3), # single-value, non-default
246
+ ([3], 3), # Single value as a list
247
+ ),
248
+ )
249
+ def test_edge_width_single_value_undirected(edgewidth, expected):
250
+ G = nx.path_graph(4)
251
+ pos = {n: (n, n) for n in range(len(G))}
252
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
253
+ assert len(drawn_edges.get_paths()) == 3
254
+ assert drawn_edges.get_linewidth() == expected
255
+
256
+
257
+ @pytest.mark.parametrize(
258
+ ("edgewidth", "expected"),
259
+ (
260
+ (3, 3), # single-value, non-default
261
+ ([3], 3), # Single value as a list
262
+ ),
263
+ )
264
+ def test_edge_width_single_value_directed(edgewidth, expected):
265
+ G = nx.path_graph(4, create_using=nx.DiGraph)
266
+ pos = {n: (n, n) for n in range(len(G))}
267
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
268
+ assert len(drawn_edges) == 3
269
+ for fap in drawn_edges:
270
+ assert fap.get_linewidth() == expected
271
+
272
+
273
+ @pytest.mark.parametrize(
274
+ "edgelist",
275
+ (
276
+ [(0, 1), (1, 2), (2, 3)], # one width specification per edge
277
+ None, # fewer widths than edges - widths cycle
278
+ [(0, 1), (1, 2)], # More widths than edges - unused widths ignored
279
+ ),
280
+ )
281
+ def test_edge_width_sequence(edgelist):
282
+ G = barbell.to_directed()
283
+ pos = nx.random_layout(G)
284
+ widths = (0.5, 2.0, 12.0)
285
+ drawn_edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, width=widths)
286
+ for fap, expected_width in zip(drawn_edges, itertools.cycle(widths)):
287
+ assert fap.get_linewidth() == expected_width
288
+
289
+
290
+ def test_edge_color_with_edge_vmin_vmax():
291
+ """Test that edge_vmin and edge_vmax properly set the dynamic range of the
292
+ color map when num edges == len(edge_colors)."""
293
+ G = nx.path_graph(3, create_using=nx.DiGraph)
294
+ pos = nx.random_layout(G)
295
+ # Extract colors from the original (unscaled) colormap
296
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=[0, 1.0])
297
+ orig_colors = [e.get_edgecolor() for e in drawn_edges]
298
+ # Colors from scaled colormap
299
+ drawn_edges = nx.draw_networkx_edges(
300
+ G, pos, edge_color=[0.2, 0.8], edge_vmin=0.2, edge_vmax=0.8
301
+ )
302
+ scaled_colors = [e.get_edgecolor() for e in drawn_edges]
303
+ assert mpl.colors.same_color(orig_colors, scaled_colors)
304
+
305
+
306
+ def test_directed_edges_linestyle_default():
307
+ """Test default linestyle for edges drawn with FancyArrowPatches."""
308
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
309
+ pos = {n: (n, n) for n in range(len(G))}
310
+
311
+ # edge with default style
312
+ drawn_edges = nx.draw_networkx_edges(G, pos)
313
+ assert len(drawn_edges) == 3
314
+ for fap in drawn_edges:
315
+ assert fap.get_linestyle() == "solid"
316
+
317
+
318
+ @pytest.mark.parametrize(
319
+ "style",
320
+ (
321
+ "dashed", # edge with string style
322
+ "--", # edge with simplified string style
323
+ (1, (1, 1)), # edge with (offset, onoffseq) style
324
+ ),
325
+ )
326
+ def test_directed_edges_linestyle_single_value(style):
327
+ """Tests support for specifying linestyles with a single value to be applied to
328
+ all edges in ``draw_networkx_edges`` for FancyArrowPatch outputs
329
+ (e.g. directed edges)."""
330
+
331
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
332
+ pos = {n: (n, n) for n in range(len(G))}
333
+
334
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style)
335
+ assert len(drawn_edges) == 3
336
+ for fap in drawn_edges:
337
+ assert fap.get_linestyle() == style
338
+
339
+
340
+ @pytest.mark.parametrize(
341
+ "style_seq",
342
+ (
343
+ ["dashed"], # edge with string style in list
344
+ ["--"], # edge with simplified string style in list
345
+ [(1, (1, 1))], # edge with (offset, onoffseq) style in list
346
+ ["--", "-", ":"], # edges with styles for each edge
347
+ ["--", "-"], # edges with fewer styles than edges (styles cycle)
348
+ ["--", "-", ":", "-."], # edges with more styles than edges (extra unused)
349
+ ),
350
+ )
351
+ def test_directed_edges_linestyle_sequence(style_seq):
352
+ """Tests support for specifying linestyles with sequences in
353
+ ``draw_networkx_edges`` for FancyArrowPatch outputs (e.g. directed edges)."""
354
+
355
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
356
+ pos = {n: (n, n) for n in range(len(G))}
357
+
358
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style_seq)
359
+ assert len(drawn_edges) == 3
360
+ for fap, style in zip(drawn_edges, itertools.cycle(style_seq)):
361
+ assert fap.get_linestyle() == style
362
+
363
+
364
+ def test_labels_and_colors():
365
+ G = nx.cubical_graph()
366
+ pos = nx.spring_layout(G) # positions for all nodes
367
+ # nodes
368
+ nx.draw_networkx_nodes(
369
+ G, pos, nodelist=[0, 1, 2, 3], node_color="r", node_size=500, alpha=0.75
370
+ )
371
+ nx.draw_networkx_nodes(
372
+ G,
373
+ pos,
374
+ nodelist=[4, 5, 6, 7],
375
+ node_color="b",
376
+ node_size=500,
377
+ alpha=[0.25, 0.5, 0.75, 1.0],
378
+ )
379
+ # edges
380
+ nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
381
+ nx.draw_networkx_edges(
382
+ G,
383
+ pos,
384
+ edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
385
+ width=8,
386
+ alpha=0.5,
387
+ edge_color="r",
388
+ )
389
+ nx.draw_networkx_edges(
390
+ G,
391
+ pos,
392
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
393
+ width=8,
394
+ alpha=0.5,
395
+ edge_color="b",
396
+ )
397
+ nx.draw_networkx_edges(
398
+ G,
399
+ pos,
400
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
401
+ arrows=True,
402
+ min_source_margin=0.5,
403
+ min_target_margin=0.75,
404
+ width=8,
405
+ edge_color="b",
406
+ )
407
+ # some math labels
408
+ labels = {}
409
+ labels[0] = r"$a$"
410
+ labels[1] = r"$b$"
411
+ labels[2] = r"$c$"
412
+ labels[3] = r"$d$"
413
+ labels[4] = r"$\alpha$"
414
+ labels[5] = r"$\beta$"
415
+ labels[6] = r"$\gamma$"
416
+ labels[7] = r"$\delta$"
417
+ nx.draw_networkx_labels(G, pos, labels, font_size=16)
418
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=None, rotate=False)
419
+ nx.draw_networkx_edge_labels(G, pos, edge_labels={(4, 5): "4-5"})
420
+ # plt.show()
421
+
422
+
423
+ @pytest.mark.mpl_image_compare
424
+ def test_house_with_colors():
425
+ G = nx.house_graph()
426
+ # explicitly set positions
427
+ fig, ax = plt.subplots()
428
+ pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
429
+
430
+ # Plot nodes with different properties for the "wall" and "roof" nodes
431
+ nx.draw_networkx_nodes(
432
+ G,
433
+ pos,
434
+ node_size=3000,
435
+ nodelist=[0, 1, 2, 3],
436
+ node_color="tab:blue",
437
+ )
438
+ nx.draw_networkx_nodes(
439
+ G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
440
+ )
441
+ nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
442
+ # Customize axes
443
+ ax.margins(0.11)
444
+ plt.tight_layout()
445
+ plt.axis("off")
446
+ return fig
447
+
448
+
449
+ def test_axes():
450
+ fig, ax = plt.subplots()
451
+ nx.draw(barbell, ax=ax)
452
+ nx.draw_networkx_edge_labels(barbell, nx.circular_layout(barbell), ax=ax)
453
+
454
+
455
+ def test_empty_graph():
456
+ G = nx.Graph()
457
+ nx.draw(G)
458
+
459
+
460
+ def test_draw_empty_nodes_return_values():
461
+ # See Issue #3833
462
+ import matplotlib.collections # call as mpl.collections
463
+
464
+ G = nx.Graph([(1, 2), (2, 3)])
465
+ DG = nx.DiGraph([(1, 2), (2, 3)])
466
+ pos = nx.circular_layout(G)
467
+ assert isinstance(
468
+ nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection
469
+ )
470
+ assert isinstance(
471
+ nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection
472
+ )
473
+
474
+ # drawing empty edges used to return an empty LineCollection or empty list.
475
+ # Now it is always an empty list (because edges are now lists of FancyArrows)
476
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=True) == []
477
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=False) == []
478
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=False) == []
479
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=True) == []
480
+
481
+
482
+ def test_multigraph_edgelist_tuples():
483
+ # See Issue #3295
484
+ G = nx.path_graph(3, create_using=nx.MultiDiGraph)
485
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)])
486
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20, 0])
487
+
488
+
489
+ def test_alpha_iter():
490
+ pos = nx.random_layout(barbell)
491
+ fig = plt.figure()
492
+ # with fewer alpha elements than nodes
493
+ fig.add_subplot(131) # Each test in a new axis object
494
+ nx.draw_networkx_nodes(barbell, pos, alpha=[0.1, 0.2])
495
+ # with equal alpha elements and nodes
496
+ num_nodes = len(barbell.nodes)
497
+ alpha = [x / num_nodes for x in range(num_nodes)]
498
+ colors = range(num_nodes)
499
+ fig.add_subplot(132)
500
+ nx.draw_networkx_nodes(barbell, pos, node_color=colors, alpha=alpha)
501
+ # with more alpha elements than nodes
502
+ alpha.append(1)
503
+ fig.add_subplot(133)
504
+ nx.draw_networkx_nodes(barbell, pos, alpha=alpha)
505
+
506
+
507
+ def test_error_invalid_kwds():
508
+ with pytest.raises(ValueError, match="Received invalid argument"):
509
+ nx.draw(barbell, foo="bar")
510
+
511
+
512
+ def test_draw_networkx_arrowsize_incorrect_size():
513
+ G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 3)])
514
+ arrowsize = [1, 2, 3]
515
+ with pytest.raises(
516
+ ValueError, match="arrowsize should have the same length as edgelist"
517
+ ):
518
+ nx.draw(G, arrowsize=arrowsize)
519
+
520
+
521
+ @pytest.mark.parametrize("arrowsize", (30, [10, 20, 30]))
522
+ def test_draw_edges_arrowsize(arrowsize):
523
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
524
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
525
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowsize=arrowsize)
526
+
527
+ arrowsize = itertools.repeat(arrowsize) if isinstance(arrowsize, int) else arrowsize
528
+
529
+ for fap, expected in zip(edges, arrowsize):
530
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
531
+ assert fap.get_mutation_scale() == expected
532
+
533
+
534
+ def test_np_edgelist():
535
+ # see issue #4129
536
+ nx.draw_networkx(barbell, edgelist=np.array([(0, 2), (0, 3)]))
537
+
538
+
539
+ def test_draw_nodes_missing_node_from_position():
540
+ G = nx.path_graph(3)
541
+ pos = {0: (0, 0), 1: (1, 1)} # No position for node 2
542
+ with pytest.raises(nx.NetworkXError, match="has no position"):
543
+ nx.draw_networkx_nodes(G, pos)
544
+
545
+
546
+ # NOTE: parametrizing on marker to test both branches of internal
547
+ # nx.draw_networkx_edges.to_marker_edge function
548
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
549
+ def test_draw_edges_min_source_target_margins(node_shape):
550
+ """Test that there is a wider gap between the node and the start of an
551
+ incident edge when min_source_margin is specified.
552
+
553
+ This test checks that the use of min_{source/target}_margin kwargs result
554
+ in shorter (more padding) between the edges and source and target nodes.
555
+ As a crude visual example, let 's' and 't' represent source and target
556
+ nodes, respectively:
557
+
558
+ Default:
559
+ s-----------------------------t
560
+
561
+ With margins:
562
+ s ----------------------- t
563
+
564
+ """
565
+ # Create a single axis object to get consistent pixel coords across
566
+ # multiple draws
567
+ fig, ax = plt.subplots()
568
+ G = nx.DiGraph([(0, 1)])
569
+ pos = {0: (0, 0), 1: (1, 0)} # horizontal layout
570
+ # Get leftmost and rightmost points of the FancyArrowPatch object
571
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
572
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)[0]
573
+ default_extent = default_patch.get_extents().corners()[::2, 0]
574
+ # Now, do the same but with "padding" for the source and target via the
575
+ # min_{source/target}_margin kwargs
576
+ padded_patch = nx.draw_networkx_edges(
577
+ G,
578
+ pos,
579
+ ax=ax,
580
+ node_shape=node_shape,
581
+ min_source_margin=100,
582
+ min_target_margin=100,
583
+ )[0]
584
+ padded_extent = padded_patch.get_extents().corners()[::2, 0]
585
+
586
+ # With padding, the left-most extent of the edge should be further to the
587
+ # right
588
+ assert padded_extent[0] > default_extent[0]
589
+ # And the rightmost extent of the edge, further to the left
590
+ assert padded_extent[1] < default_extent[1]
591
+
592
+
593
+ def test_nonzero_selfloop_with_single_node():
594
+ """Ensure that selfloop extent is non-zero when there is only one node."""
595
+ # Create explicit axis object for test
596
+ fig, ax = plt.subplots()
597
+ # Graph with single node + self loop
598
+ G = nx.DiGraph()
599
+ G.add_node(0)
600
+ G.add_edge(0, 0)
601
+ # Draw
602
+ patch = nx.draw_networkx_edges(G, {0: (0, 0)})[0]
603
+ # The resulting patch must have non-zero extent
604
+ bbox = patch.get_extents()
605
+ assert bbox.width > 0 and bbox.height > 0
606
+ # Cleanup
607
+ plt.delaxes(ax)
608
+ plt.close()
609
+
610
+
611
+ def test_nonzero_selfloop_with_single_edge_in_edgelist():
612
+ """Ensure that selfloop extent is non-zero when only a single edge is
613
+ specified in the edgelist.
614
+ """
615
+ # Create explicit axis object for test
616
+ fig, ax = plt.subplots()
617
+ # Graph with selfloop
618
+ G = nx.path_graph(2, create_using=nx.DiGraph)
619
+ G.add_edge(1, 1)
620
+ pos = {n: (n, n) for n in G.nodes}
621
+ # Draw only the selfloop edge via the `edgelist` kwarg
622
+ patch = nx.draw_networkx_edges(G, pos, edgelist=[(1, 1)])[0]
623
+ # The resulting patch must have non-zero extent
624
+ bbox = patch.get_extents()
625
+ assert bbox.width > 0 and bbox.height > 0
626
+ # Cleanup
627
+ plt.delaxes(ax)
628
+ plt.close()
629
+
630
+
631
+ def test_apply_alpha():
632
+ """Test apply_alpha when there is a mismatch between the number of
633
+ supplied colors and elements.
634
+ """
635
+ nodelist = [0, 1, 2]
636
+ colorlist = ["r", "g", "b"]
637
+ alpha = 0.5
638
+ rgba_colors = nx.drawing.nx_pylab.apply_alpha(colorlist, alpha, nodelist)
639
+ assert all(rgba_colors[:, -1] == alpha)
640
+
641
+
642
+ def test_draw_edges_toggling_with_arrows_kwarg():
643
+ """
644
+ The `arrows` keyword argument is used as a 3-way switch to select which
645
+ type of object to use for drawing edges:
646
+ - ``arrows=None`` -> default (FancyArrowPatches for directed, else LineCollection)
647
+ - ``arrows=True`` -> FancyArrowPatches
648
+ - ``arrows=False`` -> LineCollection
649
+ """
650
+ import matplotlib.collections
651
+ import matplotlib.patches
652
+
653
+ UG = nx.path_graph(3)
654
+ DG = nx.path_graph(3, create_using=nx.DiGraph)
655
+ pos = {n: (n, n) for n in UG}
656
+
657
+ # Use FancyArrowPatches when arrows=True, regardless of graph type
658
+ for G in (UG, DG):
659
+ edges = nx.draw_networkx_edges(G, pos, arrows=True)
660
+ assert len(edges) == len(G.edges)
661
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
662
+
663
+ # Use LineCollection when arrows=False, regardless of graph type
664
+ for G in (UG, DG):
665
+ edges = nx.draw_networkx_edges(G, pos, arrows=False)
666
+ assert isinstance(edges, mpl.collections.LineCollection)
667
+
668
+ # Default behavior when arrows=None: FAPs for directed, LC's for undirected
669
+ edges = nx.draw_networkx_edges(UG, pos)
670
+ assert isinstance(edges, mpl.collections.LineCollection)
671
+ edges = nx.draw_networkx_edges(DG, pos)
672
+ assert len(edges) == len(G.edges)
673
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
674
+
675
+
676
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
677
+ def test_draw_networkx_arrows_default_undirected(drawing_func):
678
+ import matplotlib.collections
679
+
680
+ G = nx.path_graph(3)
681
+ fig, ax = plt.subplots()
682
+ drawing_func(G, ax=ax)
683
+ assert any(isinstance(c, mpl.collections.LineCollection) for c in ax.collections)
684
+ assert not ax.patches
685
+ plt.delaxes(ax)
686
+ plt.close()
687
+
688
+
689
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
690
+ def test_draw_networkx_arrows_default_directed(drawing_func):
691
+ import matplotlib.collections
692
+
693
+ G = nx.path_graph(3, create_using=nx.DiGraph)
694
+ fig, ax = plt.subplots()
695
+ drawing_func(G, ax=ax)
696
+ assert not any(
697
+ isinstance(c, mpl.collections.LineCollection) for c in ax.collections
698
+ )
699
+ assert ax.patches
700
+ plt.delaxes(ax)
701
+ plt.close()
702
+
703
+
704
+ def test_edgelist_kwarg_not_ignored():
705
+ # See gh-4994
706
+ G = nx.path_graph(3)
707
+ G.add_edge(0, 0)
708
+ fig, ax = plt.subplots()
709
+ nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax) # Exclude self-loop from edgelist
710
+ assert not ax.patches
711
+ plt.delaxes(ax)
712
+ plt.close()
713
+
714
+
715
+ @pytest.mark.parametrize(
716
+ ("G", "expected_n_edges"),
717
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
718
+ )
719
+ def test_draw_networkx_edges_multiedge_connectionstyle(G, expected_n_edges):
720
+ """Draws edges correctly for 3 types of graphs and checks for valid length"""
721
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
722
+ G.add_edge(u, v, weight=round(i / 3, 2))
723
+ pos = {n: (n, n) for n in G}
724
+ # Raises on insuficient connectionstyle length
725
+ for conn_style in [
726
+ "arc3,rad=0.1",
727
+ ["arc3,rad=0.1", "arc3,rad=0.1"],
728
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.2"],
729
+ ]:
730
+ nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
731
+ arrows = nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
732
+ assert len(arrows) == expected_n_edges
733
+
734
+
735
+ @pytest.mark.parametrize(
736
+ ("G", "expected_n_edges"),
737
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
738
+ )
739
+ def test_draw_networkx_edge_labels_multiedge_connectionstyle(G, expected_n_edges):
740
+ """Draws labels correctly for 3 types of graphs and checks for valid length and class names"""
741
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
742
+ G.add_edge(u, v, weight=round(i / 3, 2))
743
+ pos = {n: (n, n) for n in G}
744
+ # Raises on insuficient connectionstyle length
745
+ arrows = nx.draw_networkx_edges(
746
+ G, pos, connectionstyle=["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"]
747
+ )
748
+ for conn_style in [
749
+ "arc3,rad=0.1",
750
+ ["arc3,rad=0.1", "arc3,rad=0.2"],
751
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"],
752
+ ]:
753
+ text_items = nx.draw_networkx_edge_labels(G, pos, connectionstyle=conn_style)
754
+ assert len(text_items) == expected_n_edges
755
+ for ti in text_items.values():
756
+ assert ti.__class__.__name__ == "CurvedArrowText"
757
+
758
+
759
+ def test_draw_networkx_edge_label_multiedge():
760
+ G = nx.MultiGraph()
761
+ G.add_edge(0, 1, weight=10)
762
+ G.add_edge(0, 1, weight=20)
763
+ edge_labels = nx.get_edge_attributes(G, "weight") # Includes edge keys
764
+ pos = {n: (n, n) for n in G}
765
+ text_items = nx.draw_networkx_edge_labels(
766
+ G,
767
+ pos,
768
+ edge_labels=edge_labels,
769
+ connectionstyle=["arc3,rad=0.1", "arc3,rad=0.2"],
770
+ )
771
+ assert len(text_items) == 2
772
+
773
+
774
+ def test_draw_networkx_edge_label_empty_dict():
775
+ """Regression test for draw_networkx_edge_labels with empty dict. See
776
+ gh-5372."""
777
+ G = nx.path_graph(3)
778
+ pos = {n: (n, n) for n in G.nodes}
779
+ assert nx.draw_networkx_edge_labels(G, pos, edge_labels={}) == {}
780
+
781
+
782
+ def test_draw_networkx_edges_undirected_selfloop_colors():
783
+ """When an edgelist is supplied along with a sequence of colors, check that
784
+ the self-loops have the correct colors."""
785
+ fig, ax = plt.subplots()
786
+ # Edge list and corresponding colors
787
+ edgelist = [(1, 3), (1, 2), (2, 3), (1, 1), (3, 3), (2, 2)]
788
+ edge_colors = ["pink", "cyan", "black", "red", "blue", "green"]
789
+
790
+ G = nx.Graph(edgelist)
791
+ pos = {n: (n, n) for n in G.nodes}
792
+ nx.draw_networkx_edges(G, pos, ax=ax, edgelist=edgelist, edge_color=edge_colors)
793
+
794
+ # Verify that there are three fancy arrow patches (1 per self loop)
795
+ assert len(ax.patches) == 3
796
+
797
+ # These are points that should be contained in the self loops. For example,
798
+ # sl_points[0] will be (1, 1.1), which is inside the "path" of the first
799
+ # self-loop but outside the others
800
+ sl_points = np.array(edgelist[-3:]) + np.array([0, 0.1])
801
+
802
+ # Check that the mapping between self-loop locations and their colors is
803
+ # correct
804
+ for fap, clr, slp in zip(ax.patches, edge_colors[-3:], sl_points):
805
+ assert fap.get_path().contains_point(slp)
806
+ assert mpl.colors.same_color(fap.get_edgecolor(), clr)
807
+ plt.delaxes(ax)
808
+ plt.close()
809
+
810
+
811
+ @pytest.mark.parametrize(
812
+ "fap_only_kwarg", # Non-default values for kwargs that only apply to FAPs
813
+ (
814
+ {"arrowstyle": "-"},
815
+ {"arrowsize": 20},
816
+ {"connectionstyle": "arc3,rad=0.2"},
817
+ {"min_source_margin": 10},
818
+ {"min_target_margin": 10},
819
+ ),
820
+ )
821
+ def test_user_warnings_for_unused_edge_drawing_kwargs(fap_only_kwarg):
822
+ """Users should get a warning when they specify a non-default value for
823
+ one of the kwargs that applies only to edges drawn with FancyArrowPatches,
824
+ but FancyArrowPatches aren't being used under the hood."""
825
+ G = nx.path_graph(3)
826
+ pos = {n: (n, n) for n in G}
827
+ fig, ax = plt.subplots()
828
+ # By default, an undirected graph will use LineCollection to represent
829
+ # the edges
830
+ kwarg_name = list(fap_only_kwarg.keys())[0]
831
+ with pytest.warns(
832
+ UserWarning, match=f"\n\nThe {kwarg_name} keyword argument is not applicable"
833
+ ):
834
+ nx.draw_networkx_edges(G, pos, ax=ax, **fap_only_kwarg)
835
+ # FancyArrowPatches are always used when `arrows=True` is specified.
836
+ # Check that warnings are *not* raised in this case
837
+ with warnings.catch_warnings():
838
+ # Escalate warnings -> errors so tests fail if warnings are raised
839
+ warnings.simplefilter("error")
840
+ nx.draw_networkx_edges(G, pos, ax=ax, arrows=True, **fap_only_kwarg)
841
+
842
+ plt.delaxes(ax)
843
+ plt.close()
844
+
845
+
846
+ @pytest.mark.parametrize("draw_fn", (nx.draw, nx.draw_circular))
847
+ def test_no_warning_on_default_draw_arrowstyle(draw_fn):
848
+ # See gh-7284
849
+ fig, ax = plt.subplots()
850
+ G = nx.cycle_graph(5)
851
+ with warnings.catch_warnings(record=True) as w:
852
+ draw_fn(G, ax=ax)
853
+ assert len(w) == 0
854
+
855
+ plt.delaxes(ax)
856
+ plt.close()
857
+
858
+
859
+ @pytest.mark.parametrize("hide_ticks", [False, True])
860
+ @pytest.mark.parametrize(
861
+ "method",
862
+ [
863
+ nx.draw_networkx,
864
+ nx.draw_networkx_edge_labels,
865
+ nx.draw_networkx_edges,
866
+ nx.draw_networkx_labels,
867
+ nx.draw_networkx_nodes,
868
+ ],
869
+ )
870
+ def test_hide_ticks(method, hide_ticks):
871
+ G = nx.path_graph(3)
872
+ pos = {n: (n, n) for n in G.nodes}
873
+ _, ax = plt.subplots()
874
+ method(G, pos=pos, ax=ax, hide_ticks=hide_ticks)
875
+ for axis in [ax.xaxis, ax.yaxis]:
876
+ assert bool(axis.get_ticklabels()) != hide_ticks
877
+
878
+ plt.delaxes(ax)
879
+ plt.close()
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (730 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc ADDED
Binary file (8.35 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/edgelist.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc ADDED
Binary file (24.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc ADDED
Binary file (28.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/leda.cpython-310.pyc ADDED
Binary file (2.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc ADDED
Binary file (9.53 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc ADDED
Binary file (6.77 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/sparse6.cpython-310.pyc ADDED
Binary file (9.79 kB). View file
 
llmeval-env/lib/python3.10/site-packages/networkx/readwrite/__pycache__/text.cpython-310.pyc ADDED
Binary file (23 kB). View file