ZTWHHH commited on
Commit
ff7cc17
·
verified ·
1 Parent(s): c9ed4f9

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. .gitattributes +1 -0
  2. deepseek/lib/python3.10/site-packages/networkx/__pycache__/__init__.cpython-310.pyc +0 -0
  3. deepseek/lib/python3.10/site-packages/networkx/__pycache__/conftest.cpython-310.pyc +0 -0
  4. deepseek/lib/python3.10/site-packages/networkx/__pycache__/convert.cpython-310.pyc +0 -0
  5. deepseek/lib/python3.10/site-packages/networkx/__pycache__/convert_matrix.cpython-310.pyc +0 -0
  6. deepseek/lib/python3.10/site-packages/networkx/__pycache__/exception.cpython-310.pyc +0 -0
  7. deepseek/lib/python3.10/site-packages/networkx/__pycache__/lazy_imports.cpython-310.pyc +0 -0
  8. deepseek/lib/python3.10/site-packages/networkx/__pycache__/relabel.cpython-310.pyc +0 -0
  9. deepseek/lib/python3.10/site-packages/networkx/classes/__pycache__/filters.cpython-310.pyc +0 -0
  10. deepseek/lib/python3.10/site-packages/networkx/classes/__pycache__/multidigraph.cpython-310.pyc +0 -0
  11. deepseek/lib/python3.10/site-packages/networkx/classes/coreviews.py +431 -0
  12. deepseek/lib/python3.10/site-packages/networkx/classes/digraph.py +1352 -0
  13. deepseek/lib/python3.10/site-packages/networkx/classes/filters.py +95 -0
  14. deepseek/lib/python3.10/site-packages/networkx/classes/function.py +1407 -0
  15. deepseek/lib/python3.10/site-packages/networkx/classes/graph.py +2058 -0
  16. deepseek/lib/python3.10/site-packages/networkx/classes/multidigraph.py +966 -0
  17. deepseek/lib/python3.10/site-packages/networkx/classes/multigraph.py +1283 -0
  18. deepseek/lib/python3.10/site-packages/networkx/classes/reportviews.py +1447 -0
  19. deepseek/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py +185 -0
  20. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_graphviews.py +350 -0
  21. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_multigraph.py +528 -0
  22. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_special.py +131 -0
  23. deepseek/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc +0 -0
  24. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc +0 -0
  25. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc +0 -0
  26. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/edgelist.cpython-310.pyc +0 -0
  27. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc +0 -0
  28. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc +0 -0
  29. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc +0 -0
  30. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc +0 -0
  31. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc +0 -0
  32. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc +0 -0
  33. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc +0 -0
  34. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/sparse6.cpython-310.pyc +0 -0
  35. deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/text.cpython-310.pyc +0 -0
  36. deepseek/lib/python3.10/site-packages/networkx/readwrite/gml.py +879 -0
  37. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/__init__.cpython-310.pyc +0 -0
  38. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/adjacency.cpython-310.pyc +0 -0
  39. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/tree.cpython-310.pyc +0 -0
  40. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/adjacency.py +156 -0
  41. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/cytoscape.py +178 -0
  42. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/node_link.py +330 -0
  43. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_adjacency.cpython-310.pyc +0 -0
  44. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_cytoscape.cpython-310.pyc +0 -0
  45. deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/tests/test_adjacency.py +78 -0
  46. deepseek/lib/python3.10/site-packages/networkx/readwrite/pajek.py +286 -0
  47. deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  48. deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/test_graphml.cpython-310.pyc +0 -0
  49. deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/test_text.cpython-310.pyc +0 -0
  50. deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/test_gml.py +744 -0
.gitattributes CHANGED
@@ -1425,3 +1425,4 @@ deepseek/lib/python3.10/site-packages/ray/_private/runtime_env/agent/thirdparty_
1425
  deepseek/lib/python3.10/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1426
  evalkit_tf433/lib/python3.10/site-packages/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1427
  deepseek/lib/python3.10/site-packages/pyarrow/_parquet.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
1425
  deepseek/lib/python3.10/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1426
  evalkit_tf433/lib/python3.10/site-packages/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1427
  deepseek/lib/python3.10/site-packages/pyarrow/_parquet.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1428
+ deepseek/lib/python3.10/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
deepseek/lib/python3.10/site-packages/networkx/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.29 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (6.03 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/__pycache__/convert.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/__pycache__/convert_matrix.cpython-310.pyc ADDED
Binary file (41.2 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/__pycache__/exception.cpython-310.pyc ADDED
Binary file (4.76 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/__pycache__/lazy_imports.cpython-310.pyc ADDED
Binary file (5.85 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/__pycache__/relabel.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/__pycache__/filters.cpython-310.pyc ADDED
Binary file (5.02 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/__pycache__/multidigraph.cpython-310.pyc ADDED
Binary file (36 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/coreviews.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Views of core data structures such as nested Mappings (e.g. dict-of-dicts).
2
+ These ``Views`` often restrict element access, with either the entire view or
3
+ layers of nested mappings being read-only.
4
+ """
5
+
6
+ from collections.abc import Mapping
7
+
8
+ __all__ = [
9
+ "AtlasView",
10
+ "AdjacencyView",
11
+ "MultiAdjacencyView",
12
+ "UnionAtlas",
13
+ "UnionAdjacency",
14
+ "UnionMultiInner",
15
+ "UnionMultiAdjacency",
16
+ "FilterAtlas",
17
+ "FilterAdjacency",
18
+ "FilterMultiInner",
19
+ "FilterMultiAdjacency",
20
+ ]
21
+
22
+
23
+ class AtlasView(Mapping):
24
+ """An AtlasView is a Read-only Mapping of Mappings.
25
+
26
+ It is a View into a dict-of-dict data structure.
27
+ The inner level of dict is read-write. But the
28
+ outer level is read-only.
29
+
30
+ See Also
31
+ ========
32
+ AdjacencyView: View into dict-of-dict-of-dict
33
+ MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
34
+ """
35
+
36
+ __slots__ = ("_atlas",)
37
+
38
+ def __getstate__(self):
39
+ return {"_atlas": self._atlas}
40
+
41
+ def __setstate__(self, state):
42
+ self._atlas = state["_atlas"]
43
+
44
+ def __init__(self, d):
45
+ self._atlas = d
46
+
47
+ def __len__(self):
48
+ return len(self._atlas)
49
+
50
+ def __iter__(self):
51
+ return iter(self._atlas)
52
+
53
+ def __getitem__(self, key):
54
+ return self._atlas[key]
55
+
56
+ def copy(self):
57
+ return {n: self[n].copy() for n in self._atlas}
58
+
59
+ def __str__(self):
60
+ return str(self._atlas) # {nbr: self[nbr] for nbr in self})
61
+
62
+ def __repr__(self):
63
+ return f"{self.__class__.__name__}({self._atlas!r})"
64
+
65
+
66
+ class AdjacencyView(AtlasView):
67
+ """An AdjacencyView is a Read-only Map of Maps of Maps.
68
+
69
+ It is a View into a dict-of-dict-of-dict data structure.
70
+ The inner level of dict is read-write. But the
71
+ outer levels are read-only.
72
+
73
+ See Also
74
+ ========
75
+ AtlasView: View into dict-of-dict
76
+ MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
77
+ """
78
+
79
+ __slots__ = () # Still uses AtlasView slots names _atlas
80
+
81
+ def __getitem__(self, name):
82
+ return AtlasView(self._atlas[name])
83
+
84
+ def copy(self):
85
+ return {n: self[n].copy() for n in self._atlas}
86
+
87
+
88
+ class MultiAdjacencyView(AdjacencyView):
89
+ """An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.
90
+
91
+ It is a View into a dict-of-dict-of-dict-of-dict data structure.
92
+ The inner level of dict is read-write. But the
93
+ outer levels are read-only.
94
+
95
+ See Also
96
+ ========
97
+ AtlasView: View into dict-of-dict
98
+ AdjacencyView: View into dict-of-dict-of-dict
99
+ """
100
+
101
+ __slots__ = () # Still uses AtlasView slots names _atlas
102
+
103
+ def __getitem__(self, name):
104
+ return AdjacencyView(self._atlas[name])
105
+
106
+ def copy(self):
107
+ return {n: self[n].copy() for n in self._atlas}
108
+
109
+
110
+ class UnionAtlas(Mapping):
111
+ """A read-only union of two atlases (dict-of-dict).
112
+
113
+ The two dict-of-dicts represent the inner dict of
114
+ an Adjacency: `G.succ[node]` and `G.pred[node]`.
115
+ The inner level of dict of both hold attribute key:value
116
+ pairs and is read-write. But the outer level is read-only.
117
+
118
+ See Also
119
+ ========
120
+ UnionAdjacency: View into dict-of-dict-of-dict
121
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
122
+ """
123
+
124
+ __slots__ = ("_succ", "_pred")
125
+
126
+ def __getstate__(self):
127
+ return {"_succ": self._succ, "_pred": self._pred}
128
+
129
+ def __setstate__(self, state):
130
+ self._succ = state["_succ"]
131
+ self._pred = state["_pred"]
132
+
133
+ def __init__(self, succ, pred):
134
+ self._succ = succ
135
+ self._pred = pred
136
+
137
+ def __len__(self):
138
+ return len(self._succ.keys() | self._pred.keys())
139
+
140
+ def __iter__(self):
141
+ return iter(set(self._succ.keys()) | set(self._pred.keys()))
142
+
143
+ def __getitem__(self, key):
144
+ try:
145
+ return self._succ[key]
146
+ except KeyError:
147
+ return self._pred[key]
148
+
149
+ def copy(self):
150
+ result = {nbr: dd.copy() for nbr, dd in self._succ.items()}
151
+ for nbr, dd in self._pred.items():
152
+ if nbr in result:
153
+ result[nbr].update(dd)
154
+ else:
155
+ result[nbr] = dd.copy()
156
+ return result
157
+
158
+ def __str__(self):
159
+ return str({nbr: self[nbr] for nbr in self})
160
+
161
+ def __repr__(self):
162
+ return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
163
+
164
+
165
+ class UnionAdjacency(Mapping):
166
+ """A read-only union of dict Adjacencies as a Map of Maps of Maps.
167
+
168
+ The two input dict-of-dict-of-dicts represent the union of
169
+ `G.succ` and `G.pred`. Return values are UnionAtlas
170
+ The inner level of dict is read-write. But the
171
+ middle and outer levels are read-only.
172
+
173
+ succ : a dict-of-dict-of-dict {node: nbrdict}
174
+ pred : a dict-of-dict-of-dict {node: nbrdict}
175
+ The keys for the two dicts should be the same
176
+
177
+ See Also
178
+ ========
179
+ UnionAtlas: View into dict-of-dict
180
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
181
+ """
182
+
183
+ __slots__ = ("_succ", "_pred")
184
+
185
+ def __getstate__(self):
186
+ return {"_succ": self._succ, "_pred": self._pred}
187
+
188
+ def __setstate__(self, state):
189
+ self._succ = state["_succ"]
190
+ self._pred = state["_pred"]
191
+
192
+ def __init__(self, succ, pred):
193
+ # keys must be the same for two input dicts
194
+ assert len(set(succ.keys()) ^ set(pred.keys())) == 0
195
+ self._succ = succ
196
+ self._pred = pred
197
+
198
+ def __len__(self):
199
+ return len(self._succ) # length of each dict should be the same
200
+
201
+ def __iter__(self):
202
+ return iter(self._succ)
203
+
204
+ def __getitem__(self, nbr):
205
+ return UnionAtlas(self._succ[nbr], self._pred[nbr])
206
+
207
+ def copy(self):
208
+ return {n: self[n].copy() for n in self._succ}
209
+
210
+ def __str__(self):
211
+ return str({nbr: self[nbr] for nbr in self})
212
+
213
+ def __repr__(self):
214
+ return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
215
+
216
+
217
+ class UnionMultiInner(UnionAtlas):
218
+ """A read-only union of two inner dicts of MultiAdjacencies.
219
+
220
+ The two input dict-of-dict-of-dicts represent the union of
221
+ `G.succ[node]` and `G.pred[node]` for MultiDiGraphs.
222
+ Return values are UnionAtlas.
223
+ The inner level of dict is read-write. But the outer levels are read-only.
224
+
225
+ See Also
226
+ ========
227
+ UnionAtlas: View into dict-of-dict
228
+ UnionAdjacency: View into dict-of-dict-of-dict
229
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
230
+ """
231
+
232
+ __slots__ = () # Still uses UnionAtlas slots names _succ, _pred
233
+
234
+ def __getitem__(self, node):
235
+ in_succ = node in self._succ
236
+ in_pred = node in self._pred
237
+ if in_succ:
238
+ if in_pred:
239
+ return UnionAtlas(self._succ[node], self._pred[node])
240
+ return UnionAtlas(self._succ[node], {})
241
+ return UnionAtlas({}, self._pred[node])
242
+
243
+ def copy(self):
244
+ nodes = set(self._succ.keys()) | set(self._pred.keys())
245
+ return {n: self[n].copy() for n in nodes}
246
+
247
+
248
+ class UnionMultiAdjacency(UnionAdjacency):
249
+ """A read-only union of two dict MultiAdjacencies.
250
+
251
+ The two input dict-of-dict-of-dict-of-dicts represent the union of
252
+ `G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency.
253
+ The inner level of dict is read-write. But the outer levels are read-only.
254
+
255
+ See Also
256
+ ========
257
+ UnionAtlas: View into dict-of-dict
258
+ UnionMultiInner: View into dict-of-dict-of-dict
259
+ """
260
+
261
+ __slots__ = () # Still uses UnionAdjacency slots names _succ, _pred
262
+
263
+ def __getitem__(self, node):
264
+ return UnionMultiInner(self._succ[node], self._pred[node])
265
+
266
+
267
+ class FilterAtlas(Mapping): # nodedict, nbrdict, keydict
268
+ """A read-only Mapping of Mappings with filtering criteria for nodes.
269
+
270
+ It is a view into a dict-of-dict data structure, and it selects only
271
+ nodes that meet the criteria defined by ``NODE_OK``.
272
+
273
+ See Also
274
+ ========
275
+ FilterAdjacency
276
+ FilterMultiInner
277
+ FilterMultiAdjacency
278
+ """
279
+
280
+ def __init__(self, d, NODE_OK):
281
+ self._atlas = d
282
+ self.NODE_OK = NODE_OK
283
+
284
+ def __len__(self):
285
+ # check whether NODE_OK stores the number of nodes as `length`
286
+ # or the nodes themselves as a set `nodes`. If not, count the nodes.
287
+ if hasattr(self.NODE_OK, "length"):
288
+ return self.NODE_OK.length
289
+ if hasattr(self.NODE_OK, "nodes"):
290
+ return len(self.NODE_OK.nodes & self._atlas.keys())
291
+ return sum(1 for n in self._atlas if self.NODE_OK(n))
292
+
293
+ def __iter__(self):
294
+ try: # check that NODE_OK has attr 'nodes'
295
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
296
+ except AttributeError:
297
+ node_ok_shorter = False
298
+ if node_ok_shorter:
299
+ return (n for n in self.NODE_OK.nodes if n in self._atlas)
300
+ return (n for n in self._atlas if self.NODE_OK(n))
301
+
302
+ def __getitem__(self, key):
303
+ if key in self._atlas and self.NODE_OK(key):
304
+ return self._atlas[key]
305
+ raise KeyError(f"Key {key} not found")
306
+
307
+ def __str__(self):
308
+ return str({nbr: self[nbr] for nbr in self})
309
+
310
+ def __repr__(self):
311
+ return f"{self.__class__.__name__}({self._atlas!r}, {self.NODE_OK!r})"
312
+
313
+
314
+ class FilterAdjacency(Mapping): # edgedict
315
+ """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
316
+
317
+ It is a view into a dict-of-dict-of-dict data structure, and it selects nodes
318
+ and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``,
319
+ respectively.
320
+
321
+ See Also
322
+ ========
323
+ FilterAtlas
324
+ FilterMultiInner
325
+ FilterMultiAdjacency
326
+ """
327
+
328
+ def __init__(self, d, NODE_OK, EDGE_OK):
329
+ self._atlas = d
330
+ self.NODE_OK = NODE_OK
331
+ self.EDGE_OK = EDGE_OK
332
+
333
+ def __len__(self):
334
+ # check whether NODE_OK stores the number of nodes as `length`
335
+ # or the nodes themselves as a set `nodes`. If not, count the nodes.
336
+ if hasattr(self.NODE_OK, "length"):
337
+ return self.NODE_OK.length
338
+ if hasattr(self.NODE_OK, "nodes"):
339
+ return len(self.NODE_OK.nodes & self._atlas.keys())
340
+ return sum(1 for n in self._atlas if self.NODE_OK(n))
341
+
342
+ def __iter__(self):
343
+ try: # check that NODE_OK has attr 'nodes'
344
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
345
+ except AttributeError:
346
+ node_ok_shorter = False
347
+ if node_ok_shorter:
348
+ return (n for n in self.NODE_OK.nodes if n in self._atlas)
349
+ return (n for n in self._atlas if self.NODE_OK(n))
350
+
351
+ def __getitem__(self, node):
352
+ if node in self._atlas and self.NODE_OK(node):
353
+
354
+ def new_node_ok(nbr):
355
+ return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr)
356
+
357
+ return FilterAtlas(self._atlas[node], new_node_ok)
358
+ raise KeyError(f"Key {node} not found")
359
+
360
+ def __str__(self):
361
+ return str({nbr: self[nbr] for nbr in self})
362
+
363
+ def __repr__(self):
364
+ name = self.__class__.__name__
365
+ return f"{name}({self._atlas!r}, {self.NODE_OK!r}, {self.EDGE_OK!r})"
366
+
367
+
368
+ class FilterMultiInner(FilterAdjacency): # muliedge_seconddict
369
+ """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
370
+
371
+ It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes
372
+ and edges that meet specific criteria defined by ``NODE_OK`` and ``EDGE_OK``.
373
+
374
+ See Also
375
+ ========
376
+ FilterAtlas
377
+ FilterAdjacency
378
+ FilterMultiAdjacency
379
+ """
380
+
381
+ def __iter__(self):
382
+ try: # check that NODE_OK has attr 'nodes'
383
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
384
+ except AttributeError:
385
+ node_ok_shorter = False
386
+ if node_ok_shorter:
387
+ my_nodes = (n for n in self.NODE_OK.nodes if n in self._atlas)
388
+ else:
389
+ my_nodes = (n for n in self._atlas if self.NODE_OK(n))
390
+ for n in my_nodes:
391
+ some_keys_ok = False
392
+ for key in self._atlas[n]:
393
+ if self.EDGE_OK(n, key):
394
+ some_keys_ok = True
395
+ break
396
+ if some_keys_ok is True:
397
+ yield n
398
+
399
+ def __getitem__(self, nbr):
400
+ if nbr in self._atlas and self.NODE_OK(nbr):
401
+
402
+ def new_node_ok(key):
403
+ return self.EDGE_OK(nbr, key)
404
+
405
+ return FilterAtlas(self._atlas[nbr], new_node_ok)
406
+ raise KeyError(f"Key {nbr} not found")
407
+
408
+
409
+ class FilterMultiAdjacency(FilterAdjacency): # multiedgedict
410
+ """A read-only Mapping of Mappings with filtering criteria
411
+ for nodes and edges.
412
+
413
+ It is a view into a dict-of-dict-of-dict-of-dict data structure,
414
+ and it selects nodes and edges that satisfy specific criteria
415
+ defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
416
+
417
+ See Also
418
+ ========
419
+ FilterAtlas
420
+ FilterAdjacency
421
+ FilterMultiInner
422
+ """
423
+
424
+ def __getitem__(self, node):
425
+ if node in self._atlas and self.NODE_OK(node):
426
+
427
+ def edge_ok(nbr, key):
428
+ return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr, key)
429
+
430
+ return FilterMultiInner(self._atlas[node], self.NODE_OK, edge_ok)
431
+ raise KeyError(f"Key {node} not found")
deepseek/lib/python3.10/site-packages/networkx/classes/digraph.py ADDED
@@ -0,0 +1,1352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for directed graphs."""
2
+
3
+ from copy import deepcopy
4
+ from functools import cached_property
5
+
6
+ import networkx as nx
7
+ from networkx import convert
8
+ from networkx.classes.coreviews import AdjacencyView
9
+ from networkx.classes.graph import Graph
10
+ from networkx.classes.reportviews import (
11
+ DiDegreeView,
12
+ InDegreeView,
13
+ InEdgeView,
14
+ OutDegreeView,
15
+ OutEdgeView,
16
+ )
17
+ from networkx.exception import NetworkXError
18
+
19
+ __all__ = ["DiGraph"]
20
+
21
+
22
+ class _CachedPropertyResetterAdjAndSucc:
23
+ """Data Descriptor class that syncs and resets cached properties adj and succ
24
+
25
+ The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ`
26
+ are set to new objects. In addition, the attributes `_succ` and `_adj`
27
+ are synced so these two names point to the same object.
28
+
29
+ Warning: most of the time, when ``G._adj`` is set, ``G._pred`` should also
30
+ be set to maintain a valid data structure. They share datadicts.
31
+
32
+ This object sits on a class and ensures that any instance of that
33
+ class clears its cached properties "succ" and "adj" whenever the
34
+ underlying instance attributes "_succ" or "_adj" are set to a new object.
35
+ It only affects the set process of the obj._adj and obj._succ attribute.
36
+ All get/del operations act as they normally would.
37
+
38
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
39
+ """
40
+
41
+ def __set__(self, obj, value):
42
+ od = obj.__dict__
43
+ od["_adj"] = value
44
+ od["_succ"] = value
45
+ # reset cached properties
46
+ props = [
47
+ "adj",
48
+ "succ",
49
+ "edges",
50
+ "out_edges",
51
+ "degree",
52
+ "out_degree",
53
+ "in_degree",
54
+ ]
55
+ for prop in props:
56
+ if prop in od:
57
+ del od[prop]
58
+
59
+
60
+ class _CachedPropertyResetterPred:
61
+ """Data Descriptor class for _pred that resets ``pred`` cached_property when needed
62
+
63
+ This assumes that the ``cached_property`` ``G.pred`` should be reset whenever
64
+ ``G._pred`` is set to a new value.
65
+
66
+ Warning: most of the time, when ``G._pred`` is set, ``G._adj`` should also
67
+ be set to maintain a valid data structure. They share datadicts.
68
+
69
+ This object sits on a class and ensures that any instance of that
70
+ class clears its cached property "pred" whenever the underlying
71
+ instance attribute "_pred" is set to a new object. It only affects
72
+ the set process of the obj._pred attribute. All get/del operations
73
+ act as they normally would.
74
+
75
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
76
+ """
77
+
78
+ def __set__(self, obj, value):
79
+ od = obj.__dict__
80
+ od["_pred"] = value
81
+ # reset cached properties
82
+ props = ["pred", "in_edges", "degree", "out_degree", "in_degree"]
83
+ for prop in props:
84
+ if prop in od:
85
+ del od[prop]
86
+
87
+
88
+ class DiGraph(Graph):
89
+ """
90
+ Base class for directed graphs.
91
+
92
+ A DiGraph stores nodes and edges with optional data, or attributes.
93
+
94
+ DiGraphs hold directed edges. Self loops are allowed but multiple
95
+ (parallel) edges are not.
96
+
97
+ Nodes can be arbitrary (hashable) Python objects with optional
98
+ key/value attributes. By convention `None` is not used as a node.
99
+
100
+ Edges are represented as links between nodes with optional
101
+ key/value attributes.
102
+
103
+ Parameters
104
+ ----------
105
+ incoming_graph_data : input graph (optional, default: None)
106
+ Data to initialize graph. If None (default) an empty
107
+ graph is created. The data can be any format that is supported
108
+ by the to_networkx_graph() function, currently including edge list,
109
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
110
+ sparse matrix, or PyGraphviz graph.
111
+
112
+ attr : keyword arguments, optional (default= no attributes)
113
+ Attributes to add to graph as key=value pairs.
114
+
115
+ See Also
116
+ --------
117
+ Graph
118
+ MultiGraph
119
+ MultiDiGraph
120
+
121
+ Examples
122
+ --------
123
+ Create an empty graph structure (a "null graph") with no nodes and
124
+ no edges.
125
+
126
+ >>> G = nx.DiGraph()
127
+
128
+ G can be grown in several ways.
129
+
130
+ **Nodes:**
131
+
132
+ Add one node at a time:
133
+
134
+ >>> G.add_node(1)
135
+
136
+ Add the nodes from any container (a list, dict, set or
137
+ even the lines from a file or the nodes from another graph).
138
+
139
+ >>> G.add_nodes_from([2, 3])
140
+ >>> G.add_nodes_from(range(100, 110))
141
+ >>> H = nx.path_graph(10)
142
+ >>> G.add_nodes_from(H)
143
+
144
+ In addition to strings and integers any hashable Python object
145
+ (except None) can represent a node, e.g. a customized node object,
146
+ or even another Graph.
147
+
148
+ >>> G.add_node(H)
149
+
150
+ **Edges:**
151
+
152
+ G can also be grown by adding edges.
153
+
154
+ Add one edge,
155
+
156
+ >>> G.add_edge(1, 2)
157
+
158
+ a list of edges,
159
+
160
+ >>> G.add_edges_from([(1, 2), (1, 3)])
161
+
162
+ or a collection of edges,
163
+
164
+ >>> G.add_edges_from(H.edges)
165
+
166
+ If some edges connect nodes not yet in the graph, the nodes
167
+ are added automatically. There are no errors when adding
168
+ nodes or edges that already exist.
169
+
170
+ **Attributes:**
171
+
172
+ Each graph, node, and edge can hold key/value attribute pairs
173
+ in an associated attribute dictionary (the keys must be hashable).
174
+ By default these are empty, but can be added or changed using
175
+ add_edge, add_node or direct manipulation of the attribute
176
+ dictionaries named graph, node and edge respectively.
177
+
178
+ >>> G = nx.DiGraph(day="Friday")
179
+ >>> G.graph
180
+ {'day': 'Friday'}
181
+
182
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
183
+
184
+ >>> G.add_node(1, time="5pm")
185
+ >>> G.add_nodes_from([3], time="2pm")
186
+ >>> G.nodes[1]
187
+ {'time': '5pm'}
188
+ >>> G.nodes[1]["room"] = 714
189
+ >>> del G.nodes[1]["room"] # remove attribute
190
+ >>> list(G.nodes(data=True))
191
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
192
+
193
+ Add edge attributes using add_edge(), add_edges_from(), subscript
194
+ notation, or G.edges.
195
+
196
+ >>> G.add_edge(1, 2, weight=4.7)
197
+ >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
198
+ >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
199
+ >>> G[1][2]["weight"] = 4.7
200
+ >>> G.edges[1, 2]["weight"] = 4
201
+
202
+ Warning: we protect the graph data structure by making `G.edges[1, 2]` a
203
+ read-only dict-like structure. However, you can assign to attributes
204
+ in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
205
+ data attributes: `G.edges[1, 2]['weight'] = 4`
206
+ (For multigraphs: `MG.edges[u, v, key][name] = value`).
207
+
208
+ **Shortcuts:**
209
+
210
+ Many common graph features allow python syntax to speed reporting.
211
+
212
+ >>> 1 in G # check if node in graph
213
+ True
214
+ >>> [n for n in G if n < 3] # iterate through nodes
215
+ [1, 2]
216
+ >>> len(G) # number of nodes in graph
217
+ 5
218
+
219
+ Often the best way to traverse all edges of a graph is via the neighbors.
220
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
221
+
222
+ >>> for n, nbrsdict in G.adjacency():
223
+ ... for nbr, eattr in nbrsdict.items():
224
+ ... if "weight" in eattr:
225
+ ... # Do something useful with the edges
226
+ ... pass
227
+
228
+ But the edges reporting object is often more convenient:
229
+
230
+ >>> for u, v, weight in G.edges(data="weight"):
231
+ ... if weight is not None:
232
+ ... # Do something useful with the edges
233
+ ... pass
234
+
235
+ **Reporting:**
236
+
237
+ Simple graph information is obtained using object-attributes and methods.
238
+ Reporting usually provides views instead of containers to reduce memory
239
+ usage. The views update as the graph is updated similarly to dict-views.
240
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
241
+ via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
242
+ (e.g. `nodes.items()`, `nodes.data('color')`,
243
+ `nodes.data('color', default='blue')` and similarly for `edges`)
244
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
245
+
246
+ For details on these and other miscellaneous methods, see below.
247
+
248
+ **Subclasses (Advanced):**
249
+
250
+ The Graph class uses a dict-of-dict-of-dict data structure.
251
+ The outer dict (node_dict) holds adjacency information keyed by node.
252
+ The next dict (adjlist_dict) represents the adjacency information and holds
253
+ edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
254
+ the edge data and holds edge attribute values keyed by attribute names.
255
+
256
+ Each of these three dicts can be replaced in a subclass by a user defined
257
+ dict-like object. In general, the dict-like features should be
258
+ maintained but extra features can be added. To replace one of the
259
+ dicts create a new graph class by changing the class(!) variable
260
+ holding the factory for that dict-like structure. The variable names are
261
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
262
+ adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
263
+
264
+ node_dict_factory : function, (default: dict)
265
+ Factory function to be used to create the dict containing node
266
+ attributes, keyed by node id.
267
+ It should require no arguments and return a dict-like object
268
+
269
+ node_attr_dict_factory: function, (default: dict)
270
+ Factory function to be used to create the node attribute
271
+ dict which holds attribute values keyed by attribute name.
272
+ It should require no arguments and return a dict-like object
273
+
274
+ adjlist_outer_dict_factory : function, (default: dict)
275
+ Factory function to be used to create the outer-most dict
276
+ in the data structure that holds adjacency info keyed by node.
277
+ It should require no arguments and return a dict-like object.
278
+
279
+ adjlist_inner_dict_factory : function, optional (default: dict)
280
+ Factory function to be used to create the adjacency list
281
+ dict which holds edge data keyed by neighbor.
282
+ It should require no arguments and return a dict-like object
283
+
284
+ edge_attr_dict_factory : function, optional (default: dict)
285
+ Factory function to be used to create the edge attribute
286
+ dict which holds attribute values keyed by attribute name.
287
+ It should require no arguments and return a dict-like object.
288
+
289
+ graph_attr_dict_factory : function, (default: dict)
290
+ Factory function to be used to create the graph attribute
291
+ dict which holds attribute values keyed by attribute name.
292
+ It should require no arguments and return a dict-like object.
293
+
294
+ Typically, if your extension doesn't impact the data structure all
295
+ methods will inherited without issue except: `to_directed/to_undirected`.
296
+ By default these methods create a DiGraph/Graph class and you probably
297
+ want them to create your extension of a DiGraph/Graph. To facilitate
298
+ this we define two class variables that you can set in your subclass.
299
+
300
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
301
+ Class to create a new graph structure in the `to_directed` method.
302
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
303
+
304
+ to_undirected_class : callable, (default: Graph or MultiGraph)
305
+ Class to create a new graph structure in the `to_undirected` method.
306
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
307
+
308
+ **Subclassing Example**
309
+
310
+ Create a low memory graph class that effectively disallows edge
311
+ attributes by using a single attribute dict for all edges.
312
+ This reduces the memory used, but you lose edge attributes.
313
+
314
+ >>> class ThinGraph(nx.Graph):
315
+ ... all_edge_dict = {"weight": 1}
316
+ ...
317
+ ... def single_edge_dict(self):
318
+ ... return self.all_edge_dict
319
+ ...
320
+ ... edge_attr_dict_factory = single_edge_dict
321
+ >>> G = ThinGraph()
322
+ >>> G.add_edge(2, 1)
323
+ >>> G[2][1]
324
+ {'weight': 1}
325
+ >>> G.add_edge(2, 2)
326
+ >>> G[2][1] is G[2][2]
327
+ True
328
+ """
329
+
330
+ _adj = _CachedPropertyResetterAdjAndSucc() # type: ignore[assignment]
331
+ _succ = _adj # type: ignore[has-type]
332
+ _pred = _CachedPropertyResetterPred()
333
+
334
+ def __init__(self, incoming_graph_data=None, **attr):
335
+ """Initialize a graph with edges, name, or graph attributes.
336
+
337
+ Parameters
338
+ ----------
339
+ incoming_graph_data : input graph (optional, default: None)
340
+ Data to initialize graph. If None (default) an empty
341
+ graph is created. The data can be an edge list, or any
342
+ NetworkX graph object. If the corresponding optional Python
343
+ packages are installed the data can also be a 2D NumPy array, a
344
+ SciPy sparse array, or a PyGraphviz graph.
345
+
346
+ attr : keyword arguments, optional (default= no attributes)
347
+ Attributes to add to graph as key=value pairs.
348
+
349
+ See Also
350
+ --------
351
+ convert
352
+
353
+ Examples
354
+ --------
355
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
356
+ >>> G = nx.Graph(name="my graph")
357
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
358
+ >>> G = nx.Graph(e)
359
+
360
+ Arbitrary graph attribute pairs (key=value) may be assigned
361
+
362
+ >>> G = nx.Graph(e, day="Friday")
363
+ >>> G.graph
364
+ {'day': 'Friday'}
365
+
366
+ """
367
+ self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
368
+ self._node = self.node_dict_factory() # dictionary for node attr
369
+ # We store two adjacency lists:
370
+ # the predecessors of node n are stored in the dict self._pred
371
+ # the successors of node n are stored in the dict self._succ=self._adj
372
+ self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict successor
373
+ self._pred = self.adjlist_outer_dict_factory() # predecessor
374
+ # Note: self._succ = self._adj # successor
375
+
376
+ self.__networkx_cache__ = {}
377
+ # attempt to load graph with data
378
+ if incoming_graph_data is not None:
379
+ convert.to_networkx_graph(incoming_graph_data, create_using=self)
380
+ # load graph attributes (must be after convert)
381
+ self.graph.update(attr)
382
+
383
+ @cached_property
384
+ def adj(self):
385
+ """Graph adjacency object holding the neighbors of each node.
386
+
387
+ This object is a read-only dict-like structure with node keys
388
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
389
+ to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
390
+ the color of the edge `(3, 2)` to `"blue"`.
391
+
392
+ Iterating over G.adj behaves like a dict. Useful idioms include
393
+ `for nbr, datadict in G.adj[n].items():`.
394
+
395
+ The neighbor information is also provided by subscripting the graph.
396
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
397
+
398
+ For directed graphs, `G.adj` holds outgoing (successor) info.
399
+ """
400
+ return AdjacencyView(self._succ)
401
+
402
+ @cached_property
403
+ def succ(self):
404
+ """Graph adjacency object holding the successors of each node.
405
+
406
+ This object is a read-only dict-like structure with node keys
407
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
408
+ to the edge-data-dict. So `G.succ[3][2]['color'] = 'blue'` sets
409
+ the color of the edge `(3, 2)` to `"blue"`.
410
+
411
+ Iterating over G.succ behaves like a dict. Useful idioms include
412
+ `for nbr, datadict in G.succ[n].items():`. A data-view not provided
413
+ by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`
414
+ and a default can be set via a `default` argument to the `data` method.
415
+
416
+ The neighbor information is also provided by subscripting the graph.
417
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
418
+
419
+ For directed graphs, `G.adj` is identical to `G.succ`.
420
+ """
421
+ return AdjacencyView(self._succ)
422
+
423
+ @cached_property
424
+ def pred(self):
425
+ """Graph adjacency object holding the predecessors of each node.
426
+
427
+ This object is a read-only dict-like structure with node keys
428
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
429
+ to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
430
+ the color of the edge `(3, 2)` to `"blue"`.
431
+
432
+ Iterating over G.pred behaves like a dict. Useful idioms include
433
+ `for nbr, datadict in G.pred[n].items():`. A data-view not provided
434
+ by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
435
+ A default can be set via a `default` argument to the `data` method.
436
+ """
437
+ return AdjacencyView(self._pred)
438
+
439
+ def add_node(self, node_for_adding, **attr):
440
+ """Add a single node `node_for_adding` and update node attributes.
441
+
442
+ Parameters
443
+ ----------
444
+ node_for_adding : node
445
+ A node can be any hashable Python object except None.
446
+ attr : keyword arguments, optional
447
+ Set or change node attributes using key=value.
448
+
449
+ See Also
450
+ --------
451
+ add_nodes_from
452
+
453
+ Examples
454
+ --------
455
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
456
+ >>> G.add_node(1)
457
+ >>> G.add_node("Hello")
458
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
459
+ >>> G.add_node(K3)
460
+ >>> G.number_of_nodes()
461
+ 3
462
+
463
+ Use keywords set/change node attributes:
464
+
465
+ >>> G.add_node(1, size=10)
466
+ >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
467
+
468
+ Notes
469
+ -----
470
+ A hashable object is one that can be used as a key in a Python
471
+ dictionary. This includes strings, numbers, tuples of strings
472
+ and numbers, etc.
473
+
474
+ On many platforms hashable items also include mutables such as
475
+ NetworkX Graphs, though one should be careful that the hash
476
+ doesn't change on mutables.
477
+ """
478
+ if node_for_adding not in self._succ:
479
+ if node_for_adding is None:
480
+ raise ValueError("None cannot be a node")
481
+ self._succ[node_for_adding] = self.adjlist_inner_dict_factory()
482
+ self._pred[node_for_adding] = self.adjlist_inner_dict_factory()
483
+ attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
484
+ attr_dict.update(attr)
485
+ else: # update attr even if node already exists
486
+ self._node[node_for_adding].update(attr)
487
+ nx._clear_cache(self)
488
+
489
+ def add_nodes_from(self, nodes_for_adding, **attr):
490
+ """Add multiple nodes.
491
+
492
+ Parameters
493
+ ----------
494
+ nodes_for_adding : iterable container
495
+ A container of nodes (list, dict, set, etc.).
496
+ OR
497
+ A container of (node, attribute dict) tuples.
498
+ Node attributes are updated using the attribute dict.
499
+ attr : keyword arguments, optional (default= no attributes)
500
+ Update attributes for all nodes in nodes.
501
+ Node attributes specified in nodes as a tuple take
502
+ precedence over attributes specified via keyword arguments.
503
+
504
+ See Also
505
+ --------
506
+ add_node
507
+
508
+ Notes
509
+ -----
510
+ When adding nodes from an iterator over the graph you are changing,
511
+ a `RuntimeError` can be raised with message:
512
+ `RuntimeError: dictionary changed size during iteration`. This
513
+ happens when the graph's underlying dictionary is modified during
514
+ iteration. To avoid this error, evaluate the iterator into a separate
515
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
516
+ object to `G.add_nodes_from`.
517
+
518
+ Examples
519
+ --------
520
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
521
+ >>> G.add_nodes_from("Hello")
522
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
523
+ >>> G.add_nodes_from(K3)
524
+ >>> sorted(G.nodes(), key=str)
525
+ [0, 1, 2, 'H', 'e', 'l', 'o']
526
+
527
+ Use keywords to update specific node attributes for every node.
528
+
529
+ >>> G.add_nodes_from([1, 2], size=10)
530
+ >>> G.add_nodes_from([3, 4], weight=0.4)
531
+
532
+ Use (node, attrdict) tuples to update attributes for specific nodes.
533
+
534
+ >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
535
+ >>> G.nodes[1]["size"]
536
+ 11
537
+ >>> H = nx.Graph()
538
+ >>> H.add_nodes_from(G.nodes(data=True))
539
+ >>> H.nodes[1]["size"]
540
+ 11
541
+
542
+ Evaluate an iterator over a graph if using it to modify the same graph
543
+
544
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
545
+ >>> # wrong way - will raise RuntimeError
546
+ >>> # G.add_nodes_from(n + 1 for n in G.nodes)
547
+ >>> # correct way
548
+ >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
549
+ """
550
+ for n in nodes_for_adding:
551
+ try:
552
+ newnode = n not in self._node
553
+ newdict = attr
554
+ except TypeError:
555
+ n, ndict = n
556
+ newnode = n not in self._node
557
+ newdict = attr.copy()
558
+ newdict.update(ndict)
559
+ if newnode:
560
+ if n is None:
561
+ raise ValueError("None cannot be a node")
562
+ self._succ[n] = self.adjlist_inner_dict_factory()
563
+ self._pred[n] = self.adjlist_inner_dict_factory()
564
+ self._node[n] = self.node_attr_dict_factory()
565
+ self._node[n].update(newdict)
566
+ nx._clear_cache(self)
567
+
568
+ def remove_node(self, n):
569
+ """Remove node n.
570
+
571
+ Removes the node n and all adjacent edges.
572
+ Attempting to remove a nonexistent node will raise an exception.
573
+
574
+ Parameters
575
+ ----------
576
+ n : node
577
+ A node in the graph
578
+
579
+ Raises
580
+ ------
581
+ NetworkXError
582
+ If n is not in the graph.
583
+
584
+ See Also
585
+ --------
586
+ remove_nodes_from
587
+
588
+ Examples
589
+ --------
590
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
591
+ >>> list(G.edges)
592
+ [(0, 1), (1, 2)]
593
+ >>> G.remove_node(1)
594
+ >>> list(G.edges)
595
+ []
596
+
597
+ """
598
+ try:
599
+ nbrs = self._succ[n]
600
+ del self._node[n]
601
+ except KeyError as err: # NetworkXError if n not in self
602
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
603
+ for u in nbrs:
604
+ del self._pred[u][n] # remove all edges n-u in digraph
605
+ del self._succ[n] # remove node from succ
606
+ for u in self._pred[n]:
607
+ del self._succ[u][n] # remove all edges n-u in digraph
608
+ del self._pred[n] # remove node from pred
609
+ nx._clear_cache(self)
610
+
611
+ def remove_nodes_from(self, nodes):
612
+ """Remove multiple nodes.
613
+
614
+ Parameters
615
+ ----------
616
+ nodes : iterable container
617
+ A container of nodes (list, dict, set, etc.). If a node
618
+ in the container is not in the graph it is silently ignored.
619
+
620
+ See Also
621
+ --------
622
+ remove_node
623
+
624
+ Notes
625
+ -----
626
+ When removing nodes from an iterator over the graph you are changing,
627
+ a `RuntimeError` will be raised with message:
628
+ `RuntimeError: dictionary changed size during iteration`. This
629
+ happens when the graph's underlying dictionary is modified during
630
+ iteration. To avoid this error, evaluate the iterator into a separate
631
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
632
+ object to `G.remove_nodes_from`.
633
+
634
+ Examples
635
+ --------
636
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
637
+ >>> e = list(G.nodes)
638
+ >>> e
639
+ [0, 1, 2]
640
+ >>> G.remove_nodes_from(e)
641
+ >>> list(G.nodes)
642
+ []
643
+
644
+ Evaluate an iterator over a graph if using it to modify the same graph
645
+
646
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
647
+ >>> # this command will fail, as the graph's dict is modified during iteration
648
+ >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
649
+ >>> # this command will work, since the dictionary underlying graph is not modified
650
+ >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
651
+ """
652
+ for n in nodes:
653
+ try:
654
+ succs = self._succ[n]
655
+ del self._node[n]
656
+ for u in succs:
657
+ del self._pred[u][n] # remove all edges n-u in digraph
658
+ del self._succ[n] # now remove node
659
+ for u in self._pred[n]:
660
+ del self._succ[u][n] # remove all edges n-u in digraph
661
+ del self._pred[n] # now remove node
662
+ except KeyError:
663
+ pass # silent failure on remove
664
+ nx._clear_cache(self)
665
+
666
+ def add_edge(self, u_of_edge, v_of_edge, **attr):
667
+ """Add an edge between u and v.
668
+
669
+ The nodes u and v will be automatically added if they are
670
+ not already in the graph.
671
+
672
+ Edge attributes can be specified with keywords or by directly
673
+ accessing the edge's attribute dictionary. See examples below.
674
+
675
+ Parameters
676
+ ----------
677
+ u_of_edge, v_of_edge : nodes
678
+ Nodes can be, for example, strings or numbers.
679
+ Nodes must be hashable (and not None) Python objects.
680
+ attr : keyword arguments, optional
681
+ Edge data (or labels or objects) can be assigned using
682
+ keyword arguments.
683
+
684
+ See Also
685
+ --------
686
+ add_edges_from : add a collection of edges
687
+
688
+ Notes
689
+ -----
690
+ Adding an edge that already exists updates the edge data.
691
+
692
+ Many NetworkX algorithms designed for weighted graphs use
693
+ an edge attribute (by default `weight`) to hold a numerical value.
694
+
695
+ Examples
696
+ --------
697
+ The following all add the edge e=(1, 2) to graph G:
698
+
699
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
700
+ >>> e = (1, 2)
701
+ >>> G.add_edge(1, 2) # explicit two-node form
702
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
703
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
704
+
705
+ Associate data to edges using keywords:
706
+
707
+ >>> G.add_edge(1, 2, weight=3)
708
+ >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
709
+
710
+ For non-string attribute keys, use subscript notation.
711
+
712
+ >>> G.add_edge(1, 2)
713
+ >>> G[1][2].update({0: 5})
714
+ >>> G.edges[1, 2].update({0: 5})
715
+ """
716
+ u, v = u_of_edge, v_of_edge
717
+ # add nodes
718
+ if u not in self._succ:
719
+ if u is None:
720
+ raise ValueError("None cannot be a node")
721
+ self._succ[u] = self.adjlist_inner_dict_factory()
722
+ self._pred[u] = self.adjlist_inner_dict_factory()
723
+ self._node[u] = self.node_attr_dict_factory()
724
+ if v not in self._succ:
725
+ if v is None:
726
+ raise ValueError("None cannot be a node")
727
+ self._succ[v] = self.adjlist_inner_dict_factory()
728
+ self._pred[v] = self.adjlist_inner_dict_factory()
729
+ self._node[v] = self.node_attr_dict_factory()
730
+ # add the edge
731
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
732
+ datadict.update(attr)
733
+ self._succ[u][v] = datadict
734
+ self._pred[v][u] = datadict
735
+ nx._clear_cache(self)
736
+
737
+ def add_edges_from(self, ebunch_to_add, **attr):
738
+ """Add all the edges in ebunch_to_add.
739
+
740
+ Parameters
741
+ ----------
742
+ ebunch_to_add : container of edges
743
+ Each edge given in the container will be added to the
744
+ graph. The edges must be given as 2-tuples (u, v) or
745
+ 3-tuples (u, v, d) where d is a dictionary containing edge data.
746
+ attr : keyword arguments, optional
747
+ Edge data (or labels or objects) can be assigned using
748
+ keyword arguments.
749
+
750
+ See Also
751
+ --------
752
+ add_edge : add a single edge
753
+ add_weighted_edges_from : convenient way to add weighted edges
754
+
755
+ Notes
756
+ -----
757
+ Adding the same edge twice has no effect but any edge data
758
+ will be updated when each duplicate edge is added.
759
+
760
+ Edge attributes specified in an ebunch take precedence over
761
+ attributes specified via keyword arguments.
762
+
763
+ When adding edges from an iterator over the graph you are changing,
764
+ a `RuntimeError` can be raised with message:
765
+ `RuntimeError: dictionary changed size during iteration`. This
766
+ happens when the graph's underlying dictionary is modified during
767
+ iteration. To avoid this error, evaluate the iterator into a separate
768
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
769
+ object to `G.add_edges_from`.
770
+
771
+ Examples
772
+ --------
773
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
774
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
775
+ >>> e = zip(range(0, 3), range(1, 4))
776
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
777
+
778
+ Associate data to edges
779
+
780
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
781
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
782
+
783
+ Evaluate an iterator over a graph if using it to modify the same graph
784
+
785
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
786
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
787
+ >>> # wrong way - will raise RuntimeError
788
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
789
+ >>> # right way - note that there will be no self-edge for node 5
790
+ >>> G.add_edges_from(list((5, n) for n in G.nodes))
791
+ """
792
+ for e in ebunch_to_add:
793
+ ne = len(e)
794
+ if ne == 3:
795
+ u, v, dd = e
796
+ elif ne == 2:
797
+ u, v = e
798
+ dd = {}
799
+ else:
800
+ raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
801
+ if u not in self._succ:
802
+ if u is None:
803
+ raise ValueError("None cannot be a node")
804
+ self._succ[u] = self.adjlist_inner_dict_factory()
805
+ self._pred[u] = self.adjlist_inner_dict_factory()
806
+ self._node[u] = self.node_attr_dict_factory()
807
+ if v not in self._succ:
808
+ if v is None:
809
+ raise ValueError("None cannot be a node")
810
+ self._succ[v] = self.adjlist_inner_dict_factory()
811
+ self._pred[v] = self.adjlist_inner_dict_factory()
812
+ self._node[v] = self.node_attr_dict_factory()
813
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
814
+ datadict.update(attr)
815
+ datadict.update(dd)
816
+ self._succ[u][v] = datadict
817
+ self._pred[v][u] = datadict
818
+ nx._clear_cache(self)
819
+
820
+ def remove_edge(self, u, v):
821
+ """Remove the edge between u and v.
822
+
823
+ Parameters
824
+ ----------
825
+ u, v : nodes
826
+ Remove the edge between nodes u and v.
827
+
828
+ Raises
829
+ ------
830
+ NetworkXError
831
+ If there is not an edge between u and v.
832
+
833
+ See Also
834
+ --------
835
+ remove_edges_from : remove a collection of edges
836
+
837
+ Examples
838
+ --------
839
+ >>> G = nx.Graph() # or DiGraph, etc
840
+ >>> nx.add_path(G, [0, 1, 2, 3])
841
+ >>> G.remove_edge(0, 1)
842
+ >>> e = (1, 2)
843
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
844
+ >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
845
+ >>> G.remove_edge(*e[:2]) # select first part of edge tuple
846
+ """
847
+ try:
848
+ del self._succ[u][v]
849
+ del self._pred[v][u]
850
+ except KeyError as err:
851
+ raise NetworkXError(f"The edge {u}-{v} not in graph.") from err
852
+ nx._clear_cache(self)
853
+
854
+ def remove_edges_from(self, ebunch):
855
+ """Remove all edges specified in ebunch.
856
+
857
+ Parameters
858
+ ----------
859
+ ebunch: list or container of edge tuples
860
+ Each edge given in the list or container will be removed
861
+ from the graph. The edges can be:
862
+
863
+ - 2-tuples (u, v) edge between u and v.
864
+ - 3-tuples (u, v, k) where k is ignored.
865
+
866
+ See Also
867
+ --------
868
+ remove_edge : remove a single edge
869
+
870
+ Notes
871
+ -----
872
+ Will fail silently if an edge in ebunch is not in the graph.
873
+
874
+ Examples
875
+ --------
876
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
877
+ >>> ebunch = [(1, 2), (2, 3)]
878
+ >>> G.remove_edges_from(ebunch)
879
+ """
880
+ for e in ebunch:
881
+ u, v = e[:2] # ignore edge data
882
+ if u in self._succ and v in self._succ[u]:
883
+ del self._succ[u][v]
884
+ del self._pred[v][u]
885
+ nx._clear_cache(self)
886
+
887
+ def has_successor(self, u, v):
888
+ """Returns True if node u has successor v.
889
+
890
+ This is true if graph has the edge u->v.
891
+ """
892
+ return u in self._succ and v in self._succ[u]
893
+
894
+ def has_predecessor(self, u, v):
895
+ """Returns True if node u has predecessor v.
896
+
897
+ This is true if graph has the edge u<-v.
898
+ """
899
+ return u in self._pred and v in self._pred[u]
900
+
901
+ def successors(self, n):
902
+ """Returns an iterator over successor nodes of n.
903
+
904
+ A successor of n is a node m such that there exists a directed
905
+ edge from n to m.
906
+
907
+ Parameters
908
+ ----------
909
+ n : node
910
+ A node in the graph
911
+
912
+ Raises
913
+ ------
914
+ NetworkXError
915
+ If n is not in the graph.
916
+
917
+ See Also
918
+ --------
919
+ predecessors
920
+
921
+ Notes
922
+ -----
923
+ neighbors() and successors() are the same.
924
+ """
925
+ try:
926
+ return iter(self._succ[n])
927
+ except KeyError as err:
928
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
929
+
930
+ # digraph definitions
931
+ neighbors = successors
932
+
933
+ def predecessors(self, n):
934
+ """Returns an iterator over predecessor nodes of n.
935
+
936
+ A predecessor of n is a node m such that there exists a directed
937
+ edge from m to n.
938
+
939
+ Parameters
940
+ ----------
941
+ n : node
942
+ A node in the graph
943
+
944
+ Raises
945
+ ------
946
+ NetworkXError
947
+ If n is not in the graph.
948
+
949
+ See Also
950
+ --------
951
+ successors
952
+ """
953
+ try:
954
+ return iter(self._pred[n])
955
+ except KeyError as err:
956
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
957
+
958
+ @cached_property
959
+ def edges(self):
960
+ """An OutEdgeView of the DiGraph as G.edges or G.edges().
961
+
962
+ edges(self, nbunch=None, data=False, default=None)
963
+
964
+ The OutEdgeView provides set-like operations on the edge-tuples
965
+ as well as edge attribute lookup. When called, it also provides
966
+ an EdgeDataView object which allows control of access to edge
967
+ attributes (but does not provide set-like operations).
968
+ Hence, `G.edges[u, v]['color']` provides the value of the color
969
+ attribute for edge `(u, v)` while
970
+ `for (u, v, c) in G.edges.data('color', default='red'):`
971
+ iterates through all the edges yielding the color attribute
972
+ with default `'red'` if no color attribute exists.
973
+
974
+ Parameters
975
+ ----------
976
+ nbunch : single node, container, or all nodes (default= all nodes)
977
+ The view will only report edges from these nodes.
978
+ data : string or bool, optional (default=False)
979
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
980
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
981
+ If False, return 2-tuple (u, v).
982
+ default : value, optional (default=None)
983
+ Value used for edges that don't have the requested attribute.
984
+ Only relevant if data is not True or False.
985
+
986
+ Returns
987
+ -------
988
+ edges : OutEdgeView
989
+ A view of edge attributes, usually it iterates over (u, v)
990
+ or (u, v, d) tuples of edges, but can also be used for
991
+ attribute lookup as `edges[u, v]['foo']`.
992
+
993
+ See Also
994
+ --------
995
+ in_edges, out_edges
996
+
997
+ Notes
998
+ -----
999
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
1000
+ For directed graphs this returns the out-edges.
1001
+
1002
+ Examples
1003
+ --------
1004
+ >>> G = nx.DiGraph() # or MultiDiGraph, etc
1005
+ >>> nx.add_path(G, [0, 1, 2])
1006
+ >>> G.add_edge(2, 3, weight=5)
1007
+ >>> [e for e in G.edges]
1008
+ [(0, 1), (1, 2), (2, 3)]
1009
+ >>> G.edges.data() # default data is {} (empty dict)
1010
+ OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
1011
+ >>> G.edges.data("weight", default=1)
1012
+ OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
1013
+ >>> G.edges([0, 2]) # only edges originating from these nodes
1014
+ OutEdgeDataView([(0, 1), (2, 3)])
1015
+ >>> G.edges(0) # only edges from node 0
1016
+ OutEdgeDataView([(0, 1)])
1017
+
1018
+ """
1019
+ return OutEdgeView(self)
1020
+
1021
+ # alias out_edges to edges
1022
+ @cached_property
1023
+ def out_edges(self):
1024
+ return OutEdgeView(self)
1025
+
1026
+ out_edges.__doc__ = edges.__doc__
1027
+
1028
+ @cached_property
1029
+ def in_edges(self):
1030
+ """A view of the in edges of the graph as G.in_edges or G.in_edges().
1031
+
1032
+ in_edges(self, nbunch=None, data=False, default=None):
1033
+
1034
+ Parameters
1035
+ ----------
1036
+ nbunch : single node, container, or all nodes (default= all nodes)
1037
+ The view will only report edges incident to these nodes.
1038
+ data : string or bool, optional (default=False)
1039
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
1040
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
1041
+ If False, return 2-tuple (u, v).
1042
+ default : value, optional (default=None)
1043
+ Value used for edges that don't have the requested attribute.
1044
+ Only relevant if data is not True or False.
1045
+
1046
+ Returns
1047
+ -------
1048
+ in_edges : InEdgeView or InEdgeDataView
1049
+ A view of edge attributes, usually it iterates over (u, v)
1050
+ or (u, v, d) tuples of edges, but can also be used for
1051
+ attribute lookup as `edges[u, v]['foo']`.
1052
+
1053
+ Examples
1054
+ --------
1055
+ >>> G = nx.DiGraph()
1056
+ >>> G.add_edge(1, 2, color="blue")
1057
+ >>> G.in_edges()
1058
+ InEdgeView([(1, 2)])
1059
+ >>> G.in_edges(nbunch=2)
1060
+ InEdgeDataView([(1, 2)])
1061
+
1062
+ See Also
1063
+ --------
1064
+ edges
1065
+ """
1066
+ return InEdgeView(self)
1067
+
1068
+ @cached_property
1069
+ def degree(self):
1070
+ """A DegreeView for the Graph as G.degree or G.degree().
1071
+
1072
+ The node degree is the number of edges adjacent to the node.
1073
+ The weighted node degree is the sum of the edge weights for
1074
+ edges incident to that node.
1075
+
1076
+ This object provides an iterator for (node, degree) as well as
1077
+ lookup for the degree for a single node.
1078
+
1079
+ Parameters
1080
+ ----------
1081
+ nbunch : single node, container, or all nodes (default= all nodes)
1082
+ The view will only report edges incident to these nodes.
1083
+
1084
+ weight : string or None, optional (default=None)
1085
+ The name of an edge attribute that holds the numerical value used
1086
+ as a weight. If None, then each edge has weight 1.
1087
+ The degree is the sum of the edge weights adjacent to the node.
1088
+
1089
+ Returns
1090
+ -------
1091
+ DiDegreeView or int
1092
+ If multiple nodes are requested (the default), returns a `DiDegreeView`
1093
+ mapping nodes to their degree.
1094
+ If a single node is requested, returns the degree of the node as an integer.
1095
+
1096
+ See Also
1097
+ --------
1098
+ in_degree, out_degree
1099
+
1100
+ Examples
1101
+ --------
1102
+ >>> G = nx.DiGraph() # or MultiDiGraph
1103
+ >>> nx.add_path(G, [0, 1, 2, 3])
1104
+ >>> G.degree(0) # node 0 with degree 1
1105
+ 1
1106
+ >>> list(G.degree([0, 1, 2]))
1107
+ [(0, 1), (1, 2), (2, 2)]
1108
+
1109
+ """
1110
+ return DiDegreeView(self)
1111
+
1112
+ @cached_property
1113
+ def in_degree(self):
1114
+ """An InDegreeView for (node, in_degree) or in_degree for single node.
1115
+
1116
+ The node in_degree is the number of edges pointing to the node.
1117
+ The weighted node degree is the sum of the edge weights for
1118
+ edges incident to that node.
1119
+
1120
+ This object provides an iteration over (node, in_degree) as well as
1121
+ lookup for the degree for a single node.
1122
+
1123
+ Parameters
1124
+ ----------
1125
+ nbunch : single node, container, or all nodes (default= all nodes)
1126
+ The view will only report edges incident to these nodes.
1127
+
1128
+ weight : string or None, optional (default=None)
1129
+ The name of an edge attribute that holds the numerical value used
1130
+ as a weight. If None, then each edge has weight 1.
1131
+ The degree is the sum of the edge weights adjacent to the node.
1132
+
1133
+ Returns
1134
+ -------
1135
+ If a single node is requested
1136
+ deg : int
1137
+ In-degree of the node
1138
+
1139
+ OR if multiple nodes are requested
1140
+ nd_iter : iterator
1141
+ The iterator returns two-tuples of (node, in-degree).
1142
+
1143
+ See Also
1144
+ --------
1145
+ degree, out_degree
1146
+
1147
+ Examples
1148
+ --------
1149
+ >>> G = nx.DiGraph()
1150
+ >>> nx.add_path(G, [0, 1, 2, 3])
1151
+ >>> G.in_degree(0) # node 0 with degree 0
1152
+ 0
1153
+ >>> list(G.in_degree([0, 1, 2]))
1154
+ [(0, 0), (1, 1), (2, 1)]
1155
+
1156
+ """
1157
+ return InDegreeView(self)
1158
+
1159
+ @cached_property
1160
+ def out_degree(self):
1161
+ """An OutDegreeView for (node, out_degree)
1162
+
1163
+ The node out_degree is the number of edges pointing out of the node.
1164
+ The weighted node degree is the sum of the edge weights for
1165
+ edges incident to that node.
1166
+
1167
+ This object provides an iterator over (node, out_degree) as well as
1168
+ lookup for the degree for a single node.
1169
+
1170
+ Parameters
1171
+ ----------
1172
+ nbunch : single node, container, or all nodes (default= all nodes)
1173
+ The view will only report edges incident to these nodes.
1174
+
1175
+ weight : string or None, optional (default=None)
1176
+ The name of an edge attribute that holds the numerical value used
1177
+ as a weight. If None, then each edge has weight 1.
1178
+ The degree is the sum of the edge weights adjacent to the node.
1179
+
1180
+ Returns
1181
+ -------
1182
+ If a single node is requested
1183
+ deg : int
1184
+ Out-degree of the node
1185
+
1186
+ OR if multiple nodes are requested
1187
+ nd_iter : iterator
1188
+ The iterator returns two-tuples of (node, out-degree).
1189
+
1190
+ See Also
1191
+ --------
1192
+ degree, in_degree
1193
+
1194
+ Examples
1195
+ --------
1196
+ >>> G = nx.DiGraph()
1197
+ >>> nx.add_path(G, [0, 1, 2, 3])
1198
+ >>> G.out_degree(0) # node 0 with degree 1
1199
+ 1
1200
+ >>> list(G.out_degree([0, 1, 2]))
1201
+ [(0, 1), (1, 1), (2, 1)]
1202
+
1203
+ """
1204
+ return OutDegreeView(self)
1205
+
1206
+ def clear(self):
1207
+ """Remove all nodes and edges from the graph.
1208
+
1209
+ This also removes the name, and all graph, node, and edge attributes.
1210
+
1211
+ Examples
1212
+ --------
1213
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1214
+ >>> G.clear()
1215
+ >>> list(G.nodes)
1216
+ []
1217
+ >>> list(G.edges)
1218
+ []
1219
+
1220
+ """
1221
+ self._succ.clear()
1222
+ self._pred.clear()
1223
+ self._node.clear()
1224
+ self.graph.clear()
1225
+ nx._clear_cache(self)
1226
+
1227
+ def clear_edges(self):
1228
+ """Remove all edges from the graph without altering nodes.
1229
+
1230
+ Examples
1231
+ --------
1232
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1233
+ >>> G.clear_edges()
1234
+ >>> list(G.nodes)
1235
+ [0, 1, 2, 3]
1236
+ >>> list(G.edges)
1237
+ []
1238
+
1239
+ """
1240
+ for predecessor_dict in self._pred.values():
1241
+ predecessor_dict.clear()
1242
+ for successor_dict in self._succ.values():
1243
+ successor_dict.clear()
1244
+ nx._clear_cache(self)
1245
+
1246
+ def is_multigraph(self):
1247
+ """Returns True if graph is a multigraph, False otherwise."""
1248
+ return False
1249
+
1250
+ def is_directed(self):
1251
+ """Returns True if graph is directed, False otherwise."""
1252
+ return True
1253
+
1254
+ def to_undirected(self, reciprocal=False, as_view=False):
1255
+ """Returns an undirected representation of the digraph.
1256
+
1257
+ Parameters
1258
+ ----------
1259
+ reciprocal : bool (optional)
1260
+ If True only keep edges that appear in both directions
1261
+ in the original digraph.
1262
+ as_view : bool (optional, default=False)
1263
+ If True return an undirected view of the original directed graph.
1264
+
1265
+ Returns
1266
+ -------
1267
+ G : Graph
1268
+ An undirected graph with the same name and nodes and
1269
+ with edge (u, v, data) if either (u, v, data) or (v, u, data)
1270
+ is in the digraph. If both edges exist in digraph and
1271
+ their edge data is different, only one edge is created
1272
+ with an arbitrary choice of which edge data to use.
1273
+ You must check and correct for this manually if desired.
1274
+
1275
+ See Also
1276
+ --------
1277
+ Graph, copy, add_edge, add_edges_from
1278
+
1279
+ Notes
1280
+ -----
1281
+ If edges in both directions (u, v) and (v, u) exist in the
1282
+ graph, attributes for the new undirected edge will be a combination of
1283
+ the attributes of the directed edges. The edge data is updated
1284
+ in the (arbitrary) order that the edges are encountered. For
1285
+ more customized control of the edge attributes use add_edge().
1286
+
1287
+ This returns a "deepcopy" of the edge, node, and
1288
+ graph attributes which attempts to completely copy
1289
+ all of the data and references.
1290
+
1291
+ This is in contrast to the similar G=DiGraph(D) which returns a
1292
+ shallow copy of the data.
1293
+
1294
+ See the Python copy module for more information on shallow
1295
+ and deep copies, https://docs.python.org/3/library/copy.html.
1296
+
1297
+ Warning: If you have subclassed DiGraph to use dict-like objects
1298
+ in the data structure, those changes do not transfer to the
1299
+ Graph created by this method.
1300
+
1301
+ Examples
1302
+ --------
1303
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
1304
+ >>> H = G.to_directed()
1305
+ >>> list(H.edges)
1306
+ [(0, 1), (1, 0)]
1307
+ >>> G2 = H.to_undirected()
1308
+ >>> list(G2.edges)
1309
+ [(0, 1)]
1310
+ """
1311
+ graph_class = self.to_undirected_class()
1312
+ if as_view is True:
1313
+ return nx.graphviews.generic_graph_view(self, graph_class)
1314
+ # deepcopy when not a view
1315
+ G = graph_class()
1316
+ G.graph.update(deepcopy(self.graph))
1317
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1318
+ if reciprocal is True:
1319
+ G.add_edges_from(
1320
+ (u, v, deepcopy(d))
1321
+ for u, nbrs in self._adj.items()
1322
+ for v, d in nbrs.items()
1323
+ if v in self._pred[u]
1324
+ )
1325
+ else:
1326
+ G.add_edges_from(
1327
+ (u, v, deepcopy(d))
1328
+ for u, nbrs in self._adj.items()
1329
+ for v, d in nbrs.items()
1330
+ )
1331
+ return G
1332
+
1333
+ def reverse(self, copy=True):
1334
+ """Returns the reverse of the graph.
1335
+
1336
+ The reverse is a graph with the same nodes and edges
1337
+ but with the directions of the edges reversed.
1338
+
1339
+ Parameters
1340
+ ----------
1341
+ copy : bool optional (default=True)
1342
+ If True, return a new DiGraph holding the reversed edges.
1343
+ If False, the reverse graph is created using a view of
1344
+ the original graph.
1345
+ """
1346
+ if copy:
1347
+ H = self.__class__()
1348
+ H.graph.update(deepcopy(self.graph))
1349
+ H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items())
1350
+ H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True))
1351
+ return H
1352
+ return nx.reverse_view(self)
deepseek/lib/python3.10/site-packages/networkx/classes/filters.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filter factories to hide or show sets of nodes and edges.
2
+
3
+ These filters return the function used when creating `SubGraph`.
4
+ """
5
+
6
+ __all__ = [
7
+ "no_filter",
8
+ "hide_nodes",
9
+ "hide_edges",
10
+ "hide_multiedges",
11
+ "hide_diedges",
12
+ "hide_multidiedges",
13
+ "show_nodes",
14
+ "show_edges",
15
+ "show_multiedges",
16
+ "show_diedges",
17
+ "show_multidiedges",
18
+ ]
19
+
20
+
21
+ def no_filter(*items):
22
+ """Returns a filter function that always evaluates to True."""
23
+ return True
24
+
25
+
26
+ def hide_nodes(nodes):
27
+ """Returns a filter function that hides specific nodes."""
28
+ nodes = set(nodes)
29
+ return lambda node: node not in nodes
30
+
31
+
32
+ def hide_diedges(edges):
33
+ """Returns a filter function that hides specific directed edges."""
34
+ edges = {(u, v) for u, v in edges}
35
+ return lambda u, v: (u, v) not in edges
36
+
37
+
38
+ def hide_edges(edges):
39
+ """Returns a filter function that hides specific undirected edges."""
40
+ alledges = set(edges) | {(v, u) for (u, v) in edges}
41
+ return lambda u, v: (u, v) not in alledges
42
+
43
+
44
+ def hide_multidiedges(edges):
45
+ """Returns a filter function that hides specific multi-directed edges."""
46
+ edges = {(u, v, k) for u, v, k in edges}
47
+ return lambda u, v, k: (u, v, k) not in edges
48
+
49
+
50
+ def hide_multiedges(edges):
51
+ """Returns a filter function that hides specific multi-undirected edges."""
52
+ alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
53
+ return lambda u, v, k: (u, v, k) not in alledges
54
+
55
+
56
+ # write show_nodes as a class to make SubGraph pickleable
57
+ class show_nodes:
58
+ """Filter class to show specific nodes.
59
+
60
+ Attach the set of nodes as an attribute to speed up this commonly used filter
61
+
62
+ Note that another allowed attribute for filters is to store the number of nodes
63
+ on the filter as attribute `length` (used in `__len__`). It is a user
64
+ responsibility to ensure this attribute is accurate if present.
65
+ """
66
+
67
+ def __init__(self, nodes):
68
+ self.nodes = set(nodes)
69
+
70
+ def __call__(self, node):
71
+ return node in self.nodes
72
+
73
+
74
+ def show_diedges(edges):
75
+ """Returns a filter function that shows specific directed edges."""
76
+ edges = {(u, v) for u, v in edges}
77
+ return lambda u, v: (u, v) in edges
78
+
79
+
80
+ def show_edges(edges):
81
+ """Returns a filter function that shows specific undirected edges."""
82
+ alledges = set(edges) | {(v, u) for (u, v) in edges}
83
+ return lambda u, v: (u, v) in alledges
84
+
85
+
86
+ def show_multidiedges(edges):
87
+ """Returns a filter function that shows specific multi-directed edges."""
88
+ edges = {(u, v, k) for u, v, k in edges}
89
+ return lambda u, v, k: (u, v, k) in edges
90
+
91
+
92
+ def show_multiedges(edges):
93
+ """Returns a filter function that shows specific multi-undirected edges."""
94
+ alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
95
+ return lambda u, v, k: (u, v, k) in alledges
deepseek/lib/python3.10/site-packages/networkx/classes/function.py ADDED
@@ -0,0 +1,1407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functional interface to graph methods and assorted utilities."""
2
+
3
+ from collections import Counter
4
+ from itertools import chain
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for, pairwise
8
+
9
+ __all__ = [
10
+ "nodes",
11
+ "edges",
12
+ "degree",
13
+ "degree_histogram",
14
+ "neighbors",
15
+ "number_of_nodes",
16
+ "number_of_edges",
17
+ "density",
18
+ "is_directed",
19
+ "freeze",
20
+ "is_frozen",
21
+ "subgraph",
22
+ "induced_subgraph",
23
+ "edge_subgraph",
24
+ "restricted_view",
25
+ "to_directed",
26
+ "to_undirected",
27
+ "add_star",
28
+ "add_path",
29
+ "add_cycle",
30
+ "create_empty_copy",
31
+ "set_node_attributes",
32
+ "get_node_attributes",
33
+ "remove_node_attributes",
34
+ "set_edge_attributes",
35
+ "get_edge_attributes",
36
+ "remove_edge_attributes",
37
+ "all_neighbors",
38
+ "non_neighbors",
39
+ "non_edges",
40
+ "common_neighbors",
41
+ "is_weighted",
42
+ "is_negatively_weighted",
43
+ "is_empty",
44
+ "selfloop_edges",
45
+ "nodes_with_selfloops",
46
+ "number_of_selfloops",
47
+ "path_weight",
48
+ "is_path",
49
+ ]
50
+
51
+
52
+ def nodes(G):
53
+ """Returns a NodeView over the graph nodes.
54
+
55
+ This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
56
+ """
57
+ return G.nodes()
58
+
59
+
60
+ def edges(G, nbunch=None):
61
+ """Returns an edge view of edges incident to nodes in nbunch.
62
+
63
+ Return all edges if nbunch is unspecified or nbunch=None.
64
+
65
+ For digraphs, edges=out_edges
66
+
67
+ This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
68
+ """
69
+ return G.edges(nbunch)
70
+
71
+
72
+ def degree(G, nbunch=None, weight=None):
73
+ """Returns a degree view of single node or of nbunch of nodes.
74
+ If nbunch is omitted, then return degrees of *all* nodes.
75
+
76
+ This function wraps the :func:`G.degree <networkx.Graph.degree>` property.
77
+ """
78
+ return G.degree(nbunch, weight)
79
+
80
+
81
+ def neighbors(G, n):
82
+ """Returns an iterator over all neighbors of node n.
83
+
84
+ This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
85
+ """
86
+ return G.neighbors(n)
87
+
88
+
89
+ def number_of_nodes(G):
90
+ """Returns the number of nodes in the graph.
91
+
92
+ This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
93
+ """
94
+ return G.number_of_nodes()
95
+
96
+
97
+ def number_of_edges(G):
98
+ """Returns the number of edges in the graph.
99
+
100
+ This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
101
+ """
102
+ return G.number_of_edges()
103
+
104
+
105
+ def density(G):
106
+ r"""Returns the density of a graph.
107
+
108
+ The density for undirected graphs is
109
+
110
+ .. math::
111
+
112
+ d = \frac{2m}{n(n-1)},
113
+
114
+ and for directed graphs is
115
+
116
+ .. math::
117
+
118
+ d = \frac{m}{n(n-1)},
119
+
120
+ where `n` is the number of nodes and `m` is the number of edges in `G`.
121
+
122
+ Notes
123
+ -----
124
+ The density is 0 for a graph without edges and 1 for a complete graph.
125
+ The density of multigraphs can be higher than 1.
126
+
127
+ Self loops are counted in the total number of edges so graphs with self
128
+ loops can have density higher than 1.
129
+ """
130
+ n = number_of_nodes(G)
131
+ m = number_of_edges(G)
132
+ if m == 0 or n <= 1:
133
+ return 0
134
+ d = m / (n * (n - 1))
135
+ if not G.is_directed():
136
+ d *= 2
137
+ return d
138
+
139
+
140
+ def degree_histogram(G):
141
+ """Returns a list of the frequency of each degree value.
142
+
143
+ Parameters
144
+ ----------
145
+ G : Networkx graph
146
+ A graph
147
+
148
+ Returns
149
+ -------
150
+ hist : list
151
+ A list of frequencies of degrees.
152
+ The degree values are the index in the list.
153
+
154
+ Notes
155
+ -----
156
+ Note: the bins are width one, hence len(list) can be large
157
+ (Order(number_of_edges))
158
+ """
159
+ counts = Counter(d for n, d in G.degree())
160
+ return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
161
+
162
+
163
+ def is_directed(G):
164
+ """Return True if graph is directed."""
165
+ return G.is_directed()
166
+
167
+
168
+ def frozen(*args, **kwargs):
169
+ """Dummy method for raising errors when trying to modify frozen graphs"""
170
+ raise nx.NetworkXError("Frozen graph can't be modified")
171
+
172
+
173
+ def freeze(G):
174
+ """Modify graph to prevent further change by adding or removing
175
+ nodes or edges.
176
+
177
+ Node and edge data can still be modified.
178
+
179
+ Parameters
180
+ ----------
181
+ G : graph
182
+ A NetworkX graph
183
+
184
+ Examples
185
+ --------
186
+ >>> G = nx.path_graph(4)
187
+ >>> G = nx.freeze(G)
188
+ >>> try:
189
+ ... G.add_edge(4, 5)
190
+ ... except nx.NetworkXError as err:
191
+ ... print(str(err))
192
+ Frozen graph can't be modified
193
+
194
+ Notes
195
+ -----
196
+ To "unfreeze" a graph you must make a copy by creating a new graph object:
197
+
198
+ >>> graph = nx.path_graph(4)
199
+ >>> frozen_graph = nx.freeze(graph)
200
+ >>> unfrozen_graph = nx.Graph(frozen_graph)
201
+ >>> nx.is_frozen(unfrozen_graph)
202
+ False
203
+
204
+ See Also
205
+ --------
206
+ is_frozen
207
+ """
208
+ G.add_node = frozen
209
+ G.add_nodes_from = frozen
210
+ G.remove_node = frozen
211
+ G.remove_nodes_from = frozen
212
+ G.add_edge = frozen
213
+ G.add_edges_from = frozen
214
+ G.add_weighted_edges_from = frozen
215
+ G.remove_edge = frozen
216
+ G.remove_edges_from = frozen
217
+ G.clear = frozen
218
+ G.clear_edges = frozen
219
+ G.frozen = True
220
+ return G
221
+
222
+
223
+ def is_frozen(G):
224
+ """Returns True if graph is frozen.
225
+
226
+ Parameters
227
+ ----------
228
+ G : graph
229
+ A NetworkX graph
230
+
231
+ See Also
232
+ --------
233
+ freeze
234
+ """
235
+ try:
236
+ return G.frozen
237
+ except AttributeError:
238
+ return False
239
+
240
+
241
+ def add_star(G_to_add_to, nodes_for_star, **attr):
242
+ """Add a star to Graph G_to_add_to.
243
+
244
+ The first node in `nodes_for_star` is the middle of the star.
245
+ It is connected to all other nodes.
246
+
247
+ Parameters
248
+ ----------
249
+ G_to_add_to : graph
250
+ A NetworkX graph
251
+ nodes_for_star : iterable container
252
+ A container of nodes.
253
+ attr : keyword arguments, optional (default= no attributes)
254
+ Attributes to add to every edge in star.
255
+
256
+ See Also
257
+ --------
258
+ add_path, add_cycle
259
+
260
+ Examples
261
+ --------
262
+ >>> G = nx.Graph()
263
+ >>> nx.add_star(G, [0, 1, 2, 3])
264
+ >>> nx.add_star(G, [10, 11, 12], weight=2)
265
+ """
266
+ nlist = iter(nodes_for_star)
267
+ try:
268
+ v = next(nlist)
269
+ except StopIteration:
270
+ return
271
+ G_to_add_to.add_node(v)
272
+ edges = ((v, n) for n in nlist)
273
+ G_to_add_to.add_edges_from(edges, **attr)
274
+
275
+
276
+ def add_path(G_to_add_to, nodes_for_path, **attr):
277
+ """Add a path to the Graph G_to_add_to.
278
+
279
+ Parameters
280
+ ----------
281
+ G_to_add_to : graph
282
+ A NetworkX graph
283
+ nodes_for_path : iterable container
284
+ A container of nodes. A path will be constructed from
285
+ the nodes (in order) and added to the graph.
286
+ attr : keyword arguments, optional (default= no attributes)
287
+ Attributes to add to every edge in path.
288
+
289
+ See Also
290
+ --------
291
+ add_star, add_cycle
292
+
293
+ Examples
294
+ --------
295
+ >>> G = nx.Graph()
296
+ >>> nx.add_path(G, [0, 1, 2, 3])
297
+ >>> nx.add_path(G, [10, 11, 12], weight=7)
298
+ """
299
+ nlist = iter(nodes_for_path)
300
+ try:
301
+ first_node = next(nlist)
302
+ except StopIteration:
303
+ return
304
+ G_to_add_to.add_node(first_node)
305
+ G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
306
+
307
+
308
+ def add_cycle(G_to_add_to, nodes_for_cycle, **attr):
309
+ """Add a cycle to the Graph G_to_add_to.
310
+
311
+ Parameters
312
+ ----------
313
+ G_to_add_to : graph
314
+ A NetworkX graph
315
+ nodes_for_cycle: iterable container
316
+ A container of nodes. A cycle will be constructed from
317
+ the nodes (in order) and added to the graph.
318
+ attr : keyword arguments, optional (default= no attributes)
319
+ Attributes to add to every edge in cycle.
320
+
321
+ See Also
322
+ --------
323
+ add_path, add_star
324
+
325
+ Examples
326
+ --------
327
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
328
+ >>> nx.add_cycle(G, [0, 1, 2, 3])
329
+ >>> nx.add_cycle(G, [10, 11, 12], weight=7)
330
+ """
331
+ nlist = iter(nodes_for_cycle)
332
+ try:
333
+ first_node = next(nlist)
334
+ except StopIteration:
335
+ return
336
+ G_to_add_to.add_node(first_node)
337
+ G_to_add_to.add_edges_from(
338
+ pairwise(chain((first_node,), nlist), cyclic=True), **attr
339
+ )
340
+
341
+
342
+ def subgraph(G, nbunch):
343
+ """Returns the subgraph induced on nodes in nbunch.
344
+
345
+ Parameters
346
+ ----------
347
+ G : graph
348
+ A NetworkX graph
349
+
350
+ nbunch : list, iterable
351
+ A container of nodes that will be iterated through once (thus
352
+ it should be an iterator or be iterable). Each element of the
353
+ container should be a valid node type: any hashable type except
354
+ None. If nbunch is None, return all edges data in the graph.
355
+ Nodes in nbunch that are not in the graph will be (quietly)
356
+ ignored.
357
+
358
+ Notes
359
+ -----
360
+ subgraph(G) calls G.subgraph()
361
+ """
362
+ return G.subgraph(nbunch)
363
+
364
+
365
+ def induced_subgraph(G, nbunch):
366
+ """Returns a SubGraph view of `G` showing only nodes in nbunch.
367
+
368
+ The induced subgraph of a graph on a set of nodes N is the
369
+ graph with nodes N and edges from G which have both ends in N.
370
+
371
+ Parameters
372
+ ----------
373
+ G : NetworkX Graph
374
+ nbunch : node, container of nodes or None (for all nodes)
375
+
376
+ Returns
377
+ -------
378
+ subgraph : SubGraph View
379
+ A read-only view of the subgraph in `G` induced by the nodes.
380
+ Changes to the graph `G` will be reflected in the view.
381
+
382
+ Notes
383
+ -----
384
+ To create a mutable subgraph with its own copies of nodes
385
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
386
+
387
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
388
+ `G.remove_nodes_from(n in G if n not in set(nbunch))`
389
+
390
+ If you are going to compute subgraphs of your subgraphs you could
391
+ end up with a chain of views that can be very slow once the chain
392
+ has about 15 views in it. If they are all induced subgraphs, you
393
+ can short-cut the chain by making them all subgraphs of the original
394
+ graph. The graph class method `G.subgraph` does this when `G` is
395
+ a subgraph. In contrast, this function allows you to choose to build
396
+ chains or not, as you wish. The returned subgraph is a view on `G`.
397
+
398
+ Examples
399
+ --------
400
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
401
+ >>> H = nx.induced_subgraph(G, [0, 1, 3])
402
+ >>> list(H.edges)
403
+ [(0, 1)]
404
+ >>> list(H.nodes)
405
+ [0, 1, 3]
406
+ """
407
+ induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
408
+ return nx.subgraph_view(G, filter_node=induced_nodes)
409
+
410
+
411
+ def edge_subgraph(G, edges):
412
+ """Returns a view of the subgraph induced by the specified edges.
413
+
414
+ The induced subgraph contains each edge in `edges` and each
415
+ node incident to any of those edges.
416
+
417
+ Parameters
418
+ ----------
419
+ G : NetworkX Graph
420
+ edges : iterable
421
+ An iterable of edges. Edges not present in `G` are ignored.
422
+
423
+ Returns
424
+ -------
425
+ subgraph : SubGraph View
426
+ A read-only edge-induced subgraph of `G`.
427
+ Changes to `G` are reflected in the view.
428
+
429
+ Notes
430
+ -----
431
+ To create a mutable subgraph with its own copies of nodes
432
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
433
+
434
+ If you create a subgraph of a subgraph recursively you can end up
435
+ with a chain of subgraphs that becomes very slow with about 15
436
+ nested subgraph views. Luckily the edge_subgraph filter nests
437
+ nicely so you can use the original graph as G in this function
438
+ to avoid chains. We do not rule out chains programmatically so
439
+ that odd cases like an `edge_subgraph` of a `restricted_view`
440
+ can be created.
441
+
442
+ Examples
443
+ --------
444
+ >>> G = nx.path_graph(5)
445
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
446
+ >>> list(H.nodes)
447
+ [0, 1, 3, 4]
448
+ >>> list(H.edges)
449
+ [(0, 1), (3, 4)]
450
+ """
451
+ nxf = nx.filters
452
+ edges = set(edges)
453
+ nodes = set()
454
+ for e in edges:
455
+ nodes.update(e[:2])
456
+ induced_nodes = nxf.show_nodes(nodes)
457
+ if G.is_multigraph():
458
+ if G.is_directed():
459
+ induced_edges = nxf.show_multidiedges(edges)
460
+ else:
461
+ induced_edges = nxf.show_multiedges(edges)
462
+ else:
463
+ if G.is_directed():
464
+ induced_edges = nxf.show_diedges(edges)
465
+ else:
466
+ induced_edges = nxf.show_edges(edges)
467
+ return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
468
+
469
+
470
+ def restricted_view(G, nodes, edges):
471
+ """Returns a view of `G` with hidden nodes and edges.
472
+
473
+ The resulting subgraph filters out node `nodes` and edges `edges`.
474
+ Filtered out nodes also filter out any of their edges.
475
+
476
+ Parameters
477
+ ----------
478
+ G : NetworkX Graph
479
+ nodes : iterable
480
+ An iterable of nodes. Nodes not present in `G` are ignored.
481
+ edges : iterable
482
+ An iterable of edges. Edges not present in `G` are ignored.
483
+
484
+ Returns
485
+ -------
486
+ subgraph : SubGraph View
487
+ A read-only restricted view of `G` filtering out nodes and edges.
488
+ Changes to `G` are reflected in the view.
489
+
490
+ Notes
491
+ -----
492
+ To create a mutable subgraph with its own copies of nodes
493
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
494
+
495
+ If you create a subgraph of a subgraph recursively you may end up
496
+ with a chain of subgraph views. Such chains can get quite slow
497
+ for lengths near 15. To avoid long chains, try to make your subgraph
498
+ based on the original graph. We do not rule out chains programmatically
499
+ so that odd cases like an `edge_subgraph` of a `restricted_view`
500
+ can be created.
501
+
502
+ Examples
503
+ --------
504
+ >>> G = nx.path_graph(5)
505
+ >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)])
506
+ >>> list(H.nodes)
507
+ [1, 2, 3, 4]
508
+ >>> list(H.edges)
509
+ [(2, 3)]
510
+ """
511
+ nxf = nx.filters
512
+ hide_nodes = nxf.hide_nodes(nodes)
513
+ if G.is_multigraph():
514
+ if G.is_directed():
515
+ hide_edges = nxf.hide_multidiedges(edges)
516
+ else:
517
+ hide_edges = nxf.hide_multiedges(edges)
518
+ else:
519
+ if G.is_directed():
520
+ hide_edges = nxf.hide_diedges(edges)
521
+ else:
522
+ hide_edges = nxf.hide_edges(edges)
523
+ return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
524
+
525
+
526
+ def to_directed(graph):
527
+ """Returns a directed view of the graph `graph`.
528
+
529
+ Identical to graph.to_directed(as_view=True)
530
+ Note that graph.to_directed defaults to `as_view=False`
531
+ while this function always provides a view.
532
+ """
533
+ return graph.to_directed(as_view=True)
534
+
535
+
536
+ def to_undirected(graph):
537
+ """Returns an undirected view of the graph `graph`.
538
+
539
+ Identical to graph.to_undirected(as_view=True)
540
+ Note that graph.to_undirected defaults to `as_view=False`
541
+ while this function always provides a view.
542
+ """
543
+ return graph.to_undirected(as_view=True)
544
+
545
+
546
+ def create_empty_copy(G, with_data=True):
547
+ """Returns a copy of the graph G with all of the edges removed.
548
+
549
+ Parameters
550
+ ----------
551
+ G : graph
552
+ A NetworkX graph
553
+
554
+ with_data : bool (default=True)
555
+ Propagate Graph and Nodes data to the new graph.
556
+
557
+ See Also
558
+ --------
559
+ empty_graph
560
+
561
+ """
562
+ H = G.__class__()
563
+ H.add_nodes_from(G.nodes(data=with_data))
564
+ if with_data:
565
+ H.graph.update(G.graph)
566
+ return H
567
+
568
+
569
+ def set_node_attributes(G, values, name=None):
570
+ """Sets node attributes from a given value or dictionary of values.
571
+
572
+ .. Warning:: The call order of arguments `values` and `name`
573
+ switched between v1.x & v2.x.
574
+
575
+ Parameters
576
+ ----------
577
+ G : NetworkX Graph
578
+
579
+ values : scalar value, dict-like
580
+ What the node attribute should be set to. If `values` is
581
+ not a dictionary, then it is treated as a single attribute value
582
+ that is then applied to every node in `G`. This means that if
583
+ you provide a mutable object, like a list, updates to that object
584
+ will be reflected in the node attribute for every node.
585
+ The attribute name will be `name`.
586
+
587
+ If `values` is a dict or a dict of dict, it should be keyed
588
+ by node to either an attribute value or a dict of attribute key/value
589
+ pairs used to update the node's attributes.
590
+
591
+ name : string (optional, default=None)
592
+ Name of the node attribute to set if values is a scalar.
593
+
594
+ Examples
595
+ --------
596
+ After computing some property of the nodes of a graph, you may want
597
+ to assign a node attribute to store the value of that property for
598
+ each node::
599
+
600
+ >>> G = nx.path_graph(3)
601
+ >>> bb = nx.betweenness_centrality(G)
602
+ >>> isinstance(bb, dict)
603
+ True
604
+ >>> nx.set_node_attributes(G, bb, "betweenness")
605
+ >>> G.nodes[1]["betweenness"]
606
+ 1.0
607
+
608
+ If you provide a list as the second argument, updates to the list
609
+ will be reflected in the node attribute for each node::
610
+
611
+ >>> G = nx.path_graph(3)
612
+ >>> labels = []
613
+ >>> nx.set_node_attributes(G, labels, "labels")
614
+ >>> labels.append("foo")
615
+ >>> G.nodes[0]["labels"]
616
+ ['foo']
617
+ >>> G.nodes[1]["labels"]
618
+ ['foo']
619
+ >>> G.nodes[2]["labels"]
620
+ ['foo']
621
+
622
+ If you provide a dictionary of dictionaries as the second argument,
623
+ the outer dictionary is assumed to be keyed by node to an inner
624
+ dictionary of node attributes for that node::
625
+
626
+ >>> G = nx.path_graph(3)
627
+ >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}}
628
+ >>> nx.set_node_attributes(G, attrs)
629
+ >>> G.nodes[0]["attr1"]
630
+ 20
631
+ >>> G.nodes[0]["attr2"]
632
+ 'nothing'
633
+ >>> G.nodes[1]["attr2"]
634
+ 3
635
+ >>> G.nodes[2]
636
+ {}
637
+
638
+ Note that if the dictionary contains nodes that are not in `G`, the
639
+ values are silently ignored::
640
+
641
+ >>> G = nx.Graph()
642
+ >>> G.add_node(0)
643
+ >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color")
644
+ >>> G.nodes[0]["color"]
645
+ 'red'
646
+ >>> 1 in G.nodes
647
+ False
648
+
649
+ """
650
+ # Set node attributes based on type of `values`
651
+ if name is not None: # `values` must not be a dict of dict
652
+ try: # `values` is a dict
653
+ for n, v in values.items():
654
+ try:
655
+ G.nodes[n][name] = values[n]
656
+ except KeyError:
657
+ pass
658
+ except AttributeError: # `values` is a constant
659
+ for n in G:
660
+ G.nodes[n][name] = values
661
+ else: # `values` must be dict of dict
662
+ for n, d in values.items():
663
+ try:
664
+ G.nodes[n].update(d)
665
+ except KeyError:
666
+ pass
667
+ nx._clear_cache(G)
668
+
669
+
670
+ def get_node_attributes(G, name, default=None):
671
+ """Get node attributes from graph
672
+
673
+ Parameters
674
+ ----------
675
+ G : NetworkX Graph
676
+
677
+ name : string
678
+ Attribute name
679
+
680
+ default: object (default=None)
681
+ Default value of the node attribute if there is no value set for that
682
+ node in graph. If `None` then nodes without this attribute are not
683
+ included in the returned dict.
684
+
685
+ Returns
686
+ -------
687
+ Dictionary of attributes keyed by node.
688
+
689
+ Examples
690
+ --------
691
+ >>> G = nx.Graph()
692
+ >>> G.add_nodes_from([1, 2, 3], color="red")
693
+ >>> color = nx.get_node_attributes(G, "color")
694
+ >>> color[1]
695
+ 'red'
696
+ >>> G.add_node(4)
697
+ >>> color = nx.get_node_attributes(G, "color", default="yellow")
698
+ >>> color[4]
699
+ 'yellow'
700
+ """
701
+ if default is not None:
702
+ return {n: d.get(name, default) for n, d in G.nodes.items()}
703
+ return {n: d[name] for n, d in G.nodes.items() if name in d}
704
+
705
+
706
+ def remove_node_attributes(G, *attr_names, nbunch=None):
707
+ """Remove node attributes from all nodes in the graph.
708
+
709
+ Parameters
710
+ ----------
711
+ G : NetworkX Graph
712
+
713
+ *attr_names : List of Strings
714
+ The attribute names to remove from the graph.
715
+
716
+ nbunch : List of Nodes
717
+ Remove the node attributes only from the nodes in this list.
718
+
719
+ Examples
720
+ --------
721
+ >>> G = nx.Graph()
722
+ >>> G.add_nodes_from([1, 2, 3], color="blue")
723
+ >>> nx.get_node_attributes(G, "color")
724
+ {1: 'blue', 2: 'blue', 3: 'blue'}
725
+ >>> nx.remove_node_attributes(G, "color")
726
+ >>> nx.get_node_attributes(G, "color")
727
+ {}
728
+ """
729
+
730
+ if nbunch is None:
731
+ nbunch = G.nodes()
732
+
733
+ for attr in attr_names:
734
+ for n, d in G.nodes(data=True):
735
+ if n in nbunch:
736
+ try:
737
+ del d[attr]
738
+ except KeyError:
739
+ pass
740
+
741
+
742
+ def set_edge_attributes(G, values, name=None):
743
+ """Sets edge attributes from a given value or dictionary of values.
744
+
745
+ .. Warning:: The call order of arguments `values` and `name`
746
+ switched between v1.x & v2.x.
747
+
748
+ Parameters
749
+ ----------
750
+ G : NetworkX Graph
751
+
752
+ values : scalar value, dict-like
753
+ What the edge attribute should be set to. If `values` is
754
+ not a dictionary, then it is treated as a single attribute value
755
+ that is then applied to every edge in `G`. This means that if
756
+ you provide a mutable object, like a list, updates to that object
757
+ will be reflected in the edge attribute for each edge. The attribute
758
+ name will be `name`.
759
+
760
+ If `values` is a dict or a dict of dict, it should be keyed
761
+ by edge tuple to either an attribute value or a dict of attribute
762
+ key/value pairs used to update the edge's attributes.
763
+ For multigraphs, the edge tuples must be of the form ``(u, v, key)``,
764
+ where `u` and `v` are nodes and `key` is the edge key.
765
+ For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
766
+
767
+ name : string (optional, default=None)
768
+ Name of the edge attribute to set if values is a scalar.
769
+
770
+ Examples
771
+ --------
772
+ After computing some property of the edges of a graph, you may want
773
+ to assign a edge attribute to store the value of that property for
774
+ each edge::
775
+
776
+ >>> G = nx.path_graph(3)
777
+ >>> bb = nx.edge_betweenness_centrality(G, normalized=False)
778
+ >>> nx.set_edge_attributes(G, bb, "betweenness")
779
+ >>> G.edges[1, 2]["betweenness"]
780
+ 2.0
781
+
782
+ If you provide a list as the second argument, updates to the list
783
+ will be reflected in the edge attribute for each edge::
784
+
785
+ >>> labels = []
786
+ >>> nx.set_edge_attributes(G, labels, "labels")
787
+ >>> labels.append("foo")
788
+ >>> G.edges[0, 1]["labels"]
789
+ ['foo']
790
+ >>> G.edges[1, 2]["labels"]
791
+ ['foo']
792
+
793
+ If you provide a dictionary of dictionaries as the second argument,
794
+ the entire dictionary will be used to update edge attributes::
795
+
796
+ >>> G = nx.path_graph(3)
797
+ >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}}
798
+ >>> nx.set_edge_attributes(G, attrs)
799
+ >>> G[0][1]["attr1"]
800
+ 20
801
+ >>> G[0][1]["attr2"]
802
+ 'nothing'
803
+ >>> G[1][2]["attr2"]
804
+ 3
805
+
806
+ The attributes of one Graph can be used to set those of another.
807
+
808
+ >>> H = nx.path_graph(3)
809
+ >>> nx.set_edge_attributes(H, G.edges)
810
+
811
+ Note that if the dict contains edges that are not in `G`, they are
812
+ silently ignored::
813
+
814
+ >>> G = nx.Graph([(0, 1)])
815
+ >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}})
816
+ >>> (1, 2) in G.edges()
817
+ False
818
+
819
+ For multigraphs, the `values` dict is expected to be keyed by 3-tuples
820
+ including the edge key::
821
+
822
+ >>> MG = nx.MultiGraph()
823
+ >>> edges = [(0, 1), (0, 1)]
824
+ >>> MG.add_edges_from(edges) # Returns list of edge keys
825
+ [0, 1]
826
+ >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
827
+ >>> nx.set_edge_attributes(MG, attributes)
828
+ >>> MG[0][1][0]["cost"]
829
+ 21
830
+ >>> MG[0][1][1]["cost"]
831
+ 7
832
+
833
+ If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
834
+ multiedge to a 2-tuple edge and the last multiedge's attribute value will
835
+ overwrite the previous values. Continuing from the previous case we get::
836
+
837
+ >>> H = nx.path_graph([0, 1, 2])
838
+ >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
839
+ >>> nx.get_edge_attributes(H, "cost")
840
+ {(0, 1): 7}
841
+
842
+ """
843
+ if name is not None:
844
+ # `values` does not contain attribute names
845
+ try:
846
+ # if `values` is a dict using `.items()` => {edge: value}
847
+ if G.is_multigraph():
848
+ for (u, v, key), value in values.items():
849
+ try:
850
+ G._adj[u][v][key][name] = value
851
+ except KeyError:
852
+ pass
853
+ else:
854
+ for (u, v), value in values.items():
855
+ try:
856
+ G._adj[u][v][name] = value
857
+ except KeyError:
858
+ pass
859
+ except AttributeError:
860
+ # treat `values` as a constant
861
+ for u, v, data in G.edges(data=True):
862
+ data[name] = values
863
+ else:
864
+ # `values` consists of doct-of-dict {edge: {attr: value}} shape
865
+ if G.is_multigraph():
866
+ for (u, v, key), d in values.items():
867
+ try:
868
+ G._adj[u][v][key].update(d)
869
+ except KeyError:
870
+ pass
871
+ else:
872
+ for (u, v), d in values.items():
873
+ try:
874
+ G._adj[u][v].update(d)
875
+ except KeyError:
876
+ pass
877
+ nx._clear_cache(G)
878
+
879
+
880
+ def get_edge_attributes(G, name, default=None):
881
+ """Get edge attributes from graph
882
+
883
+ Parameters
884
+ ----------
885
+ G : NetworkX Graph
886
+
887
+ name : string
888
+ Attribute name
889
+
890
+ default: object (default=None)
891
+ Default value of the edge attribute if there is no value set for that
892
+ edge in graph. If `None` then edges without this attribute are not
893
+ included in the returned dict.
894
+
895
+ Returns
896
+ -------
897
+ Dictionary of attributes keyed by edge. For (di)graphs, the keys are
898
+ 2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
899
+ the form: (u, v, key).
900
+
901
+ Examples
902
+ --------
903
+ >>> G = nx.Graph()
904
+ >>> nx.add_path(G, [1, 2, 3], color="red")
905
+ >>> color = nx.get_edge_attributes(G, "color")
906
+ >>> color[(1, 2)]
907
+ 'red'
908
+ >>> G.add_edge(3, 4)
909
+ >>> color = nx.get_edge_attributes(G, "color", default="yellow")
910
+ >>> color[(3, 4)]
911
+ 'yellow'
912
+ """
913
+ if G.is_multigraph():
914
+ edges = G.edges(keys=True, data=True)
915
+ else:
916
+ edges = G.edges(data=True)
917
+ if default is not None:
918
+ return {x[:-1]: x[-1].get(name, default) for x in edges}
919
+ return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
920
+
921
+
922
+ def remove_edge_attributes(G, *attr_names, ebunch=None):
923
+ """Remove edge attributes from all edges in the graph.
924
+
925
+ Parameters
926
+ ----------
927
+ G : NetworkX Graph
928
+
929
+ *attr_names : List of Strings
930
+ The attribute names to remove from the graph.
931
+
932
+ Examples
933
+ --------
934
+ >>> G = nx.path_graph(3)
935
+ >>> nx.set_edge_attributes(G, {(u, v): u + v for u, v in G.edges()}, name="weight")
936
+ >>> nx.get_edge_attributes(G, "weight")
937
+ {(0, 1): 1, (1, 2): 3}
938
+ >>> remove_edge_attributes(G, "weight")
939
+ >>> nx.get_edge_attributes(G, "weight")
940
+ {}
941
+ """
942
+ if ebunch is None:
943
+ ebunch = G.edges(keys=True) if G.is_multigraph() else G.edges()
944
+
945
+ for attr in attr_names:
946
+ edges = (
947
+ G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
948
+ )
949
+ for *e, d in edges:
950
+ if tuple(e) in ebunch:
951
+ try:
952
+ del d[attr]
953
+ except KeyError:
954
+ pass
955
+
956
+
957
+ def all_neighbors(graph, node):
958
+ """Returns all of the neighbors of a node in the graph.
959
+
960
+ If the graph is directed returns predecessors as well as successors.
961
+
962
+ Parameters
963
+ ----------
964
+ graph : NetworkX graph
965
+ Graph to find neighbors.
966
+
967
+ node : node
968
+ The node whose neighbors will be returned.
969
+
970
+ Returns
971
+ -------
972
+ neighbors : iterator
973
+ Iterator of neighbors
974
+ """
975
+ if graph.is_directed():
976
+ values = chain(graph.predecessors(node), graph.successors(node))
977
+ else:
978
+ values = graph.neighbors(node)
979
+ return values
980
+
981
+
982
+ def non_neighbors(graph, node):
983
+ """Returns the non-neighbors of the node in the graph.
984
+
985
+ Parameters
986
+ ----------
987
+ graph : NetworkX graph
988
+ Graph to find neighbors.
989
+
990
+ node : node
991
+ The node whose neighbors will be returned.
992
+
993
+ Returns
994
+ -------
995
+ non_neighbors : set
996
+ Set of nodes in the graph that are not neighbors of the node.
997
+ """
998
+ return graph._adj.keys() - graph._adj[node].keys() - {node}
999
+
1000
+
1001
+ def non_edges(graph):
1002
+ """Returns the nonexistent edges in the graph.
1003
+
1004
+ Parameters
1005
+ ----------
1006
+ graph : NetworkX graph.
1007
+ Graph to find nonexistent edges.
1008
+
1009
+ Returns
1010
+ -------
1011
+ non_edges : iterator
1012
+ Iterator of edges that are not in the graph.
1013
+ """
1014
+ if graph.is_directed():
1015
+ for u in graph:
1016
+ for v in non_neighbors(graph, u):
1017
+ yield (u, v)
1018
+ else:
1019
+ nodes = set(graph)
1020
+ while nodes:
1021
+ u = nodes.pop()
1022
+ for v in nodes - set(graph[u]):
1023
+ yield (u, v)
1024
+
1025
+
1026
+ @not_implemented_for("directed")
1027
+ def common_neighbors(G, u, v):
1028
+ """Returns the common neighbors of two nodes in a graph.
1029
+
1030
+ Parameters
1031
+ ----------
1032
+ G : graph
1033
+ A NetworkX undirected graph.
1034
+
1035
+ u, v : nodes
1036
+ Nodes in the graph.
1037
+
1038
+ Returns
1039
+ -------
1040
+ cnbors : set
1041
+ Set of common neighbors of u and v in the graph.
1042
+
1043
+ Raises
1044
+ ------
1045
+ NetworkXError
1046
+ If u or v is not a node in the graph.
1047
+
1048
+ Examples
1049
+ --------
1050
+ >>> G = nx.complete_graph(5)
1051
+ >>> sorted(nx.common_neighbors(G, 0, 1))
1052
+ [2, 3, 4]
1053
+ """
1054
+ if u not in G:
1055
+ raise nx.NetworkXError("u is not in the graph.")
1056
+ if v not in G:
1057
+ raise nx.NetworkXError("v is not in the graph.")
1058
+
1059
+ return G._adj[u].keys() & G._adj[v].keys() - {u, v}
1060
+
1061
+
1062
+ def is_weighted(G, edge=None, weight="weight"):
1063
+ """Returns True if `G` has weighted edges.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ G : graph
1068
+ A NetworkX graph.
1069
+
1070
+ edge : tuple, optional
1071
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1072
+ None, then every edge in `G` is tested.
1073
+
1074
+ weight: string, optional
1075
+ The attribute name used to query for edge weights.
1076
+
1077
+ Returns
1078
+ -------
1079
+ bool
1080
+ A boolean signifying if `G`, or the specified edge, is weighted.
1081
+
1082
+ Raises
1083
+ ------
1084
+ NetworkXError
1085
+ If the specified edge does not exist.
1086
+
1087
+ Examples
1088
+ --------
1089
+ >>> G = nx.path_graph(4)
1090
+ >>> nx.is_weighted(G)
1091
+ False
1092
+ >>> nx.is_weighted(G, (2, 3))
1093
+ False
1094
+
1095
+ >>> G = nx.DiGraph()
1096
+ >>> G.add_edge(1, 2, weight=1)
1097
+ >>> nx.is_weighted(G)
1098
+ True
1099
+
1100
+ """
1101
+ if edge is not None:
1102
+ data = G.get_edge_data(*edge)
1103
+ if data is None:
1104
+ msg = f"Edge {edge!r} does not exist."
1105
+ raise nx.NetworkXError(msg)
1106
+ return weight in data
1107
+
1108
+ if is_empty(G):
1109
+ # Special handling required since: all([]) == True
1110
+ return False
1111
+
1112
+ return all(weight in data for u, v, data in G.edges(data=True))
1113
+
1114
+
1115
+ @nx._dispatchable(edge_attrs="weight")
1116
+ def is_negatively_weighted(G, edge=None, weight="weight"):
1117
+ """Returns True if `G` has negatively weighted edges.
1118
+
1119
+ Parameters
1120
+ ----------
1121
+ G : graph
1122
+ A NetworkX graph.
1123
+
1124
+ edge : tuple, optional
1125
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1126
+ None, then every edge in `G` is tested.
1127
+
1128
+ weight: string, optional
1129
+ The attribute name used to query for edge weights.
1130
+
1131
+ Returns
1132
+ -------
1133
+ bool
1134
+ A boolean signifying if `G`, or the specified edge, is negatively
1135
+ weighted.
1136
+
1137
+ Raises
1138
+ ------
1139
+ NetworkXError
1140
+ If the specified edge does not exist.
1141
+
1142
+ Examples
1143
+ --------
1144
+ >>> G = nx.Graph()
1145
+ >>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
1146
+ >>> G.add_edge(1, 2, weight=4)
1147
+ >>> nx.is_negatively_weighted(G, (1, 2))
1148
+ False
1149
+ >>> G[2][4]["weight"] = -2
1150
+ >>> nx.is_negatively_weighted(G)
1151
+ True
1152
+ >>> G = nx.DiGraph()
1153
+ >>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)]
1154
+ >>> G.add_weighted_edges_from(edges)
1155
+ >>> nx.is_negatively_weighted(G)
1156
+ True
1157
+
1158
+ """
1159
+ if edge is not None:
1160
+ data = G.get_edge_data(*edge)
1161
+ if data is None:
1162
+ msg = f"Edge {edge!r} does not exist."
1163
+ raise nx.NetworkXError(msg)
1164
+ return weight in data and data[weight] < 0
1165
+
1166
+ return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
1167
+
1168
+
1169
+ def is_empty(G):
1170
+ """Returns True if `G` has no edges.
1171
+
1172
+ Parameters
1173
+ ----------
1174
+ G : graph
1175
+ A NetworkX graph.
1176
+
1177
+ Returns
1178
+ -------
1179
+ bool
1180
+ True if `G` has no edges, and False otherwise.
1181
+
1182
+ Notes
1183
+ -----
1184
+ An empty graph can have nodes but not edges. The empty graph with zero
1185
+ nodes is known as the null graph. This is an $O(n)$ operation where n
1186
+ is the number of nodes in the graph.
1187
+
1188
+ """
1189
+ return not any(G._adj.values())
1190
+
1191
+
1192
+ def nodes_with_selfloops(G):
1193
+ """Returns an iterator over nodes with self loops.
1194
+
1195
+ A node with a self loop has an edge with both ends adjacent
1196
+ to that node.
1197
+
1198
+ Returns
1199
+ -------
1200
+ nodelist : iterator
1201
+ A iterator over nodes with self loops.
1202
+
1203
+ See Also
1204
+ --------
1205
+ selfloop_edges, number_of_selfloops
1206
+
1207
+ Examples
1208
+ --------
1209
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1210
+ >>> G.add_edge(1, 1)
1211
+ >>> G.add_edge(1, 2)
1212
+ >>> list(nx.nodes_with_selfloops(G))
1213
+ [1]
1214
+
1215
+ """
1216
+ return (n for n, nbrs in G._adj.items() if n in nbrs)
1217
+
1218
+
1219
+ def selfloop_edges(G, data=False, keys=False, default=None):
1220
+ """Returns an iterator over selfloop edges.
1221
+
1222
+ A selfloop edge has the same node at both ends.
1223
+
1224
+ Parameters
1225
+ ----------
1226
+ G : graph
1227
+ A NetworkX graph.
1228
+ data : string or bool, optional (default=False)
1229
+ Return selfloop edges as two tuples (u, v) (data=False)
1230
+ or three-tuples (u, v, datadict) (data=True)
1231
+ or three-tuples (u, v, datavalue) (data='attrname')
1232
+ keys : bool, optional (default=False)
1233
+ If True, return edge keys with each edge.
1234
+ default : value, optional (default=None)
1235
+ Value used for edges that don't have the requested attribute.
1236
+ Only relevant if data is not True or False.
1237
+
1238
+ Returns
1239
+ -------
1240
+ edgeiter : iterator over edge tuples
1241
+ An iterator over all selfloop edges.
1242
+
1243
+ See Also
1244
+ --------
1245
+ nodes_with_selfloops, number_of_selfloops
1246
+
1247
+ Examples
1248
+ --------
1249
+ >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc
1250
+ >>> ekey = G.add_edge(1, 1)
1251
+ >>> ekey = G.add_edge(1, 2)
1252
+ >>> list(nx.selfloop_edges(G))
1253
+ [(1, 1)]
1254
+ >>> list(nx.selfloop_edges(G, data=True))
1255
+ [(1, 1, {})]
1256
+ >>> list(nx.selfloop_edges(G, keys=True))
1257
+ [(1, 1, 0)]
1258
+ >>> list(nx.selfloop_edges(G, keys=True, data=True))
1259
+ [(1, 1, 0, {})]
1260
+ """
1261
+ if data is True:
1262
+ if G.is_multigraph():
1263
+ if keys is True:
1264
+ return (
1265
+ (n, n, k, d)
1266
+ for n, nbrs in G._adj.items()
1267
+ if n in nbrs
1268
+ for k, d in nbrs[n].items()
1269
+ )
1270
+ else:
1271
+ return (
1272
+ (n, n, d)
1273
+ for n, nbrs in G._adj.items()
1274
+ if n in nbrs
1275
+ for d in nbrs[n].values()
1276
+ )
1277
+ else:
1278
+ return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs)
1279
+ elif data is not False:
1280
+ if G.is_multigraph():
1281
+ if keys is True:
1282
+ return (
1283
+ (n, n, k, d.get(data, default))
1284
+ for n, nbrs in G._adj.items()
1285
+ if n in nbrs
1286
+ for k, d in nbrs[n].items()
1287
+ )
1288
+ else:
1289
+ return (
1290
+ (n, n, d.get(data, default))
1291
+ for n, nbrs in G._adj.items()
1292
+ if n in nbrs
1293
+ for d in nbrs[n].values()
1294
+ )
1295
+ else:
1296
+ return (
1297
+ (n, n, nbrs[n].get(data, default))
1298
+ for n, nbrs in G._adj.items()
1299
+ if n in nbrs
1300
+ )
1301
+ else:
1302
+ if G.is_multigraph():
1303
+ if keys is True:
1304
+ return (
1305
+ (n, n, k)
1306
+ for n, nbrs in G._adj.items()
1307
+ if n in nbrs
1308
+ for k in nbrs[n]
1309
+ )
1310
+ else:
1311
+ return (
1312
+ (n, n)
1313
+ for n, nbrs in G._adj.items()
1314
+ if n in nbrs
1315
+ for i in range(len(nbrs[n])) # for easy edge removal (#4068)
1316
+ )
1317
+ else:
1318
+ return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
1319
+
1320
+
1321
+ def number_of_selfloops(G):
1322
+ """Returns the number of selfloop edges.
1323
+
1324
+ A selfloop edge has the same node at both ends.
1325
+
1326
+ Returns
1327
+ -------
1328
+ nloops : int
1329
+ The number of selfloops.
1330
+
1331
+ See Also
1332
+ --------
1333
+ nodes_with_selfloops, selfloop_edges
1334
+
1335
+ Examples
1336
+ --------
1337
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1338
+ >>> G.add_edge(1, 1)
1339
+ >>> G.add_edge(1, 2)
1340
+ >>> nx.number_of_selfloops(G)
1341
+ 1
1342
+ """
1343
+ return sum(1 for _ in nx.selfloop_edges(G))
1344
+
1345
+
1346
+ def is_path(G, path):
1347
+ """Returns whether or not the specified path exists.
1348
+
1349
+ For it to return True, every node on the path must exist and
1350
+ each consecutive pair must be connected via one or more edges.
1351
+
1352
+ Parameters
1353
+ ----------
1354
+ G : graph
1355
+ A NetworkX graph.
1356
+
1357
+ path : list
1358
+ A list of nodes which defines the path to traverse
1359
+
1360
+ Returns
1361
+ -------
1362
+ bool
1363
+ True if `path` is a valid path in `G`
1364
+
1365
+ """
1366
+ try:
1367
+ return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path))
1368
+ except (KeyError, TypeError):
1369
+ return False
1370
+
1371
+
1372
+ def path_weight(G, path, weight):
1373
+ """Returns total cost associated with specified path and weight
1374
+
1375
+ Parameters
1376
+ ----------
1377
+ G : graph
1378
+ A NetworkX graph.
1379
+
1380
+ path: list
1381
+ A list of node labels which defines the path to traverse
1382
+
1383
+ weight: string
1384
+ A string indicating which edge attribute to use for path cost
1385
+
1386
+ Returns
1387
+ -------
1388
+ cost: int or float
1389
+ An integer or a float representing the total cost with respect to the
1390
+ specified weight of the specified path
1391
+
1392
+ Raises
1393
+ ------
1394
+ NetworkXNoPath
1395
+ If the specified edge does not exist.
1396
+ """
1397
+ multigraph = G.is_multigraph()
1398
+ cost = 0
1399
+
1400
+ if not nx.is_path(G, path):
1401
+ raise nx.NetworkXNoPath("path does not exist")
1402
+ for node, nbr in nx.utils.pairwise(path):
1403
+ if multigraph:
1404
+ cost += min(v[weight] for v in G._adj[node][nbr].values())
1405
+ else:
1406
+ cost += G._adj[node][nbr][weight]
1407
+ return cost
deepseek/lib/python3.10/site-packages/networkx/classes/graph.py ADDED
@@ -0,0 +1,2058 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for undirected graphs.
2
+
3
+ The Graph class allows any hashable object as a node
4
+ and can associate key/value attribute pairs with each undirected edge.
5
+
6
+ Self-loops are allowed but multiple edges are not (see MultiGraph).
7
+
8
+ For directed graphs see DiGraph and MultiDiGraph.
9
+ """
10
+
11
+ from copy import deepcopy
12
+ from functools import cached_property
13
+
14
+ import networkx as nx
15
+ from networkx import convert
16
+ from networkx.classes.coreviews import AdjacencyView
17
+ from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
18
+ from networkx.exception import NetworkXError
19
+
20
+ __all__ = ["Graph"]
21
+
22
+
23
+ class _CachedPropertyResetterAdj:
24
+ """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
25
+
26
+ This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
27
+ ``G._adj`` is set to a new value.
28
+
29
+ This object sits on a class and ensures that any instance of that
30
+ class clears its cached property "adj" whenever the underlying
31
+ instance attribute "_adj" is set to a new object. It only affects
32
+ the set process of the obj._adj attribute. All get/del operations
33
+ act as they normally would.
34
+
35
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
36
+ """
37
+
38
+ def __set__(self, obj, value):
39
+ od = obj.__dict__
40
+ od["_adj"] = value
41
+ # reset cached properties
42
+ props = ["adj", "edges", "degree"]
43
+ for prop in props:
44
+ if prop in od:
45
+ del od[prop]
46
+
47
+
48
+ class _CachedPropertyResetterNode:
49
+ """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
50
+
51
+ This assumes that the ``cached_property`` ``G.node`` should be reset whenever
52
+ ``G._node`` is set to a new value.
53
+
54
+ This object sits on a class and ensures that any instance of that
55
+ class clears its cached property "nodes" whenever the underlying
56
+ instance attribute "_node" is set to a new object. It only affects
57
+ the set process of the obj._adj attribute. All get/del operations
58
+ act as they normally would.
59
+
60
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
61
+ """
62
+
63
+ def __set__(self, obj, value):
64
+ od = obj.__dict__
65
+ od["_node"] = value
66
+ # reset cached properties
67
+ if "nodes" in od:
68
+ del od["nodes"]
69
+
70
+
71
+ class Graph:
72
+ """
73
+ Base class for undirected graphs.
74
+
75
+ A Graph stores nodes and edges with optional data, or attributes.
76
+
77
+ Graphs hold undirected edges. Self loops are allowed but multiple
78
+ (parallel) edges are not.
79
+
80
+ Nodes can be arbitrary (hashable) Python objects with optional
81
+ key/value attributes, except that `None` is not allowed as a node.
82
+
83
+ Edges are represented as links between nodes with optional
84
+ key/value attributes.
85
+
86
+ Parameters
87
+ ----------
88
+ incoming_graph_data : input graph (optional, default: None)
89
+ Data to initialize graph. If None (default) an empty
90
+ graph is created. The data can be any format that is supported
91
+ by the to_networkx_graph() function, currently including edge list,
92
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
93
+ sparse matrix, or PyGraphviz graph.
94
+
95
+ attr : keyword arguments, optional (default= no attributes)
96
+ Attributes to add to graph as key=value pairs.
97
+
98
+ See Also
99
+ --------
100
+ DiGraph
101
+ MultiGraph
102
+ MultiDiGraph
103
+
104
+ Examples
105
+ --------
106
+ Create an empty graph structure (a "null graph") with no nodes and
107
+ no edges.
108
+
109
+ >>> G = nx.Graph()
110
+
111
+ G can be grown in several ways.
112
+
113
+ **Nodes:**
114
+
115
+ Add one node at a time:
116
+
117
+ >>> G.add_node(1)
118
+
119
+ Add the nodes from any container (a list, dict, set or
120
+ even the lines from a file or the nodes from another graph).
121
+
122
+ >>> G.add_nodes_from([2, 3])
123
+ >>> G.add_nodes_from(range(100, 110))
124
+ >>> H = nx.path_graph(10)
125
+ >>> G.add_nodes_from(H)
126
+
127
+ In addition to strings and integers any hashable Python object
128
+ (except None) can represent a node, e.g. a customized node object,
129
+ or even another Graph.
130
+
131
+ >>> G.add_node(H)
132
+
133
+ **Edges:**
134
+
135
+ G can also be grown by adding edges.
136
+
137
+ Add one edge,
138
+
139
+ >>> G.add_edge(1, 2)
140
+
141
+ a list of edges,
142
+
143
+ >>> G.add_edges_from([(1, 2), (1, 3)])
144
+
145
+ or a collection of edges,
146
+
147
+ >>> G.add_edges_from(H.edges)
148
+
149
+ If some edges connect nodes not yet in the graph, the nodes
150
+ are added automatically. There are no errors when adding
151
+ nodes or edges that already exist.
152
+
153
+ **Attributes:**
154
+
155
+ Each graph, node, and edge can hold key/value attribute pairs
156
+ in an associated attribute dictionary (the keys must be hashable).
157
+ By default these are empty, but can be added or changed using
158
+ add_edge, add_node or direct manipulation of the attribute
159
+ dictionaries named graph, node and edge respectively.
160
+
161
+ >>> G = nx.Graph(day="Friday")
162
+ >>> G.graph
163
+ {'day': 'Friday'}
164
+
165
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
166
+
167
+ >>> G.add_node(1, time="5pm")
168
+ >>> G.add_nodes_from([3], time="2pm")
169
+ >>> G.nodes[1]
170
+ {'time': '5pm'}
171
+ >>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes
172
+ >>> del G.nodes[1]["room"] # remove attribute
173
+ >>> list(G.nodes(data=True))
174
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
175
+
176
+ Add edge attributes using add_edge(), add_edges_from(), subscript
177
+ notation, or G.edges.
178
+
179
+ >>> G.add_edge(1, 2, weight=4.7)
180
+ >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
181
+ >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
182
+ >>> G[1][2]["weight"] = 4.7
183
+ >>> G.edges[1, 2]["weight"] = 4
184
+
185
+ Warning: we protect the graph data structure by making `G.edges` a
186
+ read-only dict-like structure. However, you can assign to attributes
187
+ in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
188
+ data attributes: `G.edges[1, 2]['weight'] = 4`
189
+ (For multigraphs: `MG.edges[u, v, key][name] = value`).
190
+
191
+ **Shortcuts:**
192
+
193
+ Many common graph features allow python syntax to speed reporting.
194
+
195
+ >>> 1 in G # check if node in graph
196
+ True
197
+ >>> [n for n in G if n < 3] # iterate through nodes
198
+ [1, 2]
199
+ >>> len(G) # number of nodes in graph
200
+ 5
201
+
202
+ Often the best way to traverse all edges of a graph is via the neighbors.
203
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
204
+
205
+ >>> for n, nbrsdict in G.adjacency():
206
+ ... for nbr, eattr in nbrsdict.items():
207
+ ... if "weight" in eattr:
208
+ ... # Do something useful with the edges
209
+ ... pass
210
+
211
+ But the edges() method is often more convenient:
212
+
213
+ >>> for u, v, weight in G.edges.data("weight"):
214
+ ... if weight is not None:
215
+ ... # Do something useful with the edges
216
+ ... pass
217
+
218
+ **Reporting:**
219
+
220
+ Simple graph information is obtained using object-attributes and methods.
221
+ Reporting typically provides views instead of containers to reduce memory
222
+ usage. The views update as the graph is updated similarly to dict-views.
223
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
224
+ via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
225
+ (e.g. `nodes.items()`, `nodes.data('color')`,
226
+ `nodes.data('color', default='blue')` and similarly for `edges`)
227
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
228
+
229
+ For details on these and other miscellaneous methods, see below.
230
+
231
+ **Subclasses (Advanced):**
232
+
233
+ The Graph class uses a dict-of-dict-of-dict data structure.
234
+ The outer dict (node_dict) holds adjacency information keyed by node.
235
+ The next dict (adjlist_dict) represents the adjacency information and holds
236
+ edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
237
+ the edge data and holds edge attribute values keyed by attribute names.
238
+
239
+ Each of these three dicts can be replaced in a subclass by a user defined
240
+ dict-like object. In general, the dict-like features should be
241
+ maintained but extra features can be added. To replace one of the
242
+ dicts create a new graph class by changing the class(!) variable
243
+ holding the factory for that dict-like structure.
244
+
245
+ node_dict_factory : function, (default: dict)
246
+ Factory function to be used to create the dict containing node
247
+ attributes, keyed by node id.
248
+ It should require no arguments and return a dict-like object
249
+
250
+ node_attr_dict_factory: function, (default: dict)
251
+ Factory function to be used to create the node attribute
252
+ dict which holds attribute values keyed by attribute name.
253
+ It should require no arguments and return a dict-like object
254
+
255
+ adjlist_outer_dict_factory : function, (default: dict)
256
+ Factory function to be used to create the outer-most dict
257
+ in the data structure that holds adjacency info keyed by node.
258
+ It should require no arguments and return a dict-like object.
259
+
260
+ adjlist_inner_dict_factory : function, (default: dict)
261
+ Factory function to be used to create the adjacency list
262
+ dict which holds edge data keyed by neighbor.
263
+ It should require no arguments and return a dict-like object
264
+
265
+ edge_attr_dict_factory : function, (default: dict)
266
+ Factory function to be used to create the edge attribute
267
+ dict which holds attribute values keyed by attribute name.
268
+ It should require no arguments and return a dict-like object.
269
+
270
+ graph_attr_dict_factory : function, (default: dict)
271
+ Factory function to be used to create the graph attribute
272
+ dict which holds attribute values keyed by attribute name.
273
+ It should require no arguments and return a dict-like object.
274
+
275
+ Typically, if your extension doesn't impact the data structure all
276
+ methods will inherit without issue except: `to_directed/to_undirected`.
277
+ By default these methods create a DiGraph/Graph class and you probably
278
+ want them to create your extension of a DiGraph/Graph. To facilitate
279
+ this we define two class variables that you can set in your subclass.
280
+
281
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
282
+ Class to create a new graph structure in the `to_directed` method.
283
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
284
+
285
+ to_undirected_class : callable, (default: Graph or MultiGraph)
286
+ Class to create a new graph structure in the `to_undirected` method.
287
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
288
+
289
+ **Subclassing Example**
290
+
291
+ Create a low memory graph class that effectively disallows edge
292
+ attributes by using a single attribute dict for all edges.
293
+ This reduces the memory used, but you lose edge attributes.
294
+
295
+ >>> class ThinGraph(nx.Graph):
296
+ ... all_edge_dict = {"weight": 1}
297
+ ...
298
+ ... def single_edge_dict(self):
299
+ ... return self.all_edge_dict
300
+ ...
301
+ ... edge_attr_dict_factory = single_edge_dict
302
+ >>> G = ThinGraph()
303
+ >>> G.add_edge(2, 1)
304
+ >>> G[2][1]
305
+ {'weight': 1}
306
+ >>> G.add_edge(2, 2)
307
+ >>> G[2][1] is G[2][2]
308
+ True
309
+ """
310
+
311
+ __networkx_backend__ = "networkx"
312
+
313
+ _adj = _CachedPropertyResetterAdj()
314
+ _node = _CachedPropertyResetterNode()
315
+
316
+ node_dict_factory = dict
317
+ node_attr_dict_factory = dict
318
+ adjlist_outer_dict_factory = dict
319
+ adjlist_inner_dict_factory = dict
320
+ edge_attr_dict_factory = dict
321
+ graph_attr_dict_factory = dict
322
+
323
+ def to_directed_class(self):
324
+ """Returns the class to use for empty directed copies.
325
+
326
+ If you subclass the base classes, use this to designate
327
+ what directed class to use for `to_directed()` copies.
328
+ """
329
+ return nx.DiGraph
330
+
331
+ def to_undirected_class(self):
332
+ """Returns the class to use for empty undirected copies.
333
+
334
+ If you subclass the base classes, use this to designate
335
+ what directed class to use for `to_directed()` copies.
336
+ """
337
+ return Graph
338
+
339
+ def __init__(self, incoming_graph_data=None, **attr):
340
+ """Initialize a graph with edges, name, or graph attributes.
341
+
342
+ Parameters
343
+ ----------
344
+ incoming_graph_data : input graph (optional, default: None)
345
+ Data to initialize graph. If None (default) an empty
346
+ graph is created. The data can be an edge list, or any
347
+ NetworkX graph object. If the corresponding optional Python
348
+ packages are installed the data can also be a 2D NumPy array, a
349
+ SciPy sparse array, or a PyGraphviz graph.
350
+
351
+ attr : keyword arguments, optional (default= no attributes)
352
+ Attributes to add to graph as key=value pairs.
353
+
354
+ See Also
355
+ --------
356
+ convert
357
+
358
+ Examples
359
+ --------
360
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
361
+ >>> G = nx.Graph(name="my graph")
362
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
363
+ >>> G = nx.Graph(e)
364
+
365
+ Arbitrary graph attribute pairs (key=value) may be assigned
366
+
367
+ >>> G = nx.Graph(e, day="Friday")
368
+ >>> G.graph
369
+ {'day': 'Friday'}
370
+
371
+ """
372
+ self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
373
+ self._node = self.node_dict_factory() # empty node attribute dict
374
+ self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict
375
+ self.__networkx_cache__ = {}
376
+ # attempt to load graph with data
377
+ if incoming_graph_data is not None:
378
+ convert.to_networkx_graph(incoming_graph_data, create_using=self)
379
+ # load graph attributes (must be after convert)
380
+ self.graph.update(attr)
381
+
382
+ @cached_property
383
+ def adj(self):
384
+ """Graph adjacency object holding the neighbors of each node.
385
+
386
+ This object is a read-only dict-like structure with node keys
387
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
388
+ to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
389
+ the color of the edge `(3, 2)` to `"blue"`.
390
+
391
+ Iterating over G.adj behaves like a dict. Useful idioms include
392
+ `for nbr, datadict in G.adj[n].items():`.
393
+
394
+ The neighbor information is also provided by subscripting the graph.
395
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
396
+
397
+ For directed graphs, `G.adj` holds outgoing (successor) info.
398
+ """
399
+ return AdjacencyView(self._adj)
400
+
401
+ @property
402
+ def name(self):
403
+ """String identifier of the graph.
404
+
405
+ This graph attribute appears in the attribute dict G.graph
406
+ keyed by the string `"name"`. as well as an attribute (technically
407
+ a property) `G.name`. This is entirely user controlled.
408
+ """
409
+ return self.graph.get("name", "")
410
+
411
+ @name.setter
412
+ def name(self, s):
413
+ self.graph["name"] = s
414
+ nx._clear_cache(self)
415
+
416
+ def __str__(self):
417
+ """Returns a short summary of the graph.
418
+
419
+ Returns
420
+ -------
421
+ info : string
422
+ Graph information including the graph name (if any), graph type, and the
423
+ number of nodes and edges.
424
+
425
+ Examples
426
+ --------
427
+ >>> G = nx.Graph(name="foo")
428
+ >>> str(G)
429
+ "Graph named 'foo' with 0 nodes and 0 edges"
430
+
431
+ >>> G = nx.path_graph(3)
432
+ >>> str(G)
433
+ 'Graph with 3 nodes and 2 edges'
434
+
435
+ """
436
+ return "".join(
437
+ [
438
+ type(self).__name__,
439
+ f" named {self.name!r}" if self.name else "",
440
+ f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
441
+ ]
442
+ )
443
+
444
+ def __iter__(self):
445
+ """Iterate over the nodes. Use: 'for n in G'.
446
+
447
+ Returns
448
+ -------
449
+ niter : iterator
450
+ An iterator over all nodes in the graph.
451
+
452
+ Examples
453
+ --------
454
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
455
+ >>> [n for n in G]
456
+ [0, 1, 2, 3]
457
+ >>> list(G)
458
+ [0, 1, 2, 3]
459
+ """
460
+ return iter(self._node)
461
+
462
+ def __contains__(self, n):
463
+ """Returns True if n is a node, False otherwise. Use: 'n in G'.
464
+
465
+ Examples
466
+ --------
467
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
468
+ >>> 1 in G
469
+ True
470
+ """
471
+ try:
472
+ return n in self._node
473
+ except TypeError:
474
+ return False
475
+
476
+ def __len__(self):
477
+ """Returns the number of nodes in the graph. Use: 'len(G)'.
478
+
479
+ Returns
480
+ -------
481
+ nnodes : int
482
+ The number of nodes in the graph.
483
+
484
+ See Also
485
+ --------
486
+ number_of_nodes: identical method
487
+ order: identical method
488
+
489
+ Examples
490
+ --------
491
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
492
+ >>> len(G)
493
+ 4
494
+
495
+ """
496
+ return len(self._node)
497
+
498
+ def __getitem__(self, n):
499
+ """Returns a dict of neighbors of node n. Use: 'G[n]'.
500
+
501
+ Parameters
502
+ ----------
503
+ n : node
504
+ A node in the graph.
505
+
506
+ Returns
507
+ -------
508
+ adj_dict : dictionary
509
+ The adjacency dictionary for nodes connected to n.
510
+
511
+ Notes
512
+ -----
513
+ G[n] is the same as G.adj[n] and similar to G.neighbors(n)
514
+ (which is an iterator over G.adj[n])
515
+
516
+ Examples
517
+ --------
518
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
519
+ >>> G[0]
520
+ AtlasView({1: {}})
521
+ """
522
+ return self.adj[n]
523
+
524
+ def add_node(self, node_for_adding, **attr):
525
+ """Add a single node `node_for_adding` and update node attributes.
526
+
527
+ Parameters
528
+ ----------
529
+ node_for_adding : node
530
+ A node can be any hashable Python object except None.
531
+ attr : keyword arguments, optional
532
+ Set or change node attributes using key=value.
533
+
534
+ See Also
535
+ --------
536
+ add_nodes_from
537
+
538
+ Examples
539
+ --------
540
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
541
+ >>> G.add_node(1)
542
+ >>> G.add_node("Hello")
543
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
544
+ >>> G.add_node(K3)
545
+ >>> G.number_of_nodes()
546
+ 3
547
+
548
+ Use keywords set/change node attributes:
549
+
550
+ >>> G.add_node(1, size=10)
551
+ >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
552
+
553
+ Notes
554
+ -----
555
+ A hashable object is one that can be used as a key in a Python
556
+ dictionary. This includes strings, numbers, tuples of strings
557
+ and numbers, etc.
558
+
559
+ On many platforms hashable items also include mutables such as
560
+ NetworkX Graphs, though one should be careful that the hash
561
+ doesn't change on mutables.
562
+ """
563
+ if node_for_adding not in self._node:
564
+ if node_for_adding is None:
565
+ raise ValueError("None cannot be a node")
566
+ self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
567
+ attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
568
+ attr_dict.update(attr)
569
+ else: # update attr even if node already exists
570
+ self._node[node_for_adding].update(attr)
571
+ nx._clear_cache(self)
572
+
573
+ def add_nodes_from(self, nodes_for_adding, **attr):
574
+ """Add multiple nodes.
575
+
576
+ Parameters
577
+ ----------
578
+ nodes_for_adding : iterable container
579
+ A container of nodes (list, dict, set, etc.).
580
+ OR
581
+ A container of (node, attribute dict) tuples.
582
+ Node attributes are updated using the attribute dict.
583
+ attr : keyword arguments, optional (default= no attributes)
584
+ Update attributes for all nodes in nodes.
585
+ Node attributes specified in nodes as a tuple take
586
+ precedence over attributes specified via keyword arguments.
587
+
588
+ See Also
589
+ --------
590
+ add_node
591
+
592
+ Notes
593
+ -----
594
+ When adding nodes from an iterator over the graph you are changing,
595
+ a `RuntimeError` can be raised with message:
596
+ `RuntimeError: dictionary changed size during iteration`. This
597
+ happens when the graph's underlying dictionary is modified during
598
+ iteration. To avoid this error, evaluate the iterator into a separate
599
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
600
+ object to `G.add_nodes_from`.
601
+
602
+ Examples
603
+ --------
604
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
605
+ >>> G.add_nodes_from("Hello")
606
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
607
+ >>> G.add_nodes_from(K3)
608
+ >>> sorted(G.nodes(), key=str)
609
+ [0, 1, 2, 'H', 'e', 'l', 'o']
610
+
611
+ Use keywords to update specific node attributes for every node.
612
+
613
+ >>> G.add_nodes_from([1, 2], size=10)
614
+ >>> G.add_nodes_from([3, 4], weight=0.4)
615
+
616
+ Use (node, attrdict) tuples to update attributes for specific nodes.
617
+
618
+ >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
619
+ >>> G.nodes[1]["size"]
620
+ 11
621
+ >>> H = nx.Graph()
622
+ >>> H.add_nodes_from(G.nodes(data=True))
623
+ >>> H.nodes[1]["size"]
624
+ 11
625
+
626
+ Evaluate an iterator over a graph if using it to modify the same graph
627
+
628
+ >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
629
+ >>> # wrong way - will raise RuntimeError
630
+ >>> # G.add_nodes_from(n + 1 for n in G.nodes)
631
+ >>> # correct way
632
+ >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
633
+ """
634
+ for n in nodes_for_adding:
635
+ try:
636
+ newnode = n not in self._node
637
+ newdict = attr
638
+ except TypeError:
639
+ n, ndict = n
640
+ newnode = n not in self._node
641
+ newdict = attr.copy()
642
+ newdict.update(ndict)
643
+ if newnode:
644
+ if n is None:
645
+ raise ValueError("None cannot be a node")
646
+ self._adj[n] = self.adjlist_inner_dict_factory()
647
+ self._node[n] = self.node_attr_dict_factory()
648
+ self._node[n].update(newdict)
649
+ nx._clear_cache(self)
650
+
651
+ def remove_node(self, n):
652
+ """Remove node n.
653
+
654
+ Removes the node n and all adjacent edges.
655
+ Attempting to remove a nonexistent node will raise an exception.
656
+
657
+ Parameters
658
+ ----------
659
+ n : node
660
+ A node in the graph
661
+
662
+ Raises
663
+ ------
664
+ NetworkXError
665
+ If n is not in the graph.
666
+
667
+ See Also
668
+ --------
669
+ remove_nodes_from
670
+
671
+ Examples
672
+ --------
673
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
674
+ >>> list(G.edges)
675
+ [(0, 1), (1, 2)]
676
+ >>> G.remove_node(1)
677
+ >>> list(G.edges)
678
+ []
679
+
680
+ """
681
+ adj = self._adj
682
+ try:
683
+ nbrs = list(adj[n]) # list handles self-loops (allows mutation)
684
+ del self._node[n]
685
+ except KeyError as err: # NetworkXError if n not in self
686
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
687
+ for u in nbrs:
688
+ del adj[u][n] # remove all edges n-u in graph
689
+ del adj[n] # now remove node
690
+ nx._clear_cache(self)
691
+
692
+ def remove_nodes_from(self, nodes):
693
+ """Remove multiple nodes.
694
+
695
+ Parameters
696
+ ----------
697
+ nodes : iterable container
698
+ A container of nodes (list, dict, set, etc.). If a node
699
+ in the container is not in the graph it is silently
700
+ ignored.
701
+
702
+ See Also
703
+ --------
704
+ remove_node
705
+
706
+ Notes
707
+ -----
708
+ When removing nodes from an iterator over the graph you are changing,
709
+ a `RuntimeError` will be raised with message:
710
+ `RuntimeError: dictionary changed size during iteration`. This
711
+ happens when the graph's underlying dictionary is modified during
712
+ iteration. To avoid this error, evaluate the iterator into a separate
713
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
714
+ object to `G.remove_nodes_from`.
715
+
716
+ Examples
717
+ --------
718
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
719
+ >>> e = list(G.nodes)
720
+ >>> e
721
+ [0, 1, 2]
722
+ >>> G.remove_nodes_from(e)
723
+ >>> list(G.nodes)
724
+ []
725
+
726
+ Evaluate an iterator over a graph if using it to modify the same graph
727
+
728
+ >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
729
+ >>> # this command will fail, as the graph's dict is modified during iteration
730
+ >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
731
+ >>> # this command will work, since the dictionary underlying graph is not modified
732
+ >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
733
+ """
734
+ adj = self._adj
735
+ for n in nodes:
736
+ try:
737
+ del self._node[n]
738
+ for u in list(adj[n]): # list handles self-loops
739
+ del adj[u][n] # (allows mutation of dict in loop)
740
+ del adj[n]
741
+ except KeyError:
742
+ pass
743
+ nx._clear_cache(self)
744
+
745
+ @cached_property
746
+ def nodes(self):
747
+ """A NodeView of the Graph as G.nodes or G.nodes().
748
+
749
+ Can be used as `G.nodes` for data lookup and for set-like operations.
750
+ Can also be used as `G.nodes(data='color', default=None)` to return a
751
+ NodeDataView which reports specific node data but no set operations.
752
+ It presents a dict-like interface as well with `G.nodes.items()`
753
+ iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
754
+ providing the value of the `foo` attribute for node `3`. In addition,
755
+ a view `G.nodes.data('foo')` provides a dict-like interface to the
756
+ `foo` attribute of each node. `G.nodes.data('foo', default=1)`
757
+ provides a default for nodes that do not have attribute `foo`.
758
+
759
+ Parameters
760
+ ----------
761
+ data : string or bool, optional (default=False)
762
+ The node attribute returned in 2-tuple (n, ddict[data]).
763
+ If True, return entire node attribute dict as (n, ddict).
764
+ If False, return just the nodes n.
765
+
766
+ default : value, optional (default=None)
767
+ Value used for nodes that don't have the requested attribute.
768
+ Only relevant if data is not True or False.
769
+
770
+ Returns
771
+ -------
772
+ NodeView
773
+ Allows set-like operations over the nodes as well as node
774
+ attribute dict lookup and calling to get a NodeDataView.
775
+ A NodeDataView iterates over `(n, data)` and has no set operations.
776
+ A NodeView iterates over `n` and includes set operations.
777
+
778
+ When called, if data is False, an iterator over nodes.
779
+ Otherwise an iterator of 2-tuples (node, attribute value)
780
+ where the attribute is specified in `data`.
781
+ If data is True then the attribute becomes the
782
+ entire data dictionary.
783
+
784
+ Notes
785
+ -----
786
+ If your node data is not needed, it is simpler and equivalent
787
+ to use the expression ``for n in G``, or ``list(G)``.
788
+
789
+ Examples
790
+ --------
791
+ There are two simple ways of getting a list of all nodes in the graph:
792
+
793
+ >>> G = nx.path_graph(3)
794
+ >>> list(G.nodes)
795
+ [0, 1, 2]
796
+ >>> list(G)
797
+ [0, 1, 2]
798
+
799
+ To get the node data along with the nodes:
800
+
801
+ >>> G.add_node(1, time="5pm")
802
+ >>> G.nodes[0]["foo"] = "bar"
803
+ >>> list(G.nodes(data=True))
804
+ [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
805
+ >>> list(G.nodes.data())
806
+ [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
807
+
808
+ >>> list(G.nodes(data="foo"))
809
+ [(0, 'bar'), (1, None), (2, None)]
810
+ >>> list(G.nodes.data("foo"))
811
+ [(0, 'bar'), (1, None), (2, None)]
812
+
813
+ >>> list(G.nodes(data="time"))
814
+ [(0, None), (1, '5pm'), (2, None)]
815
+ >>> list(G.nodes.data("time"))
816
+ [(0, None), (1, '5pm'), (2, None)]
817
+
818
+ >>> list(G.nodes(data="time", default="Not Available"))
819
+ [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
820
+ >>> list(G.nodes.data("time", default="Not Available"))
821
+ [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
822
+
823
+ If some of your nodes have an attribute and the rest are assumed
824
+ to have a default attribute value you can create a dictionary
825
+ from node/attribute pairs using the `default` keyword argument
826
+ to guarantee the value is never None::
827
+
828
+ >>> G = nx.Graph()
829
+ >>> G.add_node(0)
830
+ >>> G.add_node(1, weight=2)
831
+ >>> G.add_node(2, weight=3)
832
+ >>> dict(G.nodes(data="weight", default=1))
833
+ {0: 1, 1: 2, 2: 3}
834
+
835
+ """
836
+ return NodeView(self)
837
+
838
+ def number_of_nodes(self):
839
+ """Returns the number of nodes in the graph.
840
+
841
+ Returns
842
+ -------
843
+ nnodes : int
844
+ The number of nodes in the graph.
845
+
846
+ See Also
847
+ --------
848
+ order: identical method
849
+ __len__: identical method
850
+
851
+ Examples
852
+ --------
853
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
854
+ >>> G.number_of_nodes()
855
+ 3
856
+ """
857
+ return len(self._node)
858
+
859
+ def order(self):
860
+ """Returns the number of nodes in the graph.
861
+
862
+ Returns
863
+ -------
864
+ nnodes : int
865
+ The number of nodes in the graph.
866
+
867
+ See Also
868
+ --------
869
+ number_of_nodes: identical method
870
+ __len__: identical method
871
+
872
+ Examples
873
+ --------
874
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
875
+ >>> G.order()
876
+ 3
877
+ """
878
+ return len(self._node)
879
+
880
+ def has_node(self, n):
881
+ """Returns True if the graph contains the node n.
882
+
883
+ Identical to `n in G`
884
+
885
+ Parameters
886
+ ----------
887
+ n : node
888
+
889
+ Examples
890
+ --------
891
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
892
+ >>> G.has_node(0)
893
+ True
894
+
895
+ It is more readable and simpler to use
896
+
897
+ >>> 0 in G
898
+ True
899
+
900
+ """
901
+ try:
902
+ return n in self._node
903
+ except TypeError:
904
+ return False
905
+
906
+ def add_edge(self, u_of_edge, v_of_edge, **attr):
907
+ """Add an edge between u and v.
908
+
909
+ The nodes u and v will be automatically added if they are
910
+ not already in the graph.
911
+
912
+ Edge attributes can be specified with keywords or by directly
913
+ accessing the edge's attribute dictionary. See examples below.
914
+
915
+ Parameters
916
+ ----------
917
+ u_of_edge, v_of_edge : nodes
918
+ Nodes can be, for example, strings or numbers.
919
+ Nodes must be hashable (and not None) Python objects.
920
+ attr : keyword arguments, optional
921
+ Edge data (or labels or objects) can be assigned using
922
+ keyword arguments.
923
+
924
+ See Also
925
+ --------
926
+ add_edges_from : add a collection of edges
927
+
928
+ Notes
929
+ -----
930
+ Adding an edge that already exists updates the edge data.
931
+
932
+ Many NetworkX algorithms designed for weighted graphs use
933
+ an edge attribute (by default `weight`) to hold a numerical value.
934
+
935
+ Examples
936
+ --------
937
+ The following all add the edge e=(1, 2) to graph G:
938
+
939
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
940
+ >>> e = (1, 2)
941
+ >>> G.add_edge(1, 2) # explicit two-node form
942
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
943
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
944
+
945
+ Associate data to edges using keywords:
946
+
947
+ >>> G.add_edge(1, 2, weight=3)
948
+ >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
949
+
950
+ For non-string attribute keys, use subscript notation.
951
+
952
+ >>> G.add_edge(1, 2)
953
+ >>> G[1][2].update({0: 5})
954
+ >>> G.edges[1, 2].update({0: 5})
955
+ """
956
+ u, v = u_of_edge, v_of_edge
957
+ # add nodes
958
+ if u not in self._node:
959
+ if u is None:
960
+ raise ValueError("None cannot be a node")
961
+ self._adj[u] = self.adjlist_inner_dict_factory()
962
+ self._node[u] = self.node_attr_dict_factory()
963
+ if v not in self._node:
964
+ if v is None:
965
+ raise ValueError("None cannot be a node")
966
+ self._adj[v] = self.adjlist_inner_dict_factory()
967
+ self._node[v] = self.node_attr_dict_factory()
968
+ # add the edge
969
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
970
+ datadict.update(attr)
971
+ self._adj[u][v] = datadict
972
+ self._adj[v][u] = datadict
973
+ nx._clear_cache(self)
974
+
975
+ def add_edges_from(self, ebunch_to_add, **attr):
976
+ """Add all the edges in ebunch_to_add.
977
+
978
+ Parameters
979
+ ----------
980
+ ebunch_to_add : container of edges
981
+ Each edge given in the container will be added to the
982
+ graph. The edges must be given as 2-tuples (u, v) or
983
+ 3-tuples (u, v, d) where d is a dictionary containing edge data.
984
+ attr : keyword arguments, optional
985
+ Edge data (or labels or objects) can be assigned using
986
+ keyword arguments.
987
+
988
+ See Also
989
+ --------
990
+ add_edge : add a single edge
991
+ add_weighted_edges_from : convenient way to add weighted edges
992
+
993
+ Notes
994
+ -----
995
+ Adding the same edge twice has no effect but any edge data
996
+ will be updated when each duplicate edge is added.
997
+
998
+ Edge attributes specified in an ebunch take precedence over
999
+ attributes specified via keyword arguments.
1000
+
1001
+ When adding edges from an iterator over the graph you are changing,
1002
+ a `RuntimeError` can be raised with message:
1003
+ `RuntimeError: dictionary changed size during iteration`. This
1004
+ happens when the graph's underlying dictionary is modified during
1005
+ iteration. To avoid this error, evaluate the iterator into a separate
1006
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
1007
+ object to `G.add_edges_from`.
1008
+
1009
+ Examples
1010
+ --------
1011
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1012
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
1013
+ >>> e = zip(range(0, 3), range(1, 4))
1014
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
1015
+
1016
+ Associate data to edges
1017
+
1018
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
1019
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
1020
+
1021
+ Evaluate an iterator over a graph if using it to modify the same graph
1022
+
1023
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
1024
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
1025
+ >>> # wrong way - will raise RuntimeError
1026
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
1027
+ >>> # correct way - note that there will be no self-edge for node 5
1028
+ >>> G.add_edges_from(list((5, n) for n in G.nodes))
1029
+ """
1030
+ for e in ebunch_to_add:
1031
+ ne = len(e)
1032
+ if ne == 3:
1033
+ u, v, dd = e
1034
+ elif ne == 2:
1035
+ u, v = e
1036
+ dd = {} # doesn't need edge_attr_dict_factory
1037
+ else:
1038
+ raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
1039
+ if u not in self._node:
1040
+ if u is None:
1041
+ raise ValueError("None cannot be a node")
1042
+ self._adj[u] = self.adjlist_inner_dict_factory()
1043
+ self._node[u] = self.node_attr_dict_factory()
1044
+ if v not in self._node:
1045
+ if v is None:
1046
+ raise ValueError("None cannot be a node")
1047
+ self._adj[v] = self.adjlist_inner_dict_factory()
1048
+ self._node[v] = self.node_attr_dict_factory()
1049
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
1050
+ datadict.update(attr)
1051
+ datadict.update(dd)
1052
+ self._adj[u][v] = datadict
1053
+ self._adj[v][u] = datadict
1054
+ nx._clear_cache(self)
1055
+
1056
+ def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
1057
+ """Add weighted edges in `ebunch_to_add` with specified weight attr
1058
+
1059
+ Parameters
1060
+ ----------
1061
+ ebunch_to_add : container of edges
1062
+ Each edge given in the list or container will be added
1063
+ to the graph. The edges must be given as 3-tuples (u, v, w)
1064
+ where w is a number.
1065
+ weight : string, optional (default= 'weight')
1066
+ The attribute name for the edge weights to be added.
1067
+ attr : keyword arguments, optional (default= no attributes)
1068
+ Edge attributes to add/update for all edges.
1069
+
1070
+ See Also
1071
+ --------
1072
+ add_edge : add a single edge
1073
+ add_edges_from : add multiple edges
1074
+
1075
+ Notes
1076
+ -----
1077
+ Adding the same edge twice for Graph/DiGraph simply updates
1078
+ the edge data. For MultiGraph/MultiDiGraph, duplicate edges
1079
+ are stored.
1080
+
1081
+ When adding edges from an iterator over the graph you are changing,
1082
+ a `RuntimeError` can be raised with message:
1083
+ `RuntimeError: dictionary changed size during iteration`. This
1084
+ happens when the graph's underlying dictionary is modified during
1085
+ iteration. To avoid this error, evaluate the iterator into a separate
1086
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
1087
+ object to `G.add_weighted_edges_from`.
1088
+
1089
+ Examples
1090
+ --------
1091
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1092
+ >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
1093
+
1094
+ Evaluate an iterator over edges before passing it
1095
+
1096
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
1097
+ >>> weight = 0.1
1098
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
1099
+ >>> # wrong way - will raise RuntimeError
1100
+ >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
1101
+ >>> # correct way - note that there will be no self-edge for node 5
1102
+ >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
1103
+ """
1104
+ self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
1105
+ nx._clear_cache(self)
1106
+
1107
+ def remove_edge(self, u, v):
1108
+ """Remove the edge between u and v.
1109
+
1110
+ Parameters
1111
+ ----------
1112
+ u, v : nodes
1113
+ Remove the edge between nodes u and v.
1114
+
1115
+ Raises
1116
+ ------
1117
+ NetworkXError
1118
+ If there is not an edge between u and v.
1119
+
1120
+ See Also
1121
+ --------
1122
+ remove_edges_from : remove a collection of edges
1123
+
1124
+ Examples
1125
+ --------
1126
+ >>> G = nx.path_graph(4) # or DiGraph, etc
1127
+ >>> G.remove_edge(0, 1)
1128
+ >>> e = (1, 2)
1129
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
1130
+ >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
1131
+ >>> G.remove_edge(*e[:2]) # select first part of edge tuple
1132
+ """
1133
+ try:
1134
+ del self._adj[u][v]
1135
+ if u != v: # self-loop needs only one entry removed
1136
+ del self._adj[v][u]
1137
+ except KeyError as err:
1138
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
1139
+ nx._clear_cache(self)
1140
+
1141
+ def remove_edges_from(self, ebunch):
1142
+ """Remove all edges specified in ebunch.
1143
+
1144
+ Parameters
1145
+ ----------
1146
+ ebunch: list or container of edge tuples
1147
+ Each edge given in the list or container will be removed
1148
+ from the graph. The edges can be:
1149
+
1150
+ - 2-tuples (u, v) edge between u and v.
1151
+ - 3-tuples (u, v, k) where k is ignored.
1152
+
1153
+ See Also
1154
+ --------
1155
+ remove_edge : remove a single edge
1156
+
1157
+ Notes
1158
+ -----
1159
+ Will fail silently if an edge in ebunch is not in the graph.
1160
+
1161
+ Examples
1162
+ --------
1163
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1164
+ >>> ebunch = [(1, 2), (2, 3)]
1165
+ >>> G.remove_edges_from(ebunch)
1166
+ """
1167
+ adj = self._adj
1168
+ for e in ebunch:
1169
+ u, v = e[:2] # ignore edge data if present
1170
+ if u in adj and v in adj[u]:
1171
+ del adj[u][v]
1172
+ if u != v: # self loop needs only one entry removed
1173
+ del adj[v][u]
1174
+ nx._clear_cache(self)
1175
+
1176
+ def update(self, edges=None, nodes=None):
1177
+ """Update the graph using nodes/edges/graphs as input.
1178
+
1179
+ Like dict.update, this method takes a graph as input, adding the
1180
+ graph's nodes and edges to this graph. It can also take two inputs:
1181
+ edges and nodes. Finally it can take either edges or nodes.
1182
+ To specify only nodes the keyword `nodes` must be used.
1183
+
1184
+ The collections of edges and nodes are treated similarly to
1185
+ the add_edges_from/add_nodes_from methods. When iterated, they
1186
+ should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
1187
+
1188
+ Parameters
1189
+ ----------
1190
+ edges : Graph object, collection of edges, or None
1191
+ The first parameter can be a graph or some edges. If it has
1192
+ attributes `nodes` and `edges`, then it is taken to be a
1193
+ Graph-like object and those attributes are used as collections
1194
+ of nodes and edges to be added to the graph.
1195
+ If the first parameter does not have those attributes, it is
1196
+ treated as a collection of edges and added to the graph.
1197
+ If the first argument is None, no edges are added.
1198
+ nodes : collection of nodes, or None
1199
+ The second parameter is treated as a collection of nodes
1200
+ to be added to the graph unless it is None.
1201
+ If `edges is None` and `nodes is None` an exception is raised.
1202
+ If the first parameter is a Graph, then `nodes` is ignored.
1203
+
1204
+ Examples
1205
+ --------
1206
+ >>> G = nx.path_graph(5)
1207
+ >>> G.update(nx.complete_graph(range(4, 10)))
1208
+ >>> from itertools import combinations
1209
+ >>> edges = (
1210
+ ... (u, v, {"power": u * v})
1211
+ ... for u, v in combinations(range(10, 20), 2)
1212
+ ... if u * v < 225
1213
+ ... )
1214
+ >>> nodes = [1000] # for singleton, use a container
1215
+ >>> G.update(edges, nodes)
1216
+
1217
+ Notes
1218
+ -----
1219
+ It you want to update the graph using an adjacency structure
1220
+ it is straightforward to obtain the edges/nodes from adjacency.
1221
+ The following examples provide common cases, your adjacency may
1222
+ be slightly different and require tweaks of these examples::
1223
+
1224
+ >>> # dict-of-set/list/tuple
1225
+ >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
1226
+ >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
1227
+ >>> G.update(edges=e, nodes=adj)
1228
+
1229
+ >>> DG = nx.DiGraph()
1230
+ >>> # dict-of-dict-of-attribute
1231
+ >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
1232
+ >>> e = [
1233
+ ... (u, v, {"weight": d})
1234
+ ... for u, nbrs in adj.items()
1235
+ ... for v, d in nbrs.items()
1236
+ ... ]
1237
+ >>> DG.update(edges=e, nodes=adj)
1238
+
1239
+ >>> # dict-of-dict-of-dict
1240
+ >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
1241
+ >>> e = [
1242
+ ... (u, v, {"weight": d})
1243
+ ... for u, nbrs in adj.items()
1244
+ ... for v, d in nbrs.items()
1245
+ ... ]
1246
+ >>> DG.update(edges=e, nodes=adj)
1247
+
1248
+ >>> # predecessor adjacency (dict-of-set)
1249
+ >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
1250
+ >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
1251
+
1252
+ >>> # MultiGraph dict-of-dict-of-dict-of-attribute
1253
+ >>> MDG = nx.MultiDiGraph()
1254
+ >>> adj = {
1255
+ ... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
1256
+ ... 3: {2: {0: {"weight": 0.7}}},
1257
+ ... }
1258
+ >>> e = [
1259
+ ... (u, v, ekey, d)
1260
+ ... for u, nbrs in adj.items()
1261
+ ... for v, keydict in nbrs.items()
1262
+ ... for ekey, d in keydict.items()
1263
+ ... ]
1264
+ >>> MDG.update(edges=e)
1265
+
1266
+ See Also
1267
+ --------
1268
+ add_edges_from: add multiple edges to a graph
1269
+ add_nodes_from: add multiple nodes to a graph
1270
+ """
1271
+ if edges is not None:
1272
+ if nodes is not None:
1273
+ self.add_nodes_from(nodes)
1274
+ self.add_edges_from(edges)
1275
+ else:
1276
+ # check if edges is a Graph object
1277
+ try:
1278
+ graph_nodes = edges.nodes
1279
+ graph_edges = edges.edges
1280
+ except AttributeError:
1281
+ # edge not Graph-like
1282
+ self.add_edges_from(edges)
1283
+ else: # edges is Graph-like
1284
+ self.add_nodes_from(graph_nodes.data())
1285
+ self.add_edges_from(graph_edges.data())
1286
+ self.graph.update(edges.graph)
1287
+ elif nodes is not None:
1288
+ self.add_nodes_from(nodes)
1289
+ else:
1290
+ raise NetworkXError("update needs nodes or edges input")
1291
+
1292
+ def has_edge(self, u, v):
1293
+ """Returns True if the edge (u, v) is in the graph.
1294
+
1295
+ This is the same as `v in G[u]` without KeyError exceptions.
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ u, v : nodes
1300
+ Nodes can be, for example, strings or numbers.
1301
+ Nodes must be hashable (and not None) Python objects.
1302
+
1303
+ Returns
1304
+ -------
1305
+ edge_ind : bool
1306
+ True if edge is in the graph, False otherwise.
1307
+
1308
+ Examples
1309
+ --------
1310
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1311
+ >>> G.has_edge(0, 1) # using two nodes
1312
+ True
1313
+ >>> e = (0, 1)
1314
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
1315
+ True
1316
+ >>> e = (0, 1, {"weight": 7})
1317
+ >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
1318
+ True
1319
+
1320
+ The following syntax are equivalent:
1321
+
1322
+ >>> G.has_edge(0, 1)
1323
+ True
1324
+ >>> 1 in G[0] # though this gives KeyError if 0 not in G
1325
+ True
1326
+
1327
+ """
1328
+ try:
1329
+ return v in self._adj[u]
1330
+ except KeyError:
1331
+ return False
1332
+
1333
+ def neighbors(self, n):
1334
+ """Returns an iterator over all neighbors of node n.
1335
+
1336
+ This is identical to `iter(G[n])`
1337
+
1338
+ Parameters
1339
+ ----------
1340
+ n : node
1341
+ A node in the graph
1342
+
1343
+ Returns
1344
+ -------
1345
+ neighbors : iterator
1346
+ An iterator over all neighbors of node n
1347
+
1348
+ Raises
1349
+ ------
1350
+ NetworkXError
1351
+ If the node n is not in the graph.
1352
+
1353
+ Examples
1354
+ --------
1355
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1356
+ >>> [n for n in G.neighbors(0)]
1357
+ [1]
1358
+
1359
+ Notes
1360
+ -----
1361
+ Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
1362
+
1363
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1364
+ >>> G.add_edge("a", "b", weight=7)
1365
+ >>> G["a"]
1366
+ AtlasView({'b': {'weight': 7}})
1367
+ >>> G = nx.path_graph(4)
1368
+ >>> [n for n in G[0]]
1369
+ [1]
1370
+ """
1371
+ try:
1372
+ return iter(self._adj[n])
1373
+ except KeyError as err:
1374
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
1375
+
1376
+ @cached_property
1377
+ def edges(self):
1378
+ """An EdgeView of the Graph as G.edges or G.edges().
1379
+
1380
+ edges(self, nbunch=None, data=False, default=None)
1381
+
1382
+ The EdgeView provides set-like operations on the edge-tuples
1383
+ as well as edge attribute lookup. When called, it also provides
1384
+ an EdgeDataView object which allows control of access to edge
1385
+ attributes (but does not provide set-like operations).
1386
+ Hence, `G.edges[u, v]['color']` provides the value of the color
1387
+ attribute for edge `(u, v)` while
1388
+ `for (u, v, c) in G.edges.data('color', default='red'):`
1389
+ iterates through all the edges yielding the color attribute
1390
+ with default `'red'` if no color attribute exists.
1391
+
1392
+ Parameters
1393
+ ----------
1394
+ nbunch : single node, container, or all nodes (default= all nodes)
1395
+ The view will only report edges from these nodes.
1396
+ data : string or bool, optional (default=False)
1397
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
1398
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
1399
+ If False, return 2-tuple (u, v).
1400
+ default : value, optional (default=None)
1401
+ Value used for edges that don't have the requested attribute.
1402
+ Only relevant if data is not True or False.
1403
+
1404
+ Returns
1405
+ -------
1406
+ edges : EdgeView
1407
+ A view of edge attributes, usually it iterates over (u, v)
1408
+ or (u, v, d) tuples of edges, but can also be used for
1409
+ attribute lookup as `edges[u, v]['foo']`.
1410
+
1411
+ Notes
1412
+ -----
1413
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
1414
+ For directed graphs this returns the out-edges.
1415
+
1416
+ Examples
1417
+ --------
1418
+ >>> G = nx.path_graph(3) # or MultiGraph, etc
1419
+ >>> G.add_edge(2, 3, weight=5)
1420
+ >>> [e for e in G.edges]
1421
+ [(0, 1), (1, 2), (2, 3)]
1422
+ >>> G.edges.data() # default data is {} (empty dict)
1423
+ EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
1424
+ >>> G.edges.data("weight", default=1)
1425
+ EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
1426
+ >>> G.edges([0, 3]) # only edges from these nodes
1427
+ EdgeDataView([(0, 1), (3, 2)])
1428
+ >>> G.edges(0) # only edges from node 0
1429
+ EdgeDataView([(0, 1)])
1430
+ """
1431
+ return EdgeView(self)
1432
+
1433
+ def get_edge_data(self, u, v, default=None):
1434
+ """Returns the attribute dictionary associated with edge (u, v).
1435
+
1436
+ This is identical to `G[u][v]` except the default is returned
1437
+ instead of an exception if the edge doesn't exist.
1438
+
1439
+ Parameters
1440
+ ----------
1441
+ u, v : nodes
1442
+ default: any Python object (default=None)
1443
+ Value to return if the edge (u, v) is not found.
1444
+
1445
+ Returns
1446
+ -------
1447
+ edge_dict : dictionary
1448
+ The edge attribute dictionary.
1449
+
1450
+ Examples
1451
+ --------
1452
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1453
+ >>> G[0][1]
1454
+ {}
1455
+
1456
+ Warning: Assigning to `G[u][v]` is not permitted.
1457
+ But it is safe to assign attributes `G[u][v]['foo']`
1458
+
1459
+ >>> G[0][1]["weight"] = 7
1460
+ >>> G[0][1]["weight"]
1461
+ 7
1462
+ >>> G[1][0]["weight"]
1463
+ 7
1464
+
1465
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1466
+ >>> G.get_edge_data(0, 1) # default edge data is {}
1467
+ {}
1468
+ >>> e = (0, 1)
1469
+ >>> G.get_edge_data(*e) # tuple form
1470
+ {}
1471
+ >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
1472
+ 0
1473
+ """
1474
+ try:
1475
+ return self._adj[u][v]
1476
+ except KeyError:
1477
+ return default
1478
+
1479
+ def adjacency(self):
1480
+ """Returns an iterator over (node, adjacency dict) tuples for all nodes.
1481
+
1482
+ For directed graphs, only outgoing neighbors/adjacencies are included.
1483
+
1484
+ Returns
1485
+ -------
1486
+ adj_iter : iterator
1487
+ An iterator over (node, adjacency dictionary) for all nodes in
1488
+ the graph.
1489
+
1490
+ Examples
1491
+ --------
1492
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1493
+ >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
1494
+ [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
1495
+
1496
+ """
1497
+ return iter(self._adj.items())
1498
+
1499
+ @cached_property
1500
+ def degree(self):
1501
+ """A DegreeView for the Graph as G.degree or G.degree().
1502
+
1503
+ The node degree is the number of edges adjacent to the node.
1504
+ The weighted node degree is the sum of the edge weights for
1505
+ edges incident to that node.
1506
+
1507
+ This object provides an iterator for (node, degree) as well as
1508
+ lookup for the degree for a single node.
1509
+
1510
+ Parameters
1511
+ ----------
1512
+ nbunch : single node, container, or all nodes (default= all nodes)
1513
+ The view will only report edges incident to these nodes.
1514
+
1515
+ weight : string or None, optional (default=None)
1516
+ The name of an edge attribute that holds the numerical value used
1517
+ as a weight. If None, then each edge has weight 1.
1518
+ The degree is the sum of the edge weights adjacent to the node.
1519
+
1520
+ Returns
1521
+ -------
1522
+ DegreeView or int
1523
+ If multiple nodes are requested (the default), returns a `DegreeView`
1524
+ mapping nodes to their degree.
1525
+ If a single node is requested, returns the degree of the node as an integer.
1526
+
1527
+ Examples
1528
+ --------
1529
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1530
+ >>> G.degree[0] # node 0 has degree 1
1531
+ 1
1532
+ >>> list(G.degree([0, 1, 2]))
1533
+ [(0, 1), (1, 2), (2, 2)]
1534
+ """
1535
+ return DegreeView(self)
1536
+
1537
+ def clear(self):
1538
+ """Remove all nodes and edges from the graph.
1539
+
1540
+ This also removes the name, and all graph, node, and edge attributes.
1541
+
1542
+ Examples
1543
+ --------
1544
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1545
+ >>> G.clear()
1546
+ >>> list(G.nodes)
1547
+ []
1548
+ >>> list(G.edges)
1549
+ []
1550
+
1551
+ """
1552
+ self._adj.clear()
1553
+ self._node.clear()
1554
+ self.graph.clear()
1555
+ nx._clear_cache(self)
1556
+
1557
+ def clear_edges(self):
1558
+ """Remove all edges from the graph without altering nodes.
1559
+
1560
+ Examples
1561
+ --------
1562
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1563
+ >>> G.clear_edges()
1564
+ >>> list(G.nodes)
1565
+ [0, 1, 2, 3]
1566
+ >>> list(G.edges)
1567
+ []
1568
+ """
1569
+ for nbr_dict in self._adj.values():
1570
+ nbr_dict.clear()
1571
+ nx._clear_cache(self)
1572
+
1573
+ def is_multigraph(self):
1574
+ """Returns True if graph is a multigraph, False otherwise."""
1575
+ return False
1576
+
1577
+ def is_directed(self):
1578
+ """Returns True if graph is directed, False otherwise."""
1579
+ return False
1580
+
1581
+ def copy(self, as_view=False):
1582
+ """Returns a copy of the graph.
1583
+
1584
+ The copy method by default returns an independent shallow copy
1585
+ of the graph and attributes. That is, if an attribute is a
1586
+ container, that container is shared by the original an the copy.
1587
+ Use Python's `copy.deepcopy` for new containers.
1588
+
1589
+ If `as_view` is True then a view is returned instead of a copy.
1590
+
1591
+ Notes
1592
+ -----
1593
+ All copies reproduce the graph structure, but data attributes
1594
+ may be handled in different ways. There are four types of copies
1595
+ of a graph that people might want.
1596
+
1597
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1598
+ all data attributes and any objects they might contain.
1599
+ The entire graph object is new so that changes in the copy
1600
+ do not affect the original object. (see Python's copy.deepcopy)
1601
+
1602
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1603
+ is copied but the edge, node and graph attribute dicts are
1604
+ references to those in the original graph. This saves
1605
+ time and memory but could cause confusion if you change an attribute
1606
+ in one graph and it changes the attribute in the other.
1607
+ NetworkX does not provide this level of shallow copy.
1608
+
1609
+ Independent Shallow -- This copy creates new independent attribute
1610
+ dicts and then does a shallow copy of the attributes. That is, any
1611
+ attributes that are containers are shared between the new graph
1612
+ and the original. This is exactly what `dict.copy()` provides.
1613
+ You can obtain this style copy using:
1614
+
1615
+ >>> G = nx.path_graph(5)
1616
+ >>> H = G.copy()
1617
+ >>> H = G.copy(as_view=False)
1618
+ >>> H = nx.Graph(G)
1619
+ >>> H = G.__class__(G)
1620
+
1621
+ Fresh Data -- For fresh data, the graph structure is copied while
1622
+ new empty data attribute dicts are created. The resulting graph
1623
+ is independent of the original and it has no edge, node or graph
1624
+ attributes. Fresh copies are not enabled. Instead use:
1625
+
1626
+ >>> H = G.__class__()
1627
+ >>> H.add_nodes_from(G)
1628
+ >>> H.add_edges_from(G.edges)
1629
+
1630
+ View -- Inspired by dict-views, graph-views act like read-only
1631
+ versions of the original graph, providing a copy of the original
1632
+ structure without requiring any memory for copying the information.
1633
+
1634
+ See the Python copy module for more information on shallow
1635
+ and deep copies, https://docs.python.org/3/library/copy.html.
1636
+
1637
+ Parameters
1638
+ ----------
1639
+ as_view : bool, optional (default=False)
1640
+ If True, the returned graph-view provides a read-only view
1641
+ of the original graph without actually copying any data.
1642
+
1643
+ Returns
1644
+ -------
1645
+ G : Graph
1646
+ A copy of the graph.
1647
+
1648
+ See Also
1649
+ --------
1650
+ to_directed: return a directed copy of the graph.
1651
+
1652
+ Examples
1653
+ --------
1654
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1655
+ >>> H = G.copy()
1656
+
1657
+ """
1658
+ if as_view is True:
1659
+ return nx.graphviews.generic_graph_view(self)
1660
+ G = self.__class__()
1661
+ G.graph.update(self.graph)
1662
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1663
+ G.add_edges_from(
1664
+ (u, v, datadict.copy())
1665
+ for u, nbrs in self._adj.items()
1666
+ for v, datadict in nbrs.items()
1667
+ )
1668
+ return G
1669
+
1670
+ def to_directed(self, as_view=False):
1671
+ """Returns a directed representation of the graph.
1672
+
1673
+ Returns
1674
+ -------
1675
+ G : DiGraph
1676
+ A directed graph with the same name, same nodes, and with
1677
+ each edge (u, v, data) replaced by two directed edges
1678
+ (u, v, data) and (v, u, data).
1679
+
1680
+ Notes
1681
+ -----
1682
+ This returns a "deepcopy" of the edge, node, and
1683
+ graph attributes which attempts to completely copy
1684
+ all of the data and references.
1685
+
1686
+ This is in contrast to the similar D=DiGraph(G) which returns a
1687
+ shallow copy of the data.
1688
+
1689
+ See the Python copy module for more information on shallow
1690
+ and deep copies, https://docs.python.org/3/library/copy.html.
1691
+
1692
+ Warning: If you have subclassed Graph to use dict-like objects
1693
+ in the data structure, those changes do not transfer to the
1694
+ DiGraph created by this method.
1695
+
1696
+ Examples
1697
+ --------
1698
+ >>> G = nx.Graph() # or MultiGraph, etc
1699
+ >>> G.add_edge(0, 1)
1700
+ >>> H = G.to_directed()
1701
+ >>> list(H.edges)
1702
+ [(0, 1), (1, 0)]
1703
+
1704
+ If already directed, return a (deep) copy
1705
+
1706
+ >>> G = nx.DiGraph() # or MultiDiGraph, etc
1707
+ >>> G.add_edge(0, 1)
1708
+ >>> H = G.to_directed()
1709
+ >>> list(H.edges)
1710
+ [(0, 1)]
1711
+ """
1712
+ graph_class = self.to_directed_class()
1713
+ if as_view is True:
1714
+ return nx.graphviews.generic_graph_view(self, graph_class)
1715
+ # deepcopy when not a view
1716
+ G = graph_class()
1717
+ G.graph.update(deepcopy(self.graph))
1718
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1719
+ G.add_edges_from(
1720
+ (u, v, deepcopy(data))
1721
+ for u, nbrs in self._adj.items()
1722
+ for v, data in nbrs.items()
1723
+ )
1724
+ return G
1725
+
1726
+ def to_undirected(self, as_view=False):
1727
+ """Returns an undirected copy of the graph.
1728
+
1729
+ Parameters
1730
+ ----------
1731
+ as_view : bool (optional, default=False)
1732
+ If True return a view of the original undirected graph.
1733
+
1734
+ Returns
1735
+ -------
1736
+ G : Graph/MultiGraph
1737
+ A deepcopy of the graph.
1738
+
1739
+ See Also
1740
+ --------
1741
+ Graph, copy, add_edge, add_edges_from
1742
+
1743
+ Notes
1744
+ -----
1745
+ This returns a "deepcopy" of the edge, node, and
1746
+ graph attributes which attempts to completely copy
1747
+ all of the data and references.
1748
+
1749
+ This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
1750
+ shallow copy of the data.
1751
+
1752
+ See the Python copy module for more information on shallow
1753
+ and deep copies, https://docs.python.org/3/library/copy.html.
1754
+
1755
+ Warning: If you have subclassed DiGraph to use dict-like objects
1756
+ in the data structure, those changes do not transfer to the
1757
+ Graph created by this method.
1758
+
1759
+ Examples
1760
+ --------
1761
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
1762
+ >>> H = G.to_directed()
1763
+ >>> list(H.edges)
1764
+ [(0, 1), (1, 0)]
1765
+ >>> G2 = H.to_undirected()
1766
+ >>> list(G2.edges)
1767
+ [(0, 1)]
1768
+ """
1769
+ graph_class = self.to_undirected_class()
1770
+ if as_view is True:
1771
+ return nx.graphviews.generic_graph_view(self, graph_class)
1772
+ # deepcopy when not a view
1773
+ G = graph_class()
1774
+ G.graph.update(deepcopy(self.graph))
1775
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1776
+ G.add_edges_from(
1777
+ (u, v, deepcopy(d))
1778
+ for u, nbrs in self._adj.items()
1779
+ for v, d in nbrs.items()
1780
+ )
1781
+ return G
1782
+
1783
+ def subgraph(self, nodes):
1784
+ """Returns a SubGraph view of the subgraph induced on `nodes`.
1785
+
1786
+ The induced subgraph of the graph contains the nodes in `nodes`
1787
+ and the edges between those nodes.
1788
+
1789
+ Parameters
1790
+ ----------
1791
+ nodes : list, iterable
1792
+ A container of nodes which will be iterated through once.
1793
+
1794
+ Returns
1795
+ -------
1796
+ G : SubGraph View
1797
+ A subgraph view of the graph. The graph structure cannot be
1798
+ changed but node/edge attributes can and are shared with the
1799
+ original graph.
1800
+
1801
+ Notes
1802
+ -----
1803
+ The graph, edge and node attributes are shared with the original graph.
1804
+ Changes to the graph structure is ruled out by the view, but changes
1805
+ to attributes are reflected in the original graph.
1806
+
1807
+ To create a subgraph with its own copy of the edge/node attributes use:
1808
+ G.subgraph(nodes).copy()
1809
+
1810
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
1811
+ G.remove_nodes_from([n for n in G if n not in set(nodes)])
1812
+
1813
+ Subgraph views are sometimes NOT what you want. In most cases where
1814
+ you want to do more than simply look at the induced edges, it makes
1815
+ more sense to just create the subgraph as its own graph with code like:
1816
+
1817
+ ::
1818
+
1819
+ # Create a subgraph SG based on a (possibly multigraph) G
1820
+ SG = G.__class__()
1821
+ SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
1822
+ if SG.is_multigraph():
1823
+ SG.add_edges_from(
1824
+ (n, nbr, key, d)
1825
+ for n, nbrs in G.adj.items()
1826
+ if n in largest_wcc
1827
+ for nbr, keydict in nbrs.items()
1828
+ if nbr in largest_wcc
1829
+ for key, d in keydict.items()
1830
+ )
1831
+ else:
1832
+ SG.add_edges_from(
1833
+ (n, nbr, d)
1834
+ for n, nbrs in G.adj.items()
1835
+ if n in largest_wcc
1836
+ for nbr, d in nbrs.items()
1837
+ if nbr in largest_wcc
1838
+ )
1839
+ SG.graph.update(G.graph)
1840
+
1841
+ Examples
1842
+ --------
1843
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1844
+ >>> H = G.subgraph([0, 1, 2])
1845
+ >>> list(H.edges)
1846
+ [(0, 1), (1, 2)]
1847
+ """
1848
+ induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
1849
+ # if already a subgraph, don't make a chain
1850
+ subgraph = nx.subgraph_view
1851
+ if hasattr(self, "_NODE_OK"):
1852
+ return subgraph(
1853
+ self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
1854
+ )
1855
+ return subgraph(self, filter_node=induced_nodes)
1856
+
1857
+ def edge_subgraph(self, edges):
1858
+ """Returns the subgraph induced by the specified edges.
1859
+
1860
+ The induced subgraph contains each edge in `edges` and each
1861
+ node incident to any one of those edges.
1862
+
1863
+ Parameters
1864
+ ----------
1865
+ edges : iterable
1866
+ An iterable of edges in this graph.
1867
+
1868
+ Returns
1869
+ -------
1870
+ G : Graph
1871
+ An edge-induced subgraph of this graph with the same edge
1872
+ attributes.
1873
+
1874
+ Notes
1875
+ -----
1876
+ The graph, edge, and node attributes in the returned subgraph
1877
+ view are references to the corresponding attributes in the original
1878
+ graph. The view is read-only.
1879
+
1880
+ To create a full graph version of the subgraph with its own copy
1881
+ of the edge or node attributes, use::
1882
+
1883
+ G.edge_subgraph(edges).copy()
1884
+
1885
+ Examples
1886
+ --------
1887
+ >>> G = nx.path_graph(5)
1888
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
1889
+ >>> list(H.nodes)
1890
+ [0, 1, 3, 4]
1891
+ >>> list(H.edges)
1892
+ [(0, 1), (3, 4)]
1893
+
1894
+ """
1895
+ return nx.edge_subgraph(self, edges)
1896
+
1897
+ def size(self, weight=None):
1898
+ """Returns the number of edges or total of all edge weights.
1899
+
1900
+ Parameters
1901
+ ----------
1902
+ weight : string or None, optional (default=None)
1903
+ The edge attribute that holds the numerical value used
1904
+ as a weight. If None, then each edge has weight 1.
1905
+
1906
+ Returns
1907
+ -------
1908
+ size : numeric
1909
+ The number of edges or
1910
+ (if weight keyword is provided) the total weight sum.
1911
+
1912
+ If weight is None, returns an int. Otherwise a float
1913
+ (or more general numeric if the weights are more general).
1914
+
1915
+ See Also
1916
+ --------
1917
+ number_of_edges
1918
+
1919
+ Examples
1920
+ --------
1921
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1922
+ >>> G.size()
1923
+ 3
1924
+
1925
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1926
+ >>> G.add_edge("a", "b", weight=2)
1927
+ >>> G.add_edge("b", "c", weight=4)
1928
+ >>> G.size()
1929
+ 2
1930
+ >>> G.size(weight="weight")
1931
+ 6.0
1932
+ """
1933
+ s = sum(d for v, d in self.degree(weight=weight))
1934
+ # If `weight` is None, the sum of the degrees is guaranteed to be
1935
+ # even, so we can perform integer division and hence return an
1936
+ # integer. Otherwise, the sum of the weighted degrees is not
1937
+ # guaranteed to be an integer, so we perform "real" division.
1938
+ return s // 2 if weight is None else s / 2
1939
+
1940
+ def number_of_edges(self, u=None, v=None):
1941
+ """Returns the number of edges between two nodes.
1942
+
1943
+ Parameters
1944
+ ----------
1945
+ u, v : nodes, optional (default=all edges)
1946
+ If u and v are specified, return the number of edges between
1947
+ u and v. Otherwise return the total number of all edges.
1948
+
1949
+ Returns
1950
+ -------
1951
+ nedges : int
1952
+ The number of edges in the graph. If nodes `u` and `v` are
1953
+ specified return the number of edges between those nodes. If
1954
+ the graph is directed, this only returns the number of edges
1955
+ from `u` to `v`.
1956
+
1957
+ See Also
1958
+ --------
1959
+ size
1960
+
1961
+ Examples
1962
+ --------
1963
+ For undirected graphs, this method counts the total number of
1964
+ edges in the graph:
1965
+
1966
+ >>> G = nx.path_graph(4)
1967
+ >>> G.number_of_edges()
1968
+ 3
1969
+
1970
+ If you specify two nodes, this counts the total number of edges
1971
+ joining the two nodes:
1972
+
1973
+ >>> G.number_of_edges(0, 1)
1974
+ 1
1975
+
1976
+ For directed graphs, this method can count the total number of
1977
+ directed edges from `u` to `v`:
1978
+
1979
+ >>> G = nx.DiGraph()
1980
+ >>> G.add_edge(0, 1)
1981
+ >>> G.add_edge(1, 0)
1982
+ >>> G.number_of_edges(0, 1)
1983
+ 1
1984
+
1985
+ """
1986
+ if u is None:
1987
+ return int(self.size())
1988
+ if v in self._adj[u]:
1989
+ return 1
1990
+ return 0
1991
+
1992
+ def nbunch_iter(self, nbunch=None):
1993
+ """Returns an iterator over nodes contained in nbunch that are
1994
+ also in the graph.
1995
+
1996
+ The nodes in nbunch are checked for membership in the graph
1997
+ and if not are silently ignored.
1998
+
1999
+ Parameters
2000
+ ----------
2001
+ nbunch : single node, container, or all nodes (default= all nodes)
2002
+ The view will only report edges incident to these nodes.
2003
+
2004
+ Returns
2005
+ -------
2006
+ niter : iterator
2007
+ An iterator over nodes in nbunch that are also in the graph.
2008
+ If nbunch is None, iterate over all nodes in the graph.
2009
+
2010
+ Raises
2011
+ ------
2012
+ NetworkXError
2013
+ If nbunch is not a node or sequence of nodes.
2014
+ If a node in nbunch is not hashable.
2015
+
2016
+ See Also
2017
+ --------
2018
+ Graph.__iter__
2019
+
2020
+ Notes
2021
+ -----
2022
+ When nbunch is an iterator, the returned iterator yields values
2023
+ directly from nbunch, becoming exhausted when nbunch is exhausted.
2024
+
2025
+ To test whether nbunch is a single node, one can use
2026
+ "if nbunch in self:", even after processing with this routine.
2027
+
2028
+ If nbunch is not a node or a (possibly empty) sequence/iterator
2029
+ or None, a :exc:`NetworkXError` is raised. Also, if any object in
2030
+ nbunch is not hashable, a :exc:`NetworkXError` is raised.
2031
+ """
2032
+ if nbunch is None: # include all nodes via iterator
2033
+ bunch = iter(self._adj)
2034
+ elif nbunch in self: # if nbunch is a single node
2035
+ bunch = iter([nbunch])
2036
+ else: # if nbunch is a sequence of nodes
2037
+
2038
+ def bunch_iter(nlist, adj):
2039
+ try:
2040
+ for n in nlist:
2041
+ if n in adj:
2042
+ yield n
2043
+ except TypeError as err:
2044
+ exc, message = err, err.args[0]
2045
+ # capture error for non-sequence/iterator nbunch.
2046
+ if "iter" in message:
2047
+ exc = NetworkXError(
2048
+ "nbunch is not a node or a sequence of nodes."
2049
+ )
2050
+ # capture error for unhashable node.
2051
+ if "hashable" in message:
2052
+ exc = NetworkXError(
2053
+ f"Node {n} in sequence nbunch is not a valid node."
2054
+ )
2055
+ raise exc
2056
+
2057
+ bunch = bunch_iter(nbunch, self._adj)
2058
+ return bunch
deepseek/lib/python3.10/site-packages/networkx/classes/multidigraph.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiDiGraph."""
2
+
3
+ from copy import deepcopy
4
+ from functools import cached_property
5
+
6
+ import networkx as nx
7
+ from networkx import convert
8
+ from networkx.classes.coreviews import MultiAdjacencyView
9
+ from networkx.classes.digraph import DiGraph
10
+ from networkx.classes.multigraph import MultiGraph
11
+ from networkx.classes.reportviews import (
12
+ DiMultiDegreeView,
13
+ InMultiDegreeView,
14
+ InMultiEdgeView,
15
+ OutMultiDegreeView,
16
+ OutMultiEdgeView,
17
+ )
18
+ from networkx.exception import NetworkXError
19
+
20
+ __all__ = ["MultiDiGraph"]
21
+
22
+
23
+ class MultiDiGraph(MultiGraph, DiGraph):
24
+ """A directed graph class that can store multiedges.
25
+
26
+ Multiedges are multiple edges between two nodes. Each edge
27
+ can hold optional data or attributes.
28
+
29
+ A MultiDiGraph holds directed edges. Self loops are allowed.
30
+
31
+ Nodes can be arbitrary (hashable) Python objects with optional
32
+ key/value attributes. By convention `None` is not used as a node.
33
+
34
+ Edges are represented as links between nodes with optional
35
+ key/value attributes.
36
+
37
+ Parameters
38
+ ----------
39
+ incoming_graph_data : input graph (optional, default: None)
40
+ Data to initialize graph. If None (default) an empty
41
+ graph is created. The data can be any format that is supported
42
+ by the to_networkx_graph() function, currently including edge list,
43
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
44
+ sparse matrix, or PyGraphviz graph.
45
+
46
+ multigraph_input : bool or None (default None)
47
+ Note: Only used when `incoming_graph_data` is a dict.
48
+ If True, `incoming_graph_data` is assumed to be a
49
+ dict-of-dict-of-dict-of-dict structure keyed by
50
+ node to neighbor to edge keys to edge data for multi-edges.
51
+ A NetworkXError is raised if this is not the case.
52
+ If False, :func:`to_networkx_graph` is used to try to determine
53
+ the dict's graph data structure as either a dict-of-dict-of-dict
54
+ keyed by node to neighbor to edge data, or a dict-of-iterable
55
+ keyed by node to neighbors.
56
+ If None, the treatment for True is tried, but if it fails,
57
+ the treatment for False is tried.
58
+
59
+ attr : keyword arguments, optional (default= no attributes)
60
+ Attributes to add to graph as key=value pairs.
61
+
62
+ See Also
63
+ --------
64
+ Graph
65
+ DiGraph
66
+ MultiGraph
67
+
68
+ Examples
69
+ --------
70
+ Create an empty graph structure (a "null graph") with no nodes and
71
+ no edges.
72
+
73
+ >>> G = nx.MultiDiGraph()
74
+
75
+ G can be grown in several ways.
76
+
77
+ **Nodes:**
78
+
79
+ Add one node at a time:
80
+
81
+ >>> G.add_node(1)
82
+
83
+ Add the nodes from any container (a list, dict, set or
84
+ even the lines from a file or the nodes from another graph).
85
+
86
+ >>> G.add_nodes_from([2, 3])
87
+ >>> G.add_nodes_from(range(100, 110))
88
+ >>> H = nx.path_graph(10)
89
+ >>> G.add_nodes_from(H)
90
+
91
+ In addition to strings and integers any hashable Python object
92
+ (except None) can represent a node, e.g. a customized node object,
93
+ or even another Graph.
94
+
95
+ >>> G.add_node(H)
96
+
97
+ **Edges:**
98
+
99
+ G can also be grown by adding edges.
100
+
101
+ Add one edge,
102
+
103
+ >>> key = G.add_edge(1, 2)
104
+
105
+ a list of edges,
106
+
107
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
108
+
109
+ or a collection of edges,
110
+
111
+ >>> keys = G.add_edges_from(H.edges)
112
+
113
+ If some edges connect nodes not yet in the graph, the nodes
114
+ are added automatically. If an edge already exists, an additional
115
+ edge is created and stored using a key to identify the edge.
116
+ By default the key is the lowest unused integer.
117
+
118
+ >>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
119
+ >>> G[4]
120
+ AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
121
+
122
+ **Attributes:**
123
+
124
+ Each graph, node, and edge can hold key/value attribute pairs
125
+ in an associated attribute dictionary (the keys must be hashable).
126
+ By default these are empty, but can be added or changed using
127
+ add_edge, add_node or direct manipulation of the attribute
128
+ dictionaries named graph, node and edge respectively.
129
+
130
+ >>> G = nx.MultiDiGraph(day="Friday")
131
+ >>> G.graph
132
+ {'day': 'Friday'}
133
+
134
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
135
+
136
+ >>> G.add_node(1, time="5pm")
137
+ >>> G.add_nodes_from([3], time="2pm")
138
+ >>> G.nodes[1]
139
+ {'time': '5pm'}
140
+ >>> G.nodes[1]["room"] = 714
141
+ >>> del G.nodes[1]["room"] # remove attribute
142
+ >>> list(G.nodes(data=True))
143
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
144
+
145
+ Add edge attributes using add_edge(), add_edges_from(), subscript
146
+ notation, or G.edges.
147
+
148
+ >>> key = G.add_edge(1, 2, weight=4.7)
149
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
150
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
151
+ >>> G[1][2][0]["weight"] = 4.7
152
+ >>> G.edges[1, 2, 0]["weight"] = 4
153
+
154
+ Warning: we protect the graph data structure by making `G.edges[1,
155
+ 2, 0]` a read-only dict-like structure. However, you can assign to
156
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
157
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
158
+ (for multigraphs the edge key is required: `MG.edges[u, v,
159
+ key][name] = value`).
160
+
161
+ **Shortcuts:**
162
+
163
+ Many common graph features allow python syntax to speed reporting.
164
+
165
+ >>> 1 in G # check if node in graph
166
+ True
167
+ >>> [n for n in G if n < 3] # iterate through nodes
168
+ [1, 2]
169
+ >>> len(G) # number of nodes in graph
170
+ 5
171
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
172
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
173
+
174
+ Often the best way to traverse all edges of a graph is via the neighbors.
175
+ The neighbors are available as an adjacency-view `G.adj` object or via
176
+ the method `G.adjacency()`.
177
+
178
+ >>> for n, nbrsdict in G.adjacency():
179
+ ... for nbr, keydict in nbrsdict.items():
180
+ ... for key, eattr in keydict.items():
181
+ ... if "weight" in eattr:
182
+ ... # Do something useful with the edges
183
+ ... pass
184
+
185
+ But the edges() method is often more convenient:
186
+
187
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
188
+ ... if weight is not None:
189
+ ... # Do something useful with the edges
190
+ ... pass
191
+
192
+ **Reporting:**
193
+
194
+ Simple graph information is obtained using methods and object-attributes.
195
+ Reporting usually provides views instead of containers to reduce memory
196
+ usage. The views update as the graph is updated similarly to dict-views.
197
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
198
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
199
+ (e.g. `nodes.items()`, `nodes.data('color')`,
200
+ `nodes.data('color', default='blue')` and similarly for `edges`)
201
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
202
+
203
+ For details on these and other miscellaneous methods, see below.
204
+
205
+ **Subclasses (Advanced):**
206
+
207
+ The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
208
+ The outer dict (node_dict) holds adjacency information keyed by node.
209
+ The next dict (adjlist_dict) represents the adjacency information
210
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
211
+ each edge_attr dict keyed by edge key. The inner dict
212
+ (edge_attr_dict) represents the edge data and holds edge attribute
213
+ values keyed by attribute names.
214
+
215
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
216
+ structure can be replaced by a user defined dict-like object.
217
+ In general, the dict-like features should be maintained but
218
+ extra features can be added. To replace one of the dicts create
219
+ a new graph class by changing the class(!) variable holding the
220
+ factory for that dict-like structure. The variable names are
221
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
222
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
223
+ and graph_attr_dict_factory.
224
+
225
+ node_dict_factory : function, (default: dict)
226
+ Factory function to be used to create the dict containing node
227
+ attributes, keyed by node id.
228
+ It should require no arguments and return a dict-like object
229
+
230
+ node_attr_dict_factory: function, (default: dict)
231
+ Factory function to be used to create the node attribute
232
+ dict which holds attribute values keyed by attribute name.
233
+ It should require no arguments and return a dict-like object
234
+
235
+ adjlist_outer_dict_factory : function, (default: dict)
236
+ Factory function to be used to create the outer-most dict
237
+ in the data structure that holds adjacency info keyed by node.
238
+ It should require no arguments and return a dict-like object.
239
+
240
+ adjlist_inner_dict_factory : function, (default: dict)
241
+ Factory function to be used to create the adjacency list
242
+ dict which holds multiedge key dicts keyed by neighbor.
243
+ It should require no arguments and return a dict-like object.
244
+
245
+ edge_key_dict_factory : function, (default: dict)
246
+ Factory function to be used to create the edge key dict
247
+ which holds edge data keyed by edge key.
248
+ It should require no arguments and return a dict-like object.
249
+
250
+ edge_attr_dict_factory : function, (default: dict)
251
+ Factory function to be used to create the edge attribute
252
+ dict which holds attribute values keyed by attribute name.
253
+ It should require no arguments and return a dict-like object.
254
+
255
+ graph_attr_dict_factory : function, (default: dict)
256
+ Factory function to be used to create the graph attribute
257
+ dict which holds attribute values keyed by attribute name.
258
+ It should require no arguments and return a dict-like object.
259
+
260
+ Typically, if your extension doesn't impact the data structure all
261
+ methods will inherited without issue except: `to_directed/to_undirected`.
262
+ By default these methods create a DiGraph/Graph class and you probably
263
+ want them to create your extension of a DiGraph/Graph. To facilitate
264
+ this we define two class variables that you can set in your subclass.
265
+
266
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
267
+ Class to create a new graph structure in the `to_directed` method.
268
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
269
+
270
+ to_undirected_class : callable, (default: Graph or MultiGraph)
271
+ Class to create a new graph structure in the `to_undirected` method.
272
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
273
+
274
+ **Subclassing Example**
275
+
276
+ Create a low memory graph class that effectively disallows edge
277
+ attributes by using a single attribute dict for all edges.
278
+ This reduces the memory used, but you lose edge attributes.
279
+
280
+ >>> class ThinGraph(nx.Graph):
281
+ ... all_edge_dict = {"weight": 1}
282
+ ...
283
+ ... def single_edge_dict(self):
284
+ ... return self.all_edge_dict
285
+ ...
286
+ ... edge_attr_dict_factory = single_edge_dict
287
+ >>> G = ThinGraph()
288
+ >>> G.add_edge(2, 1)
289
+ >>> G[2][1]
290
+ {'weight': 1}
291
+ >>> G.add_edge(2, 2)
292
+ >>> G[2][1] is G[2][2]
293
+ True
294
+ """
295
+
296
+ # node_dict_factory = dict # already assigned in Graph
297
+ # adjlist_outer_dict_factory = dict
298
+ # adjlist_inner_dict_factory = dict
299
+ edge_key_dict_factory = dict
300
+ # edge_attr_dict_factory = dict
301
+
302
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
303
+ """Initialize a graph with edges, name, or graph attributes.
304
+
305
+ Parameters
306
+ ----------
307
+ incoming_graph_data : input graph
308
+ Data to initialize graph. If incoming_graph_data=None (default)
309
+ an empty graph is created. The data can be an edge list, or any
310
+ NetworkX graph object. If the corresponding optional Python
311
+ packages are installed the data can also be a 2D NumPy array, a
312
+ SciPy sparse array, or a PyGraphviz graph.
313
+
314
+ multigraph_input : bool or None (default None)
315
+ Note: Only used when `incoming_graph_data` is a dict.
316
+ If True, `incoming_graph_data` is assumed to be a
317
+ dict-of-dict-of-dict-of-dict structure keyed by
318
+ node to neighbor to edge keys to edge data for multi-edges.
319
+ A NetworkXError is raised if this is not the case.
320
+ If False, :func:`to_networkx_graph` is used to try to determine
321
+ the dict's graph data structure as either a dict-of-dict-of-dict
322
+ keyed by node to neighbor to edge data, or a dict-of-iterable
323
+ keyed by node to neighbors.
324
+ If None, the treatment for True is tried, but if it fails,
325
+ the treatment for False is tried.
326
+
327
+ attr : keyword arguments, optional (default= no attributes)
328
+ Attributes to add to graph as key=value pairs.
329
+
330
+ See Also
331
+ --------
332
+ convert
333
+
334
+ Examples
335
+ --------
336
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
337
+ >>> G = nx.Graph(name="my graph")
338
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
339
+ >>> G = nx.Graph(e)
340
+
341
+ Arbitrary graph attribute pairs (key=value) may be assigned
342
+
343
+ >>> G = nx.Graph(e, day="Friday")
344
+ >>> G.graph
345
+ {'day': 'Friday'}
346
+
347
+ """
348
+ # multigraph_input can be None/True/False. So check "is not False"
349
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
350
+ DiGraph.__init__(self)
351
+ try:
352
+ convert.from_dict_of_dicts(
353
+ incoming_graph_data, create_using=self, multigraph_input=True
354
+ )
355
+ self.graph.update(attr)
356
+ except Exception as err:
357
+ if multigraph_input is True:
358
+ raise nx.NetworkXError(
359
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
360
+ )
361
+ DiGraph.__init__(self, incoming_graph_data, **attr)
362
+ else:
363
+ DiGraph.__init__(self, incoming_graph_data, **attr)
364
+
365
+ @cached_property
366
+ def adj(self):
367
+ """Graph adjacency object holding the neighbors of each node.
368
+
369
+ This object is a read-only dict-like structure with node keys
370
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
371
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
372
+ the color of the edge `(3, 2, 0)` to `"blue"`.
373
+
374
+ Iterating over G.adj behaves like a dict. Useful idioms include
375
+ `for nbr, datadict in G.adj[n].items():`.
376
+
377
+ The neighbor information is also provided by subscripting the graph.
378
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
379
+
380
+ For directed graphs, `G.adj` holds outgoing (successor) info.
381
+ """
382
+ return MultiAdjacencyView(self._succ)
383
+
384
+ @cached_property
385
+ def succ(self):
386
+ """Graph adjacency object holding the successors of each node.
387
+
388
+ This object is a read-only dict-like structure with node keys
389
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
390
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
391
+ the color of the edge `(3, 2, 0)` to `"blue"`.
392
+
393
+ Iterating over G.adj behaves like a dict. Useful idioms include
394
+ `for nbr, datadict in G.adj[n].items():`.
395
+
396
+ The neighbor information is also provided by subscripting the graph.
397
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
398
+
399
+ For directed graphs, `G.succ` is identical to `G.adj`.
400
+ """
401
+ return MultiAdjacencyView(self._succ)
402
+
403
+ @cached_property
404
+ def pred(self):
405
+ """Graph adjacency object holding the predecessors of each node.
406
+
407
+ This object is a read-only dict-like structure with node keys
408
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
409
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
410
+ the color of the edge `(3, 2, 0)` to `"blue"`.
411
+
412
+ Iterating over G.adj behaves like a dict. Useful idioms include
413
+ `for nbr, datadict in G.adj[n].items():`.
414
+ """
415
+ return MultiAdjacencyView(self._pred)
416
+
417
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
418
+ """Add an edge between u and v.
419
+
420
+ The nodes u and v will be automatically added if they are
421
+ not already in the graph.
422
+
423
+ Edge attributes can be specified with keywords or by directly
424
+ accessing the edge's attribute dictionary. See examples below.
425
+
426
+ Parameters
427
+ ----------
428
+ u_for_edge, v_for_edge : nodes
429
+ Nodes can be, for example, strings or numbers.
430
+ Nodes must be hashable (and not None) Python objects.
431
+ key : hashable identifier, optional (default=lowest unused integer)
432
+ Used to distinguish multiedges between a pair of nodes.
433
+ attr : keyword arguments, optional
434
+ Edge data (or labels or objects) can be assigned using
435
+ keyword arguments.
436
+
437
+ Returns
438
+ -------
439
+ The edge key assigned to the edge.
440
+
441
+ See Also
442
+ --------
443
+ add_edges_from : add a collection of edges
444
+
445
+ Notes
446
+ -----
447
+ To replace/update edge data, use the optional key argument
448
+ to identify a unique edge. Otherwise a new edge will be created.
449
+
450
+ NetworkX algorithms designed for weighted graphs cannot use
451
+ multigraphs directly because it is not clear how to handle
452
+ multiedge weights. Convert to Graph using edge attribute
453
+ 'weight' to enable weighted graph algorithms.
454
+
455
+ Default keys are generated using the method `new_edge_key()`.
456
+ This method can be overridden by subclassing the base class and
457
+ providing a custom `new_edge_key()` method.
458
+
459
+ Examples
460
+ --------
461
+ The following all add the edge e=(1, 2) to graph G:
462
+
463
+ >>> G = nx.MultiDiGraph()
464
+ >>> e = (1, 2)
465
+ >>> key = G.add_edge(1, 2) # explicit two-node form
466
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
467
+ 1
468
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
469
+ [2]
470
+
471
+ Associate data to edges using keywords:
472
+
473
+ >>> key = G.add_edge(1, 2, weight=3)
474
+ >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
475
+ >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
476
+
477
+ For non-string attribute keys, use subscript notation.
478
+
479
+ >>> ekey = G.add_edge(1, 2)
480
+ >>> G[1][2][0].update({0: 5})
481
+ >>> G.edges[1, 2, 0].update({0: 5})
482
+ """
483
+ u, v = u_for_edge, v_for_edge
484
+ # add nodes
485
+ if u not in self._succ:
486
+ if u is None:
487
+ raise ValueError("None cannot be a node")
488
+ self._succ[u] = self.adjlist_inner_dict_factory()
489
+ self._pred[u] = self.adjlist_inner_dict_factory()
490
+ self._node[u] = self.node_attr_dict_factory()
491
+ if v not in self._succ:
492
+ if v is None:
493
+ raise ValueError("None cannot be a node")
494
+ self._succ[v] = self.adjlist_inner_dict_factory()
495
+ self._pred[v] = self.adjlist_inner_dict_factory()
496
+ self._node[v] = self.node_attr_dict_factory()
497
+ if key is None:
498
+ key = self.new_edge_key(u, v)
499
+ if v in self._succ[u]:
500
+ keydict = self._adj[u][v]
501
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
502
+ datadict.update(attr)
503
+ keydict[key] = datadict
504
+ else:
505
+ # selfloops work this way without special treatment
506
+ datadict = self.edge_attr_dict_factory()
507
+ datadict.update(attr)
508
+ keydict = self.edge_key_dict_factory()
509
+ keydict[key] = datadict
510
+ self._succ[u][v] = keydict
511
+ self._pred[v][u] = keydict
512
+ nx._clear_cache(self)
513
+ return key
514
+
515
+ def remove_edge(self, u, v, key=None):
516
+ """Remove an edge between u and v.
517
+
518
+ Parameters
519
+ ----------
520
+ u, v : nodes
521
+ Remove an edge between nodes u and v.
522
+ key : hashable identifier, optional (default=None)
523
+ Used to distinguish multiple edges between a pair of nodes.
524
+ If None, remove a single edge between u and v. If there are
525
+ multiple edges, removes the last edge added in terms of
526
+ insertion order.
527
+
528
+ Raises
529
+ ------
530
+ NetworkXError
531
+ If there is not an edge between u and v, or
532
+ if there is no edge with the specified key.
533
+
534
+ See Also
535
+ --------
536
+ remove_edges_from : remove a collection of edges
537
+
538
+ Examples
539
+ --------
540
+ >>> G = nx.MultiDiGraph()
541
+ >>> nx.add_path(G, [0, 1, 2, 3])
542
+ >>> G.remove_edge(0, 1)
543
+ >>> e = (1, 2)
544
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
545
+
546
+ For multiple edges
547
+
548
+ >>> G = nx.MultiDiGraph()
549
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
550
+ [0, 1, 2]
551
+
552
+ When ``key=None`` (the default), edges are removed in the opposite
553
+ order that they were added:
554
+
555
+ >>> G.remove_edge(1, 2)
556
+ >>> G.edges(keys=True)
557
+ OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
558
+
559
+ For edges with keys
560
+
561
+ >>> G = nx.MultiDiGraph()
562
+ >>> G.add_edge(1, 2, key="first")
563
+ 'first'
564
+ >>> G.add_edge(1, 2, key="second")
565
+ 'second'
566
+ >>> G.remove_edge(1, 2, key="first")
567
+ >>> G.edges(keys=True)
568
+ OutMultiEdgeView([(1, 2, 'second')])
569
+
570
+ """
571
+ try:
572
+ d = self._adj[u][v]
573
+ except KeyError as err:
574
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
575
+ # remove the edge with specified data
576
+ if key is None:
577
+ d.popitem()
578
+ else:
579
+ try:
580
+ del d[key]
581
+ except KeyError as err:
582
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
583
+ raise NetworkXError(msg) from err
584
+ if len(d) == 0:
585
+ # remove the key entries if last edge
586
+ del self._succ[u][v]
587
+ del self._pred[v][u]
588
+ nx._clear_cache(self)
589
+
590
+ @cached_property
591
+ def edges(self):
592
+ """An OutMultiEdgeView of the Graph as G.edges or G.edges().
593
+
594
+ edges(self, nbunch=None, data=False, keys=False, default=None)
595
+
596
+ The OutMultiEdgeView provides set-like operations on the edge-tuples
597
+ as well as edge attribute lookup. When called, it also provides
598
+ an EdgeDataView object which allows control of access to edge
599
+ attributes (but does not provide set-like operations).
600
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
601
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
602
+ ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
603
+ iterates through all the edges yielding the color attribute with
604
+ default `'red'` if no color attribute exists.
605
+
606
+ Edges are returned as tuples with optional data and keys
607
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
608
+ provided, the tuples will just be (node, neighbor, data), but
609
+ multiple tuples with the same node and neighbor will be
610
+ generated when multiple edges between two nodes exist.
611
+
612
+ Parameters
613
+ ----------
614
+ nbunch : single node, container, or all nodes (default= all nodes)
615
+ The view will only report edges from these nodes.
616
+ data : string or bool, optional (default=False)
617
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
618
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
619
+ If False, return 2-tuple (u, v).
620
+ keys : bool, optional (default=False)
621
+ If True, return edge keys with each edge, creating (u, v, k,
622
+ d) tuples when data is also requested (the default) and (u,
623
+ v, k) tuples when data is not requested.
624
+ default : value, optional (default=None)
625
+ Value used for edges that don't have the requested attribute.
626
+ Only relevant if data is not True or False.
627
+
628
+ Returns
629
+ -------
630
+ edges : OutMultiEdgeView
631
+ A view of edge attributes, usually it iterates over (u, v)
632
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
633
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
634
+
635
+ Notes
636
+ -----
637
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
638
+ For directed graphs this returns the out-edges.
639
+
640
+ Examples
641
+ --------
642
+ >>> G = nx.MultiDiGraph()
643
+ >>> nx.add_path(G, [0, 1, 2])
644
+ >>> key = G.add_edge(2, 3, weight=5)
645
+ >>> key2 = G.add_edge(1, 2) # second edge between these nodes
646
+ >>> [e for e in G.edges()]
647
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
648
+ >>> list(G.edges(data=True)) # default data is {} (empty dict)
649
+ [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
650
+ >>> list(G.edges(data="weight", default=1))
651
+ [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
652
+ >>> list(G.edges(keys=True)) # default keys are integers
653
+ [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
654
+ >>> list(G.edges(data=True, keys=True))
655
+ [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
656
+ >>> list(G.edges(data="weight", default=1, keys=True))
657
+ [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
658
+ >>> list(G.edges([0, 2]))
659
+ [(0, 1), (2, 3)]
660
+ >>> list(G.edges(0))
661
+ [(0, 1)]
662
+ >>> list(G.edges(1))
663
+ [(1, 2), (1, 2)]
664
+
665
+ See Also
666
+ --------
667
+ in_edges, out_edges
668
+ """
669
+ return OutMultiEdgeView(self)
670
+
671
+ # alias out_edges to edges
672
+ @cached_property
673
+ def out_edges(self):
674
+ return OutMultiEdgeView(self)
675
+
676
+ out_edges.__doc__ = edges.__doc__
677
+
678
+ @cached_property
679
+ def in_edges(self):
680
+ """A view of the in edges of the graph as G.in_edges or G.in_edges().
681
+
682
+ in_edges(self, nbunch=None, data=False, keys=False, default=None)
683
+
684
+ Parameters
685
+ ----------
686
+ nbunch : single node, container, or all nodes (default= all nodes)
687
+ The view will only report edges incident to these nodes.
688
+ data : string or bool, optional (default=False)
689
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
690
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
691
+ If False, return 2-tuple (u, v).
692
+ keys : bool, optional (default=False)
693
+ If True, return edge keys with each edge, creating 3-tuples
694
+ (u, v, k) or with data, 4-tuples (u, v, k, d).
695
+ default : value, optional (default=None)
696
+ Value used for edges that don't have the requested attribute.
697
+ Only relevant if data is not True or False.
698
+
699
+ Returns
700
+ -------
701
+ in_edges : InMultiEdgeView or InMultiEdgeDataView
702
+ A view of edge attributes, usually it iterates over (u, v)
703
+ or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
704
+ used for attribute lookup as `edges[u, v, k]['foo']`.
705
+
706
+ See Also
707
+ --------
708
+ edges
709
+ """
710
+ return InMultiEdgeView(self)
711
+
712
+ @cached_property
713
+ def degree(self):
714
+ """A DegreeView for the Graph as G.degree or G.degree().
715
+
716
+ The node degree is the number of edges adjacent to the node.
717
+ The weighted node degree is the sum of the edge weights for
718
+ edges incident to that node.
719
+
720
+ This object provides an iterator for (node, degree) as well as
721
+ lookup for the degree for a single node.
722
+
723
+ Parameters
724
+ ----------
725
+ nbunch : single node, container, or all nodes (default= all nodes)
726
+ The view will only report edges incident to these nodes.
727
+
728
+ weight : string or None, optional (default=None)
729
+ The name of an edge attribute that holds the numerical value used
730
+ as a weight. If None, then each edge has weight 1.
731
+ The degree is the sum of the edge weights adjacent to the node.
732
+
733
+ Returns
734
+ -------
735
+ DiMultiDegreeView or int
736
+ If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
737
+ mapping nodes to their degree.
738
+ If a single node is requested, returns the degree of the node as an integer.
739
+
740
+ See Also
741
+ --------
742
+ out_degree, in_degree
743
+
744
+ Examples
745
+ --------
746
+ >>> G = nx.MultiDiGraph()
747
+ >>> nx.add_path(G, [0, 1, 2, 3])
748
+ >>> G.degree(0) # node 0 with degree 1
749
+ 1
750
+ >>> list(G.degree([0, 1, 2]))
751
+ [(0, 1), (1, 2), (2, 2)]
752
+ >>> G.add_edge(0, 1) # parallel edge
753
+ 1
754
+ >>> list(G.degree([0, 1, 2])) # parallel edges are counted
755
+ [(0, 2), (1, 3), (2, 2)]
756
+
757
+ """
758
+ return DiMultiDegreeView(self)
759
+
760
+ @cached_property
761
+ def in_degree(self):
762
+ """A DegreeView for (node, in_degree) or in_degree for single node.
763
+
764
+ The node in-degree is the number of edges pointing into the node.
765
+ The weighted node degree is the sum of the edge weights for
766
+ edges incident to that node.
767
+
768
+ This object provides an iterator for (node, degree) as well as
769
+ lookup for the degree for a single node.
770
+
771
+ Parameters
772
+ ----------
773
+ nbunch : single node, container, or all nodes (default= all nodes)
774
+ The view will only report edges incident to these nodes.
775
+
776
+ weight : string or None, optional (default=None)
777
+ The edge attribute that holds the numerical value used
778
+ as a weight. If None, then each edge has weight 1.
779
+ The degree is the sum of the edge weights adjacent to the node.
780
+
781
+ Returns
782
+ -------
783
+ If a single node is requested
784
+ deg : int
785
+ Degree of the node
786
+
787
+ OR if multiple nodes are requested
788
+ nd_iter : iterator
789
+ The iterator returns two-tuples of (node, in-degree).
790
+
791
+ See Also
792
+ --------
793
+ degree, out_degree
794
+
795
+ Examples
796
+ --------
797
+ >>> G = nx.MultiDiGraph()
798
+ >>> nx.add_path(G, [0, 1, 2, 3])
799
+ >>> G.in_degree(0) # node 0 with degree 0
800
+ 0
801
+ >>> list(G.in_degree([0, 1, 2]))
802
+ [(0, 0), (1, 1), (2, 1)]
803
+ >>> G.add_edge(0, 1) # parallel edge
804
+ 1
805
+ >>> list(G.in_degree([0, 1, 2])) # parallel edges counted
806
+ [(0, 0), (1, 2), (2, 1)]
807
+
808
+ """
809
+ return InMultiDegreeView(self)
810
+
811
+ @cached_property
812
+ def out_degree(self):
813
+ """Returns an iterator for (node, out-degree) or out-degree for single node.
814
+
815
+ out_degree(self, nbunch=None, weight=None)
816
+
817
+ The node out-degree is the number of edges pointing out of the node.
818
+ This function returns the out-degree for a single node or an iterator
819
+ for a bunch of nodes or if nothing is passed as argument.
820
+
821
+ Parameters
822
+ ----------
823
+ nbunch : single node, container, or all nodes (default= all nodes)
824
+ The view will only report edges incident to these nodes.
825
+
826
+ weight : string or None, optional (default=None)
827
+ The edge attribute that holds the numerical value used
828
+ as a weight. If None, then each edge has weight 1.
829
+ The degree is the sum of the edge weights.
830
+
831
+ Returns
832
+ -------
833
+ If a single node is requested
834
+ deg : int
835
+ Degree of the node
836
+
837
+ OR if multiple nodes are requested
838
+ nd_iter : iterator
839
+ The iterator returns two-tuples of (node, out-degree).
840
+
841
+ See Also
842
+ --------
843
+ degree, in_degree
844
+
845
+ Examples
846
+ --------
847
+ >>> G = nx.MultiDiGraph()
848
+ >>> nx.add_path(G, [0, 1, 2, 3])
849
+ >>> G.out_degree(0) # node 0 with degree 1
850
+ 1
851
+ >>> list(G.out_degree([0, 1, 2]))
852
+ [(0, 1), (1, 1), (2, 1)]
853
+ >>> G.add_edge(0, 1) # parallel edge
854
+ 1
855
+ >>> list(G.out_degree([0, 1, 2])) # counts parallel edges
856
+ [(0, 2), (1, 1), (2, 1)]
857
+
858
+ """
859
+ return OutMultiDegreeView(self)
860
+
861
+ def is_multigraph(self):
862
+ """Returns True if graph is a multigraph, False otherwise."""
863
+ return True
864
+
865
+ def is_directed(self):
866
+ """Returns True if graph is directed, False otherwise."""
867
+ return True
868
+
869
+ def to_undirected(self, reciprocal=False, as_view=False):
870
+ """Returns an undirected representation of the digraph.
871
+
872
+ Parameters
873
+ ----------
874
+ reciprocal : bool (optional)
875
+ If True only keep edges that appear in both directions
876
+ in the original digraph.
877
+ as_view : bool (optional, default=False)
878
+ If True return an undirected view of the original directed graph.
879
+
880
+ Returns
881
+ -------
882
+ G : MultiGraph
883
+ An undirected graph with the same name and nodes and
884
+ with edge (u, v, data) if either (u, v, data) or (v, u, data)
885
+ is in the digraph. If both edges exist in digraph and
886
+ their edge data is different, only one edge is created
887
+ with an arbitrary choice of which edge data to use.
888
+ You must check and correct for this manually if desired.
889
+
890
+ See Also
891
+ --------
892
+ MultiGraph, copy, add_edge, add_edges_from
893
+
894
+ Notes
895
+ -----
896
+ This returns a "deepcopy" of the edge, node, and
897
+ graph attributes which attempts to completely copy
898
+ all of the data and references.
899
+
900
+ This is in contrast to the similar D=MultiDiGraph(G) which
901
+ returns a shallow copy of the data.
902
+
903
+ See the Python copy module for more information on shallow
904
+ and deep copies, https://docs.python.org/3/library/copy.html.
905
+
906
+ Warning: If you have subclassed MultiDiGraph to use dict-like
907
+ objects in the data structure, those changes do not transfer
908
+ to the MultiGraph created by this method.
909
+
910
+ Examples
911
+ --------
912
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
913
+ >>> H = G.to_directed()
914
+ >>> list(H.edges)
915
+ [(0, 1), (1, 0)]
916
+ >>> G2 = H.to_undirected()
917
+ >>> list(G2.edges)
918
+ [(0, 1)]
919
+ """
920
+ graph_class = self.to_undirected_class()
921
+ if as_view is True:
922
+ return nx.graphviews.generic_graph_view(self, graph_class)
923
+ # deepcopy when not a view
924
+ G = graph_class()
925
+ G.graph.update(deepcopy(self.graph))
926
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
927
+ if reciprocal is True:
928
+ G.add_edges_from(
929
+ (u, v, key, deepcopy(data))
930
+ for u, nbrs in self._adj.items()
931
+ for v, keydict in nbrs.items()
932
+ for key, data in keydict.items()
933
+ if v in self._pred[u] and key in self._pred[u][v]
934
+ )
935
+ else:
936
+ G.add_edges_from(
937
+ (u, v, key, deepcopy(data))
938
+ for u, nbrs in self._adj.items()
939
+ for v, keydict in nbrs.items()
940
+ for key, data in keydict.items()
941
+ )
942
+ return G
943
+
944
+ def reverse(self, copy=True):
945
+ """Returns the reverse of the graph.
946
+
947
+ The reverse is a graph with the same nodes and edges
948
+ but with the directions of the edges reversed.
949
+
950
+ Parameters
951
+ ----------
952
+ copy : bool optional (default=True)
953
+ If True, return a new DiGraph holding the reversed edges.
954
+ If False, the reverse graph is created using a view of
955
+ the original graph.
956
+ """
957
+ if copy:
958
+ H = self.__class__()
959
+ H.graph.update(deepcopy(self.graph))
960
+ H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
961
+ H.add_edges_from(
962
+ (v, u, k, deepcopy(d))
963
+ for u, v, k, d in self.edges(keys=True, data=True)
964
+ )
965
+ return H
966
+ return nx.reverse_view(self)
deepseek/lib/python3.10/site-packages/networkx/classes/multigraph.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiGraph."""
2
+
3
+ from copy import deepcopy
4
+ from functools import cached_property
5
+
6
+ import networkx as nx
7
+ from networkx import NetworkXError, convert
8
+ from networkx.classes.coreviews import MultiAdjacencyView
9
+ from networkx.classes.graph import Graph
10
+ from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
11
+
12
+ __all__ = ["MultiGraph"]
13
+
14
+
15
+ class MultiGraph(Graph):
16
+ """
17
+ An undirected graph class that can store multiedges.
18
+
19
+ Multiedges are multiple edges between two nodes. Each edge
20
+ can hold optional data or attributes.
21
+
22
+ A MultiGraph holds undirected edges. Self loops are allowed.
23
+
24
+ Nodes can be arbitrary (hashable) Python objects with optional
25
+ key/value attributes. By convention `None` is not used as a node.
26
+
27
+ Edges are represented as links between nodes with optional
28
+ key/value attributes, in a MultiGraph each edge has a key to
29
+ distinguish between multiple edges that have the same source and
30
+ destination nodes.
31
+
32
+ Parameters
33
+ ----------
34
+ incoming_graph_data : input graph (optional, default: None)
35
+ Data to initialize graph. If None (default) an empty
36
+ graph is created. The data can be any format that is supported
37
+ by the to_networkx_graph() function, currently including edge list,
38
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
39
+ SciPy sparse array, or PyGraphviz graph.
40
+
41
+ multigraph_input : bool or None (default None)
42
+ Note: Only used when `incoming_graph_data` is a dict.
43
+ If True, `incoming_graph_data` is assumed to be a
44
+ dict-of-dict-of-dict-of-dict structure keyed by
45
+ node to neighbor to edge keys to edge data for multi-edges.
46
+ A NetworkXError is raised if this is not the case.
47
+ If False, :func:`to_networkx_graph` is used to try to determine
48
+ the dict's graph data structure as either a dict-of-dict-of-dict
49
+ keyed by node to neighbor to edge data, or a dict-of-iterable
50
+ keyed by node to neighbors.
51
+ If None, the treatment for True is tried, but if it fails,
52
+ the treatment for False is tried.
53
+
54
+ attr : keyword arguments, optional (default= no attributes)
55
+ Attributes to add to graph as key=value pairs.
56
+
57
+ See Also
58
+ --------
59
+ Graph
60
+ DiGraph
61
+ MultiDiGraph
62
+
63
+ Examples
64
+ --------
65
+ Create an empty graph structure (a "null graph") with no nodes and
66
+ no edges.
67
+
68
+ >>> G = nx.MultiGraph()
69
+
70
+ G can be grown in several ways.
71
+
72
+ **Nodes:**
73
+
74
+ Add one node at a time:
75
+
76
+ >>> G.add_node(1)
77
+
78
+ Add the nodes from any container (a list, dict, set or
79
+ even the lines from a file or the nodes from another graph).
80
+
81
+ >>> G.add_nodes_from([2, 3])
82
+ >>> G.add_nodes_from(range(100, 110))
83
+ >>> H = nx.path_graph(10)
84
+ >>> G.add_nodes_from(H)
85
+
86
+ In addition to strings and integers any hashable Python object
87
+ (except None) can represent a node, e.g. a customized node object,
88
+ or even another Graph.
89
+
90
+ >>> G.add_node(H)
91
+
92
+ **Edges:**
93
+
94
+ G can also be grown by adding edges.
95
+
96
+ Add one edge,
97
+
98
+ >>> key = G.add_edge(1, 2)
99
+
100
+ a list of edges,
101
+
102
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
103
+
104
+ or a collection of edges,
105
+
106
+ >>> keys = G.add_edges_from(H.edges)
107
+
108
+ If some edges connect nodes not yet in the graph, the nodes
109
+ are added automatically. If an edge already exists, an additional
110
+ edge is created and stored using a key to identify the edge.
111
+ By default the key is the lowest unused integer.
112
+
113
+ >>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
114
+ >>> G[4]
115
+ AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
116
+
117
+ **Attributes:**
118
+
119
+ Each graph, node, and edge can hold key/value attribute pairs
120
+ in an associated attribute dictionary (the keys must be hashable).
121
+ By default these are empty, but can be added or changed using
122
+ add_edge, add_node or direct manipulation of the attribute
123
+ dictionaries named graph, node and edge respectively.
124
+
125
+ >>> G = nx.MultiGraph(day="Friday")
126
+ >>> G.graph
127
+ {'day': 'Friday'}
128
+
129
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
130
+
131
+ >>> G.add_node(1, time="5pm")
132
+ >>> G.add_nodes_from([3], time="2pm")
133
+ >>> G.nodes[1]
134
+ {'time': '5pm'}
135
+ >>> G.nodes[1]["room"] = 714
136
+ >>> del G.nodes[1]["room"] # remove attribute
137
+ >>> list(G.nodes(data=True))
138
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
139
+
140
+ Add edge attributes using add_edge(), add_edges_from(), subscript
141
+ notation, or G.edges.
142
+
143
+ >>> key = G.add_edge(1, 2, weight=4.7)
144
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
145
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
146
+ >>> G[1][2][0]["weight"] = 4.7
147
+ >>> G.edges[1, 2, 0]["weight"] = 4
148
+
149
+ Warning: we protect the graph data structure by making `G.edges[1,
150
+ 2, 0]` a read-only dict-like structure. However, you can assign to
151
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
152
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
153
+
154
+ **Shortcuts:**
155
+
156
+ Many common graph features allow python syntax to speed reporting.
157
+
158
+ >>> 1 in G # check if node in graph
159
+ True
160
+ >>> [n for n in G if n < 3] # iterate through nodes
161
+ [1, 2]
162
+ >>> len(G) # number of nodes in graph
163
+ 5
164
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
165
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
166
+
167
+ Often the best way to traverse all edges of a graph is via the neighbors.
168
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
169
+
170
+ >>> for n, nbrsdict in G.adjacency():
171
+ ... for nbr, keydict in nbrsdict.items():
172
+ ... for key, eattr in keydict.items():
173
+ ... if "weight" in eattr:
174
+ ... # Do something useful with the edges
175
+ ... pass
176
+
177
+ But the edges() method is often more convenient:
178
+
179
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
180
+ ... if weight is not None:
181
+ ... # Do something useful with the edges
182
+ ... pass
183
+
184
+ **Reporting:**
185
+
186
+ Simple graph information is obtained using methods and object-attributes.
187
+ Reporting usually provides views instead of containers to reduce memory
188
+ usage. The views update as the graph is updated similarly to dict-views.
189
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
190
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
191
+ (e.g. `nodes.items()`, `nodes.data('color')`,
192
+ `nodes.data('color', default='blue')` and similarly for `edges`)
193
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
194
+
195
+ For details on these and other miscellaneous methods, see below.
196
+
197
+ **Subclasses (Advanced):**
198
+
199
+ The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
200
+ The outer dict (node_dict) holds adjacency information keyed by node.
201
+ The next dict (adjlist_dict) represents the adjacency information
202
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
203
+ each edge_attr dict keyed by edge key. The inner dict
204
+ (edge_attr_dict) represents the edge data and holds edge attribute
205
+ values keyed by attribute names.
206
+
207
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
208
+ structure can be replaced by a user defined dict-like object.
209
+ In general, the dict-like features should be maintained but
210
+ extra features can be added. To replace one of the dicts create
211
+ a new graph class by changing the class(!) variable holding the
212
+ factory for that dict-like structure. The variable names are
213
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
214
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
215
+ and graph_attr_dict_factory.
216
+
217
+ node_dict_factory : function, (default: dict)
218
+ Factory function to be used to create the dict containing node
219
+ attributes, keyed by node id.
220
+ It should require no arguments and return a dict-like object
221
+
222
+ node_attr_dict_factory: function, (default: dict)
223
+ Factory function to be used to create the node attribute
224
+ dict which holds attribute values keyed by attribute name.
225
+ It should require no arguments and return a dict-like object
226
+
227
+ adjlist_outer_dict_factory : function, (default: dict)
228
+ Factory function to be used to create the outer-most dict
229
+ in the data structure that holds adjacency info keyed by node.
230
+ It should require no arguments and return a dict-like object.
231
+
232
+ adjlist_inner_dict_factory : function, (default: dict)
233
+ Factory function to be used to create the adjacency list
234
+ dict which holds multiedge key dicts keyed by neighbor.
235
+ It should require no arguments and return a dict-like object.
236
+
237
+ edge_key_dict_factory : function, (default: dict)
238
+ Factory function to be used to create the edge key dict
239
+ which holds edge data keyed by edge key.
240
+ It should require no arguments and return a dict-like object.
241
+
242
+ edge_attr_dict_factory : function, (default: dict)
243
+ Factory function to be used to create the edge attribute
244
+ dict which holds attribute values keyed by attribute name.
245
+ It should require no arguments and return a dict-like object.
246
+
247
+ graph_attr_dict_factory : function, (default: dict)
248
+ Factory function to be used to create the graph attribute
249
+ dict which holds attribute values keyed by attribute name.
250
+ It should require no arguments and return a dict-like object.
251
+
252
+ Typically, if your extension doesn't impact the data structure all
253
+ methods will inherited without issue except: `to_directed/to_undirected`.
254
+ By default these methods create a DiGraph/Graph class and you probably
255
+ want them to create your extension of a DiGraph/Graph. To facilitate
256
+ this we define two class variables that you can set in your subclass.
257
+
258
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
259
+ Class to create a new graph structure in the `to_directed` method.
260
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
261
+
262
+ to_undirected_class : callable, (default: Graph or MultiGraph)
263
+ Class to create a new graph structure in the `to_undirected` method.
264
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
265
+
266
+ **Subclassing Example**
267
+
268
+ Create a low memory graph class that effectively disallows edge
269
+ attributes by using a single attribute dict for all edges.
270
+ This reduces the memory used, but you lose edge attributes.
271
+
272
+ >>> class ThinGraph(nx.Graph):
273
+ ... all_edge_dict = {"weight": 1}
274
+ ...
275
+ ... def single_edge_dict(self):
276
+ ... return self.all_edge_dict
277
+ ...
278
+ ... edge_attr_dict_factory = single_edge_dict
279
+ >>> G = ThinGraph()
280
+ >>> G.add_edge(2, 1)
281
+ >>> G[2][1]
282
+ {'weight': 1}
283
+ >>> G.add_edge(2, 2)
284
+ >>> G[2][1] is G[2][2]
285
+ True
286
+ """
287
+
288
+ # node_dict_factory = dict # already assigned in Graph
289
+ # adjlist_outer_dict_factory = dict
290
+ # adjlist_inner_dict_factory = dict
291
+ edge_key_dict_factory = dict
292
+ # edge_attr_dict_factory = dict
293
+
294
+ def to_directed_class(self):
295
+ """Returns the class to use for empty directed copies.
296
+
297
+ If you subclass the base classes, use this to designate
298
+ what directed class to use for `to_directed()` copies.
299
+ """
300
+ return nx.MultiDiGraph
301
+
302
+ def to_undirected_class(self):
303
+ """Returns the class to use for empty undirected copies.
304
+
305
+ If you subclass the base classes, use this to designate
306
+ what directed class to use for `to_directed()` copies.
307
+ """
308
+ return MultiGraph
309
+
310
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
311
+ """Initialize a graph with edges, name, or graph attributes.
312
+
313
+ Parameters
314
+ ----------
315
+ incoming_graph_data : input graph
316
+ Data to initialize graph. If incoming_graph_data=None (default)
317
+ an empty graph is created. The data can be an edge list, or any
318
+ NetworkX graph object. If the corresponding optional Python
319
+ packages are installed the data can also be a 2D NumPy array, a
320
+ SciPy sparse array, or a PyGraphviz graph.
321
+
322
+ multigraph_input : bool or None (default None)
323
+ Note: Only used when `incoming_graph_data` is a dict.
324
+ If True, `incoming_graph_data` is assumed to be a
325
+ dict-of-dict-of-dict-of-dict structure keyed by
326
+ node to neighbor to edge keys to edge data for multi-edges.
327
+ A NetworkXError is raised if this is not the case.
328
+ If False, :func:`to_networkx_graph` is used to try to determine
329
+ the dict's graph data structure as either a dict-of-dict-of-dict
330
+ keyed by node to neighbor to edge data, or a dict-of-iterable
331
+ keyed by node to neighbors.
332
+ If None, the treatment for True is tried, but if it fails,
333
+ the treatment for False is tried.
334
+
335
+ attr : keyword arguments, optional (default= no attributes)
336
+ Attributes to add to graph as key=value pairs.
337
+
338
+ See Also
339
+ --------
340
+ convert
341
+
342
+ Examples
343
+ --------
344
+ >>> G = nx.MultiGraph()
345
+ >>> G = nx.MultiGraph(name="my graph")
346
+ >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
347
+ >>> G = nx.MultiGraph(e)
348
+
349
+ Arbitrary graph attribute pairs (key=value) may be assigned
350
+
351
+ >>> G = nx.MultiGraph(e, day="Friday")
352
+ >>> G.graph
353
+ {'day': 'Friday'}
354
+
355
+ """
356
+ # multigraph_input can be None/True/False. So check "is not False"
357
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
358
+ Graph.__init__(self)
359
+ try:
360
+ convert.from_dict_of_dicts(
361
+ incoming_graph_data, create_using=self, multigraph_input=True
362
+ )
363
+ self.graph.update(attr)
364
+ except Exception as err:
365
+ if multigraph_input is True:
366
+ raise nx.NetworkXError(
367
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
368
+ )
369
+ Graph.__init__(self, incoming_graph_data, **attr)
370
+ else:
371
+ Graph.__init__(self, incoming_graph_data, **attr)
372
+
373
+ @cached_property
374
+ def adj(self):
375
+ """Graph adjacency object holding the neighbors of each node.
376
+
377
+ This object is a read-only dict-like structure with node keys
378
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
379
+ to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
380
+ the color of the edge `(3, 2, 0)` to `"blue"`.
381
+
382
+ Iterating over G.adj behaves like a dict. Useful idioms include
383
+ `for nbr, edgesdict in G.adj[n].items():`.
384
+
385
+ The neighbor information is also provided by subscripting the graph.
386
+
387
+ Examples
388
+ --------
389
+ >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
390
+ >>> G = nx.MultiGraph(e)
391
+ >>> G.edges[1, 2, 0]["weight"] = 3
392
+ >>> result = set()
393
+ >>> for edgekey, data in G[1][2].items():
394
+ ... result.add(data.get("weight", 1))
395
+ >>> result
396
+ {1, 3}
397
+
398
+ For directed graphs, `G.adj` holds outgoing (successor) info.
399
+ """
400
+ return MultiAdjacencyView(self._adj)
401
+
402
+ def new_edge_key(self, u, v):
403
+ """Returns an unused key for edges between nodes `u` and `v`.
404
+
405
+ The nodes `u` and `v` do not need to be already in the graph.
406
+
407
+ Notes
408
+ -----
409
+ In the standard MultiGraph class the new key is the number of existing
410
+ edges between `u` and `v` (increased if necessary to ensure unused).
411
+ The first edge will have key 0, then 1, etc. If an edge is removed
412
+ further new_edge_keys may not be in this order.
413
+
414
+ Parameters
415
+ ----------
416
+ u, v : nodes
417
+
418
+ Returns
419
+ -------
420
+ key : int
421
+ """
422
+ try:
423
+ keydict = self._adj[u][v]
424
+ except KeyError:
425
+ return 0
426
+ key = len(keydict)
427
+ while key in keydict:
428
+ key += 1
429
+ return key
430
+
431
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
432
+ """Add an edge between u and v.
433
+
434
+ The nodes u and v will be automatically added if they are
435
+ not already in the graph.
436
+
437
+ Edge attributes can be specified with keywords or by directly
438
+ accessing the edge's attribute dictionary. See examples below.
439
+
440
+ Parameters
441
+ ----------
442
+ u_for_edge, v_for_edge : nodes
443
+ Nodes can be, for example, strings or numbers.
444
+ Nodes must be hashable (and not None) Python objects.
445
+ key : hashable identifier, optional (default=lowest unused integer)
446
+ Used to distinguish multiedges between a pair of nodes.
447
+ attr : keyword arguments, optional
448
+ Edge data (or labels or objects) can be assigned using
449
+ keyword arguments.
450
+
451
+ Returns
452
+ -------
453
+ The edge key assigned to the edge.
454
+
455
+ See Also
456
+ --------
457
+ add_edges_from : add a collection of edges
458
+
459
+ Notes
460
+ -----
461
+ To replace/update edge data, use the optional key argument
462
+ to identify a unique edge. Otherwise a new edge will be created.
463
+
464
+ NetworkX algorithms designed for weighted graphs cannot use
465
+ multigraphs directly because it is not clear how to handle
466
+ multiedge weights. Convert to Graph using edge attribute
467
+ 'weight' to enable weighted graph algorithms.
468
+
469
+ Default keys are generated using the method `new_edge_key()`.
470
+ This method can be overridden by subclassing the base class and
471
+ providing a custom `new_edge_key()` method.
472
+
473
+ Examples
474
+ --------
475
+ The following each add an additional edge e=(1, 2) to graph G:
476
+
477
+ >>> G = nx.MultiGraph()
478
+ >>> e = (1, 2)
479
+ >>> ekey = G.add_edge(1, 2) # explicit two-node form
480
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
481
+ 1
482
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
483
+ [2]
484
+
485
+ Associate data to edges using keywords:
486
+
487
+ >>> ekey = G.add_edge(1, 2, weight=3)
488
+ >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
489
+ >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
490
+
491
+ For non-string attribute keys, use subscript notation.
492
+
493
+ >>> ekey = G.add_edge(1, 2)
494
+ >>> G[1][2][0].update({0: 5})
495
+ >>> G.edges[1, 2, 0].update({0: 5})
496
+ """
497
+ u, v = u_for_edge, v_for_edge
498
+ # add nodes
499
+ if u not in self._adj:
500
+ if u is None:
501
+ raise ValueError("None cannot be a node")
502
+ self._adj[u] = self.adjlist_inner_dict_factory()
503
+ self._node[u] = self.node_attr_dict_factory()
504
+ if v not in self._adj:
505
+ if v is None:
506
+ raise ValueError("None cannot be a node")
507
+ self._adj[v] = self.adjlist_inner_dict_factory()
508
+ self._node[v] = self.node_attr_dict_factory()
509
+ if key is None:
510
+ key = self.new_edge_key(u, v)
511
+ if v in self._adj[u]:
512
+ keydict = self._adj[u][v]
513
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
514
+ datadict.update(attr)
515
+ keydict[key] = datadict
516
+ else:
517
+ # selfloops work this way without special treatment
518
+ datadict = self.edge_attr_dict_factory()
519
+ datadict.update(attr)
520
+ keydict = self.edge_key_dict_factory()
521
+ keydict[key] = datadict
522
+ self._adj[u][v] = keydict
523
+ self._adj[v][u] = keydict
524
+ nx._clear_cache(self)
525
+ return key
526
+
527
+ def add_edges_from(self, ebunch_to_add, **attr):
528
+ """Add all the edges in ebunch_to_add.
529
+
530
+ Parameters
531
+ ----------
532
+ ebunch_to_add : container of edges
533
+ Each edge given in the container will be added to the
534
+ graph. The edges can be:
535
+
536
+ - 2-tuples (u, v) or
537
+ - 3-tuples (u, v, d) for an edge data dict d, or
538
+ - 3-tuples (u, v, k) for not iterable key k, or
539
+ - 4-tuples (u, v, k, d) for an edge with data and key k
540
+
541
+ attr : keyword arguments, optional
542
+ Edge data (or labels or objects) can be assigned using
543
+ keyword arguments.
544
+
545
+ Returns
546
+ -------
547
+ A list of edge keys assigned to the edges in `ebunch`.
548
+
549
+ See Also
550
+ --------
551
+ add_edge : add a single edge
552
+ add_weighted_edges_from : convenient way to add weighted edges
553
+
554
+ Notes
555
+ -----
556
+ Adding the same edge twice has no effect but any edge data
557
+ will be updated when each duplicate edge is added.
558
+
559
+ Edge attributes specified in an ebunch take precedence over
560
+ attributes specified via keyword arguments.
561
+
562
+ Default keys are generated using the method ``new_edge_key()``.
563
+ This method can be overridden by subclassing the base class and
564
+ providing a custom ``new_edge_key()`` method.
565
+
566
+ When adding edges from an iterator over the graph you are changing,
567
+ a `RuntimeError` can be raised with message:
568
+ `RuntimeError: dictionary changed size during iteration`. This
569
+ happens when the graph's underlying dictionary is modified during
570
+ iteration. To avoid this error, evaluate the iterator into a separate
571
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
572
+ object to `G.add_edges_from`.
573
+
574
+ Examples
575
+ --------
576
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
577
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
578
+ >>> e = zip(range(0, 3), range(1, 4))
579
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
580
+
581
+ Associate data to edges
582
+
583
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
584
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
585
+
586
+ Evaluate an iterator over a graph if using it to modify the same graph
587
+
588
+ >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
589
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
590
+ >>> # wrong way - will raise RuntimeError
591
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
592
+ >>> # right way - note that there will be no self-edge for node 5
593
+ >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
594
+ """
595
+ keylist = []
596
+ for e in ebunch_to_add:
597
+ ne = len(e)
598
+ if ne == 4:
599
+ u, v, key, dd = e
600
+ elif ne == 3:
601
+ u, v, dd = e
602
+ key = None
603
+ elif ne == 2:
604
+ u, v = e
605
+ dd = {}
606
+ key = None
607
+ else:
608
+ msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
609
+ raise NetworkXError(msg)
610
+ ddd = {}
611
+ ddd.update(attr)
612
+ try:
613
+ ddd.update(dd)
614
+ except (TypeError, ValueError):
615
+ if ne != 3:
616
+ raise
617
+ key = dd # ne == 3 with 3rd value not dict, must be a key
618
+ key = self.add_edge(u, v, key)
619
+ self[u][v][key].update(ddd)
620
+ keylist.append(key)
621
+ nx._clear_cache(self)
622
+ return keylist
623
+
624
+ def remove_edge(self, u, v, key=None):
625
+ """Remove an edge between u and v.
626
+
627
+ Parameters
628
+ ----------
629
+ u, v : nodes
630
+ Remove an edge between nodes u and v.
631
+ key : hashable identifier, optional (default=None)
632
+ Used to distinguish multiple edges between a pair of nodes.
633
+ If None, remove a single edge between u and v. If there are
634
+ multiple edges, removes the last edge added in terms of
635
+ insertion order.
636
+
637
+ Raises
638
+ ------
639
+ NetworkXError
640
+ If there is not an edge between u and v, or
641
+ if there is no edge with the specified key.
642
+
643
+ See Also
644
+ --------
645
+ remove_edges_from : remove a collection of edges
646
+
647
+ Examples
648
+ --------
649
+ >>> G = nx.MultiGraph()
650
+ >>> nx.add_path(G, [0, 1, 2, 3])
651
+ >>> G.remove_edge(0, 1)
652
+ >>> e = (1, 2)
653
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
654
+
655
+ For multiple edges
656
+
657
+ >>> G = nx.MultiGraph() # or MultiDiGraph, etc
658
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
659
+ [0, 1, 2]
660
+
661
+ When ``key=None`` (the default), edges are removed in the opposite
662
+ order that they were added:
663
+
664
+ >>> G.remove_edge(1, 2)
665
+ >>> G.edges(keys=True)
666
+ MultiEdgeView([(1, 2, 0), (1, 2, 1)])
667
+ >>> G.remove_edge(2, 1) # edges are not directed
668
+ >>> G.edges(keys=True)
669
+ MultiEdgeView([(1, 2, 0)])
670
+
671
+ For edges with keys
672
+
673
+ >>> G = nx.MultiGraph()
674
+ >>> G.add_edge(1, 2, key="first")
675
+ 'first'
676
+ >>> G.add_edge(1, 2, key="second")
677
+ 'second'
678
+ >>> G.remove_edge(1, 2, key="first")
679
+ >>> G.edges(keys=True)
680
+ MultiEdgeView([(1, 2, 'second')])
681
+
682
+ """
683
+ try:
684
+ d = self._adj[u][v]
685
+ except KeyError as err:
686
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
687
+ # remove the edge with specified data
688
+ if key is None:
689
+ d.popitem()
690
+ else:
691
+ try:
692
+ del d[key]
693
+ except KeyError as err:
694
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
695
+ raise NetworkXError(msg) from err
696
+ if len(d) == 0:
697
+ # remove the key entries if last edge
698
+ del self._adj[u][v]
699
+ if u != v: # check for selfloop
700
+ del self._adj[v][u]
701
+ nx._clear_cache(self)
702
+
703
+ def remove_edges_from(self, ebunch):
704
+ """Remove all edges specified in ebunch.
705
+
706
+ Parameters
707
+ ----------
708
+ ebunch: list or container of edge tuples
709
+ Each edge given in the list or container will be removed
710
+ from the graph. The edges can be:
711
+
712
+ - 2-tuples (u, v) A single edge between u and v is removed.
713
+ - 3-tuples (u, v, key) The edge identified by key is removed.
714
+ - 4-tuples (u, v, key, data) where data is ignored.
715
+
716
+ See Also
717
+ --------
718
+ remove_edge : remove a single edge
719
+
720
+ Notes
721
+ -----
722
+ Will fail silently if an edge in ebunch is not in the graph.
723
+
724
+ Examples
725
+ --------
726
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
727
+ >>> ebunch = [(1, 2), (2, 3)]
728
+ >>> G.remove_edges_from(ebunch)
729
+
730
+ Removing multiple copies of edges
731
+
732
+ >>> G = nx.MultiGraph()
733
+ >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
734
+ >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
735
+ >>> list(G.edges())
736
+ [(1, 2)]
737
+ >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
738
+ >>> list(G.edges) # now empty graph
739
+ []
740
+
741
+ When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
742
+ u and v in the graph, the most recent edge (in terms of insertion
743
+ order) is removed.
744
+
745
+ >>> G = nx.MultiGraph()
746
+ >>> for key in ("x", "y", "a"):
747
+ ... k = G.add_edge(0, 1, key=key)
748
+ >>> G.edges(keys=True)
749
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
750
+ >>> G.remove_edges_from([(0, 1)])
751
+ >>> G.edges(keys=True)
752
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
753
+
754
+ """
755
+ for e in ebunch:
756
+ try:
757
+ self.remove_edge(*e[:3])
758
+ except NetworkXError:
759
+ pass
760
+ nx._clear_cache(self)
761
+
762
+ def has_edge(self, u, v, key=None):
763
+ """Returns True if the graph has an edge between nodes u and v.
764
+
765
+ This is the same as `v in G[u] or key in G[u][v]`
766
+ without KeyError exceptions.
767
+
768
+ Parameters
769
+ ----------
770
+ u, v : nodes
771
+ Nodes can be, for example, strings or numbers.
772
+
773
+ key : hashable identifier, optional (default=None)
774
+ If specified return True only if the edge with
775
+ key is found.
776
+
777
+ Returns
778
+ -------
779
+ edge_ind : bool
780
+ True if edge is in the graph, False otherwise.
781
+
782
+ Examples
783
+ --------
784
+ Can be called either using two nodes u, v, an edge tuple (u, v),
785
+ or an edge tuple (u, v, key).
786
+
787
+ >>> G = nx.MultiGraph() # or MultiDiGraph
788
+ >>> nx.add_path(G, [0, 1, 2, 3])
789
+ >>> G.has_edge(0, 1) # using two nodes
790
+ True
791
+ >>> e = (0, 1)
792
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
793
+ True
794
+ >>> G.add_edge(0, 1, key="a")
795
+ 'a'
796
+ >>> G.has_edge(0, 1, key="a") # specify key
797
+ True
798
+ >>> G.has_edge(1, 0, key="a") # edges aren't directed
799
+ True
800
+ >>> e = (0, 1, "a")
801
+ >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
802
+ True
803
+
804
+ The following syntax are equivalent:
805
+
806
+ >>> G.has_edge(0, 1)
807
+ True
808
+ >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
809
+ True
810
+ >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
811
+ True
812
+
813
+ """
814
+ try:
815
+ if key is None:
816
+ return v in self._adj[u]
817
+ else:
818
+ return key in self._adj[u][v]
819
+ except KeyError:
820
+ return False
821
+
822
+ @cached_property
823
+ def edges(self):
824
+ """Returns an iterator over the edges.
825
+
826
+ edges(self, nbunch=None, data=False, keys=False, default=None)
827
+
828
+ The MultiEdgeView provides set-like operations on the edge-tuples
829
+ as well as edge attribute lookup. When called, it also provides
830
+ an EdgeDataView object which allows control of access to edge
831
+ attributes (but does not provide set-like operations).
832
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
833
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
834
+ ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
835
+ iterates through all the edges yielding the color attribute with
836
+ default `'red'` if no color attribute exists.
837
+
838
+ Edges are returned as tuples with optional data and keys
839
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
840
+ provided, the tuples will just be (node, neighbor, data), but
841
+ multiple tuples with the same node and neighbor will be generated
842
+ when multiple edges exist between two nodes.
843
+
844
+ Parameters
845
+ ----------
846
+ nbunch : single node, container, or all nodes (default= all nodes)
847
+ The view will only report edges from these nodes.
848
+ data : string or bool, optional (default=False)
849
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
850
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
851
+ If False, return 2-tuple (u, v).
852
+ keys : bool, optional (default=False)
853
+ If True, return edge keys with each edge, creating (u, v, k)
854
+ tuples or (u, v, k, d) tuples if data is also requested.
855
+ default : value, optional (default=None)
856
+ Value used for edges that don't have the requested attribute.
857
+ Only relevant if data is not True or False.
858
+
859
+ Returns
860
+ -------
861
+ edges : MultiEdgeView
862
+ A view of edge attributes, usually it iterates over (u, v)
863
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
864
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
865
+
866
+ Notes
867
+ -----
868
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
869
+ For directed graphs this returns the out-edges.
870
+
871
+ Examples
872
+ --------
873
+ >>> G = nx.MultiGraph()
874
+ >>> nx.add_path(G, [0, 1, 2])
875
+ >>> key = G.add_edge(2, 3, weight=5)
876
+ >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
877
+ >>> [e for e in G.edges()]
878
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
879
+ >>> G.edges.data() # default data is {} (empty dict)
880
+ MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
881
+ >>> G.edges.data("weight", default=1)
882
+ MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
883
+ >>> G.edges(keys=True) # default keys are integers
884
+ MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
885
+ >>> G.edges.data(keys=True)
886
+ MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
887
+ >>> G.edges.data("weight", default=1, keys=True)
888
+ MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
889
+ >>> G.edges([0, 3]) # Note ordering of tuples from listed sources
890
+ MultiEdgeDataView([(0, 1), (3, 2)])
891
+ >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
892
+ MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
893
+ >>> G.edges(0)
894
+ MultiEdgeDataView([(0, 1)])
895
+ """
896
+ return MultiEdgeView(self)
897
+
898
+ def get_edge_data(self, u, v, key=None, default=None):
899
+ """Returns the attribute dictionary associated with edge (u, v,
900
+ key).
901
+
902
+ If a key is not provided, returns a dictionary mapping edge keys
903
+ to attribute dictionaries for each edge between u and v.
904
+
905
+ This is identical to `G[u][v][key]` except the default is returned
906
+ instead of an exception is the edge doesn't exist.
907
+
908
+ Parameters
909
+ ----------
910
+ u, v : nodes
911
+
912
+ default : any Python object (default=None)
913
+ Value to return if the specific edge (u, v, key) is not
914
+ found, OR if there are no edges between u and v and no key
915
+ is specified.
916
+
917
+ key : hashable identifier, optional (default=None)
918
+ Return data only for the edge with specified key, as an
919
+ attribute dictionary (rather than a dictionary mapping keys
920
+ to attribute dictionaries).
921
+
922
+ Returns
923
+ -------
924
+ edge_dict : dictionary
925
+ The edge attribute dictionary, OR a dictionary mapping edge
926
+ keys to attribute dictionaries for each of those edges if no
927
+ specific key is provided (even if there's only one edge
928
+ between u and v).
929
+
930
+ Examples
931
+ --------
932
+ >>> G = nx.MultiGraph() # or MultiDiGraph
933
+ >>> key = G.add_edge(0, 1, key="a", weight=7)
934
+ >>> G[0][1]["a"] # key='a'
935
+ {'weight': 7}
936
+ >>> G.edges[0, 1, "a"] # key='a'
937
+ {'weight': 7}
938
+
939
+ Warning: we protect the graph data structure by making
940
+ `G.edges` and `G[1][2]` read-only dict-like structures.
941
+ However, you can assign values to attributes in e.g.
942
+ `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
943
+ bracket as shown next. You need to specify all edge info
944
+ to assign to the edge data associated with an edge.
945
+
946
+ >>> G[0][1]["a"]["weight"] = 10
947
+ >>> G.edges[0, 1, "a"]["weight"] = 10
948
+ >>> G[0][1]["a"]["weight"]
949
+ 10
950
+ >>> G.edges[1, 0, "a"]["weight"]
951
+ 10
952
+
953
+ >>> G = nx.MultiGraph() # or MultiDiGraph
954
+ >>> nx.add_path(G, [0, 1, 2, 3])
955
+ >>> G.edges[0, 1, 0]["weight"] = 5
956
+ >>> G.get_edge_data(0, 1)
957
+ {0: {'weight': 5}}
958
+ >>> e = (0, 1)
959
+ >>> G.get_edge_data(*e) # tuple form
960
+ {0: {'weight': 5}}
961
+ >>> G.get_edge_data(3, 0) # edge not in graph, returns None
962
+ >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
963
+ 0
964
+ >>> G.get_edge_data(1, 0, 0) # specific key gives back
965
+ {'weight': 5}
966
+ """
967
+ try:
968
+ if key is None:
969
+ return self._adj[u][v]
970
+ else:
971
+ return self._adj[u][v][key]
972
+ except KeyError:
973
+ return default
974
+
975
+ @cached_property
976
+ def degree(self):
977
+ """A DegreeView for the Graph as G.degree or G.degree().
978
+
979
+ The node degree is the number of edges adjacent to the node.
980
+ The weighted node degree is the sum of the edge weights for
981
+ edges incident to that node.
982
+
983
+ This object provides an iterator for (node, degree) as well as
984
+ lookup for the degree for a single node.
985
+
986
+ Parameters
987
+ ----------
988
+ nbunch : single node, container, or all nodes (default= all nodes)
989
+ The view will only report edges incident to these nodes.
990
+
991
+ weight : string or None, optional (default=None)
992
+ The name of an edge attribute that holds the numerical value used
993
+ as a weight. If None, then each edge has weight 1.
994
+ The degree is the sum of the edge weights adjacent to the node.
995
+
996
+ Returns
997
+ -------
998
+ MultiDegreeView or int
999
+ If multiple nodes are requested (the default), returns a `MultiDegreeView`
1000
+ mapping nodes to their degree.
1001
+ If a single node is requested, returns the degree of the node as an integer.
1002
+
1003
+ Examples
1004
+ --------
1005
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1006
+ >>> nx.add_path(G, [0, 1, 2, 3])
1007
+ >>> G.degree(0) # node 0 with degree 1
1008
+ 1
1009
+ >>> list(G.degree([0, 1]))
1010
+ [(0, 1), (1, 2)]
1011
+
1012
+ """
1013
+ return MultiDegreeView(self)
1014
+
1015
+ def is_multigraph(self):
1016
+ """Returns True if graph is a multigraph, False otherwise."""
1017
+ return True
1018
+
1019
+ def is_directed(self):
1020
+ """Returns True if graph is directed, False otherwise."""
1021
+ return False
1022
+
1023
+ def copy(self, as_view=False):
1024
+ """Returns a copy of the graph.
1025
+
1026
+ The copy method by default returns an independent shallow copy
1027
+ of the graph and attributes. That is, if an attribute is a
1028
+ container, that container is shared by the original an the copy.
1029
+ Use Python's `copy.deepcopy` for new containers.
1030
+
1031
+ If `as_view` is True then a view is returned instead of a copy.
1032
+
1033
+ Notes
1034
+ -----
1035
+ All copies reproduce the graph structure, but data attributes
1036
+ may be handled in different ways. There are four types of copies
1037
+ of a graph that people might want.
1038
+
1039
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1040
+ all data attributes and any objects they might contain.
1041
+ The entire graph object is new so that changes in the copy
1042
+ do not affect the original object. (see Python's copy.deepcopy)
1043
+
1044
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1045
+ is copied but the edge, node and graph attribute dicts are
1046
+ references to those in the original graph. This saves
1047
+ time and memory but could cause confusion if you change an attribute
1048
+ in one graph and it changes the attribute in the other.
1049
+ NetworkX does not provide this level of shallow copy.
1050
+
1051
+ Independent Shallow -- This copy creates new independent attribute
1052
+ dicts and then does a shallow copy of the attributes. That is, any
1053
+ attributes that are containers are shared between the new graph
1054
+ and the original. This is exactly what `dict.copy()` provides.
1055
+ You can obtain this style copy using:
1056
+
1057
+ >>> G = nx.path_graph(5)
1058
+ >>> H = G.copy()
1059
+ >>> H = G.copy(as_view=False)
1060
+ >>> H = nx.Graph(G)
1061
+ >>> H = G.__class__(G)
1062
+
1063
+ Fresh Data -- For fresh data, the graph structure is copied while
1064
+ new empty data attribute dicts are created. The resulting graph
1065
+ is independent of the original and it has no edge, node or graph
1066
+ attributes. Fresh copies are not enabled. Instead use:
1067
+
1068
+ >>> H = G.__class__()
1069
+ >>> H.add_nodes_from(G)
1070
+ >>> H.add_edges_from(G.edges)
1071
+
1072
+ View -- Inspired by dict-views, graph-views act like read-only
1073
+ versions of the original graph, providing a copy of the original
1074
+ structure without requiring any memory for copying the information.
1075
+
1076
+ See the Python copy module for more information on shallow
1077
+ and deep copies, https://docs.python.org/3/library/copy.html.
1078
+
1079
+ Parameters
1080
+ ----------
1081
+ as_view : bool, optional (default=False)
1082
+ If True, the returned graph-view provides a read-only view
1083
+ of the original graph without actually copying any data.
1084
+
1085
+ Returns
1086
+ -------
1087
+ G : Graph
1088
+ A copy of the graph.
1089
+
1090
+ See Also
1091
+ --------
1092
+ to_directed: return a directed copy of the graph.
1093
+
1094
+ Examples
1095
+ --------
1096
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1097
+ >>> H = G.copy()
1098
+
1099
+ """
1100
+ if as_view is True:
1101
+ return nx.graphviews.generic_graph_view(self)
1102
+ G = self.__class__()
1103
+ G.graph.update(self.graph)
1104
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1105
+ G.add_edges_from(
1106
+ (u, v, key, datadict.copy())
1107
+ for u, nbrs in self._adj.items()
1108
+ for v, keydict in nbrs.items()
1109
+ for key, datadict in keydict.items()
1110
+ )
1111
+ return G
1112
+
1113
+ def to_directed(self, as_view=False):
1114
+ """Returns a directed representation of the graph.
1115
+
1116
+ Returns
1117
+ -------
1118
+ G : MultiDiGraph
1119
+ A directed graph with the same name, same nodes, and with
1120
+ each edge (u, v, k, data) replaced by two directed edges
1121
+ (u, v, k, data) and (v, u, k, data).
1122
+
1123
+ Notes
1124
+ -----
1125
+ This returns a "deepcopy" of the edge, node, and
1126
+ graph attributes which attempts to completely copy
1127
+ all of the data and references.
1128
+
1129
+ This is in contrast to the similar D=MultiDiGraph(G) which
1130
+ returns a shallow copy of the data.
1131
+
1132
+ See the Python copy module for more information on shallow
1133
+ and deep copies, https://docs.python.org/3/library/copy.html.
1134
+
1135
+ Warning: If you have subclassed MultiGraph to use dict-like objects
1136
+ in the data structure, those changes do not transfer to the
1137
+ MultiDiGraph created by this method.
1138
+
1139
+ Examples
1140
+ --------
1141
+ >>> G = nx.MultiGraph()
1142
+ >>> G.add_edge(0, 1)
1143
+ 0
1144
+ >>> G.add_edge(0, 1)
1145
+ 1
1146
+ >>> H = G.to_directed()
1147
+ >>> list(H.edges)
1148
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
1149
+
1150
+ If already directed, return a (deep) copy
1151
+
1152
+ >>> G = nx.MultiDiGraph()
1153
+ >>> G.add_edge(0, 1)
1154
+ 0
1155
+ >>> H = G.to_directed()
1156
+ >>> list(H.edges)
1157
+ [(0, 1, 0)]
1158
+ """
1159
+ graph_class = self.to_directed_class()
1160
+ if as_view is True:
1161
+ return nx.graphviews.generic_graph_view(self, graph_class)
1162
+ # deepcopy when not a view
1163
+ G = graph_class()
1164
+ G.graph.update(deepcopy(self.graph))
1165
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1166
+ G.add_edges_from(
1167
+ (u, v, key, deepcopy(datadict))
1168
+ for u, nbrs in self.adj.items()
1169
+ for v, keydict in nbrs.items()
1170
+ for key, datadict in keydict.items()
1171
+ )
1172
+ return G
1173
+
1174
+ def to_undirected(self, as_view=False):
1175
+ """Returns an undirected copy of the graph.
1176
+
1177
+ Returns
1178
+ -------
1179
+ G : Graph/MultiGraph
1180
+ A deepcopy of the graph.
1181
+
1182
+ See Also
1183
+ --------
1184
+ copy, add_edge, add_edges_from
1185
+
1186
+ Notes
1187
+ -----
1188
+ This returns a "deepcopy" of the edge, node, and
1189
+ graph attributes which attempts to completely copy
1190
+ all of the data and references.
1191
+
1192
+ This is in contrast to the similar `G = nx.MultiGraph(D)`
1193
+ which returns a shallow copy of the data.
1194
+
1195
+ See the Python copy module for more information on shallow
1196
+ and deep copies, https://docs.python.org/3/library/copy.html.
1197
+
1198
+ Warning: If you have subclassed MultiGraph to use dict-like
1199
+ objects in the data structure, those changes do not transfer
1200
+ to the MultiGraph created by this method.
1201
+
1202
+ Examples
1203
+ --------
1204
+ >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
1205
+ >>> H = G.to_directed()
1206
+ >>> list(H.edges)
1207
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
1208
+ >>> G2 = H.to_undirected()
1209
+ >>> list(G2.edges)
1210
+ [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
1211
+ """
1212
+ graph_class = self.to_undirected_class()
1213
+ if as_view is True:
1214
+ return nx.graphviews.generic_graph_view(self, graph_class)
1215
+ # deepcopy when not a view
1216
+ G = graph_class()
1217
+ G.graph.update(deepcopy(self.graph))
1218
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1219
+ G.add_edges_from(
1220
+ (u, v, key, deepcopy(datadict))
1221
+ for u, nbrs in self._adj.items()
1222
+ for v, keydict in nbrs.items()
1223
+ for key, datadict in keydict.items()
1224
+ )
1225
+ return G
1226
+
1227
+ def number_of_edges(self, u=None, v=None):
1228
+ """Returns the number of edges between two nodes.
1229
+
1230
+ Parameters
1231
+ ----------
1232
+ u, v : nodes, optional (Default=all edges)
1233
+ If u and v are specified, return the number of edges between
1234
+ u and v. Otherwise return the total number of all edges.
1235
+
1236
+ Returns
1237
+ -------
1238
+ nedges : int
1239
+ The number of edges in the graph. If nodes `u` and `v` are
1240
+ specified return the number of edges between those nodes. If
1241
+ the graph is directed, this only returns the number of edges
1242
+ from `u` to `v`.
1243
+
1244
+ See Also
1245
+ --------
1246
+ size
1247
+
1248
+ Examples
1249
+ --------
1250
+ For undirected multigraphs, this method counts the total number
1251
+ of edges in the graph::
1252
+
1253
+ >>> G = nx.MultiGraph()
1254
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
1255
+ [0, 1, 0]
1256
+ >>> G.number_of_edges()
1257
+ 3
1258
+
1259
+ If you specify two nodes, this counts the total number of edges
1260
+ joining the two nodes::
1261
+
1262
+ >>> G.number_of_edges(0, 1)
1263
+ 2
1264
+
1265
+ For directed multigraphs, this method can count the total number
1266
+ of directed edges from `u` to `v`::
1267
+
1268
+ >>> G = nx.MultiDiGraph()
1269
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
1270
+ [0, 1, 0]
1271
+ >>> G.number_of_edges(0, 1)
1272
+ 2
1273
+ >>> G.number_of_edges(1, 0)
1274
+ 1
1275
+
1276
+ """
1277
+ if u is None:
1278
+ return self.size()
1279
+ try:
1280
+ edgedata = self._adj[u][v]
1281
+ except KeyError:
1282
+ return 0 # no such edge
1283
+ return len(edgedata)
deepseek/lib/python3.10/site-packages/networkx/classes/reportviews.py ADDED
@@ -0,0 +1,1447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
86
+ from abc import ABC
87
+ from collections.abc import Mapping, Set
88
+
89
+ import networkx as nx
90
+
91
+ __all__ = [
92
+ "NodeView",
93
+ "NodeDataView",
94
+ "EdgeView",
95
+ "OutEdgeView",
96
+ "InEdgeView",
97
+ "EdgeDataView",
98
+ "OutEdgeDataView",
99
+ "InEdgeDataView",
100
+ "MultiEdgeView",
101
+ "OutMultiEdgeView",
102
+ "InMultiEdgeView",
103
+ "MultiEdgeDataView",
104
+ "OutMultiEdgeDataView",
105
+ "InMultiEdgeDataView",
106
+ "DegreeView",
107
+ "DiDegreeView",
108
+ "InDegreeView",
109
+ "OutDegreeView",
110
+ "MultiDegreeView",
111
+ "DiMultiDegreeView",
112
+ "InMultiDegreeView",
113
+ "OutMultiDegreeView",
114
+ ]
115
+
116
+
117
+ # NodeViews
118
+ class NodeView(Mapping, Set):
119
+ """A NodeView class to act as G.nodes for a NetworkX Graph
120
+
121
+ Set operations act on the nodes without considering data.
122
+ Iteration is over nodes. Node data can be looked up like a dict.
123
+ Use NodeDataView to iterate over node data or to specify a data
124
+ attribute for lookup. NodeDataView is created by calling the NodeView.
125
+
126
+ Parameters
127
+ ----------
128
+ graph : NetworkX graph-like class
129
+
130
+ Examples
131
+ --------
132
+ >>> G = nx.path_graph(3)
133
+ >>> NV = G.nodes()
134
+ >>> 2 in NV
135
+ True
136
+ >>> for n in NV:
137
+ ... print(n)
138
+ 0
139
+ 1
140
+ 2
141
+ >>> assert NV & {1, 2, 3} == {1, 2}
142
+
143
+ >>> G.add_node(2, color="blue")
144
+ >>> NV[2]
145
+ {'color': 'blue'}
146
+ >>> G.add_node(8, color="red")
147
+ >>> NDV = G.nodes(data=True)
148
+ >>> (2, NV[2]) in NDV
149
+ True
150
+ >>> for n, dd in NDV:
151
+ ... print((n, dd.get("color", "aqua")))
152
+ (0, 'aqua')
153
+ (1, 'aqua')
154
+ (2, 'blue')
155
+ (8, 'red')
156
+ >>> NDV[2] == NV[2]
157
+ True
158
+
159
+ >>> NVdata = G.nodes(data="color", default="aqua")
160
+ >>> (2, NVdata[2]) in NVdata
161
+ True
162
+ >>> for n, dd in NVdata:
163
+ ... print((n, dd))
164
+ (0, 'aqua')
165
+ (1, 'aqua')
166
+ (2, 'blue')
167
+ (8, 'red')
168
+ >>> NVdata[2] == NV[2] # NVdata gets 'color', NV gets datadict
169
+ False
170
+ """
171
+
172
+ __slots__ = ("_nodes",)
173
+
174
+ def __getstate__(self):
175
+ return {"_nodes": self._nodes}
176
+
177
+ def __setstate__(self, state):
178
+ self._nodes = state["_nodes"]
179
+
180
+ def __init__(self, graph):
181
+ self._nodes = graph._node
182
+
183
+ # Mapping methods
184
+ def __len__(self):
185
+ return len(self._nodes)
186
+
187
+ def __iter__(self):
188
+ return iter(self._nodes)
189
+
190
+ def __getitem__(self, n):
191
+ if isinstance(n, slice):
192
+ raise nx.NetworkXError(
193
+ f"{type(self).__name__} does not support slicing, "
194
+ f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]"
195
+ )
196
+ return self._nodes[n]
197
+
198
+ # Set methods
199
+ def __contains__(self, n):
200
+ return n in self._nodes
201
+
202
+ @classmethod
203
+ def _from_iterable(cls, it):
204
+ return set(it)
205
+
206
+ # DataView method
207
+ def __call__(self, data=False, default=None):
208
+ if data is False:
209
+ return self
210
+ return NodeDataView(self._nodes, data, default)
211
+
212
+ def data(self, data=True, default=None):
213
+ """
214
+ Return a read-only view of node data.
215
+
216
+ Parameters
217
+ ----------
218
+ data : bool or node data key, default=True
219
+ If ``data=True`` (the default), return a `NodeDataView` object that
220
+ maps each node to *all* of its attributes. `data` may also be an
221
+ arbitrary key, in which case the `NodeDataView` maps each node to
222
+ the value for the keyed attribute. In this case, if a node does
223
+ not have the `data` attribute, the `default` value is used.
224
+ default : object, default=None
225
+ The value used when a node does not have a specific attribute.
226
+
227
+ Returns
228
+ -------
229
+ NodeDataView
230
+ The layout of the returned NodeDataView depends on the value of the
231
+ `data` parameter.
232
+
233
+ Notes
234
+ -----
235
+ If ``data=False``, returns a `NodeView` object without data.
236
+
237
+ See Also
238
+ --------
239
+ NodeDataView
240
+
241
+ Examples
242
+ --------
243
+ >>> G = nx.Graph()
244
+ >>> G.add_nodes_from(
245
+ ... [
246
+ ... (0, {"color": "red", "weight": 10}),
247
+ ... (1, {"color": "blue"}),
248
+ ... (2, {"color": "yellow", "weight": 2}),
249
+ ... ]
250
+ ... )
251
+
252
+ Accessing node data with ``data=True`` (the default) returns a
253
+ NodeDataView mapping each node to all of its attributes:
254
+
255
+ >>> G.nodes.data()
256
+ NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}})
257
+
258
+ If `data` represents a key in the node attribute dict, a NodeDataView mapping
259
+ the nodes to the value for that specific key is returned:
260
+
261
+ >>> G.nodes.data("color")
262
+ NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color')
263
+
264
+ If a specific key is not found in an attribute dict, the value specified
265
+ by `default` is returned:
266
+
267
+ >>> G.nodes.data("weight", default=-999)
268
+ NodeDataView({0: 10, 1: -999, 2: 2}, data='weight')
269
+
270
+ Note that there is no check that the `data` key is in any of the
271
+ node attribute dictionaries:
272
+
273
+ >>> G.nodes.data("height")
274
+ NodeDataView({0: None, 1: None, 2: None}, data='height')
275
+ """
276
+ if data is False:
277
+ return self
278
+ return NodeDataView(self._nodes, data, default)
279
+
280
+ def __str__(self):
281
+ return str(list(self))
282
+
283
+ def __repr__(self):
284
+ return f"{self.__class__.__name__}({tuple(self)})"
285
+
286
+
287
+ class NodeDataView(Set):
288
+ """A DataView class for nodes of a NetworkX Graph
289
+
290
+ The main use for this class is to iterate through node-data pairs.
291
+ The data can be the entire data-dictionary for each node, or it
292
+ can be a specific attribute (with default) for each node.
293
+ Set operations are enabled with NodeDataView, but don't work in
294
+ cases where the data is not hashable. Use with caution.
295
+ Typically, set operations on nodes use NodeView, not NodeDataView.
296
+ That is, they use `G.nodes` instead of `G.nodes(data='foo')`.
297
+
298
+ Parameters
299
+ ==========
300
+ graph : NetworkX graph-like class
301
+ data : bool or string (default=False)
302
+ default : object (default=None)
303
+ """
304
+
305
+ __slots__ = ("_nodes", "_data", "_default")
306
+
307
+ def __getstate__(self):
308
+ return {"_nodes": self._nodes, "_data": self._data, "_default": self._default}
309
+
310
+ def __setstate__(self, state):
311
+ self._nodes = state["_nodes"]
312
+ self._data = state["_data"]
313
+ self._default = state["_default"]
314
+
315
+ def __init__(self, nodedict, data=False, default=None):
316
+ self._nodes = nodedict
317
+ self._data = data
318
+ self._default = default
319
+
320
+ @classmethod
321
+ def _from_iterable(cls, it):
322
+ try:
323
+ return set(it)
324
+ except TypeError as err:
325
+ if "unhashable" in str(err):
326
+ msg = " : Could be b/c data=True or your values are unhashable"
327
+ raise TypeError(str(err) + msg) from err
328
+ raise
329
+
330
+ def __len__(self):
331
+ return len(self._nodes)
332
+
333
+ def __iter__(self):
334
+ data = self._data
335
+ if data is False:
336
+ return iter(self._nodes)
337
+ if data is True:
338
+ return iter(self._nodes.items())
339
+ return (
340
+ (n, dd[data] if data in dd else self._default)
341
+ for n, dd in self._nodes.items()
342
+ )
343
+
344
+ def __contains__(self, n):
345
+ try:
346
+ node_in = n in self._nodes
347
+ except TypeError:
348
+ n, d = n
349
+ return n in self._nodes and self[n] == d
350
+ if node_in is True:
351
+ return node_in
352
+ try:
353
+ n, d = n
354
+ except (TypeError, ValueError):
355
+ return False
356
+ return n in self._nodes and self[n] == d
357
+
358
+ def __getitem__(self, n):
359
+ if isinstance(n, slice):
360
+ raise nx.NetworkXError(
361
+ f"{type(self).__name__} does not support slicing, "
362
+ f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]"
363
+ )
364
+ ddict = self._nodes[n]
365
+ data = self._data
366
+ if data is False or data is True:
367
+ return ddict
368
+ return ddict[data] if data in ddict else self._default
369
+
370
+ def __str__(self):
371
+ return str(list(self))
372
+
373
+ def __repr__(self):
374
+ name = self.__class__.__name__
375
+ if self._data is False:
376
+ return f"{name}({tuple(self)})"
377
+ if self._data is True:
378
+ return f"{name}({dict(self)})"
379
+ return f"{name}({dict(self)}, data={self._data!r})"
380
+
381
+
382
+ # DegreeViews
383
+ class DiDegreeView:
384
+ """A View class for degree of nodes in a NetworkX Graph
385
+
386
+ The functionality is like dict.items() with (node, degree) pairs.
387
+ Additional functionality includes read-only lookup of node degree,
388
+ and calling with optional features nbunch (for only a subset of nodes)
389
+ and weight (use edge weights to compute degree).
390
+
391
+ Parameters
392
+ ==========
393
+ graph : NetworkX graph-like class
394
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
395
+ weight : bool or string (default=None)
396
+
397
+ Notes
398
+ -----
399
+ DegreeView can still lookup any node even if nbunch is specified.
400
+
401
+ Examples
402
+ --------
403
+ >>> G = nx.path_graph(3)
404
+ >>> DV = G.degree()
405
+ >>> assert DV[2] == 1
406
+ >>> assert sum(deg for n, deg in DV) == 4
407
+
408
+ >>> DVweight = G.degree(weight="span")
409
+ >>> G.add_edge(1, 2, span=34)
410
+ >>> DVweight[2]
411
+ 34
412
+ >>> DVweight[0] # default edge weight is 1
413
+ 1
414
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
415
+ 70
416
+
417
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
418
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
419
+ """
420
+
421
+ def __init__(self, G, nbunch=None, weight=None):
422
+ self._graph = G
423
+ self._succ = G._succ if hasattr(G, "_succ") else G._adj
424
+ self._pred = G._pred if hasattr(G, "_pred") else G._adj
425
+ self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch))
426
+ self._weight = weight
427
+
428
+ def __call__(self, nbunch=None, weight=None):
429
+ if nbunch is None:
430
+ if weight == self._weight:
431
+ return self
432
+ return self.__class__(self._graph, None, weight)
433
+ try:
434
+ if nbunch in self._nodes:
435
+ if weight == self._weight:
436
+ return self[nbunch]
437
+ return self.__class__(self._graph, None, weight)[nbunch]
438
+ except TypeError:
439
+ pass
440
+ return self.__class__(self._graph, nbunch, weight)
441
+
442
+ def __getitem__(self, n):
443
+ weight = self._weight
444
+ succs = self._succ[n]
445
+ preds = self._pred[n]
446
+ if weight is None:
447
+ return len(succs) + len(preds)
448
+ return sum(dd.get(weight, 1) for dd in succs.values()) + sum(
449
+ dd.get(weight, 1) for dd in preds.values()
450
+ )
451
+
452
+ def __iter__(self):
453
+ weight = self._weight
454
+ if weight is None:
455
+ for n in self._nodes:
456
+ succs = self._succ[n]
457
+ preds = self._pred[n]
458
+ yield (n, len(succs) + len(preds))
459
+ else:
460
+ for n in self._nodes:
461
+ succs = self._succ[n]
462
+ preds = self._pred[n]
463
+ deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum(
464
+ dd.get(weight, 1) for dd in preds.values()
465
+ )
466
+ yield (n, deg)
467
+
468
+ def __len__(self):
469
+ return len(self._nodes)
470
+
471
+ def __str__(self):
472
+ return str(list(self))
473
+
474
+ def __repr__(self):
475
+ return f"{self.__class__.__name__}({dict(self)})"
476
+
477
+
478
+ class DegreeView(DiDegreeView):
479
+ """A DegreeView class to act as G.degree for a NetworkX Graph
480
+
481
+ Typical usage focuses on iteration over `(node, degree)` pairs.
482
+ The degree is by default the number of edges incident to the node.
483
+ Optional argument `weight` enables weighted degree using the edge
484
+ attribute named in the `weight` argument. Reporting and iteration
485
+ can also be restricted to a subset of nodes using `nbunch`.
486
+
487
+ Additional functionality include node lookup so that `G.degree[n]`
488
+ reported the (possibly weighted) degree of node `n`. Calling the
489
+ view creates a view with different arguments `nbunch` or `weight`.
490
+
491
+ Parameters
492
+ ==========
493
+ graph : NetworkX graph-like class
494
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
495
+ weight : string or None (default=None)
496
+
497
+ Notes
498
+ -----
499
+ DegreeView can still lookup any node even if nbunch is specified.
500
+
501
+ Examples
502
+ --------
503
+ >>> G = nx.path_graph(3)
504
+ >>> DV = G.degree()
505
+ >>> assert DV[2] == 1
506
+ >>> assert G.degree[2] == 1
507
+ >>> assert sum(deg for n, deg in DV) == 4
508
+
509
+ >>> DVweight = G.degree(weight="span")
510
+ >>> G.add_edge(1, 2, span=34)
511
+ >>> DVweight[2]
512
+ 34
513
+ >>> DVweight[0] # default edge weight is 1
514
+ 1
515
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
516
+ 70
517
+
518
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
519
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
520
+ """
521
+
522
+ def __getitem__(self, n):
523
+ weight = self._weight
524
+ nbrs = self._succ[n]
525
+ if weight is None:
526
+ return len(nbrs) + (n in nbrs)
527
+ return sum(dd.get(weight, 1) for dd in nbrs.values()) + (
528
+ n in nbrs and nbrs[n].get(weight, 1)
529
+ )
530
+
531
+ def __iter__(self):
532
+ weight = self._weight
533
+ if weight is None:
534
+ for n in self._nodes:
535
+ nbrs = self._succ[n]
536
+ yield (n, len(nbrs) + (n in nbrs))
537
+ else:
538
+ for n in self._nodes:
539
+ nbrs = self._succ[n]
540
+ deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + (
541
+ n in nbrs and nbrs[n].get(weight, 1)
542
+ )
543
+ yield (n, deg)
544
+
545
+
546
+ class OutDegreeView(DiDegreeView):
547
+ """A DegreeView class to report out_degree for a DiGraph; See DegreeView"""
548
+
549
+ def __getitem__(self, n):
550
+ weight = self._weight
551
+ nbrs = self._succ[n]
552
+ if self._weight is None:
553
+ return len(nbrs)
554
+ return sum(dd.get(self._weight, 1) for dd in nbrs.values())
555
+
556
+ def __iter__(self):
557
+ weight = self._weight
558
+ if weight is None:
559
+ for n in self._nodes:
560
+ succs = self._succ[n]
561
+ yield (n, len(succs))
562
+ else:
563
+ for n in self._nodes:
564
+ succs = self._succ[n]
565
+ deg = sum(dd.get(weight, 1) for dd in succs.values())
566
+ yield (n, deg)
567
+
568
+
569
+ class InDegreeView(DiDegreeView):
570
+ """A DegreeView class to report in_degree for a DiGraph; See DegreeView"""
571
+
572
+ def __getitem__(self, n):
573
+ weight = self._weight
574
+ nbrs = self._pred[n]
575
+ if weight is None:
576
+ return len(nbrs)
577
+ return sum(dd.get(weight, 1) for dd in nbrs.values())
578
+
579
+ def __iter__(self):
580
+ weight = self._weight
581
+ if weight is None:
582
+ for n in self._nodes:
583
+ preds = self._pred[n]
584
+ yield (n, len(preds))
585
+ else:
586
+ for n in self._nodes:
587
+ preds = self._pred[n]
588
+ deg = sum(dd.get(weight, 1) for dd in preds.values())
589
+ yield (n, deg)
590
+
591
+
592
+ class MultiDegreeView(DiDegreeView):
593
+ """A DegreeView class for undirected multigraphs; See DegreeView"""
594
+
595
+ def __getitem__(self, n):
596
+ weight = self._weight
597
+ nbrs = self._succ[n]
598
+ if weight is None:
599
+ return sum(len(keys) for keys in nbrs.values()) + (
600
+ n in nbrs and len(nbrs[n])
601
+ )
602
+ # edge weighted graph - degree is sum of nbr edge weights
603
+ deg = sum(
604
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
605
+ )
606
+ if n in nbrs:
607
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
608
+ return deg
609
+
610
+ def __iter__(self):
611
+ weight = self._weight
612
+ if weight is None:
613
+ for n in self._nodes:
614
+ nbrs = self._succ[n]
615
+ deg = sum(len(keys) for keys in nbrs.values()) + (
616
+ n in nbrs and len(nbrs[n])
617
+ )
618
+ yield (n, deg)
619
+ else:
620
+ for n in self._nodes:
621
+ nbrs = self._succ[n]
622
+ deg = sum(
623
+ d.get(weight, 1)
624
+ for key_dict in nbrs.values()
625
+ for d in key_dict.values()
626
+ )
627
+ if n in nbrs:
628
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
629
+ yield (n, deg)
630
+
631
+
632
+ class DiMultiDegreeView(DiDegreeView):
633
+ """A DegreeView class for MultiDiGraph; See DegreeView"""
634
+
635
+ def __getitem__(self, n):
636
+ weight = self._weight
637
+ succs = self._succ[n]
638
+ preds = self._pred[n]
639
+ if weight is None:
640
+ return sum(len(keys) for keys in succs.values()) + sum(
641
+ len(keys) for keys in preds.values()
642
+ )
643
+ # edge weighted graph - degree is sum of nbr edge weights
644
+ deg = sum(
645
+ d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values()
646
+ ) + sum(
647
+ d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values()
648
+ )
649
+ return deg
650
+
651
+ def __iter__(self):
652
+ weight = self._weight
653
+ if weight is None:
654
+ for n in self._nodes:
655
+ succs = self._succ[n]
656
+ preds = self._pred[n]
657
+ deg = sum(len(keys) for keys in succs.values()) + sum(
658
+ len(keys) for keys in preds.values()
659
+ )
660
+ yield (n, deg)
661
+ else:
662
+ for n in self._nodes:
663
+ succs = self._succ[n]
664
+ preds = self._pred[n]
665
+ deg = sum(
666
+ d.get(weight, 1)
667
+ for key_dict in succs.values()
668
+ for d in key_dict.values()
669
+ ) + sum(
670
+ d.get(weight, 1)
671
+ for key_dict in preds.values()
672
+ for d in key_dict.values()
673
+ )
674
+ yield (n, deg)
675
+
676
+
677
+ class InMultiDegreeView(DiDegreeView):
678
+ """A DegreeView class for inward degree of MultiDiGraph; See DegreeView"""
679
+
680
+ def __getitem__(self, n):
681
+ weight = self._weight
682
+ nbrs = self._pred[n]
683
+ if weight is None:
684
+ return sum(len(data) for data in nbrs.values())
685
+ # edge weighted graph - degree is sum of nbr edge weights
686
+ return sum(
687
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
688
+ )
689
+
690
+ def __iter__(self):
691
+ weight = self._weight
692
+ if weight is None:
693
+ for n in self._nodes:
694
+ nbrs = self._pred[n]
695
+ deg = sum(len(data) for data in nbrs.values())
696
+ yield (n, deg)
697
+ else:
698
+ for n in self._nodes:
699
+ nbrs = self._pred[n]
700
+ deg = sum(
701
+ d.get(weight, 1)
702
+ for key_dict in nbrs.values()
703
+ for d in key_dict.values()
704
+ )
705
+ yield (n, deg)
706
+
707
+
708
+ class OutMultiDegreeView(DiDegreeView):
709
+ """A DegreeView class for outward degree of MultiDiGraph; See DegreeView"""
710
+
711
+ def __getitem__(self, n):
712
+ weight = self._weight
713
+ nbrs = self._succ[n]
714
+ if weight is None:
715
+ return sum(len(data) for data in nbrs.values())
716
+ # edge weighted graph - degree is sum of nbr edge weights
717
+ return sum(
718
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
719
+ )
720
+
721
+ def __iter__(self):
722
+ weight = self._weight
723
+ if weight is None:
724
+ for n in self._nodes:
725
+ nbrs = self._succ[n]
726
+ deg = sum(len(data) for data in nbrs.values())
727
+ yield (n, deg)
728
+ else:
729
+ for n in self._nodes:
730
+ nbrs = self._succ[n]
731
+ deg = sum(
732
+ d.get(weight, 1)
733
+ for key_dict in nbrs.values()
734
+ for d in key_dict.values()
735
+ )
736
+ yield (n, deg)
737
+
738
+
739
+ # A base class for all edge views. Ensures all edge view and edge data view
740
+ # objects/classes are captured by `isinstance(obj, EdgeViewABC)` and
741
+ # `issubclass(cls, EdgeViewABC)` respectively
742
+ class EdgeViewABC(ABC):
743
+ pass
744
+
745
+
746
+ # EdgeDataViews
747
+ class OutEdgeDataView(EdgeViewABC):
748
+ """EdgeDataView for outward edges of DiGraph; See EdgeDataView"""
749
+
750
+ __slots__ = (
751
+ "_viewer",
752
+ "_nbunch",
753
+ "_data",
754
+ "_default",
755
+ "_adjdict",
756
+ "_nodes_nbrs",
757
+ "_report",
758
+ )
759
+
760
+ def __getstate__(self):
761
+ return {
762
+ "viewer": self._viewer,
763
+ "nbunch": self._nbunch,
764
+ "data": self._data,
765
+ "default": self._default,
766
+ }
767
+
768
+ def __setstate__(self, state):
769
+ self.__init__(**state)
770
+
771
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None):
772
+ self._viewer = viewer
773
+ adjdict = self._adjdict = viewer._adjdict
774
+ if nbunch is None:
775
+ self._nodes_nbrs = adjdict.items
776
+ else:
777
+ # dict retains order of nodes but acts like a set
778
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
779
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
780
+ self._nbunch = nbunch
781
+ self._data = data
782
+ self._default = default
783
+ # Set _report based on data and default
784
+ if data is True:
785
+ self._report = lambda n, nbr, dd: (n, nbr, dd)
786
+ elif data is False:
787
+ self._report = lambda n, nbr, dd: (n, nbr)
788
+ else: # data is attribute name
789
+ self._report = (
790
+ lambda n, nbr, dd: (n, nbr, dd[data])
791
+ if data in dd
792
+ else (n, nbr, default)
793
+ )
794
+
795
+ def __len__(self):
796
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
797
+
798
+ def __iter__(self):
799
+ return (
800
+ self._report(n, nbr, dd)
801
+ for n, nbrs in self._nodes_nbrs()
802
+ for nbr, dd in nbrs.items()
803
+ )
804
+
805
+ def __contains__(self, e):
806
+ u, v = e[:2]
807
+ if self._nbunch is not None and u not in self._nbunch:
808
+ return False # this edge doesn't start in nbunch
809
+ try:
810
+ ddict = self._adjdict[u][v]
811
+ except KeyError:
812
+ return False
813
+ return e == self._report(u, v, ddict)
814
+
815
+ def __str__(self):
816
+ return str(list(self))
817
+
818
+ def __repr__(self):
819
+ return f"{self.__class__.__name__}({list(self)})"
820
+
821
+
822
+ class EdgeDataView(OutEdgeDataView):
823
+ """A EdgeDataView class for edges of Graph
824
+
825
+ This view is primarily used to iterate over the edges reporting
826
+ edges as node-tuples with edge data optionally reported. The
827
+ argument `nbunch` allows restriction to edges incident to nodes
828
+ in that container/singleton. The default (nbunch=None)
829
+ reports all edges. The arguments `data` and `default` control
830
+ what edge data is reported. The default `data is False` reports
831
+ only node-tuples for each edge. If `data is True` the entire edge
832
+ data dict is returned. Otherwise `data` is assumed to hold the name
833
+ of the edge attribute to report with default `default` if that
834
+ edge attribute is not present.
835
+
836
+ Parameters
837
+ ----------
838
+ nbunch : container of nodes, node or None (default None)
839
+ data : False, True or string (default False)
840
+ default : default value (default None)
841
+
842
+ Examples
843
+ --------
844
+ >>> G = nx.path_graph(3)
845
+ >>> G.add_edge(1, 2, foo="bar")
846
+ >>> list(G.edges(data="foo", default="biz"))
847
+ [(0, 1, 'biz'), (1, 2, 'bar')]
848
+ >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz")
849
+ """
850
+
851
+ __slots__ = ()
852
+
853
+ def __len__(self):
854
+ return sum(1 for e in self)
855
+
856
+ def __iter__(self):
857
+ seen = {}
858
+ for n, nbrs in self._nodes_nbrs():
859
+ for nbr, dd in nbrs.items():
860
+ if nbr not in seen:
861
+ yield self._report(n, nbr, dd)
862
+ seen[n] = 1
863
+ del seen
864
+
865
+ def __contains__(self, e):
866
+ u, v = e[:2]
867
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
868
+ return False # this edge doesn't start and it doesn't end in nbunch
869
+ try:
870
+ ddict = self._adjdict[u][v]
871
+ except KeyError:
872
+ return False
873
+ return e == self._report(u, v, ddict)
874
+
875
+
876
+ class InEdgeDataView(OutEdgeDataView):
877
+ """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView"""
878
+
879
+ __slots__ = ()
880
+
881
+ def __iter__(self):
882
+ return (
883
+ self._report(nbr, n, dd)
884
+ for n, nbrs in self._nodes_nbrs()
885
+ for nbr, dd in nbrs.items()
886
+ )
887
+
888
+ def __contains__(self, e):
889
+ u, v = e[:2]
890
+ if self._nbunch is not None and v not in self._nbunch:
891
+ return False # this edge doesn't end in nbunch
892
+ try:
893
+ ddict = self._adjdict[v][u]
894
+ except KeyError:
895
+ return False
896
+ return e == self._report(u, v, ddict)
897
+
898
+
899
+ class OutMultiEdgeDataView(OutEdgeDataView):
900
+ """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
901
+
902
+ __slots__ = ("keys",)
903
+
904
+ def __getstate__(self):
905
+ return {
906
+ "viewer": self._viewer,
907
+ "nbunch": self._nbunch,
908
+ "keys": self.keys,
909
+ "data": self._data,
910
+ "default": self._default,
911
+ }
912
+
913
+ def __setstate__(self, state):
914
+ self.__init__(**state)
915
+
916
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None, keys=False):
917
+ self._viewer = viewer
918
+ adjdict = self._adjdict = viewer._adjdict
919
+ self.keys = keys
920
+ if nbunch is None:
921
+ self._nodes_nbrs = adjdict.items
922
+ else:
923
+ # dict retains order of nodes but acts like a set
924
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
925
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
926
+ self._nbunch = nbunch
927
+ self._data = data
928
+ self._default = default
929
+ # Set _report based on data and default
930
+ if data is True:
931
+ if keys is True:
932
+ self._report = lambda n, nbr, k, dd: (n, nbr, k, dd)
933
+ else:
934
+ self._report = lambda n, nbr, k, dd: (n, nbr, dd)
935
+ elif data is False:
936
+ if keys is True:
937
+ self._report = lambda n, nbr, k, dd: (n, nbr, k)
938
+ else:
939
+ self._report = lambda n, nbr, k, dd: (n, nbr)
940
+ else: # data is attribute name
941
+ if keys is True:
942
+ self._report = (
943
+ lambda n, nbr, k, dd: (n, nbr, k, dd[data])
944
+ if data in dd
945
+ else (n, nbr, k, default)
946
+ )
947
+ else:
948
+ self._report = (
949
+ lambda n, nbr, k, dd: (n, nbr, dd[data])
950
+ if data in dd
951
+ else (n, nbr, default)
952
+ )
953
+
954
+ def __len__(self):
955
+ return sum(1 for e in self)
956
+
957
+ def __iter__(self):
958
+ return (
959
+ self._report(n, nbr, k, dd)
960
+ for n, nbrs in self._nodes_nbrs()
961
+ for nbr, kd in nbrs.items()
962
+ for k, dd in kd.items()
963
+ )
964
+
965
+ def __contains__(self, e):
966
+ u, v = e[:2]
967
+ if self._nbunch is not None and u not in self._nbunch:
968
+ return False # this edge doesn't start in nbunch
969
+ try:
970
+ kdict = self._adjdict[u][v]
971
+ except KeyError:
972
+ return False
973
+ if self.keys is True:
974
+ k = e[2]
975
+ try:
976
+ dd = kdict[k]
977
+ except KeyError:
978
+ return False
979
+ return e == self._report(u, v, k, dd)
980
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
981
+
982
+
983
+ class MultiEdgeDataView(OutMultiEdgeDataView):
984
+ """An EdgeDataView class for edges of MultiGraph; See EdgeDataView"""
985
+
986
+ __slots__ = ()
987
+
988
+ def __iter__(self):
989
+ seen = {}
990
+ for n, nbrs in self._nodes_nbrs():
991
+ for nbr, kd in nbrs.items():
992
+ if nbr not in seen:
993
+ for k, dd in kd.items():
994
+ yield self._report(n, nbr, k, dd)
995
+ seen[n] = 1
996
+ del seen
997
+
998
+ def __contains__(self, e):
999
+ u, v = e[:2]
1000
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
1001
+ return False # this edge doesn't start and doesn't end in nbunch
1002
+ try:
1003
+ kdict = self._adjdict[u][v]
1004
+ except KeyError:
1005
+ try:
1006
+ kdict = self._adjdict[v][u]
1007
+ except KeyError:
1008
+ return False
1009
+ if self.keys is True:
1010
+ k = e[2]
1011
+ try:
1012
+ dd = kdict[k]
1013
+ except KeyError:
1014
+ return False
1015
+ return e == self._report(u, v, k, dd)
1016
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1017
+
1018
+
1019
+ class InMultiEdgeDataView(OutMultiEdgeDataView):
1020
+ """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView"""
1021
+
1022
+ __slots__ = ()
1023
+
1024
+ def __iter__(self):
1025
+ return (
1026
+ self._report(nbr, n, k, dd)
1027
+ for n, nbrs in self._nodes_nbrs()
1028
+ for nbr, kd in nbrs.items()
1029
+ for k, dd in kd.items()
1030
+ )
1031
+
1032
+ def __contains__(self, e):
1033
+ u, v = e[:2]
1034
+ if self._nbunch is not None and v not in self._nbunch:
1035
+ return False # this edge doesn't end in nbunch
1036
+ try:
1037
+ kdict = self._adjdict[v][u]
1038
+ except KeyError:
1039
+ return False
1040
+ if self.keys is True:
1041
+ k = e[2]
1042
+ dd = kdict[k]
1043
+ return e == self._report(u, v, k, dd)
1044
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1045
+
1046
+
1047
+ # EdgeViews have set operations and no data reported
1048
+ class OutEdgeView(Set, Mapping, EdgeViewABC):
1049
+ """A EdgeView class for outward edges of a DiGraph"""
1050
+
1051
+ __slots__ = ("_adjdict", "_graph", "_nodes_nbrs")
1052
+
1053
+ def __getstate__(self):
1054
+ return {"_graph": self._graph, "_adjdict": self._adjdict}
1055
+
1056
+ def __setstate__(self, state):
1057
+ self._graph = state["_graph"]
1058
+ self._adjdict = state["_adjdict"]
1059
+ self._nodes_nbrs = self._adjdict.items
1060
+
1061
+ @classmethod
1062
+ def _from_iterable(cls, it):
1063
+ return set(it)
1064
+
1065
+ dataview = OutEdgeDataView
1066
+
1067
+ def __init__(self, G):
1068
+ self._graph = G
1069
+ self._adjdict = G._succ if hasattr(G, "succ") else G._adj
1070
+ self._nodes_nbrs = self._adjdict.items
1071
+
1072
+ # Set methods
1073
+ def __len__(self):
1074
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
1075
+
1076
+ def __iter__(self):
1077
+ for n, nbrs in self._nodes_nbrs():
1078
+ for nbr in nbrs:
1079
+ yield (n, nbr)
1080
+
1081
+ def __contains__(self, e):
1082
+ try:
1083
+ u, v = e
1084
+ return v in self._adjdict[u]
1085
+ except KeyError:
1086
+ return False
1087
+
1088
+ # Mapping Methods
1089
+ def __getitem__(self, e):
1090
+ if isinstance(e, slice):
1091
+ raise nx.NetworkXError(
1092
+ f"{type(self).__name__} does not support slicing, "
1093
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1094
+ )
1095
+ u, v = e
1096
+ try:
1097
+ return self._adjdict[u][v]
1098
+ except KeyError as ex: # Customize msg to indicate exception origin
1099
+ raise KeyError(f"The edge {e} is not in the graph.")
1100
+
1101
+ # EdgeDataView methods
1102
+ def __call__(self, nbunch=None, data=False, *, default=None):
1103
+ if nbunch is None and data is False:
1104
+ return self
1105
+ return self.dataview(self, nbunch, data, default=default)
1106
+
1107
+ def data(self, data=True, default=None, nbunch=None):
1108
+ """
1109
+ Return a read-only view of edge data.
1110
+
1111
+ Parameters
1112
+ ----------
1113
+ data : bool or edge attribute key
1114
+ If ``data=True``, then the data view maps each edge to a dictionary
1115
+ containing all of its attributes. If `data` is a key in the edge
1116
+ dictionary, then the data view maps each edge to its value for
1117
+ the keyed attribute. In this case, if the edge doesn't have the
1118
+ attribute, the `default` value is returned.
1119
+ default : object, default=None
1120
+ The value used when an edge does not have a specific attribute
1121
+ nbunch : container of nodes, optional (default=None)
1122
+ Allows restriction to edges only involving certain nodes. All edges
1123
+ are considered by default.
1124
+
1125
+ Returns
1126
+ -------
1127
+ dataview
1128
+ Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView`
1129
+ for DiGraphs, `MultiEdgeDataView` for MultiGraphs and
1130
+ `OutMultiEdgeDataView` for MultiDiGraphs.
1131
+
1132
+ Notes
1133
+ -----
1134
+ If ``data=False``, returns an `EdgeView` without any edge data.
1135
+
1136
+ See Also
1137
+ --------
1138
+ EdgeDataView
1139
+ OutEdgeDataView
1140
+ MultiEdgeDataView
1141
+ OutMultiEdgeDataView
1142
+
1143
+ Examples
1144
+ --------
1145
+ >>> G = nx.Graph()
1146
+ >>> G.add_edges_from(
1147
+ ... [
1148
+ ... (0, 1, {"dist": 3, "capacity": 20}),
1149
+ ... (1, 2, {"dist": 4}),
1150
+ ... (2, 0, {"dist": 5}),
1151
+ ... ]
1152
+ ... )
1153
+
1154
+ Accessing edge data with ``data=True`` (the default) returns an
1155
+ edge data view object listing each edge with all of its attributes:
1156
+
1157
+ >>> G.edges.data()
1158
+ EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})])
1159
+
1160
+ If `data` represents a key in the edge attribute dict, a dataview listing
1161
+ each edge with its value for that specific key is returned:
1162
+
1163
+ >>> G.edges.data("dist")
1164
+ EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)])
1165
+
1166
+ `nbunch` can be used to limit the edges:
1167
+
1168
+ >>> G.edges.data("dist", nbunch=[0])
1169
+ EdgeDataView([(0, 1, 3), (0, 2, 5)])
1170
+
1171
+ If a specific key is not found in an edge attribute dict, the value
1172
+ specified by `default` is used:
1173
+
1174
+ >>> G.edges.data("capacity")
1175
+ EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)])
1176
+
1177
+ Note that there is no check that the `data` key is present in any of
1178
+ the edge attribute dictionaries:
1179
+
1180
+ >>> G.edges.data("speed")
1181
+ EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)])
1182
+ """
1183
+ if nbunch is None and data is False:
1184
+ return self
1185
+ return self.dataview(self, nbunch, data, default=default)
1186
+
1187
+ # String Methods
1188
+ def __str__(self):
1189
+ return str(list(self))
1190
+
1191
+ def __repr__(self):
1192
+ return f"{self.__class__.__name__}({list(self)})"
1193
+
1194
+
1195
+ class EdgeView(OutEdgeView):
1196
+ """A EdgeView class for edges of a Graph
1197
+
1198
+ This densely packed View allows iteration over edges, data lookup
1199
+ like a dict and set operations on edges represented by node-tuples.
1200
+ In addition, edge data can be controlled by calling this object
1201
+ possibly creating an EdgeDataView. Typically edges are iterated over
1202
+ and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples
1203
+ for multigraphs. Those edge representations can also be using to
1204
+ lookup the data dict for any edge. Set operations also are available
1205
+ where those tuples are the elements of the set.
1206
+ Calling this object with optional arguments `data`, `default` and `keys`
1207
+ controls the form of the tuple (see EdgeDataView). Optional argument
1208
+ `nbunch` allows restriction to edges only involving certain nodes.
1209
+
1210
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
1211
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
1212
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
1213
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above.
1214
+
1215
+ Parameters
1216
+ ==========
1217
+ graph : NetworkX graph-like class
1218
+ nbunch : (default= all nodes in graph) only report edges with these nodes
1219
+ keys : (only for MultiGraph. default=False) report edge key in tuple
1220
+ data : bool or string (default=False) see above
1221
+ default : object (default=None)
1222
+
1223
+ Examples
1224
+ ========
1225
+ >>> G = nx.path_graph(4)
1226
+ >>> EV = G.edges()
1227
+ >>> (2, 3) in EV
1228
+ True
1229
+ >>> for u, v in EV:
1230
+ ... print((u, v))
1231
+ (0, 1)
1232
+ (1, 2)
1233
+ (2, 3)
1234
+ >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)}
1235
+
1236
+ >>> EVdata = G.edges(data="color", default="aqua")
1237
+ >>> G.add_edge(2, 3, color="blue")
1238
+ >>> assert (2, 3, "blue") in EVdata
1239
+ >>> for u, v, c in EVdata:
1240
+ ... print(f"({u}, {v}) has color: {c}")
1241
+ (0, 1) has color: aqua
1242
+ (1, 2) has color: aqua
1243
+ (2, 3) has color: blue
1244
+
1245
+ >>> EVnbunch = G.edges(nbunch=2)
1246
+ >>> assert (2, 3) in EVnbunch
1247
+ >>> assert (0, 1) not in EVnbunch
1248
+ >>> for u, v in EVnbunch:
1249
+ ... assert u == 2 or v == 2
1250
+
1251
+ >>> MG = nx.path_graph(4, create_using=nx.MultiGraph)
1252
+ >>> EVmulti = MG.edges(keys=True)
1253
+ >>> (2, 3, 0) in EVmulti
1254
+ True
1255
+ >>> (2, 3) in EVmulti # 2-tuples work even when keys is True
1256
+ True
1257
+ >>> key = MG.add_edge(2, 3)
1258
+ >>> for u, v, k in EVmulti:
1259
+ ... print((u, v, k))
1260
+ (0, 1, 0)
1261
+ (1, 2, 0)
1262
+ (2, 3, 0)
1263
+ (2, 3, 1)
1264
+ """
1265
+
1266
+ __slots__ = ()
1267
+
1268
+ dataview = EdgeDataView
1269
+
1270
+ def __len__(self):
1271
+ num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs())
1272
+ return sum(num_nbrs) // 2
1273
+
1274
+ def __iter__(self):
1275
+ seen = {}
1276
+ for n, nbrs in self._nodes_nbrs():
1277
+ for nbr in list(nbrs):
1278
+ if nbr not in seen:
1279
+ yield (n, nbr)
1280
+ seen[n] = 1
1281
+ del seen
1282
+
1283
+ def __contains__(self, e):
1284
+ try:
1285
+ u, v = e[:2]
1286
+ return v in self._adjdict[u] or u in self._adjdict[v]
1287
+ except (KeyError, ValueError):
1288
+ return False
1289
+
1290
+
1291
+ class InEdgeView(OutEdgeView):
1292
+ """A EdgeView class for inward edges of a DiGraph"""
1293
+
1294
+ __slots__ = ()
1295
+
1296
+ def __setstate__(self, state):
1297
+ self._graph = state["_graph"]
1298
+ self._adjdict = state["_adjdict"]
1299
+ self._nodes_nbrs = self._adjdict.items
1300
+
1301
+ dataview = InEdgeDataView
1302
+
1303
+ def __init__(self, G):
1304
+ self._graph = G
1305
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1306
+ self._nodes_nbrs = self._adjdict.items
1307
+
1308
+ def __iter__(self):
1309
+ for n, nbrs in self._nodes_nbrs():
1310
+ for nbr in nbrs:
1311
+ yield (nbr, n)
1312
+
1313
+ def __contains__(self, e):
1314
+ try:
1315
+ u, v = e
1316
+ return u in self._adjdict[v]
1317
+ except KeyError:
1318
+ return False
1319
+
1320
+ def __getitem__(self, e):
1321
+ if isinstance(e, slice):
1322
+ raise nx.NetworkXError(
1323
+ f"{type(self).__name__} does not support slicing, "
1324
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1325
+ )
1326
+ u, v = e
1327
+ return self._adjdict[v][u]
1328
+
1329
+
1330
+ class OutMultiEdgeView(OutEdgeView):
1331
+ """A EdgeView class for outward edges of a MultiDiGraph"""
1332
+
1333
+ __slots__ = ()
1334
+
1335
+ dataview = OutMultiEdgeDataView
1336
+
1337
+ def __len__(self):
1338
+ return sum(
1339
+ len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items()
1340
+ )
1341
+
1342
+ def __iter__(self):
1343
+ for n, nbrs in self._nodes_nbrs():
1344
+ for nbr, kdict in nbrs.items():
1345
+ for key in kdict:
1346
+ yield (n, nbr, key)
1347
+
1348
+ def __contains__(self, e):
1349
+ N = len(e)
1350
+ if N == 3:
1351
+ u, v, k = e
1352
+ elif N == 2:
1353
+ u, v = e
1354
+ k = 0
1355
+ else:
1356
+ raise ValueError("MultiEdge must have length 2 or 3")
1357
+ try:
1358
+ return k in self._adjdict[u][v]
1359
+ except KeyError:
1360
+ return False
1361
+
1362
+ def __getitem__(self, e):
1363
+ if isinstance(e, slice):
1364
+ raise nx.NetworkXError(
1365
+ f"{type(self).__name__} does not support slicing, "
1366
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1367
+ )
1368
+ u, v, k = e
1369
+ return self._adjdict[u][v][k]
1370
+
1371
+ def __call__(self, nbunch=None, data=False, *, default=None, keys=False):
1372
+ if nbunch is None and data is False and keys is True:
1373
+ return self
1374
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1375
+
1376
+ def data(self, data=True, default=None, nbunch=None, keys=False):
1377
+ if nbunch is None and data is False and keys is True:
1378
+ return self
1379
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1380
+
1381
+
1382
+ class MultiEdgeView(OutMultiEdgeView):
1383
+ """A EdgeView class for edges of a MultiGraph"""
1384
+
1385
+ __slots__ = ()
1386
+
1387
+ dataview = MultiEdgeDataView
1388
+
1389
+ def __len__(self):
1390
+ return sum(1 for e in self)
1391
+
1392
+ def __iter__(self):
1393
+ seen = {}
1394
+ for n, nbrs in self._nodes_nbrs():
1395
+ for nbr, kd in nbrs.items():
1396
+ if nbr not in seen:
1397
+ for k, dd in kd.items():
1398
+ yield (n, nbr, k)
1399
+ seen[n] = 1
1400
+ del seen
1401
+
1402
+
1403
+ class InMultiEdgeView(OutMultiEdgeView):
1404
+ """A EdgeView class for inward edges of a MultiDiGraph"""
1405
+
1406
+ __slots__ = ()
1407
+
1408
+ def __setstate__(self, state):
1409
+ self._graph = state["_graph"]
1410
+ self._adjdict = state["_adjdict"]
1411
+ self._nodes_nbrs = self._adjdict.items
1412
+
1413
+ dataview = InMultiEdgeDataView
1414
+
1415
+ def __init__(self, G):
1416
+ self._graph = G
1417
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1418
+ self._nodes_nbrs = self._adjdict.items
1419
+
1420
+ def __iter__(self):
1421
+ for n, nbrs in self._nodes_nbrs():
1422
+ for nbr, kdict in nbrs.items():
1423
+ for key in kdict:
1424
+ yield (nbr, n, key)
1425
+
1426
+ def __contains__(self, e):
1427
+ N = len(e)
1428
+ if N == 3:
1429
+ u, v, k = e
1430
+ elif N == 2:
1431
+ u, v = e
1432
+ k = 0
1433
+ else:
1434
+ raise ValueError("MultiEdge must have length 2 or 3")
1435
+ try:
1436
+ return k in self._adjdict[v][u]
1437
+ except KeyError:
1438
+ return False
1439
+
1440
+ def __getitem__(self, e):
1441
+ if isinstance(e, slice):
1442
+ raise nx.NetworkXError(
1443
+ f"{type(self).__name__} does not support slicing, "
1444
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1445
+ )
1446
+ u, v, k = e
1447
+ return self._adjdict[v][u][k]
deepseek/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains utilities for testing the dispatching feature
2
+
3
+ # A full test of all dispatchable algorithms is performed by
4
+ # modifying the pytest invocation and setting an environment variable
5
+ # NETWORKX_TEST_BACKEND=nx_loopback pytest
6
+ # This is comprehensive, but only tests the `test_override_dispatch`
7
+ # function in networkx.classes.backends.
8
+
9
+ # To test the `_dispatchable` function directly, several tests scattered throughout
10
+ # NetworkX have been augmented to test normal and dispatch mode.
11
+ # Searching for `dispatch_interface` should locate the specific tests.
12
+
13
+ import networkx as nx
14
+ from networkx import DiGraph, Graph, MultiDiGraph, MultiGraph, PlanarEmbedding
15
+ from networkx.classes.reportviews import NodeView
16
+
17
+
18
+ class LoopbackGraph(Graph):
19
+ __networkx_backend__ = "nx_loopback"
20
+
21
+
22
+ class LoopbackDiGraph(DiGraph):
23
+ __networkx_backend__ = "nx_loopback"
24
+
25
+
26
+ class LoopbackMultiGraph(MultiGraph):
27
+ __networkx_backend__ = "nx_loopback"
28
+
29
+
30
+ class LoopbackMultiDiGraph(MultiDiGraph):
31
+ __networkx_backend__ = "nx_loopback"
32
+
33
+
34
+ class LoopbackPlanarEmbedding(PlanarEmbedding):
35
+ __networkx_backend__ = "nx_loopback"
36
+
37
+
38
+ def convert(graph):
39
+ if isinstance(graph, PlanarEmbedding):
40
+ return LoopbackPlanarEmbedding(graph)
41
+ if isinstance(graph, MultiDiGraph):
42
+ return LoopbackMultiDiGraph(graph)
43
+ if isinstance(graph, MultiGraph):
44
+ return LoopbackMultiGraph(graph)
45
+ if isinstance(graph, DiGraph):
46
+ return LoopbackDiGraph(graph)
47
+ if isinstance(graph, Graph):
48
+ return LoopbackGraph(graph)
49
+ raise TypeError(f"Unsupported type of graph: {type(graph)}")
50
+
51
+
52
+ class LoopbackBackendInterface:
53
+ def __getattr__(self, item):
54
+ try:
55
+ return nx.utils.backends._registered_algorithms[item].orig_func
56
+ except KeyError:
57
+ raise AttributeError(item) from None
58
+
59
+ @staticmethod
60
+ def convert_from_nx(
61
+ graph,
62
+ *,
63
+ edge_attrs=None,
64
+ node_attrs=None,
65
+ preserve_edge_attrs=None,
66
+ preserve_node_attrs=None,
67
+ preserve_graph_attrs=None,
68
+ name=None,
69
+ graph_name=None,
70
+ ):
71
+ if name in {
72
+ # Raise if input graph changes. See test_dag.py::test_topological_sort6
73
+ "lexicographical_topological_sort",
74
+ "topological_generations",
75
+ "topological_sort",
76
+ # Would be nice to some day avoid these cutoffs of full testing
77
+ }:
78
+ return graph
79
+ if isinstance(graph, NodeView):
80
+ # Convert to a Graph with only nodes (no edges)
81
+ new_graph = Graph()
82
+ new_graph.add_nodes_from(graph.items())
83
+ graph = new_graph
84
+ G = LoopbackGraph()
85
+ elif not isinstance(graph, Graph):
86
+ raise TypeError(
87
+ f"Bad type for graph argument {graph_name} in {name}: {type(graph)}"
88
+ )
89
+ elif graph.__class__ in {Graph, LoopbackGraph}:
90
+ G = LoopbackGraph()
91
+ elif graph.__class__ in {DiGraph, LoopbackDiGraph}:
92
+ G = LoopbackDiGraph()
93
+ elif graph.__class__ in {MultiGraph, LoopbackMultiGraph}:
94
+ G = LoopbackMultiGraph()
95
+ elif graph.__class__ in {MultiDiGraph, LoopbackMultiDiGraph}:
96
+ G = LoopbackMultiDiGraph()
97
+ elif graph.__class__ in {PlanarEmbedding, LoopbackPlanarEmbedding}:
98
+ G = LoopbackDiGraph() # or LoopbackPlanarEmbedding
99
+ else:
100
+ # Would be nice to handle these better some day
101
+ # nx.algorithms.approximation.kcomponents._AntiGraph
102
+ # nx.classes.tests.test_multidigraph.MultiDiGraphSubClass
103
+ # nx.classes.tests.test_multigraph.MultiGraphSubClass
104
+ G = graph.__class__()
105
+
106
+ if preserve_graph_attrs:
107
+ G.graph.update(graph.graph)
108
+
109
+ # add nodes
110
+ G.add_nodes_from(graph)
111
+ if preserve_node_attrs:
112
+ for n, dd in G._node.items():
113
+ dd.update(graph.nodes[n])
114
+ elif node_attrs:
115
+ for n, dd in G._node.items():
116
+ dd.update(
117
+ (attr, graph._node[n].get(attr, default))
118
+ for attr, default in node_attrs.items()
119
+ if default is not None or attr in graph._node[n]
120
+ )
121
+
122
+ # tools to build datadict and keydict
123
+ if preserve_edge_attrs:
124
+
125
+ def G_new_datadict(old_dd):
126
+ return G.edge_attr_dict_factory(old_dd)
127
+ elif edge_attrs:
128
+
129
+ def G_new_datadict(old_dd):
130
+ return G.edge_attr_dict_factory(
131
+ (attr, old_dd.get(attr, default))
132
+ for attr, default in edge_attrs.items()
133
+ if default is not None or attr in old_dd
134
+ )
135
+ else:
136
+
137
+ def G_new_datadict(old_dd):
138
+ return G.edge_attr_dict_factory()
139
+
140
+ if G.is_multigraph():
141
+
142
+ def G_new_inner(keydict):
143
+ kd = G.adjlist_inner_dict_factory(
144
+ (k, G_new_datadict(dd)) for k, dd in keydict.items()
145
+ )
146
+ return kd
147
+ else:
148
+ G_new_inner = G_new_datadict
149
+
150
+ # add edges keeping the same order in _adj and _pred
151
+ G_adj = G._adj
152
+ if G.is_directed():
153
+ for n, nbrs in graph._adj.items():
154
+ G_adj[n].update((nbr, G_new_inner(dd)) for nbr, dd in nbrs.items())
155
+ # ensure same datadict for pred and adj; and pred order of graph._pred
156
+ G_pred = G._pred
157
+ for n, nbrs in graph._pred.items():
158
+ G_pred[n].update((nbr, G_adj[nbr][n]) for nbr in nbrs)
159
+ else: # undirected
160
+ for n, nbrs in graph._adj.items():
161
+ # ensure same datadict for both ways; and adj order of graph._adj
162
+ G_adj[n].update(
163
+ (nbr, G_adj[nbr][n] if n in G_adj[nbr] else G_new_inner(dd))
164
+ for nbr, dd in nbrs.items()
165
+ )
166
+
167
+ return G
168
+
169
+ @staticmethod
170
+ def convert_to_nx(obj, *, name=None):
171
+ return obj
172
+
173
+ @staticmethod
174
+ def on_start_tests(items):
175
+ # Verify that items can be xfailed
176
+ for item in items:
177
+ assert hasattr(item, "add_marker")
178
+
179
+ def can_run(self, name, args, kwargs):
180
+ # It is unnecessary to define this function if algorithms are fully supported.
181
+ # We include it for illustration purposes.
182
+ return hasattr(self, name)
183
+
184
+
185
+ backend_interface = LoopbackBackendInterface()
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_graphviews.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal, nodes_equal
5
+
6
+ # Note: SubGraph views are not tested here. They have their own testing file
7
+
8
+
9
+ class TestReverseView:
10
+ def setup_method(self):
11
+ self.G = nx.path_graph(9, create_using=nx.DiGraph())
12
+ self.rv = nx.reverse_view(self.G)
13
+
14
+ def test_pickle(self):
15
+ import pickle
16
+
17
+ rv = self.rv
18
+ prv = pickle.loads(pickle.dumps(rv, -1))
19
+ assert rv._node == prv._node
20
+ assert rv._adj == prv._adj
21
+ assert rv.graph == prv.graph
22
+
23
+ def test_contains(self):
24
+ assert (2, 3) in self.G.edges
25
+ assert (3, 2) not in self.G.edges
26
+ assert (2, 3) not in self.rv.edges
27
+ assert (3, 2) in self.rv.edges
28
+
29
+ def test_iter(self):
30
+ expected = sorted(tuple(reversed(e)) for e in self.G.edges)
31
+ assert sorted(self.rv.edges) == expected
32
+
33
+ def test_exceptions(self):
34
+ G = nx.Graph()
35
+ pytest.raises(nx.NetworkXNotImplemented, nx.reverse_view, G)
36
+
37
+ def test_subclass(self):
38
+ class MyGraph(nx.DiGraph):
39
+ def my_method(self):
40
+ return "me"
41
+
42
+ def to_directed_class(self):
43
+ return MyGraph()
44
+
45
+ M = MyGraph()
46
+ M.add_edge(1, 2)
47
+ RM = nx.reverse_view(M)
48
+ print("RM class", RM.__class__)
49
+ RMC = RM.copy()
50
+ print("RMC class", RMC.__class__)
51
+ print(RMC.edges)
52
+ assert RMC.has_edge(2, 1)
53
+ assert RMC.my_method() == "me"
54
+
55
+
56
+ class TestMultiReverseView:
57
+ def setup_method(self):
58
+ self.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
59
+ self.G.add_edge(4, 5)
60
+ self.rv = nx.reverse_view(self.G)
61
+
62
+ def test_pickle(self):
63
+ import pickle
64
+
65
+ rv = self.rv
66
+ prv = pickle.loads(pickle.dumps(rv, -1))
67
+ assert rv._node == prv._node
68
+ assert rv._adj == prv._adj
69
+ assert rv.graph == prv.graph
70
+
71
+ def test_contains(self):
72
+ assert (2, 3, 0) in self.G.edges
73
+ assert (3, 2, 0) not in self.G.edges
74
+ assert (2, 3, 0) not in self.rv.edges
75
+ assert (3, 2, 0) in self.rv.edges
76
+ assert (5, 4, 1) in self.rv.edges
77
+ assert (4, 5, 1) not in self.rv.edges
78
+
79
+ def test_iter(self):
80
+ expected = sorted((v, u, k) for u, v, k in self.G.edges)
81
+ assert sorted(self.rv.edges) == expected
82
+
83
+ def test_exceptions(self):
84
+ MG = nx.MultiGraph(self.G)
85
+ pytest.raises(nx.NetworkXNotImplemented, nx.reverse_view, MG)
86
+
87
+
88
+ def test_generic_multitype():
89
+ nxg = nx.graphviews
90
+ G = nx.DiGraph([(1, 2)])
91
+ with pytest.raises(nx.NetworkXError):
92
+ nxg.generic_graph_view(G, create_using=nx.MultiGraph)
93
+ G = nx.MultiDiGraph([(1, 2)])
94
+ with pytest.raises(nx.NetworkXError):
95
+ nxg.generic_graph_view(G, create_using=nx.DiGraph)
96
+
97
+
98
+ class TestToDirected:
99
+ def setup_method(self):
100
+ self.G = nx.path_graph(9)
101
+ self.dv = nx.to_directed(self.G)
102
+ self.MG = nx.path_graph(9, create_using=nx.MultiGraph())
103
+ self.Mdv = nx.to_directed(self.MG)
104
+
105
+ def test_directed(self):
106
+ assert not self.G.is_directed()
107
+ assert self.dv.is_directed()
108
+
109
+ def test_already_directed(self):
110
+ dd = nx.to_directed(self.dv)
111
+ Mdd = nx.to_directed(self.Mdv)
112
+ assert edges_equal(dd.edges, self.dv.edges)
113
+ assert edges_equal(Mdd.edges, self.Mdv.edges)
114
+
115
+ def test_pickle(self):
116
+ import pickle
117
+
118
+ dv = self.dv
119
+ pdv = pickle.loads(pickle.dumps(dv, -1))
120
+ assert dv._node == pdv._node
121
+ assert dv._succ == pdv._succ
122
+ assert dv._pred == pdv._pred
123
+ assert dv.graph == pdv.graph
124
+
125
+ def test_contains(self):
126
+ assert (2, 3) in self.G.edges
127
+ assert (3, 2) in self.G.edges
128
+ assert (2, 3) in self.dv.edges
129
+ assert (3, 2) in self.dv.edges
130
+
131
+ def test_iter(self):
132
+ revd = [tuple(reversed(e)) for e in self.G.edges]
133
+ expected = sorted(list(self.G.edges) + revd)
134
+ assert sorted(self.dv.edges) == expected
135
+
136
+
137
+ class TestToUndirected:
138
+ def setup_method(self):
139
+ self.DG = nx.path_graph(9, create_using=nx.DiGraph())
140
+ self.uv = nx.to_undirected(self.DG)
141
+ self.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph())
142
+ self.Muv = nx.to_undirected(self.MDG)
143
+
144
+ def test_directed(self):
145
+ assert self.DG.is_directed()
146
+ assert not self.uv.is_directed()
147
+
148
+ def test_already_directed(self):
149
+ uu = nx.to_undirected(self.uv)
150
+ Muu = nx.to_undirected(self.Muv)
151
+ assert edges_equal(uu.edges, self.uv.edges)
152
+ assert edges_equal(Muu.edges, self.Muv.edges)
153
+
154
+ def test_pickle(self):
155
+ import pickle
156
+
157
+ uv = self.uv
158
+ puv = pickle.loads(pickle.dumps(uv, -1))
159
+ assert uv._node == puv._node
160
+ assert uv._adj == puv._adj
161
+ assert uv.graph == puv.graph
162
+ assert hasattr(uv, "_graph")
163
+
164
+ def test_contains(self):
165
+ assert (2, 3) in self.DG.edges
166
+ assert (3, 2) not in self.DG.edges
167
+ assert (2, 3) in self.uv.edges
168
+ assert (3, 2) in self.uv.edges
169
+
170
+ def test_iter(self):
171
+ expected = sorted(self.DG.edges)
172
+ assert sorted(self.uv.edges) == expected
173
+
174
+
175
+ class TestChainsOfViews:
176
+ @classmethod
177
+ def setup_class(cls):
178
+ cls.G = nx.path_graph(9)
179
+ cls.DG = nx.path_graph(9, create_using=nx.DiGraph())
180
+ cls.MG = nx.path_graph(9, create_using=nx.MultiGraph())
181
+ cls.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph())
182
+ cls.Gv = nx.to_undirected(cls.DG)
183
+ cls.DGv = nx.to_directed(cls.G)
184
+ cls.MGv = nx.to_undirected(cls.MDG)
185
+ cls.MDGv = nx.to_directed(cls.MG)
186
+ cls.Rv = cls.DG.reverse()
187
+ cls.MRv = cls.MDG.reverse()
188
+ cls.graphs = [
189
+ cls.G,
190
+ cls.DG,
191
+ cls.MG,
192
+ cls.MDG,
193
+ cls.Gv,
194
+ cls.DGv,
195
+ cls.MGv,
196
+ cls.MDGv,
197
+ cls.Rv,
198
+ cls.MRv,
199
+ ]
200
+ for G in cls.graphs:
201
+ G.edges, G.nodes, G.degree
202
+
203
+ def test_pickle(self):
204
+ import pickle
205
+
206
+ for G in self.graphs:
207
+ H = pickle.loads(pickle.dumps(G, -1))
208
+ assert edges_equal(H.edges, G.edges)
209
+ assert nodes_equal(H.nodes, G.nodes)
210
+
211
+ def test_subgraph_of_subgraph(self):
212
+ SGv = nx.subgraph(self.G, range(3, 7))
213
+ SDGv = nx.subgraph(self.DG, range(3, 7))
214
+ SMGv = nx.subgraph(self.MG, range(3, 7))
215
+ SMDGv = nx.subgraph(self.MDG, range(3, 7))
216
+ for G in self.graphs + [SGv, SDGv, SMGv, SMDGv]:
217
+ SG = nx.induced_subgraph(G, [4, 5, 6])
218
+ assert list(SG) == [4, 5, 6]
219
+ SSG = SG.subgraph([6, 7])
220
+ assert list(SSG) == [6]
221
+ # subgraph-subgraph chain is short-cut in base class method
222
+ assert SSG._graph is G
223
+
224
+ def test_restricted_induced_subgraph_chains(self):
225
+ """Test subgraph chains that both restrict and show nodes/edges.
226
+
227
+ A restricted_view subgraph should allow induced subgraphs using
228
+ G.subgraph that automagically without a chain (meaning the result
229
+ is a subgraph view of the original graph not a subgraph-of-subgraph.
230
+ """
231
+ hide_nodes = [3, 4, 5]
232
+ hide_edges = [(6, 7)]
233
+ RG = nx.restricted_view(self.G, hide_nodes, hide_edges)
234
+ nodes = [4, 5, 6, 7, 8]
235
+ SG = nx.induced_subgraph(RG, nodes)
236
+ SSG = RG.subgraph(nodes)
237
+ assert RG._graph is self.G
238
+ assert SSG._graph is self.G
239
+ assert SG._graph is RG
240
+ assert edges_equal(SG.edges, SSG.edges)
241
+ # should be same as morphing the graph
242
+ CG = self.G.copy()
243
+ CG.remove_nodes_from(hide_nodes)
244
+ CG.remove_edges_from(hide_edges)
245
+ assert edges_equal(CG.edges(nodes), SSG.edges)
246
+ CG.remove_nodes_from([0, 1, 2, 3])
247
+ assert edges_equal(CG.edges, SSG.edges)
248
+ # switch order: subgraph first, then restricted view
249
+ SSSG = self.G.subgraph(nodes)
250
+ RSG = nx.restricted_view(SSSG, hide_nodes, hide_edges)
251
+ assert RSG._graph is not self.G
252
+ assert edges_equal(RSG.edges, CG.edges)
253
+
254
+ def test_subgraph_copy(self):
255
+ for origG in self.graphs:
256
+ G = nx.Graph(origG)
257
+ SG = G.subgraph([4, 5, 6])
258
+ H = SG.copy()
259
+ assert type(G) == type(H)
260
+
261
+ def test_subgraph_todirected(self):
262
+ SG = nx.induced_subgraph(self.G, [4, 5, 6])
263
+ SSG = SG.to_directed()
264
+ assert sorted(SSG) == [4, 5, 6]
265
+ assert sorted(SSG.edges) == [(4, 5), (5, 4), (5, 6), (6, 5)]
266
+
267
+ def test_subgraph_toundirected(self):
268
+ SG = nx.induced_subgraph(self.G, [4, 5, 6])
269
+ SSG = SG.to_undirected()
270
+ assert list(SSG) == [4, 5, 6]
271
+ assert sorted(SSG.edges) == [(4, 5), (5, 6)]
272
+
273
+ def test_reverse_subgraph_toundirected(self):
274
+ G = self.DG.reverse(copy=False)
275
+ SG = G.subgraph([4, 5, 6])
276
+ SSG = SG.to_undirected()
277
+ assert list(SSG) == [4, 5, 6]
278
+ assert sorted(SSG.edges) == [(4, 5), (5, 6)]
279
+
280
+ def test_reverse_reverse_copy(self):
281
+ G = self.DG.reverse(copy=False)
282
+ H = G.reverse(copy=True)
283
+ assert H.nodes == self.DG.nodes
284
+ assert H.edges == self.DG.edges
285
+ G = self.MDG.reverse(copy=False)
286
+ H = G.reverse(copy=True)
287
+ assert H.nodes == self.MDG.nodes
288
+ assert H.edges == self.MDG.edges
289
+
290
+ def test_subgraph_edgesubgraph_toundirected(self):
291
+ G = self.G.copy()
292
+ SG = G.subgraph([4, 5, 6])
293
+ SSG = SG.edge_subgraph([(4, 5), (5, 4)])
294
+ USSG = SSG.to_undirected()
295
+ assert list(USSG) == [4, 5]
296
+ assert sorted(USSG.edges) == [(4, 5)]
297
+
298
+ def test_copy_subgraph(self):
299
+ G = self.G.copy()
300
+ SG = G.subgraph([4, 5, 6])
301
+ CSG = SG.copy(as_view=True)
302
+ DCSG = SG.copy(as_view=False)
303
+ assert hasattr(CSG, "_graph") # is a view
304
+ assert not hasattr(DCSG, "_graph") # not a view
305
+
306
+ def test_copy_disubgraph(self):
307
+ G = self.DG.copy()
308
+ SG = G.subgraph([4, 5, 6])
309
+ CSG = SG.copy(as_view=True)
310
+ DCSG = SG.copy(as_view=False)
311
+ assert hasattr(CSG, "_graph") # is a view
312
+ assert not hasattr(DCSG, "_graph") # not a view
313
+
314
+ def test_copy_multidisubgraph(self):
315
+ G = self.MDG.copy()
316
+ SG = G.subgraph([4, 5, 6])
317
+ CSG = SG.copy(as_view=True)
318
+ DCSG = SG.copy(as_view=False)
319
+ assert hasattr(CSG, "_graph") # is a view
320
+ assert not hasattr(DCSG, "_graph") # not a view
321
+
322
+ def test_copy_multisubgraph(self):
323
+ G = self.MG.copy()
324
+ SG = G.subgraph([4, 5, 6])
325
+ CSG = SG.copy(as_view=True)
326
+ DCSG = SG.copy(as_view=False)
327
+ assert hasattr(CSG, "_graph") # is a view
328
+ assert not hasattr(DCSG, "_graph") # not a view
329
+
330
+ def test_copy_of_view(self):
331
+ G = nx.MultiGraph(self.MGv)
332
+ assert G.__class__.__name__ == "MultiGraph"
333
+ G = G.copy(as_view=True)
334
+ assert G.__class__.__name__ == "MultiGraph"
335
+
336
+ def test_subclass(self):
337
+ class MyGraph(nx.DiGraph):
338
+ def my_method(self):
339
+ return "me"
340
+
341
+ def to_directed_class(self):
342
+ return MyGraph()
343
+
344
+ for origG in self.graphs:
345
+ G = MyGraph(origG)
346
+ SG = G.subgraph([4, 5, 6])
347
+ H = SG.copy()
348
+ assert SG.my_method() == "me"
349
+ assert H.my_method() == "me"
350
+ assert 3 not in H or 3 in SG
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_multigraph.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import UserDict
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal
7
+
8
+ from .test_graph import BaseAttrGraphTester
9
+ from .test_graph import TestGraph as _TestGraph
10
+
11
+
12
+ class BaseMultiGraphTester(BaseAttrGraphTester):
13
+ def test_has_edge(self):
14
+ G = self.K3
15
+ assert G.has_edge(0, 1)
16
+ assert not G.has_edge(0, -1)
17
+ assert G.has_edge(0, 1, 0)
18
+ assert not G.has_edge(0, 1, 1)
19
+
20
+ def test_get_edge_data(self):
21
+ G = self.K3
22
+ assert G.get_edge_data(0, 1) == {0: {}}
23
+ assert G[0][1] == {0: {}}
24
+ assert G[0][1][0] == {}
25
+ assert G.get_edge_data(10, 20) is None
26
+ assert G.get_edge_data(0, 1, 0) == {}
27
+
28
+ def test_adjacency(self):
29
+ G = self.K3
30
+ assert dict(G.adjacency()) == {
31
+ 0: {1: {0: {}}, 2: {0: {}}},
32
+ 1: {0: {0: {}}, 2: {0: {}}},
33
+ 2: {0: {0: {}}, 1: {0: {}}},
34
+ }
35
+
36
+ def deepcopy_edge_attr(self, H, G):
37
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
38
+ G[1][2][0]["foo"].append(1)
39
+ assert G[1][2][0]["foo"] != H[1][2][0]["foo"]
40
+
41
+ def shallow_copy_edge_attr(self, H, G):
42
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
43
+ G[1][2][0]["foo"].append(1)
44
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
45
+
46
+ def graphs_equal(self, H, G):
47
+ assert G._adj == H._adj
48
+ assert G._node == H._node
49
+ assert G.graph == H.graph
50
+ assert G.name == H.name
51
+ if not G.is_directed() and not H.is_directed():
52
+ assert H._adj[1][2][0] is H._adj[2][1][0]
53
+ assert G._adj[1][2][0] is G._adj[2][1][0]
54
+ else: # at least one is directed
55
+ if not G.is_directed():
56
+ G._pred = G._adj
57
+ G._succ = G._adj
58
+ if not H.is_directed():
59
+ H._pred = H._adj
60
+ H._succ = H._adj
61
+ assert G._pred == H._pred
62
+ assert G._succ == H._succ
63
+ assert H._succ[1][2][0] is H._pred[2][1][0]
64
+ assert G._succ[1][2][0] is G._pred[2][1][0]
65
+
66
+ def same_attrdict(self, H, G):
67
+ # same attrdict in the edgedata
68
+ old_foo = H[1][2][0]["foo"]
69
+ H.adj[1][2][0]["foo"] = "baz"
70
+ assert G._adj == H._adj
71
+ H.adj[1][2][0]["foo"] = old_foo
72
+ assert G._adj == H._adj
73
+
74
+ old_foo = H.nodes[0]["foo"]
75
+ H.nodes[0]["foo"] = "baz"
76
+ assert G._node == H._node
77
+ H.nodes[0]["foo"] = old_foo
78
+ assert G._node == H._node
79
+
80
+ def different_attrdict(self, H, G):
81
+ # used by graph_equal_but_different
82
+ old_foo = H[1][2][0]["foo"]
83
+ H.adj[1][2][0]["foo"] = "baz"
84
+ assert G._adj != H._adj
85
+ H.adj[1][2][0]["foo"] = old_foo
86
+ assert G._adj == H._adj
87
+
88
+ old_foo = H.nodes[0]["foo"]
89
+ H.nodes[0]["foo"] = "baz"
90
+ assert G._node != H._node
91
+ H.nodes[0]["foo"] = old_foo
92
+ assert G._node == H._node
93
+
94
+ def test_to_undirected(self):
95
+ G = self.K3
96
+ self.add_attributes(G)
97
+ H = nx.MultiGraph(G)
98
+ self.is_shallow_copy(H, G)
99
+ H = G.to_undirected()
100
+ self.is_deepcopy(H, G)
101
+
102
+ def test_to_directed(self):
103
+ G = self.K3
104
+ self.add_attributes(G)
105
+ H = nx.MultiDiGraph(G)
106
+ self.is_shallow_copy(H, G)
107
+ H = G.to_directed()
108
+ self.is_deepcopy(H, G)
109
+
110
+ def test_number_of_edges_selfloops(self):
111
+ G = self.K3
112
+ G.add_edge(0, 0)
113
+ G.add_edge(0, 0)
114
+ G.add_edge(0, 0, key="parallel edge")
115
+ G.remove_edge(0, 0, key="parallel edge")
116
+ assert G.number_of_edges(0, 0) == 2
117
+ G.remove_edge(0, 0)
118
+ assert G.number_of_edges(0, 0) == 1
119
+
120
+ def test_edge_lookup(self):
121
+ G = self.Graph()
122
+ G.add_edge(1, 2, foo="bar")
123
+ G.add_edge(1, 2, "key", foo="biz")
124
+ assert edges_equal(G.edges[1, 2, 0], {"foo": "bar"})
125
+ assert edges_equal(G.edges[1, 2, "key"], {"foo": "biz"})
126
+
127
+ def test_edge_attr(self):
128
+ G = self.Graph()
129
+ G.add_edge(1, 2, key="k1", foo="bar")
130
+ G.add_edge(1, 2, key="k2", foo="baz")
131
+ assert isinstance(G.get_edge_data(1, 2), G.edge_key_dict_factory)
132
+ assert all(
133
+ isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True)
134
+ )
135
+ assert edges_equal(
136
+ G.edges(keys=True, data=True),
137
+ [(1, 2, "k1", {"foo": "bar"}), (1, 2, "k2", {"foo": "baz"})],
138
+ )
139
+ assert edges_equal(
140
+ G.edges(keys=True, data="foo"), [(1, 2, "k1", "bar"), (1, 2, "k2", "baz")]
141
+ )
142
+
143
+ def test_edge_attr4(self):
144
+ G = self.Graph()
145
+ G.add_edge(1, 2, key=0, data=7, spam="bar", bar="foo")
146
+ assert edges_equal(
147
+ G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
148
+ )
149
+ G[1][2][0]["data"] = 10 # OK to set data like this
150
+ assert edges_equal(
151
+ G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
152
+ )
153
+
154
+ G.adj[1][2][0]["data"] = 20
155
+ assert edges_equal(
156
+ G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
157
+ )
158
+ G.edges[1, 2, 0]["data"] = 21 # another spelling, "edge"
159
+ assert edges_equal(
160
+ G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
161
+ )
162
+ G.adj[1][2][0]["listdata"] = [20, 200]
163
+ G.adj[1][2][0]["weight"] = 20
164
+ assert edges_equal(
165
+ G.edges(data=True),
166
+ [
167
+ (
168
+ 1,
169
+ 2,
170
+ {
171
+ "data": 21,
172
+ "spam": "bar",
173
+ "bar": "foo",
174
+ "listdata": [20, 200],
175
+ "weight": 20,
176
+ },
177
+ )
178
+ ],
179
+ )
180
+
181
+
182
+ class TestMultiGraph(BaseMultiGraphTester, _TestGraph):
183
+ def setup_method(self):
184
+ self.Graph = nx.MultiGraph
185
+ # build K3
186
+ ed1, ed2, ed3 = ({0: {}}, {0: {}}, {0: {}})
187
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
188
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
189
+ self.k3nodes = [0, 1, 2]
190
+ self.K3 = self.Graph()
191
+ self.K3._adj = self.k3adj
192
+ self.K3._node = {}
193
+ self.K3._node[0] = {}
194
+ self.K3._node[1] = {}
195
+ self.K3._node[2] = {}
196
+
197
+ def test_data_input(self):
198
+ G = self.Graph({1: [2], 2: [1]}, name="test")
199
+ assert G.name == "test"
200
+ expected = [(1, {2: {0: {}}}), (2, {1: {0: {}}})]
201
+ assert sorted(G.adj.items()) == expected
202
+
203
+ def test_data_multigraph_input(self):
204
+ # standard case with edge keys and edge data
205
+ edata0 = {"w": 200, "s": "foo"}
206
+ edata1 = {"w": 201, "s": "bar"}
207
+ keydict = {0: edata0, 1: edata1}
208
+ dododod = {"a": {"b": keydict}}
209
+
210
+ multiple_edge = [("a", "b", 0, edata0), ("a", "b", 1, edata1)]
211
+ single_edge = [("a", "b", 0, keydict)]
212
+
213
+ G = self.Graph(dododod, multigraph_input=True)
214
+ assert list(G.edges(keys=True, data=True)) == multiple_edge
215
+ G = self.Graph(dododod, multigraph_input=None)
216
+ assert list(G.edges(keys=True, data=True)) == multiple_edge
217
+ G = self.Graph(dododod, multigraph_input=False)
218
+ assert list(G.edges(keys=True, data=True)) == single_edge
219
+
220
+ # test round-trip to_dict_of_dict and MultiGraph constructor
221
+ G = self.Graph(dododod, multigraph_input=True)
222
+ H = self.Graph(nx.to_dict_of_dicts(G))
223
+ assert nx.is_isomorphic(G, H) is True # test that default is True
224
+ for mgi in [True, False]:
225
+ H = self.Graph(nx.to_dict_of_dicts(G), multigraph_input=mgi)
226
+ assert nx.is_isomorphic(G, H) == mgi
227
+
228
+ # Set up cases for when incoming_graph_data is not multigraph_input
229
+ etraits = {"w": 200, "s": "foo"}
230
+ egraphics = {"color": "blue", "shape": "box"}
231
+ edata = {"traits": etraits, "graphics": egraphics}
232
+ dodod1 = {"a": {"b": edata}}
233
+ dodod2 = {"a": {"b": etraits}}
234
+ dodod3 = {"a": {"b": {"traits": etraits, "s": "foo"}}}
235
+ dol = {"a": ["b"]}
236
+
237
+ multiple_edge = [("a", "b", "traits", etraits), ("a", "b", "graphics", egraphics)]
238
+ single_edge = [("a", "b", 0, {})] # type: ignore[var-annotated]
239
+ single_edge1 = [("a", "b", 0, edata)]
240
+ single_edge2 = [("a", "b", 0, etraits)]
241
+ single_edge3 = [("a", "b", 0, {"traits": etraits, "s": "foo"})]
242
+
243
+ cases = [ # (dod, mgi, edges)
244
+ (dodod1, True, multiple_edge),
245
+ (dodod1, False, single_edge1),
246
+ (dodod2, False, single_edge2),
247
+ (dodod3, False, single_edge3),
248
+ (dol, False, single_edge),
249
+ ]
250
+
251
+ @pytest.mark.parametrize("dod, mgi, edges", cases)
252
+ def test_non_multigraph_input(self, dod, mgi, edges):
253
+ G = self.Graph(dod, multigraph_input=mgi)
254
+ assert list(G.edges(keys=True, data=True)) == edges
255
+ G = nx.to_networkx_graph(dod, create_using=self.Graph, multigraph_input=mgi)
256
+ assert list(G.edges(keys=True, data=True)) == edges
257
+
258
+ mgi_none_cases = [
259
+ (dodod1, multiple_edge),
260
+ (dodod2, single_edge2),
261
+ (dodod3, single_edge3),
262
+ ]
263
+
264
+ @pytest.mark.parametrize("dod, edges", mgi_none_cases)
265
+ def test_non_multigraph_input_mgi_none(self, dod, edges):
266
+ # test constructor without to_networkx_graph for mgi=None
267
+ G = self.Graph(dod)
268
+ assert list(G.edges(keys=True, data=True)) == edges
269
+
270
+ raise_cases = [dodod2, dodod3, dol]
271
+
272
+ @pytest.mark.parametrize("dod", raise_cases)
273
+ def test_non_multigraph_input_raise(self, dod):
274
+ # cases where NetworkXError is raised
275
+ pytest.raises(nx.NetworkXError, self.Graph, dod, multigraph_input=True)
276
+ pytest.raises(
277
+ nx.NetworkXError,
278
+ nx.to_networkx_graph,
279
+ dod,
280
+ create_using=self.Graph,
281
+ multigraph_input=True,
282
+ )
283
+
284
+ def test_getitem(self):
285
+ G = self.K3
286
+ assert G[0] == {1: {0: {}}, 2: {0: {}}}
287
+ with pytest.raises(KeyError):
288
+ G.__getitem__("j")
289
+ with pytest.raises(TypeError):
290
+ G.__getitem__(["A"])
291
+
292
+ def test_remove_node(self):
293
+ G = self.K3
294
+ G.remove_node(0)
295
+ assert G.adj == {1: {2: {0: {}}}, 2: {1: {0: {}}}}
296
+ with pytest.raises(nx.NetworkXError):
297
+ G.remove_node(-1)
298
+
299
+ def test_add_edge(self):
300
+ G = self.Graph()
301
+ G.add_edge(0, 1)
302
+ assert G.adj == {0: {1: {0: {}}}, 1: {0: {0: {}}}}
303
+ G = self.Graph()
304
+ G.add_edge(*(0, 1))
305
+ assert G.adj == {0: {1: {0: {}}}, 1: {0: {0: {}}}}
306
+ G = self.Graph()
307
+ with pytest.raises(ValueError):
308
+ G.add_edge(None, "anything")
309
+
310
+ def test_add_edge_conflicting_key(self):
311
+ G = self.Graph()
312
+ G.add_edge(0, 1, key=1)
313
+ G.add_edge(0, 1)
314
+ assert G.number_of_edges() == 2
315
+ G = self.Graph()
316
+ G.add_edges_from([(0, 1, 1, {})])
317
+ G.add_edges_from([(0, 1)])
318
+ assert G.number_of_edges() == 2
319
+
320
+ def test_add_edges_from(self):
321
+ G = self.Graph()
322
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})])
323
+ assert G.adj == {
324
+ 0: {1: {0: {}, 1: {"weight": 3}}},
325
+ 1: {0: {0: {}, 1: {"weight": 3}}},
326
+ }
327
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})], weight=2)
328
+ assert G.adj == {
329
+ 0: {1: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
330
+ 1: {0: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
331
+ }
332
+ G = self.Graph()
333
+ edges = [
334
+ (0, 1, {"weight": 3}),
335
+ (0, 1, (("weight", 2),)),
336
+ (0, 1, 5),
337
+ (0, 1, "s"),
338
+ ]
339
+ G.add_edges_from(edges)
340
+ keydict = {0: {"weight": 3}, 1: {"weight": 2}, 5: {}, "s": {}}
341
+ assert G._adj == {0: {1: keydict}, 1: {0: keydict}}
342
+
343
+ # too few in tuple
344
+ with pytest.raises(nx.NetworkXError):
345
+ G.add_edges_from([(0,)])
346
+ # too many in tuple
347
+ with pytest.raises(nx.NetworkXError):
348
+ G.add_edges_from([(0, 1, 2, 3, 4)])
349
+ # not a tuple
350
+ with pytest.raises(TypeError):
351
+ G.add_edges_from([0])
352
+
353
+ def test_multigraph_add_edges_from_four_tuple_misordered(self):
354
+ """add_edges_from expects 4-tuples of the format (u, v, key, data_dict).
355
+
356
+ Ensure 4-tuples of form (u, v, data_dict, key) raise exception.
357
+ """
358
+ G = nx.MultiGraph()
359
+ with pytest.raises(TypeError):
360
+ # key/data values flipped in 4-tuple
361
+ G.add_edges_from([(0, 1, {"color": "red"}, 0)])
362
+
363
+ def test_remove_edge(self):
364
+ G = self.K3
365
+ G.remove_edge(0, 1)
366
+ assert G.adj == {0: {2: {0: {}}}, 1: {2: {0: {}}}, 2: {0: {0: {}}, 1: {0: {}}}}
367
+
368
+ with pytest.raises(nx.NetworkXError):
369
+ G.remove_edge(-1, 0)
370
+ with pytest.raises(nx.NetworkXError):
371
+ G.remove_edge(0, 2, key=1)
372
+
373
+ def test_remove_edges_from(self):
374
+ G = self.K3.copy()
375
+ G.remove_edges_from([(0, 1)])
376
+ kd = {0: {}}
377
+ assert G.adj == {0: {2: kd}, 1: {2: kd}, 2: {0: kd, 1: kd}}
378
+ G.remove_edges_from([(0, 0)]) # silent fail
379
+ self.K3.add_edge(0, 1)
380
+ G = self.K3.copy()
381
+ G.remove_edges_from(list(G.edges(data=True, keys=True)))
382
+ assert G.adj == {0: {}, 1: {}, 2: {}}
383
+ G = self.K3.copy()
384
+ G.remove_edges_from(list(G.edges(data=False, keys=True)))
385
+ assert G.adj == {0: {}, 1: {}, 2: {}}
386
+ G = self.K3.copy()
387
+ G.remove_edges_from(list(G.edges(data=False, keys=False)))
388
+ assert G.adj == {0: {}, 1: {}, 2: {}}
389
+ G = self.K3.copy()
390
+ G.remove_edges_from([(0, 1, 0), (0, 2, 0, {}), (1, 2)])
391
+ assert G.adj == {0: {1: {1: {}}}, 1: {0: {1: {}}}, 2: {}}
392
+
393
+ def test_remove_multiedge(self):
394
+ G = self.K3
395
+ G.add_edge(0, 1, key="parallel edge")
396
+ G.remove_edge(0, 1, key="parallel edge")
397
+ assert G.adj == {
398
+ 0: {1: {0: {}}, 2: {0: {}}},
399
+ 1: {0: {0: {}}, 2: {0: {}}},
400
+ 2: {0: {0: {}}, 1: {0: {}}},
401
+ }
402
+ G.remove_edge(0, 1)
403
+ kd = {0: {}}
404
+ assert G.adj == {0: {2: kd}, 1: {2: kd}, 2: {0: kd, 1: kd}}
405
+ with pytest.raises(nx.NetworkXError):
406
+ G.remove_edge(-1, 0)
407
+
408
+
409
+ class TestEdgeSubgraph:
410
+ """Unit tests for the :meth:`MultiGraph.edge_subgraph` method."""
411
+
412
+ def setup_method(self):
413
+ # Create a doubly-linked path graph on five nodes.
414
+ G = nx.MultiGraph()
415
+ nx.add_path(G, range(5))
416
+ nx.add_path(G, range(5))
417
+ # Add some node, edge, and graph attributes.
418
+ for i in range(5):
419
+ G.nodes[i]["name"] = f"node{i}"
420
+ G.adj[0][1][0]["name"] = "edge010"
421
+ G.adj[0][1][1]["name"] = "edge011"
422
+ G.adj[3][4][0]["name"] = "edge340"
423
+ G.adj[3][4][1]["name"] = "edge341"
424
+ G.graph["name"] = "graph"
425
+ # Get the subgraph induced by one of the first edges and one of
426
+ # the last edges.
427
+ self.G = G
428
+ self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)])
429
+
430
+ def test_correct_nodes(self):
431
+ """Tests that the subgraph has the correct nodes."""
432
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
433
+
434
+ def test_correct_edges(self):
435
+ """Tests that the subgraph has the correct edges."""
436
+ assert [(0, 1, 0, "edge010"), (3, 4, 1, "edge341")] == sorted(
437
+ self.H.edges(keys=True, data="name")
438
+ )
439
+
440
+ def test_add_node(self):
441
+ """Tests that adding a node to the original graph does not
442
+ affect the nodes of the subgraph.
443
+
444
+ """
445
+ self.G.add_node(5)
446
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
447
+
448
+ def test_remove_node(self):
449
+ """Tests that removing a node in the original graph does
450
+ affect the nodes of the subgraph.
451
+
452
+ """
453
+ self.G.remove_node(0)
454
+ assert [1, 3, 4] == sorted(self.H.nodes())
455
+
456
+ def test_node_attr_dict(self):
457
+ """Tests that the node attribute dictionary of the two graphs is
458
+ the same object.
459
+
460
+ """
461
+ for v in self.H:
462
+ assert self.G.nodes[v] == self.H.nodes[v]
463
+ # Making a change to G should make a change in H and vice versa.
464
+ self.G.nodes[0]["name"] = "foo"
465
+ assert self.G.nodes[0] == self.H.nodes[0]
466
+ self.H.nodes[1]["name"] = "bar"
467
+ assert self.G.nodes[1] == self.H.nodes[1]
468
+
469
+ def test_edge_attr_dict(self):
470
+ """Tests that the edge attribute dictionary of the two graphs is
471
+ the same object.
472
+
473
+ """
474
+ for u, v, k in self.H.edges(keys=True):
475
+ assert self.G._adj[u][v][k] == self.H._adj[u][v][k]
476
+ # Making a change to G should make a change in H and vice versa.
477
+ self.G._adj[0][1][0]["name"] = "foo"
478
+ assert self.G._adj[0][1][0]["name"] == self.H._adj[0][1][0]["name"]
479
+ self.H._adj[3][4][1]["name"] = "bar"
480
+ assert self.G._adj[3][4][1]["name"] == self.H._adj[3][4][1]["name"]
481
+
482
+ def test_graph_attr_dict(self):
483
+ """Tests that the graph attribute dictionary of the two graphs
484
+ is the same object.
485
+
486
+ """
487
+ assert self.G.graph is self.H.graph
488
+
489
+
490
+ class CustomDictClass(UserDict):
491
+ pass
492
+
493
+
494
+ class MultiGraphSubClass(nx.MultiGraph):
495
+ node_dict_factory = CustomDictClass # type: ignore[assignment]
496
+ node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
497
+ adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
498
+ adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignment]
499
+ edge_key_dict_factory = CustomDictClass # type: ignore[assignment]
500
+ edge_attr_dict_factory = CustomDictClass # type: ignore[assignment]
501
+ graph_attr_dict_factory = CustomDictClass # type: ignore[assignment]
502
+
503
+
504
+ class TestMultiGraphSubclass(TestMultiGraph):
505
+ def setup_method(self):
506
+ self.Graph = MultiGraphSubClass
507
+ # build K3
508
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
509
+ self.k3nodes = [0, 1, 2]
510
+ self.K3 = self.Graph()
511
+ self.K3._adj = self.K3.adjlist_outer_dict_factory(
512
+ {
513
+ 0: self.K3.adjlist_inner_dict_factory(),
514
+ 1: self.K3.adjlist_inner_dict_factory(),
515
+ 2: self.K3.adjlist_inner_dict_factory(),
516
+ }
517
+ )
518
+ self.K3._pred = {0: {}, 1: {}, 2: {}}
519
+ for u in self.k3nodes:
520
+ for v in self.k3nodes:
521
+ if u != v:
522
+ d = {0: {}}
523
+ self.K3._adj[u][v] = d
524
+ self.K3._adj[v][u] = d
525
+ self.K3._node = self.K3.node_dict_factory()
526
+ self.K3._node[0] = self.K3.node_attr_dict_factory()
527
+ self.K3._node[1] = self.K3.node_attr_dict_factory()
528
+ self.K3._node[2] = self.K3.node_attr_dict_factory()
deepseek/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
deepseek/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (711 Bytes). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc ADDED
Binary file (8.34 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/edgelist.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc ADDED
Binary file (24.4 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc ADDED
Binary file (28.5 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc ADDED
Binary file (9.53 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc ADDED
Binary file (3.07 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc ADDED
Binary file (6.75 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/sparse6.cpython-310.pyc ADDED
Binary file (9.77 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/__pycache__/text.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/gml.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Read graphs in GML format.
3
+
4
+ "GML, the Graph Modelling Language, is our proposal for a portable
5
+ file format for graphs. GML's key features are portability, simple
6
+ syntax, extensibility and flexibility. A GML file consists of a
7
+ hierarchical key-value lists. Graphs can be annotated with arbitrary
8
+ data structures. The idea for a common file format was born at the
9
+ GD'95; this proposal is the outcome of many discussions. GML is the
10
+ standard file format in the Graphlet graph editor system. It has been
11
+ overtaken and adapted by several other systems for drawing graphs."
12
+
13
+ GML files are stored using a 7-bit ASCII encoding with any extended
14
+ ASCII characters (iso8859-1) appearing as HTML character entities.
15
+ You will need to give some thought into how the exported data should
16
+ interact with different languages and even different Python versions.
17
+ Re-importing from gml is also a concern.
18
+
19
+ Without specifying a `stringizer`/`destringizer`, the code is capable of
20
+ writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
21
+ specification. For writing other data types, and for reading data other
22
+ than `str` you need to explicitly supply a `stringizer`/`destringizer`.
23
+
24
+ For additional documentation on the GML file format, please see the
25
+ `GML website <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
26
+
27
+ Several example graphs in GML format may be found on Mark Newman's
28
+ `Network data page <http://www-personal.umich.edu/~mejn/netdata/>`_.
29
+ """
30
+
31
+ import html.entities as htmlentitydefs
32
+ import re
33
+ import warnings
34
+ from ast import literal_eval
35
+ from collections import defaultdict
36
+ from enum import Enum
37
+ from io import StringIO
38
+ from typing import Any, NamedTuple
39
+
40
+ import networkx as nx
41
+ from networkx.exception import NetworkXError
42
+ from networkx.utils import open_file
43
+
44
+ __all__ = ["read_gml", "parse_gml", "generate_gml", "write_gml"]
45
+
46
+
47
+ def escape(text):
48
+ """Use XML character references to escape characters.
49
+
50
+ Use XML character references for unprintable or non-ASCII
51
+ characters, double quotes and ampersands in a string
52
+ """
53
+
54
+ def fixup(m):
55
+ ch = m.group(0)
56
+ return "&#" + str(ord(ch)) + ";"
57
+
58
+ text = re.sub('[^ -~]|[&"]', fixup, text)
59
+ return text if isinstance(text, str) else str(text)
60
+
61
+
62
+ def unescape(text):
63
+ """Replace XML character references with the referenced characters"""
64
+
65
+ def fixup(m):
66
+ text = m.group(0)
67
+ if text[1] == "#":
68
+ # Character reference
69
+ if text[2] == "x":
70
+ code = int(text[3:-1], 16)
71
+ else:
72
+ code = int(text[2:-1])
73
+ else:
74
+ # Named entity
75
+ try:
76
+ code = htmlentitydefs.name2codepoint[text[1:-1]]
77
+ except KeyError:
78
+ return text # leave unchanged
79
+ try:
80
+ return chr(code)
81
+ except (ValueError, OverflowError):
82
+ return text # leave unchanged
83
+
84
+ return re.sub("&(?:[0-9A-Za-z]+|#(?:[0-9]+|x[0-9A-Fa-f]+));", fixup, text)
85
+
86
+
87
+ def literal_destringizer(rep):
88
+ """Convert a Python literal to the value it represents.
89
+
90
+ Parameters
91
+ ----------
92
+ rep : string
93
+ A Python literal.
94
+
95
+ Returns
96
+ -------
97
+ value : object
98
+ The value of the Python literal.
99
+
100
+ Raises
101
+ ------
102
+ ValueError
103
+ If `rep` is not a Python literal.
104
+ """
105
+ if isinstance(rep, str):
106
+ orig_rep = rep
107
+ try:
108
+ return literal_eval(rep)
109
+ except SyntaxError as err:
110
+ raise ValueError(f"{orig_rep!r} is not a valid Python literal") from err
111
+ else:
112
+ raise ValueError(f"{rep!r} is not a string")
113
+
114
+
115
+ @open_file(0, mode="rb")
116
+ @nx._dispatchable(graphs=None, returns_graph=True)
117
+ def read_gml(path, label="label", destringizer=None):
118
+ """Read graph in GML format from `path`.
119
+
120
+ Parameters
121
+ ----------
122
+ path : filename or filehandle
123
+ The filename or filehandle to read from.
124
+
125
+ label : string, optional
126
+ If not None, the parsed nodes will be renamed according to node
127
+ attributes indicated by `label`. Default value: 'label'.
128
+
129
+ destringizer : callable, optional
130
+ A `destringizer` that recovers values stored as strings in GML. If it
131
+ cannot convert a string to a value, a `ValueError` is raised. Default
132
+ value : None.
133
+
134
+ Returns
135
+ -------
136
+ G : NetworkX graph
137
+ The parsed graph.
138
+
139
+ Raises
140
+ ------
141
+ NetworkXError
142
+ If the input cannot be parsed.
143
+
144
+ See Also
145
+ --------
146
+ write_gml, parse_gml
147
+ literal_destringizer
148
+
149
+ Notes
150
+ -----
151
+ GML files are stored using a 7-bit ASCII encoding with any extended
152
+ ASCII characters (iso8859-1) appearing as HTML character entities.
153
+ Without specifying a `stringizer`/`destringizer`, the code is capable of
154
+ writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
155
+ specification. For writing other data types, and for reading data other
156
+ than `str` you need to explicitly supply a `stringizer`/`destringizer`.
157
+
158
+ For additional documentation on the GML file format, please see the
159
+ `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
160
+
161
+ See the module docstring :mod:`networkx.readwrite.gml` for more details.
162
+
163
+ Examples
164
+ --------
165
+ >>> G = nx.path_graph(4)
166
+ >>> nx.write_gml(G, "test.gml")
167
+
168
+ GML values are interpreted as strings by default:
169
+
170
+ >>> H = nx.read_gml("test.gml")
171
+ >>> H.nodes
172
+ NodeView(('0', '1', '2', '3'))
173
+
174
+ When a `destringizer` is provided, GML values are converted to the provided type.
175
+ For example, integer nodes can be recovered as shown below:
176
+
177
+ >>> J = nx.read_gml("test.gml", destringizer=int)
178
+ >>> J.nodes
179
+ NodeView((0, 1, 2, 3))
180
+
181
+ """
182
+
183
+ def filter_lines(lines):
184
+ for line in lines:
185
+ try:
186
+ line = line.decode("ascii")
187
+ except UnicodeDecodeError as err:
188
+ raise NetworkXError("input is not ASCII-encoded") from err
189
+ if not isinstance(line, str):
190
+ lines = str(lines)
191
+ if line and line[-1] == "\n":
192
+ line = line[:-1]
193
+ yield line
194
+
195
+ G = parse_gml_lines(filter_lines(path), label, destringizer)
196
+ return G
197
+
198
+
199
+ @nx._dispatchable(graphs=None, returns_graph=True)
200
+ def parse_gml(lines, label="label", destringizer=None):
201
+ """Parse GML graph from a string or iterable.
202
+
203
+ Parameters
204
+ ----------
205
+ lines : string or iterable of strings
206
+ Data in GML format.
207
+
208
+ label : string, optional
209
+ If not None, the parsed nodes will be renamed according to node
210
+ attributes indicated by `label`. Default value: 'label'.
211
+
212
+ destringizer : callable, optional
213
+ A `destringizer` that recovers values stored as strings in GML. If it
214
+ cannot convert a string to a value, a `ValueError` is raised. Default
215
+ value : None.
216
+
217
+ Returns
218
+ -------
219
+ G : NetworkX graph
220
+ The parsed graph.
221
+
222
+ Raises
223
+ ------
224
+ NetworkXError
225
+ If the input cannot be parsed.
226
+
227
+ See Also
228
+ --------
229
+ write_gml, read_gml
230
+
231
+ Notes
232
+ -----
233
+ This stores nested GML attributes as dictionaries in the NetworkX graph,
234
+ node, and edge attribute structures.
235
+
236
+ GML files are stored using a 7-bit ASCII encoding with any extended
237
+ ASCII characters (iso8859-1) appearing as HTML character entities.
238
+ Without specifying a `stringizer`/`destringizer`, the code is capable of
239
+ writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
240
+ specification. For writing other data types, and for reading data other
241
+ than `str` you need to explicitly supply a `stringizer`/`destringizer`.
242
+
243
+ For additional documentation on the GML file format, please see the
244
+ `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
245
+
246
+ See the module docstring :mod:`networkx.readwrite.gml` for more details.
247
+ """
248
+
249
+ def decode_line(line):
250
+ if isinstance(line, bytes):
251
+ try:
252
+ line.decode("ascii")
253
+ except UnicodeDecodeError as err:
254
+ raise NetworkXError("input is not ASCII-encoded") from err
255
+ if not isinstance(line, str):
256
+ line = str(line)
257
+ return line
258
+
259
+ def filter_lines(lines):
260
+ if isinstance(lines, str):
261
+ lines = decode_line(lines)
262
+ lines = lines.splitlines()
263
+ yield from lines
264
+ else:
265
+ for line in lines:
266
+ line = decode_line(line)
267
+ if line and line[-1] == "\n":
268
+ line = line[:-1]
269
+ if line.find("\n") != -1:
270
+ raise NetworkXError("input line contains newline")
271
+ yield line
272
+
273
+ G = parse_gml_lines(filter_lines(lines), label, destringizer)
274
+ return G
275
+
276
+
277
+ class Pattern(Enum):
278
+ """encodes the index of each token-matching pattern in `tokenize`."""
279
+
280
+ KEYS = 0
281
+ REALS = 1
282
+ INTS = 2
283
+ STRINGS = 3
284
+ DICT_START = 4
285
+ DICT_END = 5
286
+ COMMENT_WHITESPACE = 6
287
+
288
+
289
+ class Token(NamedTuple):
290
+ category: Pattern
291
+ value: Any
292
+ line: int
293
+ position: int
294
+
295
+
296
+ LIST_START_VALUE = "_networkx_list_start"
297
+
298
+
299
+ def parse_gml_lines(lines, label, destringizer):
300
+ """Parse GML `lines` into a graph."""
301
+
302
+ def tokenize():
303
+ patterns = [
304
+ r"[A-Za-z][0-9A-Za-z_]*\b", # keys
305
+ # reals
306
+ r"[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|INF)(?:[Ee][+-]?[0-9]+)?",
307
+ r"[+-]?[0-9]+", # ints
308
+ r'".*?"', # strings
309
+ r"\[", # dict start
310
+ r"\]", # dict end
311
+ r"#.*$|\s+", # comments and whitespaces
312
+ ]
313
+ tokens = re.compile("|".join(f"({pattern})" for pattern in patterns))
314
+ lineno = 0
315
+ multilines = [] # entries spread across multiple lines
316
+ for line in lines:
317
+ pos = 0
318
+
319
+ # deal with entries spread across multiple lines
320
+ #
321
+ # should we actually have to deal with escaped "s then do it here
322
+ if multilines:
323
+ multilines.append(line.strip())
324
+ if line[-1] == '"': # closing multiline entry
325
+ # multiline entries will be joined by space. cannot
326
+ # reintroduce newlines as this will break the tokenizer
327
+ line = " ".join(multilines)
328
+ multilines = []
329
+ else: # continued multiline entry
330
+ lineno += 1
331
+ continue
332
+ else:
333
+ if line.count('"') == 1: # opening multiline entry
334
+ if line.strip()[0] != '"' and line.strip()[-1] != '"':
335
+ # since we expect something like key "value", the " should not be found at ends
336
+ # otherwise tokenizer will pick up the formatting mistake.
337
+ multilines = [line.rstrip()]
338
+ lineno += 1
339
+ continue
340
+
341
+ length = len(line)
342
+
343
+ while pos < length:
344
+ match = tokens.match(line, pos)
345
+ if match is None:
346
+ m = f"cannot tokenize {line[pos:]} at ({lineno + 1}, {pos + 1})"
347
+ raise NetworkXError(m)
348
+ for i in range(len(patterns)):
349
+ group = match.group(i + 1)
350
+ if group is not None:
351
+ if i == 0: # keys
352
+ value = group.rstrip()
353
+ elif i == 1: # reals
354
+ value = float(group)
355
+ elif i == 2: # ints
356
+ value = int(group)
357
+ else:
358
+ value = group
359
+ if i != 6: # comments and whitespaces
360
+ yield Token(Pattern(i), value, lineno + 1, pos + 1)
361
+ pos += len(group)
362
+ break
363
+ lineno += 1
364
+ yield Token(None, None, lineno + 1, 1) # EOF
365
+
366
+ def unexpected(curr_token, expected):
367
+ category, value, lineno, pos = curr_token
368
+ value = repr(value) if value is not None else "EOF"
369
+ raise NetworkXError(f"expected {expected}, found {value} at ({lineno}, {pos})")
370
+
371
+ def consume(curr_token, category, expected):
372
+ if curr_token.category == category:
373
+ return next(tokens)
374
+ unexpected(curr_token, expected)
375
+
376
+ def parse_kv(curr_token):
377
+ dct = defaultdict(list)
378
+ while curr_token.category == Pattern.KEYS:
379
+ key = curr_token.value
380
+ curr_token = next(tokens)
381
+ category = curr_token.category
382
+ if category == Pattern.REALS or category == Pattern.INTS:
383
+ value = curr_token.value
384
+ curr_token = next(tokens)
385
+ elif category == Pattern.STRINGS:
386
+ value = unescape(curr_token.value[1:-1])
387
+ if destringizer:
388
+ try:
389
+ value = destringizer(value)
390
+ except ValueError:
391
+ pass
392
+ # Special handling for empty lists and tuples
393
+ if value == "()":
394
+ value = ()
395
+ if value == "[]":
396
+ value = []
397
+ curr_token = next(tokens)
398
+ elif category == Pattern.DICT_START:
399
+ curr_token, value = parse_dict(curr_token)
400
+ else:
401
+ # Allow for string convertible id and label values
402
+ if key in ("id", "label", "source", "target"):
403
+ try:
404
+ # String convert the token value
405
+ value = unescape(str(curr_token.value))
406
+ if destringizer:
407
+ try:
408
+ value = destringizer(value)
409
+ except ValueError:
410
+ pass
411
+ curr_token = next(tokens)
412
+ except Exception:
413
+ msg = (
414
+ "an int, float, string, '[' or string"
415
+ + " convertible ASCII value for node id or label"
416
+ )
417
+ unexpected(curr_token, msg)
418
+ # Special handling for nan and infinity. Since the gml language
419
+ # defines unquoted strings as keys, the numeric and string branches
420
+ # are skipped and we end up in this special branch, so we need to
421
+ # convert the current token value to a float for NAN and plain INF.
422
+ # +/-INF are handled in the pattern for 'reals' in tokenize(). This
423
+ # allows labels and values to be nan or infinity, but not keys.
424
+ elif curr_token.value in {"NAN", "INF"}:
425
+ value = float(curr_token.value)
426
+ curr_token = next(tokens)
427
+ else: # Otherwise error out
428
+ unexpected(curr_token, "an int, float, string or '['")
429
+ dct[key].append(value)
430
+
431
+ def clean_dict_value(value):
432
+ if not isinstance(value, list):
433
+ return value
434
+ if len(value) == 1:
435
+ return value[0]
436
+ if value[0] == LIST_START_VALUE:
437
+ return value[1:]
438
+ return value
439
+
440
+ dct = {key: clean_dict_value(value) for key, value in dct.items()}
441
+ return curr_token, dct
442
+
443
+ def parse_dict(curr_token):
444
+ # dict start
445
+ curr_token = consume(curr_token, Pattern.DICT_START, "'['")
446
+ # dict contents
447
+ curr_token, dct = parse_kv(curr_token)
448
+ # dict end
449
+ curr_token = consume(curr_token, Pattern.DICT_END, "']'")
450
+ return curr_token, dct
451
+
452
+ def parse_graph():
453
+ curr_token, dct = parse_kv(next(tokens))
454
+ if curr_token.category is not None: # EOF
455
+ unexpected(curr_token, "EOF")
456
+ if "graph" not in dct:
457
+ raise NetworkXError("input contains no graph")
458
+ graph = dct["graph"]
459
+ if isinstance(graph, list):
460
+ raise NetworkXError("input contains more than one graph")
461
+ return graph
462
+
463
+ tokens = tokenize()
464
+ graph = parse_graph()
465
+
466
+ directed = graph.pop("directed", False)
467
+ multigraph = graph.pop("multigraph", False)
468
+ if not multigraph:
469
+ G = nx.DiGraph() if directed else nx.Graph()
470
+ else:
471
+ G = nx.MultiDiGraph() if directed else nx.MultiGraph()
472
+ graph_attr = {k: v for k, v in graph.items() if k not in ("node", "edge")}
473
+ G.graph.update(graph_attr)
474
+
475
+ def pop_attr(dct, category, attr, i):
476
+ try:
477
+ return dct.pop(attr)
478
+ except KeyError as err:
479
+ raise NetworkXError(f"{category} #{i} has no {attr!r} attribute") from err
480
+
481
+ nodes = graph.get("node", [])
482
+ mapping = {}
483
+ node_labels = set()
484
+ for i, node in enumerate(nodes if isinstance(nodes, list) else [nodes]):
485
+ id = pop_attr(node, "node", "id", i)
486
+ if id in G:
487
+ raise NetworkXError(f"node id {id!r} is duplicated")
488
+ if label is not None and label != "id":
489
+ node_label = pop_attr(node, "node", label, i)
490
+ if node_label in node_labels:
491
+ raise NetworkXError(f"node label {node_label!r} is duplicated")
492
+ node_labels.add(node_label)
493
+ mapping[id] = node_label
494
+ G.add_node(id, **node)
495
+
496
+ edges = graph.get("edge", [])
497
+ for i, edge in enumerate(edges if isinstance(edges, list) else [edges]):
498
+ source = pop_attr(edge, "edge", "source", i)
499
+ target = pop_attr(edge, "edge", "target", i)
500
+ if source not in G:
501
+ raise NetworkXError(f"edge #{i} has undefined source {source!r}")
502
+ if target not in G:
503
+ raise NetworkXError(f"edge #{i} has undefined target {target!r}")
504
+ if not multigraph:
505
+ if not G.has_edge(source, target):
506
+ G.add_edge(source, target, **edge)
507
+ else:
508
+ arrow = "->" if directed else "--"
509
+ msg = f"edge #{i} ({source!r}{arrow}{target!r}) is duplicated"
510
+ raise nx.NetworkXError(msg)
511
+ else:
512
+ key = edge.pop("key", None)
513
+ if key is not None and G.has_edge(source, target, key):
514
+ arrow = "->" if directed else "--"
515
+ msg = f"edge #{i} ({source!r}{arrow}{target!r}, {key!r})"
516
+ msg2 = 'Hint: If multigraph add "multigraph 1" to file header.'
517
+ raise nx.NetworkXError(msg + " is duplicated\n" + msg2)
518
+ G.add_edge(source, target, key, **edge)
519
+
520
+ if label is not None and label != "id":
521
+ G = nx.relabel_nodes(G, mapping)
522
+ return G
523
+
524
+
525
+ def literal_stringizer(value):
526
+ """Convert a `value` to a Python literal in GML representation.
527
+
528
+ Parameters
529
+ ----------
530
+ value : object
531
+ The `value` to be converted to GML representation.
532
+
533
+ Returns
534
+ -------
535
+ rep : string
536
+ A double-quoted Python literal representing value. Unprintable
537
+ characters are replaced by XML character references.
538
+
539
+ Raises
540
+ ------
541
+ ValueError
542
+ If `value` cannot be converted to GML.
543
+
544
+ Notes
545
+ -----
546
+ The original value can be recovered using the
547
+ :func:`networkx.readwrite.gml.literal_destringizer` function.
548
+ """
549
+
550
+ def stringize(value):
551
+ if isinstance(value, int | bool) or value is None:
552
+ if value is True: # GML uses 1/0 for boolean values.
553
+ buf.write(str(1))
554
+ elif value is False:
555
+ buf.write(str(0))
556
+ else:
557
+ buf.write(str(value))
558
+ elif isinstance(value, str):
559
+ text = repr(value)
560
+ if text[0] != "u":
561
+ try:
562
+ value.encode("latin1")
563
+ except UnicodeEncodeError:
564
+ text = "u" + text
565
+ buf.write(text)
566
+ elif isinstance(value, float | complex | str | bytes):
567
+ buf.write(repr(value))
568
+ elif isinstance(value, list):
569
+ buf.write("[")
570
+ first = True
571
+ for item in value:
572
+ if not first:
573
+ buf.write(",")
574
+ else:
575
+ first = False
576
+ stringize(item)
577
+ buf.write("]")
578
+ elif isinstance(value, tuple):
579
+ if len(value) > 1:
580
+ buf.write("(")
581
+ first = True
582
+ for item in value:
583
+ if not first:
584
+ buf.write(",")
585
+ else:
586
+ first = False
587
+ stringize(item)
588
+ buf.write(")")
589
+ elif value:
590
+ buf.write("(")
591
+ stringize(value[0])
592
+ buf.write(",)")
593
+ else:
594
+ buf.write("()")
595
+ elif isinstance(value, dict):
596
+ buf.write("{")
597
+ first = True
598
+ for key, value in value.items():
599
+ if not first:
600
+ buf.write(",")
601
+ else:
602
+ first = False
603
+ stringize(key)
604
+ buf.write(":")
605
+ stringize(value)
606
+ buf.write("}")
607
+ elif isinstance(value, set):
608
+ buf.write("{")
609
+ first = True
610
+ for item in value:
611
+ if not first:
612
+ buf.write(",")
613
+ else:
614
+ first = False
615
+ stringize(item)
616
+ buf.write("}")
617
+ else:
618
+ msg = f"{value!r} cannot be converted into a Python literal"
619
+ raise ValueError(msg)
620
+
621
+ buf = StringIO()
622
+ stringize(value)
623
+ return buf.getvalue()
624
+
625
+
626
+ def generate_gml(G, stringizer=None):
627
+ r"""Generate a single entry of the graph `G` in GML format.
628
+
629
+ Parameters
630
+ ----------
631
+ G : NetworkX graph
632
+ The graph to be converted to GML.
633
+
634
+ stringizer : callable, optional
635
+ A `stringizer` which converts non-int/non-float/non-dict values into
636
+ strings. If it cannot convert a value into a string, it should raise a
637
+ `ValueError` to indicate that. Default value: None.
638
+
639
+ Returns
640
+ -------
641
+ lines: generator of strings
642
+ Lines of GML data. Newlines are not appended.
643
+
644
+ Raises
645
+ ------
646
+ NetworkXError
647
+ If `stringizer` cannot convert a value into a string, or the value to
648
+ convert is not a string while `stringizer` is None.
649
+
650
+ See Also
651
+ --------
652
+ literal_stringizer
653
+
654
+ Notes
655
+ -----
656
+ Graph attributes named 'directed', 'multigraph', 'node' or
657
+ 'edge', node attributes named 'id' or 'label', edge attributes
658
+ named 'source' or 'target' (or 'key' if `G` is a multigraph)
659
+ are ignored because these attribute names are used to encode the graph
660
+ structure.
661
+
662
+ GML files are stored using a 7-bit ASCII encoding with any extended
663
+ ASCII characters (iso8859-1) appearing as HTML character entities.
664
+ Without specifying a `stringizer`/`destringizer`, the code is capable of
665
+ writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
666
+ specification. For writing other data types, and for reading data other
667
+ than `str` you need to explicitly supply a `stringizer`/`destringizer`.
668
+
669
+ For additional documentation on the GML file format, please see the
670
+ `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
671
+
672
+ See the module docstring :mod:`networkx.readwrite.gml` for more details.
673
+
674
+ Examples
675
+ --------
676
+ >>> G = nx.Graph()
677
+ >>> G.add_node("1")
678
+ >>> print("\n".join(nx.generate_gml(G)))
679
+ graph [
680
+ node [
681
+ id 0
682
+ label "1"
683
+ ]
684
+ ]
685
+ >>> G = nx.MultiGraph([("a", "b"), ("a", "b")])
686
+ >>> print("\n".join(nx.generate_gml(G)))
687
+ graph [
688
+ multigraph 1
689
+ node [
690
+ id 0
691
+ label "a"
692
+ ]
693
+ node [
694
+ id 1
695
+ label "b"
696
+ ]
697
+ edge [
698
+ source 0
699
+ target 1
700
+ key 0
701
+ ]
702
+ edge [
703
+ source 0
704
+ target 1
705
+ key 1
706
+ ]
707
+ ]
708
+ """
709
+ valid_keys = re.compile("^[A-Za-z][0-9A-Za-z_]*$")
710
+
711
+ def stringize(key, value, ignored_keys, indent, in_list=False):
712
+ if not isinstance(key, str):
713
+ raise NetworkXError(f"{key!r} is not a string")
714
+ if not valid_keys.match(key):
715
+ raise NetworkXError(f"{key!r} is not a valid key")
716
+ if not isinstance(key, str):
717
+ key = str(key)
718
+ if key not in ignored_keys:
719
+ if isinstance(value, int | bool):
720
+ if key == "label":
721
+ yield indent + key + ' "' + str(value) + '"'
722
+ elif value is True:
723
+ # python bool is an instance of int
724
+ yield indent + key + " 1"
725
+ elif value is False:
726
+ yield indent + key + " 0"
727
+ # GML only supports signed 32-bit integers
728
+ elif value < -(2**31) or value >= 2**31:
729
+ yield indent + key + ' "' + str(value) + '"'
730
+ else:
731
+ yield indent + key + " " + str(value)
732
+ elif isinstance(value, float):
733
+ text = repr(value).upper()
734
+ # GML matches INF to keys, so prepend + to INF. Use repr(float(*))
735
+ # instead of string literal to future proof against changes to repr.
736
+ if text == repr(float("inf")).upper():
737
+ text = "+" + text
738
+ else:
739
+ # GML requires that a real literal contain a decimal point, but
740
+ # repr may not output a decimal point when the mantissa is
741
+ # integral and hence needs fixing.
742
+ epos = text.rfind("E")
743
+ if epos != -1 and text.find(".", 0, epos) == -1:
744
+ text = text[:epos] + "." + text[epos:]
745
+ if key == "label":
746
+ yield indent + key + ' "' + text + '"'
747
+ else:
748
+ yield indent + key + " " + text
749
+ elif isinstance(value, dict):
750
+ yield indent + key + " ["
751
+ next_indent = indent + " "
752
+ for key, value in value.items():
753
+ yield from stringize(key, value, (), next_indent)
754
+ yield indent + "]"
755
+ elif isinstance(value, tuple) and key == "label":
756
+ yield indent + key + f" \"({','.join(repr(v) for v in value)})\""
757
+ elif isinstance(value, list | tuple) and key != "label" and not in_list:
758
+ if len(value) == 0:
759
+ yield indent + key + " " + f'"{value!r}"'
760
+ if len(value) == 1:
761
+ yield indent + key + " " + f'"{LIST_START_VALUE}"'
762
+ for val in value:
763
+ yield from stringize(key, val, (), indent, True)
764
+ else:
765
+ if stringizer:
766
+ try:
767
+ value = stringizer(value)
768
+ except ValueError as err:
769
+ raise NetworkXError(
770
+ f"{value!r} cannot be converted into a string"
771
+ ) from err
772
+ if not isinstance(value, str):
773
+ raise NetworkXError(f"{value!r} is not a string")
774
+ yield indent + key + ' "' + escape(value) + '"'
775
+
776
+ multigraph = G.is_multigraph()
777
+ yield "graph ["
778
+
779
+ # Output graph attributes
780
+ if G.is_directed():
781
+ yield " directed 1"
782
+ if multigraph:
783
+ yield " multigraph 1"
784
+ ignored_keys = {"directed", "multigraph", "node", "edge"}
785
+ for attr, value in G.graph.items():
786
+ yield from stringize(attr, value, ignored_keys, " ")
787
+
788
+ # Output node data
789
+ node_id = dict(zip(G, range(len(G))))
790
+ ignored_keys = {"id", "label"}
791
+ for node, attrs in G.nodes.items():
792
+ yield " node ["
793
+ yield " id " + str(node_id[node])
794
+ yield from stringize("label", node, (), " ")
795
+ for attr, value in attrs.items():
796
+ yield from stringize(attr, value, ignored_keys, " ")
797
+ yield " ]"
798
+
799
+ # Output edge data
800
+ ignored_keys = {"source", "target"}
801
+ kwargs = {"data": True}
802
+ if multigraph:
803
+ ignored_keys.add("key")
804
+ kwargs["keys"] = True
805
+ for e in G.edges(**kwargs):
806
+ yield " edge ["
807
+ yield " source " + str(node_id[e[0]])
808
+ yield " target " + str(node_id[e[1]])
809
+ if multigraph:
810
+ yield from stringize("key", e[2], (), " ")
811
+ for attr, value in e[-1].items():
812
+ yield from stringize(attr, value, ignored_keys, " ")
813
+ yield " ]"
814
+ yield "]"
815
+
816
+
817
+ @open_file(1, mode="wb")
818
+ def write_gml(G, path, stringizer=None):
819
+ """Write a graph `G` in GML format to the file or file handle `path`.
820
+
821
+ Parameters
822
+ ----------
823
+ G : NetworkX graph
824
+ The graph to be converted to GML.
825
+
826
+ path : filename or filehandle
827
+ The filename or filehandle to write. Files whose names end with .gz or
828
+ .bz2 will be compressed.
829
+
830
+ stringizer : callable, optional
831
+ A `stringizer` which converts non-int/non-float/non-dict values into
832
+ strings. If it cannot convert a value into a string, it should raise a
833
+ `ValueError` to indicate that. Default value: None.
834
+
835
+ Raises
836
+ ------
837
+ NetworkXError
838
+ If `stringizer` cannot convert a value into a string, or the value to
839
+ convert is not a string while `stringizer` is None.
840
+
841
+ See Also
842
+ --------
843
+ read_gml, generate_gml
844
+ literal_stringizer
845
+
846
+ Notes
847
+ -----
848
+ Graph attributes named 'directed', 'multigraph', 'node' or
849
+ 'edge', node attributes named 'id' or 'label', edge attributes
850
+ named 'source' or 'target' (or 'key' if `G` is a multigraph)
851
+ are ignored because these attribute names are used to encode the graph
852
+ structure.
853
+
854
+ GML files are stored using a 7-bit ASCII encoding with any extended
855
+ ASCII characters (iso8859-1) appearing as HTML character entities.
856
+ Without specifying a `stringizer`/`destringizer`, the code is capable of
857
+ writing `int`/`float`/`str`/`dict`/`list` data as required by the GML
858
+ specification. For writing other data types, and for reading data other
859
+ than `str` you need to explicitly supply a `stringizer`/`destringizer`.
860
+
861
+ Note that while we allow non-standard GML to be read from a file, we make
862
+ sure to write GML format. In particular, underscores are not allowed in
863
+ attribute names.
864
+ For additional documentation on the GML file format, please see the
865
+ `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
866
+
867
+ See the module docstring :mod:`networkx.readwrite.gml` for more details.
868
+
869
+ Examples
870
+ --------
871
+ >>> G = nx.path_graph(4)
872
+ >>> nx.write_gml(G, "test.gml")
873
+
874
+ Filenames ending in .gz or .bz2 will be compressed.
875
+
876
+ >>> nx.write_gml(G, "test.gml.gz")
877
+ """
878
+ for line in generate_gml(G, stringizer):
879
+ path.write((line + "\n").encode("ascii"))
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (865 Bytes). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/adjacency.cpython-310.pyc ADDED
Binary file (4.14 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/tree.cpython-310.pyc ADDED
Binary file (4.11 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/adjacency.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["adjacency_data", "adjacency_graph"]
4
+
5
+ _attrs = {"id": "id", "key": "key"}
6
+
7
+
8
+ def adjacency_data(G, attrs=_attrs):
9
+ """Returns data in adjacency format that is suitable for JSON serialization
10
+ and use in JavaScript documents.
11
+
12
+ Parameters
13
+ ----------
14
+ G : NetworkX graph
15
+
16
+ attrs : dict
17
+ A dictionary that contains two keys 'id' and 'key'. The corresponding
18
+ values provide the attribute names for storing NetworkX-internal graph
19
+ data. The values should be unique. Default value:
20
+ :samp:`dict(id='id', key='key')`.
21
+
22
+ If some user-defined graph data use these attribute names as data keys,
23
+ they may be silently dropped.
24
+
25
+ Returns
26
+ -------
27
+ data : dict
28
+ A dictionary with adjacency formatted data.
29
+
30
+ Raises
31
+ ------
32
+ NetworkXError
33
+ If values in attrs are not unique.
34
+
35
+ Examples
36
+ --------
37
+ >>> from networkx.readwrite import json_graph
38
+ >>> G = nx.Graph([(1, 2)])
39
+ >>> data = json_graph.adjacency_data(G)
40
+
41
+ To serialize with json
42
+
43
+ >>> import json
44
+ >>> s = json.dumps(data)
45
+
46
+ Notes
47
+ -----
48
+ Graph, node, and link attributes will be written when using this format
49
+ but attribute keys must be strings if you want to serialize the resulting
50
+ data with JSON.
51
+
52
+ The default value of attrs will be changed in a future release of NetworkX.
53
+
54
+ See Also
55
+ --------
56
+ adjacency_graph, node_link_data, tree_data
57
+ """
58
+ multigraph = G.is_multigraph()
59
+ id_ = attrs["id"]
60
+ # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
61
+ key = None if not multigraph else attrs["key"]
62
+ if id_ == key:
63
+ raise nx.NetworkXError("Attribute names are not unique.")
64
+ data = {}
65
+ data["directed"] = G.is_directed()
66
+ data["multigraph"] = multigraph
67
+ data["graph"] = list(G.graph.items())
68
+ data["nodes"] = []
69
+ data["adjacency"] = []
70
+ for n, nbrdict in G.adjacency():
71
+ data["nodes"].append({**G.nodes[n], id_: n})
72
+ adj = []
73
+ if multigraph:
74
+ for nbr, keys in nbrdict.items():
75
+ for k, d in keys.items():
76
+ adj.append({**d, id_: nbr, key: k})
77
+ else:
78
+ for nbr, d in nbrdict.items():
79
+ adj.append({**d, id_: nbr})
80
+ data["adjacency"].append(adj)
81
+ return data
82
+
83
+
84
+ @nx._dispatchable(graphs=None, returns_graph=True)
85
+ def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
86
+ """Returns graph from adjacency data format.
87
+
88
+ Parameters
89
+ ----------
90
+ data : dict
91
+ Adjacency list formatted graph data
92
+
93
+ directed : bool
94
+ If True, and direction not specified in data, return a directed graph.
95
+
96
+ multigraph : bool
97
+ If True, and multigraph not specified in data, return a multigraph.
98
+
99
+ attrs : dict
100
+ A dictionary that contains two keys 'id' and 'key'. The corresponding
101
+ values provide the attribute names for storing NetworkX-internal graph
102
+ data. The values should be unique. Default value:
103
+ :samp:`dict(id='id', key='key')`.
104
+
105
+ Returns
106
+ -------
107
+ G : NetworkX graph
108
+ A NetworkX graph object
109
+
110
+ Examples
111
+ --------
112
+ >>> from networkx.readwrite import json_graph
113
+ >>> G = nx.Graph([(1, 2)])
114
+ >>> data = json_graph.adjacency_data(G)
115
+ >>> H = json_graph.adjacency_graph(data)
116
+
117
+ Notes
118
+ -----
119
+ The default value of attrs will be changed in a future release of NetworkX.
120
+
121
+ See Also
122
+ --------
123
+ adjacency_graph, node_link_data, tree_data
124
+ """
125
+ multigraph = data.get("multigraph", multigraph)
126
+ directed = data.get("directed", directed)
127
+ if multigraph:
128
+ graph = nx.MultiGraph()
129
+ else:
130
+ graph = nx.Graph()
131
+ if directed:
132
+ graph = graph.to_directed()
133
+ id_ = attrs["id"]
134
+ # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
135
+ key = None if not multigraph else attrs["key"]
136
+ graph.graph = dict(data.get("graph", []))
137
+ mapping = []
138
+ for d in data["nodes"]:
139
+ node_data = d.copy()
140
+ node = node_data.pop(id_)
141
+ mapping.append(node)
142
+ graph.add_node(node)
143
+ graph.nodes[node].update(node_data)
144
+ for i, d in enumerate(data["adjacency"]):
145
+ source = mapping[i]
146
+ for tdata in d:
147
+ target_data = tdata.copy()
148
+ target = target_data.pop(id_)
149
+ if not multigraph:
150
+ graph.add_edge(source, target)
151
+ graph[source][target].update(target_data)
152
+ else:
153
+ ky = target_data.pop(key, None)
154
+ graph.add_edge(source, target, key=ky)
155
+ graph[source][target][ky].update(target_data)
156
+ return graph
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/cytoscape.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["cytoscape_data", "cytoscape_graph"]
4
+
5
+
6
+ def cytoscape_data(G, name="name", ident="id"):
7
+ """Returns data in Cytoscape JSON format (cyjs).
8
+
9
+ Parameters
10
+ ----------
11
+ G : NetworkX Graph
12
+ The graph to convert to cytoscape format
13
+ name : string
14
+ A string which is mapped to the 'name' node element in cyjs format.
15
+ Must not have the same value as `ident`.
16
+ ident : string
17
+ A string which is mapped to the 'id' node element in cyjs format.
18
+ Must not have the same value as `name`.
19
+
20
+ Returns
21
+ -------
22
+ data: dict
23
+ A dictionary with cyjs formatted data.
24
+
25
+ Raises
26
+ ------
27
+ NetworkXError
28
+ If the values for `name` and `ident` are identical.
29
+
30
+ See Also
31
+ --------
32
+ cytoscape_graph: convert a dictionary in cyjs format to a graph
33
+
34
+ References
35
+ ----------
36
+ .. [1] Cytoscape user's manual:
37
+ http://manual.cytoscape.org/en/stable/index.html
38
+
39
+ Examples
40
+ --------
41
+ >>> G = nx.path_graph(2)
42
+ >>> nx.cytoscape_data(G) # doctest: +SKIP
43
+ {'data': [],
44
+ 'directed': False,
45
+ 'multigraph': False,
46
+ 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
47
+ {'data': {'id': '1', 'value': 1, 'name': '1'}}],
48
+ 'edges': [{'data': {'source': 0, 'target': 1}}]}}
49
+ """
50
+ if name == ident:
51
+ raise nx.NetworkXError("name and ident must be different.")
52
+
53
+ jsondata = {"data": list(G.graph.items())}
54
+ jsondata["directed"] = G.is_directed()
55
+ jsondata["multigraph"] = G.is_multigraph()
56
+ jsondata["elements"] = {"nodes": [], "edges": []}
57
+ nodes = jsondata["elements"]["nodes"]
58
+ edges = jsondata["elements"]["edges"]
59
+
60
+ for i, j in G.nodes.items():
61
+ n = {"data": j.copy()}
62
+ n["data"]["id"] = j.get(ident) or str(i)
63
+ n["data"]["value"] = i
64
+ n["data"]["name"] = j.get(name) or str(i)
65
+ nodes.append(n)
66
+
67
+ if G.is_multigraph():
68
+ for e in G.edges(keys=True):
69
+ n = {"data": G.adj[e[0]][e[1]][e[2]].copy()}
70
+ n["data"]["source"] = e[0]
71
+ n["data"]["target"] = e[1]
72
+ n["data"]["key"] = e[2]
73
+ edges.append(n)
74
+ else:
75
+ for e in G.edges():
76
+ n = {"data": G.adj[e[0]][e[1]].copy()}
77
+ n["data"]["source"] = e[0]
78
+ n["data"]["target"] = e[1]
79
+ edges.append(n)
80
+ return jsondata
81
+
82
+
83
+ @nx._dispatchable(graphs=None, returns_graph=True)
84
+ def cytoscape_graph(data, name="name", ident="id"):
85
+ """
86
+ Create a NetworkX graph from a dictionary in cytoscape JSON format.
87
+
88
+ Parameters
89
+ ----------
90
+ data : dict
91
+ A dictionary of data conforming to cytoscape JSON format.
92
+ name : string
93
+ A string which is mapped to the 'name' node element in cyjs format.
94
+ Must not have the same value as `ident`.
95
+ ident : string
96
+ A string which is mapped to the 'id' node element in cyjs format.
97
+ Must not have the same value as `name`.
98
+
99
+ Returns
100
+ -------
101
+ graph : a NetworkX graph instance
102
+ The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or
103
+ `MultiDiGraph` depending on the input data.
104
+
105
+ Raises
106
+ ------
107
+ NetworkXError
108
+ If the `name` and `ident` attributes are identical.
109
+
110
+ See Also
111
+ --------
112
+ cytoscape_data: convert a NetworkX graph to a dict in cyjs format
113
+
114
+ References
115
+ ----------
116
+ .. [1] Cytoscape user's manual:
117
+ http://manual.cytoscape.org/en/stable/index.html
118
+
119
+ Examples
120
+ --------
121
+ >>> data_dict = {
122
+ ... "data": [],
123
+ ... "directed": False,
124
+ ... "multigraph": False,
125
+ ... "elements": {
126
+ ... "nodes": [
127
+ ... {"data": {"id": "0", "value": 0, "name": "0"}},
128
+ ... {"data": {"id": "1", "value": 1, "name": "1"}},
129
+ ... ],
130
+ ... "edges": [{"data": {"source": 0, "target": 1}}],
131
+ ... },
132
+ ... }
133
+ >>> G = nx.cytoscape_graph(data_dict)
134
+ >>> G.name
135
+ ''
136
+ >>> G.nodes()
137
+ NodeView((0, 1))
138
+ >>> G.nodes(data=True)[0]
139
+ {'id': '0', 'value': 0, 'name': '0'}
140
+ >>> G.edges(data=True)
141
+ EdgeDataView([(0, 1, {'source': 0, 'target': 1})])
142
+ """
143
+ if name == ident:
144
+ raise nx.NetworkXError("name and ident must be different.")
145
+
146
+ multigraph = data.get("multigraph")
147
+ directed = data.get("directed")
148
+ if multigraph:
149
+ graph = nx.MultiGraph()
150
+ else:
151
+ graph = nx.Graph()
152
+ if directed:
153
+ graph = graph.to_directed()
154
+ graph.graph = dict(data.get("data"))
155
+ for d in data["elements"]["nodes"]:
156
+ node_data = d["data"].copy()
157
+ node = d["data"]["value"]
158
+
159
+ if d["data"].get(name):
160
+ node_data[name] = d["data"].get(name)
161
+ if d["data"].get(ident):
162
+ node_data[ident] = d["data"].get(ident)
163
+
164
+ graph.add_node(node)
165
+ graph.nodes[node].update(node_data)
166
+
167
+ for d in data["elements"]["edges"]:
168
+ edge_data = d["data"].copy()
169
+ sour = d["data"]["source"]
170
+ targ = d["data"]["target"]
171
+ if multigraph:
172
+ key = d["data"].get("key", 0)
173
+ graph.add_edge(sour, targ, key=key)
174
+ graph.edges[sour, targ, key].update(edge_data)
175
+ else:
176
+ graph.add_edge(sour, targ)
177
+ graph.edges[sour, targ].update(edge_data)
178
+ return graph
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/node_link.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from itertools import count
3
+
4
+ import networkx as nx
5
+
6
+ __all__ = ["node_link_data", "node_link_graph"]
7
+
8
+
9
+ def _to_tuple(x):
10
+ """Converts lists to tuples, including nested lists.
11
+
12
+ All other non-list inputs are passed through unmodified. This function is
13
+ intended to be used to convert potentially nested lists from json files
14
+ into valid nodes.
15
+
16
+ Examples
17
+ --------
18
+ >>> _to_tuple([1, 2, [3, 4]])
19
+ (1, 2, (3, 4))
20
+ """
21
+ if not isinstance(x, tuple | list):
22
+ return x
23
+ return tuple(map(_to_tuple, x))
24
+
25
+
26
+ def node_link_data(
27
+ G,
28
+ *,
29
+ source="source",
30
+ target="target",
31
+ name="id",
32
+ key="key",
33
+ edges=None,
34
+ nodes="nodes",
35
+ link=None,
36
+ ):
37
+ """Returns data in node-link format that is suitable for JSON serialization
38
+ and use in JavaScript documents.
39
+
40
+ Parameters
41
+ ----------
42
+ G : NetworkX graph
43
+ source : string
44
+ A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
45
+ target : string
46
+ A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
47
+ name : string
48
+ A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
49
+ key : string
50
+ A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
51
+ edges : string
52
+ A string that provides the 'edges' attribute name for storing NetworkX-internal graph data.
53
+ nodes : string
54
+ A string that provides the 'nodes' attribute name for storing NetworkX-internal graph data.
55
+ link : string
56
+ .. deprecated:: 3.4
57
+
58
+ The `link` argument is deprecated and will be removed in version `3.6`.
59
+ Use the `edges` keyword instead.
60
+
61
+ A string that provides the 'edges' attribute name for storing NetworkX-internal graph data.
62
+
63
+ Returns
64
+ -------
65
+ data : dict
66
+ A dictionary with node-link formatted data.
67
+
68
+ Raises
69
+ ------
70
+ NetworkXError
71
+ If the values of 'source', 'target' and 'key' are not unique.
72
+
73
+ Examples
74
+ --------
75
+ >>> from pprint import pprint
76
+ >>> G = nx.Graph([("A", "B")])
77
+ >>> data1 = nx.node_link_data(G, edges="edges")
78
+ >>> pprint(data1)
79
+ {'directed': False,
80
+ 'edges': [{'source': 'A', 'target': 'B'}],
81
+ 'graph': {},
82
+ 'multigraph': False,
83
+ 'nodes': [{'id': 'A'}, {'id': 'B'}]}
84
+
85
+ To serialize with JSON
86
+
87
+ >>> import json
88
+ >>> s1 = json.dumps(data1)
89
+ >>> s1
90
+ '{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "edges": [{"source": "A", "target": "B"}]}'
91
+
92
+ A graph can also be serialized by passing `node_link_data` as an encoder function.
93
+
94
+ >>> s1 = json.dumps(G, default=nx.node_link_data)
95
+ >>> s1
96
+ '{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
97
+
98
+ The attribute names for storing NetworkX-internal graph data can
99
+ be specified as keyword options.
100
+
101
+ >>> H = nx.gn_graph(2)
102
+ >>> data2 = nx.node_link_data(
103
+ ... H, edges="links", source="from", target="to", nodes="vertices"
104
+ ... )
105
+ >>> pprint(data2)
106
+ {'directed': True,
107
+ 'graph': {},
108
+ 'links': [{'from': 1, 'to': 0}],
109
+ 'multigraph': False,
110
+ 'vertices': [{'id': 0}, {'id': 1}]}
111
+
112
+ Notes
113
+ -----
114
+ Graph, node, and link attributes are stored in this format. Note that
115
+ attribute keys will be converted to strings in order to comply with JSON.
116
+
117
+ Attribute 'key' is only used for multigraphs.
118
+
119
+ To use `node_link_data` in conjunction with `node_link_graph`,
120
+ the keyword names for the attributes must match.
121
+
122
+ See Also
123
+ --------
124
+ node_link_graph, adjacency_data, tree_data
125
+ """
126
+ # TODO: Remove between the lines when `link` deprecation expires
127
+ # -------------------------------------------------------------
128
+ if link is not None:
129
+ warnings.warn(
130
+ "Keyword argument 'link' is deprecated; use 'edges' instead",
131
+ DeprecationWarning,
132
+ stacklevel=2,
133
+ )
134
+ if edges is not None:
135
+ raise ValueError(
136
+ "Both 'edges' and 'link' are specified. Use 'edges', 'link' will be remove in a future release"
137
+ )
138
+ else:
139
+ edges = link
140
+ else:
141
+ if edges is None:
142
+ warnings.warn(
143
+ (
144
+ '\nThe default value will be `edges="edges" in NetworkX 3.6.\n\n'
145
+ "To make this warning go away, explicitly set the edges kwarg, e.g.:\n\n"
146
+ ' nx.node_link_data(G, edges="links") to preserve current behavior, or\n'
147
+ ' nx.node_link_data(G, edges="edges") for forward compatibility.'
148
+ ),
149
+ FutureWarning,
150
+ )
151
+ edges = "links"
152
+ # ------------------------------------------------------------
153
+
154
+ multigraph = G.is_multigraph()
155
+
156
+ # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
157
+ key = None if not multigraph else key
158
+ if len({source, target, key}) < 3:
159
+ raise nx.NetworkXError("Attribute names are not unique.")
160
+ data = {
161
+ "directed": G.is_directed(),
162
+ "multigraph": multigraph,
163
+ "graph": G.graph,
164
+ nodes: [{**G.nodes[n], name: n} for n in G],
165
+ }
166
+ if multigraph:
167
+ data[edges] = [
168
+ {**d, source: u, target: v, key: k}
169
+ for u, v, k, d in G.edges(keys=True, data=True)
170
+ ]
171
+ else:
172
+ data[edges] = [{**d, source: u, target: v} for u, v, d in G.edges(data=True)]
173
+ return data
174
+
175
+
176
+ @nx._dispatchable(graphs=None, returns_graph=True)
177
+ def node_link_graph(
178
+ data,
179
+ directed=False,
180
+ multigraph=True,
181
+ *,
182
+ source="source",
183
+ target="target",
184
+ name="id",
185
+ key="key",
186
+ edges=None,
187
+ nodes="nodes",
188
+ link=None,
189
+ ):
190
+ """Returns graph from node-link data format.
191
+
192
+ Useful for de-serialization from JSON.
193
+
194
+ Parameters
195
+ ----------
196
+ data : dict
197
+ node-link formatted graph data
198
+
199
+ directed : bool
200
+ If True, and direction not specified in data, return a directed graph.
201
+
202
+ multigraph : bool
203
+ If True, and multigraph not specified in data, return a multigraph.
204
+
205
+ source : string
206
+ A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
207
+ target : string
208
+ A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
209
+ name : string
210
+ A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
211
+ key : string
212
+ A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
213
+ edges : string
214
+ A string that provides the 'edges' attribute name for storing NetworkX-internal graph data.
215
+ nodes : string
216
+ A string that provides the 'nodes' attribute name for storing NetworkX-internal graph data.
217
+ link : string
218
+ .. deprecated:: 3.4
219
+
220
+ The `link` argument is deprecated and will be removed in version `3.6`.
221
+ Use the `edges` keyword instead.
222
+
223
+ A string that provides the 'edges' attribute name for storing NetworkX-internal graph data.
224
+
225
+ Returns
226
+ -------
227
+ G : NetworkX graph
228
+ A NetworkX graph object
229
+
230
+ Examples
231
+ --------
232
+
233
+ Create data in node-link format by converting a graph.
234
+
235
+ >>> from pprint import pprint
236
+ >>> G = nx.Graph([("A", "B")])
237
+ >>> data = nx.node_link_data(G, edges="edges")
238
+ >>> pprint(data)
239
+ {'directed': False,
240
+ 'edges': [{'source': 'A', 'target': 'B'}],
241
+ 'graph': {},
242
+ 'multigraph': False,
243
+ 'nodes': [{'id': 'A'}, {'id': 'B'}]}
244
+
245
+ Revert data in node-link format to a graph.
246
+
247
+ >>> H = nx.node_link_graph(data, edges="edges")
248
+ >>> print(H.edges)
249
+ [('A', 'B')]
250
+
251
+ To serialize and deserialize a graph with JSON,
252
+
253
+ >>> import json
254
+ >>> d = json.dumps(nx.node_link_data(G, edges="edges"))
255
+ >>> H = nx.node_link_graph(json.loads(d), edges="edges")
256
+ >>> print(G.edges, H.edges)
257
+ [('A', 'B')] [('A', 'B')]
258
+
259
+
260
+ Notes
261
+ -----
262
+ Attribute 'key' is only used for multigraphs.
263
+
264
+ To use `node_link_data` in conjunction with `node_link_graph`,
265
+ the keyword names for the attributes must match.
266
+
267
+ See Also
268
+ --------
269
+ node_link_data, adjacency_data, tree_data
270
+ """
271
+ # TODO: Remove between the lines when `link` deprecation expires
272
+ # -------------------------------------------------------------
273
+ if link is not None:
274
+ warnings.warn(
275
+ "Keyword argument 'link' is deprecated; use 'edges' instead",
276
+ DeprecationWarning,
277
+ stacklevel=2,
278
+ )
279
+ if edges is not None:
280
+ raise ValueError(
281
+ "Both 'edges' and 'link' are specified. Use 'edges', 'link' will be remove in a future release"
282
+ )
283
+ else:
284
+ edges = link
285
+ else:
286
+ if edges is None:
287
+ warnings.warn(
288
+ (
289
+ '\nThe default value will be changed to `edges="edges" in NetworkX 3.6.\n\n'
290
+ "To make this warning go away, explicitly set the edges kwarg, e.g.:\n\n"
291
+ ' nx.node_link_graph(data, edges="links") to preserve current behavior, or\n'
292
+ ' nx.node_link_graph(data, edges="edges") for forward compatibility.'
293
+ ),
294
+ FutureWarning,
295
+ )
296
+ edges = "links"
297
+ # -------------------------------------------------------------
298
+
299
+ multigraph = data.get("multigraph", multigraph)
300
+ directed = data.get("directed", directed)
301
+ if multigraph:
302
+ graph = nx.MultiGraph()
303
+ else:
304
+ graph = nx.Graph()
305
+ if directed:
306
+ graph = graph.to_directed()
307
+
308
+ # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
309
+ key = None if not multigraph else key
310
+ graph.graph = data.get("graph", {})
311
+ c = count()
312
+ for d in data[nodes]:
313
+ node = _to_tuple(d.get(name, next(c)))
314
+ nodedata = {str(k): v for k, v in d.items() if k != name}
315
+ graph.add_node(node, **nodedata)
316
+ for d in data[edges]:
317
+ src = tuple(d[source]) if isinstance(d[source], list) else d[source]
318
+ tgt = tuple(d[target]) if isinstance(d[target], list) else d[target]
319
+ if not multigraph:
320
+ edgedata = {str(k): v for k, v in d.items() if k != source and k != target}
321
+ graph.add_edge(src, tgt, **edgedata)
322
+ else:
323
+ ky = d.get(key, None)
324
+ edgedata = {
325
+ str(k): v
326
+ for k, v in d.items()
327
+ if k != source and k != target and k != key
328
+ }
329
+ graph.add_edge(src, tgt, ky, **edgedata)
330
+ return graph
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_adjacency.cpython-310.pyc ADDED
Binary file (3.18 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_cytoscape.cpython-310.pyc ADDED
Binary file (2.54 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/json_graph/tests/test_adjacency.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.readwrite.json_graph import adjacency_data, adjacency_graph
8
+ from networkx.utils import graphs_equal
9
+
10
+
11
+ class TestAdjacency:
12
+ def test_graph(self):
13
+ G = nx.path_graph(4)
14
+ H = adjacency_graph(adjacency_data(G))
15
+ assert graphs_equal(G, H)
16
+
17
+ def test_graph_attributes(self):
18
+ G = nx.path_graph(4)
19
+ G.add_node(1, color="red")
20
+ G.add_edge(1, 2, width=7)
21
+ G.graph["foo"] = "bar"
22
+ G.graph[1] = "one"
23
+
24
+ H = adjacency_graph(adjacency_data(G))
25
+ assert graphs_equal(G, H)
26
+ assert H.graph["foo"] == "bar"
27
+ assert H.nodes[1]["color"] == "red"
28
+ assert H[1][2]["width"] == 7
29
+
30
+ d = json.dumps(adjacency_data(G))
31
+ H = adjacency_graph(json.loads(d))
32
+ assert graphs_equal(G, H)
33
+ assert H.graph["foo"] == "bar"
34
+ assert H.graph[1] == "one"
35
+ assert H.nodes[1]["color"] == "red"
36
+ assert H[1][2]["width"] == 7
37
+
38
+ def test_digraph(self):
39
+ G = nx.DiGraph()
40
+ nx.add_path(G, [1, 2, 3])
41
+ H = adjacency_graph(adjacency_data(G))
42
+ assert H.is_directed()
43
+ assert graphs_equal(G, H)
44
+
45
+ def test_multidigraph(self):
46
+ G = nx.MultiDiGraph()
47
+ nx.add_path(G, [1, 2, 3])
48
+ H = adjacency_graph(adjacency_data(G))
49
+ assert H.is_directed()
50
+ assert H.is_multigraph()
51
+ assert graphs_equal(G, H)
52
+
53
+ def test_multigraph(self):
54
+ G = nx.MultiGraph()
55
+ G.add_edge(1, 2, key="first")
56
+ G.add_edge(1, 2, key="second", color="blue")
57
+ H = adjacency_graph(adjacency_data(G))
58
+ assert graphs_equal(G, H)
59
+ assert H[1][2]["second"]["color"] == "blue"
60
+
61
+ def test_input_data_is_not_modified_when_building_graph(self):
62
+ G = nx.path_graph(4)
63
+ input_data = adjacency_data(G)
64
+ orig_data = copy.deepcopy(input_data)
65
+ # Ensure input is unmodified by deserialisation
66
+ assert graphs_equal(G, adjacency_graph(input_data))
67
+ assert input_data == orig_data
68
+
69
+ def test_adjacency_form_json_serialisable(self):
70
+ G = nx.path_graph(4)
71
+ H = adjacency_graph(json.loads(json.dumps(adjacency_data(G))))
72
+ assert graphs_equal(G, H)
73
+
74
+ def test_exception(self):
75
+ with pytest.raises(nx.NetworkXError):
76
+ G = nx.MultiDiGraph()
77
+ attrs = {"id": "node", "key": "node"}
78
+ adjacency_data(G, attrs)
deepseek/lib/python3.10/site-packages/networkx/readwrite/pajek.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ *****
3
+ Pajek
4
+ *****
5
+ Read graphs in Pajek format.
6
+
7
+ This implementation handles directed and undirected graphs including
8
+ those with self loops and parallel edges.
9
+
10
+ Format
11
+ ------
12
+ See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
13
+ for format information.
14
+
15
+ """
16
+
17
+ import warnings
18
+
19
+ import networkx as nx
20
+ from networkx.utils import open_file
21
+
22
+ __all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"]
23
+
24
+
25
+ def generate_pajek(G):
26
+ """Generate lines in Pajek graph format.
27
+
28
+ Parameters
29
+ ----------
30
+ G : graph
31
+ A Networkx graph
32
+
33
+ References
34
+ ----------
35
+ See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
36
+ for format information.
37
+ """
38
+ if G.name == "":
39
+ name = "NetworkX"
40
+ else:
41
+ name = G.name
42
+ # Apparently many Pajek format readers can't process this line
43
+ # So we'll leave it out for now.
44
+ # yield '*network %s'%name
45
+
46
+ # write nodes with attributes
47
+ yield f"*vertices {G.order()}"
48
+ nodes = list(G)
49
+ # make dictionary mapping nodes to integers
50
+ nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
51
+ for n in nodes:
52
+ # copy node attributes and pop mandatory attributes
53
+ # to avoid duplication.
54
+ na = G.nodes.get(n, {}).copy()
55
+ x = na.pop("x", 0.0)
56
+ y = na.pop("y", 0.0)
57
+ try:
58
+ id = int(na.pop("id", nodenumber[n]))
59
+ except ValueError as err:
60
+ err.args += (
61
+ (
62
+ "Pajek format requires 'id' to be an int()."
63
+ " Refer to the 'Relabeling nodes' section."
64
+ ),
65
+ )
66
+ raise
67
+ nodenumber[n] = id
68
+ shape = na.pop("shape", "ellipse")
69
+ s = " ".join(map(make_qstr, (id, n, x, y, shape)))
70
+ # only optional attributes are left in na.
71
+ for k, v in na.items():
72
+ if isinstance(v, str) and v.strip() != "":
73
+ s += f" {make_qstr(k)} {make_qstr(v)}"
74
+ else:
75
+ warnings.warn(
76
+ f"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
77
+ )
78
+ yield s
79
+
80
+ # write edges with attributes
81
+ if G.is_directed():
82
+ yield "*arcs"
83
+ else:
84
+ yield "*edges"
85
+ for u, v, edgedata in G.edges(data=True):
86
+ d = edgedata.copy()
87
+ value = d.pop("weight", 1.0) # use 1 as default edge value
88
+ s = " ".join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
89
+ for k, v in d.items():
90
+ if isinstance(v, str) and v.strip() != "":
91
+ s += f" {make_qstr(k)} {make_qstr(v)}"
92
+ else:
93
+ warnings.warn(
94
+ f"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
95
+ )
96
+ yield s
97
+
98
+
99
+ @open_file(1, mode="wb")
100
+ def write_pajek(G, path, encoding="UTF-8"):
101
+ """Write graph in Pajek format to path.
102
+
103
+ Parameters
104
+ ----------
105
+ G : graph
106
+ A Networkx graph
107
+ path : file or string
108
+ File or filename to write.
109
+ Filenames ending in .gz or .bz2 will be compressed.
110
+
111
+ Examples
112
+ --------
113
+ >>> G = nx.path_graph(4)
114
+ >>> nx.write_pajek(G, "test.net")
115
+
116
+ Warnings
117
+ --------
118
+ Optional node attributes and edge attributes must be non-empty strings.
119
+ Otherwise it will not be written into the file. You will need to
120
+ convert those attributes to strings if you want to keep them.
121
+
122
+ References
123
+ ----------
124
+ See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
125
+ for format information.
126
+ """
127
+ for line in generate_pajek(G):
128
+ line += "\n"
129
+ path.write(line.encode(encoding))
130
+
131
+
132
+ @open_file(0, mode="rb")
133
+ @nx._dispatchable(graphs=None, returns_graph=True)
134
+ def read_pajek(path, encoding="UTF-8"):
135
+ """Read graph in Pajek format from path.
136
+
137
+ Parameters
138
+ ----------
139
+ path : file or string
140
+ File or filename to write.
141
+ Filenames ending in .gz or .bz2 will be uncompressed.
142
+
143
+ Returns
144
+ -------
145
+ G : NetworkX MultiGraph or MultiDiGraph.
146
+
147
+ Examples
148
+ --------
149
+ >>> G = nx.path_graph(4)
150
+ >>> nx.write_pajek(G, "test.net")
151
+ >>> G = nx.read_pajek("test.net")
152
+
153
+ To create a Graph instead of a MultiGraph use
154
+
155
+ >>> G1 = nx.Graph(G)
156
+
157
+ References
158
+ ----------
159
+ See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
160
+ for format information.
161
+ """
162
+ lines = (line.decode(encoding) for line in path)
163
+ return parse_pajek(lines)
164
+
165
+
166
+ @nx._dispatchable(graphs=None, returns_graph=True)
167
+ def parse_pajek(lines):
168
+ """Parse Pajek format graph from string or iterable.
169
+
170
+ Parameters
171
+ ----------
172
+ lines : string or iterable
173
+ Data in Pajek format.
174
+
175
+ Returns
176
+ -------
177
+ G : NetworkX graph
178
+
179
+ See Also
180
+ --------
181
+ read_pajek
182
+
183
+ """
184
+ import shlex
185
+
186
+ # multigraph=False
187
+ if isinstance(lines, str):
188
+ lines = iter(lines.split("\n"))
189
+ lines = iter([line.rstrip("\n") for line in lines])
190
+ G = nx.MultiDiGraph() # are multiedges allowed in Pajek? assume yes
191
+ labels = [] # in the order of the file, needed for matrix
192
+ while lines:
193
+ try:
194
+ l = next(lines)
195
+ except: # EOF
196
+ break
197
+ if l.lower().startswith("*network"):
198
+ try:
199
+ label, name = l.split(None, 1)
200
+ except ValueError:
201
+ # Line was not of the form: *network NAME
202
+ pass
203
+ else:
204
+ G.graph["name"] = name
205
+ elif l.lower().startswith("*vertices"):
206
+ nodelabels = {}
207
+ l, nnodes = l.split()
208
+ for i in range(int(nnodes)):
209
+ l = next(lines)
210
+ try:
211
+ splitline = [
212
+ x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
213
+ ]
214
+ except AttributeError:
215
+ splitline = shlex.split(str(l))
216
+ id, label = splitline[0:2]
217
+ labels.append(label)
218
+ G.add_node(label)
219
+ nodelabels[id] = label
220
+ G.nodes[label]["id"] = id
221
+ try:
222
+ x, y, shape = splitline[2:5]
223
+ G.nodes[label].update(
224
+ {"x": float(x), "y": float(y), "shape": shape}
225
+ )
226
+ except:
227
+ pass
228
+ extra_attr = zip(splitline[5::2], splitline[6::2])
229
+ G.nodes[label].update(extra_attr)
230
+ elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
231
+ if l.lower().startswith("*edge"):
232
+ # switch from multidigraph to multigraph
233
+ G = nx.MultiGraph(G)
234
+ if l.lower().startswith("*arcs"):
235
+ # switch to directed with multiple arcs for each existing edge
236
+ G = G.to_directed()
237
+ for l in lines:
238
+ try:
239
+ splitline = [
240
+ x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
241
+ ]
242
+ except AttributeError:
243
+ splitline = shlex.split(str(l))
244
+
245
+ if len(splitline) < 2:
246
+ continue
247
+ ui, vi = splitline[0:2]
248
+ u = nodelabels.get(ui, ui)
249
+ v = nodelabels.get(vi, vi)
250
+ # parse the data attached to this edge and put in a dictionary
251
+ edge_data = {}
252
+ try:
253
+ # there should always be a single value on the edge?
254
+ w = splitline[2:3]
255
+ edge_data.update({"weight": float(w[0])})
256
+ except:
257
+ pass
258
+ # if there isn't, just assign a 1
259
+ # edge_data.update({'value':1})
260
+ extra_attr = zip(splitline[3::2], splitline[4::2])
261
+ edge_data.update(extra_attr)
262
+ # if G.has_edge(u,v):
263
+ # multigraph=True
264
+ G.add_edge(u, v, **edge_data)
265
+ elif l.lower().startswith("*matrix"):
266
+ G = nx.DiGraph(G)
267
+ adj_list = (
268
+ (labels[row], labels[col], {"weight": int(data)})
269
+ for (row, line) in enumerate(lines)
270
+ for (col, data) in enumerate(line.split())
271
+ if int(data) != 0
272
+ )
273
+ G.add_edges_from(adj_list)
274
+
275
+ return G
276
+
277
+
278
+ def make_qstr(t):
279
+ """Returns the string representation of t.
280
+ Add outer double-quotes if the string has a space.
281
+ """
282
+ if not isinstance(t, str):
283
+ t = str(t)
284
+ if " " in t:
285
+ t = f'"{t}"'
286
+ return t
deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (178 Bytes). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/test_graphml.cpython-310.pyc ADDED
Binary file (62.4 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/test_text.cpython-310.pyc ADDED
Binary file (50.5 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/test_gml.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ import io
3
+ import math
4
+ from ast import literal_eval
5
+ from contextlib import contextmanager
6
+ from textwrap import dedent
7
+
8
+ import pytest
9
+
10
+ import networkx as nx
11
+ from networkx.readwrite.gml import literal_destringizer, literal_stringizer
12
+
13
+
14
+ class TestGraph:
15
+ @classmethod
16
+ def setup_class(cls):
17
+ cls.simple_data = """Creator "me"
18
+ Version "xx"
19
+ graph [
20
+ comment "This is a sample graph"
21
+ directed 1
22
+ IsPlanar 1
23
+ pos [ x 0 y 1 ]
24
+ node [
25
+ id 1
26
+ label "Node 1"
27
+ pos [ x 1 y 1 ]
28
+ ]
29
+ node [
30
+ id 2
31
+ pos [ x 1 y 2 ]
32
+ label "Node 2"
33
+ ]
34
+ node [
35
+ id 3
36
+ label "Node 3"
37
+ pos [ x 1 y 3 ]
38
+ ]
39
+ edge [
40
+ source 1
41
+ target 2
42
+ label "Edge from node 1 to node 2"
43
+ color [line "blue" thickness 3]
44
+
45
+ ]
46
+ edge [
47
+ source 2
48
+ target 3
49
+ label "Edge from node 2 to node 3"
50
+ ]
51
+ edge [
52
+ source 3
53
+ target 1
54
+ label "Edge from node 3 to node 1"
55
+ ]
56
+ ]
57
+ """
58
+
59
+ def test_parse_gml_cytoscape_bug(self):
60
+ # example from issue #321, originally #324 in trac
61
+ cytoscape_example = """
62
+ Creator "Cytoscape"
63
+ Version 1.0
64
+ graph [
65
+ node [
66
+ root_index -3
67
+ id -3
68
+ graphics [
69
+ x -96.0
70
+ y -67.0
71
+ w 40.0
72
+ h 40.0
73
+ fill "#ff9999"
74
+ type "ellipse"
75
+ outline "#666666"
76
+ outline_width 1.5
77
+ ]
78
+ label "node2"
79
+ ]
80
+ node [
81
+ root_index -2
82
+ id -2
83
+ graphics [
84
+ x 63.0
85
+ y 37.0
86
+ w 40.0
87
+ h 40.0
88
+ fill "#ff9999"
89
+ type "ellipse"
90
+ outline "#666666"
91
+ outline_width 1.5
92
+ ]
93
+ label "node1"
94
+ ]
95
+ node [
96
+ root_index -1
97
+ id -1
98
+ graphics [
99
+ x -31.0
100
+ y -17.0
101
+ w 40.0
102
+ h 40.0
103
+ fill "#ff9999"
104
+ type "ellipse"
105
+ outline "#666666"
106
+ outline_width 1.5
107
+ ]
108
+ label "node0"
109
+ ]
110
+ edge [
111
+ root_index -2
112
+ target -2
113
+ source -1
114
+ graphics [
115
+ width 1.5
116
+ fill "#0000ff"
117
+ type "line"
118
+ Line [
119
+ ]
120
+ source_arrow 0
121
+ target_arrow 3
122
+ ]
123
+ label "DirectedEdge"
124
+ ]
125
+ edge [
126
+ root_index -1
127
+ target -1
128
+ source -3
129
+ graphics [
130
+ width 1.5
131
+ fill "#0000ff"
132
+ type "line"
133
+ Line [
134
+ ]
135
+ source_arrow 0
136
+ target_arrow 3
137
+ ]
138
+ label "DirectedEdge"
139
+ ]
140
+ ]
141
+ """
142
+ nx.parse_gml(cytoscape_example)
143
+
144
+ def test_parse_gml(self):
145
+ G = nx.parse_gml(self.simple_data, label="label")
146
+ assert sorted(G.nodes()) == ["Node 1", "Node 2", "Node 3"]
147
+ assert sorted(G.edges()) == [
148
+ ("Node 1", "Node 2"),
149
+ ("Node 2", "Node 3"),
150
+ ("Node 3", "Node 1"),
151
+ ]
152
+
153
+ assert sorted(G.edges(data=True)) == [
154
+ (
155
+ "Node 1",
156
+ "Node 2",
157
+ {
158
+ "color": {"line": "blue", "thickness": 3},
159
+ "label": "Edge from node 1 to node 2",
160
+ },
161
+ ),
162
+ ("Node 2", "Node 3", {"label": "Edge from node 2 to node 3"}),
163
+ ("Node 3", "Node 1", {"label": "Edge from node 3 to node 1"}),
164
+ ]
165
+
166
+ def test_read_gml(self, tmp_path):
167
+ fname = tmp_path / "test.gml"
168
+ with open(fname, "w") as fh:
169
+ fh.write(self.simple_data)
170
+ Gin = nx.read_gml(fname, label="label")
171
+ G = nx.parse_gml(self.simple_data, label="label")
172
+ assert sorted(G.nodes(data=True)) == sorted(Gin.nodes(data=True))
173
+ assert sorted(G.edges(data=True)) == sorted(Gin.edges(data=True))
174
+
175
+ def test_labels_are_strings(self):
176
+ # GML requires labels to be strings (i.e., in quotes)
177
+ answer = """graph [
178
+ node [
179
+ id 0
180
+ label "1203"
181
+ ]
182
+ ]"""
183
+ G = nx.Graph()
184
+ G.add_node(1203)
185
+ data = "\n".join(nx.generate_gml(G, stringizer=literal_stringizer))
186
+ assert data == answer
187
+
188
+ def test_relabel_duplicate(self):
189
+ data = """
190
+ graph
191
+ [
192
+ label ""
193
+ directed 1
194
+ node
195
+ [
196
+ id 0
197
+ label "same"
198
+ ]
199
+ node
200
+ [
201
+ id 1
202
+ label "same"
203
+ ]
204
+ ]
205
+ """
206
+ fh = io.BytesIO(data.encode("UTF-8"))
207
+ fh.seek(0)
208
+ pytest.raises(nx.NetworkXError, nx.read_gml, fh, label="label")
209
+
210
+ @pytest.mark.parametrize("stringizer", (None, literal_stringizer))
211
+ def test_tuplelabels(self, stringizer):
212
+ # https://github.com/networkx/networkx/pull/1048
213
+ # Writing tuple labels to GML failed.
214
+ G = nx.Graph()
215
+ G.add_edge((0, 1), (1, 0))
216
+ data = "\n".join(nx.generate_gml(G, stringizer=stringizer))
217
+ answer = """graph [
218
+ node [
219
+ id 0
220
+ label "(0,1)"
221
+ ]
222
+ node [
223
+ id 1
224
+ label "(1,0)"
225
+ ]
226
+ edge [
227
+ source 0
228
+ target 1
229
+ ]
230
+ ]"""
231
+ assert data == answer
232
+
233
+ def test_quotes(self, tmp_path):
234
+ # https://github.com/networkx/networkx/issues/1061
235
+ # Encoding quotes as HTML entities.
236
+ G = nx.path_graph(1)
237
+ G.name = "path_graph(1)"
238
+ attr = 'This is "quoted" and this is a copyright: ' + chr(169)
239
+ G.nodes[0]["demo"] = attr
240
+ with open(tmp_path / "test.gml", "w+b") as fobj:
241
+ nx.write_gml(G, fobj)
242
+ fobj.seek(0)
243
+ # Should be bytes in 2.x and 3.x
244
+ data = fobj.read().strip().decode("ascii")
245
+ answer = """graph [
246
+ name "path_graph(1)"
247
+ node [
248
+ id 0
249
+ label "0"
250
+ demo "This is &#34;quoted&#34; and this is a copyright: &#169;"
251
+ ]
252
+ ]"""
253
+ assert data == answer
254
+
255
+ def test_unicode_node(self, tmp_path):
256
+ node = "node" + chr(169)
257
+ G = nx.Graph()
258
+ G.add_node(node)
259
+ with open(tmp_path / "test.gml", "w+b") as fobj:
260
+ nx.write_gml(G, fobj)
261
+ fobj.seek(0)
262
+ # Should be bytes in 2.x and 3.x
263
+ data = fobj.read().strip().decode("ascii")
264
+ answer = """graph [
265
+ node [
266
+ id 0
267
+ label "node&#169;"
268
+ ]
269
+ ]"""
270
+ assert data == answer
271
+
272
+ def test_float_label(self, tmp_path):
273
+ node = 1.0
274
+ G = nx.Graph()
275
+ G.add_node(node)
276
+ with open(tmp_path / "test.gml", "w+b") as fobj:
277
+ nx.write_gml(G, fobj)
278
+ fobj.seek(0)
279
+ # Should be bytes in 2.x and 3.x
280
+ data = fobj.read().strip().decode("ascii")
281
+ answer = """graph [
282
+ node [
283
+ id 0
284
+ label "1.0"
285
+ ]
286
+ ]"""
287
+ assert data == answer
288
+
289
+ def test_special_float_label(self, tmp_path):
290
+ special_floats = [float("nan"), float("+inf"), float("-inf")]
291
+ try:
292
+ import numpy as np
293
+
294
+ special_floats += [np.nan, np.inf, np.inf * -1]
295
+ except ImportError:
296
+ special_floats += special_floats
297
+
298
+ G = nx.cycle_graph(len(special_floats))
299
+ attrs = dict(enumerate(special_floats))
300
+ nx.set_node_attributes(G, attrs, "nodefloat")
301
+ edges = list(G.edges)
302
+ attrs = {edges[i]: value for i, value in enumerate(special_floats)}
303
+ nx.set_edge_attributes(G, attrs, "edgefloat")
304
+
305
+ with open(tmp_path / "test.gml", "w+b") as fobj:
306
+ nx.write_gml(G, fobj)
307
+ fobj.seek(0)
308
+ # Should be bytes in 2.x and 3.x
309
+ data = fobj.read().strip().decode("ascii")
310
+ answer = """graph [
311
+ node [
312
+ id 0
313
+ label "0"
314
+ nodefloat NAN
315
+ ]
316
+ node [
317
+ id 1
318
+ label "1"
319
+ nodefloat +INF
320
+ ]
321
+ node [
322
+ id 2
323
+ label "2"
324
+ nodefloat -INF
325
+ ]
326
+ node [
327
+ id 3
328
+ label "3"
329
+ nodefloat NAN
330
+ ]
331
+ node [
332
+ id 4
333
+ label "4"
334
+ nodefloat +INF
335
+ ]
336
+ node [
337
+ id 5
338
+ label "5"
339
+ nodefloat -INF
340
+ ]
341
+ edge [
342
+ source 0
343
+ target 1
344
+ edgefloat NAN
345
+ ]
346
+ edge [
347
+ source 0
348
+ target 5
349
+ edgefloat +INF
350
+ ]
351
+ edge [
352
+ source 1
353
+ target 2
354
+ edgefloat -INF
355
+ ]
356
+ edge [
357
+ source 2
358
+ target 3
359
+ edgefloat NAN
360
+ ]
361
+ edge [
362
+ source 3
363
+ target 4
364
+ edgefloat +INF
365
+ ]
366
+ edge [
367
+ source 4
368
+ target 5
369
+ edgefloat -INF
370
+ ]
371
+ ]"""
372
+ assert data == answer
373
+
374
+ fobj.seek(0)
375
+ graph = nx.read_gml(fobj)
376
+ for indx, value in enumerate(special_floats):
377
+ node_value = graph.nodes[str(indx)]["nodefloat"]
378
+ if math.isnan(value):
379
+ assert math.isnan(node_value)
380
+ else:
381
+ assert node_value == value
382
+
383
+ edge = edges[indx]
384
+ string_edge = (str(edge[0]), str(edge[1]))
385
+ edge_value = graph.edges[string_edge]["edgefloat"]
386
+ if math.isnan(value):
387
+ assert math.isnan(edge_value)
388
+ else:
389
+ assert edge_value == value
390
+
391
+ def test_name(self):
392
+ G = nx.parse_gml('graph [ name "x" node [ id 0 label "x" ] ]')
393
+ assert "x" == G.graph["name"]
394
+ G = nx.parse_gml('graph [ node [ id 0 label "x" ] ]')
395
+ assert "" == G.name
396
+ assert "name" not in G.graph
397
+
398
+ def test_graph_types(self):
399
+ for directed in [None, False, True]:
400
+ for multigraph in [None, False, True]:
401
+ gml = "graph ["
402
+ if directed is not None:
403
+ gml += " directed " + str(int(directed))
404
+ if multigraph is not None:
405
+ gml += " multigraph " + str(int(multigraph))
406
+ gml += ' node [ id 0 label "0" ]'
407
+ gml += " edge [ source 0 target 0 ]"
408
+ gml += " ]"
409
+ G = nx.parse_gml(gml)
410
+ assert bool(directed) == G.is_directed()
411
+ assert bool(multigraph) == G.is_multigraph()
412
+ gml = "graph [\n"
413
+ if directed is True:
414
+ gml += " directed 1\n"
415
+ if multigraph is True:
416
+ gml += " multigraph 1\n"
417
+ gml += """ node [
418
+ id 0
419
+ label "0"
420
+ ]
421
+ edge [
422
+ source 0
423
+ target 0
424
+ """
425
+ if multigraph:
426
+ gml += " key 0\n"
427
+ gml += " ]\n]"
428
+ assert gml == "\n".join(nx.generate_gml(G))
429
+
430
+ def test_data_types(self):
431
+ data = [
432
+ True,
433
+ False,
434
+ 10**20,
435
+ -2e33,
436
+ "'",
437
+ '"&&amp;&&#34;"',
438
+ [{(b"\xfd",): "\x7f", chr(0x4444): (1, 2)}, (2, "3")],
439
+ ]
440
+ data.append(chr(0x14444))
441
+ data.append(literal_eval("{2.3j, 1 - 2.3j, ()}"))
442
+ G = nx.Graph()
443
+ G.name = data
444
+ G.graph["data"] = data
445
+ G.add_node(0, int=-1, data={"data": data})
446
+ G.add_edge(0, 0, float=-2.5, data=data)
447
+ gml = "\n".join(nx.generate_gml(G, stringizer=literal_stringizer))
448
+ G = nx.parse_gml(gml, destringizer=literal_destringizer)
449
+ assert data == G.name
450
+ assert {"name": data, "data": data} == G.graph
451
+ assert list(G.nodes(data=True)) == [(0, {"int": -1, "data": {"data": data}})]
452
+ assert list(G.edges(data=True)) == [(0, 0, {"float": -2.5, "data": data})]
453
+ G = nx.Graph()
454
+ G.graph["data"] = "frozenset([1, 2, 3])"
455
+ G = nx.parse_gml(nx.generate_gml(G), destringizer=literal_eval)
456
+ assert G.graph["data"] == "frozenset([1, 2, 3])"
457
+
458
+ def test_escape_unescape(self):
459
+ gml = """graph [
460
+ name "&amp;&#34;&#xf;&#x4444;&#1234567890;&#x1234567890abcdef;&unknown;"
461
+ ]"""
462
+ G = nx.parse_gml(gml)
463
+ assert (
464
+ '&"\x0f' + chr(0x4444) + "&#1234567890;&#x1234567890abcdef;&unknown;"
465
+ == G.name
466
+ )
467
+ gml = "\n".join(nx.generate_gml(G))
468
+ alnu = "#1234567890;&#38;#x1234567890abcdef"
469
+ answer = (
470
+ """graph [
471
+ name "&#38;&#34;&#15;&#17476;&#38;"""
472
+ + alnu
473
+ + """;&#38;unknown;"
474
+ ]"""
475
+ )
476
+ assert answer == gml
477
+
478
+ def test_exceptions(self, tmp_path):
479
+ pytest.raises(ValueError, literal_destringizer, "(")
480
+ pytest.raises(ValueError, literal_destringizer, "frozenset([1, 2, 3])")
481
+ pytest.raises(ValueError, literal_destringizer, literal_destringizer)
482
+ pytest.raises(ValueError, literal_stringizer, frozenset([1, 2, 3]))
483
+ pytest.raises(ValueError, literal_stringizer, literal_stringizer)
484
+ with open(tmp_path / "test.gml", "w+b") as f:
485
+ f.write(codecs.BOM_UTF8 + b"graph[]")
486
+ f.seek(0)
487
+ pytest.raises(nx.NetworkXError, nx.read_gml, f)
488
+
489
+ def assert_parse_error(gml):
490
+ pytest.raises(nx.NetworkXError, nx.parse_gml, gml)
491
+
492
+ assert_parse_error(["graph [\n\n", "]"])
493
+ assert_parse_error("")
494
+ assert_parse_error('Creator ""')
495
+ assert_parse_error("0")
496
+ assert_parse_error("graph ]")
497
+ assert_parse_error("graph [ 1 ]")
498
+ assert_parse_error("graph [ 1.E+2 ]")
499
+ assert_parse_error('graph [ "A" ]')
500
+ assert_parse_error("graph [ ] graph ]")
501
+ assert_parse_error("graph [ ] graph [ ]")
502
+ assert_parse_error("graph [ data [1, 2, 3] ]")
503
+ assert_parse_error("graph [ node [ ] ]")
504
+ assert_parse_error("graph [ node [ id 0 ] ]")
505
+ nx.parse_gml('graph [ node [ id "a" ] ]', label="id")
506
+ assert_parse_error("graph [ node [ id 0 label 0 ] node [ id 0 label 1 ] ]")
507
+ assert_parse_error("graph [ node [ id 0 label 0 ] node [ id 1 label 0 ] ]")
508
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ ] ]")
509
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 0 ] ]")
510
+ nx.parse_gml("graph [edge [ source 0 target 0 ] node [ id 0 label 0 ] ]")
511
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 1 target 0 ] ]")
512
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 0 target 1 ] ]")
513
+ assert_parse_error(
514
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
515
+ "edge [ source 0 target 1 ] edge [ source 1 target 0 ] ]"
516
+ )
517
+ nx.parse_gml(
518
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
519
+ "edge [ source 0 target 1 ] edge [ source 1 target 0 ] "
520
+ "directed 1 ]"
521
+ )
522
+ nx.parse_gml(
523
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
524
+ "edge [ source 0 target 1 ] edge [ source 0 target 1 ]"
525
+ "multigraph 1 ]"
526
+ )
527
+ nx.parse_gml(
528
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
529
+ "edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 ]"
530
+ "multigraph 1 ]"
531
+ )
532
+ assert_parse_error(
533
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
534
+ "edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 0 ]"
535
+ "multigraph 1 ]"
536
+ )
537
+ nx.parse_gml(
538
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
539
+ "edge [ source 0 target 1 key 0 ] edge [ source 1 target 0 key 0 ]"
540
+ "directed 1 multigraph 1 ]"
541
+ )
542
+
543
+ # Tests for string convertible alphanumeric id and label values
544
+ nx.parse_gml("graph [edge [ source a target a ] node [ id a label b ] ]")
545
+ nx.parse_gml(
546
+ "graph [ node [ id n42 label 0 ] node [ id x43 label 1 ]"
547
+ "edge [ source n42 target x43 key 0 ]"
548
+ "edge [ source x43 target n42 key 0 ]"
549
+ "directed 1 multigraph 1 ]"
550
+ )
551
+ assert_parse_error(
552
+ "graph [edge [ source '\u4200' target '\u4200' ] "
553
+ + "node [ id '\u4200' label b ] ]"
554
+ )
555
+
556
+ def assert_generate_error(*args, **kwargs):
557
+ pytest.raises(
558
+ nx.NetworkXError, lambda: list(nx.generate_gml(*args, **kwargs))
559
+ )
560
+
561
+ G = nx.Graph()
562
+ G.graph[3] = 3
563
+ assert_generate_error(G)
564
+ G = nx.Graph()
565
+ G.graph["3"] = 3
566
+ assert_generate_error(G)
567
+ G = nx.Graph()
568
+ G.graph["data"] = frozenset([1, 2, 3])
569
+ assert_generate_error(G, stringizer=literal_stringizer)
570
+
571
+ def test_label_kwarg(self):
572
+ G = nx.parse_gml(self.simple_data, label="id")
573
+ assert sorted(G.nodes) == [1, 2, 3]
574
+ labels = [G.nodes[n]["label"] for n in sorted(G.nodes)]
575
+ assert labels == ["Node 1", "Node 2", "Node 3"]
576
+
577
+ G = nx.parse_gml(self.simple_data, label=None)
578
+ assert sorted(G.nodes) == [1, 2, 3]
579
+ labels = [G.nodes[n]["label"] for n in sorted(G.nodes)]
580
+ assert labels == ["Node 1", "Node 2", "Node 3"]
581
+
582
+ def test_outofrange_integers(self, tmp_path):
583
+ # GML restricts integers to 32 signed bits.
584
+ # Check that we honor this restriction on export
585
+ G = nx.Graph()
586
+ # Test export for numbers that barely fit or don't fit into 32 bits,
587
+ # and 3 numbers in the middle
588
+ numbers = {
589
+ "toosmall": (-(2**31)) - 1,
590
+ "small": -(2**31),
591
+ "med1": -4,
592
+ "med2": 0,
593
+ "med3": 17,
594
+ "big": (2**31) - 1,
595
+ "toobig": 2**31,
596
+ }
597
+ G.add_node("Node", **numbers)
598
+
599
+ fname = tmp_path / "test.gml"
600
+ nx.write_gml(G, fname)
601
+ # Check that the export wrote the nonfitting numbers as strings
602
+ G2 = nx.read_gml(fname)
603
+ for attr, value in G2.nodes["Node"].items():
604
+ if attr == "toosmall" or attr == "toobig":
605
+ assert type(value) == str
606
+ else:
607
+ assert type(value) == int
608
+
609
+ def test_multiline(self):
610
+ # example from issue #6836
611
+ multiline_example = """
612
+ graph
613
+ [
614
+ node
615
+ [
616
+ id 0
617
+ label "multiline node"
618
+ label2 "multiline1
619
+ multiline2
620
+ multiline3"
621
+ alt_name "id 0"
622
+ ]
623
+ ]
624
+ """
625
+ G = nx.parse_gml(multiline_example)
626
+ assert G.nodes["multiline node"] == {
627
+ "label2": "multiline1 multiline2 multiline3",
628
+ "alt_name": "id 0",
629
+ }
630
+
631
+
632
+ @contextmanager
633
+ def byte_file():
634
+ _file_handle = io.BytesIO()
635
+ yield _file_handle
636
+ _file_handle.seek(0)
637
+
638
+
639
+ class TestPropertyLists:
640
+ def test_writing_graph_with_multi_element_property_list(self):
641
+ g = nx.Graph()
642
+ g.add_node("n1", properties=["element", 0, 1, 2.5, True, False])
643
+ with byte_file() as f:
644
+ nx.write_gml(g, f)
645
+ result = f.read().decode()
646
+
647
+ assert result == dedent(
648
+ """\
649
+ graph [
650
+ node [
651
+ id 0
652
+ label "n1"
653
+ properties "element"
654
+ properties 0
655
+ properties 1
656
+ properties 2.5
657
+ properties 1
658
+ properties 0
659
+ ]
660
+ ]
661
+ """
662
+ )
663
+
664
+ def test_writing_graph_with_one_element_property_list(self):
665
+ g = nx.Graph()
666
+ g.add_node("n1", properties=["element"])
667
+ with byte_file() as f:
668
+ nx.write_gml(g, f)
669
+ result = f.read().decode()
670
+
671
+ assert result == dedent(
672
+ """\
673
+ graph [
674
+ node [
675
+ id 0
676
+ label "n1"
677
+ properties "_networkx_list_start"
678
+ properties "element"
679
+ ]
680
+ ]
681
+ """
682
+ )
683
+
684
+ def test_reading_graph_with_list_property(self):
685
+ with byte_file() as f:
686
+ f.write(
687
+ dedent(
688
+ """
689
+ graph [
690
+ node [
691
+ id 0
692
+ label "n1"
693
+ properties "element"
694
+ properties 0
695
+ properties 1
696
+ properties 2.5
697
+ ]
698
+ ]
699
+ """
700
+ ).encode("ascii")
701
+ )
702
+ f.seek(0)
703
+ graph = nx.read_gml(f)
704
+ assert graph.nodes(data=True)["n1"] == {"properties": ["element", 0, 1, 2.5]}
705
+
706
+ def test_reading_graph_with_single_element_list_property(self):
707
+ with byte_file() as f:
708
+ f.write(
709
+ dedent(
710
+ """
711
+ graph [
712
+ node [
713
+ id 0
714
+ label "n1"
715
+ properties "_networkx_list_start"
716
+ properties "element"
717
+ ]
718
+ ]
719
+ """
720
+ ).encode("ascii")
721
+ )
722
+ f.seek(0)
723
+ graph = nx.read_gml(f)
724
+ assert graph.nodes(data=True)["n1"] == {"properties": ["element"]}
725
+
726
+
727
+ @pytest.mark.parametrize("coll", ([], ()))
728
+ def test_stringize_empty_list_tuple(coll):
729
+ G = nx.path_graph(2)
730
+ G.nodes[0]["test"] = coll # test serializing an empty collection
731
+ f = io.BytesIO()
732
+ nx.write_gml(G, f) # Smoke test - should not raise
733
+ f.seek(0)
734
+ H = nx.read_gml(f)
735
+ assert H.nodes["0"]["test"] == coll # Check empty list round-trips properly
736
+ # Check full round-tripping. Note that nodes are loaded as strings by
737
+ # default, so there needs to be some remapping prior to comparison
738
+ H = nx.relabel_nodes(H, {"0": 0, "1": 1})
739
+ assert nx.utils.graphs_equal(G, H)
740
+ # Same as above, but use destringizer for node remapping. Should have no
741
+ # effect on node attr
742
+ f.seek(0)
743
+ H = nx.read_gml(f, destringizer=int)
744
+ assert nx.utils.graphs_equal(G, H)