applied-ai-018 commited on
Commit
a980632
·
verified ·
1 Parent(s): 53756b8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/networkx/classes/__init__.py +13 -0
  2. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/coreviews.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/digraph.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/filters.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/function.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/graphviews.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/multidigraph.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/multigraph.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/reportviews.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/networkx/classes/coreviews.py +418 -0
  12. env-llmeval/lib/python3.10/site-packages/networkx/classes/digraph.py +1334 -0
  13. env-llmeval/lib/python3.10/site-packages/networkx/classes/filters.py +87 -0
  14. env-llmeval/lib/python3.10/site-packages/networkx/classes/function.py +1335 -0
  15. env-llmeval/lib/python3.10/site-packages/networkx/classes/graph.py +2043 -0
  16. env-llmeval/lib/python3.10/site-packages/networkx/classes/graphviews.py +269 -0
  17. env-llmeval/lib/python3.10/site-packages/networkx/classes/multidigraph.py +965 -0
  18. env-llmeval/lib/python3.10/site-packages/networkx/classes/multigraph.py +1282 -0
  19. env-llmeval/lib/python3.10/site-packages/networkx/classes/reportviews.py +1438 -0
  20. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_coreviews.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_reportviews.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_special.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py +194 -0
  24. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_digraph.py +331 -0
  25. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_digraph_historical.py +110 -0
  26. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py +177 -0
  27. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_function.py +787 -0
  28. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_multigraph.py +528 -0
  29. env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_reportviews.py +1427 -0
  30. env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png +3 -0
  31. env-llmeval/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz +3 -0
  32. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__init__.py +13 -0
  33. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/bethehessianmatrix.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/graphmatrix.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc +0 -0
  39. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py +656 -0
  42. env-llmeval/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py +166 -0
  43. env-llmeval/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py +616 -0
  44. env-llmeval/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py +166 -0
  45. env-llmeval/lib/python3.10/site-packages/networkx/linalg/spectrum.py +185 -0
  46. env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py +0 -0
  47. env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_bethehessian.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/networkx/classes/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .graph import Graph
2
+ from .digraph import DiGraph
3
+ from .multigraph import MultiGraph
4
+ from .multidigraph import MultiDiGraph
5
+
6
+ from .function import *
7
+ from .graphviews import subgraph_view, reverse_view
8
+
9
+ from networkx.classes import filters
10
+
11
+ from networkx.classes import coreviews
12
+ from networkx.classes import graphviews
13
+ from networkx.classes import reportviews
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (585 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/coreviews.cpython-310.pyc ADDED
Binary file (16.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/digraph.cpython-310.pyc ADDED
Binary file (46.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/filters.cpython-310.pyc ADDED
Binary file (4.71 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/function.cpython-310.pyc ADDED
Binary file (37.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/graphviews.cpython-310.pyc ADDED
Binary file (8.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/multidigraph.cpython-310.pyc ADDED
Binary file (36 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/multigraph.cpython-310.pyc ADDED
Binary file (46.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/reportviews.cpython-310.pyc ADDED
Binary file (49 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/coreviews.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from collections.abc import Mapping
6
+
7
+ __all__ = [
8
+ "AtlasView",
9
+ "AdjacencyView",
10
+ "MultiAdjacencyView",
11
+ "UnionAtlas",
12
+ "UnionAdjacency",
13
+ "UnionMultiInner",
14
+ "UnionMultiAdjacency",
15
+ "FilterAtlas",
16
+ "FilterAdjacency",
17
+ "FilterMultiInner",
18
+ "FilterMultiAdjacency",
19
+ ]
20
+
21
+
22
+ class AtlasView(Mapping):
23
+ """An AtlasView is a Read-only Mapping of Mappings.
24
+
25
+ It is a View into a dict-of-dict data structure.
26
+ The inner level of dict is read-write. But the
27
+ outer level is read-only.
28
+
29
+ See Also
30
+ ========
31
+ AdjacencyView: View into dict-of-dict-of-dict
32
+ MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
33
+ """
34
+
35
+ __slots__ = ("_atlas",)
36
+
37
+ def __getstate__(self):
38
+ return {"_atlas": self._atlas}
39
+
40
+ def __setstate__(self, state):
41
+ self._atlas = state["_atlas"]
42
+
43
+ def __init__(self, d):
44
+ self._atlas = d
45
+
46
+ def __len__(self):
47
+ return len(self._atlas)
48
+
49
+ def __iter__(self):
50
+ return iter(self._atlas)
51
+
52
+ def __getitem__(self, key):
53
+ return self._atlas[key]
54
+
55
+ def copy(self):
56
+ return {n: self[n].copy() for n in self._atlas}
57
+
58
+ def __str__(self):
59
+ return str(self._atlas) # {nbr: self[nbr] for nbr in self})
60
+
61
+ def __repr__(self):
62
+ return f"{self.__class__.__name__}({self._atlas!r})"
63
+
64
+
65
+ class AdjacencyView(AtlasView):
66
+ """An AdjacencyView is a Read-only Map of Maps of Maps.
67
+
68
+ It is a View into a dict-of-dict-of-dict data structure.
69
+ The inner level of dict is read-write. But the
70
+ outer levels are read-only.
71
+
72
+ See Also
73
+ ========
74
+ AtlasView: View into dict-of-dict
75
+ MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
76
+ """
77
+
78
+ __slots__ = () # Still uses AtlasView slots names _atlas
79
+
80
+ def __getitem__(self, name):
81
+ return AtlasView(self._atlas[name])
82
+
83
+ def copy(self):
84
+ return {n: self[n].copy() for n in self._atlas}
85
+
86
+
87
+ class MultiAdjacencyView(AdjacencyView):
88
+ """An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.
89
+
90
+ It is a View into a dict-of-dict-of-dict-of-dict data structure.
91
+ The inner level of dict is read-write. But the
92
+ outer levels are read-only.
93
+
94
+ See Also
95
+ ========
96
+ AtlasView: View into dict-of-dict
97
+ AdjacencyView: View into dict-of-dict-of-dict
98
+ """
99
+
100
+ __slots__ = () # Still uses AtlasView slots names _atlas
101
+
102
+ def __getitem__(self, name):
103
+ return AdjacencyView(self._atlas[name])
104
+
105
+ def copy(self):
106
+ return {n: self[n].copy() for n in self._atlas}
107
+
108
+
109
+ class UnionAtlas(Mapping):
110
+ """A read-only union of two atlases (dict-of-dict).
111
+
112
+ The two dict-of-dicts represent the inner dict of
113
+ an Adjacency: `G.succ[node]` and `G.pred[node]`.
114
+ The inner level of dict of both hold attribute key:value
115
+ pairs and is read-write. But the outer level is read-only.
116
+
117
+ See Also
118
+ ========
119
+ UnionAdjacency: View into dict-of-dict-of-dict
120
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
121
+ """
122
+
123
+ __slots__ = ("_succ", "_pred")
124
+
125
+ def __getstate__(self):
126
+ return {"_succ": self._succ, "_pred": self._pred}
127
+
128
+ def __setstate__(self, state):
129
+ self._succ = state["_succ"]
130
+ self._pred = state["_pred"]
131
+
132
+ def __init__(self, succ, pred):
133
+ self._succ = succ
134
+ self._pred = pred
135
+
136
+ def __len__(self):
137
+ return len(self._succ.keys() | self._pred.keys())
138
+
139
+ def __iter__(self):
140
+ return iter(set(self._succ.keys()) | set(self._pred.keys()))
141
+
142
+ def __getitem__(self, key):
143
+ try:
144
+ return self._succ[key]
145
+ except KeyError:
146
+ return self._pred[key]
147
+
148
+ def copy(self):
149
+ result = {nbr: dd.copy() for nbr, dd in self._succ.items()}
150
+ for nbr, dd in self._pred.items():
151
+ if nbr in result:
152
+ result[nbr].update(dd)
153
+ else:
154
+ result[nbr] = dd.copy()
155
+ return result
156
+
157
+ def __str__(self):
158
+ return str({nbr: self[nbr] for nbr in self})
159
+
160
+ def __repr__(self):
161
+ return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
162
+
163
+
164
+ class UnionAdjacency(Mapping):
165
+ """A read-only union of dict Adjacencies as a Map of Maps of Maps.
166
+
167
+ The two input dict-of-dict-of-dicts represent the union of
168
+ `G.succ` and `G.pred`. Return values are UnionAtlas
169
+ The inner level of dict is read-write. But the
170
+ middle and outer levels are read-only.
171
+
172
+ succ : a dict-of-dict-of-dict {node: nbrdict}
173
+ pred : a dict-of-dict-of-dict {node: nbrdict}
174
+ The keys for the two dicts should be the same
175
+
176
+ See Also
177
+ ========
178
+ UnionAtlas: View into dict-of-dict
179
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
180
+ """
181
+
182
+ __slots__ = ("_succ", "_pred")
183
+
184
+ def __getstate__(self):
185
+ return {"_succ": self._succ, "_pred": self._pred}
186
+
187
+ def __setstate__(self, state):
188
+ self._succ = state["_succ"]
189
+ self._pred = state["_pred"]
190
+
191
+ def __init__(self, succ, pred):
192
+ # keys must be the same for two input dicts
193
+ assert len(set(succ.keys()) ^ set(pred.keys())) == 0
194
+ self._succ = succ
195
+ self._pred = pred
196
+
197
+ def __len__(self):
198
+ return len(self._succ) # length of each dict should be the same
199
+
200
+ def __iter__(self):
201
+ return iter(self._succ)
202
+
203
+ def __getitem__(self, nbr):
204
+ return UnionAtlas(self._succ[nbr], self._pred[nbr])
205
+
206
+ def copy(self):
207
+ return {n: self[n].copy() for n in self._succ}
208
+
209
+ def __str__(self):
210
+ return str({nbr: self[nbr] for nbr in self})
211
+
212
+ def __repr__(self):
213
+ return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
214
+
215
+
216
+ class UnionMultiInner(UnionAtlas):
217
+ """A read-only union of two inner dicts of MultiAdjacencies.
218
+
219
+ The two input dict-of-dict-of-dicts represent the union of
220
+ `G.succ[node]` and `G.pred[node]` for MultiDiGraphs.
221
+ Return values are UnionAtlas.
222
+ The inner level of dict is read-write. But the outer levels are read-only.
223
+
224
+ See Also
225
+ ========
226
+ UnionAtlas: View into dict-of-dict
227
+ UnionAdjacency: View into dict-of-dict-of-dict
228
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
229
+ """
230
+
231
+ __slots__ = () # Still uses UnionAtlas slots names _succ, _pred
232
+
233
+ def __getitem__(self, node):
234
+ in_succ = node in self._succ
235
+ in_pred = node in self._pred
236
+ if in_succ:
237
+ if in_pred:
238
+ return UnionAtlas(self._succ[node], self._pred[node])
239
+ return UnionAtlas(self._succ[node], {})
240
+ return UnionAtlas({}, self._pred[node])
241
+
242
+ def copy(self):
243
+ nodes = set(self._succ.keys()) | set(self._pred.keys())
244
+ return {n: self[n].copy() for n in nodes}
245
+
246
+
247
+ class UnionMultiAdjacency(UnionAdjacency):
248
+ """A read-only union of two dict MultiAdjacencies.
249
+
250
+ The two input dict-of-dict-of-dict-of-dicts represent the union of
251
+ `G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency.
252
+ The inner level of dict is read-write. But the outer levels are read-only.
253
+
254
+ See Also
255
+ ========
256
+ UnionAtlas: View into dict-of-dict
257
+ UnionMultiInner: View into dict-of-dict-of-dict
258
+ """
259
+
260
+ __slots__ = () # Still uses UnionAdjacency slots names _succ, _pred
261
+
262
+ def __getitem__(self, node):
263
+ return UnionMultiInner(self._succ[node], self._pred[node])
264
+
265
+
266
+ class FilterAtlas(Mapping): # nodedict, nbrdict, keydict
267
+ """A read-only Mapping of Mappings with filtering criteria for nodes.
268
+
269
+ It is a view into a dict-of-dict data structure, and it selects only
270
+ nodes that meet the criteria defined by ``NODE_OK``.
271
+
272
+ See Also
273
+ ========
274
+ FilterAdjacency
275
+ FilterMultiInner
276
+ FilterMultiAdjacency
277
+ """
278
+
279
+ def __init__(self, d, NODE_OK):
280
+ self._atlas = d
281
+ self.NODE_OK = NODE_OK
282
+
283
+ def __len__(self):
284
+ return sum(1 for n in self)
285
+
286
+ def __iter__(self):
287
+ try: # check that NODE_OK has attr 'nodes'
288
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
289
+ except AttributeError:
290
+ node_ok_shorter = False
291
+ if node_ok_shorter:
292
+ return (n for n in self.NODE_OK.nodes if n in self._atlas)
293
+ return (n for n in self._atlas if self.NODE_OK(n))
294
+
295
+ def __getitem__(self, key):
296
+ if key in self._atlas and self.NODE_OK(key):
297
+ return self._atlas[key]
298
+ raise KeyError(f"Key {key} not found")
299
+
300
+ def __str__(self):
301
+ return str({nbr: self[nbr] for nbr in self})
302
+
303
+ def __repr__(self):
304
+ return f"{self.__class__.__name__}({self._atlas!r}, {self.NODE_OK!r})"
305
+
306
+
307
+ class FilterAdjacency(Mapping): # edgedict
308
+ """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
309
+
310
+ It is a view into a dict-of-dict-of-dict data structure, and it selects nodes
311
+ and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``,
312
+ respectively.
313
+
314
+ See Also
315
+ ========
316
+ FilterAtlas
317
+ FilterMultiInner
318
+ FilterMultiAdjacency
319
+ """
320
+
321
+ def __init__(self, d, NODE_OK, EDGE_OK):
322
+ self._atlas = d
323
+ self.NODE_OK = NODE_OK
324
+ self.EDGE_OK = EDGE_OK
325
+
326
+ def __len__(self):
327
+ return sum(1 for n in self)
328
+
329
+ def __iter__(self):
330
+ try: # check that NODE_OK has attr 'nodes'
331
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
332
+ except AttributeError:
333
+ node_ok_shorter = False
334
+ if node_ok_shorter:
335
+ return (n for n in self.NODE_OK.nodes if n in self._atlas)
336
+ return (n for n in self._atlas if self.NODE_OK(n))
337
+
338
+ def __getitem__(self, node):
339
+ if node in self._atlas and self.NODE_OK(node):
340
+
341
+ def new_node_ok(nbr):
342
+ return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr)
343
+
344
+ return FilterAtlas(self._atlas[node], new_node_ok)
345
+ raise KeyError(f"Key {node} not found")
346
+
347
+ def __str__(self):
348
+ return str({nbr: self[nbr] for nbr in self})
349
+
350
+ def __repr__(self):
351
+ name = self.__class__.__name__
352
+ return f"{name}({self._atlas!r}, {self.NODE_OK!r}, {self.EDGE_OK!r})"
353
+
354
+
355
+ class FilterMultiInner(FilterAdjacency): # muliedge_seconddict
356
+ """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
357
+
358
+ It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes
359
+ and edges that meet specific criteria defined by ``NODE_OK`` and ``EDGE_OK``.
360
+
361
+ See Also
362
+ ========
363
+ FilterAtlas
364
+ FilterAdjacency
365
+ FilterMultiAdjacency
366
+ """
367
+
368
+ def __iter__(self):
369
+ try: # check that NODE_OK has attr 'nodes'
370
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
371
+ except AttributeError:
372
+ node_ok_shorter = False
373
+ if node_ok_shorter:
374
+ my_nodes = (n for n in self.NODE_OK.nodes if n in self._atlas)
375
+ else:
376
+ my_nodes = (n for n in self._atlas if self.NODE_OK(n))
377
+ for n in my_nodes:
378
+ some_keys_ok = False
379
+ for key in self._atlas[n]:
380
+ if self.EDGE_OK(n, key):
381
+ some_keys_ok = True
382
+ break
383
+ if some_keys_ok is True:
384
+ yield n
385
+
386
+ def __getitem__(self, nbr):
387
+ if nbr in self._atlas and self.NODE_OK(nbr):
388
+
389
+ def new_node_ok(key):
390
+ return self.EDGE_OK(nbr, key)
391
+
392
+ return FilterAtlas(self._atlas[nbr], new_node_ok)
393
+ raise KeyError(f"Key {nbr} not found")
394
+
395
+
396
+ class FilterMultiAdjacency(FilterAdjacency): # multiedgedict
397
+ """A read-only Mapping of Mappings with filtering criteria
398
+ for nodes and edges.
399
+
400
+ It is a view into a dict-of-dict-of-dict-of-dict data structure,
401
+ and it selects nodes and edges that satisfy specific criteria
402
+ defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
403
+
404
+ See Also
405
+ ========
406
+ FilterAtlas
407
+ FilterAdjacency
408
+ FilterMultiInner
409
+ """
410
+
411
+ def __getitem__(self, node):
412
+ if node in self._atlas and self.NODE_OK(node):
413
+
414
+ def edge_ok(nbr, key):
415
+ return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr, key)
416
+
417
+ return FilterMultiInner(self._atlas[node], self.NODE_OK, edge_ok)
418
+ raise KeyError(f"Key {node} not found")
env-llmeval/lib/python3.10/site-packages/networkx/classes/digraph.py ADDED
@@ -0,0 +1,1334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for directed graphs."""
2
+ from copy import deepcopy
3
+ from functools import cached_property
4
+
5
+ import networkx as nx
6
+ from networkx import convert
7
+ from networkx.classes.coreviews import AdjacencyView
8
+ from networkx.classes.graph import Graph
9
+ from networkx.classes.reportviews import (
10
+ DiDegreeView,
11
+ InDegreeView,
12
+ InEdgeView,
13
+ OutDegreeView,
14
+ OutEdgeView,
15
+ )
16
+ from networkx.exception import NetworkXError
17
+
18
+ __all__ = ["DiGraph"]
19
+
20
+
21
+ class _CachedPropertyResetterAdjAndSucc:
22
+ """Data Descriptor class that syncs and resets cached properties adj and succ
23
+
24
+ The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ`
25
+ are set to new objects. In addition, the attributes `_succ` and `_adj`
26
+ are synced so these two names point to the same object.
27
+
28
+ This object sits on a class and ensures that any instance of that
29
+ class clears its cached properties "succ" and "adj" whenever the
30
+ underlying instance attributes "_succ" or "_adj" are set to a new object.
31
+ It only affects the set process of the obj._adj and obj._succ attribute.
32
+ All get/del operations act as they normally would.
33
+
34
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
35
+ """
36
+
37
+ def __set__(self, obj, value):
38
+ od = obj.__dict__
39
+ od["_adj"] = value
40
+ od["_succ"] = value
41
+ # reset cached properties
42
+ if "adj" in od:
43
+ del od["adj"]
44
+ if "succ" in od:
45
+ del od["succ"]
46
+
47
+
48
+ class _CachedPropertyResetterPred:
49
+ """Data Descriptor class for _pred that resets ``pred`` cached_property when needed
50
+
51
+ This assumes that the ``cached_property`` ``G.pred`` should be reset whenever
52
+ ``G._pred`` 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 "pred" whenever the underlying
56
+ instance attribute "_pred" is set to a new object. It only affects
57
+ the set process of the obj._pred 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["_pred"] = value
66
+ if "pred" in od:
67
+ del od["pred"]
68
+
69
+
70
+ class DiGraph(Graph):
71
+ """
72
+ Base class for directed graphs.
73
+
74
+ A DiGraph stores nodes and edges with optional data, or attributes.
75
+
76
+ DiGraphs hold directed edges. Self loops are allowed but multiple
77
+ (parallel) edges are not.
78
+
79
+ Nodes can be arbitrary (hashable) Python objects with optional
80
+ key/value attributes. By convention `None` is not used as a node.
81
+
82
+ Edges are represented as links between nodes with optional
83
+ key/value attributes.
84
+
85
+ Parameters
86
+ ----------
87
+ incoming_graph_data : input graph (optional, default: None)
88
+ Data to initialize graph. If None (default) an empty
89
+ graph is created. The data can be any format that is supported
90
+ by the to_networkx_graph() function, currently including edge list,
91
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
92
+ sparse matrix, or PyGraphviz graph.
93
+
94
+ attr : keyword arguments, optional (default= no attributes)
95
+ Attributes to add to graph as key=value pairs.
96
+
97
+ See Also
98
+ --------
99
+ Graph
100
+ MultiGraph
101
+ MultiDiGraph
102
+
103
+ Examples
104
+ --------
105
+ Create an empty graph structure (a "null graph") with no nodes and
106
+ no edges.
107
+
108
+ >>> G = nx.DiGraph()
109
+
110
+ G can be grown in several ways.
111
+
112
+ **Nodes:**
113
+
114
+ Add one node at a time:
115
+
116
+ >>> G.add_node(1)
117
+
118
+ Add the nodes from any container (a list, dict, set or
119
+ even the lines from a file or the nodes from another graph).
120
+
121
+ >>> G.add_nodes_from([2, 3])
122
+ >>> G.add_nodes_from(range(100, 110))
123
+ >>> H = nx.path_graph(10)
124
+ >>> G.add_nodes_from(H)
125
+
126
+ In addition to strings and integers any hashable Python object
127
+ (except None) can represent a node, e.g. a customized node object,
128
+ or even another Graph.
129
+
130
+ >>> G.add_node(H)
131
+
132
+ **Edges:**
133
+
134
+ G can also be grown by adding edges.
135
+
136
+ Add one edge,
137
+
138
+ >>> G.add_edge(1, 2)
139
+
140
+ a list of edges,
141
+
142
+ >>> G.add_edges_from([(1, 2), (1, 3)])
143
+
144
+ or a collection of edges,
145
+
146
+ >>> G.add_edges_from(H.edges)
147
+
148
+ If some edges connect nodes not yet in the graph, the nodes
149
+ are added automatically. There are no errors when adding
150
+ nodes or edges that already exist.
151
+
152
+ **Attributes:**
153
+
154
+ Each graph, node, and edge can hold key/value attribute pairs
155
+ in an associated attribute dictionary (the keys must be hashable).
156
+ By default these are empty, but can be added or changed using
157
+ add_edge, add_node or direct manipulation of the attribute
158
+ dictionaries named graph, node and edge respectively.
159
+
160
+ >>> G = nx.DiGraph(day="Friday")
161
+ >>> G.graph
162
+ {'day': 'Friday'}
163
+
164
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
165
+
166
+ >>> G.add_node(1, time="5pm")
167
+ >>> G.add_nodes_from([3], time="2pm")
168
+ >>> G.nodes[1]
169
+ {'time': '5pm'}
170
+ >>> G.nodes[1]["room"] = 714
171
+ >>> del G.nodes[1]["room"] # remove attribute
172
+ >>> list(G.nodes(data=True))
173
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
174
+
175
+ Add edge attributes using add_edge(), add_edges_from(), subscript
176
+ notation, or G.edges.
177
+
178
+ >>> G.add_edge(1, 2, weight=4.7)
179
+ >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
180
+ >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
181
+ >>> G[1][2]["weight"] = 4.7
182
+ >>> G.edges[1, 2]["weight"] = 4
183
+
184
+ Warning: we protect the graph data structure by making `G.edges[1, 2]` a
185
+ read-only dict-like structure. However, you can assign to attributes
186
+ in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
187
+ data attributes: `G.edges[1, 2]['weight'] = 4`
188
+ (For multigraphs: `MG.edges[u, v, key][name] = value`).
189
+
190
+ **Shortcuts:**
191
+
192
+ Many common graph features allow python syntax to speed reporting.
193
+
194
+ >>> 1 in G # check if node in graph
195
+ True
196
+ >>> [n for n in G if n < 3] # iterate through nodes
197
+ [1, 2]
198
+ >>> len(G) # number of nodes in graph
199
+ 5
200
+
201
+ Often the best way to traverse all edges of a graph is via the neighbors.
202
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
203
+
204
+ >>> for n, nbrsdict in G.adjacency():
205
+ ... for nbr, eattr in nbrsdict.items():
206
+ ... if "weight" in eattr:
207
+ ... # Do something useful with the edges
208
+ ... pass
209
+
210
+ But the edges reporting object is often more convenient:
211
+
212
+ >>> for u, v, weight in G.edges(data="weight"):
213
+ ... if weight is not None:
214
+ ... # Do something useful with the edges
215
+ ... pass
216
+
217
+ **Reporting:**
218
+
219
+ Simple graph information is obtained using object-attributes and methods.
220
+ Reporting usually provides views instead of containers to reduce memory
221
+ usage. The views update as the graph is updated similarly to dict-views.
222
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
223
+ via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
224
+ (e.g. `nodes.items()`, `nodes.data('color')`,
225
+ `nodes.data('color', default='blue')` and similarly for `edges`)
226
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
227
+
228
+ For details on these and other miscellaneous methods, see below.
229
+
230
+ **Subclasses (Advanced):**
231
+
232
+ The Graph class uses a dict-of-dict-of-dict data structure.
233
+ The outer dict (node_dict) holds adjacency information keyed by node.
234
+ The next dict (adjlist_dict) represents the adjacency information and holds
235
+ edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
236
+ the edge data and holds edge attribute values keyed by attribute names.
237
+
238
+ Each of these three dicts can be replaced in a subclass by a user defined
239
+ dict-like object. In general, the dict-like features should be
240
+ maintained but extra features can be added. To replace one of the
241
+ dicts create a new graph class by changing the class(!) variable
242
+ holding the factory for that dict-like structure. The variable names are
243
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
244
+ adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
245
+
246
+ node_dict_factory : function, (default: dict)
247
+ Factory function to be used to create the dict containing node
248
+ attributes, keyed by node id.
249
+ It should require no arguments and return a dict-like object
250
+
251
+ node_attr_dict_factory: function, (default: dict)
252
+ Factory function to be used to create the node attribute
253
+ dict which holds attribute values keyed by attribute name.
254
+ It should require no arguments and return a dict-like object
255
+
256
+ adjlist_outer_dict_factory : function, (default: dict)
257
+ Factory function to be used to create the outer-most dict
258
+ in the data structure that holds adjacency info keyed by node.
259
+ It should require no arguments and return a dict-like object.
260
+
261
+ adjlist_inner_dict_factory : function, optional (default: dict)
262
+ Factory function to be used to create the adjacency list
263
+ dict which holds edge data keyed by neighbor.
264
+ It should require no arguments and return a dict-like object
265
+
266
+ edge_attr_dict_factory : function, optional (default: dict)
267
+ Factory function to be used to create the edge attribute
268
+ dict which holds attribute values keyed by attribute name.
269
+ It should require no arguments and return a dict-like object.
270
+
271
+ graph_attr_dict_factory : function, (default: dict)
272
+ Factory function to be used to create the graph attribute
273
+ dict which holds attribute values keyed by attribute name.
274
+ It should require no arguments and return a dict-like object.
275
+
276
+ Typically, if your extension doesn't impact the data structure all
277
+ methods will inherited without issue except: `to_directed/to_undirected`.
278
+ By default these methods create a DiGraph/Graph class and you probably
279
+ want them to create your extension of a DiGraph/Graph. To facilitate
280
+ this we define two class variables that you can set in your subclass.
281
+
282
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
283
+ Class to create a new graph structure in the `to_directed` method.
284
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
285
+
286
+ to_undirected_class : callable, (default: Graph or MultiGraph)
287
+ Class to create a new graph structure in the `to_undirected` method.
288
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
289
+
290
+ **Subclassing Example**
291
+
292
+ Create a low memory graph class that effectively disallows edge
293
+ attributes by using a single attribute dict for all edges.
294
+ This reduces the memory used, but you lose edge attributes.
295
+
296
+ >>> class ThinGraph(nx.Graph):
297
+ ... all_edge_dict = {"weight": 1}
298
+ ...
299
+ ... def single_edge_dict(self):
300
+ ... return self.all_edge_dict
301
+ ...
302
+ ... edge_attr_dict_factory = single_edge_dict
303
+ >>> G = ThinGraph()
304
+ >>> G.add_edge(2, 1)
305
+ >>> G[2][1]
306
+ {'weight': 1}
307
+ >>> G.add_edge(2, 2)
308
+ >>> G[2][1] is G[2][2]
309
+ True
310
+ """
311
+
312
+ _adj = _CachedPropertyResetterAdjAndSucc() # type: ignore[assignment]
313
+ _succ = _adj # type: ignore[has-type]
314
+ _pred = _CachedPropertyResetterPred()
315
+
316
+ def __init__(self, incoming_graph_data=None, **attr):
317
+ """Initialize a graph with edges, name, or graph attributes.
318
+
319
+ Parameters
320
+ ----------
321
+ incoming_graph_data : input graph (optional, default: None)
322
+ Data to initialize graph. If None (default) an empty
323
+ graph is created. The data can be an edge list, or any
324
+ NetworkX graph object. If the corresponding optional Python
325
+ packages are installed the data can also be a 2D NumPy array, a
326
+ SciPy sparse array, or a PyGraphviz graph.
327
+
328
+ attr : keyword arguments, optional (default= no attributes)
329
+ Attributes to add to graph as key=value pairs.
330
+
331
+ See Also
332
+ --------
333
+ convert
334
+
335
+ Examples
336
+ --------
337
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
338
+ >>> G = nx.Graph(name="my graph")
339
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
340
+ >>> G = nx.Graph(e)
341
+
342
+ Arbitrary graph attribute pairs (key=value) may be assigned
343
+
344
+ >>> G = nx.Graph(e, day="Friday")
345
+ >>> G.graph
346
+ {'day': 'Friday'}
347
+
348
+ """
349
+ self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
350
+ self._node = self.node_dict_factory() # dictionary for node attr
351
+ # We store two adjacency lists:
352
+ # the predecessors of node n are stored in the dict self._pred
353
+ # the successors of node n are stored in the dict self._succ=self._adj
354
+ self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict successor
355
+ self._pred = self.adjlist_outer_dict_factory() # predecessor
356
+ # Note: self._succ = self._adj # successor
357
+
358
+ self.__networkx_cache__ = {}
359
+ # attempt to load graph with data
360
+ if incoming_graph_data is not None:
361
+ convert.to_networkx_graph(incoming_graph_data, create_using=self)
362
+ # load graph attributes (must be after convert)
363
+ self.graph.update(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 edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
372
+ the color of the edge `(3, 2)` 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 AdjacencyView(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 edge-data-dict. So `G.succ[3][2]['color'] = 'blue'` sets
391
+ the color of the edge `(3, 2)` to `"blue"`.
392
+
393
+ Iterating over G.succ behaves like a dict. Useful idioms include
394
+ `for nbr, datadict in G.succ[n].items():`. A data-view not provided
395
+ by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`
396
+ and a default can be set via a `default` argument to the `data` method.
397
+
398
+ The neighbor information is also provided by subscripting the graph.
399
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
400
+
401
+ For directed graphs, `G.adj` is identical to `G.succ`.
402
+ """
403
+ return AdjacencyView(self._succ)
404
+
405
+ @cached_property
406
+ def pred(self):
407
+ """Graph adjacency object holding the predecessors of each node.
408
+
409
+ This object is a read-only dict-like structure with node keys
410
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
411
+ to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
412
+ the color of the edge `(3, 2)` to `"blue"`.
413
+
414
+ Iterating over G.pred behaves like a dict. Useful idioms include
415
+ `for nbr, datadict in G.pred[n].items():`. A data-view not provided
416
+ by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
417
+ A default can be set via a `default` argument to the `data` method.
418
+ """
419
+ return AdjacencyView(self._pred)
420
+
421
+ def add_node(self, node_for_adding, **attr):
422
+ """Add a single node `node_for_adding` and update node attributes.
423
+
424
+ Parameters
425
+ ----------
426
+ node_for_adding : node
427
+ A node can be any hashable Python object except None.
428
+ attr : keyword arguments, optional
429
+ Set or change node attributes using key=value.
430
+
431
+ See Also
432
+ --------
433
+ add_nodes_from
434
+
435
+ Examples
436
+ --------
437
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
438
+ >>> G.add_node(1)
439
+ >>> G.add_node("Hello")
440
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
441
+ >>> G.add_node(K3)
442
+ >>> G.number_of_nodes()
443
+ 3
444
+
445
+ Use keywords set/change node attributes:
446
+
447
+ >>> G.add_node(1, size=10)
448
+ >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
449
+
450
+ Notes
451
+ -----
452
+ A hashable object is one that can be used as a key in a Python
453
+ dictionary. This includes strings, numbers, tuples of strings
454
+ and numbers, etc.
455
+
456
+ On many platforms hashable items also include mutables such as
457
+ NetworkX Graphs, though one should be careful that the hash
458
+ doesn't change on mutables.
459
+ """
460
+ if node_for_adding not in self._succ:
461
+ if node_for_adding is None:
462
+ raise ValueError("None cannot be a node")
463
+ self._succ[node_for_adding] = self.adjlist_inner_dict_factory()
464
+ self._pred[node_for_adding] = self.adjlist_inner_dict_factory()
465
+ attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
466
+ attr_dict.update(attr)
467
+ else: # update attr even if node already exists
468
+ self._node[node_for_adding].update(attr)
469
+ nx._clear_cache(self)
470
+
471
+ def add_nodes_from(self, nodes_for_adding, **attr):
472
+ """Add multiple nodes.
473
+
474
+ Parameters
475
+ ----------
476
+ nodes_for_adding : iterable container
477
+ A container of nodes (list, dict, set, etc.).
478
+ OR
479
+ A container of (node, attribute dict) tuples.
480
+ Node attributes are updated using the attribute dict.
481
+ attr : keyword arguments, optional (default= no attributes)
482
+ Update attributes for all nodes in nodes.
483
+ Node attributes specified in nodes as a tuple take
484
+ precedence over attributes specified via keyword arguments.
485
+
486
+ See Also
487
+ --------
488
+ add_node
489
+
490
+ Notes
491
+ -----
492
+ When adding nodes from an iterator over the graph you are changing,
493
+ a `RuntimeError` can be raised with message:
494
+ `RuntimeError: dictionary changed size during iteration`. This
495
+ happens when the graph's underlying dictionary is modified during
496
+ iteration. To avoid this error, evaluate the iterator into a separate
497
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
498
+ object to `G.add_nodes_from`.
499
+
500
+ Examples
501
+ --------
502
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
503
+ >>> G.add_nodes_from("Hello")
504
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
505
+ >>> G.add_nodes_from(K3)
506
+ >>> sorted(G.nodes(), key=str)
507
+ [0, 1, 2, 'H', 'e', 'l', 'o']
508
+
509
+ Use keywords to update specific node attributes for every node.
510
+
511
+ >>> G.add_nodes_from([1, 2], size=10)
512
+ >>> G.add_nodes_from([3, 4], weight=0.4)
513
+
514
+ Use (node, attrdict) tuples to update attributes for specific nodes.
515
+
516
+ >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
517
+ >>> G.nodes[1]["size"]
518
+ 11
519
+ >>> H = nx.Graph()
520
+ >>> H.add_nodes_from(G.nodes(data=True))
521
+ >>> H.nodes[1]["size"]
522
+ 11
523
+
524
+ Evaluate an iterator over a graph if using it to modify the same graph
525
+
526
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
527
+ >>> # wrong way - will raise RuntimeError
528
+ >>> # G.add_nodes_from(n + 1 for n in G.nodes)
529
+ >>> # correct way
530
+ >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
531
+ """
532
+ for n in nodes_for_adding:
533
+ try:
534
+ newnode = n not in self._node
535
+ newdict = attr
536
+ except TypeError:
537
+ n, ndict = n
538
+ newnode = n not in self._node
539
+ newdict = attr.copy()
540
+ newdict.update(ndict)
541
+ if newnode:
542
+ if n is None:
543
+ raise ValueError("None cannot be a node")
544
+ self._succ[n] = self.adjlist_inner_dict_factory()
545
+ self._pred[n] = self.adjlist_inner_dict_factory()
546
+ self._node[n] = self.node_attr_dict_factory()
547
+ self._node[n].update(newdict)
548
+ nx._clear_cache(self)
549
+
550
+ def remove_node(self, n):
551
+ """Remove node n.
552
+
553
+ Removes the node n and all adjacent edges.
554
+ Attempting to remove a nonexistent node will raise an exception.
555
+
556
+ Parameters
557
+ ----------
558
+ n : node
559
+ A node in the graph
560
+
561
+ Raises
562
+ ------
563
+ NetworkXError
564
+ If n is not in the graph.
565
+
566
+ See Also
567
+ --------
568
+ remove_nodes_from
569
+
570
+ Examples
571
+ --------
572
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
573
+ >>> list(G.edges)
574
+ [(0, 1), (1, 2)]
575
+ >>> G.remove_node(1)
576
+ >>> list(G.edges)
577
+ []
578
+
579
+ """
580
+ try:
581
+ nbrs = self._succ[n]
582
+ del self._node[n]
583
+ except KeyError as err: # NetworkXError if n not in self
584
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
585
+ for u in nbrs:
586
+ del self._pred[u][n] # remove all edges n-u in digraph
587
+ del self._succ[n] # remove node from succ
588
+ for u in self._pred[n]:
589
+ del self._succ[u][n] # remove all edges n-u in digraph
590
+ del self._pred[n] # remove node from pred
591
+ nx._clear_cache(self)
592
+
593
+ def remove_nodes_from(self, nodes):
594
+ """Remove multiple nodes.
595
+
596
+ Parameters
597
+ ----------
598
+ nodes : iterable container
599
+ A container of nodes (list, dict, set, etc.). If a node
600
+ in the container is not in the graph it is silently ignored.
601
+
602
+ See Also
603
+ --------
604
+ remove_node
605
+
606
+ Notes
607
+ -----
608
+ When removing nodes from an iterator over the graph you are changing,
609
+ a `RuntimeError` will be raised with message:
610
+ `RuntimeError: dictionary changed size during iteration`. This
611
+ happens when the graph's underlying dictionary is modified during
612
+ iteration. To avoid this error, evaluate the iterator into a separate
613
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
614
+ object to `G.remove_nodes_from`.
615
+
616
+ Examples
617
+ --------
618
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
619
+ >>> e = list(G.nodes)
620
+ >>> e
621
+ [0, 1, 2]
622
+ >>> G.remove_nodes_from(e)
623
+ >>> list(G.nodes)
624
+ []
625
+
626
+ Evaluate an iterator over a graph if using it to modify the same graph
627
+
628
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
629
+ >>> # this command will fail, as the graph's dict is modified during iteration
630
+ >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
631
+ >>> # this command will work, since the dictionary underlying graph is not modified
632
+ >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
633
+ """
634
+ for n in nodes:
635
+ try:
636
+ succs = self._succ[n]
637
+ del self._node[n]
638
+ for u in succs:
639
+ del self._pred[u][n] # remove all edges n-u in digraph
640
+ del self._succ[n] # now remove node
641
+ for u in self._pred[n]:
642
+ del self._succ[u][n] # remove all edges n-u in digraph
643
+ del self._pred[n] # now remove node
644
+ except KeyError:
645
+ pass # silent failure on remove
646
+ nx._clear_cache(self)
647
+
648
+ def add_edge(self, u_of_edge, v_of_edge, **attr):
649
+ """Add an edge between u and v.
650
+
651
+ The nodes u and v will be automatically added if they are
652
+ not already in the graph.
653
+
654
+ Edge attributes can be specified with keywords or by directly
655
+ accessing the edge's attribute dictionary. See examples below.
656
+
657
+ Parameters
658
+ ----------
659
+ u_of_edge, v_of_edge : nodes
660
+ Nodes can be, for example, strings or numbers.
661
+ Nodes must be hashable (and not None) Python objects.
662
+ attr : keyword arguments, optional
663
+ Edge data (or labels or objects) can be assigned using
664
+ keyword arguments.
665
+
666
+ See Also
667
+ --------
668
+ add_edges_from : add a collection of edges
669
+
670
+ Notes
671
+ -----
672
+ Adding an edge that already exists updates the edge data.
673
+
674
+ Many NetworkX algorithms designed for weighted graphs use
675
+ an edge attribute (by default `weight`) to hold a numerical value.
676
+
677
+ Examples
678
+ --------
679
+ The following all add the edge e=(1, 2) to graph G:
680
+
681
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
682
+ >>> e = (1, 2)
683
+ >>> G.add_edge(1, 2) # explicit two-node form
684
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
685
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
686
+
687
+ Associate data to edges using keywords:
688
+
689
+ >>> G.add_edge(1, 2, weight=3)
690
+ >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
691
+
692
+ For non-string attribute keys, use subscript notation.
693
+
694
+ >>> G.add_edge(1, 2)
695
+ >>> G[1][2].update({0: 5})
696
+ >>> G.edges[1, 2].update({0: 5})
697
+ """
698
+ u, v = u_of_edge, v_of_edge
699
+ # add nodes
700
+ if u not in self._succ:
701
+ if u is None:
702
+ raise ValueError("None cannot be a node")
703
+ self._succ[u] = self.adjlist_inner_dict_factory()
704
+ self._pred[u] = self.adjlist_inner_dict_factory()
705
+ self._node[u] = self.node_attr_dict_factory()
706
+ if v not in self._succ:
707
+ if v is None:
708
+ raise ValueError("None cannot be a node")
709
+ self._succ[v] = self.adjlist_inner_dict_factory()
710
+ self._pred[v] = self.adjlist_inner_dict_factory()
711
+ self._node[v] = self.node_attr_dict_factory()
712
+ # add the edge
713
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
714
+ datadict.update(attr)
715
+ self._succ[u][v] = datadict
716
+ self._pred[v][u] = datadict
717
+ nx._clear_cache(self)
718
+
719
+ def add_edges_from(self, ebunch_to_add, **attr):
720
+ """Add all the edges in ebunch_to_add.
721
+
722
+ Parameters
723
+ ----------
724
+ ebunch_to_add : container of edges
725
+ Each edge given in the container will be added to the
726
+ graph. The edges must be given as 2-tuples (u, v) or
727
+ 3-tuples (u, v, d) where d is a dictionary containing edge data.
728
+ attr : keyword arguments, optional
729
+ Edge data (or labels or objects) can be assigned using
730
+ keyword arguments.
731
+
732
+ See Also
733
+ --------
734
+ add_edge : add a single edge
735
+ add_weighted_edges_from : convenient way to add weighted edges
736
+
737
+ Notes
738
+ -----
739
+ Adding the same edge twice has no effect but any edge data
740
+ will be updated when each duplicate edge is added.
741
+
742
+ Edge attributes specified in an ebunch take precedence over
743
+ attributes specified via keyword arguments.
744
+
745
+ When adding edges from an iterator over the graph you are changing,
746
+ a `RuntimeError` can be raised with message:
747
+ `RuntimeError: dictionary changed size during iteration`. This
748
+ happens when the graph's underlying dictionary is modified during
749
+ iteration. To avoid this error, evaluate the iterator into a separate
750
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
751
+ object to `G.add_edges_from`.
752
+
753
+ Examples
754
+ --------
755
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
756
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
757
+ >>> e = zip(range(0, 3), range(1, 4))
758
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
759
+
760
+ Associate data to edges
761
+
762
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
763
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
764
+
765
+ Evaluate an iterator over a graph if using it to modify the same graph
766
+
767
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
768
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
769
+ >>> # wrong way - will raise RuntimeError
770
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
771
+ >>> # right way - note that there will be no self-edge for node 5
772
+ >>> G.add_edges_from(list((5, n) for n in G.nodes))
773
+ """
774
+ for e in ebunch_to_add:
775
+ ne = len(e)
776
+ if ne == 3:
777
+ u, v, dd = e
778
+ elif ne == 2:
779
+ u, v = e
780
+ dd = {}
781
+ else:
782
+ raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
783
+ if u not in self._succ:
784
+ if u is None:
785
+ raise ValueError("None cannot be a node")
786
+ self._succ[u] = self.adjlist_inner_dict_factory()
787
+ self._pred[u] = self.adjlist_inner_dict_factory()
788
+ self._node[u] = self.node_attr_dict_factory()
789
+ if v not in self._succ:
790
+ if v is None:
791
+ raise ValueError("None cannot be a node")
792
+ self._succ[v] = self.adjlist_inner_dict_factory()
793
+ self._pred[v] = self.adjlist_inner_dict_factory()
794
+ self._node[v] = self.node_attr_dict_factory()
795
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
796
+ datadict.update(attr)
797
+ datadict.update(dd)
798
+ self._succ[u][v] = datadict
799
+ self._pred[v][u] = datadict
800
+ nx._clear_cache(self)
801
+
802
+ def remove_edge(self, u, v):
803
+ """Remove the edge between u and v.
804
+
805
+ Parameters
806
+ ----------
807
+ u, v : nodes
808
+ Remove the edge between nodes u and v.
809
+
810
+ Raises
811
+ ------
812
+ NetworkXError
813
+ If there is not an edge between u and v.
814
+
815
+ See Also
816
+ --------
817
+ remove_edges_from : remove a collection of edges
818
+
819
+ Examples
820
+ --------
821
+ >>> G = nx.Graph() # or DiGraph, etc
822
+ >>> nx.add_path(G, [0, 1, 2, 3])
823
+ >>> G.remove_edge(0, 1)
824
+ >>> e = (1, 2)
825
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
826
+ >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
827
+ >>> G.remove_edge(*e[:2]) # select first part of edge tuple
828
+ """
829
+ try:
830
+ del self._succ[u][v]
831
+ del self._pred[v][u]
832
+ except KeyError as err:
833
+ raise NetworkXError(f"The edge {u}-{v} not in graph.") from err
834
+ nx._clear_cache(self)
835
+
836
+ def remove_edges_from(self, ebunch):
837
+ """Remove all edges specified in ebunch.
838
+
839
+ Parameters
840
+ ----------
841
+ ebunch: list or container of edge tuples
842
+ Each edge given in the list or container will be removed
843
+ from the graph. The edges can be:
844
+
845
+ - 2-tuples (u, v) edge between u and v.
846
+ - 3-tuples (u, v, k) where k is ignored.
847
+
848
+ See Also
849
+ --------
850
+ remove_edge : remove a single edge
851
+
852
+ Notes
853
+ -----
854
+ Will fail silently if an edge in ebunch is not in the graph.
855
+
856
+ Examples
857
+ --------
858
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
859
+ >>> ebunch = [(1, 2), (2, 3)]
860
+ >>> G.remove_edges_from(ebunch)
861
+ """
862
+ for e in ebunch:
863
+ u, v = e[:2] # ignore edge data
864
+ if u in self._succ and v in self._succ[u]:
865
+ del self._succ[u][v]
866
+ del self._pred[v][u]
867
+ nx._clear_cache(self)
868
+
869
+ def has_successor(self, u, v):
870
+ """Returns True if node u has successor v.
871
+
872
+ This is true if graph has the edge u->v.
873
+ """
874
+ return u in self._succ and v in self._succ[u]
875
+
876
+ def has_predecessor(self, u, v):
877
+ """Returns True if node u has predecessor v.
878
+
879
+ This is true if graph has the edge u<-v.
880
+ """
881
+ return u in self._pred and v in self._pred[u]
882
+
883
+ def successors(self, n):
884
+ """Returns an iterator over successor nodes of n.
885
+
886
+ A successor of n is a node m such that there exists a directed
887
+ edge from n to m.
888
+
889
+ Parameters
890
+ ----------
891
+ n : node
892
+ A node in the graph
893
+
894
+ Raises
895
+ ------
896
+ NetworkXError
897
+ If n is not in the graph.
898
+
899
+ See Also
900
+ --------
901
+ predecessors
902
+
903
+ Notes
904
+ -----
905
+ neighbors() and successors() are the same.
906
+ """
907
+ try:
908
+ return iter(self._succ[n])
909
+ except KeyError as err:
910
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
911
+
912
+ # digraph definitions
913
+ neighbors = successors
914
+
915
+ def predecessors(self, n):
916
+ """Returns an iterator over predecessor nodes of n.
917
+
918
+ A predecessor of n is a node m such that there exists a directed
919
+ edge from m to n.
920
+
921
+ Parameters
922
+ ----------
923
+ n : node
924
+ A node in the graph
925
+
926
+ Raises
927
+ ------
928
+ NetworkXError
929
+ If n is not in the graph.
930
+
931
+ See Also
932
+ --------
933
+ successors
934
+ """
935
+ try:
936
+ return iter(self._pred[n])
937
+ except KeyError as err:
938
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
939
+
940
+ @cached_property
941
+ def edges(self):
942
+ """An OutEdgeView of the DiGraph as G.edges or G.edges().
943
+
944
+ edges(self, nbunch=None, data=False, default=None)
945
+
946
+ The OutEdgeView provides set-like operations on the edge-tuples
947
+ as well as edge attribute lookup. When called, it also provides
948
+ an EdgeDataView object which allows control of access to edge
949
+ attributes (but does not provide set-like operations).
950
+ Hence, `G.edges[u, v]['color']` provides the value of the color
951
+ attribute for edge `(u, v)` while
952
+ `for (u, v, c) in G.edges.data('color', default='red'):`
953
+ iterates through all the edges yielding the color attribute
954
+ with default `'red'` if no color attribute exists.
955
+
956
+ Parameters
957
+ ----------
958
+ nbunch : single node, container, or all nodes (default= all nodes)
959
+ The view will only report edges from these nodes.
960
+ data : string or bool, optional (default=False)
961
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
962
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
963
+ If False, return 2-tuple (u, v).
964
+ default : value, optional (default=None)
965
+ Value used for edges that don't have the requested attribute.
966
+ Only relevant if data is not True or False.
967
+
968
+ Returns
969
+ -------
970
+ edges : OutEdgeView
971
+ A view of edge attributes, usually it iterates over (u, v)
972
+ or (u, v, d) tuples of edges, but can also be used for
973
+ attribute lookup as `edges[u, v]['foo']`.
974
+
975
+ See Also
976
+ --------
977
+ in_edges, out_edges
978
+
979
+ Notes
980
+ -----
981
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
982
+ For directed graphs this returns the out-edges.
983
+
984
+ Examples
985
+ --------
986
+ >>> G = nx.DiGraph() # or MultiDiGraph, etc
987
+ >>> nx.add_path(G, [0, 1, 2])
988
+ >>> G.add_edge(2, 3, weight=5)
989
+ >>> [e for e in G.edges]
990
+ [(0, 1), (1, 2), (2, 3)]
991
+ >>> G.edges.data() # default data is {} (empty dict)
992
+ OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
993
+ >>> G.edges.data("weight", default=1)
994
+ OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
995
+ >>> G.edges([0, 2]) # only edges originating from these nodes
996
+ OutEdgeDataView([(0, 1), (2, 3)])
997
+ >>> G.edges(0) # only edges from node 0
998
+ OutEdgeDataView([(0, 1)])
999
+
1000
+ """
1001
+ return OutEdgeView(self)
1002
+
1003
+ # alias out_edges to edges
1004
+ @cached_property
1005
+ def out_edges(self):
1006
+ return OutEdgeView(self)
1007
+
1008
+ out_edges.__doc__ = edges.__doc__
1009
+
1010
+ @cached_property
1011
+ def in_edges(self):
1012
+ """A view of the in edges of the graph as G.in_edges or G.in_edges().
1013
+
1014
+ in_edges(self, nbunch=None, data=False, default=None):
1015
+
1016
+ Parameters
1017
+ ----------
1018
+ nbunch : single node, container, or all nodes (default= all nodes)
1019
+ The view will only report edges incident to these nodes.
1020
+ data : string or bool, optional (default=False)
1021
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
1022
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
1023
+ If False, return 2-tuple (u, v).
1024
+ default : value, optional (default=None)
1025
+ Value used for edges that don't have the requested attribute.
1026
+ Only relevant if data is not True or False.
1027
+
1028
+ Returns
1029
+ -------
1030
+ in_edges : InEdgeView or InEdgeDataView
1031
+ A view of edge attributes, usually it iterates over (u, v)
1032
+ or (u, v, d) tuples of edges, but can also be used for
1033
+ attribute lookup as `edges[u, v]['foo']`.
1034
+
1035
+ Examples
1036
+ --------
1037
+ >>> G = nx.DiGraph()
1038
+ >>> G.add_edge(1, 2, color="blue")
1039
+ >>> G.in_edges()
1040
+ InEdgeView([(1, 2)])
1041
+ >>> G.in_edges(nbunch=2)
1042
+ InEdgeDataView([(1, 2)])
1043
+
1044
+ See Also
1045
+ --------
1046
+ edges
1047
+ """
1048
+ return InEdgeView(self)
1049
+
1050
+ @cached_property
1051
+ def degree(self):
1052
+ """A DegreeView for the Graph as G.degree or G.degree().
1053
+
1054
+ The node degree is the number of edges adjacent to the node.
1055
+ The weighted node degree is the sum of the edge weights for
1056
+ edges incident to that node.
1057
+
1058
+ This object provides an iterator for (node, degree) as well as
1059
+ lookup for the degree for a single node.
1060
+
1061
+ Parameters
1062
+ ----------
1063
+ nbunch : single node, container, or all nodes (default= all nodes)
1064
+ The view will only report edges incident to these nodes.
1065
+
1066
+ weight : string or None, optional (default=None)
1067
+ The name of an edge attribute that holds the numerical value used
1068
+ as a weight. If None, then each edge has weight 1.
1069
+ The degree is the sum of the edge weights adjacent to the node.
1070
+
1071
+ Returns
1072
+ -------
1073
+ DiDegreeView or int
1074
+ If multiple nodes are requested (the default), returns a `DiDegreeView`
1075
+ mapping nodes to their degree.
1076
+ If a single node is requested, returns the degree of the node as an integer.
1077
+
1078
+ See Also
1079
+ --------
1080
+ in_degree, out_degree
1081
+
1082
+ Examples
1083
+ --------
1084
+ >>> G = nx.DiGraph() # or MultiDiGraph
1085
+ >>> nx.add_path(G, [0, 1, 2, 3])
1086
+ >>> G.degree(0) # node 0 with degree 1
1087
+ 1
1088
+ >>> list(G.degree([0, 1, 2]))
1089
+ [(0, 1), (1, 2), (2, 2)]
1090
+
1091
+ """
1092
+ return DiDegreeView(self)
1093
+
1094
+ @cached_property
1095
+ def in_degree(self):
1096
+ """An InDegreeView for (node, in_degree) or in_degree for single node.
1097
+
1098
+ The node in_degree is the number of edges pointing to the node.
1099
+ The weighted node degree is the sum of the edge weights for
1100
+ edges incident to that node.
1101
+
1102
+ This object provides an iteration over (node, in_degree) as well as
1103
+ lookup for the degree for a single node.
1104
+
1105
+ Parameters
1106
+ ----------
1107
+ nbunch : single node, container, or all nodes (default= all nodes)
1108
+ The view will only report edges incident to these nodes.
1109
+
1110
+ weight : string or None, optional (default=None)
1111
+ The name of an edge attribute that holds the numerical value used
1112
+ as a weight. If None, then each edge has weight 1.
1113
+ The degree is the sum of the edge weights adjacent to the node.
1114
+
1115
+ Returns
1116
+ -------
1117
+ If a single node is requested
1118
+ deg : int
1119
+ In-degree of the node
1120
+
1121
+ OR if multiple nodes are requested
1122
+ nd_iter : iterator
1123
+ The iterator returns two-tuples of (node, in-degree).
1124
+
1125
+ See Also
1126
+ --------
1127
+ degree, out_degree
1128
+
1129
+ Examples
1130
+ --------
1131
+ >>> G = nx.DiGraph()
1132
+ >>> nx.add_path(G, [0, 1, 2, 3])
1133
+ >>> G.in_degree(0) # node 0 with degree 0
1134
+ 0
1135
+ >>> list(G.in_degree([0, 1, 2]))
1136
+ [(0, 0), (1, 1), (2, 1)]
1137
+
1138
+ """
1139
+ return InDegreeView(self)
1140
+
1141
+ @cached_property
1142
+ def out_degree(self):
1143
+ """An OutDegreeView for (node, out_degree)
1144
+
1145
+ The node out_degree is the number of edges pointing out of the node.
1146
+ The weighted node degree is the sum of the edge weights for
1147
+ edges incident to that node.
1148
+
1149
+ This object provides an iterator over (node, out_degree) as well as
1150
+ lookup for the degree for a single node.
1151
+
1152
+ Parameters
1153
+ ----------
1154
+ nbunch : single node, container, or all nodes (default= all nodes)
1155
+ The view will only report edges incident to these nodes.
1156
+
1157
+ weight : string or None, optional (default=None)
1158
+ The name of an edge attribute that holds the numerical value used
1159
+ as a weight. If None, then each edge has weight 1.
1160
+ The degree is the sum of the edge weights adjacent to the node.
1161
+
1162
+ Returns
1163
+ -------
1164
+ If a single node is requested
1165
+ deg : int
1166
+ Out-degree of the node
1167
+
1168
+ OR if multiple nodes are requested
1169
+ nd_iter : iterator
1170
+ The iterator returns two-tuples of (node, out-degree).
1171
+
1172
+ See Also
1173
+ --------
1174
+ degree, in_degree
1175
+
1176
+ Examples
1177
+ --------
1178
+ >>> G = nx.DiGraph()
1179
+ >>> nx.add_path(G, [0, 1, 2, 3])
1180
+ >>> G.out_degree(0) # node 0 with degree 1
1181
+ 1
1182
+ >>> list(G.out_degree([0, 1, 2]))
1183
+ [(0, 1), (1, 1), (2, 1)]
1184
+
1185
+ """
1186
+ return OutDegreeView(self)
1187
+
1188
+ def clear(self):
1189
+ """Remove all nodes and edges from the graph.
1190
+
1191
+ This also removes the name, and all graph, node, and edge attributes.
1192
+
1193
+ Examples
1194
+ --------
1195
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1196
+ >>> G.clear()
1197
+ >>> list(G.nodes)
1198
+ []
1199
+ >>> list(G.edges)
1200
+ []
1201
+
1202
+ """
1203
+ self._succ.clear()
1204
+ self._pred.clear()
1205
+ self._node.clear()
1206
+ self.graph.clear()
1207
+ nx._clear_cache(self)
1208
+
1209
+ def clear_edges(self):
1210
+ """Remove all edges from the graph without altering nodes.
1211
+
1212
+ Examples
1213
+ --------
1214
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1215
+ >>> G.clear_edges()
1216
+ >>> list(G.nodes)
1217
+ [0, 1, 2, 3]
1218
+ >>> list(G.edges)
1219
+ []
1220
+
1221
+ """
1222
+ for predecessor_dict in self._pred.values():
1223
+ predecessor_dict.clear()
1224
+ for successor_dict in self._succ.values():
1225
+ successor_dict.clear()
1226
+ nx._clear_cache(self)
1227
+
1228
+ def is_multigraph(self):
1229
+ """Returns True if graph is a multigraph, False otherwise."""
1230
+ return False
1231
+
1232
+ def is_directed(self):
1233
+ """Returns True if graph is directed, False otherwise."""
1234
+ return True
1235
+
1236
+ def to_undirected(self, reciprocal=False, as_view=False):
1237
+ """Returns an undirected representation of the digraph.
1238
+
1239
+ Parameters
1240
+ ----------
1241
+ reciprocal : bool (optional)
1242
+ If True only keep edges that appear in both directions
1243
+ in the original digraph.
1244
+ as_view : bool (optional, default=False)
1245
+ If True return an undirected view of the original directed graph.
1246
+
1247
+ Returns
1248
+ -------
1249
+ G : Graph
1250
+ An undirected graph with the same name and nodes and
1251
+ with edge (u, v, data) if either (u, v, data) or (v, u, data)
1252
+ is in the digraph. If both edges exist in digraph and
1253
+ their edge data is different, only one edge is created
1254
+ with an arbitrary choice of which edge data to use.
1255
+ You must check and correct for this manually if desired.
1256
+
1257
+ See Also
1258
+ --------
1259
+ Graph, copy, add_edge, add_edges_from
1260
+
1261
+ Notes
1262
+ -----
1263
+ If edges in both directions (u, v) and (v, u) exist in the
1264
+ graph, attributes for the new undirected edge will be a combination of
1265
+ the attributes of the directed edges. The edge data is updated
1266
+ in the (arbitrary) order that the edges are encountered. For
1267
+ more customized control of the edge attributes use add_edge().
1268
+
1269
+ This returns a "deepcopy" of the edge, node, and
1270
+ graph attributes which attempts to completely copy
1271
+ all of the data and references.
1272
+
1273
+ This is in contrast to the similar G=DiGraph(D) which returns a
1274
+ shallow copy of the data.
1275
+
1276
+ See the Python copy module for more information on shallow
1277
+ and deep copies, https://docs.python.org/3/library/copy.html.
1278
+
1279
+ Warning: If you have subclassed DiGraph to use dict-like objects
1280
+ in the data structure, those changes do not transfer to the
1281
+ Graph created by this method.
1282
+
1283
+ Examples
1284
+ --------
1285
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
1286
+ >>> H = G.to_directed()
1287
+ >>> list(H.edges)
1288
+ [(0, 1), (1, 0)]
1289
+ >>> G2 = H.to_undirected()
1290
+ >>> list(G2.edges)
1291
+ [(0, 1)]
1292
+ """
1293
+ graph_class = self.to_undirected_class()
1294
+ if as_view is True:
1295
+ return nx.graphviews.generic_graph_view(self, graph_class)
1296
+ # deepcopy when not a view
1297
+ G = graph_class()
1298
+ G.graph.update(deepcopy(self.graph))
1299
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1300
+ if reciprocal is True:
1301
+ G.add_edges_from(
1302
+ (u, v, deepcopy(d))
1303
+ for u, nbrs in self._adj.items()
1304
+ for v, d in nbrs.items()
1305
+ if v in self._pred[u]
1306
+ )
1307
+ else:
1308
+ G.add_edges_from(
1309
+ (u, v, deepcopy(d))
1310
+ for u, nbrs in self._adj.items()
1311
+ for v, d in nbrs.items()
1312
+ )
1313
+ return G
1314
+
1315
+ def reverse(self, copy=True):
1316
+ """Returns the reverse of the graph.
1317
+
1318
+ The reverse is a graph with the same nodes and edges
1319
+ but with the directions of the edges reversed.
1320
+
1321
+ Parameters
1322
+ ----------
1323
+ copy : bool optional (default=True)
1324
+ If True, return a new DiGraph holding the reversed edges.
1325
+ If False, the reverse graph is created using a view of
1326
+ the original graph.
1327
+ """
1328
+ if copy:
1329
+ H = self.__class__()
1330
+ H.graph.update(deepcopy(self.graph))
1331
+ H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items())
1332
+ H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True))
1333
+ return H
1334
+ return nx.reverse_view(self)
env-llmeval/lib/python3.10/site-packages/networkx/classes/filters.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ __all__ = [
6
+ "no_filter",
7
+ "hide_nodes",
8
+ "hide_edges",
9
+ "hide_multiedges",
10
+ "hide_diedges",
11
+ "hide_multidiedges",
12
+ "show_nodes",
13
+ "show_edges",
14
+ "show_multiedges",
15
+ "show_diedges",
16
+ "show_multidiedges",
17
+ ]
18
+
19
+
20
+ def no_filter(*items):
21
+ """Returns a filter function that always evaluates to True."""
22
+ return True
23
+
24
+
25
+ def hide_nodes(nodes):
26
+ """Returns a filter function that hides specific nodes."""
27
+ nodes = set(nodes)
28
+ return lambda node: node not in nodes
29
+
30
+
31
+ def hide_diedges(edges):
32
+ """Returns a filter function that hides specific directed edges."""
33
+ edges = {(u, v) for u, v in edges}
34
+ return lambda u, v: (u, v) not in edges
35
+
36
+
37
+ def hide_edges(edges):
38
+ """Returns a filter function that hides specific undirected edges."""
39
+ alledges = set(edges) | {(v, u) for (u, v) in edges}
40
+ return lambda u, v: (u, v) not in alledges
41
+
42
+
43
+ def hide_multidiedges(edges):
44
+ """Returns a filter function that hides specific multi-directed edges."""
45
+ edges = {(u, v, k) for u, v, k in edges}
46
+ return lambda u, v, k: (u, v, k) not in edges
47
+
48
+
49
+ def hide_multiedges(edges):
50
+ """Returns a filter function that hides specific multi-undirected edges."""
51
+ alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
52
+ return lambda u, v, k: (u, v, k) not in alledges
53
+
54
+
55
+ # write show_nodes as a class to make SubGraph pickleable
56
+ class show_nodes:
57
+ """Filter class to show specific nodes."""
58
+
59
+ def __init__(self, nodes):
60
+ self.nodes = set(nodes)
61
+
62
+ def __call__(self, node):
63
+ return node in self.nodes
64
+
65
+
66
+ def show_diedges(edges):
67
+ """Returns a filter function that shows specific directed edges."""
68
+ edges = {(u, v) for u, v in edges}
69
+ return lambda u, v: (u, v) in edges
70
+
71
+
72
+ def show_edges(edges):
73
+ """Returns a filter function that shows specific undirected edges."""
74
+ alledges = set(edges) | {(v, u) for (u, v) in edges}
75
+ return lambda u, v: (u, v) in alledges
76
+
77
+
78
+ def show_multidiedges(edges):
79
+ """Returns a filter function that shows specific multi-directed edges."""
80
+ edges = {(u, v, k) for u, v, k in edges}
81
+ return lambda u, v, k: (u, v, k) in edges
82
+
83
+
84
+ def show_multiedges(edges):
85
+ """Returns a filter function that shows specific multi-undirected edges."""
86
+ alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
87
+ return lambda u, v, k: (u, v, k) in alledges
env-llmeval/lib/python3.10/site-packages/networkx/classes/function.py ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functional interface to graph methods and assorted utilities.
2
+ """
3
+
4
+ from collections import Counter
5
+ from itertools import chain
6
+
7
+ import networkx as nx
8
+ from networkx.utils import not_implemented_for, pairwise
9
+
10
+ __all__ = [
11
+ "nodes",
12
+ "edges",
13
+ "degree",
14
+ "degree_histogram",
15
+ "neighbors",
16
+ "number_of_nodes",
17
+ "number_of_edges",
18
+ "density",
19
+ "is_directed",
20
+ "freeze",
21
+ "is_frozen",
22
+ "subgraph",
23
+ "induced_subgraph",
24
+ "edge_subgraph",
25
+ "restricted_view",
26
+ "to_directed",
27
+ "to_undirected",
28
+ "add_star",
29
+ "add_path",
30
+ "add_cycle",
31
+ "create_empty_copy",
32
+ "set_node_attributes",
33
+ "get_node_attributes",
34
+ "set_edge_attributes",
35
+ "get_edge_attributes",
36
+ "all_neighbors",
37
+ "non_neighbors",
38
+ "non_edges",
39
+ "common_neighbors",
40
+ "is_weighted",
41
+ "is_negatively_weighted",
42
+ "is_empty",
43
+ "selfloop_edges",
44
+ "nodes_with_selfloops",
45
+ "number_of_selfloops",
46
+ "path_weight",
47
+ "is_path",
48
+ ]
49
+
50
+
51
+ def nodes(G):
52
+ """Returns a NodeView over the graph nodes.
53
+
54
+ This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
55
+ """
56
+ return G.nodes()
57
+
58
+
59
+ def edges(G, nbunch=None):
60
+ """Returns an edge view of edges incident to nodes in nbunch.
61
+
62
+ Return all edges if nbunch is unspecified or nbunch=None.
63
+
64
+ For digraphs, edges=out_edges
65
+
66
+ This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
67
+ """
68
+ return G.edges(nbunch)
69
+
70
+
71
+ def degree(G, nbunch=None, weight=None):
72
+ """Returns a degree view of single node or of nbunch of nodes.
73
+ If nbunch is omitted, then return degrees of *all* nodes.
74
+
75
+ This function wraps the :func:`G.degree <networkx.Graph.degree>` property.
76
+ """
77
+ return G.degree(nbunch, weight)
78
+
79
+
80
+ def neighbors(G, n):
81
+ """Returns an iterator over all neighbors of node n.
82
+
83
+ This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
84
+ """
85
+ return G.neighbors(n)
86
+
87
+
88
+ def number_of_nodes(G):
89
+ """Returns the number of nodes in the graph.
90
+
91
+ This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
92
+ """
93
+ return G.number_of_nodes()
94
+
95
+
96
+ def number_of_edges(G):
97
+ """Returns the number of edges in the graph.
98
+
99
+ This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
100
+ """
101
+ return G.number_of_edges()
102
+
103
+
104
+ def density(G):
105
+ r"""Returns the density of a graph.
106
+
107
+ The density for undirected graphs is
108
+
109
+ .. math::
110
+
111
+ d = \frac{2m}{n(n-1)},
112
+
113
+ and for directed graphs is
114
+
115
+ .. math::
116
+
117
+ d = \frac{m}{n(n-1)},
118
+
119
+ where `n` is the number of nodes and `m` is the number of edges in `G`.
120
+
121
+ Notes
122
+ -----
123
+ The density is 0 for a graph without edges and 1 for a complete graph.
124
+ The density of multigraphs can be higher than 1.
125
+
126
+ Self loops are counted in the total number of edges so graphs with self
127
+ loops can have density higher than 1.
128
+ """
129
+ n = number_of_nodes(G)
130
+ m = number_of_edges(G)
131
+ if m == 0 or n <= 1:
132
+ return 0
133
+ d = m / (n * (n - 1))
134
+ if not G.is_directed():
135
+ d *= 2
136
+ return d
137
+
138
+
139
+ def degree_histogram(G):
140
+ """Returns a list of the frequency of each degree value.
141
+
142
+ Parameters
143
+ ----------
144
+ G : Networkx graph
145
+ A graph
146
+
147
+ Returns
148
+ -------
149
+ hist : list
150
+ A list of frequencies of degrees.
151
+ The degree values are the index in the list.
152
+
153
+ Notes
154
+ -----
155
+ Note: the bins are width one, hence len(list) can be large
156
+ (Order(number_of_edges))
157
+ """
158
+ counts = Counter(d for n, d in G.degree())
159
+ return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
160
+
161
+
162
+ def is_directed(G):
163
+ """Return True if graph is directed."""
164
+ return G.is_directed()
165
+
166
+
167
+ def frozen(*args, **kwargs):
168
+ """Dummy method for raising errors when trying to modify frozen graphs"""
169
+ raise nx.NetworkXError("Frozen graph can't be modified")
170
+
171
+
172
+ def freeze(G):
173
+ """Modify graph to prevent further change by adding or removing
174
+ nodes or edges.
175
+
176
+ Node and edge data can still be modified.
177
+
178
+ Parameters
179
+ ----------
180
+ G : graph
181
+ A NetworkX graph
182
+
183
+ Examples
184
+ --------
185
+ >>> G = nx.path_graph(4)
186
+ >>> G = nx.freeze(G)
187
+ >>> try:
188
+ ... G.add_edge(4, 5)
189
+ ... except nx.NetworkXError as err:
190
+ ... print(str(err))
191
+ Frozen graph can't be modified
192
+
193
+ Notes
194
+ -----
195
+ To "unfreeze" a graph you must make a copy by creating a new graph object:
196
+
197
+ >>> graph = nx.path_graph(4)
198
+ >>> frozen_graph = nx.freeze(graph)
199
+ >>> unfrozen_graph = nx.Graph(frozen_graph)
200
+ >>> nx.is_frozen(unfrozen_graph)
201
+ False
202
+
203
+ See Also
204
+ --------
205
+ is_frozen
206
+ """
207
+ G.add_node = frozen
208
+ G.add_nodes_from = frozen
209
+ G.remove_node = frozen
210
+ G.remove_nodes_from = frozen
211
+ G.add_edge = frozen
212
+ G.add_edges_from = frozen
213
+ G.add_weighted_edges_from = frozen
214
+ G.remove_edge = frozen
215
+ G.remove_edges_from = frozen
216
+ G.clear = frozen
217
+ G.clear_edges = frozen
218
+ G.frozen = True
219
+ return G
220
+
221
+
222
+ def is_frozen(G):
223
+ """Returns True if graph is frozen.
224
+
225
+ Parameters
226
+ ----------
227
+ G : graph
228
+ A NetworkX graph
229
+
230
+ See Also
231
+ --------
232
+ freeze
233
+ """
234
+ try:
235
+ return G.frozen
236
+ except AttributeError:
237
+ return False
238
+
239
+
240
+ def add_star(G_to_add_to, nodes_for_star, **attr):
241
+ """Add a star to Graph G_to_add_to.
242
+
243
+ The first node in `nodes_for_star` is the middle of the star.
244
+ It is connected to all other nodes.
245
+
246
+ Parameters
247
+ ----------
248
+ G_to_add_to : graph
249
+ A NetworkX graph
250
+ nodes_for_star : iterable container
251
+ A container of nodes.
252
+ attr : keyword arguments, optional (default= no attributes)
253
+ Attributes to add to every edge in star.
254
+
255
+ See Also
256
+ --------
257
+ add_path, add_cycle
258
+
259
+ Examples
260
+ --------
261
+ >>> G = nx.Graph()
262
+ >>> nx.add_star(G, [0, 1, 2, 3])
263
+ >>> nx.add_star(G, [10, 11, 12], weight=2)
264
+ """
265
+ nlist = iter(nodes_for_star)
266
+ try:
267
+ v = next(nlist)
268
+ except StopIteration:
269
+ return
270
+ G_to_add_to.add_node(v)
271
+ edges = ((v, n) for n in nlist)
272
+ G_to_add_to.add_edges_from(edges, **attr)
273
+
274
+
275
+ def add_path(G_to_add_to, nodes_for_path, **attr):
276
+ """Add a path to the Graph G_to_add_to.
277
+
278
+ Parameters
279
+ ----------
280
+ G_to_add_to : graph
281
+ A NetworkX graph
282
+ nodes_for_path : iterable container
283
+ A container of nodes. A path will be constructed from
284
+ the nodes (in order) and added to the graph.
285
+ attr : keyword arguments, optional (default= no attributes)
286
+ Attributes to add to every edge in path.
287
+
288
+ See Also
289
+ --------
290
+ add_star, add_cycle
291
+
292
+ Examples
293
+ --------
294
+ >>> G = nx.Graph()
295
+ >>> nx.add_path(G, [0, 1, 2, 3])
296
+ >>> nx.add_path(G, [10, 11, 12], weight=7)
297
+ """
298
+ nlist = iter(nodes_for_path)
299
+ try:
300
+ first_node = next(nlist)
301
+ except StopIteration:
302
+ return
303
+ G_to_add_to.add_node(first_node)
304
+ G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
305
+
306
+
307
+ def add_cycle(G_to_add_to, nodes_for_cycle, **attr):
308
+ """Add a cycle to the Graph G_to_add_to.
309
+
310
+ Parameters
311
+ ----------
312
+ G_to_add_to : graph
313
+ A NetworkX graph
314
+ nodes_for_cycle: iterable container
315
+ A container of nodes. A cycle will be constructed from
316
+ the nodes (in order) and added to the graph.
317
+ attr : keyword arguments, optional (default= no attributes)
318
+ Attributes to add to every edge in cycle.
319
+
320
+ See Also
321
+ --------
322
+ add_path, add_star
323
+
324
+ Examples
325
+ --------
326
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
327
+ >>> nx.add_cycle(G, [0, 1, 2, 3])
328
+ >>> nx.add_cycle(G, [10, 11, 12], weight=7)
329
+ """
330
+ nlist = iter(nodes_for_cycle)
331
+ try:
332
+ first_node = next(nlist)
333
+ except StopIteration:
334
+ return
335
+ G_to_add_to.add_node(first_node)
336
+ G_to_add_to.add_edges_from(
337
+ pairwise(chain((first_node,), nlist), cyclic=True), **attr
338
+ )
339
+
340
+
341
+ def subgraph(G, nbunch):
342
+ """Returns the subgraph induced on nodes in nbunch.
343
+
344
+ Parameters
345
+ ----------
346
+ G : graph
347
+ A NetworkX graph
348
+
349
+ nbunch : list, iterable
350
+ A container of nodes that will be iterated through once (thus
351
+ it should be an iterator or be iterable). Each element of the
352
+ container should be a valid node type: any hashable type except
353
+ None. If nbunch is None, return all edges data in the graph.
354
+ Nodes in nbunch that are not in the graph will be (quietly)
355
+ ignored.
356
+
357
+ Notes
358
+ -----
359
+ subgraph(G) calls G.subgraph()
360
+ """
361
+ return G.subgraph(nbunch)
362
+
363
+
364
+ def induced_subgraph(G, nbunch):
365
+ """Returns a SubGraph view of `G` showing only nodes in nbunch.
366
+
367
+ The induced subgraph of a graph on a set of nodes N is the
368
+ graph with nodes N and edges from G which have both ends in N.
369
+
370
+ Parameters
371
+ ----------
372
+ G : NetworkX Graph
373
+ nbunch : node, container of nodes or None (for all nodes)
374
+
375
+ Returns
376
+ -------
377
+ subgraph : SubGraph View
378
+ A read-only view of the subgraph in `G` induced by the nodes.
379
+ Changes to the graph `G` will be reflected in the view.
380
+
381
+ Notes
382
+ -----
383
+ To create a mutable subgraph with its own copies of nodes
384
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
385
+
386
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
387
+ `G.remove_nodes_from(n in G if n not in set(nbunch))`
388
+
389
+ If you are going to compute subgraphs of your subgraphs you could
390
+ end up with a chain of views that can be very slow once the chain
391
+ has about 15 views in it. If they are all induced subgraphs, you
392
+ can short-cut the chain by making them all subgraphs of the original
393
+ graph. The graph class method `G.subgraph` does this when `G` is
394
+ a subgraph. In contrast, this function allows you to choose to build
395
+ chains or not, as you wish. The returned subgraph is a view on `G`.
396
+
397
+ Examples
398
+ --------
399
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
400
+ >>> H = nx.induced_subgraph(G, [0, 1, 3])
401
+ >>> list(H.edges)
402
+ [(0, 1)]
403
+ >>> list(H.nodes)
404
+ [0, 1, 3]
405
+ """
406
+ induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
407
+ return nx.subgraph_view(G, filter_node=induced_nodes)
408
+
409
+
410
+ def edge_subgraph(G, edges):
411
+ """Returns a view of the subgraph induced by the specified edges.
412
+
413
+ The induced subgraph contains each edge in `edges` and each
414
+ node incident to any of those edges.
415
+
416
+ Parameters
417
+ ----------
418
+ G : NetworkX Graph
419
+ edges : iterable
420
+ An iterable of edges. Edges not present in `G` are ignored.
421
+
422
+ Returns
423
+ -------
424
+ subgraph : SubGraph View
425
+ A read-only edge-induced subgraph of `G`.
426
+ Changes to `G` are reflected in the view.
427
+
428
+ Notes
429
+ -----
430
+ To create a mutable subgraph with its own copies of nodes
431
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
432
+
433
+ If you create a subgraph of a subgraph recursively you can end up
434
+ with a chain of subgraphs that becomes very slow with about 15
435
+ nested subgraph views. Luckily the edge_subgraph filter nests
436
+ nicely so you can use the original graph as G in this function
437
+ to avoid chains. We do not rule out chains programmatically so
438
+ that odd cases like an `edge_subgraph` of a `restricted_view`
439
+ can be created.
440
+
441
+ Examples
442
+ --------
443
+ >>> G = nx.path_graph(5)
444
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
445
+ >>> list(H.nodes)
446
+ [0, 1, 3, 4]
447
+ >>> list(H.edges)
448
+ [(0, 1), (3, 4)]
449
+ """
450
+ nxf = nx.filters
451
+ edges = set(edges)
452
+ nodes = set()
453
+ for e in edges:
454
+ nodes.update(e[:2])
455
+ induced_nodes = nxf.show_nodes(nodes)
456
+ if G.is_multigraph():
457
+ if G.is_directed():
458
+ induced_edges = nxf.show_multidiedges(edges)
459
+ else:
460
+ induced_edges = nxf.show_multiedges(edges)
461
+ else:
462
+ if G.is_directed():
463
+ induced_edges = nxf.show_diedges(edges)
464
+ else:
465
+ induced_edges = nxf.show_edges(edges)
466
+ return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
467
+
468
+
469
+ def restricted_view(G, nodes, edges):
470
+ """Returns a view of `G` with hidden nodes and edges.
471
+
472
+ The resulting subgraph filters out node `nodes` and edges `edges`.
473
+ Filtered out nodes also filter out any of their edges.
474
+
475
+ Parameters
476
+ ----------
477
+ G : NetworkX Graph
478
+ nodes : iterable
479
+ An iterable of nodes. Nodes not present in `G` are ignored.
480
+ edges : iterable
481
+ An iterable of edges. Edges not present in `G` are ignored.
482
+
483
+ Returns
484
+ -------
485
+ subgraph : SubGraph View
486
+ A read-only restricted view of `G` filtering out nodes and edges.
487
+ Changes to `G` are reflected in the view.
488
+
489
+ Notes
490
+ -----
491
+ To create a mutable subgraph with its own copies of nodes
492
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
493
+
494
+ If you create a subgraph of a subgraph recursively you may end up
495
+ with a chain of subgraph views. Such chains can get quite slow
496
+ for lengths near 15. To avoid long chains, try to make your subgraph
497
+ based on the original graph. We do not rule out chains programmatically
498
+ so that odd cases like an `edge_subgraph` of a `restricted_view`
499
+ can be created.
500
+
501
+ Examples
502
+ --------
503
+ >>> G = nx.path_graph(5)
504
+ >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)])
505
+ >>> list(H.nodes)
506
+ [1, 2, 3, 4]
507
+ >>> list(H.edges)
508
+ [(2, 3)]
509
+ """
510
+ nxf = nx.filters
511
+ hide_nodes = nxf.hide_nodes(nodes)
512
+ if G.is_multigraph():
513
+ if G.is_directed():
514
+ hide_edges = nxf.hide_multidiedges(edges)
515
+ else:
516
+ hide_edges = nxf.hide_multiedges(edges)
517
+ else:
518
+ if G.is_directed():
519
+ hide_edges = nxf.hide_diedges(edges)
520
+ else:
521
+ hide_edges = nxf.hide_edges(edges)
522
+ return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
523
+
524
+
525
+ def to_directed(graph):
526
+ """Returns a directed view of the graph `graph`.
527
+
528
+ Identical to graph.to_directed(as_view=True)
529
+ Note that graph.to_directed defaults to `as_view=False`
530
+ while this function always provides a view.
531
+ """
532
+ return graph.to_directed(as_view=True)
533
+
534
+
535
+ def to_undirected(graph):
536
+ """Returns an undirected view of the graph `graph`.
537
+
538
+ Identical to graph.to_undirected(as_view=True)
539
+ Note that graph.to_undirected defaults to `as_view=False`
540
+ while this function always provides a view.
541
+ """
542
+ return graph.to_undirected(as_view=True)
543
+
544
+
545
+ def create_empty_copy(G, with_data=True):
546
+ """Returns a copy of the graph G with all of the edges removed.
547
+
548
+ Parameters
549
+ ----------
550
+ G : graph
551
+ A NetworkX graph
552
+
553
+ with_data : bool (default=True)
554
+ Propagate Graph and Nodes data to the new graph.
555
+
556
+ See Also
557
+ --------
558
+ empty_graph
559
+
560
+ """
561
+ H = G.__class__()
562
+ H.add_nodes_from(G.nodes(data=with_data))
563
+ if with_data:
564
+ H.graph.update(G.graph)
565
+ return H
566
+
567
+
568
+ def set_node_attributes(G, values, name=None):
569
+ """Sets node attributes from a given value or dictionary of values.
570
+
571
+ .. Warning:: The call order of arguments `values` and `name`
572
+ switched between v1.x & v2.x.
573
+
574
+ Parameters
575
+ ----------
576
+ G : NetworkX Graph
577
+
578
+ values : scalar value, dict-like
579
+ What the node attribute should be set to. If `values` is
580
+ not a dictionary, then it is treated as a single attribute value
581
+ that is then applied to every node in `G`. This means that if
582
+ you provide a mutable object, like a list, updates to that object
583
+ will be reflected in the node attribute for every node.
584
+ The attribute name will be `name`.
585
+
586
+ If `values` is a dict or a dict of dict, it should be keyed
587
+ by node to either an attribute value or a dict of attribute key/value
588
+ pairs used to update the node's attributes.
589
+
590
+ name : string (optional, default=None)
591
+ Name of the node attribute to set if values is a scalar.
592
+
593
+ Examples
594
+ --------
595
+ After computing some property of the nodes of a graph, you may want
596
+ to assign a node attribute to store the value of that property for
597
+ each node::
598
+
599
+ >>> G = nx.path_graph(3)
600
+ >>> bb = nx.betweenness_centrality(G)
601
+ >>> isinstance(bb, dict)
602
+ True
603
+ >>> nx.set_node_attributes(G, bb, "betweenness")
604
+ >>> G.nodes[1]["betweenness"]
605
+ 1.0
606
+
607
+ If you provide a list as the second argument, updates to the list
608
+ will be reflected in the node attribute for each node::
609
+
610
+ >>> G = nx.path_graph(3)
611
+ >>> labels = []
612
+ >>> nx.set_node_attributes(G, labels, "labels")
613
+ >>> labels.append("foo")
614
+ >>> G.nodes[0]["labels"]
615
+ ['foo']
616
+ >>> G.nodes[1]["labels"]
617
+ ['foo']
618
+ >>> G.nodes[2]["labels"]
619
+ ['foo']
620
+
621
+ If you provide a dictionary of dictionaries as the second argument,
622
+ the outer dictionary is assumed to be keyed by node to an inner
623
+ dictionary of node attributes for that node::
624
+
625
+ >>> G = nx.path_graph(3)
626
+ >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}}
627
+ >>> nx.set_node_attributes(G, attrs)
628
+ >>> G.nodes[0]["attr1"]
629
+ 20
630
+ >>> G.nodes[0]["attr2"]
631
+ 'nothing'
632
+ >>> G.nodes[1]["attr2"]
633
+ 3
634
+ >>> G.nodes[2]
635
+ {}
636
+
637
+ Note that if the dictionary contains nodes that are not in `G`, the
638
+ values are silently ignored::
639
+
640
+ >>> G = nx.Graph()
641
+ >>> G.add_node(0)
642
+ >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color")
643
+ >>> G.nodes[0]["color"]
644
+ 'red'
645
+ >>> 1 in G.nodes
646
+ False
647
+
648
+ """
649
+ # Set node attributes based on type of `values`
650
+ if name is not None: # `values` must not be a dict of dict
651
+ try: # `values` is a dict
652
+ for n, v in values.items():
653
+ try:
654
+ G.nodes[n][name] = values[n]
655
+ except KeyError:
656
+ pass
657
+ except AttributeError: # `values` is a constant
658
+ for n in G:
659
+ G.nodes[n][name] = values
660
+ else: # `values` must be dict of dict
661
+ for n, d in values.items():
662
+ try:
663
+ G.nodes[n].update(d)
664
+ except KeyError:
665
+ pass
666
+ nx._clear_cache(G)
667
+
668
+
669
+ def get_node_attributes(G, name, default=None):
670
+ """Get node attributes from graph
671
+
672
+ Parameters
673
+ ----------
674
+ G : NetworkX Graph
675
+
676
+ name : string
677
+ Attribute name
678
+
679
+ default: object (default=None)
680
+ Default value of the node attribute if there is no value set for that
681
+ node in graph. If `None` then nodes without this attribute are not
682
+ included in the returned dict.
683
+
684
+ Returns
685
+ -------
686
+ Dictionary of attributes keyed by node.
687
+
688
+ Examples
689
+ --------
690
+ >>> G = nx.Graph()
691
+ >>> G.add_nodes_from([1, 2, 3], color="red")
692
+ >>> color = nx.get_node_attributes(G, "color")
693
+ >>> color[1]
694
+ 'red'
695
+ >>> G.add_node(4)
696
+ >>> color = nx.get_node_attributes(G, "color", default="yellow")
697
+ >>> color[4]
698
+ 'yellow'
699
+ """
700
+ if default is not None:
701
+ return {n: d.get(name, default) for n, d in G.nodes.items()}
702
+ return {n: d[name] for n, d in G.nodes.items() if name in d}
703
+
704
+
705
+ def set_edge_attributes(G, values, name=None):
706
+ """Sets edge attributes from a given value or dictionary of values.
707
+
708
+ .. Warning:: The call order of arguments `values` and `name`
709
+ switched between v1.x & v2.x.
710
+
711
+ Parameters
712
+ ----------
713
+ G : NetworkX Graph
714
+
715
+ values : scalar value, dict-like
716
+ What the edge attribute should be set to. If `values` is
717
+ not a dictionary, then it is treated as a single attribute value
718
+ that is then applied to every edge in `G`. This means that if
719
+ you provide a mutable object, like a list, updates to that object
720
+ will be reflected in the edge attribute for each edge. The attribute
721
+ name will be `name`.
722
+
723
+ If `values` is a dict or a dict of dict, it should be keyed
724
+ by edge tuple to either an attribute value or a dict of attribute
725
+ key/value pairs used to update the edge's attributes.
726
+ For multigraphs, the edge tuples must be of the form ``(u, v, key)``,
727
+ where `u` and `v` are nodes and `key` is the edge key.
728
+ For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
729
+
730
+ name : string (optional, default=None)
731
+ Name of the edge attribute to set if values is a scalar.
732
+
733
+ Examples
734
+ --------
735
+ After computing some property of the edges of a graph, you may want
736
+ to assign a edge attribute to store the value of that property for
737
+ each edge::
738
+
739
+ >>> G = nx.path_graph(3)
740
+ >>> bb = nx.edge_betweenness_centrality(G, normalized=False)
741
+ >>> nx.set_edge_attributes(G, bb, "betweenness")
742
+ >>> G.edges[1, 2]["betweenness"]
743
+ 2.0
744
+
745
+ If you provide a list as the second argument, updates to the list
746
+ will be reflected in the edge attribute for each edge::
747
+
748
+ >>> labels = []
749
+ >>> nx.set_edge_attributes(G, labels, "labels")
750
+ >>> labels.append("foo")
751
+ >>> G.edges[0, 1]["labels"]
752
+ ['foo']
753
+ >>> G.edges[1, 2]["labels"]
754
+ ['foo']
755
+
756
+ If you provide a dictionary of dictionaries as the second argument,
757
+ the entire dictionary will be used to update edge attributes::
758
+
759
+ >>> G = nx.path_graph(3)
760
+ >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}}
761
+ >>> nx.set_edge_attributes(G, attrs)
762
+ >>> G[0][1]["attr1"]
763
+ 20
764
+ >>> G[0][1]["attr2"]
765
+ 'nothing'
766
+ >>> G[1][2]["attr2"]
767
+ 3
768
+
769
+ The attributes of one Graph can be used to set those of another.
770
+
771
+ >>> H = nx.path_graph(3)
772
+ >>> nx.set_edge_attributes(H, G.edges)
773
+
774
+ Note that if the dict contains edges that are not in `G`, they are
775
+ silently ignored::
776
+
777
+ >>> G = nx.Graph([(0, 1)])
778
+ >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}})
779
+ >>> (1, 2) in G.edges()
780
+ False
781
+
782
+ For multigraphs, the `values` dict is expected to be keyed by 3-tuples
783
+ including the edge key::
784
+
785
+ >>> MG = nx.MultiGraph()
786
+ >>> edges = [(0, 1), (0, 1)]
787
+ >>> MG.add_edges_from(edges) # Returns list of edge keys
788
+ [0, 1]
789
+ >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
790
+ >>> nx.set_edge_attributes(MG, attributes)
791
+ >>> MG[0][1][0]["cost"]
792
+ 21
793
+ >>> MG[0][1][1]["cost"]
794
+ 7
795
+
796
+ If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
797
+ multiedge to a 2-tuple edge and the last multiedge's attribute value will
798
+ overwrite the previous values. Continuing from the previous case we get::
799
+
800
+ >>> H = nx.path_graph([0, 1, 2])
801
+ >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
802
+ >>> nx.get_edge_attributes(H, "cost")
803
+ {(0, 1): 7}
804
+
805
+ """
806
+ if name is not None:
807
+ # `values` does not contain attribute names
808
+ try:
809
+ # if `values` is a dict using `.items()` => {edge: value}
810
+ if G.is_multigraph():
811
+ for (u, v, key), value in values.items():
812
+ try:
813
+ G._adj[u][v][key][name] = value
814
+ except KeyError:
815
+ pass
816
+ else:
817
+ for (u, v), value in values.items():
818
+ try:
819
+ G._adj[u][v][name] = value
820
+ except KeyError:
821
+ pass
822
+ except AttributeError:
823
+ # treat `values` as a constant
824
+ for u, v, data in G.edges(data=True):
825
+ data[name] = values
826
+ else:
827
+ # `values` consists of doct-of-dict {edge: {attr: value}} shape
828
+ if G.is_multigraph():
829
+ for (u, v, key), d in values.items():
830
+ try:
831
+ G._adj[u][v][key].update(d)
832
+ except KeyError:
833
+ pass
834
+ else:
835
+ for (u, v), d in values.items():
836
+ try:
837
+ G._adj[u][v].update(d)
838
+ except KeyError:
839
+ pass
840
+ nx._clear_cache(G)
841
+
842
+
843
+ def get_edge_attributes(G, name, default=None):
844
+ """Get edge attributes from graph
845
+
846
+ Parameters
847
+ ----------
848
+ G : NetworkX Graph
849
+
850
+ name : string
851
+ Attribute name
852
+
853
+ default: object (default=None)
854
+ Default value of the edge attribute if there is no value set for that
855
+ edge in graph. If `None` then edges without this attribute are not
856
+ included in the returned dict.
857
+
858
+ Returns
859
+ -------
860
+ Dictionary of attributes keyed by edge. For (di)graphs, the keys are
861
+ 2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
862
+ the form: (u, v, key).
863
+
864
+ Examples
865
+ --------
866
+ >>> G = nx.Graph()
867
+ >>> nx.add_path(G, [1, 2, 3], color="red")
868
+ >>> color = nx.get_edge_attributes(G, "color")
869
+ >>> color[(1, 2)]
870
+ 'red'
871
+ >>> G.add_edge(3, 4)
872
+ >>> color = nx.get_edge_attributes(G, "color", default="yellow")
873
+ >>> color[(3, 4)]
874
+ 'yellow'
875
+ """
876
+ if G.is_multigraph():
877
+ edges = G.edges(keys=True, data=True)
878
+ else:
879
+ edges = G.edges(data=True)
880
+ if default is not None:
881
+ return {x[:-1]: x[-1].get(name, default) for x in edges}
882
+ return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
883
+
884
+
885
+ def all_neighbors(graph, node):
886
+ """Returns all of the neighbors of a node in the graph.
887
+
888
+ If the graph is directed returns predecessors as well as successors.
889
+
890
+ Parameters
891
+ ----------
892
+ graph : NetworkX graph
893
+ Graph to find neighbors.
894
+
895
+ node : node
896
+ The node whose neighbors will be returned.
897
+
898
+ Returns
899
+ -------
900
+ neighbors : iterator
901
+ Iterator of neighbors
902
+ """
903
+ if graph.is_directed():
904
+ values = chain(graph.predecessors(node), graph.successors(node))
905
+ else:
906
+ values = graph.neighbors(node)
907
+ return values
908
+
909
+
910
+ def non_neighbors(graph, node):
911
+ """Returns the non-neighbors of the node in the graph.
912
+
913
+ Parameters
914
+ ----------
915
+ graph : NetworkX graph
916
+ Graph to find neighbors.
917
+
918
+ node : node
919
+ The node whose neighbors will be returned.
920
+
921
+ Returns
922
+ -------
923
+ non_neighbors : set
924
+ Set of nodes in the graph that are not neighbors of the node.
925
+ """
926
+ return graph._adj.keys() - graph._adj[node].keys() - {node}
927
+
928
+
929
+ def non_edges(graph):
930
+ """Returns the nonexistent edges in the graph.
931
+
932
+ Parameters
933
+ ----------
934
+ graph : NetworkX graph.
935
+ Graph to find nonexistent edges.
936
+
937
+ Returns
938
+ -------
939
+ non_edges : iterator
940
+ Iterator of edges that are not in the graph.
941
+ """
942
+ if graph.is_directed():
943
+ for u in graph:
944
+ for v in non_neighbors(graph, u):
945
+ yield (u, v)
946
+ else:
947
+ nodes = set(graph)
948
+ while nodes:
949
+ u = nodes.pop()
950
+ for v in nodes - set(graph[u]):
951
+ yield (u, v)
952
+
953
+
954
+ @not_implemented_for("directed")
955
+ def common_neighbors(G, u, v):
956
+ """Returns the common neighbors of two nodes in a graph.
957
+
958
+ Parameters
959
+ ----------
960
+ G : graph
961
+ A NetworkX undirected graph.
962
+
963
+ u, v : nodes
964
+ Nodes in the graph.
965
+
966
+ Returns
967
+ -------
968
+ cnbors : set
969
+ Set of common neighbors of u and v in the graph.
970
+
971
+ Raises
972
+ ------
973
+ NetworkXError
974
+ If u or v is not a node in the graph.
975
+
976
+ Examples
977
+ --------
978
+ >>> G = nx.complete_graph(5)
979
+ >>> sorted(nx.common_neighbors(G, 0, 1))
980
+ [2, 3, 4]
981
+ """
982
+ if u not in G:
983
+ raise nx.NetworkXError("u is not in the graph.")
984
+ if v not in G:
985
+ raise nx.NetworkXError("v is not in the graph.")
986
+
987
+ return G._adj[u].keys() & G._adj[v].keys() - {u, v}
988
+
989
+
990
+ def is_weighted(G, edge=None, weight="weight"):
991
+ """Returns True if `G` has weighted edges.
992
+
993
+ Parameters
994
+ ----------
995
+ G : graph
996
+ A NetworkX graph.
997
+
998
+ edge : tuple, optional
999
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1000
+ None, then every edge in `G` is tested.
1001
+
1002
+ weight: string, optional
1003
+ The attribute name used to query for edge weights.
1004
+
1005
+ Returns
1006
+ -------
1007
+ bool
1008
+ A boolean signifying if `G`, or the specified edge, is weighted.
1009
+
1010
+ Raises
1011
+ ------
1012
+ NetworkXError
1013
+ If the specified edge does not exist.
1014
+
1015
+ Examples
1016
+ --------
1017
+ >>> G = nx.path_graph(4)
1018
+ >>> nx.is_weighted(G)
1019
+ False
1020
+ >>> nx.is_weighted(G, (2, 3))
1021
+ False
1022
+
1023
+ >>> G = nx.DiGraph()
1024
+ >>> G.add_edge(1, 2, weight=1)
1025
+ >>> nx.is_weighted(G)
1026
+ True
1027
+
1028
+ """
1029
+ if edge is not None:
1030
+ data = G.get_edge_data(*edge)
1031
+ if data is None:
1032
+ msg = f"Edge {edge!r} does not exist."
1033
+ raise nx.NetworkXError(msg)
1034
+ return weight in data
1035
+
1036
+ if is_empty(G):
1037
+ # Special handling required since: all([]) == True
1038
+ return False
1039
+
1040
+ return all(weight in data for u, v, data in G.edges(data=True))
1041
+
1042
+
1043
+ @nx._dispatchable(edge_attrs="weight")
1044
+ def is_negatively_weighted(G, edge=None, weight="weight"):
1045
+ """Returns True if `G` has negatively weighted edges.
1046
+
1047
+ Parameters
1048
+ ----------
1049
+ G : graph
1050
+ A NetworkX graph.
1051
+
1052
+ edge : tuple, optional
1053
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1054
+ None, then every edge in `G` is tested.
1055
+
1056
+ weight: string, optional
1057
+ The attribute name used to query for edge weights.
1058
+
1059
+ Returns
1060
+ -------
1061
+ bool
1062
+ A boolean signifying if `G`, or the specified edge, is negatively
1063
+ weighted.
1064
+
1065
+ Raises
1066
+ ------
1067
+ NetworkXError
1068
+ If the specified edge does not exist.
1069
+
1070
+ Examples
1071
+ --------
1072
+ >>> G = nx.Graph()
1073
+ >>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
1074
+ >>> G.add_edge(1, 2, weight=4)
1075
+ >>> nx.is_negatively_weighted(G, (1, 2))
1076
+ False
1077
+ >>> G[2][4]["weight"] = -2
1078
+ >>> nx.is_negatively_weighted(G)
1079
+ True
1080
+ >>> G = nx.DiGraph()
1081
+ >>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)]
1082
+ >>> G.add_weighted_edges_from(edges)
1083
+ >>> nx.is_negatively_weighted(G)
1084
+ True
1085
+
1086
+ """
1087
+ if edge is not None:
1088
+ data = G.get_edge_data(*edge)
1089
+ if data is None:
1090
+ msg = f"Edge {edge!r} does not exist."
1091
+ raise nx.NetworkXError(msg)
1092
+ return weight in data and data[weight] < 0
1093
+
1094
+ return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
1095
+
1096
+
1097
+ def is_empty(G):
1098
+ """Returns True if `G` has no edges.
1099
+
1100
+ Parameters
1101
+ ----------
1102
+ G : graph
1103
+ A NetworkX graph.
1104
+
1105
+ Returns
1106
+ -------
1107
+ bool
1108
+ True if `G` has no edges, and False otherwise.
1109
+
1110
+ Notes
1111
+ -----
1112
+ An empty graph can have nodes but not edges. The empty graph with zero
1113
+ nodes is known as the null graph. This is an $O(n)$ operation where n
1114
+ is the number of nodes in the graph.
1115
+
1116
+ """
1117
+ return not any(G._adj.values())
1118
+
1119
+
1120
+ def nodes_with_selfloops(G):
1121
+ """Returns an iterator over nodes with self loops.
1122
+
1123
+ A node with a self loop has an edge with both ends adjacent
1124
+ to that node.
1125
+
1126
+ Returns
1127
+ -------
1128
+ nodelist : iterator
1129
+ A iterator over nodes with self loops.
1130
+
1131
+ See Also
1132
+ --------
1133
+ selfloop_edges, number_of_selfloops
1134
+
1135
+ Examples
1136
+ --------
1137
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1138
+ >>> G.add_edge(1, 1)
1139
+ >>> G.add_edge(1, 2)
1140
+ >>> list(nx.nodes_with_selfloops(G))
1141
+ [1]
1142
+
1143
+ """
1144
+ return (n for n, nbrs in G._adj.items() if n in nbrs)
1145
+
1146
+
1147
+ def selfloop_edges(G, data=False, keys=False, default=None):
1148
+ """Returns an iterator over selfloop edges.
1149
+
1150
+ A selfloop edge has the same node at both ends.
1151
+
1152
+ Parameters
1153
+ ----------
1154
+ G : graph
1155
+ A NetworkX graph.
1156
+ data : string or bool, optional (default=False)
1157
+ Return selfloop edges as two tuples (u, v) (data=False)
1158
+ or three-tuples (u, v, datadict) (data=True)
1159
+ or three-tuples (u, v, datavalue) (data='attrname')
1160
+ keys : bool, optional (default=False)
1161
+ If True, return edge keys with each edge.
1162
+ default : value, optional (default=None)
1163
+ Value used for edges that don't have the requested attribute.
1164
+ Only relevant if data is not True or False.
1165
+
1166
+ Returns
1167
+ -------
1168
+ edgeiter : iterator over edge tuples
1169
+ An iterator over all selfloop edges.
1170
+
1171
+ See Also
1172
+ --------
1173
+ nodes_with_selfloops, number_of_selfloops
1174
+
1175
+ Examples
1176
+ --------
1177
+ >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc
1178
+ >>> ekey = G.add_edge(1, 1)
1179
+ >>> ekey = G.add_edge(1, 2)
1180
+ >>> list(nx.selfloop_edges(G))
1181
+ [(1, 1)]
1182
+ >>> list(nx.selfloop_edges(G, data=True))
1183
+ [(1, 1, {})]
1184
+ >>> list(nx.selfloop_edges(G, keys=True))
1185
+ [(1, 1, 0)]
1186
+ >>> list(nx.selfloop_edges(G, keys=True, data=True))
1187
+ [(1, 1, 0, {})]
1188
+ """
1189
+ if data is True:
1190
+ if G.is_multigraph():
1191
+ if keys is True:
1192
+ return (
1193
+ (n, n, k, d)
1194
+ for n, nbrs in G._adj.items()
1195
+ if n in nbrs
1196
+ for k, d in nbrs[n].items()
1197
+ )
1198
+ else:
1199
+ return (
1200
+ (n, n, d)
1201
+ for n, nbrs in G._adj.items()
1202
+ if n in nbrs
1203
+ for d in nbrs[n].values()
1204
+ )
1205
+ else:
1206
+ return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs)
1207
+ elif data is not False:
1208
+ if G.is_multigraph():
1209
+ if keys is True:
1210
+ return (
1211
+ (n, n, k, d.get(data, default))
1212
+ for n, nbrs in G._adj.items()
1213
+ if n in nbrs
1214
+ for k, d in nbrs[n].items()
1215
+ )
1216
+ else:
1217
+ return (
1218
+ (n, n, d.get(data, default))
1219
+ for n, nbrs in G._adj.items()
1220
+ if n in nbrs
1221
+ for d in nbrs[n].values()
1222
+ )
1223
+ else:
1224
+ return (
1225
+ (n, n, nbrs[n].get(data, default))
1226
+ for n, nbrs in G._adj.items()
1227
+ if n in nbrs
1228
+ )
1229
+ else:
1230
+ if G.is_multigraph():
1231
+ if keys is True:
1232
+ return (
1233
+ (n, n, k)
1234
+ for n, nbrs in G._adj.items()
1235
+ if n in nbrs
1236
+ for k in nbrs[n]
1237
+ )
1238
+ else:
1239
+ return (
1240
+ (n, n)
1241
+ for n, nbrs in G._adj.items()
1242
+ if n in nbrs
1243
+ for i in range(len(nbrs[n])) # for easy edge removal (#4068)
1244
+ )
1245
+ else:
1246
+ return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
1247
+
1248
+
1249
+ def number_of_selfloops(G):
1250
+ """Returns the number of selfloop edges.
1251
+
1252
+ A selfloop edge has the same node at both ends.
1253
+
1254
+ Returns
1255
+ -------
1256
+ nloops : int
1257
+ The number of selfloops.
1258
+
1259
+ See Also
1260
+ --------
1261
+ nodes_with_selfloops, selfloop_edges
1262
+
1263
+ Examples
1264
+ --------
1265
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1266
+ >>> G.add_edge(1, 1)
1267
+ >>> G.add_edge(1, 2)
1268
+ >>> nx.number_of_selfloops(G)
1269
+ 1
1270
+ """
1271
+ return sum(1 for _ in nx.selfloop_edges(G))
1272
+
1273
+
1274
+ def is_path(G, path):
1275
+ """Returns whether or not the specified path exists.
1276
+
1277
+ For it to return True, every node on the path must exist and
1278
+ each consecutive pair must be connected via one or more edges.
1279
+
1280
+ Parameters
1281
+ ----------
1282
+ G : graph
1283
+ A NetworkX graph.
1284
+
1285
+ path : list
1286
+ A list of nodes which defines the path to traverse
1287
+
1288
+ Returns
1289
+ -------
1290
+ bool
1291
+ True if `path` is a valid path in `G`
1292
+
1293
+ """
1294
+ try:
1295
+ return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path))
1296
+ except (KeyError, TypeError):
1297
+ return False
1298
+
1299
+
1300
+ def path_weight(G, path, weight):
1301
+ """Returns total cost associated with specified path and weight
1302
+
1303
+ Parameters
1304
+ ----------
1305
+ G : graph
1306
+ A NetworkX graph.
1307
+
1308
+ path: list
1309
+ A list of node labels which defines the path to traverse
1310
+
1311
+ weight: string
1312
+ A string indicating which edge attribute to use for path cost
1313
+
1314
+ Returns
1315
+ -------
1316
+ cost: int or float
1317
+ An integer or a float representing the total cost with respect to the
1318
+ specified weight of the specified path
1319
+
1320
+ Raises
1321
+ ------
1322
+ NetworkXNoPath
1323
+ If the specified edge does not exist.
1324
+ """
1325
+ multigraph = G.is_multigraph()
1326
+ cost = 0
1327
+
1328
+ if not nx.is_path(G, path):
1329
+ raise nx.NetworkXNoPath("path does not exist")
1330
+ for node, nbr in nx.utils.pairwise(path):
1331
+ if multigraph:
1332
+ cost += min(v[weight] for v in G._adj[node][nbr].values())
1333
+ else:
1334
+ cost += G._adj[node][nbr][weight]
1335
+ return cost
env-llmeval/lib/python3.10/site-packages/networkx/classes/graph.py ADDED
@@ -0,0 +1,2043 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from copy import deepcopy
11
+ from functools import cached_property
12
+
13
+ import networkx as nx
14
+ from networkx import convert
15
+ from networkx.classes.coreviews import AdjacencyView
16
+ from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
17
+ from networkx.exception import NetworkXError
18
+
19
+ __all__ = ["Graph"]
20
+
21
+
22
+ class _CachedPropertyResetterAdj:
23
+ """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
24
+
25
+ This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
26
+ ``G._adj`` is set to a new value.
27
+
28
+ This object sits on a class and ensures that any instance of that
29
+ class clears its cached property "adj" whenever the underlying
30
+ instance attribute "_adj" is set to a new object. It only affects
31
+ the set process of the obj._adj attribute. All get/del operations
32
+ act as they normally would.
33
+
34
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
35
+ """
36
+
37
+ def __set__(self, obj, value):
38
+ od = obj.__dict__
39
+ od["_adj"] = value
40
+ if "adj" in od:
41
+ del od["adj"]
42
+
43
+
44
+ class _CachedPropertyResetterNode:
45
+ """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
46
+
47
+ This assumes that the ``cached_property`` ``G.node`` should be reset whenever
48
+ ``G._node`` is set to a new value.
49
+
50
+ This object sits on a class and ensures that any instance of that
51
+ class clears its cached property "nodes" whenever the underlying
52
+ instance attribute "_node" is set to a new object. It only affects
53
+ the set process of the obj._adj attribute. All get/del operations
54
+ act as they normally would.
55
+
56
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
57
+ """
58
+
59
+ def __set__(self, obj, value):
60
+ od = obj.__dict__
61
+ od["_node"] = value
62
+ if "nodes" in od:
63
+ del od["nodes"]
64
+
65
+
66
+ class Graph:
67
+ """
68
+ Base class for undirected graphs.
69
+
70
+ A Graph stores nodes and edges with optional data, or attributes.
71
+
72
+ Graphs hold undirected edges. Self loops are allowed but multiple
73
+ (parallel) edges are not.
74
+
75
+ Nodes can be arbitrary (hashable) Python objects with optional
76
+ key/value attributes, except that `None` is not allowed as a node.
77
+
78
+ Edges are represented as links between nodes with optional
79
+ key/value attributes.
80
+
81
+ Parameters
82
+ ----------
83
+ incoming_graph_data : input graph (optional, default: None)
84
+ Data to initialize graph. If None (default) an empty
85
+ graph is created. The data can be any format that is supported
86
+ by the to_networkx_graph() function, currently including edge list,
87
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
88
+ sparse matrix, or PyGraphviz graph.
89
+
90
+ attr : keyword arguments, optional (default= no attributes)
91
+ Attributes to add to graph as key=value pairs.
92
+
93
+ See Also
94
+ --------
95
+ DiGraph
96
+ MultiGraph
97
+ MultiDiGraph
98
+
99
+ Examples
100
+ --------
101
+ Create an empty graph structure (a "null graph") with no nodes and
102
+ no edges.
103
+
104
+ >>> G = nx.Graph()
105
+
106
+ G can be grown in several ways.
107
+
108
+ **Nodes:**
109
+
110
+ Add one node at a time:
111
+
112
+ >>> G.add_node(1)
113
+
114
+ Add the nodes from any container (a list, dict, set or
115
+ even the lines from a file or the nodes from another graph).
116
+
117
+ >>> G.add_nodes_from([2, 3])
118
+ >>> G.add_nodes_from(range(100, 110))
119
+ >>> H = nx.path_graph(10)
120
+ >>> G.add_nodes_from(H)
121
+
122
+ In addition to strings and integers any hashable Python object
123
+ (except None) can represent a node, e.g. a customized node object,
124
+ or even another Graph.
125
+
126
+ >>> G.add_node(H)
127
+
128
+ **Edges:**
129
+
130
+ G can also be grown by adding edges.
131
+
132
+ Add one edge,
133
+
134
+ >>> G.add_edge(1, 2)
135
+
136
+ a list of edges,
137
+
138
+ >>> G.add_edges_from([(1, 2), (1, 3)])
139
+
140
+ or a collection of edges,
141
+
142
+ >>> G.add_edges_from(H.edges)
143
+
144
+ If some edges connect nodes not yet in the graph, the nodes
145
+ are added automatically. There are no errors when adding
146
+ nodes or edges that already exist.
147
+
148
+ **Attributes:**
149
+
150
+ Each graph, node, and edge can hold key/value attribute pairs
151
+ in an associated attribute dictionary (the keys must be hashable).
152
+ By default these are empty, but can be added or changed using
153
+ add_edge, add_node or direct manipulation of the attribute
154
+ dictionaries named graph, node and edge respectively.
155
+
156
+ >>> G = nx.Graph(day="Friday")
157
+ >>> G.graph
158
+ {'day': 'Friday'}
159
+
160
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
161
+
162
+ >>> G.add_node(1, time="5pm")
163
+ >>> G.add_nodes_from([3], time="2pm")
164
+ >>> G.nodes[1]
165
+ {'time': '5pm'}
166
+ >>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes
167
+ >>> del G.nodes[1]["room"] # remove attribute
168
+ >>> list(G.nodes(data=True))
169
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
170
+
171
+ Add edge attributes using add_edge(), add_edges_from(), subscript
172
+ notation, or G.edges.
173
+
174
+ >>> G.add_edge(1, 2, weight=4.7)
175
+ >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
176
+ >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
177
+ >>> G[1][2]["weight"] = 4.7
178
+ >>> G.edges[1, 2]["weight"] = 4
179
+
180
+ Warning: we protect the graph data structure by making `G.edges` a
181
+ read-only dict-like structure. However, you can assign to attributes
182
+ in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
183
+ data attributes: `G.edges[1, 2]['weight'] = 4`
184
+ (For multigraphs: `MG.edges[u, v, key][name] = value`).
185
+
186
+ **Shortcuts:**
187
+
188
+ Many common graph features allow python syntax to speed reporting.
189
+
190
+ >>> 1 in G # check if node in graph
191
+ True
192
+ >>> [n for n in G if n < 3] # iterate through nodes
193
+ [1, 2]
194
+ >>> len(G) # number of nodes in graph
195
+ 5
196
+
197
+ Often the best way to traverse all edges of a graph is via the neighbors.
198
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
199
+
200
+ >>> for n, nbrsdict in G.adjacency():
201
+ ... for nbr, eattr in nbrsdict.items():
202
+ ... if "weight" in eattr:
203
+ ... # Do something useful with the edges
204
+ ... pass
205
+
206
+ But the edges() method is often more convenient:
207
+
208
+ >>> for u, v, weight in G.edges.data("weight"):
209
+ ... if weight is not None:
210
+ ... # Do something useful with the edges
211
+ ... pass
212
+
213
+ **Reporting:**
214
+
215
+ Simple graph information is obtained using object-attributes and methods.
216
+ Reporting typically provides views instead of containers to reduce memory
217
+ usage. The views update as the graph is updated similarly to dict-views.
218
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
219
+ via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
220
+ (e.g. `nodes.items()`, `nodes.data('color')`,
221
+ `nodes.data('color', default='blue')` and similarly for `edges`)
222
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
223
+
224
+ For details on these and other miscellaneous methods, see below.
225
+
226
+ **Subclasses (Advanced):**
227
+
228
+ The Graph class uses a dict-of-dict-of-dict data structure.
229
+ The outer dict (node_dict) holds adjacency information keyed by node.
230
+ The next dict (adjlist_dict) represents the adjacency information and holds
231
+ edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
232
+ the edge data and holds edge attribute values keyed by attribute names.
233
+
234
+ Each of these three dicts can be replaced in a subclass by a user defined
235
+ dict-like object. In general, the dict-like features should be
236
+ maintained but extra features can be added. To replace one of the
237
+ dicts create a new graph class by changing the class(!) variable
238
+ holding the factory for that dict-like structure.
239
+
240
+ node_dict_factory : function, (default: dict)
241
+ Factory function to be used to create the dict containing node
242
+ attributes, keyed by node id.
243
+ It should require no arguments and return a dict-like object
244
+
245
+ node_attr_dict_factory: function, (default: dict)
246
+ Factory function to be used to create the node attribute
247
+ dict which holds attribute values keyed by attribute name.
248
+ It should require no arguments and return a dict-like object
249
+
250
+ adjlist_outer_dict_factory : function, (default: dict)
251
+ Factory function to be used to create the outer-most dict
252
+ in the data structure that holds adjacency info keyed by node.
253
+ It should require no arguments and return a dict-like object.
254
+
255
+ adjlist_inner_dict_factory : function, (default: dict)
256
+ Factory function to be used to create the adjacency list
257
+ dict which holds edge data keyed by neighbor.
258
+ It should require no arguments and return a dict-like object
259
+
260
+ edge_attr_dict_factory : function, (default: dict)
261
+ Factory function to be used to create the edge attribute
262
+ dict which holds attribute values keyed by attribute name.
263
+ It should require no arguments and return a dict-like object.
264
+
265
+ graph_attr_dict_factory : function, (default: dict)
266
+ Factory function to be used to create the graph 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
+ Typically, if your extension doesn't impact the data structure all
271
+ methods will inherit without issue except: `to_directed/to_undirected`.
272
+ By default these methods create a DiGraph/Graph class and you probably
273
+ want them to create your extension of a DiGraph/Graph. To facilitate
274
+ this we define two class variables that you can set in your subclass.
275
+
276
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
277
+ Class to create a new graph structure in the `to_directed` method.
278
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
279
+
280
+ to_undirected_class : callable, (default: Graph or MultiGraph)
281
+ Class to create a new graph structure in the `to_undirected` method.
282
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
283
+
284
+ **Subclassing Example**
285
+
286
+ Create a low memory graph class that effectively disallows edge
287
+ attributes by using a single attribute dict for all edges.
288
+ This reduces the memory used, but you lose edge attributes.
289
+
290
+ >>> class ThinGraph(nx.Graph):
291
+ ... all_edge_dict = {"weight": 1}
292
+ ...
293
+ ... def single_edge_dict(self):
294
+ ... return self.all_edge_dict
295
+ ...
296
+ ... edge_attr_dict_factory = single_edge_dict
297
+ >>> G = ThinGraph()
298
+ >>> G.add_edge(2, 1)
299
+ >>> G[2][1]
300
+ {'weight': 1}
301
+ >>> G.add_edge(2, 2)
302
+ >>> G[2][1] is G[2][2]
303
+ True
304
+ """
305
+
306
+ _adj = _CachedPropertyResetterAdj()
307
+ _node = _CachedPropertyResetterNode()
308
+
309
+ node_dict_factory = dict
310
+ node_attr_dict_factory = dict
311
+ adjlist_outer_dict_factory = dict
312
+ adjlist_inner_dict_factory = dict
313
+ edge_attr_dict_factory = dict
314
+ graph_attr_dict_factory = dict
315
+
316
+ def to_directed_class(self):
317
+ """Returns the class to use for empty directed copies.
318
+
319
+ If you subclass the base classes, use this to designate
320
+ what directed class to use for `to_directed()` copies.
321
+ """
322
+ return nx.DiGraph
323
+
324
+ def to_undirected_class(self):
325
+ """Returns the class to use for empty undirected copies.
326
+
327
+ If you subclass the base classes, use this to designate
328
+ what directed class to use for `to_directed()` copies.
329
+ """
330
+ return Graph
331
+
332
+ def __init__(self, incoming_graph_data=None, **attr):
333
+ """Initialize a graph with edges, name, or graph attributes.
334
+
335
+ Parameters
336
+ ----------
337
+ incoming_graph_data : input graph (optional, default: None)
338
+ Data to initialize graph. If None (default) an empty
339
+ graph is created. The data can be an edge list, or any
340
+ NetworkX graph object. If the corresponding optional Python
341
+ packages are installed the data can also be a 2D NumPy array, a
342
+ SciPy sparse array, or a PyGraphviz graph.
343
+
344
+ attr : keyword arguments, optional (default= no attributes)
345
+ Attributes to add to graph as key=value pairs.
346
+
347
+ See Also
348
+ --------
349
+ convert
350
+
351
+ Examples
352
+ --------
353
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
354
+ >>> G = nx.Graph(name="my graph")
355
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
356
+ >>> G = nx.Graph(e)
357
+
358
+ Arbitrary graph attribute pairs (key=value) may be assigned
359
+
360
+ >>> G = nx.Graph(e, day="Friday")
361
+ >>> G.graph
362
+ {'day': 'Friday'}
363
+
364
+ """
365
+ self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
366
+ self._node = self.node_dict_factory() # empty node attribute dict
367
+ self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict
368
+ self.__networkx_cache__ = {}
369
+ # attempt to load graph with data
370
+ if incoming_graph_data is not None:
371
+ convert.to_networkx_graph(incoming_graph_data, create_using=self)
372
+ # load graph attributes (must be after convert)
373
+ self.graph.update(attr)
374
+
375
+ @cached_property
376
+ def adj(self):
377
+ """Graph adjacency object holding the neighbors of each node.
378
+
379
+ This object is a read-only dict-like structure with node keys
380
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
381
+ to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
382
+ the color of the edge `(3, 2)` to `"blue"`.
383
+
384
+ Iterating over G.adj behaves like a dict. Useful idioms include
385
+ `for nbr, datadict in G.adj[n].items():`.
386
+
387
+ The neighbor information is also provided by subscripting the graph.
388
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
389
+
390
+ For directed graphs, `G.adj` holds outgoing (successor) info.
391
+ """
392
+ return AdjacencyView(self._adj)
393
+
394
+ @property
395
+ def name(self):
396
+ """String identifier of the graph.
397
+
398
+ This graph attribute appears in the attribute dict G.graph
399
+ keyed by the string `"name"`. as well as an attribute (technically
400
+ a property) `G.name`. This is entirely user controlled.
401
+ """
402
+ return self.graph.get("name", "")
403
+
404
+ @name.setter
405
+ def name(self, s):
406
+ self.graph["name"] = s
407
+ nx._clear_cache(self)
408
+
409
+ def __str__(self):
410
+ """Returns a short summary of the graph.
411
+
412
+ Returns
413
+ -------
414
+ info : string
415
+ Graph information including the graph name (if any), graph type, and the
416
+ number of nodes and edges.
417
+
418
+ Examples
419
+ --------
420
+ >>> G = nx.Graph(name="foo")
421
+ >>> str(G)
422
+ "Graph named 'foo' with 0 nodes and 0 edges"
423
+
424
+ >>> G = nx.path_graph(3)
425
+ >>> str(G)
426
+ 'Graph with 3 nodes and 2 edges'
427
+
428
+ """
429
+ return "".join(
430
+ [
431
+ type(self).__name__,
432
+ f" named {self.name!r}" if self.name else "",
433
+ f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
434
+ ]
435
+ )
436
+
437
+ def __iter__(self):
438
+ """Iterate over the nodes. Use: 'for n in G'.
439
+
440
+ Returns
441
+ -------
442
+ niter : iterator
443
+ An iterator over all nodes in the graph.
444
+
445
+ Examples
446
+ --------
447
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
448
+ >>> [n for n in G]
449
+ [0, 1, 2, 3]
450
+ >>> list(G)
451
+ [0, 1, 2, 3]
452
+ """
453
+ return iter(self._node)
454
+
455
+ def __contains__(self, n):
456
+ """Returns True if n is a node, False otherwise. Use: 'n in G'.
457
+
458
+ Examples
459
+ --------
460
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
461
+ >>> 1 in G
462
+ True
463
+ """
464
+ try:
465
+ return n in self._node
466
+ except TypeError:
467
+ return False
468
+
469
+ def __len__(self):
470
+ """Returns the number of nodes in the graph. Use: 'len(G)'.
471
+
472
+ Returns
473
+ -------
474
+ nnodes : int
475
+ The number of nodes in the graph.
476
+
477
+ See Also
478
+ --------
479
+ number_of_nodes: identical method
480
+ order: identical method
481
+
482
+ Examples
483
+ --------
484
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
485
+ >>> len(G)
486
+ 4
487
+
488
+ """
489
+ return len(self._node)
490
+
491
+ def __getitem__(self, n):
492
+ """Returns a dict of neighbors of node n. Use: 'G[n]'.
493
+
494
+ Parameters
495
+ ----------
496
+ n : node
497
+ A node in the graph.
498
+
499
+ Returns
500
+ -------
501
+ adj_dict : dictionary
502
+ The adjacency dictionary for nodes connected to n.
503
+
504
+ Notes
505
+ -----
506
+ G[n] is the same as G.adj[n] and similar to G.neighbors(n)
507
+ (which is an iterator over G.adj[n])
508
+
509
+ Examples
510
+ --------
511
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
512
+ >>> G[0]
513
+ AtlasView({1: {}})
514
+ """
515
+ return self.adj[n]
516
+
517
+ def add_node(self, node_for_adding, **attr):
518
+ """Add a single node `node_for_adding` and update node attributes.
519
+
520
+ Parameters
521
+ ----------
522
+ node_for_adding : node
523
+ A node can be any hashable Python object except None.
524
+ attr : keyword arguments, optional
525
+ Set or change node attributes using key=value.
526
+
527
+ See Also
528
+ --------
529
+ add_nodes_from
530
+
531
+ Examples
532
+ --------
533
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
534
+ >>> G.add_node(1)
535
+ >>> G.add_node("Hello")
536
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
537
+ >>> G.add_node(K3)
538
+ >>> G.number_of_nodes()
539
+ 3
540
+
541
+ Use keywords set/change node attributes:
542
+
543
+ >>> G.add_node(1, size=10)
544
+ >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
545
+
546
+ Notes
547
+ -----
548
+ A hashable object is one that can be used as a key in a Python
549
+ dictionary. This includes strings, numbers, tuples of strings
550
+ and numbers, etc.
551
+
552
+ On many platforms hashable items also include mutables such as
553
+ NetworkX Graphs, though one should be careful that the hash
554
+ doesn't change on mutables.
555
+ """
556
+ if node_for_adding not in self._node:
557
+ if node_for_adding is None:
558
+ raise ValueError("None cannot be a node")
559
+ self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
560
+ attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
561
+ attr_dict.update(attr)
562
+ else: # update attr even if node already exists
563
+ self._node[node_for_adding].update(attr)
564
+ nx._clear_cache(self)
565
+
566
+ def add_nodes_from(self, nodes_for_adding, **attr):
567
+ """Add multiple nodes.
568
+
569
+ Parameters
570
+ ----------
571
+ nodes_for_adding : iterable container
572
+ A container of nodes (list, dict, set, etc.).
573
+ OR
574
+ A container of (node, attribute dict) tuples.
575
+ Node attributes are updated using the attribute dict.
576
+ attr : keyword arguments, optional (default= no attributes)
577
+ Update attributes for all nodes in nodes.
578
+ Node attributes specified in nodes as a tuple take
579
+ precedence over attributes specified via keyword arguments.
580
+
581
+ See Also
582
+ --------
583
+ add_node
584
+
585
+ Notes
586
+ -----
587
+ When adding nodes from an iterator over the graph you are changing,
588
+ a `RuntimeError` can be raised with message:
589
+ `RuntimeError: dictionary changed size during iteration`. This
590
+ happens when the graph's underlying dictionary is modified during
591
+ iteration. To avoid this error, evaluate the iterator into a separate
592
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
593
+ object to `G.add_nodes_from`.
594
+
595
+ Examples
596
+ --------
597
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
598
+ >>> G.add_nodes_from("Hello")
599
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
600
+ >>> G.add_nodes_from(K3)
601
+ >>> sorted(G.nodes(), key=str)
602
+ [0, 1, 2, 'H', 'e', 'l', 'o']
603
+
604
+ Use keywords to update specific node attributes for every node.
605
+
606
+ >>> G.add_nodes_from([1, 2], size=10)
607
+ >>> G.add_nodes_from([3, 4], weight=0.4)
608
+
609
+ Use (node, attrdict) tuples to update attributes for specific nodes.
610
+
611
+ >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
612
+ >>> G.nodes[1]["size"]
613
+ 11
614
+ >>> H = nx.Graph()
615
+ >>> H.add_nodes_from(G.nodes(data=True))
616
+ >>> H.nodes[1]["size"]
617
+ 11
618
+
619
+ Evaluate an iterator over a graph if using it to modify the same graph
620
+
621
+ >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
622
+ >>> # wrong way - will raise RuntimeError
623
+ >>> # G.add_nodes_from(n + 1 for n in G.nodes)
624
+ >>> # correct way
625
+ >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
626
+ """
627
+ for n in nodes_for_adding:
628
+ try:
629
+ newnode = n not in self._node
630
+ newdict = attr
631
+ except TypeError:
632
+ n, ndict = n
633
+ newnode = n not in self._node
634
+ newdict = attr.copy()
635
+ newdict.update(ndict)
636
+ if newnode:
637
+ if n is None:
638
+ raise ValueError("None cannot be a node")
639
+ self._adj[n] = self.adjlist_inner_dict_factory()
640
+ self._node[n] = self.node_attr_dict_factory()
641
+ self._node[n].update(newdict)
642
+ nx._clear_cache(self)
643
+
644
+ def remove_node(self, n):
645
+ """Remove node n.
646
+
647
+ Removes the node n and all adjacent edges.
648
+ Attempting to remove a nonexistent node will raise an exception.
649
+
650
+ Parameters
651
+ ----------
652
+ n : node
653
+ A node in the graph
654
+
655
+ Raises
656
+ ------
657
+ NetworkXError
658
+ If n is not in the graph.
659
+
660
+ See Also
661
+ --------
662
+ remove_nodes_from
663
+
664
+ Examples
665
+ --------
666
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
667
+ >>> list(G.edges)
668
+ [(0, 1), (1, 2)]
669
+ >>> G.remove_node(1)
670
+ >>> list(G.edges)
671
+ []
672
+
673
+ """
674
+ adj = self._adj
675
+ try:
676
+ nbrs = list(adj[n]) # list handles self-loops (allows mutation)
677
+ del self._node[n]
678
+ except KeyError as err: # NetworkXError if n not in self
679
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
680
+ for u in nbrs:
681
+ del adj[u][n] # remove all edges n-u in graph
682
+ del adj[n] # now remove node
683
+ nx._clear_cache(self)
684
+
685
+ def remove_nodes_from(self, nodes):
686
+ """Remove multiple nodes.
687
+
688
+ Parameters
689
+ ----------
690
+ nodes : iterable container
691
+ A container of nodes (list, dict, set, etc.). If a node
692
+ in the container is not in the graph it is silently
693
+ ignored.
694
+
695
+ See Also
696
+ --------
697
+ remove_node
698
+
699
+ Notes
700
+ -----
701
+ When removing nodes from an iterator over the graph you are changing,
702
+ a `RuntimeError` will be raised with message:
703
+ `RuntimeError: dictionary changed size during iteration`. This
704
+ happens when the graph's underlying dictionary is modified during
705
+ iteration. To avoid this error, evaluate the iterator into a separate
706
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
707
+ object to `G.remove_nodes_from`.
708
+
709
+ Examples
710
+ --------
711
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
712
+ >>> e = list(G.nodes)
713
+ >>> e
714
+ [0, 1, 2]
715
+ >>> G.remove_nodes_from(e)
716
+ >>> list(G.nodes)
717
+ []
718
+
719
+ Evaluate an iterator over a graph if using it to modify the same graph
720
+
721
+ >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
722
+ >>> # this command will fail, as the graph's dict is modified during iteration
723
+ >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
724
+ >>> # this command will work, since the dictionary underlying graph is not modified
725
+ >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
726
+ """
727
+ adj = self._adj
728
+ for n in nodes:
729
+ try:
730
+ del self._node[n]
731
+ for u in list(adj[n]): # list handles self-loops
732
+ del adj[u][n] # (allows mutation of dict in loop)
733
+ del adj[n]
734
+ except KeyError:
735
+ pass
736
+ nx._clear_cache(self)
737
+
738
+ @cached_property
739
+ def nodes(self):
740
+ """A NodeView of the Graph as G.nodes or G.nodes().
741
+
742
+ Can be used as `G.nodes` for data lookup and for set-like operations.
743
+ Can also be used as `G.nodes(data='color', default=None)` to return a
744
+ NodeDataView which reports specific node data but no set operations.
745
+ It presents a dict-like interface as well with `G.nodes.items()`
746
+ iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
747
+ providing the value of the `foo` attribute for node `3`. In addition,
748
+ a view `G.nodes.data('foo')` provides a dict-like interface to the
749
+ `foo` attribute of each node. `G.nodes.data('foo', default=1)`
750
+ provides a default for nodes that do not have attribute `foo`.
751
+
752
+ Parameters
753
+ ----------
754
+ data : string or bool, optional (default=False)
755
+ The node attribute returned in 2-tuple (n, ddict[data]).
756
+ If True, return entire node attribute dict as (n, ddict).
757
+ If False, return just the nodes n.
758
+
759
+ default : value, optional (default=None)
760
+ Value used for nodes that don't have the requested attribute.
761
+ Only relevant if data is not True or False.
762
+
763
+ Returns
764
+ -------
765
+ NodeView
766
+ Allows set-like operations over the nodes as well as node
767
+ attribute dict lookup and calling to get a NodeDataView.
768
+ A NodeDataView iterates over `(n, data)` and has no set operations.
769
+ A NodeView iterates over `n` and includes set operations.
770
+
771
+ When called, if data is False, an iterator over nodes.
772
+ Otherwise an iterator of 2-tuples (node, attribute value)
773
+ where the attribute is specified in `data`.
774
+ If data is True then the attribute becomes the
775
+ entire data dictionary.
776
+
777
+ Notes
778
+ -----
779
+ If your node data is not needed, it is simpler and equivalent
780
+ to use the expression ``for n in G``, or ``list(G)``.
781
+
782
+ Examples
783
+ --------
784
+ There are two simple ways of getting a list of all nodes in the graph:
785
+
786
+ >>> G = nx.path_graph(3)
787
+ >>> list(G.nodes)
788
+ [0, 1, 2]
789
+ >>> list(G)
790
+ [0, 1, 2]
791
+
792
+ To get the node data along with the nodes:
793
+
794
+ >>> G.add_node(1, time="5pm")
795
+ >>> G.nodes[0]["foo"] = "bar"
796
+ >>> list(G.nodes(data=True))
797
+ [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
798
+ >>> list(G.nodes.data())
799
+ [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
800
+
801
+ >>> list(G.nodes(data="foo"))
802
+ [(0, 'bar'), (1, None), (2, None)]
803
+ >>> list(G.nodes.data("foo"))
804
+ [(0, 'bar'), (1, None), (2, None)]
805
+
806
+ >>> list(G.nodes(data="time"))
807
+ [(0, None), (1, '5pm'), (2, None)]
808
+ >>> list(G.nodes.data("time"))
809
+ [(0, None), (1, '5pm'), (2, None)]
810
+
811
+ >>> list(G.nodes(data="time", default="Not Available"))
812
+ [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
813
+ >>> list(G.nodes.data("time", default="Not Available"))
814
+ [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
815
+
816
+ If some of your nodes have an attribute and the rest are assumed
817
+ to have a default attribute value you can create a dictionary
818
+ from node/attribute pairs using the `default` keyword argument
819
+ to guarantee the value is never None::
820
+
821
+ >>> G = nx.Graph()
822
+ >>> G.add_node(0)
823
+ >>> G.add_node(1, weight=2)
824
+ >>> G.add_node(2, weight=3)
825
+ >>> dict(G.nodes(data="weight", default=1))
826
+ {0: 1, 1: 2, 2: 3}
827
+
828
+ """
829
+ return NodeView(self)
830
+
831
+ def number_of_nodes(self):
832
+ """Returns the number of nodes in the graph.
833
+
834
+ Returns
835
+ -------
836
+ nnodes : int
837
+ The number of nodes in the graph.
838
+
839
+ See Also
840
+ --------
841
+ order: identical method
842
+ __len__: identical method
843
+
844
+ Examples
845
+ --------
846
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
847
+ >>> G.number_of_nodes()
848
+ 3
849
+ """
850
+ return len(self._node)
851
+
852
+ def order(self):
853
+ """Returns the number of nodes in the graph.
854
+
855
+ Returns
856
+ -------
857
+ nnodes : int
858
+ The number of nodes in the graph.
859
+
860
+ See Also
861
+ --------
862
+ number_of_nodes: identical method
863
+ __len__: identical method
864
+
865
+ Examples
866
+ --------
867
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
868
+ >>> G.order()
869
+ 3
870
+ """
871
+ return len(self._node)
872
+
873
+ def has_node(self, n):
874
+ """Returns True if the graph contains the node n.
875
+
876
+ Identical to `n in G`
877
+
878
+ Parameters
879
+ ----------
880
+ n : node
881
+
882
+ Examples
883
+ --------
884
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
885
+ >>> G.has_node(0)
886
+ True
887
+
888
+ It is more readable and simpler to use
889
+
890
+ >>> 0 in G
891
+ True
892
+
893
+ """
894
+ try:
895
+ return n in self._node
896
+ except TypeError:
897
+ return False
898
+
899
+ def add_edge(self, u_of_edge, v_of_edge, **attr):
900
+ """Add an edge between u and v.
901
+
902
+ The nodes u and v will be automatically added if they are
903
+ not already in the graph.
904
+
905
+ Edge attributes can be specified with keywords or by directly
906
+ accessing the edge's attribute dictionary. See examples below.
907
+
908
+ Parameters
909
+ ----------
910
+ u_of_edge, v_of_edge : nodes
911
+ Nodes can be, for example, strings or numbers.
912
+ Nodes must be hashable (and not None) Python objects.
913
+ attr : keyword arguments, optional
914
+ Edge data (or labels or objects) can be assigned using
915
+ keyword arguments.
916
+
917
+ See Also
918
+ --------
919
+ add_edges_from : add a collection of edges
920
+
921
+ Notes
922
+ -----
923
+ Adding an edge that already exists updates the edge data.
924
+
925
+ Many NetworkX algorithms designed for weighted graphs use
926
+ an edge attribute (by default `weight`) to hold a numerical value.
927
+
928
+ Examples
929
+ --------
930
+ The following all add the edge e=(1, 2) to graph G:
931
+
932
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
933
+ >>> e = (1, 2)
934
+ >>> G.add_edge(1, 2) # explicit two-node form
935
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
936
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
937
+
938
+ Associate data to edges using keywords:
939
+
940
+ >>> G.add_edge(1, 2, weight=3)
941
+ >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
942
+
943
+ For non-string attribute keys, use subscript notation.
944
+
945
+ >>> G.add_edge(1, 2)
946
+ >>> G[1][2].update({0: 5})
947
+ >>> G.edges[1, 2].update({0: 5})
948
+ """
949
+ u, v = u_of_edge, v_of_edge
950
+ # add nodes
951
+ if u not in self._node:
952
+ if u is None:
953
+ raise ValueError("None cannot be a node")
954
+ self._adj[u] = self.adjlist_inner_dict_factory()
955
+ self._node[u] = self.node_attr_dict_factory()
956
+ if v not in self._node:
957
+ if v is None:
958
+ raise ValueError("None cannot be a node")
959
+ self._adj[v] = self.adjlist_inner_dict_factory()
960
+ self._node[v] = self.node_attr_dict_factory()
961
+ # add the edge
962
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
963
+ datadict.update(attr)
964
+ self._adj[u][v] = datadict
965
+ self._adj[v][u] = datadict
966
+ nx._clear_cache(self)
967
+
968
+ def add_edges_from(self, ebunch_to_add, **attr):
969
+ """Add all the edges in ebunch_to_add.
970
+
971
+ Parameters
972
+ ----------
973
+ ebunch_to_add : container of edges
974
+ Each edge given in the container will be added to the
975
+ graph. The edges must be given as 2-tuples (u, v) or
976
+ 3-tuples (u, v, d) where d is a dictionary containing edge data.
977
+ attr : keyword arguments, optional
978
+ Edge data (or labels or objects) can be assigned using
979
+ keyword arguments.
980
+
981
+ See Also
982
+ --------
983
+ add_edge : add a single edge
984
+ add_weighted_edges_from : convenient way to add weighted edges
985
+
986
+ Notes
987
+ -----
988
+ Adding the same edge twice has no effect but any edge data
989
+ will be updated when each duplicate edge is added.
990
+
991
+ Edge attributes specified in an ebunch take precedence over
992
+ attributes specified via keyword arguments.
993
+
994
+ When adding edges from an iterator over the graph you are changing,
995
+ a `RuntimeError` can be raised with message:
996
+ `RuntimeError: dictionary changed size during iteration`. This
997
+ happens when the graph's underlying dictionary is modified during
998
+ iteration. To avoid this error, evaluate the iterator into a separate
999
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
1000
+ object to `G.add_edges_from`.
1001
+
1002
+ Examples
1003
+ --------
1004
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1005
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
1006
+ >>> e = zip(range(0, 3), range(1, 4))
1007
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
1008
+
1009
+ Associate data to edges
1010
+
1011
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
1012
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
1013
+
1014
+ Evaluate an iterator over a graph if using it to modify the same graph
1015
+
1016
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
1017
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
1018
+ >>> # wrong way - will raise RuntimeError
1019
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
1020
+ >>> # correct way - note that there will be no self-edge for node 5
1021
+ >>> G.add_edges_from(list((5, n) for n in G.nodes))
1022
+ """
1023
+ for e in ebunch_to_add:
1024
+ ne = len(e)
1025
+ if ne == 3:
1026
+ u, v, dd = e
1027
+ elif ne == 2:
1028
+ u, v = e
1029
+ dd = {} # doesn't need edge_attr_dict_factory
1030
+ else:
1031
+ raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
1032
+ if u not in self._node:
1033
+ if u is None:
1034
+ raise ValueError("None cannot be a node")
1035
+ self._adj[u] = self.adjlist_inner_dict_factory()
1036
+ self._node[u] = self.node_attr_dict_factory()
1037
+ if v not in self._node:
1038
+ if v is None:
1039
+ raise ValueError("None cannot be a node")
1040
+ self._adj[v] = self.adjlist_inner_dict_factory()
1041
+ self._node[v] = self.node_attr_dict_factory()
1042
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
1043
+ datadict.update(attr)
1044
+ datadict.update(dd)
1045
+ self._adj[u][v] = datadict
1046
+ self._adj[v][u] = datadict
1047
+ nx._clear_cache(self)
1048
+
1049
+ def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
1050
+ """Add weighted edges in `ebunch_to_add` with specified weight attr
1051
+
1052
+ Parameters
1053
+ ----------
1054
+ ebunch_to_add : container of edges
1055
+ Each edge given in the list or container will be added
1056
+ to the graph. The edges must be given as 3-tuples (u, v, w)
1057
+ where w is a number.
1058
+ weight : string, optional (default= 'weight')
1059
+ The attribute name for the edge weights to be added.
1060
+ attr : keyword arguments, optional (default= no attributes)
1061
+ Edge attributes to add/update for all edges.
1062
+
1063
+ See Also
1064
+ --------
1065
+ add_edge : add a single edge
1066
+ add_edges_from : add multiple edges
1067
+
1068
+ Notes
1069
+ -----
1070
+ Adding the same edge twice for Graph/DiGraph simply updates
1071
+ the edge data. For MultiGraph/MultiDiGraph, duplicate edges
1072
+ are stored.
1073
+
1074
+ When adding edges from an iterator over the graph you are changing,
1075
+ a `RuntimeError` can be raised with message:
1076
+ `RuntimeError: dictionary changed size during iteration`. This
1077
+ happens when the graph's underlying dictionary is modified during
1078
+ iteration. To avoid this error, evaluate the iterator into a separate
1079
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
1080
+ object to `G.add_weighted_edges_from`.
1081
+
1082
+ Examples
1083
+ --------
1084
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1085
+ >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
1086
+
1087
+ Evaluate an iterator over edges before passing it
1088
+
1089
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
1090
+ >>> weight = 0.1
1091
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
1092
+ >>> # wrong way - will raise RuntimeError
1093
+ >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
1094
+ >>> # correct way - note that there will be no self-edge for node 5
1095
+ >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
1096
+ """
1097
+ self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
1098
+ nx._clear_cache(self)
1099
+
1100
+ def remove_edge(self, u, v):
1101
+ """Remove the edge between u and v.
1102
+
1103
+ Parameters
1104
+ ----------
1105
+ u, v : nodes
1106
+ Remove the edge between nodes u and v.
1107
+
1108
+ Raises
1109
+ ------
1110
+ NetworkXError
1111
+ If there is not an edge between u and v.
1112
+
1113
+ See Also
1114
+ --------
1115
+ remove_edges_from : remove a collection of edges
1116
+
1117
+ Examples
1118
+ --------
1119
+ >>> G = nx.path_graph(4) # or DiGraph, etc
1120
+ >>> G.remove_edge(0, 1)
1121
+ >>> e = (1, 2)
1122
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
1123
+ >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
1124
+ >>> G.remove_edge(*e[:2]) # select first part of edge tuple
1125
+ """
1126
+ try:
1127
+ del self._adj[u][v]
1128
+ if u != v: # self-loop needs only one entry removed
1129
+ del self._adj[v][u]
1130
+ except KeyError as err:
1131
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
1132
+ nx._clear_cache(self)
1133
+
1134
+ def remove_edges_from(self, ebunch):
1135
+ """Remove all edges specified in ebunch.
1136
+
1137
+ Parameters
1138
+ ----------
1139
+ ebunch: list or container of edge tuples
1140
+ Each edge given in the list or container will be removed
1141
+ from the graph. The edges can be:
1142
+
1143
+ - 2-tuples (u, v) edge between u and v.
1144
+ - 3-tuples (u, v, k) where k is ignored.
1145
+
1146
+ See Also
1147
+ --------
1148
+ remove_edge : remove a single edge
1149
+
1150
+ Notes
1151
+ -----
1152
+ Will fail silently if an edge in ebunch is not in the graph.
1153
+
1154
+ Examples
1155
+ --------
1156
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1157
+ >>> ebunch = [(1, 2), (2, 3)]
1158
+ >>> G.remove_edges_from(ebunch)
1159
+ """
1160
+ adj = self._adj
1161
+ for e in ebunch:
1162
+ u, v = e[:2] # ignore edge data if present
1163
+ if u in adj and v in adj[u]:
1164
+ del adj[u][v]
1165
+ if u != v: # self loop needs only one entry removed
1166
+ del adj[v][u]
1167
+ nx._clear_cache(self)
1168
+
1169
+ def update(self, edges=None, nodes=None):
1170
+ """Update the graph using nodes/edges/graphs as input.
1171
+
1172
+ Like dict.update, this method takes a graph as input, adding the
1173
+ graph's nodes and edges to this graph. It can also take two inputs:
1174
+ edges and nodes. Finally it can take either edges or nodes.
1175
+ To specify only nodes the keyword `nodes` must be used.
1176
+
1177
+ The collections of edges and nodes are treated similarly to
1178
+ the add_edges_from/add_nodes_from methods. When iterated, they
1179
+ should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
1180
+
1181
+ Parameters
1182
+ ----------
1183
+ edges : Graph object, collection of edges, or None
1184
+ The first parameter can be a graph or some edges. If it has
1185
+ attributes `nodes` and `edges`, then it is taken to be a
1186
+ Graph-like object and those attributes are used as collections
1187
+ of nodes and edges to be added to the graph.
1188
+ If the first parameter does not have those attributes, it is
1189
+ treated as a collection of edges and added to the graph.
1190
+ If the first argument is None, no edges are added.
1191
+ nodes : collection of nodes, or None
1192
+ The second parameter is treated as a collection of nodes
1193
+ to be added to the graph unless it is None.
1194
+ If `edges is None` and `nodes is None` an exception is raised.
1195
+ If the first parameter is a Graph, then `nodes` is ignored.
1196
+
1197
+ Examples
1198
+ --------
1199
+ >>> G = nx.path_graph(5)
1200
+ >>> G.update(nx.complete_graph(range(4, 10)))
1201
+ >>> from itertools import combinations
1202
+ >>> edges = (
1203
+ ... (u, v, {"power": u * v})
1204
+ ... for u, v in combinations(range(10, 20), 2)
1205
+ ... if u * v < 225
1206
+ ... )
1207
+ >>> nodes = [1000] # for singleton, use a container
1208
+ >>> G.update(edges, nodes)
1209
+
1210
+ Notes
1211
+ -----
1212
+ It you want to update the graph using an adjacency structure
1213
+ it is straightforward to obtain the edges/nodes from adjacency.
1214
+ The following examples provide common cases, your adjacency may
1215
+ be slightly different and require tweaks of these examples::
1216
+
1217
+ >>> # dict-of-set/list/tuple
1218
+ >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
1219
+ >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
1220
+ >>> G.update(edges=e, nodes=adj)
1221
+
1222
+ >>> DG = nx.DiGraph()
1223
+ >>> # dict-of-dict-of-attribute
1224
+ >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
1225
+ >>> e = [(u, v, {"weight": d}) for u, nbrs in adj.items() for v, d in nbrs.items()]
1226
+ >>> DG.update(edges=e, nodes=adj)
1227
+
1228
+ >>> # dict-of-dict-of-dict
1229
+ >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
1230
+ >>> e = [(u, v, {"weight": d}) for u, nbrs in adj.items() for v, d in nbrs.items()]
1231
+ >>> DG.update(edges=e, nodes=adj)
1232
+
1233
+ >>> # predecessor adjacency (dict-of-set)
1234
+ >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
1235
+ >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
1236
+
1237
+ >>> # MultiGraph dict-of-dict-of-dict-of-attribute
1238
+ >>> MDG = nx.MultiDiGraph()
1239
+ >>> adj = {
1240
+ ... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
1241
+ ... 3: {2: {0: {"weight": 0.7}}},
1242
+ ... }
1243
+ >>> e = [
1244
+ ... (u, v, ekey, d)
1245
+ ... for u, nbrs in adj.items()
1246
+ ... for v, keydict in nbrs.items()
1247
+ ... for ekey, d in keydict.items()
1248
+ ... ]
1249
+ >>> MDG.update(edges=e)
1250
+
1251
+ See Also
1252
+ --------
1253
+ add_edges_from: add multiple edges to a graph
1254
+ add_nodes_from: add multiple nodes to a graph
1255
+ """
1256
+ if edges is not None:
1257
+ if nodes is not None:
1258
+ self.add_nodes_from(nodes)
1259
+ self.add_edges_from(edges)
1260
+ else:
1261
+ # check if edges is a Graph object
1262
+ try:
1263
+ graph_nodes = edges.nodes
1264
+ graph_edges = edges.edges
1265
+ except AttributeError:
1266
+ # edge not Graph-like
1267
+ self.add_edges_from(edges)
1268
+ else: # edges is Graph-like
1269
+ self.add_nodes_from(graph_nodes.data())
1270
+ self.add_edges_from(graph_edges.data())
1271
+ self.graph.update(edges.graph)
1272
+ elif nodes is not None:
1273
+ self.add_nodes_from(nodes)
1274
+ else:
1275
+ raise NetworkXError("update needs nodes or edges input")
1276
+
1277
+ def has_edge(self, u, v):
1278
+ """Returns True if the edge (u, v) is in the graph.
1279
+
1280
+ This is the same as `v in G[u]` without KeyError exceptions.
1281
+
1282
+ Parameters
1283
+ ----------
1284
+ u, v : nodes
1285
+ Nodes can be, for example, strings or numbers.
1286
+ Nodes must be hashable (and not None) Python objects.
1287
+
1288
+ Returns
1289
+ -------
1290
+ edge_ind : bool
1291
+ True if edge is in the graph, False otherwise.
1292
+
1293
+ Examples
1294
+ --------
1295
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1296
+ >>> G.has_edge(0, 1) # using two nodes
1297
+ True
1298
+ >>> e = (0, 1)
1299
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
1300
+ True
1301
+ >>> e = (0, 1, {"weight": 7})
1302
+ >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
1303
+ True
1304
+
1305
+ The following syntax are equivalent:
1306
+
1307
+ >>> G.has_edge(0, 1)
1308
+ True
1309
+ >>> 1 in G[0] # though this gives KeyError if 0 not in G
1310
+ True
1311
+
1312
+ """
1313
+ try:
1314
+ return v in self._adj[u]
1315
+ except KeyError:
1316
+ return False
1317
+
1318
+ def neighbors(self, n):
1319
+ """Returns an iterator over all neighbors of node n.
1320
+
1321
+ This is identical to `iter(G[n])`
1322
+
1323
+ Parameters
1324
+ ----------
1325
+ n : node
1326
+ A node in the graph
1327
+
1328
+ Returns
1329
+ -------
1330
+ neighbors : iterator
1331
+ An iterator over all neighbors of node n
1332
+
1333
+ Raises
1334
+ ------
1335
+ NetworkXError
1336
+ If the node n is not in the graph.
1337
+
1338
+ Examples
1339
+ --------
1340
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1341
+ >>> [n for n in G.neighbors(0)]
1342
+ [1]
1343
+
1344
+ Notes
1345
+ -----
1346
+ Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
1347
+
1348
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1349
+ >>> G.add_edge("a", "b", weight=7)
1350
+ >>> G["a"]
1351
+ AtlasView({'b': {'weight': 7}})
1352
+ >>> G = nx.path_graph(4)
1353
+ >>> [n for n in G[0]]
1354
+ [1]
1355
+ """
1356
+ try:
1357
+ return iter(self._adj[n])
1358
+ except KeyError as err:
1359
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
1360
+
1361
+ @cached_property
1362
+ def edges(self):
1363
+ """An EdgeView of the Graph as G.edges or G.edges().
1364
+
1365
+ edges(self, nbunch=None, data=False, default=None)
1366
+
1367
+ The EdgeView provides set-like operations on the edge-tuples
1368
+ as well as edge attribute lookup. When called, it also provides
1369
+ an EdgeDataView object which allows control of access to edge
1370
+ attributes (but does not provide set-like operations).
1371
+ Hence, `G.edges[u, v]['color']` provides the value of the color
1372
+ attribute for edge `(u, v)` while
1373
+ `for (u, v, c) in G.edges.data('color', default='red'):`
1374
+ iterates through all the edges yielding the color attribute
1375
+ with default `'red'` if no color attribute exists.
1376
+
1377
+ Parameters
1378
+ ----------
1379
+ nbunch : single node, container, or all nodes (default= all nodes)
1380
+ The view will only report edges from these nodes.
1381
+ data : string or bool, optional (default=False)
1382
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
1383
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
1384
+ If False, return 2-tuple (u, v).
1385
+ default : value, optional (default=None)
1386
+ Value used for edges that don't have the requested attribute.
1387
+ Only relevant if data is not True or False.
1388
+
1389
+ Returns
1390
+ -------
1391
+ edges : EdgeView
1392
+ A view of edge attributes, usually it iterates over (u, v)
1393
+ or (u, v, d) tuples of edges, but can also be used for
1394
+ attribute lookup as `edges[u, v]['foo']`.
1395
+
1396
+ Notes
1397
+ -----
1398
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
1399
+ For directed graphs this returns the out-edges.
1400
+
1401
+ Examples
1402
+ --------
1403
+ >>> G = nx.path_graph(3) # or MultiGraph, etc
1404
+ >>> G.add_edge(2, 3, weight=5)
1405
+ >>> [e for e in G.edges]
1406
+ [(0, 1), (1, 2), (2, 3)]
1407
+ >>> G.edges.data() # default data is {} (empty dict)
1408
+ EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
1409
+ >>> G.edges.data("weight", default=1)
1410
+ EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
1411
+ >>> G.edges([0, 3]) # only edges from these nodes
1412
+ EdgeDataView([(0, 1), (3, 2)])
1413
+ >>> G.edges(0) # only edges from node 0
1414
+ EdgeDataView([(0, 1)])
1415
+ """
1416
+ return EdgeView(self)
1417
+
1418
+ def get_edge_data(self, u, v, default=None):
1419
+ """Returns the attribute dictionary associated with edge (u, v).
1420
+
1421
+ This is identical to `G[u][v]` except the default is returned
1422
+ instead of an exception if the edge doesn't exist.
1423
+
1424
+ Parameters
1425
+ ----------
1426
+ u, v : nodes
1427
+ default: any Python object (default=None)
1428
+ Value to return if the edge (u, v) is not found.
1429
+
1430
+ Returns
1431
+ -------
1432
+ edge_dict : dictionary
1433
+ The edge attribute dictionary.
1434
+
1435
+ Examples
1436
+ --------
1437
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1438
+ >>> G[0][1]
1439
+ {}
1440
+
1441
+ Warning: Assigning to `G[u][v]` is not permitted.
1442
+ But it is safe to assign attributes `G[u][v]['foo']`
1443
+
1444
+ >>> G[0][1]["weight"] = 7
1445
+ >>> G[0][1]["weight"]
1446
+ 7
1447
+ >>> G[1][0]["weight"]
1448
+ 7
1449
+
1450
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1451
+ >>> G.get_edge_data(0, 1) # default edge data is {}
1452
+ {}
1453
+ >>> e = (0, 1)
1454
+ >>> G.get_edge_data(*e) # tuple form
1455
+ {}
1456
+ >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
1457
+ 0
1458
+ """
1459
+ try:
1460
+ return self._adj[u][v]
1461
+ except KeyError:
1462
+ return default
1463
+
1464
+ def adjacency(self):
1465
+ """Returns an iterator over (node, adjacency dict) tuples for all nodes.
1466
+
1467
+ For directed graphs, only outgoing neighbors/adjacencies are included.
1468
+
1469
+ Returns
1470
+ -------
1471
+ adj_iter : iterator
1472
+ An iterator over (node, adjacency dictionary) for all nodes in
1473
+ the graph.
1474
+
1475
+ Examples
1476
+ --------
1477
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1478
+ >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
1479
+ [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
1480
+
1481
+ """
1482
+ return iter(self._adj.items())
1483
+
1484
+ @cached_property
1485
+ def degree(self):
1486
+ """A DegreeView for the Graph as G.degree or G.degree().
1487
+
1488
+ The node degree is the number of edges adjacent to the node.
1489
+ The weighted node degree is the sum of the edge weights for
1490
+ edges incident to that node.
1491
+
1492
+ This object provides an iterator for (node, degree) as well as
1493
+ lookup for the degree for a single node.
1494
+
1495
+ Parameters
1496
+ ----------
1497
+ nbunch : single node, container, or all nodes (default= all nodes)
1498
+ The view will only report edges incident to these nodes.
1499
+
1500
+ weight : string or None, optional (default=None)
1501
+ The name of an edge attribute that holds the numerical value used
1502
+ as a weight. If None, then each edge has weight 1.
1503
+ The degree is the sum of the edge weights adjacent to the node.
1504
+
1505
+ Returns
1506
+ -------
1507
+ DegreeView or int
1508
+ If multiple nodes are requested (the default), returns a `DegreeView`
1509
+ mapping nodes to their degree.
1510
+ If a single node is requested, returns the degree of the node as an integer.
1511
+
1512
+ Examples
1513
+ --------
1514
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1515
+ >>> G.degree[0] # node 0 has degree 1
1516
+ 1
1517
+ >>> list(G.degree([0, 1, 2]))
1518
+ [(0, 1), (1, 2), (2, 2)]
1519
+ """
1520
+ return DegreeView(self)
1521
+
1522
+ def clear(self):
1523
+ """Remove all nodes and edges from the graph.
1524
+
1525
+ This also removes the name, and all graph, node, and edge attributes.
1526
+
1527
+ Examples
1528
+ --------
1529
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1530
+ >>> G.clear()
1531
+ >>> list(G.nodes)
1532
+ []
1533
+ >>> list(G.edges)
1534
+ []
1535
+
1536
+ """
1537
+ self._adj.clear()
1538
+ self._node.clear()
1539
+ self.graph.clear()
1540
+ nx._clear_cache(self)
1541
+
1542
+ def clear_edges(self):
1543
+ """Remove all edges from the graph without altering nodes.
1544
+
1545
+ Examples
1546
+ --------
1547
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1548
+ >>> G.clear_edges()
1549
+ >>> list(G.nodes)
1550
+ [0, 1, 2, 3]
1551
+ >>> list(G.edges)
1552
+ []
1553
+ """
1554
+ for nbr_dict in self._adj.values():
1555
+ nbr_dict.clear()
1556
+ nx._clear_cache(self)
1557
+
1558
+ def is_multigraph(self):
1559
+ """Returns True if graph is a multigraph, False otherwise."""
1560
+ return False
1561
+
1562
+ def is_directed(self):
1563
+ """Returns True if graph is directed, False otherwise."""
1564
+ return False
1565
+
1566
+ def copy(self, as_view=False):
1567
+ """Returns a copy of the graph.
1568
+
1569
+ The copy method by default returns an independent shallow copy
1570
+ of the graph and attributes. That is, if an attribute is a
1571
+ container, that container is shared by the original an the copy.
1572
+ Use Python's `copy.deepcopy` for new containers.
1573
+
1574
+ If `as_view` is True then a view is returned instead of a copy.
1575
+
1576
+ Notes
1577
+ -----
1578
+ All copies reproduce the graph structure, but data attributes
1579
+ may be handled in different ways. There are four types of copies
1580
+ of a graph that people might want.
1581
+
1582
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1583
+ all data attributes and any objects they might contain.
1584
+ The entire graph object is new so that changes in the copy
1585
+ do not affect the original object. (see Python's copy.deepcopy)
1586
+
1587
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1588
+ is copied but the edge, node and graph attribute dicts are
1589
+ references to those in the original graph. This saves
1590
+ time and memory but could cause confusion if you change an attribute
1591
+ in one graph and it changes the attribute in the other.
1592
+ NetworkX does not provide this level of shallow copy.
1593
+
1594
+ Independent Shallow -- This copy creates new independent attribute
1595
+ dicts and then does a shallow copy of the attributes. That is, any
1596
+ attributes that are containers are shared between the new graph
1597
+ and the original. This is exactly what `dict.copy()` provides.
1598
+ You can obtain this style copy using:
1599
+
1600
+ >>> G = nx.path_graph(5)
1601
+ >>> H = G.copy()
1602
+ >>> H = G.copy(as_view=False)
1603
+ >>> H = nx.Graph(G)
1604
+ >>> H = G.__class__(G)
1605
+
1606
+ Fresh Data -- For fresh data, the graph structure is copied while
1607
+ new empty data attribute dicts are created. The resulting graph
1608
+ is independent of the original and it has no edge, node or graph
1609
+ attributes. Fresh copies are not enabled. Instead use:
1610
+
1611
+ >>> H = G.__class__()
1612
+ >>> H.add_nodes_from(G)
1613
+ >>> H.add_edges_from(G.edges)
1614
+
1615
+ View -- Inspired by dict-views, graph-views act like read-only
1616
+ versions of the original graph, providing a copy of the original
1617
+ structure without requiring any memory for copying the information.
1618
+
1619
+ See the Python copy module for more information on shallow
1620
+ and deep copies, https://docs.python.org/3/library/copy.html.
1621
+
1622
+ Parameters
1623
+ ----------
1624
+ as_view : bool, optional (default=False)
1625
+ If True, the returned graph-view provides a read-only view
1626
+ of the original graph without actually copying any data.
1627
+
1628
+ Returns
1629
+ -------
1630
+ G : Graph
1631
+ A copy of the graph.
1632
+
1633
+ See Also
1634
+ --------
1635
+ to_directed: return a directed copy of the graph.
1636
+
1637
+ Examples
1638
+ --------
1639
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1640
+ >>> H = G.copy()
1641
+
1642
+ """
1643
+ if as_view is True:
1644
+ return nx.graphviews.generic_graph_view(self)
1645
+ G = self.__class__()
1646
+ G.graph.update(self.graph)
1647
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1648
+ G.add_edges_from(
1649
+ (u, v, datadict.copy())
1650
+ for u, nbrs in self._adj.items()
1651
+ for v, datadict in nbrs.items()
1652
+ )
1653
+ return G
1654
+
1655
+ def to_directed(self, as_view=False):
1656
+ """Returns a directed representation of the graph.
1657
+
1658
+ Returns
1659
+ -------
1660
+ G : DiGraph
1661
+ A directed graph with the same name, same nodes, and with
1662
+ each edge (u, v, data) replaced by two directed edges
1663
+ (u, v, data) and (v, u, data).
1664
+
1665
+ Notes
1666
+ -----
1667
+ This returns a "deepcopy" of the edge, node, and
1668
+ graph attributes which attempts to completely copy
1669
+ all of the data and references.
1670
+
1671
+ This is in contrast to the similar D=DiGraph(G) which returns a
1672
+ shallow copy of the data.
1673
+
1674
+ See the Python copy module for more information on shallow
1675
+ and deep copies, https://docs.python.org/3/library/copy.html.
1676
+
1677
+ Warning: If you have subclassed Graph to use dict-like objects
1678
+ in the data structure, those changes do not transfer to the
1679
+ DiGraph created by this method.
1680
+
1681
+ Examples
1682
+ --------
1683
+ >>> G = nx.Graph() # or MultiGraph, etc
1684
+ >>> G.add_edge(0, 1)
1685
+ >>> H = G.to_directed()
1686
+ >>> list(H.edges)
1687
+ [(0, 1), (1, 0)]
1688
+
1689
+ If already directed, return a (deep) copy
1690
+
1691
+ >>> G = nx.DiGraph() # or MultiDiGraph, etc
1692
+ >>> G.add_edge(0, 1)
1693
+ >>> H = G.to_directed()
1694
+ >>> list(H.edges)
1695
+ [(0, 1)]
1696
+ """
1697
+ graph_class = self.to_directed_class()
1698
+ if as_view is True:
1699
+ return nx.graphviews.generic_graph_view(self, graph_class)
1700
+ # deepcopy when not a view
1701
+ G = graph_class()
1702
+ G.graph.update(deepcopy(self.graph))
1703
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1704
+ G.add_edges_from(
1705
+ (u, v, deepcopy(data))
1706
+ for u, nbrs in self._adj.items()
1707
+ for v, data in nbrs.items()
1708
+ )
1709
+ return G
1710
+
1711
+ def to_undirected(self, as_view=False):
1712
+ """Returns an undirected copy of the graph.
1713
+
1714
+ Parameters
1715
+ ----------
1716
+ as_view : bool (optional, default=False)
1717
+ If True return a view of the original undirected graph.
1718
+
1719
+ Returns
1720
+ -------
1721
+ G : Graph/MultiGraph
1722
+ A deepcopy of the graph.
1723
+
1724
+ See Also
1725
+ --------
1726
+ Graph, copy, add_edge, add_edges_from
1727
+
1728
+ Notes
1729
+ -----
1730
+ This returns a "deepcopy" of the edge, node, and
1731
+ graph attributes which attempts to completely copy
1732
+ all of the data and references.
1733
+
1734
+ This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
1735
+ shallow copy of the data.
1736
+
1737
+ See the Python copy module for more information on shallow
1738
+ and deep copies, https://docs.python.org/3/library/copy.html.
1739
+
1740
+ Warning: If you have subclassed DiGraph to use dict-like objects
1741
+ in the data structure, those changes do not transfer to the
1742
+ Graph created by this method.
1743
+
1744
+ Examples
1745
+ --------
1746
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
1747
+ >>> H = G.to_directed()
1748
+ >>> list(H.edges)
1749
+ [(0, 1), (1, 0)]
1750
+ >>> G2 = H.to_undirected()
1751
+ >>> list(G2.edges)
1752
+ [(0, 1)]
1753
+ """
1754
+ graph_class = self.to_undirected_class()
1755
+ if as_view is True:
1756
+ return nx.graphviews.generic_graph_view(self, graph_class)
1757
+ # deepcopy when not a view
1758
+ G = graph_class()
1759
+ G.graph.update(deepcopy(self.graph))
1760
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1761
+ G.add_edges_from(
1762
+ (u, v, deepcopy(d))
1763
+ for u, nbrs in self._adj.items()
1764
+ for v, d in nbrs.items()
1765
+ )
1766
+ return G
1767
+
1768
+ def subgraph(self, nodes):
1769
+ """Returns a SubGraph view of the subgraph induced on `nodes`.
1770
+
1771
+ The induced subgraph of the graph contains the nodes in `nodes`
1772
+ and the edges between those nodes.
1773
+
1774
+ Parameters
1775
+ ----------
1776
+ nodes : list, iterable
1777
+ A container of nodes which will be iterated through once.
1778
+
1779
+ Returns
1780
+ -------
1781
+ G : SubGraph View
1782
+ A subgraph view of the graph. The graph structure cannot be
1783
+ changed but node/edge attributes can and are shared with the
1784
+ original graph.
1785
+
1786
+ Notes
1787
+ -----
1788
+ The graph, edge and node attributes are shared with the original graph.
1789
+ Changes to the graph structure is ruled out by the view, but changes
1790
+ to attributes are reflected in the original graph.
1791
+
1792
+ To create a subgraph with its own copy of the edge/node attributes use:
1793
+ G.subgraph(nodes).copy()
1794
+
1795
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
1796
+ G.remove_nodes_from([n for n in G if n not in set(nodes)])
1797
+
1798
+ Subgraph views are sometimes NOT what you want. In most cases where
1799
+ you want to do more than simply look at the induced edges, it makes
1800
+ more sense to just create the subgraph as its own graph with code like:
1801
+
1802
+ ::
1803
+
1804
+ # Create a subgraph SG based on a (possibly multigraph) G
1805
+ SG = G.__class__()
1806
+ SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
1807
+ if SG.is_multigraph():
1808
+ SG.add_edges_from(
1809
+ (n, nbr, key, d)
1810
+ for n, nbrs in G.adj.items()
1811
+ if n in largest_wcc
1812
+ for nbr, keydict in nbrs.items()
1813
+ if nbr in largest_wcc
1814
+ for key, d in keydict.items()
1815
+ )
1816
+ else:
1817
+ SG.add_edges_from(
1818
+ (n, nbr, d)
1819
+ for n, nbrs in G.adj.items()
1820
+ if n in largest_wcc
1821
+ for nbr, d in nbrs.items()
1822
+ if nbr in largest_wcc
1823
+ )
1824
+ SG.graph.update(G.graph)
1825
+
1826
+ Examples
1827
+ --------
1828
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1829
+ >>> H = G.subgraph([0, 1, 2])
1830
+ >>> list(H.edges)
1831
+ [(0, 1), (1, 2)]
1832
+ """
1833
+ induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
1834
+ # if already a subgraph, don't make a chain
1835
+ subgraph = nx.subgraph_view
1836
+ if hasattr(self, "_NODE_OK"):
1837
+ return subgraph(
1838
+ self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
1839
+ )
1840
+ return subgraph(self, filter_node=induced_nodes)
1841
+
1842
+ def edge_subgraph(self, edges):
1843
+ """Returns the subgraph induced by the specified edges.
1844
+
1845
+ The induced subgraph contains each edge in `edges` and each
1846
+ node incident to any one of those edges.
1847
+
1848
+ Parameters
1849
+ ----------
1850
+ edges : iterable
1851
+ An iterable of edges in this graph.
1852
+
1853
+ Returns
1854
+ -------
1855
+ G : Graph
1856
+ An edge-induced subgraph of this graph with the same edge
1857
+ attributes.
1858
+
1859
+ Notes
1860
+ -----
1861
+ The graph, edge, and node attributes in the returned subgraph
1862
+ view are references to the corresponding attributes in the original
1863
+ graph. The view is read-only.
1864
+
1865
+ To create a full graph version of the subgraph with its own copy
1866
+ of the edge or node attributes, use::
1867
+
1868
+ G.edge_subgraph(edges).copy()
1869
+
1870
+ Examples
1871
+ --------
1872
+ >>> G = nx.path_graph(5)
1873
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
1874
+ >>> list(H.nodes)
1875
+ [0, 1, 3, 4]
1876
+ >>> list(H.edges)
1877
+ [(0, 1), (3, 4)]
1878
+
1879
+ """
1880
+ return nx.edge_subgraph(self, edges)
1881
+
1882
+ def size(self, weight=None):
1883
+ """Returns the number of edges or total of all edge weights.
1884
+
1885
+ Parameters
1886
+ ----------
1887
+ weight : string or None, optional (default=None)
1888
+ The edge attribute that holds the numerical value used
1889
+ as a weight. If None, then each edge has weight 1.
1890
+
1891
+ Returns
1892
+ -------
1893
+ size : numeric
1894
+ The number of edges or
1895
+ (if weight keyword is provided) the total weight sum.
1896
+
1897
+ If weight is None, returns an int. Otherwise a float
1898
+ (or more general numeric if the weights are more general).
1899
+
1900
+ See Also
1901
+ --------
1902
+ number_of_edges
1903
+
1904
+ Examples
1905
+ --------
1906
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1907
+ >>> G.size()
1908
+ 3
1909
+
1910
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1911
+ >>> G.add_edge("a", "b", weight=2)
1912
+ >>> G.add_edge("b", "c", weight=4)
1913
+ >>> G.size()
1914
+ 2
1915
+ >>> G.size(weight="weight")
1916
+ 6.0
1917
+ """
1918
+ s = sum(d for v, d in self.degree(weight=weight))
1919
+ # If `weight` is None, the sum of the degrees is guaranteed to be
1920
+ # even, so we can perform integer division and hence return an
1921
+ # integer. Otherwise, the sum of the weighted degrees is not
1922
+ # guaranteed to be an integer, so we perform "real" division.
1923
+ return s // 2 if weight is None else s / 2
1924
+
1925
+ def number_of_edges(self, u=None, v=None):
1926
+ """Returns the number of edges between two nodes.
1927
+
1928
+ Parameters
1929
+ ----------
1930
+ u, v : nodes, optional (default=all edges)
1931
+ If u and v are specified, return the number of edges between
1932
+ u and v. Otherwise return the total number of all edges.
1933
+
1934
+ Returns
1935
+ -------
1936
+ nedges : int
1937
+ The number of edges in the graph. If nodes `u` and `v` are
1938
+ specified return the number of edges between those nodes. If
1939
+ the graph is directed, this only returns the number of edges
1940
+ from `u` to `v`.
1941
+
1942
+ See Also
1943
+ --------
1944
+ size
1945
+
1946
+ Examples
1947
+ --------
1948
+ For undirected graphs, this method counts the total number of
1949
+ edges in the graph:
1950
+
1951
+ >>> G = nx.path_graph(4)
1952
+ >>> G.number_of_edges()
1953
+ 3
1954
+
1955
+ If you specify two nodes, this counts the total number of edges
1956
+ joining the two nodes:
1957
+
1958
+ >>> G.number_of_edges(0, 1)
1959
+ 1
1960
+
1961
+ For directed graphs, this method can count the total number of
1962
+ directed edges from `u` to `v`:
1963
+
1964
+ >>> G = nx.DiGraph()
1965
+ >>> G.add_edge(0, 1)
1966
+ >>> G.add_edge(1, 0)
1967
+ >>> G.number_of_edges(0, 1)
1968
+ 1
1969
+
1970
+ """
1971
+ if u is None:
1972
+ return int(self.size())
1973
+ if v in self._adj[u]:
1974
+ return 1
1975
+ return 0
1976
+
1977
+ def nbunch_iter(self, nbunch=None):
1978
+ """Returns an iterator over nodes contained in nbunch that are
1979
+ also in the graph.
1980
+
1981
+ The nodes in nbunch are checked for membership in the graph
1982
+ and if not are silently ignored.
1983
+
1984
+ Parameters
1985
+ ----------
1986
+ nbunch : single node, container, or all nodes (default= all nodes)
1987
+ The view will only report edges incident to these nodes.
1988
+
1989
+ Returns
1990
+ -------
1991
+ niter : iterator
1992
+ An iterator over nodes in nbunch that are also in the graph.
1993
+ If nbunch is None, iterate over all nodes in the graph.
1994
+
1995
+ Raises
1996
+ ------
1997
+ NetworkXError
1998
+ If nbunch is not a node or sequence of nodes.
1999
+ If a node in nbunch is not hashable.
2000
+
2001
+ See Also
2002
+ --------
2003
+ Graph.__iter__
2004
+
2005
+ Notes
2006
+ -----
2007
+ When nbunch is an iterator, the returned iterator yields values
2008
+ directly from nbunch, becoming exhausted when nbunch is exhausted.
2009
+
2010
+ To test whether nbunch is a single node, one can use
2011
+ "if nbunch in self:", even after processing with this routine.
2012
+
2013
+ If nbunch is not a node or a (possibly empty) sequence/iterator
2014
+ or None, a :exc:`NetworkXError` is raised. Also, if any object in
2015
+ nbunch is not hashable, a :exc:`NetworkXError` is raised.
2016
+ """
2017
+ if nbunch is None: # include all nodes via iterator
2018
+ bunch = iter(self._adj)
2019
+ elif nbunch in self: # if nbunch is a single node
2020
+ bunch = iter([nbunch])
2021
+ else: # if nbunch is a sequence of nodes
2022
+
2023
+ def bunch_iter(nlist, adj):
2024
+ try:
2025
+ for n in nlist:
2026
+ if n in adj:
2027
+ yield n
2028
+ except TypeError as err:
2029
+ exc, message = err, err.args[0]
2030
+ # capture error for non-sequence/iterator nbunch.
2031
+ if "iter" in message:
2032
+ exc = NetworkXError(
2033
+ "nbunch is not a node or a sequence of nodes."
2034
+ )
2035
+ # capture error for unhashable node.
2036
+ if "hashable" in message:
2037
+ exc = NetworkXError(
2038
+ f"Node {n} in sequence nbunch is not a valid node."
2039
+ )
2040
+ raise exc
2041
+
2042
+ bunch = bunch_iter(nbunch, self._adj)
2043
+ return bunch
env-llmeval/lib/python3.10/site-packages/networkx/classes/graphviews.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """View of Graphs as SubGraph, Reverse, Directed, Undirected.
2
+
3
+ In some algorithms it is convenient to temporarily morph
4
+ a graph to exclude some nodes or edges. It should be better
5
+ to do that via a view than to remove and then re-add.
6
+ In other algorithms it is convenient to temporarily morph
7
+ a graph to reverse directed edges, or treat a directed graph
8
+ as undirected, etc. This module provides those graph views.
9
+
10
+ The resulting views are essentially read-only graphs that
11
+ report data from the original graph object. We provide an
12
+ attribute G._graph which points to the underlying graph object.
13
+
14
+ Note: Since graphviews look like graphs, one can end up with
15
+ view-of-view-of-view chains. Be careful with chains because
16
+ they become very slow with about 15 nested views.
17
+ For the common simple case of node induced subgraphs created
18
+ from the graph class, we short-cut the chain by returning a
19
+ subgraph of the original graph directly rather than a subgraph
20
+ of a subgraph. We are careful not to disrupt any edge filter in
21
+ the middle subgraph. In general, determining how to short-cut
22
+ the chain is tricky and much harder with restricted_views than
23
+ with induced subgraphs.
24
+ Often it is easiest to use .copy() to avoid chains.
25
+ """
26
+ import networkx as nx
27
+ from networkx.classes.coreviews import (
28
+ FilterAdjacency,
29
+ FilterAtlas,
30
+ FilterMultiAdjacency,
31
+ UnionAdjacency,
32
+ UnionMultiAdjacency,
33
+ )
34
+ from networkx.classes.filters import no_filter
35
+ from networkx.exception import NetworkXError
36
+ from networkx.utils import deprecate_positional_args, not_implemented_for
37
+
38
+ __all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
39
+
40
+
41
+ def generic_graph_view(G, create_using=None):
42
+ """Returns a read-only view of `G`.
43
+
44
+ The graph `G` and its attributes are not copied but viewed through the new graph object
45
+ of the same class as `G` (or of the class specified in `create_using`).
46
+
47
+ Parameters
48
+ ----------
49
+ G : graph
50
+ A directed/undirected graph/multigraph.
51
+
52
+ create_using : NetworkX graph constructor, optional (default=None)
53
+ Graph type to create. If graph instance, then cleared before populated.
54
+ If `None`, then the appropriate Graph type is inferred from `G`.
55
+
56
+ Returns
57
+ -------
58
+ newG : graph
59
+ A view of the input graph `G` and its attributes as viewed through
60
+ the `create_using` class.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXError
65
+ If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
66
+
67
+ Notes
68
+ -----
69
+ The returned graph view is read-only (cannot modify the graph).
70
+ Yet the view reflects any changes in `G`. The intent is to mimic dict views.
71
+
72
+ Examples
73
+ --------
74
+ >>> G = nx.Graph()
75
+ >>> G.add_edge(1, 2, weight=0.3)
76
+ >>> G.add_edge(2, 3, weight=0.5)
77
+ >>> G.edges(data=True)
78
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
79
+
80
+ The view exposes the attributes from the original graph.
81
+
82
+ >>> viewG = nx.graphviews.generic_graph_view(G)
83
+ >>> viewG.edges(data=True)
84
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
85
+
86
+ Changes to `G` are reflected in `viewG`.
87
+
88
+ >>> G.remove_edge(2, 3)
89
+ >>> G.edges(data=True)
90
+ EdgeDataView([(1, 2, {'weight': 0.3})])
91
+
92
+ >>> viewG.edges(data=True)
93
+ EdgeDataView([(1, 2, {'weight': 0.3})])
94
+
95
+ We can change the graph type with the `create_using` parameter.
96
+
97
+ >>> type(G)
98
+ <class 'networkx.classes.graph.Graph'>
99
+ >>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph)
100
+ >>> type(viewDG)
101
+ <class 'networkx.classes.digraph.DiGraph'>
102
+ """
103
+ if create_using is None:
104
+ newG = G.__class__()
105
+ else:
106
+ newG = nx.empty_graph(0, create_using)
107
+ if G.is_multigraph() != newG.is_multigraph():
108
+ raise NetworkXError("Multigraph for G must agree with create_using")
109
+ newG = nx.freeze(newG)
110
+
111
+ # create view by assigning attributes from G
112
+ newG._graph = G
113
+ newG.graph = G.graph
114
+
115
+ newG._node = G._node
116
+ if newG.is_directed():
117
+ if G.is_directed():
118
+ newG._succ = G._succ
119
+ newG._pred = G._pred
120
+ # newG._adj is synced with _succ
121
+ else:
122
+ newG._succ = G._adj
123
+ newG._pred = G._adj
124
+ # newG._adj is synced with _succ
125
+ elif G.is_directed():
126
+ if G.is_multigraph():
127
+ newG._adj = UnionMultiAdjacency(G._succ, G._pred)
128
+ else:
129
+ newG._adj = UnionAdjacency(G._succ, G._pred)
130
+ else:
131
+ newG._adj = G._adj
132
+ return newG
133
+
134
+
135
+ @deprecate_positional_args(version="3.4")
136
+ def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter):
137
+ """View of `G` applying a filter on nodes and edges.
138
+
139
+ `subgraph_view` provides a read-only view of the input graph that excludes
140
+ nodes and edges based on the outcome of two filter functions `filter_node`
141
+ and `filter_edge`.
142
+
143
+ The `filter_node` function takes one argument --- the node --- and returns
144
+ `True` if the node should be included in the subgraph, and `False` if it
145
+ should not be included.
146
+
147
+ The `filter_edge` function takes two (or three arguments if `G` is a
148
+ multi-graph) --- the nodes describing an edge, plus the edge-key if
149
+ parallel edges are possible --- and returns `True` if the edge should be
150
+ included in the subgraph, and `False` if it should not be included.
151
+
152
+ Both node and edge filter functions are called on graph elements as they
153
+ are queried, meaning there is no up-front cost to creating the view.
154
+
155
+ Parameters
156
+ ----------
157
+ G : networkx.Graph
158
+ A directed/undirected graph/multigraph
159
+
160
+ filter_node : callable, optional
161
+ A function taking a node as input, which returns `True` if the node
162
+ should appear in the view.
163
+
164
+ filter_edge : callable, optional
165
+ A function taking as input the two nodes describing an edge (plus the
166
+ edge-key if `G` is a multi-graph), which returns `True` if the edge
167
+ should appear in the view.
168
+
169
+ Returns
170
+ -------
171
+ graph : networkx.Graph
172
+ A read-only graph view of the input graph.
173
+
174
+ Examples
175
+ --------
176
+ >>> G = nx.path_graph(6)
177
+
178
+ Filter functions operate on the node, and return `True` if the node should
179
+ appear in the view:
180
+
181
+ >>> def filter_node(n1):
182
+ ... return n1 != 5
183
+ >>> view = nx.subgraph_view(G, filter_node=filter_node)
184
+ >>> view.nodes()
185
+ NodeView((0, 1, 2, 3, 4))
186
+
187
+ We can use a closure pattern to filter graph elements based on additional
188
+ data --- for example, filtering on edge data attached to the graph:
189
+
190
+ >>> G[3][4]["cross_me"] = False
191
+ >>> def filter_edge(n1, n2):
192
+ ... return G[n1][n2].get("cross_me", True)
193
+ >>> view = nx.subgraph_view(G, filter_edge=filter_edge)
194
+ >>> view.edges()
195
+ EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
196
+
197
+ >>> view = nx.subgraph_view(
198
+ ... G,
199
+ ... filter_node=filter_node,
200
+ ... filter_edge=filter_edge,
201
+ ... )
202
+ >>> view.nodes()
203
+ NodeView((0, 1, 2, 3, 4))
204
+ >>> view.edges()
205
+ EdgeView([(0, 1), (1, 2), (2, 3)])
206
+ """
207
+ newG = nx.freeze(G.__class__())
208
+ newG._NODE_OK = filter_node
209
+ newG._EDGE_OK = filter_edge
210
+
211
+ # create view by assigning attributes from G
212
+ newG._graph = G
213
+ newG.graph = G.graph
214
+
215
+ newG._node = FilterAtlas(G._node, filter_node)
216
+ if G.is_multigraph():
217
+ Adj = FilterMultiAdjacency
218
+
219
+ def reverse_edge(u, v, k=None):
220
+ return filter_edge(v, u, k)
221
+
222
+ else:
223
+ Adj = FilterAdjacency
224
+
225
+ def reverse_edge(u, v, k=None):
226
+ return filter_edge(v, u)
227
+
228
+ if G.is_directed():
229
+ newG._succ = Adj(G._succ, filter_node, filter_edge)
230
+ newG._pred = Adj(G._pred, filter_node, reverse_edge)
231
+ # newG._adj is synced with _succ
232
+ else:
233
+ newG._adj = Adj(G._adj, filter_node, filter_edge)
234
+ return newG
235
+
236
+
237
+ @not_implemented_for("undirected")
238
+ def reverse_view(G):
239
+ """View of `G` with edge directions reversed
240
+
241
+ `reverse_view` returns a read-only view of the input graph where
242
+ edge directions are reversed.
243
+
244
+ Identical to digraph.reverse(copy=False)
245
+
246
+ Parameters
247
+ ----------
248
+ G : networkx.DiGraph
249
+
250
+ Returns
251
+ -------
252
+ graph : networkx.DiGraph
253
+
254
+ Examples
255
+ --------
256
+ >>> G = nx.DiGraph()
257
+ >>> G.add_edge(1, 2)
258
+ >>> G.add_edge(2, 3)
259
+ >>> G.edges()
260
+ OutEdgeView([(1, 2), (2, 3)])
261
+
262
+ >>> view = nx.reverse_view(G)
263
+ >>> view.edges()
264
+ OutEdgeView([(2, 1), (3, 2)])
265
+ """
266
+ newG = generic_graph_view(G)
267
+ newG._succ, newG._pred = G._pred, G._succ
268
+ # newG._adj is synced with _succ
269
+ return newG
env-llmeval/lib/python3.10/site-packages/networkx/classes/multidigraph.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiDiGraph."""
2
+ from copy import deepcopy
3
+ from functools import cached_property
4
+
5
+ import networkx as nx
6
+ from networkx import convert
7
+ from networkx.classes.coreviews import MultiAdjacencyView
8
+ from networkx.classes.digraph import DiGraph
9
+ from networkx.classes.multigraph import MultiGraph
10
+ from networkx.classes.reportviews import (
11
+ DiMultiDegreeView,
12
+ InMultiDegreeView,
13
+ InMultiEdgeView,
14
+ OutMultiDegreeView,
15
+ OutMultiEdgeView,
16
+ )
17
+ from networkx.exception import NetworkXError
18
+
19
+ __all__ = ["MultiDiGraph"]
20
+
21
+
22
+ class MultiDiGraph(MultiGraph, DiGraph):
23
+ """A directed graph class that can store multiedges.
24
+
25
+ Multiedges are multiple edges between two nodes. Each edge
26
+ can hold optional data or attributes.
27
+
28
+ A MultiDiGraph holds directed edges. Self loops are allowed.
29
+
30
+ Nodes can be arbitrary (hashable) Python objects with optional
31
+ key/value attributes. By convention `None` is not used as a node.
32
+
33
+ Edges are represented as links between nodes with optional
34
+ key/value attributes.
35
+
36
+ Parameters
37
+ ----------
38
+ incoming_graph_data : input graph (optional, default: None)
39
+ Data to initialize graph. If None (default) an empty
40
+ graph is created. The data can be any format that is supported
41
+ by the to_networkx_graph() function, currently including edge list,
42
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
43
+ sparse matrix, or PyGraphviz graph.
44
+
45
+ multigraph_input : bool or None (default None)
46
+ Note: Only used when `incoming_graph_data` is a dict.
47
+ If True, `incoming_graph_data` is assumed to be a
48
+ dict-of-dict-of-dict-of-dict structure keyed by
49
+ node to neighbor to edge keys to edge data for multi-edges.
50
+ A NetworkXError is raised if this is not the case.
51
+ If False, :func:`to_networkx_graph` is used to try to determine
52
+ the dict's graph data structure as either a dict-of-dict-of-dict
53
+ keyed by node to neighbor to edge data, or a dict-of-iterable
54
+ keyed by node to neighbors.
55
+ If None, the treatment for True is tried, but if it fails,
56
+ the treatment for False is tried.
57
+
58
+ attr : keyword arguments, optional (default= no attributes)
59
+ Attributes to add to graph as key=value pairs.
60
+
61
+ See Also
62
+ --------
63
+ Graph
64
+ DiGraph
65
+ MultiGraph
66
+
67
+ Examples
68
+ --------
69
+ Create an empty graph structure (a "null graph") with no nodes and
70
+ no edges.
71
+
72
+ >>> G = nx.MultiDiGraph()
73
+
74
+ G can be grown in several ways.
75
+
76
+ **Nodes:**
77
+
78
+ Add one node at a time:
79
+
80
+ >>> G.add_node(1)
81
+
82
+ Add the nodes from any container (a list, dict, set or
83
+ even the lines from a file or the nodes from another graph).
84
+
85
+ >>> G.add_nodes_from([2, 3])
86
+ >>> G.add_nodes_from(range(100, 110))
87
+ >>> H = nx.path_graph(10)
88
+ >>> G.add_nodes_from(H)
89
+
90
+ In addition to strings and integers any hashable Python object
91
+ (except None) can represent a node, e.g. a customized node object,
92
+ or even another Graph.
93
+
94
+ >>> G.add_node(H)
95
+
96
+ **Edges:**
97
+
98
+ G can also be grown by adding edges.
99
+
100
+ Add one edge,
101
+
102
+ >>> key = G.add_edge(1, 2)
103
+
104
+ a list of edges,
105
+
106
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
107
+
108
+ or a collection of edges,
109
+
110
+ >>> keys = G.add_edges_from(H.edges)
111
+
112
+ If some edges connect nodes not yet in the graph, the nodes
113
+ are added automatically. If an edge already exists, an additional
114
+ edge is created and stored using a key to identify the edge.
115
+ By default the key is the lowest unused integer.
116
+
117
+ >>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
118
+ >>> G[4]
119
+ AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
120
+
121
+ **Attributes:**
122
+
123
+ Each graph, node, and edge can hold key/value attribute pairs
124
+ in an associated attribute dictionary (the keys must be hashable).
125
+ By default these are empty, but can be added or changed using
126
+ add_edge, add_node or direct manipulation of the attribute
127
+ dictionaries named graph, node and edge respectively.
128
+
129
+ >>> G = nx.MultiDiGraph(day="Friday")
130
+ >>> G.graph
131
+ {'day': 'Friday'}
132
+
133
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
134
+
135
+ >>> G.add_node(1, time="5pm")
136
+ >>> G.add_nodes_from([3], time="2pm")
137
+ >>> G.nodes[1]
138
+ {'time': '5pm'}
139
+ >>> G.nodes[1]["room"] = 714
140
+ >>> del G.nodes[1]["room"] # remove attribute
141
+ >>> list(G.nodes(data=True))
142
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
143
+
144
+ Add edge attributes using add_edge(), add_edges_from(), subscript
145
+ notation, or G.edges.
146
+
147
+ >>> key = G.add_edge(1, 2, weight=4.7)
148
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
149
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
150
+ >>> G[1][2][0]["weight"] = 4.7
151
+ >>> G.edges[1, 2, 0]["weight"] = 4
152
+
153
+ Warning: we protect the graph data structure by making `G.edges[1,
154
+ 2, 0]` a read-only dict-like structure. However, you can assign to
155
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
156
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
157
+ (for multigraphs the edge key is required: `MG.edges[u, v,
158
+ key][name] = value`).
159
+
160
+ **Shortcuts:**
161
+
162
+ Many common graph features allow python syntax to speed reporting.
163
+
164
+ >>> 1 in G # check if node in graph
165
+ True
166
+ >>> [n for n in G if n < 3] # iterate through nodes
167
+ [1, 2]
168
+ >>> len(G) # number of nodes in graph
169
+ 5
170
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
171
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
172
+
173
+ Often the best way to traverse all edges of a graph is via the neighbors.
174
+ The neighbors are available as an adjacency-view `G.adj` object or via
175
+ the method `G.adjacency()`.
176
+
177
+ >>> for n, nbrsdict in G.adjacency():
178
+ ... for nbr, keydict in nbrsdict.items():
179
+ ... for key, eattr in keydict.items():
180
+ ... if "weight" in eattr:
181
+ ... # Do something useful with the edges
182
+ ... pass
183
+
184
+ But the edges() method is often more convenient:
185
+
186
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
187
+ ... if weight is not None:
188
+ ... # Do something useful with the edges
189
+ ... pass
190
+
191
+ **Reporting:**
192
+
193
+ Simple graph information is obtained using methods and object-attributes.
194
+ Reporting usually provides views instead of containers to reduce memory
195
+ usage. The views update as the graph is updated similarly to dict-views.
196
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
197
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
198
+ (e.g. `nodes.items()`, `nodes.data('color')`,
199
+ `nodes.data('color', default='blue')` and similarly for `edges`)
200
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
201
+
202
+ For details on these and other miscellaneous methods, see below.
203
+
204
+ **Subclasses (Advanced):**
205
+
206
+ The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
207
+ The outer dict (node_dict) holds adjacency information keyed by node.
208
+ The next dict (adjlist_dict) represents the adjacency information
209
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
210
+ each edge_attr dict keyed by edge key. The inner dict
211
+ (edge_attr_dict) represents the edge data and holds edge attribute
212
+ values keyed by attribute names.
213
+
214
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
215
+ structure can be replaced by a user defined dict-like object.
216
+ In general, the dict-like features should be maintained but
217
+ extra features can be added. To replace one of the dicts create
218
+ a new graph class by changing the class(!) variable holding the
219
+ factory for that dict-like structure. The variable names are
220
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
221
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
222
+ and graph_attr_dict_factory.
223
+
224
+ node_dict_factory : function, (default: dict)
225
+ Factory function to be used to create the dict containing node
226
+ attributes, keyed by node id.
227
+ It should require no arguments and return a dict-like object
228
+
229
+ node_attr_dict_factory: function, (default: dict)
230
+ Factory function to be used to create the node attribute
231
+ dict which holds attribute values keyed by attribute name.
232
+ It should require no arguments and return a dict-like object
233
+
234
+ adjlist_outer_dict_factory : function, (default: dict)
235
+ Factory function to be used to create the outer-most dict
236
+ in the data structure that holds adjacency info keyed by node.
237
+ It should require no arguments and return a dict-like object.
238
+
239
+ adjlist_inner_dict_factory : function, (default: dict)
240
+ Factory function to be used to create the adjacency list
241
+ dict which holds multiedge key dicts keyed by neighbor.
242
+ It should require no arguments and return a dict-like object.
243
+
244
+ edge_key_dict_factory : function, (default: dict)
245
+ Factory function to be used to create the edge key dict
246
+ which holds edge data keyed by edge key.
247
+ It should require no arguments and return a dict-like object.
248
+
249
+ edge_attr_dict_factory : function, (default: dict)
250
+ Factory function to be used to create the edge attribute
251
+ dict which holds attribute values keyed by attribute name.
252
+ It should require no arguments and return a dict-like object.
253
+
254
+ graph_attr_dict_factory : function, (default: dict)
255
+ Factory function to be used to create the graph attribute
256
+ dict which holds attribute values keyed by attribute name.
257
+ It should require no arguments and return a dict-like object.
258
+
259
+ Typically, if your extension doesn't impact the data structure all
260
+ methods will inherited without issue except: `to_directed/to_undirected`.
261
+ By default these methods create a DiGraph/Graph class and you probably
262
+ want them to create your extension of a DiGraph/Graph. To facilitate
263
+ this we define two class variables that you can set in your subclass.
264
+
265
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
266
+ Class to create a new graph structure in the `to_directed` method.
267
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
268
+
269
+ to_undirected_class : callable, (default: Graph or MultiGraph)
270
+ Class to create a new graph structure in the `to_undirected` method.
271
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
272
+
273
+ **Subclassing Example**
274
+
275
+ Create a low memory graph class that effectively disallows edge
276
+ attributes by using a single attribute dict for all edges.
277
+ This reduces the memory used, but you lose edge attributes.
278
+
279
+ >>> class ThinGraph(nx.Graph):
280
+ ... all_edge_dict = {"weight": 1}
281
+ ...
282
+ ... def single_edge_dict(self):
283
+ ... return self.all_edge_dict
284
+ ...
285
+ ... edge_attr_dict_factory = single_edge_dict
286
+ >>> G = ThinGraph()
287
+ >>> G.add_edge(2, 1)
288
+ >>> G[2][1]
289
+ {'weight': 1}
290
+ >>> G.add_edge(2, 2)
291
+ >>> G[2][1] is G[2][2]
292
+ True
293
+ """
294
+
295
+ # node_dict_factory = dict # already assigned in Graph
296
+ # adjlist_outer_dict_factory = dict
297
+ # adjlist_inner_dict_factory = dict
298
+ edge_key_dict_factory = dict
299
+ # edge_attr_dict_factory = dict
300
+
301
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
302
+ """Initialize a graph with edges, name, or graph attributes.
303
+
304
+ Parameters
305
+ ----------
306
+ incoming_graph_data : input graph
307
+ Data to initialize graph. If incoming_graph_data=None (default)
308
+ an empty graph is created. The data can be an edge list, or any
309
+ NetworkX graph object. If the corresponding optional Python
310
+ packages are installed the data can also be a 2D NumPy array, a
311
+ SciPy sparse array, or a PyGraphviz graph.
312
+
313
+ multigraph_input : bool or None (default None)
314
+ Note: Only used when `incoming_graph_data` is a dict.
315
+ If True, `incoming_graph_data` is assumed to be a
316
+ dict-of-dict-of-dict-of-dict structure keyed by
317
+ node to neighbor to edge keys to edge data for multi-edges.
318
+ A NetworkXError is raised if this is not the case.
319
+ If False, :func:`to_networkx_graph` is used to try to determine
320
+ the dict's graph data structure as either a dict-of-dict-of-dict
321
+ keyed by node to neighbor to edge data, or a dict-of-iterable
322
+ keyed by node to neighbors.
323
+ If None, the treatment for True is tried, but if it fails,
324
+ the treatment for False is tried.
325
+
326
+ attr : keyword arguments, optional (default= no attributes)
327
+ Attributes to add to graph as key=value pairs.
328
+
329
+ See Also
330
+ --------
331
+ convert
332
+
333
+ Examples
334
+ --------
335
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
336
+ >>> G = nx.Graph(name="my graph")
337
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
338
+ >>> G = nx.Graph(e)
339
+
340
+ Arbitrary graph attribute pairs (key=value) may be assigned
341
+
342
+ >>> G = nx.Graph(e, day="Friday")
343
+ >>> G.graph
344
+ {'day': 'Friday'}
345
+
346
+ """
347
+ # multigraph_input can be None/True/False. So check "is not False"
348
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
349
+ DiGraph.__init__(self)
350
+ try:
351
+ convert.from_dict_of_dicts(
352
+ incoming_graph_data, create_using=self, multigraph_input=True
353
+ )
354
+ self.graph.update(attr)
355
+ except Exception as err:
356
+ if multigraph_input is True:
357
+ raise nx.NetworkXError(
358
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
359
+ )
360
+ DiGraph.__init__(self, incoming_graph_data, **attr)
361
+ else:
362
+ DiGraph.__init__(self, incoming_graph_data, **attr)
363
+
364
+ @cached_property
365
+ def adj(self):
366
+ """Graph adjacency object holding the neighbors of each node.
367
+
368
+ This object is a read-only dict-like structure with node keys
369
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
370
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
371
+ the color of the edge `(3, 2, 0)` to `"blue"`.
372
+
373
+ Iterating over G.adj behaves like a dict. Useful idioms include
374
+ `for nbr, datadict in G.adj[n].items():`.
375
+
376
+ The neighbor information is also provided by subscripting the graph.
377
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
378
+
379
+ For directed graphs, `G.adj` holds outgoing (successor) info.
380
+ """
381
+ return MultiAdjacencyView(self._succ)
382
+
383
+ @cached_property
384
+ def succ(self):
385
+ """Graph adjacency object holding the successors 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 edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
390
+ the color of the edge `(3, 2, 0)` 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.succ` is identical to `G.adj`.
399
+ """
400
+ return MultiAdjacencyView(self._succ)
401
+
402
+ @cached_property
403
+ def pred(self):
404
+ """Graph adjacency object holding the predecessors 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 edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
409
+ the color of the edge `(3, 2, 0)` to `"blue"`.
410
+
411
+ Iterating over G.adj behaves like a dict. Useful idioms include
412
+ `for nbr, datadict in G.adj[n].items():`.
413
+ """
414
+ return MultiAdjacencyView(self._pred)
415
+
416
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
417
+ """Add an edge between u and v.
418
+
419
+ The nodes u and v will be automatically added if they are
420
+ not already in the graph.
421
+
422
+ Edge attributes can be specified with keywords or by directly
423
+ accessing the edge's attribute dictionary. See examples below.
424
+
425
+ Parameters
426
+ ----------
427
+ u_for_edge, v_for_edge : nodes
428
+ Nodes can be, for example, strings or numbers.
429
+ Nodes must be hashable (and not None) Python objects.
430
+ key : hashable identifier, optional (default=lowest unused integer)
431
+ Used to distinguish multiedges between a pair of nodes.
432
+ attr : keyword arguments, optional
433
+ Edge data (or labels or objects) can be assigned using
434
+ keyword arguments.
435
+
436
+ Returns
437
+ -------
438
+ The edge key assigned to the edge.
439
+
440
+ See Also
441
+ --------
442
+ add_edges_from : add a collection of edges
443
+
444
+ Notes
445
+ -----
446
+ To replace/update edge data, use the optional key argument
447
+ to identify a unique edge. Otherwise a new edge will be created.
448
+
449
+ NetworkX algorithms designed for weighted graphs cannot use
450
+ multigraphs directly because it is not clear how to handle
451
+ multiedge weights. Convert to Graph using edge attribute
452
+ 'weight' to enable weighted graph algorithms.
453
+
454
+ Default keys are generated using the method `new_edge_key()`.
455
+ This method can be overridden by subclassing the base class and
456
+ providing a custom `new_edge_key()` method.
457
+
458
+ Examples
459
+ --------
460
+ The following all add the edge e=(1, 2) to graph G:
461
+
462
+ >>> G = nx.MultiDiGraph()
463
+ >>> e = (1, 2)
464
+ >>> key = G.add_edge(1, 2) # explicit two-node form
465
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
466
+ 1
467
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
468
+ [2]
469
+
470
+ Associate data to edges using keywords:
471
+
472
+ >>> key = G.add_edge(1, 2, weight=3)
473
+ >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
474
+ >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
475
+
476
+ For non-string attribute keys, use subscript notation.
477
+
478
+ >>> ekey = G.add_edge(1, 2)
479
+ >>> G[1][2][0].update({0: 5})
480
+ >>> G.edges[1, 2, 0].update({0: 5})
481
+ """
482
+ u, v = u_for_edge, v_for_edge
483
+ # add nodes
484
+ if u not in self._succ:
485
+ if u is None:
486
+ raise ValueError("None cannot be a node")
487
+ self._succ[u] = self.adjlist_inner_dict_factory()
488
+ self._pred[u] = self.adjlist_inner_dict_factory()
489
+ self._node[u] = self.node_attr_dict_factory()
490
+ if v not in self._succ:
491
+ if v is None:
492
+ raise ValueError("None cannot be a node")
493
+ self._succ[v] = self.adjlist_inner_dict_factory()
494
+ self._pred[v] = self.adjlist_inner_dict_factory()
495
+ self._node[v] = self.node_attr_dict_factory()
496
+ if key is None:
497
+ key = self.new_edge_key(u, v)
498
+ if v in self._succ[u]:
499
+ keydict = self._adj[u][v]
500
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
501
+ datadict.update(attr)
502
+ keydict[key] = datadict
503
+ else:
504
+ # selfloops work this way without special treatment
505
+ datadict = self.edge_attr_dict_factory()
506
+ datadict.update(attr)
507
+ keydict = self.edge_key_dict_factory()
508
+ keydict[key] = datadict
509
+ self._succ[u][v] = keydict
510
+ self._pred[v][u] = keydict
511
+ nx._clear_cache(self)
512
+ return key
513
+
514
+ def remove_edge(self, u, v, key=None):
515
+ """Remove an edge between u and v.
516
+
517
+ Parameters
518
+ ----------
519
+ u, v : nodes
520
+ Remove an edge between nodes u and v.
521
+ key : hashable identifier, optional (default=None)
522
+ Used to distinguish multiple edges between a pair of nodes.
523
+ If None, remove a single edge between u and v. If there are
524
+ multiple edges, removes the last edge added in terms of
525
+ insertion order.
526
+
527
+ Raises
528
+ ------
529
+ NetworkXError
530
+ If there is not an edge between u and v, or
531
+ if there is no edge with the specified key.
532
+
533
+ See Also
534
+ --------
535
+ remove_edges_from : remove a collection of edges
536
+
537
+ Examples
538
+ --------
539
+ >>> G = nx.MultiDiGraph()
540
+ >>> nx.add_path(G, [0, 1, 2, 3])
541
+ >>> G.remove_edge(0, 1)
542
+ >>> e = (1, 2)
543
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
544
+
545
+ For multiple edges
546
+
547
+ >>> G = nx.MultiDiGraph()
548
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
549
+ [0, 1, 2]
550
+
551
+ When ``key=None`` (the default), edges are removed in the opposite
552
+ order that they were added:
553
+
554
+ >>> G.remove_edge(1, 2)
555
+ >>> G.edges(keys=True)
556
+ OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
557
+
558
+ For edges with keys
559
+
560
+ >>> G = nx.MultiDiGraph()
561
+ >>> G.add_edge(1, 2, key="first")
562
+ 'first'
563
+ >>> G.add_edge(1, 2, key="second")
564
+ 'second'
565
+ >>> G.remove_edge(1, 2, key="first")
566
+ >>> G.edges(keys=True)
567
+ OutMultiEdgeView([(1, 2, 'second')])
568
+
569
+ """
570
+ try:
571
+ d = self._adj[u][v]
572
+ except KeyError as err:
573
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
574
+ # remove the edge with specified data
575
+ if key is None:
576
+ d.popitem()
577
+ else:
578
+ try:
579
+ del d[key]
580
+ except KeyError as err:
581
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
582
+ raise NetworkXError(msg) from err
583
+ if len(d) == 0:
584
+ # remove the key entries if last edge
585
+ del self._succ[u][v]
586
+ del self._pred[v][u]
587
+ nx._clear_cache(self)
588
+
589
+ @cached_property
590
+ def edges(self):
591
+ """An OutMultiEdgeView of the Graph as G.edges or G.edges().
592
+
593
+ edges(self, nbunch=None, data=False, keys=False, default=None)
594
+
595
+ The OutMultiEdgeView provides set-like operations on the edge-tuples
596
+ as well as edge attribute lookup. When called, it also provides
597
+ an EdgeDataView object which allows control of access to edge
598
+ attributes (but does not provide set-like operations).
599
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
600
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
601
+ ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
602
+ iterates through all the edges yielding the color attribute with
603
+ default `'red'` if no color attribute exists.
604
+
605
+ Edges are returned as tuples with optional data and keys
606
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
607
+ provided, the tuples will just be (node, neighbor, data), but
608
+ multiple tuples with the same node and neighbor will be
609
+ generated when multiple edges between two nodes exist.
610
+
611
+ Parameters
612
+ ----------
613
+ nbunch : single node, container, or all nodes (default= all nodes)
614
+ The view will only report edges from these nodes.
615
+ data : string or bool, optional (default=False)
616
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
617
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
618
+ If False, return 2-tuple (u, v).
619
+ keys : bool, optional (default=False)
620
+ If True, return edge keys with each edge, creating (u, v, k,
621
+ d) tuples when data is also requested (the default) and (u,
622
+ v, k) tuples when data is not requested.
623
+ default : value, optional (default=None)
624
+ Value used for edges that don't have the requested attribute.
625
+ Only relevant if data is not True or False.
626
+
627
+ Returns
628
+ -------
629
+ edges : OutMultiEdgeView
630
+ A view of edge attributes, usually it iterates over (u, v)
631
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
632
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
633
+
634
+ Notes
635
+ -----
636
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
637
+ For directed graphs this returns the out-edges.
638
+
639
+ Examples
640
+ --------
641
+ >>> G = nx.MultiDiGraph()
642
+ >>> nx.add_path(G, [0, 1, 2])
643
+ >>> key = G.add_edge(2, 3, weight=5)
644
+ >>> key2 = G.add_edge(1, 2) # second edge between these nodes
645
+ >>> [e for e in G.edges()]
646
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
647
+ >>> list(G.edges(data=True)) # default data is {} (empty dict)
648
+ [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
649
+ >>> list(G.edges(data="weight", default=1))
650
+ [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
651
+ >>> list(G.edges(keys=True)) # default keys are integers
652
+ [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
653
+ >>> list(G.edges(data=True, keys=True))
654
+ [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
655
+ >>> list(G.edges(data="weight", default=1, keys=True))
656
+ [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
657
+ >>> list(G.edges([0, 2]))
658
+ [(0, 1), (2, 3)]
659
+ >>> list(G.edges(0))
660
+ [(0, 1)]
661
+ >>> list(G.edges(1))
662
+ [(1, 2), (1, 2)]
663
+
664
+ See Also
665
+ --------
666
+ in_edges, out_edges
667
+ """
668
+ return OutMultiEdgeView(self)
669
+
670
+ # alias out_edges to edges
671
+ @cached_property
672
+ def out_edges(self):
673
+ return OutMultiEdgeView(self)
674
+
675
+ out_edges.__doc__ = edges.__doc__
676
+
677
+ @cached_property
678
+ def in_edges(self):
679
+ """A view of the in edges of the graph as G.in_edges or G.in_edges().
680
+
681
+ in_edges(self, nbunch=None, data=False, keys=False, default=None)
682
+
683
+ Parameters
684
+ ----------
685
+ nbunch : single node, container, or all nodes (default= all nodes)
686
+ The view will only report edges incident to these nodes.
687
+ data : string or bool, optional (default=False)
688
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
689
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
690
+ If False, return 2-tuple (u, v).
691
+ keys : bool, optional (default=False)
692
+ If True, return edge keys with each edge, creating 3-tuples
693
+ (u, v, k) or with data, 4-tuples (u, v, k, d).
694
+ default : value, optional (default=None)
695
+ Value used for edges that don't have the requested attribute.
696
+ Only relevant if data is not True or False.
697
+
698
+ Returns
699
+ -------
700
+ in_edges : InMultiEdgeView or InMultiEdgeDataView
701
+ A view of edge attributes, usually it iterates over (u, v)
702
+ or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
703
+ used for attribute lookup as `edges[u, v, k]['foo']`.
704
+
705
+ See Also
706
+ --------
707
+ edges
708
+ """
709
+ return InMultiEdgeView(self)
710
+
711
+ @cached_property
712
+ def degree(self):
713
+ """A DegreeView for the Graph as G.degree or G.degree().
714
+
715
+ The node degree is the number of edges adjacent to the node.
716
+ The weighted node degree is the sum of the edge weights for
717
+ edges incident to that node.
718
+
719
+ This object provides an iterator for (node, degree) as well as
720
+ lookup for the degree for a single node.
721
+
722
+ Parameters
723
+ ----------
724
+ nbunch : single node, container, or all nodes (default= all nodes)
725
+ The view will only report edges incident to these nodes.
726
+
727
+ weight : string or None, optional (default=None)
728
+ The name of an edge attribute that holds the numerical value used
729
+ as a weight. If None, then each edge has weight 1.
730
+ The degree is the sum of the edge weights adjacent to the node.
731
+
732
+ Returns
733
+ -------
734
+ DiMultiDegreeView or int
735
+ If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
736
+ mapping nodes to their degree.
737
+ If a single node is requested, returns the degree of the node as an integer.
738
+
739
+ See Also
740
+ --------
741
+ out_degree, in_degree
742
+
743
+ Examples
744
+ --------
745
+ >>> G = nx.MultiDiGraph()
746
+ >>> nx.add_path(G, [0, 1, 2, 3])
747
+ >>> G.degree(0) # node 0 with degree 1
748
+ 1
749
+ >>> list(G.degree([0, 1, 2]))
750
+ [(0, 1), (1, 2), (2, 2)]
751
+ >>> G.add_edge(0, 1) # parallel edge
752
+ 1
753
+ >>> list(G.degree([0, 1, 2])) # parallel edges are counted
754
+ [(0, 2), (1, 3), (2, 2)]
755
+
756
+ """
757
+ return DiMultiDegreeView(self)
758
+
759
+ @cached_property
760
+ def in_degree(self):
761
+ """A DegreeView for (node, in_degree) or in_degree for single node.
762
+
763
+ The node in-degree is the number of edges pointing into the node.
764
+ The weighted node degree is the sum of the edge weights for
765
+ edges incident to that node.
766
+
767
+ This object provides an iterator for (node, degree) as well as
768
+ lookup for the degree for a single node.
769
+
770
+ Parameters
771
+ ----------
772
+ nbunch : single node, container, or all nodes (default= all nodes)
773
+ The view will only report edges incident to these nodes.
774
+
775
+ weight : string or None, optional (default=None)
776
+ The edge attribute that holds the numerical value used
777
+ as a weight. If None, then each edge has weight 1.
778
+ The degree is the sum of the edge weights adjacent to the node.
779
+
780
+ Returns
781
+ -------
782
+ If a single node is requested
783
+ deg : int
784
+ Degree of the node
785
+
786
+ OR if multiple nodes are requested
787
+ nd_iter : iterator
788
+ The iterator returns two-tuples of (node, in-degree).
789
+
790
+ See Also
791
+ --------
792
+ degree, out_degree
793
+
794
+ Examples
795
+ --------
796
+ >>> G = nx.MultiDiGraph()
797
+ >>> nx.add_path(G, [0, 1, 2, 3])
798
+ >>> G.in_degree(0) # node 0 with degree 0
799
+ 0
800
+ >>> list(G.in_degree([0, 1, 2]))
801
+ [(0, 0), (1, 1), (2, 1)]
802
+ >>> G.add_edge(0, 1) # parallel edge
803
+ 1
804
+ >>> list(G.in_degree([0, 1, 2])) # parallel edges counted
805
+ [(0, 0), (1, 2), (2, 1)]
806
+
807
+ """
808
+ return InMultiDegreeView(self)
809
+
810
+ @cached_property
811
+ def out_degree(self):
812
+ """Returns an iterator for (node, out-degree) or out-degree for single node.
813
+
814
+ out_degree(self, nbunch=None, weight=None)
815
+
816
+ The node out-degree is the number of edges pointing out of the node.
817
+ This function returns the out-degree for a single node or an iterator
818
+ for a bunch of nodes or if nothing is passed as argument.
819
+
820
+ Parameters
821
+ ----------
822
+ nbunch : single node, container, or all nodes (default= all nodes)
823
+ The view will only report edges incident to these nodes.
824
+
825
+ weight : string or None, optional (default=None)
826
+ The edge attribute that holds the numerical value used
827
+ as a weight. If None, then each edge has weight 1.
828
+ The degree is the sum of the edge weights.
829
+
830
+ Returns
831
+ -------
832
+ If a single node is requested
833
+ deg : int
834
+ Degree of the node
835
+
836
+ OR if multiple nodes are requested
837
+ nd_iter : iterator
838
+ The iterator returns two-tuples of (node, out-degree).
839
+
840
+ See Also
841
+ --------
842
+ degree, in_degree
843
+
844
+ Examples
845
+ --------
846
+ >>> G = nx.MultiDiGraph()
847
+ >>> nx.add_path(G, [0, 1, 2, 3])
848
+ >>> G.out_degree(0) # node 0 with degree 1
849
+ 1
850
+ >>> list(G.out_degree([0, 1, 2]))
851
+ [(0, 1), (1, 1), (2, 1)]
852
+ >>> G.add_edge(0, 1) # parallel edge
853
+ 1
854
+ >>> list(G.out_degree([0, 1, 2])) # counts parallel edges
855
+ [(0, 2), (1, 1), (2, 1)]
856
+
857
+ """
858
+ return OutMultiDegreeView(self)
859
+
860
+ def is_multigraph(self):
861
+ """Returns True if graph is a multigraph, False otherwise."""
862
+ return True
863
+
864
+ def is_directed(self):
865
+ """Returns True if graph is directed, False otherwise."""
866
+ return True
867
+
868
+ def to_undirected(self, reciprocal=False, as_view=False):
869
+ """Returns an undirected representation of the digraph.
870
+
871
+ Parameters
872
+ ----------
873
+ reciprocal : bool (optional)
874
+ If True only keep edges that appear in both directions
875
+ in the original digraph.
876
+ as_view : bool (optional, default=False)
877
+ If True return an undirected view of the original directed graph.
878
+
879
+ Returns
880
+ -------
881
+ G : MultiGraph
882
+ An undirected graph with the same name and nodes and
883
+ with edge (u, v, data) if either (u, v, data) or (v, u, data)
884
+ is in the digraph. If both edges exist in digraph and
885
+ their edge data is different, only one edge is created
886
+ with an arbitrary choice of which edge data to use.
887
+ You must check and correct for this manually if desired.
888
+
889
+ See Also
890
+ --------
891
+ MultiGraph, copy, add_edge, add_edges_from
892
+
893
+ Notes
894
+ -----
895
+ This returns a "deepcopy" of the edge, node, and
896
+ graph attributes which attempts to completely copy
897
+ all of the data and references.
898
+
899
+ This is in contrast to the similar D=MultiDiGraph(G) which
900
+ returns a shallow copy of the data.
901
+
902
+ See the Python copy module for more information on shallow
903
+ and deep copies, https://docs.python.org/3/library/copy.html.
904
+
905
+ Warning: If you have subclassed MultiDiGraph to use dict-like
906
+ objects in the data structure, those changes do not transfer
907
+ to the MultiGraph created by this method.
908
+
909
+ Examples
910
+ --------
911
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
912
+ >>> H = G.to_directed()
913
+ >>> list(H.edges)
914
+ [(0, 1), (1, 0)]
915
+ >>> G2 = H.to_undirected()
916
+ >>> list(G2.edges)
917
+ [(0, 1)]
918
+ """
919
+ graph_class = self.to_undirected_class()
920
+ if as_view is True:
921
+ return nx.graphviews.generic_graph_view(self, graph_class)
922
+ # deepcopy when not a view
923
+ G = graph_class()
924
+ G.graph.update(deepcopy(self.graph))
925
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
926
+ if reciprocal is True:
927
+ G.add_edges_from(
928
+ (u, v, key, deepcopy(data))
929
+ for u, nbrs in self._adj.items()
930
+ for v, keydict in nbrs.items()
931
+ for key, data in keydict.items()
932
+ if v in self._pred[u] and key in self._pred[u][v]
933
+ )
934
+ else:
935
+ G.add_edges_from(
936
+ (u, v, key, deepcopy(data))
937
+ for u, nbrs in self._adj.items()
938
+ for v, keydict in nbrs.items()
939
+ for key, data in keydict.items()
940
+ )
941
+ return G
942
+
943
+ def reverse(self, copy=True):
944
+ """Returns the reverse of the graph.
945
+
946
+ The reverse is a graph with the same nodes and edges
947
+ but with the directions of the edges reversed.
948
+
949
+ Parameters
950
+ ----------
951
+ copy : bool optional (default=True)
952
+ If True, return a new DiGraph holding the reversed edges.
953
+ If False, the reverse graph is created using a view of
954
+ the original graph.
955
+ """
956
+ if copy:
957
+ H = self.__class__()
958
+ H.graph.update(deepcopy(self.graph))
959
+ H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
960
+ H.add_edges_from(
961
+ (v, u, k, deepcopy(d))
962
+ for u, v, k, d in self.edges(keys=True, data=True)
963
+ )
964
+ return H
965
+ return nx.reverse_view(self)
env-llmeval/lib/python3.10/site-packages/networkx/classes/multigraph.py ADDED
@@ -0,0 +1,1282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiGraph."""
2
+ from copy import deepcopy
3
+ from functools import cached_property
4
+
5
+ import networkx as nx
6
+ from networkx import NetworkXError, convert
7
+ from networkx.classes.coreviews import MultiAdjacencyView
8
+ from networkx.classes.graph import Graph
9
+ from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
10
+
11
+ __all__ = ["MultiGraph"]
12
+
13
+
14
+ class MultiGraph(Graph):
15
+ """
16
+ An undirected graph class that can store multiedges.
17
+
18
+ Multiedges are multiple edges between two nodes. Each edge
19
+ can hold optional data or attributes.
20
+
21
+ A MultiGraph holds undirected edges. Self loops are allowed.
22
+
23
+ Nodes can be arbitrary (hashable) Python objects with optional
24
+ key/value attributes. By convention `None` is not used as a node.
25
+
26
+ Edges are represented as links between nodes with optional
27
+ key/value attributes, in a MultiGraph each edge has a key to
28
+ distinguish between multiple edges that have the same source and
29
+ destination nodes.
30
+
31
+ Parameters
32
+ ----------
33
+ incoming_graph_data : input graph (optional, default: None)
34
+ Data to initialize graph. If None (default) an empty
35
+ graph is created. The data can be any format that is supported
36
+ by the to_networkx_graph() function, currently including edge list,
37
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
38
+ SciPy sparse array, or PyGraphviz graph.
39
+
40
+ multigraph_input : bool or None (default None)
41
+ Note: Only used when `incoming_graph_data` is a dict.
42
+ If True, `incoming_graph_data` is assumed to be a
43
+ dict-of-dict-of-dict-of-dict structure keyed by
44
+ node to neighbor to edge keys to edge data for multi-edges.
45
+ A NetworkXError is raised if this is not the case.
46
+ If False, :func:`to_networkx_graph` is used to try to determine
47
+ the dict's graph data structure as either a dict-of-dict-of-dict
48
+ keyed by node to neighbor to edge data, or a dict-of-iterable
49
+ keyed by node to neighbors.
50
+ If None, the treatment for True is tried, but if it fails,
51
+ the treatment for False is tried.
52
+
53
+ attr : keyword arguments, optional (default= no attributes)
54
+ Attributes to add to graph as key=value pairs.
55
+
56
+ See Also
57
+ --------
58
+ Graph
59
+ DiGraph
60
+ MultiDiGraph
61
+
62
+ Examples
63
+ --------
64
+ Create an empty graph structure (a "null graph") with no nodes and
65
+ no edges.
66
+
67
+ >>> G = nx.MultiGraph()
68
+
69
+ G can be grown in several ways.
70
+
71
+ **Nodes:**
72
+
73
+ Add one node at a time:
74
+
75
+ >>> G.add_node(1)
76
+
77
+ Add the nodes from any container (a list, dict, set or
78
+ even the lines from a file or the nodes from another graph).
79
+
80
+ >>> G.add_nodes_from([2, 3])
81
+ >>> G.add_nodes_from(range(100, 110))
82
+ >>> H = nx.path_graph(10)
83
+ >>> G.add_nodes_from(H)
84
+
85
+ In addition to strings and integers any hashable Python object
86
+ (except None) can represent a node, e.g. a customized node object,
87
+ or even another Graph.
88
+
89
+ >>> G.add_node(H)
90
+
91
+ **Edges:**
92
+
93
+ G can also be grown by adding edges.
94
+
95
+ Add one edge,
96
+
97
+ >>> key = G.add_edge(1, 2)
98
+
99
+ a list of edges,
100
+
101
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
102
+
103
+ or a collection of edges,
104
+
105
+ >>> keys = G.add_edges_from(H.edges)
106
+
107
+ If some edges connect nodes not yet in the graph, the nodes
108
+ are added automatically. If an edge already exists, an additional
109
+ edge is created and stored using a key to identify the edge.
110
+ By default the key is the lowest unused integer.
111
+
112
+ >>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
113
+ >>> G[4]
114
+ AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
115
+
116
+ **Attributes:**
117
+
118
+ Each graph, node, and edge can hold key/value attribute pairs
119
+ in an associated attribute dictionary (the keys must be hashable).
120
+ By default these are empty, but can be added or changed using
121
+ add_edge, add_node or direct manipulation of the attribute
122
+ dictionaries named graph, node and edge respectively.
123
+
124
+ >>> G = nx.MultiGraph(day="Friday")
125
+ >>> G.graph
126
+ {'day': 'Friday'}
127
+
128
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
129
+
130
+ >>> G.add_node(1, time="5pm")
131
+ >>> G.add_nodes_from([3], time="2pm")
132
+ >>> G.nodes[1]
133
+ {'time': '5pm'}
134
+ >>> G.nodes[1]["room"] = 714
135
+ >>> del G.nodes[1]["room"] # remove attribute
136
+ >>> list(G.nodes(data=True))
137
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
138
+
139
+ Add edge attributes using add_edge(), add_edges_from(), subscript
140
+ notation, or G.edges.
141
+
142
+ >>> key = G.add_edge(1, 2, weight=4.7)
143
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
144
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
145
+ >>> G[1][2][0]["weight"] = 4.7
146
+ >>> G.edges[1, 2, 0]["weight"] = 4
147
+
148
+ Warning: we protect the graph data structure by making `G.edges[1,
149
+ 2, 0]` a read-only dict-like structure. However, you can assign to
150
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
151
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
152
+
153
+ **Shortcuts:**
154
+
155
+ Many common graph features allow python syntax to speed reporting.
156
+
157
+ >>> 1 in G # check if node in graph
158
+ True
159
+ >>> [n for n in G if n < 3] # iterate through nodes
160
+ [1, 2]
161
+ >>> len(G) # number of nodes in graph
162
+ 5
163
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
164
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
165
+
166
+ Often the best way to traverse all edges of a graph is via the neighbors.
167
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
168
+
169
+ >>> for n, nbrsdict in G.adjacency():
170
+ ... for nbr, keydict in nbrsdict.items():
171
+ ... for key, eattr in keydict.items():
172
+ ... if "weight" in eattr:
173
+ ... # Do something useful with the edges
174
+ ... pass
175
+
176
+ But the edges() method is often more convenient:
177
+
178
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
179
+ ... if weight is not None:
180
+ ... # Do something useful with the edges
181
+ ... pass
182
+
183
+ **Reporting:**
184
+
185
+ Simple graph information is obtained using methods and object-attributes.
186
+ Reporting usually provides views instead of containers to reduce memory
187
+ usage. The views update as the graph is updated similarly to dict-views.
188
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
189
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
190
+ (e.g. `nodes.items()`, `nodes.data('color')`,
191
+ `nodes.data('color', default='blue')` and similarly for `edges`)
192
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
193
+
194
+ For details on these and other miscellaneous methods, see below.
195
+
196
+ **Subclasses (Advanced):**
197
+
198
+ The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
199
+ The outer dict (node_dict) holds adjacency information keyed by node.
200
+ The next dict (adjlist_dict) represents the adjacency information
201
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
202
+ each edge_attr dict keyed by edge key. The inner dict
203
+ (edge_attr_dict) represents the edge data and holds edge attribute
204
+ values keyed by attribute names.
205
+
206
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
207
+ structure can be replaced by a user defined dict-like object.
208
+ In general, the dict-like features should be maintained but
209
+ extra features can be added. To replace one of the dicts create
210
+ a new graph class by changing the class(!) variable holding the
211
+ factory for that dict-like structure. The variable names are
212
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
213
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
214
+ and graph_attr_dict_factory.
215
+
216
+ node_dict_factory : function, (default: dict)
217
+ Factory function to be used to create the dict containing node
218
+ attributes, keyed by node id.
219
+ It should require no arguments and return a dict-like object
220
+
221
+ node_attr_dict_factory: function, (default: dict)
222
+ Factory function to be used to create the node attribute
223
+ dict which holds attribute values keyed by attribute name.
224
+ It should require no arguments and return a dict-like object
225
+
226
+ adjlist_outer_dict_factory : function, (default: dict)
227
+ Factory function to be used to create the outer-most dict
228
+ in the data structure that holds adjacency info keyed by node.
229
+ It should require no arguments and return a dict-like object.
230
+
231
+ adjlist_inner_dict_factory : function, (default: dict)
232
+ Factory function to be used to create the adjacency list
233
+ dict which holds multiedge key dicts keyed by neighbor.
234
+ It should require no arguments and return a dict-like object.
235
+
236
+ edge_key_dict_factory : function, (default: dict)
237
+ Factory function to be used to create the edge key dict
238
+ which holds edge data keyed by edge key.
239
+ It should require no arguments and return a dict-like object.
240
+
241
+ edge_attr_dict_factory : function, (default: dict)
242
+ Factory function to be used to create the edge attribute
243
+ dict which holds attribute values keyed by attribute name.
244
+ It should require no arguments and return a dict-like object.
245
+
246
+ graph_attr_dict_factory : function, (default: dict)
247
+ Factory function to be used to create the graph attribute
248
+ dict which holds attribute values keyed by attribute name.
249
+ It should require no arguments and return a dict-like object.
250
+
251
+ Typically, if your extension doesn't impact the data structure all
252
+ methods will inherited without issue except: `to_directed/to_undirected`.
253
+ By default these methods create a DiGraph/Graph class and you probably
254
+ want them to create your extension of a DiGraph/Graph. To facilitate
255
+ this we define two class variables that you can set in your subclass.
256
+
257
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
258
+ Class to create a new graph structure in the `to_directed` method.
259
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
260
+
261
+ to_undirected_class : callable, (default: Graph or MultiGraph)
262
+ Class to create a new graph structure in the `to_undirected` method.
263
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
264
+
265
+ **Subclassing Example**
266
+
267
+ Create a low memory graph class that effectively disallows edge
268
+ attributes by using a single attribute dict for all edges.
269
+ This reduces the memory used, but you lose edge attributes.
270
+
271
+ >>> class ThinGraph(nx.Graph):
272
+ ... all_edge_dict = {"weight": 1}
273
+ ...
274
+ ... def single_edge_dict(self):
275
+ ... return self.all_edge_dict
276
+ ...
277
+ ... edge_attr_dict_factory = single_edge_dict
278
+ >>> G = ThinGraph()
279
+ >>> G.add_edge(2, 1)
280
+ >>> G[2][1]
281
+ {'weight': 1}
282
+ >>> G.add_edge(2, 2)
283
+ >>> G[2][1] is G[2][2]
284
+ True
285
+ """
286
+
287
+ # node_dict_factory = dict # already assigned in Graph
288
+ # adjlist_outer_dict_factory = dict
289
+ # adjlist_inner_dict_factory = dict
290
+ edge_key_dict_factory = dict
291
+ # edge_attr_dict_factory = dict
292
+
293
+ def to_directed_class(self):
294
+ """Returns the class to use for empty directed copies.
295
+
296
+ If you subclass the base classes, use this to designate
297
+ what directed class to use for `to_directed()` copies.
298
+ """
299
+ return nx.MultiDiGraph
300
+
301
+ def to_undirected_class(self):
302
+ """Returns the class to use for empty undirected copies.
303
+
304
+ If you subclass the base classes, use this to designate
305
+ what directed class to use for `to_directed()` copies.
306
+ """
307
+ return MultiGraph
308
+
309
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
310
+ """Initialize a graph with edges, name, or graph attributes.
311
+
312
+ Parameters
313
+ ----------
314
+ incoming_graph_data : input graph
315
+ Data to initialize graph. If incoming_graph_data=None (default)
316
+ an empty graph is created. The data can be an edge list, or any
317
+ NetworkX graph object. If the corresponding optional Python
318
+ packages are installed the data can also be a 2D NumPy array, a
319
+ SciPy sparse array, or a PyGraphviz graph.
320
+
321
+ multigraph_input : bool or None (default None)
322
+ Note: Only used when `incoming_graph_data` is a dict.
323
+ If True, `incoming_graph_data` is assumed to be a
324
+ dict-of-dict-of-dict-of-dict structure keyed by
325
+ node to neighbor to edge keys to edge data for multi-edges.
326
+ A NetworkXError is raised if this is not the case.
327
+ If False, :func:`to_networkx_graph` is used to try to determine
328
+ the dict's graph data structure as either a dict-of-dict-of-dict
329
+ keyed by node to neighbor to edge data, or a dict-of-iterable
330
+ keyed by node to neighbors.
331
+ If None, the treatment for True is tried, but if it fails,
332
+ the treatment for False is tried.
333
+
334
+ attr : keyword arguments, optional (default= no attributes)
335
+ Attributes to add to graph as key=value pairs.
336
+
337
+ See Also
338
+ --------
339
+ convert
340
+
341
+ Examples
342
+ --------
343
+ >>> G = nx.MultiGraph()
344
+ >>> G = nx.MultiGraph(name="my graph")
345
+ >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
346
+ >>> G = nx.MultiGraph(e)
347
+
348
+ Arbitrary graph attribute pairs (key=value) may be assigned
349
+
350
+ >>> G = nx.MultiGraph(e, day="Friday")
351
+ >>> G.graph
352
+ {'day': 'Friday'}
353
+
354
+ """
355
+ # multigraph_input can be None/True/False. So check "is not False"
356
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
357
+ Graph.__init__(self)
358
+ try:
359
+ convert.from_dict_of_dicts(
360
+ incoming_graph_data, create_using=self, multigraph_input=True
361
+ )
362
+ self.graph.update(attr)
363
+ except Exception as err:
364
+ if multigraph_input is True:
365
+ raise nx.NetworkXError(
366
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
367
+ )
368
+ Graph.__init__(self, incoming_graph_data, **attr)
369
+ else:
370
+ Graph.__init__(self, incoming_graph_data, **attr)
371
+
372
+ @cached_property
373
+ def adj(self):
374
+ """Graph adjacency object holding the neighbors of each node.
375
+
376
+ This object is a read-only dict-like structure with node keys
377
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
378
+ to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
379
+ the color of the edge `(3, 2, 0)` to `"blue"`.
380
+
381
+ Iterating over G.adj behaves like a dict. Useful idioms include
382
+ `for nbr, edgesdict in G.adj[n].items():`.
383
+
384
+ The neighbor information is also provided by subscripting the graph.
385
+
386
+ Examples
387
+ --------
388
+ >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
389
+ >>> G = nx.MultiGraph(e)
390
+ >>> G.edges[1, 2, 0]["weight"] = 3
391
+ >>> result = set()
392
+ >>> for edgekey, data in G[1][2].items():
393
+ ... result.add(data.get("weight", 1))
394
+ >>> result
395
+ {1, 3}
396
+
397
+ For directed graphs, `G.adj` holds outgoing (successor) info.
398
+ """
399
+ return MultiAdjacencyView(self._adj)
400
+
401
+ def new_edge_key(self, u, v):
402
+ """Returns an unused key for edges between nodes `u` and `v`.
403
+
404
+ The nodes `u` and `v` do not need to be already in the graph.
405
+
406
+ Notes
407
+ -----
408
+ In the standard MultiGraph class the new key is the number of existing
409
+ edges between `u` and `v` (increased if necessary to ensure unused).
410
+ The first edge will have key 0, then 1, etc. If an edge is removed
411
+ further new_edge_keys may not be in this order.
412
+
413
+ Parameters
414
+ ----------
415
+ u, v : nodes
416
+
417
+ Returns
418
+ -------
419
+ key : int
420
+ """
421
+ try:
422
+ keydict = self._adj[u][v]
423
+ except KeyError:
424
+ return 0
425
+ key = len(keydict)
426
+ while key in keydict:
427
+ key += 1
428
+ return key
429
+
430
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
431
+ """Add an edge between u and v.
432
+
433
+ The nodes u and v will be automatically added if they are
434
+ not already in the graph.
435
+
436
+ Edge attributes can be specified with keywords or by directly
437
+ accessing the edge's attribute dictionary. See examples below.
438
+
439
+ Parameters
440
+ ----------
441
+ u_for_edge, v_for_edge : nodes
442
+ Nodes can be, for example, strings or numbers.
443
+ Nodes must be hashable (and not None) Python objects.
444
+ key : hashable identifier, optional (default=lowest unused integer)
445
+ Used to distinguish multiedges between a pair of nodes.
446
+ attr : keyword arguments, optional
447
+ Edge data (or labels or objects) can be assigned using
448
+ keyword arguments.
449
+
450
+ Returns
451
+ -------
452
+ The edge key assigned to the edge.
453
+
454
+ See Also
455
+ --------
456
+ add_edges_from : add a collection of edges
457
+
458
+ Notes
459
+ -----
460
+ To replace/update edge data, use the optional key argument
461
+ to identify a unique edge. Otherwise a new edge will be created.
462
+
463
+ NetworkX algorithms designed for weighted graphs cannot use
464
+ multigraphs directly because it is not clear how to handle
465
+ multiedge weights. Convert to Graph using edge attribute
466
+ 'weight' to enable weighted graph algorithms.
467
+
468
+ Default keys are generated using the method `new_edge_key()`.
469
+ This method can be overridden by subclassing the base class and
470
+ providing a custom `new_edge_key()` method.
471
+
472
+ Examples
473
+ --------
474
+ The following each add an additional edge e=(1, 2) to graph G:
475
+
476
+ >>> G = nx.MultiGraph()
477
+ >>> e = (1, 2)
478
+ >>> ekey = G.add_edge(1, 2) # explicit two-node form
479
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
480
+ 1
481
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
482
+ [2]
483
+
484
+ Associate data to edges using keywords:
485
+
486
+ >>> ekey = G.add_edge(1, 2, weight=3)
487
+ >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
488
+ >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
489
+
490
+ For non-string attribute keys, use subscript notation.
491
+
492
+ >>> ekey = G.add_edge(1, 2)
493
+ >>> G[1][2][0].update({0: 5})
494
+ >>> G.edges[1, 2, 0].update({0: 5})
495
+ """
496
+ u, v = u_for_edge, v_for_edge
497
+ # add nodes
498
+ if u not in self._adj:
499
+ if u is None:
500
+ raise ValueError("None cannot be a node")
501
+ self._adj[u] = self.adjlist_inner_dict_factory()
502
+ self._node[u] = self.node_attr_dict_factory()
503
+ if v not in self._adj:
504
+ if v is None:
505
+ raise ValueError("None cannot be a node")
506
+ self._adj[v] = self.adjlist_inner_dict_factory()
507
+ self._node[v] = self.node_attr_dict_factory()
508
+ if key is None:
509
+ key = self.new_edge_key(u, v)
510
+ if v in self._adj[u]:
511
+ keydict = self._adj[u][v]
512
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
513
+ datadict.update(attr)
514
+ keydict[key] = datadict
515
+ else:
516
+ # selfloops work this way without special treatment
517
+ datadict = self.edge_attr_dict_factory()
518
+ datadict.update(attr)
519
+ keydict = self.edge_key_dict_factory()
520
+ keydict[key] = datadict
521
+ self._adj[u][v] = keydict
522
+ self._adj[v][u] = keydict
523
+ nx._clear_cache(self)
524
+ return key
525
+
526
+ def add_edges_from(self, ebunch_to_add, **attr):
527
+ """Add all the edges in ebunch_to_add.
528
+
529
+ Parameters
530
+ ----------
531
+ ebunch_to_add : container of edges
532
+ Each edge given in the container will be added to the
533
+ graph. The edges can be:
534
+
535
+ - 2-tuples (u, v) or
536
+ - 3-tuples (u, v, d) for an edge data dict d, or
537
+ - 3-tuples (u, v, k) for not iterable key k, or
538
+ - 4-tuples (u, v, k, d) for an edge with data and key k
539
+
540
+ attr : keyword arguments, optional
541
+ Edge data (or labels or objects) can be assigned using
542
+ keyword arguments.
543
+
544
+ Returns
545
+ -------
546
+ A list of edge keys assigned to the edges in `ebunch`.
547
+
548
+ See Also
549
+ --------
550
+ add_edge : add a single edge
551
+ add_weighted_edges_from : convenient way to add weighted edges
552
+
553
+ Notes
554
+ -----
555
+ Adding the same edge twice has no effect but any edge data
556
+ will be updated when each duplicate edge is added.
557
+
558
+ Edge attributes specified in an ebunch take precedence over
559
+ attributes specified via keyword arguments.
560
+
561
+ Default keys are generated using the method ``new_edge_key()``.
562
+ This method can be overridden by subclassing the base class and
563
+ providing a custom ``new_edge_key()`` method.
564
+
565
+ When adding edges from an iterator over the graph you are changing,
566
+ a `RuntimeError` can be raised with message:
567
+ `RuntimeError: dictionary changed size during iteration`. This
568
+ happens when the graph's underlying dictionary is modified during
569
+ iteration. To avoid this error, evaluate the iterator into a separate
570
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
571
+ object to `G.add_edges_from`.
572
+
573
+ Examples
574
+ --------
575
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
576
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
577
+ >>> e = zip(range(0, 3), range(1, 4))
578
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
579
+
580
+ Associate data to edges
581
+
582
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
583
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
584
+
585
+ Evaluate an iterator over a graph if using it to modify the same graph
586
+
587
+ >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
588
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
589
+ >>> # wrong way - will raise RuntimeError
590
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
591
+ >>> # right way - note that there will be no self-edge for node 5
592
+ >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
593
+ """
594
+ keylist = []
595
+ for e in ebunch_to_add:
596
+ ne = len(e)
597
+ if ne == 4:
598
+ u, v, key, dd = e
599
+ elif ne == 3:
600
+ u, v, dd = e
601
+ key = None
602
+ elif ne == 2:
603
+ u, v = e
604
+ dd = {}
605
+ key = None
606
+ else:
607
+ msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
608
+ raise NetworkXError(msg)
609
+ ddd = {}
610
+ ddd.update(attr)
611
+ try:
612
+ ddd.update(dd)
613
+ except (TypeError, ValueError):
614
+ if ne != 3:
615
+ raise
616
+ key = dd # ne == 3 with 3rd value not dict, must be a key
617
+ key = self.add_edge(u, v, key)
618
+ self[u][v][key].update(ddd)
619
+ keylist.append(key)
620
+ nx._clear_cache(self)
621
+ return keylist
622
+
623
+ def remove_edge(self, u, v, key=None):
624
+ """Remove an edge between u and v.
625
+
626
+ Parameters
627
+ ----------
628
+ u, v : nodes
629
+ Remove an edge between nodes u and v.
630
+ key : hashable identifier, optional (default=None)
631
+ Used to distinguish multiple edges between a pair of nodes.
632
+ If None, remove a single edge between u and v. If there are
633
+ multiple edges, removes the last edge added in terms of
634
+ insertion order.
635
+
636
+ Raises
637
+ ------
638
+ NetworkXError
639
+ If there is not an edge between u and v, or
640
+ if there is no edge with the specified key.
641
+
642
+ See Also
643
+ --------
644
+ remove_edges_from : remove a collection of edges
645
+
646
+ Examples
647
+ --------
648
+ >>> G = nx.MultiGraph()
649
+ >>> nx.add_path(G, [0, 1, 2, 3])
650
+ >>> G.remove_edge(0, 1)
651
+ >>> e = (1, 2)
652
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
653
+
654
+ For multiple edges
655
+
656
+ >>> G = nx.MultiGraph() # or MultiDiGraph, etc
657
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
658
+ [0, 1, 2]
659
+
660
+ When ``key=None`` (the default), edges are removed in the opposite
661
+ order that they were added:
662
+
663
+ >>> G.remove_edge(1, 2)
664
+ >>> G.edges(keys=True)
665
+ MultiEdgeView([(1, 2, 0), (1, 2, 1)])
666
+ >>> G.remove_edge(2, 1) # edges are not directed
667
+ >>> G.edges(keys=True)
668
+ MultiEdgeView([(1, 2, 0)])
669
+
670
+ For edges with keys
671
+
672
+ >>> G = nx.MultiGraph()
673
+ >>> G.add_edge(1, 2, key="first")
674
+ 'first'
675
+ >>> G.add_edge(1, 2, key="second")
676
+ 'second'
677
+ >>> G.remove_edge(1, 2, key="first")
678
+ >>> G.edges(keys=True)
679
+ MultiEdgeView([(1, 2, 'second')])
680
+
681
+ """
682
+ try:
683
+ d = self._adj[u][v]
684
+ except KeyError as err:
685
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
686
+ # remove the edge with specified data
687
+ if key is None:
688
+ d.popitem()
689
+ else:
690
+ try:
691
+ del d[key]
692
+ except KeyError as err:
693
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
694
+ raise NetworkXError(msg) from err
695
+ if len(d) == 0:
696
+ # remove the key entries if last edge
697
+ del self._adj[u][v]
698
+ if u != v: # check for selfloop
699
+ del self._adj[v][u]
700
+ nx._clear_cache(self)
701
+
702
+ def remove_edges_from(self, ebunch):
703
+ """Remove all edges specified in ebunch.
704
+
705
+ Parameters
706
+ ----------
707
+ ebunch: list or container of edge tuples
708
+ Each edge given in the list or container will be removed
709
+ from the graph. The edges can be:
710
+
711
+ - 2-tuples (u, v) A single edge between u and v is removed.
712
+ - 3-tuples (u, v, key) The edge identified by key is removed.
713
+ - 4-tuples (u, v, key, data) where data is ignored.
714
+
715
+ See Also
716
+ --------
717
+ remove_edge : remove a single edge
718
+
719
+ Notes
720
+ -----
721
+ Will fail silently if an edge in ebunch is not in the graph.
722
+
723
+ Examples
724
+ --------
725
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
726
+ >>> ebunch = [(1, 2), (2, 3)]
727
+ >>> G.remove_edges_from(ebunch)
728
+
729
+ Removing multiple copies of edges
730
+
731
+ >>> G = nx.MultiGraph()
732
+ >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
733
+ >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
734
+ >>> list(G.edges())
735
+ [(1, 2)]
736
+ >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
737
+ >>> list(G.edges) # now empty graph
738
+ []
739
+
740
+ When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
741
+ u and v in the graph, the most recent edge (in terms of insertion
742
+ order) is removed.
743
+
744
+ >>> G = nx.MultiGraph()
745
+ >>> for key in ("x", "y", "a"):
746
+ ... k = G.add_edge(0, 1, key=key)
747
+ >>> G.edges(keys=True)
748
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
749
+ >>> G.remove_edges_from([(0, 1)])
750
+ >>> G.edges(keys=True)
751
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
752
+
753
+ """
754
+ for e in ebunch:
755
+ try:
756
+ self.remove_edge(*e[:3])
757
+ except NetworkXError:
758
+ pass
759
+ nx._clear_cache(self)
760
+
761
+ def has_edge(self, u, v, key=None):
762
+ """Returns True if the graph has an edge between nodes u and v.
763
+
764
+ This is the same as `v in G[u] or key in G[u][v]`
765
+ without KeyError exceptions.
766
+
767
+ Parameters
768
+ ----------
769
+ u, v : nodes
770
+ Nodes can be, for example, strings or numbers.
771
+
772
+ key : hashable identifier, optional (default=None)
773
+ If specified return True only if the edge with
774
+ key is found.
775
+
776
+ Returns
777
+ -------
778
+ edge_ind : bool
779
+ True if edge is in the graph, False otherwise.
780
+
781
+ Examples
782
+ --------
783
+ Can be called either using two nodes u, v, an edge tuple (u, v),
784
+ or an edge tuple (u, v, key).
785
+
786
+ >>> G = nx.MultiGraph() # or MultiDiGraph
787
+ >>> nx.add_path(G, [0, 1, 2, 3])
788
+ >>> G.has_edge(0, 1) # using two nodes
789
+ True
790
+ >>> e = (0, 1)
791
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
792
+ True
793
+ >>> G.add_edge(0, 1, key="a")
794
+ 'a'
795
+ >>> G.has_edge(0, 1, key="a") # specify key
796
+ True
797
+ >>> G.has_edge(1, 0, key="a") # edges aren't directed
798
+ True
799
+ >>> e = (0, 1, "a")
800
+ >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
801
+ True
802
+
803
+ The following syntax are equivalent:
804
+
805
+ >>> G.has_edge(0, 1)
806
+ True
807
+ >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
808
+ True
809
+ >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
810
+ True
811
+
812
+ """
813
+ try:
814
+ if key is None:
815
+ return v in self._adj[u]
816
+ else:
817
+ return key in self._adj[u][v]
818
+ except KeyError:
819
+ return False
820
+
821
+ @cached_property
822
+ def edges(self):
823
+ """Returns an iterator over the edges.
824
+
825
+ edges(self, nbunch=None, data=False, keys=False, default=None)
826
+
827
+ The MultiEdgeView provides set-like operations on the edge-tuples
828
+ as well as edge attribute lookup. When called, it also provides
829
+ an EdgeDataView object which allows control of access to edge
830
+ attributes (but does not provide set-like operations).
831
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
832
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
833
+ ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
834
+ iterates through all the edges yielding the color attribute with
835
+ default `'red'` if no color attribute exists.
836
+
837
+ Edges are returned as tuples with optional data and keys
838
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
839
+ provided, the tuples will just be (node, neighbor, data), but
840
+ multiple tuples with the same node and neighbor will be generated
841
+ when multiple edges exist between two nodes.
842
+
843
+ Parameters
844
+ ----------
845
+ nbunch : single node, container, or all nodes (default= all nodes)
846
+ The view will only report edges from these nodes.
847
+ data : string or bool, optional (default=False)
848
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
849
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
850
+ If False, return 2-tuple (u, v).
851
+ keys : bool, optional (default=False)
852
+ If True, return edge keys with each edge, creating (u, v, k)
853
+ tuples or (u, v, k, d) tuples if data is also requested.
854
+ default : value, optional (default=None)
855
+ Value used for edges that don't have the requested attribute.
856
+ Only relevant if data is not True or False.
857
+
858
+ Returns
859
+ -------
860
+ edges : MultiEdgeView
861
+ A view of edge attributes, usually it iterates over (u, v)
862
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
863
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
864
+
865
+ Notes
866
+ -----
867
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
868
+ For directed graphs this returns the out-edges.
869
+
870
+ Examples
871
+ --------
872
+ >>> G = nx.MultiGraph()
873
+ >>> nx.add_path(G, [0, 1, 2])
874
+ >>> key = G.add_edge(2, 3, weight=5)
875
+ >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
876
+ >>> [e for e in G.edges()]
877
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
878
+ >>> G.edges.data() # default data is {} (empty dict)
879
+ MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
880
+ >>> G.edges.data("weight", default=1)
881
+ MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
882
+ >>> G.edges(keys=True) # default keys are integers
883
+ MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
884
+ >>> G.edges.data(keys=True)
885
+ MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
886
+ >>> G.edges.data("weight", default=1, keys=True)
887
+ MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
888
+ >>> G.edges([0, 3]) # Note ordering of tuples from listed sources
889
+ MultiEdgeDataView([(0, 1), (3, 2)])
890
+ >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
891
+ MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
892
+ >>> G.edges(0)
893
+ MultiEdgeDataView([(0, 1)])
894
+ """
895
+ return MultiEdgeView(self)
896
+
897
+ def get_edge_data(self, u, v, key=None, default=None):
898
+ """Returns the attribute dictionary associated with edge (u, v,
899
+ key).
900
+
901
+ If a key is not provided, returns a dictionary mapping edge keys
902
+ to attribute dictionaries for each edge between u and v.
903
+
904
+ This is identical to `G[u][v][key]` except the default is returned
905
+ instead of an exception is the edge doesn't exist.
906
+
907
+ Parameters
908
+ ----------
909
+ u, v : nodes
910
+
911
+ default : any Python object (default=None)
912
+ Value to return if the specific edge (u, v, key) is not
913
+ found, OR if there are no edges between u and v and no key
914
+ is specified.
915
+
916
+ key : hashable identifier, optional (default=None)
917
+ Return data only for the edge with specified key, as an
918
+ attribute dictionary (rather than a dictionary mapping keys
919
+ to attribute dictionaries).
920
+
921
+ Returns
922
+ -------
923
+ edge_dict : dictionary
924
+ The edge attribute dictionary, OR a dictionary mapping edge
925
+ keys to attribute dictionaries for each of those edges if no
926
+ specific key is provided (even if there's only one edge
927
+ between u and v).
928
+
929
+ Examples
930
+ --------
931
+ >>> G = nx.MultiGraph() # or MultiDiGraph
932
+ >>> key = G.add_edge(0, 1, key="a", weight=7)
933
+ >>> G[0][1]["a"] # key='a'
934
+ {'weight': 7}
935
+ >>> G.edges[0, 1, "a"] # key='a'
936
+ {'weight': 7}
937
+
938
+ Warning: we protect the graph data structure by making
939
+ `G.edges` and `G[1][2]` read-only dict-like structures.
940
+ However, you can assign values to attributes in e.g.
941
+ `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
942
+ bracket as shown next. You need to specify all edge info
943
+ to assign to the edge data associated with an edge.
944
+
945
+ >>> G[0][1]["a"]["weight"] = 10
946
+ >>> G.edges[0, 1, "a"]["weight"] = 10
947
+ >>> G[0][1]["a"]["weight"]
948
+ 10
949
+ >>> G.edges[1, 0, "a"]["weight"]
950
+ 10
951
+
952
+ >>> G = nx.MultiGraph() # or MultiDiGraph
953
+ >>> nx.add_path(G, [0, 1, 2, 3])
954
+ >>> G.edges[0, 1, 0]["weight"] = 5
955
+ >>> G.get_edge_data(0, 1)
956
+ {0: {'weight': 5}}
957
+ >>> e = (0, 1)
958
+ >>> G.get_edge_data(*e) # tuple form
959
+ {0: {'weight': 5}}
960
+ >>> G.get_edge_data(3, 0) # edge not in graph, returns None
961
+ >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
962
+ 0
963
+ >>> G.get_edge_data(1, 0, 0) # specific key gives back
964
+ {'weight': 5}
965
+ """
966
+ try:
967
+ if key is None:
968
+ return self._adj[u][v]
969
+ else:
970
+ return self._adj[u][v][key]
971
+ except KeyError:
972
+ return default
973
+
974
+ @cached_property
975
+ def degree(self):
976
+ """A DegreeView for the Graph as G.degree or G.degree().
977
+
978
+ The node degree is the number of edges adjacent to the node.
979
+ The weighted node degree is the sum of the edge weights for
980
+ edges incident to that node.
981
+
982
+ This object provides an iterator for (node, degree) as well as
983
+ lookup for the degree for a single node.
984
+
985
+ Parameters
986
+ ----------
987
+ nbunch : single node, container, or all nodes (default= all nodes)
988
+ The view will only report edges incident to these nodes.
989
+
990
+ weight : string or None, optional (default=None)
991
+ The name of an edge attribute that holds the numerical value used
992
+ as a weight. If None, then each edge has weight 1.
993
+ The degree is the sum of the edge weights adjacent to the node.
994
+
995
+ Returns
996
+ -------
997
+ MultiDegreeView or int
998
+ If multiple nodes are requested (the default), returns a `MultiDegreeView`
999
+ mapping nodes to their degree.
1000
+ If a single node is requested, returns the degree of the node as an integer.
1001
+
1002
+ Examples
1003
+ --------
1004
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1005
+ >>> nx.add_path(G, [0, 1, 2, 3])
1006
+ >>> G.degree(0) # node 0 with degree 1
1007
+ 1
1008
+ >>> list(G.degree([0, 1]))
1009
+ [(0, 1), (1, 2)]
1010
+
1011
+ """
1012
+ return MultiDegreeView(self)
1013
+
1014
+ def is_multigraph(self):
1015
+ """Returns True if graph is a multigraph, False otherwise."""
1016
+ return True
1017
+
1018
+ def is_directed(self):
1019
+ """Returns True if graph is directed, False otherwise."""
1020
+ return False
1021
+
1022
+ def copy(self, as_view=False):
1023
+ """Returns a copy of the graph.
1024
+
1025
+ The copy method by default returns an independent shallow copy
1026
+ of the graph and attributes. That is, if an attribute is a
1027
+ container, that container is shared by the original an the copy.
1028
+ Use Python's `copy.deepcopy` for new containers.
1029
+
1030
+ If `as_view` is True then a view is returned instead of a copy.
1031
+
1032
+ Notes
1033
+ -----
1034
+ All copies reproduce the graph structure, but data attributes
1035
+ may be handled in different ways. There are four types of copies
1036
+ of a graph that people might want.
1037
+
1038
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1039
+ all data attributes and any objects they might contain.
1040
+ The entire graph object is new so that changes in the copy
1041
+ do not affect the original object. (see Python's copy.deepcopy)
1042
+
1043
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1044
+ is copied but the edge, node and graph attribute dicts are
1045
+ references to those in the original graph. This saves
1046
+ time and memory but could cause confusion if you change an attribute
1047
+ in one graph and it changes the attribute in the other.
1048
+ NetworkX does not provide this level of shallow copy.
1049
+
1050
+ Independent Shallow -- This copy creates new independent attribute
1051
+ dicts and then does a shallow copy of the attributes. That is, any
1052
+ attributes that are containers are shared between the new graph
1053
+ and the original. This is exactly what `dict.copy()` provides.
1054
+ You can obtain this style copy using:
1055
+
1056
+ >>> G = nx.path_graph(5)
1057
+ >>> H = G.copy()
1058
+ >>> H = G.copy(as_view=False)
1059
+ >>> H = nx.Graph(G)
1060
+ >>> H = G.__class__(G)
1061
+
1062
+ Fresh Data -- For fresh data, the graph structure is copied while
1063
+ new empty data attribute dicts are created. The resulting graph
1064
+ is independent of the original and it has no edge, node or graph
1065
+ attributes. Fresh copies are not enabled. Instead use:
1066
+
1067
+ >>> H = G.__class__()
1068
+ >>> H.add_nodes_from(G)
1069
+ >>> H.add_edges_from(G.edges)
1070
+
1071
+ View -- Inspired by dict-views, graph-views act like read-only
1072
+ versions of the original graph, providing a copy of the original
1073
+ structure without requiring any memory for copying the information.
1074
+
1075
+ See the Python copy module for more information on shallow
1076
+ and deep copies, https://docs.python.org/3/library/copy.html.
1077
+
1078
+ Parameters
1079
+ ----------
1080
+ as_view : bool, optional (default=False)
1081
+ If True, the returned graph-view provides a read-only view
1082
+ of the original graph without actually copying any data.
1083
+
1084
+ Returns
1085
+ -------
1086
+ G : Graph
1087
+ A copy of the graph.
1088
+
1089
+ See Also
1090
+ --------
1091
+ to_directed: return a directed copy of the graph.
1092
+
1093
+ Examples
1094
+ --------
1095
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1096
+ >>> H = G.copy()
1097
+
1098
+ """
1099
+ if as_view is True:
1100
+ return nx.graphviews.generic_graph_view(self)
1101
+ G = self.__class__()
1102
+ G.graph.update(self.graph)
1103
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1104
+ G.add_edges_from(
1105
+ (u, v, key, datadict.copy())
1106
+ for u, nbrs in self._adj.items()
1107
+ for v, keydict in nbrs.items()
1108
+ for key, datadict in keydict.items()
1109
+ )
1110
+ return G
1111
+
1112
+ def to_directed(self, as_view=False):
1113
+ """Returns a directed representation of the graph.
1114
+
1115
+ Returns
1116
+ -------
1117
+ G : MultiDiGraph
1118
+ A directed graph with the same name, same nodes, and with
1119
+ each edge (u, v, k, data) replaced by two directed edges
1120
+ (u, v, k, data) and (v, u, k, data).
1121
+
1122
+ Notes
1123
+ -----
1124
+ This returns a "deepcopy" of the edge, node, and
1125
+ graph attributes which attempts to completely copy
1126
+ all of the data and references.
1127
+
1128
+ This is in contrast to the similar D=MultiDiGraph(G) which
1129
+ returns a shallow copy of the data.
1130
+
1131
+ See the Python copy module for more information on shallow
1132
+ and deep copies, https://docs.python.org/3/library/copy.html.
1133
+
1134
+ Warning: If you have subclassed MultiGraph to use dict-like objects
1135
+ in the data structure, those changes do not transfer to the
1136
+ MultiDiGraph created by this method.
1137
+
1138
+ Examples
1139
+ --------
1140
+ >>> G = nx.MultiGraph()
1141
+ >>> G.add_edge(0, 1)
1142
+ 0
1143
+ >>> G.add_edge(0, 1)
1144
+ 1
1145
+ >>> H = G.to_directed()
1146
+ >>> list(H.edges)
1147
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
1148
+
1149
+ If already directed, return a (deep) copy
1150
+
1151
+ >>> G = nx.MultiDiGraph()
1152
+ >>> G.add_edge(0, 1)
1153
+ 0
1154
+ >>> H = G.to_directed()
1155
+ >>> list(H.edges)
1156
+ [(0, 1, 0)]
1157
+ """
1158
+ graph_class = self.to_directed_class()
1159
+ if as_view is True:
1160
+ return nx.graphviews.generic_graph_view(self, graph_class)
1161
+ # deepcopy when not a view
1162
+ G = graph_class()
1163
+ G.graph.update(deepcopy(self.graph))
1164
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1165
+ G.add_edges_from(
1166
+ (u, v, key, deepcopy(datadict))
1167
+ for u, nbrs in self.adj.items()
1168
+ for v, keydict in nbrs.items()
1169
+ for key, datadict in keydict.items()
1170
+ )
1171
+ return G
1172
+
1173
+ def to_undirected(self, as_view=False):
1174
+ """Returns an undirected copy of the graph.
1175
+
1176
+ Returns
1177
+ -------
1178
+ G : Graph/MultiGraph
1179
+ A deepcopy of the graph.
1180
+
1181
+ See Also
1182
+ --------
1183
+ copy, add_edge, add_edges_from
1184
+
1185
+ Notes
1186
+ -----
1187
+ This returns a "deepcopy" of the edge, node, and
1188
+ graph attributes which attempts to completely copy
1189
+ all of the data and references.
1190
+
1191
+ This is in contrast to the similar `G = nx.MultiGraph(D)`
1192
+ which returns a shallow copy of the data.
1193
+
1194
+ See the Python copy module for more information on shallow
1195
+ and deep copies, https://docs.python.org/3/library/copy.html.
1196
+
1197
+ Warning: If you have subclassed MultiGraph to use dict-like
1198
+ objects in the data structure, those changes do not transfer
1199
+ to the MultiGraph created by this method.
1200
+
1201
+ Examples
1202
+ --------
1203
+ >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
1204
+ >>> H = G.to_directed()
1205
+ >>> list(H.edges)
1206
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
1207
+ >>> G2 = H.to_undirected()
1208
+ >>> list(G2.edges)
1209
+ [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
1210
+ """
1211
+ graph_class = self.to_undirected_class()
1212
+ if as_view is True:
1213
+ return nx.graphviews.generic_graph_view(self, graph_class)
1214
+ # deepcopy when not a view
1215
+ G = graph_class()
1216
+ G.graph.update(deepcopy(self.graph))
1217
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1218
+ G.add_edges_from(
1219
+ (u, v, key, deepcopy(datadict))
1220
+ for u, nbrs in self._adj.items()
1221
+ for v, keydict in nbrs.items()
1222
+ for key, datadict in keydict.items()
1223
+ )
1224
+ return G
1225
+
1226
+ def number_of_edges(self, u=None, v=None):
1227
+ """Returns the number of edges between two nodes.
1228
+
1229
+ Parameters
1230
+ ----------
1231
+ u, v : nodes, optional (Default=all edges)
1232
+ If u and v are specified, return the number of edges between
1233
+ u and v. Otherwise return the total number of all edges.
1234
+
1235
+ Returns
1236
+ -------
1237
+ nedges : int
1238
+ The number of edges in the graph. If nodes `u` and `v` are
1239
+ specified return the number of edges between those nodes. If
1240
+ the graph is directed, this only returns the number of edges
1241
+ from `u` to `v`.
1242
+
1243
+ See Also
1244
+ --------
1245
+ size
1246
+
1247
+ Examples
1248
+ --------
1249
+ For undirected multigraphs, this method counts the total number
1250
+ of edges in the graph::
1251
+
1252
+ >>> G = nx.MultiGraph()
1253
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
1254
+ [0, 1, 0]
1255
+ >>> G.number_of_edges()
1256
+ 3
1257
+
1258
+ If you specify two nodes, this counts the total number of edges
1259
+ joining the two nodes::
1260
+
1261
+ >>> G.number_of_edges(0, 1)
1262
+ 2
1263
+
1264
+ For directed multigraphs, this method can count the total number
1265
+ of directed edges from `u` to `v`::
1266
+
1267
+ >>> G = nx.MultiDiGraph()
1268
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
1269
+ [0, 1, 0]
1270
+ >>> G.number_of_edges(0, 1)
1271
+ 2
1272
+ >>> G.number_of_edges(1, 0)
1273
+ 1
1274
+
1275
+ """
1276
+ if u is None:
1277
+ return self.size()
1278
+ try:
1279
+ edgedata = self._adj[u][v]
1280
+ except KeyError:
1281
+ return 0 # no such edge
1282
+ return len(edgedata)
env-llmeval/lib/python3.10/site-packages/networkx/classes/reportviews.py ADDED
@@ -0,0 +1,1438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ View Classes provide node, edge and degree "views" of a graph.
3
+
4
+ Views for nodes, edges and degree are provided for all base graph classes.
5
+ A view means a read-only object that is quick to create, automatically
6
+ updated when the graph changes, and provides basic access like `n in V`,
7
+ `for n in V`, `V[n]` and sometimes set operations.
8
+
9
+ The views are read-only iterable containers that are updated as the
10
+ graph is updated. As with dicts, the graph should not be updated
11
+ while iterating through the view. Views can be iterated multiple times.
12
+
13
+ Edge and Node views also allow data attribute lookup.
14
+ The resulting attribute dict is writable as `G.edges[3, 4]['color']='red'`
15
+ Degree views allow lookup of degree values for single nodes.
16
+ Weighted degree is supported with the `weight` argument.
17
+
18
+ NodeView
19
+ ========
20
+
21
+ `V = G.nodes` (or `V = G.nodes()`) allows `len(V)`, `n in V`, set
22
+ operations e.g. "G.nodes & H.nodes", and `dd = G.nodes[n]`, where
23
+ `dd` is the node data dict. Iteration is over the nodes by default.
24
+
25
+ NodeDataView
26
+ ============
27
+
28
+ To iterate over (node, data) pairs, use arguments to `G.nodes()`
29
+ to create a DataView e.g. `DV = G.nodes(data='color', default='red')`.
30
+ The DataView iterates as `for n, color in DV` and allows
31
+ `(n, 'red') in DV`. Using `DV = G.nodes(data=True)`, the DataViews
32
+ use the full datadict in writeable form also allowing contain testing as
33
+ `(n, {'color': 'red'}) in VD`. DataViews allow set operations when
34
+ data attributes are hashable.
35
+
36
+ DegreeView
37
+ ==========
38
+
39
+ `V = G.degree` allows iteration over (node, degree) pairs as well
40
+ as lookup: `deg=V[n]`. There are many flavors of DegreeView
41
+ for In/Out/Directed/Multi. For Directed Graphs, `G.degree`
42
+ counts both in and out going edges. `G.out_degree` and
43
+ `G.in_degree` count only specific directions.
44
+ Weighted degree using edge data attributes is provide via
45
+ `V = G.degree(weight='attr_name')` where any string with the
46
+ attribute name can be used. `weight=None` is the default.
47
+ No set operations are implemented for degrees, use NodeView.
48
+
49
+ The argument `nbunch` restricts iteration to nodes in nbunch.
50
+ The DegreeView can still lookup any node even if nbunch is specified.
51
+
52
+ EdgeView
53
+ ========
54
+
55
+ `V = G.edges` or `V = G.edges()` allows iteration over edges as well as
56
+ `e in V`, set operations and edge data lookup `dd = G.edges[2, 3]`.
57
+ Iteration is over 2-tuples `(u, v)` for Graph/DiGraph. For multigraphs
58
+ edges 3-tuples `(u, v, key)` are the default but 2-tuples can be obtained
59
+ via `V = G.edges(keys=False)`.
60
+
61
+ Set operations for directed graphs treat the edges as a set of 2-tuples.
62
+ For undirected graphs, 2-tuples are not a unique representation of edges.
63
+ So long as the set being compared to contains unique representations
64
+ of its edges, the set operations will act as expected. If the other
65
+ set contains both `(0, 1)` and `(1, 0)` however, the result of set
66
+ operations may contain both representations of the same edge.
67
+
68
+ EdgeDataView
69
+ ============
70
+
71
+ Edge data can be reported using an EdgeDataView typically created
72
+ by calling an EdgeView: `DV = G.edges(data='weight', default=1)`.
73
+ The EdgeDataView allows iteration over edge tuples, membership checking
74
+ but no set operations.
75
+
76
+ Iteration depends on `data` and `default` and for multigraph `keys`
77
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
78
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
79
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
80
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key`
81
+ to create 3-tuples and 4-tuples.
82
+
83
+ The argument `nbunch` restricts edges to those incident to nodes in nbunch.
84
+ """
85
+ from collections.abc import Mapping, Set
86
+
87
+ import networkx as nx
88
+
89
+ __all__ = [
90
+ "NodeView",
91
+ "NodeDataView",
92
+ "EdgeView",
93
+ "OutEdgeView",
94
+ "InEdgeView",
95
+ "EdgeDataView",
96
+ "OutEdgeDataView",
97
+ "InEdgeDataView",
98
+ "MultiEdgeView",
99
+ "OutMultiEdgeView",
100
+ "InMultiEdgeView",
101
+ "MultiEdgeDataView",
102
+ "OutMultiEdgeDataView",
103
+ "InMultiEdgeDataView",
104
+ "DegreeView",
105
+ "DiDegreeView",
106
+ "InDegreeView",
107
+ "OutDegreeView",
108
+ "MultiDegreeView",
109
+ "DiMultiDegreeView",
110
+ "InMultiDegreeView",
111
+ "OutMultiDegreeView",
112
+ ]
113
+
114
+
115
+ # NodeViews
116
+ class NodeView(Mapping, Set):
117
+ """A NodeView class to act as G.nodes for a NetworkX Graph
118
+
119
+ Set operations act on the nodes without considering data.
120
+ Iteration is over nodes. Node data can be looked up like a dict.
121
+ Use NodeDataView to iterate over node data or to specify a data
122
+ attribute for lookup. NodeDataView is created by calling the NodeView.
123
+
124
+ Parameters
125
+ ----------
126
+ graph : NetworkX graph-like class
127
+
128
+ Examples
129
+ --------
130
+ >>> G = nx.path_graph(3)
131
+ >>> NV = G.nodes()
132
+ >>> 2 in NV
133
+ True
134
+ >>> for n in NV:
135
+ ... print(n)
136
+ 0
137
+ 1
138
+ 2
139
+ >>> assert NV & {1, 2, 3} == {1, 2}
140
+
141
+ >>> G.add_node(2, color="blue")
142
+ >>> NV[2]
143
+ {'color': 'blue'}
144
+ >>> G.add_node(8, color="red")
145
+ >>> NDV = G.nodes(data=True)
146
+ >>> (2, NV[2]) in NDV
147
+ True
148
+ >>> for n, dd in NDV:
149
+ ... print((n, dd.get("color", "aqua")))
150
+ (0, 'aqua')
151
+ (1, 'aqua')
152
+ (2, 'blue')
153
+ (8, 'red')
154
+ >>> NDV[2] == NV[2]
155
+ True
156
+
157
+ >>> NVdata = G.nodes(data="color", default="aqua")
158
+ >>> (2, NVdata[2]) in NVdata
159
+ True
160
+ >>> for n, dd in NVdata:
161
+ ... print((n, dd))
162
+ (0, 'aqua')
163
+ (1, 'aqua')
164
+ (2, 'blue')
165
+ (8, 'red')
166
+ >>> NVdata[2] == NV[2] # NVdata gets 'color', NV gets datadict
167
+ False
168
+ """
169
+
170
+ __slots__ = ("_nodes",)
171
+
172
+ def __getstate__(self):
173
+ return {"_nodes": self._nodes}
174
+
175
+ def __setstate__(self, state):
176
+ self._nodes = state["_nodes"]
177
+
178
+ def __init__(self, graph):
179
+ self._nodes = graph._node
180
+
181
+ # Mapping methods
182
+ def __len__(self):
183
+ return len(self._nodes)
184
+
185
+ def __iter__(self):
186
+ return iter(self._nodes)
187
+
188
+ def __getitem__(self, n):
189
+ if isinstance(n, slice):
190
+ raise nx.NetworkXError(
191
+ f"{type(self).__name__} does not support slicing, "
192
+ f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]"
193
+ )
194
+ return self._nodes[n]
195
+
196
+ # Set methods
197
+ def __contains__(self, n):
198
+ return n in self._nodes
199
+
200
+ @classmethod
201
+ def _from_iterable(cls, it):
202
+ return set(it)
203
+
204
+ # DataView method
205
+ def __call__(self, data=False, default=None):
206
+ if data is False:
207
+ return self
208
+ return NodeDataView(self._nodes, data, default)
209
+
210
+ def data(self, data=True, default=None):
211
+ """
212
+ Return a read-only view of node data.
213
+
214
+ Parameters
215
+ ----------
216
+ data : bool or node data key, default=True
217
+ If ``data=True`` (the default), return a `NodeDataView` object that
218
+ maps each node to *all* of its attributes. `data` may also be an
219
+ arbitrary key, in which case the `NodeDataView` maps each node to
220
+ the value for the keyed attribute. In this case, if a node does
221
+ not have the `data` attribute, the `default` value is used.
222
+ default : object, default=None
223
+ The value used when a node does not have a specific attribute.
224
+
225
+ Returns
226
+ -------
227
+ NodeDataView
228
+ The layout of the returned NodeDataView depends on the value of the
229
+ `data` parameter.
230
+
231
+ Notes
232
+ -----
233
+ If ``data=False``, returns a `NodeView` object without data.
234
+
235
+ See Also
236
+ --------
237
+ NodeDataView
238
+
239
+ Examples
240
+ --------
241
+ >>> G = nx.Graph()
242
+ >>> G.add_nodes_from(
243
+ ... [
244
+ ... (0, {"color": "red", "weight": 10}),
245
+ ... (1, {"color": "blue"}),
246
+ ... (2, {"color": "yellow", "weight": 2}),
247
+ ... ]
248
+ ... )
249
+
250
+ Accessing node data with ``data=True`` (the default) returns a
251
+ NodeDataView mapping each node to all of its attributes:
252
+
253
+ >>> G.nodes.data()
254
+ NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}})
255
+
256
+ If `data` represents a key in the node attribute dict, a NodeDataView mapping
257
+ the nodes to the value for that specific key is returned:
258
+
259
+ >>> G.nodes.data("color")
260
+ NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color')
261
+
262
+ If a specific key is not found in an attribute dict, the value specified
263
+ by `default` is returned:
264
+
265
+ >>> G.nodes.data("weight", default=-999)
266
+ NodeDataView({0: 10, 1: -999, 2: 2}, data='weight')
267
+
268
+ Note that there is no check that the `data` key is in any of the
269
+ node attribute dictionaries:
270
+
271
+ >>> G.nodes.data("height")
272
+ NodeDataView({0: None, 1: None, 2: None}, data='height')
273
+ """
274
+ if data is False:
275
+ return self
276
+ return NodeDataView(self._nodes, data, default)
277
+
278
+ def __str__(self):
279
+ return str(list(self))
280
+
281
+ def __repr__(self):
282
+ return f"{self.__class__.__name__}({tuple(self)})"
283
+
284
+
285
+ class NodeDataView(Set):
286
+ """A DataView class for nodes of a NetworkX Graph
287
+
288
+ The main use for this class is to iterate through node-data pairs.
289
+ The data can be the entire data-dictionary for each node, or it
290
+ can be a specific attribute (with default) for each node.
291
+ Set operations are enabled with NodeDataView, but don't work in
292
+ cases where the data is not hashable. Use with caution.
293
+ Typically, set operations on nodes use NodeView, not NodeDataView.
294
+ That is, they use `G.nodes` instead of `G.nodes(data='foo')`.
295
+
296
+ Parameters
297
+ ==========
298
+ graph : NetworkX graph-like class
299
+ data : bool or string (default=False)
300
+ default : object (default=None)
301
+ """
302
+
303
+ __slots__ = ("_nodes", "_data", "_default")
304
+
305
+ def __getstate__(self):
306
+ return {"_nodes": self._nodes, "_data": self._data, "_default": self._default}
307
+
308
+ def __setstate__(self, state):
309
+ self._nodes = state["_nodes"]
310
+ self._data = state["_data"]
311
+ self._default = state["_default"]
312
+
313
+ def __init__(self, nodedict, data=False, default=None):
314
+ self._nodes = nodedict
315
+ self._data = data
316
+ self._default = default
317
+
318
+ @classmethod
319
+ def _from_iterable(cls, it):
320
+ try:
321
+ return set(it)
322
+ except TypeError as err:
323
+ if "unhashable" in str(err):
324
+ msg = " : Could be b/c data=True or your values are unhashable"
325
+ raise TypeError(str(err) + msg) from err
326
+ raise
327
+
328
+ def __len__(self):
329
+ return len(self._nodes)
330
+
331
+ def __iter__(self):
332
+ data = self._data
333
+ if data is False:
334
+ return iter(self._nodes)
335
+ if data is True:
336
+ return iter(self._nodes.items())
337
+ return (
338
+ (n, dd[data] if data in dd else self._default)
339
+ for n, dd in self._nodes.items()
340
+ )
341
+
342
+ def __contains__(self, n):
343
+ try:
344
+ node_in = n in self._nodes
345
+ except TypeError:
346
+ n, d = n
347
+ return n in self._nodes and self[n] == d
348
+ if node_in is True:
349
+ return node_in
350
+ try:
351
+ n, d = n
352
+ except (TypeError, ValueError):
353
+ return False
354
+ return n in self._nodes and self[n] == d
355
+
356
+ def __getitem__(self, n):
357
+ if isinstance(n, slice):
358
+ raise nx.NetworkXError(
359
+ f"{type(self).__name__} does not support slicing, "
360
+ f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]"
361
+ )
362
+ ddict = self._nodes[n]
363
+ data = self._data
364
+ if data is False or data is True:
365
+ return ddict
366
+ return ddict[data] if data in ddict else self._default
367
+
368
+ def __str__(self):
369
+ return str(list(self))
370
+
371
+ def __repr__(self):
372
+ name = self.__class__.__name__
373
+ if self._data is False:
374
+ return f"{name}({tuple(self)})"
375
+ if self._data is True:
376
+ return f"{name}({dict(self)})"
377
+ return f"{name}({dict(self)}, data={self._data!r})"
378
+
379
+
380
+ # DegreeViews
381
+ class DiDegreeView:
382
+ """A View class for degree of nodes in a NetworkX Graph
383
+
384
+ The functionality is like dict.items() with (node, degree) pairs.
385
+ Additional functionality includes read-only lookup of node degree,
386
+ and calling with optional features nbunch (for only a subset of nodes)
387
+ and weight (use edge weights to compute degree).
388
+
389
+ Parameters
390
+ ==========
391
+ graph : NetworkX graph-like class
392
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
393
+ weight : bool or string (default=None)
394
+
395
+ Notes
396
+ -----
397
+ DegreeView can still lookup any node even if nbunch is specified.
398
+
399
+ Examples
400
+ --------
401
+ >>> G = nx.path_graph(3)
402
+ >>> DV = G.degree()
403
+ >>> assert DV[2] == 1
404
+ >>> assert sum(deg for n, deg in DV) == 4
405
+
406
+ >>> DVweight = G.degree(weight="span")
407
+ >>> G.add_edge(1, 2, span=34)
408
+ >>> DVweight[2]
409
+ 34
410
+ >>> DVweight[0] # default edge weight is 1
411
+ 1
412
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
413
+ 70
414
+
415
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
416
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
417
+ """
418
+
419
+ def __init__(self, G, nbunch=None, weight=None):
420
+ self._graph = G
421
+ self._succ = G._succ if hasattr(G, "_succ") else G._adj
422
+ self._pred = G._pred if hasattr(G, "_pred") else G._adj
423
+ self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch))
424
+ self._weight = weight
425
+
426
+ def __call__(self, nbunch=None, weight=None):
427
+ if nbunch is None:
428
+ if weight == self._weight:
429
+ return self
430
+ return self.__class__(self._graph, None, weight)
431
+ try:
432
+ if nbunch in self._nodes:
433
+ if weight == self._weight:
434
+ return self[nbunch]
435
+ return self.__class__(self._graph, None, weight)[nbunch]
436
+ except TypeError:
437
+ pass
438
+ return self.__class__(self._graph, nbunch, weight)
439
+
440
+ def __getitem__(self, n):
441
+ weight = self._weight
442
+ succs = self._succ[n]
443
+ preds = self._pred[n]
444
+ if weight is None:
445
+ return len(succs) + len(preds)
446
+ return sum(dd.get(weight, 1) for dd in succs.values()) + sum(
447
+ dd.get(weight, 1) for dd in preds.values()
448
+ )
449
+
450
+ def __iter__(self):
451
+ weight = self._weight
452
+ if weight is None:
453
+ for n in self._nodes:
454
+ succs = self._succ[n]
455
+ preds = self._pred[n]
456
+ yield (n, len(succs) + len(preds))
457
+ else:
458
+ for n in self._nodes:
459
+ succs = self._succ[n]
460
+ preds = self._pred[n]
461
+ deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum(
462
+ dd.get(weight, 1) for dd in preds.values()
463
+ )
464
+ yield (n, deg)
465
+
466
+ def __len__(self):
467
+ return len(self._nodes)
468
+
469
+ def __str__(self):
470
+ return str(list(self))
471
+
472
+ def __repr__(self):
473
+ return f"{self.__class__.__name__}({dict(self)})"
474
+
475
+
476
+ class DegreeView(DiDegreeView):
477
+ """A DegreeView class to act as G.degree for a NetworkX Graph
478
+
479
+ Typical usage focuses on iteration over `(node, degree)` pairs.
480
+ The degree is by default the number of edges incident to the node.
481
+ Optional argument `weight` enables weighted degree using the edge
482
+ attribute named in the `weight` argument. Reporting and iteration
483
+ can also be restricted to a subset of nodes using `nbunch`.
484
+
485
+ Additional functionality include node lookup so that `G.degree[n]`
486
+ reported the (possibly weighted) degree of node `n`. Calling the
487
+ view creates a view with different arguments `nbunch` or `weight`.
488
+
489
+ Parameters
490
+ ==========
491
+ graph : NetworkX graph-like class
492
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
493
+ weight : string or None (default=None)
494
+
495
+ Notes
496
+ -----
497
+ DegreeView can still lookup any node even if nbunch is specified.
498
+
499
+ Examples
500
+ --------
501
+ >>> G = nx.path_graph(3)
502
+ >>> DV = G.degree()
503
+ >>> assert DV[2] == 1
504
+ >>> assert G.degree[2] == 1
505
+ >>> assert sum(deg for n, deg in DV) == 4
506
+
507
+ >>> DVweight = G.degree(weight="span")
508
+ >>> G.add_edge(1, 2, span=34)
509
+ >>> DVweight[2]
510
+ 34
511
+ >>> DVweight[0] # default edge weight is 1
512
+ 1
513
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
514
+ 70
515
+
516
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
517
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
518
+ """
519
+
520
+ def __getitem__(self, n):
521
+ weight = self._weight
522
+ nbrs = self._succ[n]
523
+ if weight is None:
524
+ return len(nbrs) + (n in nbrs)
525
+ return sum(dd.get(weight, 1) for dd in nbrs.values()) + (
526
+ n in nbrs and nbrs[n].get(weight, 1)
527
+ )
528
+
529
+ def __iter__(self):
530
+ weight = self._weight
531
+ if weight is None:
532
+ for n in self._nodes:
533
+ nbrs = self._succ[n]
534
+ yield (n, len(nbrs) + (n in nbrs))
535
+ else:
536
+ for n in self._nodes:
537
+ nbrs = self._succ[n]
538
+ deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + (
539
+ n in nbrs and nbrs[n].get(weight, 1)
540
+ )
541
+ yield (n, deg)
542
+
543
+
544
+ class OutDegreeView(DiDegreeView):
545
+ """A DegreeView class to report out_degree for a DiGraph; See DegreeView"""
546
+
547
+ def __getitem__(self, n):
548
+ weight = self._weight
549
+ nbrs = self._succ[n]
550
+ if self._weight is None:
551
+ return len(nbrs)
552
+ return sum(dd.get(self._weight, 1) for dd in nbrs.values())
553
+
554
+ def __iter__(self):
555
+ weight = self._weight
556
+ if weight is None:
557
+ for n in self._nodes:
558
+ succs = self._succ[n]
559
+ yield (n, len(succs))
560
+ else:
561
+ for n in self._nodes:
562
+ succs = self._succ[n]
563
+ deg = sum(dd.get(weight, 1) for dd in succs.values())
564
+ yield (n, deg)
565
+
566
+
567
+ class InDegreeView(DiDegreeView):
568
+ """A DegreeView class to report in_degree for a DiGraph; See DegreeView"""
569
+
570
+ def __getitem__(self, n):
571
+ weight = self._weight
572
+ nbrs = self._pred[n]
573
+ if weight is None:
574
+ return len(nbrs)
575
+ return sum(dd.get(weight, 1) for dd in nbrs.values())
576
+
577
+ def __iter__(self):
578
+ weight = self._weight
579
+ if weight is None:
580
+ for n in self._nodes:
581
+ preds = self._pred[n]
582
+ yield (n, len(preds))
583
+ else:
584
+ for n in self._nodes:
585
+ preds = self._pred[n]
586
+ deg = sum(dd.get(weight, 1) for dd in preds.values())
587
+ yield (n, deg)
588
+
589
+
590
+ class MultiDegreeView(DiDegreeView):
591
+ """A DegreeView class for undirected multigraphs; See DegreeView"""
592
+
593
+ def __getitem__(self, n):
594
+ weight = self._weight
595
+ nbrs = self._succ[n]
596
+ if weight is None:
597
+ return sum(len(keys) for keys in nbrs.values()) + (
598
+ n in nbrs and len(nbrs[n])
599
+ )
600
+ # edge weighted graph - degree is sum of nbr edge weights
601
+ deg = sum(
602
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
603
+ )
604
+ if n in nbrs:
605
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
606
+ return deg
607
+
608
+ def __iter__(self):
609
+ weight = self._weight
610
+ if weight is None:
611
+ for n in self._nodes:
612
+ nbrs = self._succ[n]
613
+ deg = sum(len(keys) for keys in nbrs.values()) + (
614
+ n in nbrs and len(nbrs[n])
615
+ )
616
+ yield (n, deg)
617
+ else:
618
+ for n in self._nodes:
619
+ nbrs = self._succ[n]
620
+ deg = sum(
621
+ d.get(weight, 1)
622
+ for key_dict in nbrs.values()
623
+ for d in key_dict.values()
624
+ )
625
+ if n in nbrs:
626
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
627
+ yield (n, deg)
628
+
629
+
630
+ class DiMultiDegreeView(DiDegreeView):
631
+ """A DegreeView class for MultiDiGraph; See DegreeView"""
632
+
633
+ def __getitem__(self, n):
634
+ weight = self._weight
635
+ succs = self._succ[n]
636
+ preds = self._pred[n]
637
+ if weight is None:
638
+ return sum(len(keys) for keys in succs.values()) + sum(
639
+ len(keys) for keys in preds.values()
640
+ )
641
+ # edge weighted graph - degree is sum of nbr edge weights
642
+ deg = sum(
643
+ d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values()
644
+ ) + sum(
645
+ d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values()
646
+ )
647
+ return deg
648
+
649
+ def __iter__(self):
650
+ weight = self._weight
651
+ if weight is None:
652
+ for n in self._nodes:
653
+ succs = self._succ[n]
654
+ preds = self._pred[n]
655
+ deg = sum(len(keys) for keys in succs.values()) + sum(
656
+ len(keys) for keys in preds.values()
657
+ )
658
+ yield (n, deg)
659
+ else:
660
+ for n in self._nodes:
661
+ succs = self._succ[n]
662
+ preds = self._pred[n]
663
+ deg = sum(
664
+ d.get(weight, 1)
665
+ for key_dict in succs.values()
666
+ for d in key_dict.values()
667
+ ) + sum(
668
+ d.get(weight, 1)
669
+ for key_dict in preds.values()
670
+ for d in key_dict.values()
671
+ )
672
+ yield (n, deg)
673
+
674
+
675
+ class InMultiDegreeView(DiDegreeView):
676
+ """A DegreeView class for inward degree of MultiDiGraph; See DegreeView"""
677
+
678
+ def __getitem__(self, n):
679
+ weight = self._weight
680
+ nbrs = self._pred[n]
681
+ if weight is None:
682
+ return sum(len(data) for data in nbrs.values())
683
+ # edge weighted graph - degree is sum of nbr edge weights
684
+ return sum(
685
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
686
+ )
687
+
688
+ def __iter__(self):
689
+ weight = self._weight
690
+ if weight is None:
691
+ for n in self._nodes:
692
+ nbrs = self._pred[n]
693
+ deg = sum(len(data) for data in nbrs.values())
694
+ yield (n, deg)
695
+ else:
696
+ for n in self._nodes:
697
+ nbrs = self._pred[n]
698
+ deg = sum(
699
+ d.get(weight, 1)
700
+ for key_dict in nbrs.values()
701
+ for d in key_dict.values()
702
+ )
703
+ yield (n, deg)
704
+
705
+
706
+ class OutMultiDegreeView(DiDegreeView):
707
+ """A DegreeView class for outward degree of MultiDiGraph; See DegreeView"""
708
+
709
+ def __getitem__(self, n):
710
+ weight = self._weight
711
+ nbrs = self._succ[n]
712
+ if weight is None:
713
+ return sum(len(data) for data in nbrs.values())
714
+ # edge weighted graph - degree is sum of nbr edge weights
715
+ return sum(
716
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
717
+ )
718
+
719
+ def __iter__(self):
720
+ weight = self._weight
721
+ if weight is None:
722
+ for n in self._nodes:
723
+ nbrs = self._succ[n]
724
+ deg = sum(len(data) for data in nbrs.values())
725
+ yield (n, deg)
726
+ else:
727
+ for n in self._nodes:
728
+ nbrs = self._succ[n]
729
+ deg = sum(
730
+ d.get(weight, 1)
731
+ for key_dict in nbrs.values()
732
+ for d in key_dict.values()
733
+ )
734
+ yield (n, deg)
735
+
736
+
737
+ # EdgeDataViews
738
+ class OutEdgeDataView:
739
+ """EdgeDataView for outward edges of DiGraph; See EdgeDataView"""
740
+
741
+ __slots__ = (
742
+ "_viewer",
743
+ "_nbunch",
744
+ "_data",
745
+ "_default",
746
+ "_adjdict",
747
+ "_nodes_nbrs",
748
+ "_report",
749
+ )
750
+
751
+ def __getstate__(self):
752
+ return {
753
+ "viewer": self._viewer,
754
+ "nbunch": self._nbunch,
755
+ "data": self._data,
756
+ "default": self._default,
757
+ }
758
+
759
+ def __setstate__(self, state):
760
+ self.__init__(**state)
761
+
762
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None):
763
+ self._viewer = viewer
764
+ adjdict = self._adjdict = viewer._adjdict
765
+ if nbunch is None:
766
+ self._nodes_nbrs = adjdict.items
767
+ else:
768
+ # dict retains order of nodes but acts like a set
769
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
770
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
771
+ self._nbunch = nbunch
772
+ self._data = data
773
+ self._default = default
774
+ # Set _report based on data and default
775
+ if data is True:
776
+ self._report = lambda n, nbr, dd: (n, nbr, dd)
777
+ elif data is False:
778
+ self._report = lambda n, nbr, dd: (n, nbr)
779
+ else: # data is attribute name
780
+ self._report = (
781
+ lambda n, nbr, dd: (n, nbr, dd[data])
782
+ if data in dd
783
+ else (n, nbr, default)
784
+ )
785
+
786
+ def __len__(self):
787
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
788
+
789
+ def __iter__(self):
790
+ return (
791
+ self._report(n, nbr, dd)
792
+ for n, nbrs in self._nodes_nbrs()
793
+ for nbr, dd in nbrs.items()
794
+ )
795
+
796
+ def __contains__(self, e):
797
+ u, v = e[:2]
798
+ if self._nbunch is not None and u not in self._nbunch:
799
+ return False # this edge doesn't start in nbunch
800
+ try:
801
+ ddict = self._adjdict[u][v]
802
+ except KeyError:
803
+ return False
804
+ return e == self._report(u, v, ddict)
805
+
806
+ def __str__(self):
807
+ return str(list(self))
808
+
809
+ def __repr__(self):
810
+ return f"{self.__class__.__name__}({list(self)})"
811
+
812
+
813
+ class EdgeDataView(OutEdgeDataView):
814
+ """A EdgeDataView class for edges of Graph
815
+
816
+ This view is primarily used to iterate over the edges reporting
817
+ edges as node-tuples with edge data optionally reported. The
818
+ argument `nbunch` allows restriction to edges incident to nodes
819
+ in that container/singleton. The default (nbunch=None)
820
+ reports all edges. The arguments `data` and `default` control
821
+ what edge data is reported. The default `data is False` reports
822
+ only node-tuples for each edge. If `data is True` the entire edge
823
+ data dict is returned. Otherwise `data` is assumed to hold the name
824
+ of the edge attribute to report with default `default` if that
825
+ edge attribute is not present.
826
+
827
+ Parameters
828
+ ----------
829
+ nbunch : container of nodes, node or None (default None)
830
+ data : False, True or string (default False)
831
+ default : default value (default None)
832
+
833
+ Examples
834
+ --------
835
+ >>> G = nx.path_graph(3)
836
+ >>> G.add_edge(1, 2, foo="bar")
837
+ >>> list(G.edges(data="foo", default="biz"))
838
+ [(0, 1, 'biz'), (1, 2, 'bar')]
839
+ >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz")
840
+ """
841
+
842
+ __slots__ = ()
843
+
844
+ def __len__(self):
845
+ return sum(1 for e in self)
846
+
847
+ def __iter__(self):
848
+ seen = {}
849
+ for n, nbrs in self._nodes_nbrs():
850
+ for nbr, dd in nbrs.items():
851
+ if nbr not in seen:
852
+ yield self._report(n, nbr, dd)
853
+ seen[n] = 1
854
+ del seen
855
+
856
+ def __contains__(self, e):
857
+ u, v = e[:2]
858
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
859
+ return False # this edge doesn't start and it doesn't end in nbunch
860
+ try:
861
+ ddict = self._adjdict[u][v]
862
+ except KeyError:
863
+ return False
864
+ return e == self._report(u, v, ddict)
865
+
866
+
867
+ class InEdgeDataView(OutEdgeDataView):
868
+ """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView"""
869
+
870
+ __slots__ = ()
871
+
872
+ def __iter__(self):
873
+ return (
874
+ self._report(nbr, n, dd)
875
+ for n, nbrs in self._nodes_nbrs()
876
+ for nbr, dd in nbrs.items()
877
+ )
878
+
879
+ def __contains__(self, e):
880
+ u, v = e[:2]
881
+ if self._nbunch is not None and v not in self._nbunch:
882
+ return False # this edge doesn't end in nbunch
883
+ try:
884
+ ddict = self._adjdict[v][u]
885
+ except KeyError:
886
+ return False
887
+ return e == self._report(u, v, ddict)
888
+
889
+
890
+ class OutMultiEdgeDataView(OutEdgeDataView):
891
+ """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
892
+
893
+ __slots__ = ("keys",)
894
+
895
+ def __getstate__(self):
896
+ return {
897
+ "viewer": self._viewer,
898
+ "nbunch": self._nbunch,
899
+ "keys": self.keys,
900
+ "data": self._data,
901
+ "default": self._default,
902
+ }
903
+
904
+ def __setstate__(self, state):
905
+ self.__init__(**state)
906
+
907
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None, keys=False):
908
+ self._viewer = viewer
909
+ adjdict = self._adjdict = viewer._adjdict
910
+ self.keys = keys
911
+ if nbunch is None:
912
+ self._nodes_nbrs = adjdict.items
913
+ else:
914
+ # dict retains order of nodes but acts like a set
915
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
916
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
917
+ self._nbunch = nbunch
918
+ self._data = data
919
+ self._default = default
920
+ # Set _report based on data and default
921
+ if data is True:
922
+ if keys is True:
923
+ self._report = lambda n, nbr, k, dd: (n, nbr, k, dd)
924
+ else:
925
+ self._report = lambda n, nbr, k, dd: (n, nbr, dd)
926
+ elif data is False:
927
+ if keys is True:
928
+ self._report = lambda n, nbr, k, dd: (n, nbr, k)
929
+ else:
930
+ self._report = lambda n, nbr, k, dd: (n, nbr)
931
+ else: # data is attribute name
932
+ if keys is True:
933
+ self._report = (
934
+ lambda n, nbr, k, dd: (n, nbr, k, dd[data])
935
+ if data in dd
936
+ else (n, nbr, k, default)
937
+ )
938
+ else:
939
+ self._report = (
940
+ lambda n, nbr, k, dd: (n, nbr, dd[data])
941
+ if data in dd
942
+ else (n, nbr, default)
943
+ )
944
+
945
+ def __len__(self):
946
+ return sum(1 for e in self)
947
+
948
+ def __iter__(self):
949
+ return (
950
+ self._report(n, nbr, k, dd)
951
+ for n, nbrs in self._nodes_nbrs()
952
+ for nbr, kd in nbrs.items()
953
+ for k, dd in kd.items()
954
+ )
955
+
956
+ def __contains__(self, e):
957
+ u, v = e[:2]
958
+ if self._nbunch is not None and u not in self._nbunch:
959
+ return False # this edge doesn't start in nbunch
960
+ try:
961
+ kdict = self._adjdict[u][v]
962
+ except KeyError:
963
+ return False
964
+ if self.keys is True:
965
+ k = e[2]
966
+ try:
967
+ dd = kdict[k]
968
+ except KeyError:
969
+ return False
970
+ return e == self._report(u, v, k, dd)
971
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
972
+
973
+
974
+ class MultiEdgeDataView(OutMultiEdgeDataView):
975
+ """An EdgeDataView class for edges of MultiGraph; See EdgeDataView"""
976
+
977
+ __slots__ = ()
978
+
979
+ def __iter__(self):
980
+ seen = {}
981
+ for n, nbrs in self._nodes_nbrs():
982
+ for nbr, kd in nbrs.items():
983
+ if nbr not in seen:
984
+ for k, dd in kd.items():
985
+ yield self._report(n, nbr, k, dd)
986
+ seen[n] = 1
987
+ del seen
988
+
989
+ def __contains__(self, e):
990
+ u, v = e[:2]
991
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
992
+ return False # this edge doesn't start and doesn't end in nbunch
993
+ try:
994
+ kdict = self._adjdict[u][v]
995
+ except KeyError:
996
+ try:
997
+ kdict = self._adjdict[v][u]
998
+ except KeyError:
999
+ return False
1000
+ if self.keys is True:
1001
+ k = e[2]
1002
+ try:
1003
+ dd = kdict[k]
1004
+ except KeyError:
1005
+ return False
1006
+ return e == self._report(u, v, k, dd)
1007
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1008
+
1009
+
1010
+ class InMultiEdgeDataView(OutMultiEdgeDataView):
1011
+ """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView"""
1012
+
1013
+ __slots__ = ()
1014
+
1015
+ def __iter__(self):
1016
+ return (
1017
+ self._report(nbr, n, k, dd)
1018
+ for n, nbrs in self._nodes_nbrs()
1019
+ for nbr, kd in nbrs.items()
1020
+ for k, dd in kd.items()
1021
+ )
1022
+
1023
+ def __contains__(self, e):
1024
+ u, v = e[:2]
1025
+ if self._nbunch is not None and v not in self._nbunch:
1026
+ return False # this edge doesn't end in nbunch
1027
+ try:
1028
+ kdict = self._adjdict[v][u]
1029
+ except KeyError:
1030
+ return False
1031
+ if self.keys is True:
1032
+ k = e[2]
1033
+ dd = kdict[k]
1034
+ return e == self._report(u, v, k, dd)
1035
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1036
+
1037
+
1038
+ # EdgeViews have set operations and no data reported
1039
+ class OutEdgeView(Set, Mapping):
1040
+ """A EdgeView class for outward edges of a DiGraph"""
1041
+
1042
+ __slots__ = ("_adjdict", "_graph", "_nodes_nbrs")
1043
+
1044
+ def __getstate__(self):
1045
+ return {"_graph": self._graph, "_adjdict": self._adjdict}
1046
+
1047
+ def __setstate__(self, state):
1048
+ self._graph = state["_graph"]
1049
+ self._adjdict = state["_adjdict"]
1050
+ self._nodes_nbrs = self._adjdict.items
1051
+
1052
+ @classmethod
1053
+ def _from_iterable(cls, it):
1054
+ return set(it)
1055
+
1056
+ dataview = OutEdgeDataView
1057
+
1058
+ def __init__(self, G):
1059
+ self._graph = G
1060
+ self._adjdict = G._succ if hasattr(G, "succ") else G._adj
1061
+ self._nodes_nbrs = self._adjdict.items
1062
+
1063
+ # Set methods
1064
+ def __len__(self):
1065
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
1066
+
1067
+ def __iter__(self):
1068
+ for n, nbrs in self._nodes_nbrs():
1069
+ for nbr in nbrs:
1070
+ yield (n, nbr)
1071
+
1072
+ def __contains__(self, e):
1073
+ try:
1074
+ u, v = e
1075
+ return v in self._adjdict[u]
1076
+ except KeyError:
1077
+ return False
1078
+
1079
+ # Mapping Methods
1080
+ def __getitem__(self, e):
1081
+ if isinstance(e, slice):
1082
+ raise nx.NetworkXError(
1083
+ f"{type(self).__name__} does not support slicing, "
1084
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1085
+ )
1086
+ u, v = e
1087
+ try:
1088
+ return self._adjdict[u][v]
1089
+ except KeyError as ex: # Customize msg to indicate exception origin
1090
+ raise KeyError(f"The edge {e} is not in the graph.")
1091
+
1092
+ # EdgeDataView methods
1093
+ def __call__(self, nbunch=None, data=False, *, default=None):
1094
+ if nbunch is None and data is False:
1095
+ return self
1096
+ return self.dataview(self, nbunch, data, default=default)
1097
+
1098
+ def data(self, data=True, default=None, nbunch=None):
1099
+ """
1100
+ Return a read-only view of edge data.
1101
+
1102
+ Parameters
1103
+ ----------
1104
+ data : bool or edge attribute key
1105
+ If ``data=True``, then the data view maps each edge to a dictionary
1106
+ containing all of its attributes. If `data` is a key in the edge
1107
+ dictionary, then the data view maps each edge to its value for
1108
+ the keyed attribute. In this case, if the edge doesn't have the
1109
+ attribute, the `default` value is returned.
1110
+ default : object, default=None
1111
+ The value used when an edge does not have a specific attribute
1112
+ nbunch : container of nodes, optional (default=None)
1113
+ Allows restriction to edges only involving certain nodes. All edges
1114
+ are considered by default.
1115
+
1116
+ Returns
1117
+ -------
1118
+ dataview
1119
+ Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView`
1120
+ for DiGraphs, `MultiEdgeDataView` for MultiGraphs and
1121
+ `OutMultiEdgeDataView` for MultiDiGraphs.
1122
+
1123
+ Notes
1124
+ -----
1125
+ If ``data=False``, returns an `EdgeView` without any edge data.
1126
+
1127
+ See Also
1128
+ --------
1129
+ EdgeDataView
1130
+ OutEdgeDataView
1131
+ MultiEdgeDataView
1132
+ OutMultiEdgeDataView
1133
+
1134
+ Examples
1135
+ --------
1136
+ >>> G = nx.Graph()
1137
+ >>> G.add_edges_from(
1138
+ ... [
1139
+ ... (0, 1, {"dist": 3, "capacity": 20}),
1140
+ ... (1, 2, {"dist": 4}),
1141
+ ... (2, 0, {"dist": 5}),
1142
+ ... ]
1143
+ ... )
1144
+
1145
+ Accessing edge data with ``data=True`` (the default) returns an
1146
+ edge data view object listing each edge with all of its attributes:
1147
+
1148
+ >>> G.edges.data()
1149
+ EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})])
1150
+
1151
+ If `data` represents a key in the edge attribute dict, a dataview listing
1152
+ each edge with its value for that specific key is returned:
1153
+
1154
+ >>> G.edges.data("dist")
1155
+ EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)])
1156
+
1157
+ `nbunch` can be used to limit the edges:
1158
+
1159
+ >>> G.edges.data("dist", nbunch=[0])
1160
+ EdgeDataView([(0, 1, 3), (0, 2, 5)])
1161
+
1162
+ If a specific key is not found in an edge attribute dict, the value
1163
+ specified by `default` is used:
1164
+
1165
+ >>> G.edges.data("capacity")
1166
+ EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)])
1167
+
1168
+ Note that there is no check that the `data` key is present in any of
1169
+ the edge attribute dictionaries:
1170
+
1171
+ >>> G.edges.data("speed")
1172
+ EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)])
1173
+ """
1174
+ if nbunch is None and data is False:
1175
+ return self
1176
+ return self.dataview(self, nbunch, data, default=default)
1177
+
1178
+ # String Methods
1179
+ def __str__(self):
1180
+ return str(list(self))
1181
+
1182
+ def __repr__(self):
1183
+ return f"{self.__class__.__name__}({list(self)})"
1184
+
1185
+
1186
+ class EdgeView(OutEdgeView):
1187
+ """A EdgeView class for edges of a Graph
1188
+
1189
+ This densely packed View allows iteration over edges, data lookup
1190
+ like a dict and set operations on edges represented by node-tuples.
1191
+ In addition, edge data can be controlled by calling this object
1192
+ possibly creating an EdgeDataView. Typically edges are iterated over
1193
+ and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples
1194
+ for multigraphs. Those edge representations can also be using to
1195
+ lookup the data dict for any edge. Set operations also are available
1196
+ where those tuples are the elements of the set.
1197
+ Calling this object with optional arguments `data`, `default` and `keys`
1198
+ controls the form of the tuple (see EdgeDataView). Optional argument
1199
+ `nbunch` allows restriction to edges only involving certain nodes.
1200
+
1201
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
1202
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
1203
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
1204
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above.
1205
+
1206
+ Parameters
1207
+ ==========
1208
+ graph : NetworkX graph-like class
1209
+ nbunch : (default= all nodes in graph) only report edges with these nodes
1210
+ keys : (only for MultiGraph. default=False) report edge key in tuple
1211
+ data : bool or string (default=False) see above
1212
+ default : object (default=None)
1213
+
1214
+ Examples
1215
+ ========
1216
+ >>> G = nx.path_graph(4)
1217
+ >>> EV = G.edges()
1218
+ >>> (2, 3) in EV
1219
+ True
1220
+ >>> for u, v in EV:
1221
+ ... print((u, v))
1222
+ (0, 1)
1223
+ (1, 2)
1224
+ (2, 3)
1225
+ >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)}
1226
+
1227
+ >>> EVdata = G.edges(data="color", default="aqua")
1228
+ >>> G.add_edge(2, 3, color="blue")
1229
+ >>> assert (2, 3, "blue") in EVdata
1230
+ >>> for u, v, c in EVdata:
1231
+ ... print(f"({u}, {v}) has color: {c}")
1232
+ (0, 1) has color: aqua
1233
+ (1, 2) has color: aqua
1234
+ (2, 3) has color: blue
1235
+
1236
+ >>> EVnbunch = G.edges(nbunch=2)
1237
+ >>> assert (2, 3) in EVnbunch
1238
+ >>> assert (0, 1) not in EVnbunch
1239
+ >>> for u, v in EVnbunch:
1240
+ ... assert u == 2 or v == 2
1241
+
1242
+ >>> MG = nx.path_graph(4, create_using=nx.MultiGraph)
1243
+ >>> EVmulti = MG.edges(keys=True)
1244
+ >>> (2, 3, 0) in EVmulti
1245
+ True
1246
+ >>> (2, 3) in EVmulti # 2-tuples work even when keys is True
1247
+ True
1248
+ >>> key = MG.add_edge(2, 3)
1249
+ >>> for u, v, k in EVmulti:
1250
+ ... print((u, v, k))
1251
+ (0, 1, 0)
1252
+ (1, 2, 0)
1253
+ (2, 3, 0)
1254
+ (2, 3, 1)
1255
+ """
1256
+
1257
+ __slots__ = ()
1258
+
1259
+ dataview = EdgeDataView
1260
+
1261
+ def __len__(self):
1262
+ num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs())
1263
+ return sum(num_nbrs) // 2
1264
+
1265
+ def __iter__(self):
1266
+ seen = {}
1267
+ for n, nbrs in self._nodes_nbrs():
1268
+ for nbr in list(nbrs):
1269
+ if nbr not in seen:
1270
+ yield (n, nbr)
1271
+ seen[n] = 1
1272
+ del seen
1273
+
1274
+ def __contains__(self, e):
1275
+ try:
1276
+ u, v = e[:2]
1277
+ return v in self._adjdict[u] or u in self._adjdict[v]
1278
+ except (KeyError, ValueError):
1279
+ return False
1280
+
1281
+
1282
+ class InEdgeView(OutEdgeView):
1283
+ """A EdgeView class for inward edges of a DiGraph"""
1284
+
1285
+ __slots__ = ()
1286
+
1287
+ def __setstate__(self, state):
1288
+ self._graph = state["_graph"]
1289
+ self._adjdict = state["_adjdict"]
1290
+ self._nodes_nbrs = self._adjdict.items
1291
+
1292
+ dataview = InEdgeDataView
1293
+
1294
+ def __init__(self, G):
1295
+ self._graph = G
1296
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1297
+ self._nodes_nbrs = self._adjdict.items
1298
+
1299
+ def __iter__(self):
1300
+ for n, nbrs in self._nodes_nbrs():
1301
+ for nbr in nbrs:
1302
+ yield (nbr, n)
1303
+
1304
+ def __contains__(self, e):
1305
+ try:
1306
+ u, v = e
1307
+ return u in self._adjdict[v]
1308
+ except KeyError:
1309
+ return False
1310
+
1311
+ def __getitem__(self, e):
1312
+ if isinstance(e, slice):
1313
+ raise nx.NetworkXError(
1314
+ f"{type(self).__name__} does not support slicing, "
1315
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1316
+ )
1317
+ u, v = e
1318
+ return self._adjdict[v][u]
1319
+
1320
+
1321
+ class OutMultiEdgeView(OutEdgeView):
1322
+ """A EdgeView class for outward edges of a MultiDiGraph"""
1323
+
1324
+ __slots__ = ()
1325
+
1326
+ dataview = OutMultiEdgeDataView
1327
+
1328
+ def __len__(self):
1329
+ return sum(
1330
+ len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items()
1331
+ )
1332
+
1333
+ def __iter__(self):
1334
+ for n, nbrs in self._nodes_nbrs():
1335
+ for nbr, kdict in nbrs.items():
1336
+ for key in kdict:
1337
+ yield (n, nbr, key)
1338
+
1339
+ def __contains__(self, e):
1340
+ N = len(e)
1341
+ if N == 3:
1342
+ u, v, k = e
1343
+ elif N == 2:
1344
+ u, v = e
1345
+ k = 0
1346
+ else:
1347
+ raise ValueError("MultiEdge must have length 2 or 3")
1348
+ try:
1349
+ return k in self._adjdict[u][v]
1350
+ except KeyError:
1351
+ return False
1352
+
1353
+ def __getitem__(self, e):
1354
+ if isinstance(e, slice):
1355
+ raise nx.NetworkXError(
1356
+ f"{type(self).__name__} does not support slicing, "
1357
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1358
+ )
1359
+ u, v, k = e
1360
+ return self._adjdict[u][v][k]
1361
+
1362
+ def __call__(self, nbunch=None, data=False, *, default=None, keys=False):
1363
+ if nbunch is None and data is False and keys is True:
1364
+ return self
1365
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1366
+
1367
+ def data(self, data=True, default=None, nbunch=None, keys=False):
1368
+ if nbunch is None and data is False and keys is True:
1369
+ return self
1370
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1371
+
1372
+
1373
+ class MultiEdgeView(OutMultiEdgeView):
1374
+ """A EdgeView class for edges of a MultiGraph"""
1375
+
1376
+ __slots__ = ()
1377
+
1378
+ dataview = MultiEdgeDataView
1379
+
1380
+ def __len__(self):
1381
+ return sum(1 for e in self)
1382
+
1383
+ def __iter__(self):
1384
+ seen = {}
1385
+ for n, nbrs in self._nodes_nbrs():
1386
+ for nbr, kd in nbrs.items():
1387
+ if nbr not in seen:
1388
+ for k, dd in kd.items():
1389
+ yield (n, nbr, k)
1390
+ seen[n] = 1
1391
+ del seen
1392
+
1393
+
1394
+ class InMultiEdgeView(OutMultiEdgeView):
1395
+ """A EdgeView class for inward edges of a MultiDiGraph"""
1396
+
1397
+ __slots__ = ()
1398
+
1399
+ def __setstate__(self, state):
1400
+ self._graph = state["_graph"]
1401
+ self._adjdict = state["_adjdict"]
1402
+ self._nodes_nbrs = self._adjdict.items
1403
+
1404
+ dataview = InMultiEdgeDataView
1405
+
1406
+ def __init__(self, G):
1407
+ self._graph = G
1408
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1409
+ self._nodes_nbrs = self._adjdict.items
1410
+
1411
+ def __iter__(self):
1412
+ for n, nbrs in self._nodes_nbrs():
1413
+ for nbr, kdict in nbrs.items():
1414
+ for key in kdict:
1415
+ yield (nbr, n, key)
1416
+
1417
+ def __contains__(self, e):
1418
+ N = len(e)
1419
+ if N == 3:
1420
+ u, v, k = e
1421
+ elif N == 2:
1422
+ u, v = e
1423
+ k = 0
1424
+ else:
1425
+ raise ValueError("MultiEdge must have length 2 or 3")
1426
+ try:
1427
+ return k in self._adjdict[v][u]
1428
+ except KeyError:
1429
+ return False
1430
+
1431
+ def __getitem__(self, e):
1432
+ if isinstance(e, slice):
1433
+ raise nx.NetworkXError(
1434
+ f"{type(self).__name__} does not support slicing, "
1435
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1436
+ )
1437
+ u, v, k = e
1438
+ return self._adjdict[v][u][k]
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_coreviews.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_reportviews.cpython-310.pyc ADDED
Binary file (41.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_special.cpython-310.pyc ADDED
Binary file (5.17 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LoopbackDispatcher:
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
73
+ "lexicographical_topological_sort",
74
+ "topological_generations",
75
+ "topological_sort",
76
+ # Sensitive tests (iteration order matters)
77
+ "dfs_labeled_edges",
78
+ }:
79
+ return graph
80
+ if isinstance(graph, NodeView):
81
+ # Convert to a Graph with only nodes (no edges)
82
+ new_graph = Graph()
83
+ new_graph.add_nodes_from(graph.items())
84
+ graph = new_graph
85
+ G = LoopbackGraph()
86
+ elif not isinstance(graph, Graph):
87
+ raise TypeError(
88
+ f"Bad type for graph argument {graph_name} in {name}: {type(graph)}"
89
+ )
90
+ elif graph.__class__ in {Graph, LoopbackGraph}:
91
+ G = LoopbackGraph()
92
+ elif graph.__class__ in {DiGraph, LoopbackDiGraph}:
93
+ G = LoopbackDiGraph()
94
+ elif graph.__class__ in {MultiGraph, LoopbackMultiGraph}:
95
+ G = LoopbackMultiGraph()
96
+ elif graph.__class__ in {MultiDiGraph, LoopbackMultiDiGraph}:
97
+ G = LoopbackMultiDiGraph()
98
+ elif graph.__class__ in {PlanarEmbedding, LoopbackPlanarEmbedding}:
99
+ G = LoopbackDiGraph() # or LoopbackPlanarEmbedding
100
+ else:
101
+ # It would be nice to be able to convert _AntiGraph to a regular Graph
102
+ # nx.algorithms.approximation.kcomponents._AntiGraph
103
+ # nx.algorithms.tree.branchings.MultiDiGraph_EdgeKey
104
+ # nx.classes.tests.test_multidigraph.MultiDiGraphSubClass
105
+ # nx.classes.tests.test_multigraph.MultiGraphSubClass
106
+ G = graph.__class__()
107
+
108
+ if preserve_graph_attrs:
109
+ G.graph.update(graph.graph)
110
+
111
+ if preserve_node_attrs:
112
+ G.add_nodes_from(graph.nodes(data=True))
113
+ elif node_attrs:
114
+ G.add_nodes_from(
115
+ (
116
+ node,
117
+ {
118
+ k: datadict.get(k, default)
119
+ for k, default in node_attrs.items()
120
+ if default is not None or k in datadict
121
+ },
122
+ )
123
+ for node, datadict in graph.nodes(data=True)
124
+ )
125
+ else:
126
+ G.add_nodes_from(graph)
127
+
128
+ if graph.is_multigraph():
129
+ if preserve_edge_attrs:
130
+ G.add_edges_from(
131
+ (u, v, key, datadict)
132
+ for u, nbrs in graph._adj.items()
133
+ for v, keydict in nbrs.items()
134
+ for key, datadict in keydict.items()
135
+ )
136
+ elif edge_attrs:
137
+ G.add_edges_from(
138
+ (
139
+ u,
140
+ v,
141
+ key,
142
+ {
143
+ k: datadict.get(k, default)
144
+ for k, default in edge_attrs.items()
145
+ if default is not None or k in datadict
146
+ },
147
+ )
148
+ for u, nbrs in graph._adj.items()
149
+ for v, keydict in nbrs.items()
150
+ for key, datadict in keydict.items()
151
+ )
152
+ else:
153
+ G.add_edges_from(
154
+ (u, v, key, {})
155
+ for u, nbrs in graph._adj.items()
156
+ for v, keydict in nbrs.items()
157
+ for key, datadict in keydict.items()
158
+ )
159
+ elif preserve_edge_attrs:
160
+ G.add_edges_from(graph.edges(data=True))
161
+ elif edge_attrs:
162
+ G.add_edges_from(
163
+ (
164
+ u,
165
+ v,
166
+ {
167
+ k: datadict.get(k, default)
168
+ for k, default in edge_attrs.items()
169
+ if default is not None or k in datadict
170
+ },
171
+ )
172
+ for u, v, datadict in graph.edges(data=True)
173
+ )
174
+ else:
175
+ G.add_edges_from(graph.edges)
176
+ return G
177
+
178
+ @staticmethod
179
+ def convert_to_nx(obj, *, name=None):
180
+ return obj
181
+
182
+ @staticmethod
183
+ def on_start_tests(items):
184
+ # Verify that items can be xfailed
185
+ for item in items:
186
+ assert hasattr(item, "add_marker")
187
+
188
+ def can_run(self, name, args, kwargs):
189
+ # It is unnecessary to define this function if algorithms are fully supported.
190
+ # We include it for illustration purposes.
191
+ return hasattr(self, name)
192
+
193
+
194
+ dispatcher = LoopbackDispatcher()
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_digraph.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import nodes_equal
5
+
6
+ from .test_graph import BaseAttrGraphTester, BaseGraphTester
7
+ from .test_graph import TestEdgeSubgraph as _TestGraphEdgeSubgraph
8
+ from .test_graph import TestGraph as _TestGraph
9
+
10
+
11
+ class BaseDiGraphTester(BaseGraphTester):
12
+ def test_has_successor(self):
13
+ G = self.K3
14
+ assert G.has_successor(0, 1)
15
+ assert not G.has_successor(0, -1)
16
+
17
+ def test_successors(self):
18
+ G = self.K3
19
+ assert sorted(G.successors(0)) == [1, 2]
20
+ with pytest.raises(nx.NetworkXError):
21
+ G.successors(-1)
22
+
23
+ def test_has_predecessor(self):
24
+ G = self.K3
25
+ assert G.has_predecessor(0, 1)
26
+ assert not G.has_predecessor(0, -1)
27
+
28
+ def test_predecessors(self):
29
+ G = self.K3
30
+ assert sorted(G.predecessors(0)) == [1, 2]
31
+ with pytest.raises(nx.NetworkXError):
32
+ G.predecessors(-1)
33
+
34
+ def test_edges(self):
35
+ G = self.K3
36
+ assert sorted(G.edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
37
+ assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
38
+ assert sorted(G.edges([0, 1])) == [(0, 1), (0, 2), (1, 0), (1, 2)]
39
+ with pytest.raises(nx.NetworkXError):
40
+ G.edges(-1)
41
+
42
+ def test_out_edges(self):
43
+ G = self.K3
44
+ assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
45
+ assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
46
+ with pytest.raises(nx.NetworkXError):
47
+ G.out_edges(-1)
48
+
49
+ def test_out_edges_dir(self):
50
+ G = self.P3
51
+ assert sorted(G.out_edges()) == [(0, 1), (1, 2)]
52
+ assert sorted(G.out_edges(0)) == [(0, 1)]
53
+ assert sorted(G.out_edges(2)) == []
54
+
55
+ def test_out_edges_data(self):
56
+ G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})])
57
+ assert sorted(G.out_edges(data=True)) == [(0, 1, {"data": 0}), (1, 0, {})]
58
+ assert sorted(G.out_edges(0, data=True)) == [(0, 1, {"data": 0})]
59
+ assert sorted(G.out_edges(data="data")) == [(0, 1, 0), (1, 0, None)]
60
+ assert sorted(G.out_edges(0, data="data")) == [(0, 1, 0)]
61
+
62
+ def test_in_edges_dir(self):
63
+ G = self.P3
64
+ assert sorted(G.in_edges()) == [(0, 1), (1, 2)]
65
+ assert sorted(G.in_edges(0)) == []
66
+ assert sorted(G.in_edges(2)) == [(1, 2)]
67
+
68
+ def test_in_edges_data(self):
69
+ G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})])
70
+ assert sorted(G.in_edges(data=True)) == [(0, 1, {"data": 0}), (1, 0, {})]
71
+ assert sorted(G.in_edges(1, data=True)) == [(0, 1, {"data": 0})]
72
+ assert sorted(G.in_edges(data="data")) == [(0, 1, 0), (1, 0, None)]
73
+ assert sorted(G.in_edges(1, data="data")) == [(0, 1, 0)]
74
+
75
+ def test_degree(self):
76
+ G = self.K3
77
+ assert sorted(G.degree()) == [(0, 4), (1, 4), (2, 4)]
78
+ assert dict(G.degree()) == {0: 4, 1: 4, 2: 4}
79
+ assert G.degree(0) == 4
80
+ assert list(G.degree(iter([0]))) == [(0, 4)] # run through iterator
81
+
82
+ def test_in_degree(self):
83
+ G = self.K3
84
+ assert sorted(G.in_degree()) == [(0, 2), (1, 2), (2, 2)]
85
+ assert dict(G.in_degree()) == {0: 2, 1: 2, 2: 2}
86
+ assert G.in_degree(0) == 2
87
+ assert list(G.in_degree(iter([0]))) == [(0, 2)] # run through iterator
88
+
89
+ def test_out_degree(self):
90
+ G = self.K3
91
+ assert sorted(G.out_degree()) == [(0, 2), (1, 2), (2, 2)]
92
+ assert dict(G.out_degree()) == {0: 2, 1: 2, 2: 2}
93
+ assert G.out_degree(0) == 2
94
+ assert list(G.out_degree(iter([0]))) == [(0, 2)]
95
+
96
+ def test_size(self):
97
+ G = self.K3
98
+ assert G.size() == 6
99
+ assert G.number_of_edges() == 6
100
+
101
+ def test_to_undirected_reciprocal(self):
102
+ G = self.Graph()
103
+ G.add_edge(1, 2)
104
+ assert G.to_undirected().has_edge(1, 2)
105
+ assert not G.to_undirected(reciprocal=True).has_edge(1, 2)
106
+ G.add_edge(2, 1)
107
+ assert G.to_undirected(reciprocal=True).has_edge(1, 2)
108
+
109
+ def test_reverse_copy(self):
110
+ G = nx.DiGraph([(0, 1), (1, 2)])
111
+ R = G.reverse()
112
+ assert sorted(R.edges()) == [(1, 0), (2, 1)]
113
+ R.remove_edge(1, 0)
114
+ assert sorted(R.edges()) == [(2, 1)]
115
+ assert sorted(G.edges()) == [(0, 1), (1, 2)]
116
+
117
+ def test_reverse_nocopy(self):
118
+ G = nx.DiGraph([(0, 1), (1, 2)])
119
+ R = G.reverse(copy=False)
120
+ assert sorted(R.edges()) == [(1, 0), (2, 1)]
121
+ with pytest.raises(nx.NetworkXError):
122
+ R.remove_edge(1, 0)
123
+
124
+ def test_reverse_hashable(self):
125
+ class Foo:
126
+ pass
127
+
128
+ x = Foo()
129
+ y = Foo()
130
+ G = nx.DiGraph()
131
+ G.add_edge(x, y)
132
+ assert nodes_equal(G.nodes(), G.reverse().nodes())
133
+ assert [(y, x)] == list(G.reverse().edges())
134
+
135
+ def test_di_cache_reset(self):
136
+ G = self.K3.copy()
137
+ old_succ = G.succ
138
+ assert id(G.succ) == id(old_succ)
139
+ old_adj = G.adj
140
+ assert id(G.adj) == id(old_adj)
141
+
142
+ G._succ = {}
143
+ assert id(G.succ) != id(old_succ)
144
+ assert id(G.adj) != id(old_adj)
145
+
146
+ old_pred = G.pred
147
+ assert id(G.pred) == id(old_pred)
148
+ G._pred = {}
149
+ assert id(G.pred) != id(old_pred)
150
+
151
+ def test_di_attributes_cached(self):
152
+ G = self.K3.copy()
153
+ assert id(G.in_edges) == id(G.in_edges)
154
+ assert id(G.out_edges) == id(G.out_edges)
155
+ assert id(G.in_degree) == id(G.in_degree)
156
+ assert id(G.out_degree) == id(G.out_degree)
157
+ assert id(G.succ) == id(G.succ)
158
+ assert id(G.pred) == id(G.pred)
159
+
160
+
161
+ class BaseAttrDiGraphTester(BaseDiGraphTester, BaseAttrGraphTester):
162
+ def test_edges_data(self):
163
+ G = self.K3
164
+ all_edges = [
165
+ (0, 1, {}),
166
+ (0, 2, {}),
167
+ (1, 0, {}),
168
+ (1, 2, {}),
169
+ (2, 0, {}),
170
+ (2, 1, {}),
171
+ ]
172
+ assert sorted(G.edges(data=True)) == all_edges
173
+ assert sorted(G.edges(0, data=True)) == all_edges[:2]
174
+ assert sorted(G.edges([0, 1], data=True)) == all_edges[:4]
175
+ with pytest.raises(nx.NetworkXError):
176
+ G.edges(-1, True)
177
+
178
+ def test_in_degree_weighted(self):
179
+ G = self.K3.copy()
180
+ G.add_edge(0, 1, weight=0.3, other=1.2)
181
+ assert sorted(G.in_degree(weight="weight")) == [(0, 2), (1, 1.3), (2, 2)]
182
+ assert dict(G.in_degree(weight="weight")) == {0: 2, 1: 1.3, 2: 2}
183
+ assert G.in_degree(1, weight="weight") == 1.3
184
+ assert sorted(G.in_degree(weight="other")) == [(0, 2), (1, 2.2), (2, 2)]
185
+ assert dict(G.in_degree(weight="other")) == {0: 2, 1: 2.2, 2: 2}
186
+ assert G.in_degree(1, weight="other") == 2.2
187
+ assert list(G.in_degree(iter([1]), weight="other")) == [(1, 2.2)]
188
+
189
+ def test_out_degree_weighted(self):
190
+ G = self.K3.copy()
191
+ G.add_edge(0, 1, weight=0.3, other=1.2)
192
+ assert sorted(G.out_degree(weight="weight")) == [(0, 1.3), (1, 2), (2, 2)]
193
+ assert dict(G.out_degree(weight="weight")) == {0: 1.3, 1: 2, 2: 2}
194
+ assert G.out_degree(0, weight="weight") == 1.3
195
+ assert sorted(G.out_degree(weight="other")) == [(0, 2.2), (1, 2), (2, 2)]
196
+ assert dict(G.out_degree(weight="other")) == {0: 2.2, 1: 2, 2: 2}
197
+ assert G.out_degree(0, weight="other") == 2.2
198
+ assert list(G.out_degree(iter([0]), weight="other")) == [(0, 2.2)]
199
+
200
+
201
+ class TestDiGraph(BaseAttrDiGraphTester, _TestGraph):
202
+ """Tests specific to dict-of-dict-of-dict digraph data structure"""
203
+
204
+ def setup_method(self):
205
+ self.Graph = nx.DiGraph
206
+ # build dict-of-dict-of-dict K3
207
+ ed1, ed2, ed3, ed4, ed5, ed6 = ({}, {}, {}, {}, {}, {})
208
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
209
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
210
+ self.k3nodes = [0, 1, 2]
211
+ self.K3 = self.Graph()
212
+ self.K3._succ = self.k3adj # K3._adj is synced with K3._succ
213
+ self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
214
+ self.K3._node = {}
215
+ self.K3._node[0] = {}
216
+ self.K3._node[1] = {}
217
+ self.K3._node[2] = {}
218
+
219
+ ed1, ed2 = ({}, {})
220
+ self.P3 = self.Graph()
221
+ self.P3._succ = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
222
+ self.P3._pred = {0: {}, 1: {0: ed1}, 2: {1: ed2}}
223
+ # P3._adj is synced with P3._succ
224
+ self.P3._node = {}
225
+ self.P3._node[0] = {}
226
+ self.P3._node[1] = {}
227
+ self.P3._node[2] = {}
228
+
229
+ def test_data_input(self):
230
+ G = self.Graph({1: [2], 2: [1]}, name="test")
231
+ assert G.name == "test"
232
+ assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
233
+ assert sorted(G.succ.items()) == [(1, {2: {}}), (2, {1: {}})]
234
+ assert sorted(G.pred.items()) == [(1, {2: {}}), (2, {1: {}})]
235
+
236
+ def test_add_edge(self):
237
+ G = self.Graph()
238
+ G.add_edge(0, 1)
239
+ assert G.adj == {0: {1: {}}, 1: {}}
240
+ assert G.succ == {0: {1: {}}, 1: {}}
241
+ assert G.pred == {0: {}, 1: {0: {}}}
242
+ G = self.Graph()
243
+ G.add_edge(*(0, 1))
244
+ assert G.adj == {0: {1: {}}, 1: {}}
245
+ assert G.succ == {0: {1: {}}, 1: {}}
246
+ assert G.pred == {0: {}, 1: {0: {}}}
247
+ with pytest.raises(ValueError, match="None cannot be a node"):
248
+ G.add_edge(None, 3)
249
+
250
+ def test_add_edges_from(self):
251
+ G = self.Graph()
252
+ G.add_edges_from([(0, 1), (0, 2, {"data": 3})], data=2)
253
+ assert G.adj == {0: {1: {"data": 2}, 2: {"data": 3}}, 1: {}, 2: {}}
254
+ assert G.succ == {0: {1: {"data": 2}, 2: {"data": 3}}, 1: {}, 2: {}}
255
+ assert G.pred == {0: {}, 1: {0: {"data": 2}}, 2: {0: {"data": 3}}}
256
+
257
+ with pytest.raises(nx.NetworkXError):
258
+ G.add_edges_from([(0,)]) # too few in tuple
259
+ with pytest.raises(nx.NetworkXError):
260
+ G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
261
+ with pytest.raises(TypeError):
262
+ G.add_edges_from([0]) # not a tuple
263
+ with pytest.raises(ValueError, match="None cannot be a node"):
264
+ G.add_edges_from([(None, 3), (3, 2)])
265
+
266
+ def test_remove_edge(self):
267
+ G = self.K3.copy()
268
+ G.remove_edge(0, 1)
269
+ assert G.succ == {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}}
270
+ assert G.pred == {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
271
+ with pytest.raises(nx.NetworkXError):
272
+ G.remove_edge(-1, 0)
273
+
274
+ def test_remove_edges_from(self):
275
+ G = self.K3.copy()
276
+ G.remove_edges_from([(0, 1)])
277
+ assert G.succ == {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}}
278
+ assert G.pred == {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
279
+ G.remove_edges_from([(0, 0)]) # silent fail
280
+
281
+ def test_clear(self):
282
+ G = self.K3
283
+ G.graph["name"] = "K3"
284
+ G.clear()
285
+ assert list(G.nodes) == []
286
+ assert G.succ == {}
287
+ assert G.pred == {}
288
+ assert G.graph == {}
289
+
290
+ def test_clear_edges(self):
291
+ G = self.K3
292
+ G.graph["name"] = "K3"
293
+ nodes = list(G.nodes)
294
+ G.clear_edges()
295
+ assert list(G.nodes) == nodes
296
+ expected = {0: {}, 1: {}, 2: {}}
297
+ assert G.succ == expected
298
+ assert G.pred == expected
299
+ assert list(G.edges) == []
300
+ assert G.graph["name"] == "K3"
301
+
302
+
303
+ class TestEdgeSubgraph(_TestGraphEdgeSubgraph):
304
+ """Unit tests for the :meth:`DiGraph.edge_subgraph` method."""
305
+
306
+ def setup_method(self):
307
+ # Create a doubly-linked path graph on five nodes.
308
+ G = nx.DiGraph(nx.path_graph(5))
309
+ # Add some node, edge, and graph attributes.
310
+ for i in range(5):
311
+ G.nodes[i]["name"] = f"node{i}"
312
+ G.edges[0, 1]["name"] = "edge01"
313
+ G.edges[3, 4]["name"] = "edge34"
314
+ G.graph["name"] = "graph"
315
+ # Get the subgraph induced by the first and last edges.
316
+ self.G = G
317
+ self.H = G.edge_subgraph([(0, 1), (3, 4)])
318
+
319
+ def test_pred_succ(self):
320
+ """Test that nodes are added to predecessors and successors.
321
+
322
+ For more information, see GitHub issue #2370.
323
+
324
+ """
325
+ G = nx.DiGraph()
326
+ G.add_edge(0, 1)
327
+ H = G.edge_subgraph([(0, 1)])
328
+ assert list(H.predecessors(0)) == []
329
+ assert list(H.successors(0)) == [1]
330
+ assert list(H.predecessors(1)) == [0]
331
+ assert list(H.successors(1)) == []
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_digraph_historical.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Original NetworkX graph tests"""
2
+ import pytest
3
+
4
+ import networkx
5
+ import networkx as nx
6
+
7
+ from .historical_tests import HistoricalTests
8
+
9
+
10
+ class TestDiGraphHistorical(HistoricalTests):
11
+ @classmethod
12
+ def setup_class(cls):
13
+ HistoricalTests.setup_class()
14
+ cls.G = nx.DiGraph
15
+
16
+ def test_in_degree(self):
17
+ G = self.G()
18
+ G.add_nodes_from("GJK")
19
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
20
+
21
+ assert sorted(d for n, d in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2]
22
+ assert dict(G.in_degree()) == {
23
+ "A": 0,
24
+ "C": 2,
25
+ "B": 1,
26
+ "D": 2,
27
+ "G": 0,
28
+ "K": 0,
29
+ "J": 0,
30
+ }
31
+
32
+ def test_out_degree(self):
33
+ G = self.G()
34
+ G.add_nodes_from("GJK")
35
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
36
+ assert sorted(v for k, v in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2]
37
+ assert dict(G.out_degree()) == {
38
+ "A": 2,
39
+ "C": 1,
40
+ "B": 2,
41
+ "D": 0,
42
+ "G": 0,
43
+ "K": 0,
44
+ "J": 0,
45
+ }
46
+
47
+ def test_degree_digraph(self):
48
+ H = nx.DiGraph()
49
+ H.add_edges_from([(1, 24), (1, 2)])
50
+ assert sorted(d for n, d in H.in_degree([1, 24])) == [0, 1]
51
+ assert sorted(d for n, d in H.out_degree([1, 24])) == [0, 2]
52
+ assert sorted(d for n, d in H.degree([1, 24])) == [1, 2]
53
+
54
+ def test_neighbors(self):
55
+ G = self.G()
56
+ G.add_nodes_from("GJK")
57
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
58
+
59
+ assert sorted(G.neighbors("C")) == ["D"]
60
+ assert sorted(G["C"]) == ["D"]
61
+ assert sorted(G.neighbors("A")) == ["B", "C"]
62
+ pytest.raises(nx.NetworkXError, G.neighbors, "j")
63
+ pytest.raises(nx.NetworkXError, G.neighbors, "j")
64
+
65
+ def test_successors(self):
66
+ G = self.G()
67
+ G.add_nodes_from("GJK")
68
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
69
+ assert sorted(G.successors("A")) == ["B", "C"]
70
+ assert sorted(G.successors("A")) == ["B", "C"]
71
+ assert sorted(G.successors("G")) == []
72
+ assert sorted(G.successors("D")) == []
73
+ assert sorted(G.successors("G")) == []
74
+ pytest.raises(nx.NetworkXError, G.successors, "j")
75
+ pytest.raises(nx.NetworkXError, G.successors, "j")
76
+
77
+ def test_predecessors(self):
78
+ G = self.G()
79
+ G.add_nodes_from("GJK")
80
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
81
+ assert sorted(G.predecessors("C")) == ["A", "B"]
82
+ assert sorted(G.predecessors("C")) == ["A", "B"]
83
+ assert sorted(G.predecessors("G")) == []
84
+ assert sorted(G.predecessors("A")) == []
85
+ assert sorted(G.predecessors("G")) == []
86
+ assert sorted(G.predecessors("A")) == []
87
+ assert sorted(G.successors("D")) == []
88
+
89
+ pytest.raises(nx.NetworkXError, G.predecessors, "j")
90
+ pytest.raises(nx.NetworkXError, G.predecessors, "j")
91
+
92
+ def test_reverse(self):
93
+ G = nx.complete_graph(10)
94
+ H = G.to_directed()
95
+ HR = H.reverse()
96
+ assert nx.is_isomorphic(H, HR)
97
+ assert sorted(H.edges()) == sorted(HR.edges())
98
+
99
+ def test_reverse2(self):
100
+ H = nx.DiGraph()
101
+ foo = [H.add_edge(u, u + 1) for u in range(5)]
102
+ HR = H.reverse()
103
+ for u in range(5):
104
+ assert HR.has_edge(u + 1, u)
105
+
106
+ def test_reverse3(self):
107
+ H = nx.DiGraph()
108
+ H.add_nodes_from([1, 2, 3, 4])
109
+ HR = H.reverse()
110
+ assert sorted(HR.nodes()) == [1, 2, 3, 4]
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestFilterFactory:
7
+ def test_no_filter(self):
8
+ nf = nx.filters.no_filter
9
+ assert nf()
10
+ assert nf(1)
11
+ assert nf(2, 1)
12
+
13
+ def test_hide_nodes(self):
14
+ f = nx.classes.filters.hide_nodes([1, 2, 3])
15
+ assert not f(1)
16
+ assert not f(2)
17
+ assert not f(3)
18
+ assert f(4)
19
+ assert f(0)
20
+ assert f("a")
21
+ pytest.raises(TypeError, f, 1, 2)
22
+ pytest.raises(TypeError, f)
23
+
24
+ def test_show_nodes(self):
25
+ f = nx.classes.filters.show_nodes([1, 2, 3])
26
+ assert f(1)
27
+ assert f(2)
28
+ assert f(3)
29
+ assert not f(4)
30
+ assert not f(0)
31
+ assert not f("a")
32
+ pytest.raises(TypeError, f, 1, 2)
33
+ pytest.raises(TypeError, f)
34
+
35
+ def test_hide_edges(self):
36
+ factory = nx.classes.filters.hide_edges
37
+ f = factory([(1, 2), (3, 4)])
38
+ assert not f(1, 2)
39
+ assert not f(3, 4)
40
+ assert not f(4, 3)
41
+ assert f(2, 3)
42
+ assert f(0, -1)
43
+ assert f("a", "b")
44
+ pytest.raises(TypeError, f, 1, 2, 3)
45
+ pytest.raises(TypeError, f, 1)
46
+ pytest.raises(TypeError, f)
47
+ pytest.raises(TypeError, factory, [1, 2, 3])
48
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
49
+
50
+ def test_show_edges(self):
51
+ factory = nx.classes.filters.show_edges
52
+ f = factory([(1, 2), (3, 4)])
53
+ assert f(1, 2)
54
+ assert f(3, 4)
55
+ assert f(4, 3)
56
+ assert not f(2, 3)
57
+ assert not f(0, -1)
58
+ assert not f("a", "b")
59
+ pytest.raises(TypeError, f, 1, 2, 3)
60
+ pytest.raises(TypeError, f, 1)
61
+ pytest.raises(TypeError, f)
62
+ pytest.raises(TypeError, factory, [1, 2, 3])
63
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
64
+
65
+ def test_hide_diedges(self):
66
+ factory = nx.classes.filters.hide_diedges
67
+ f = factory([(1, 2), (3, 4)])
68
+ assert not f(1, 2)
69
+ assert not f(3, 4)
70
+ assert f(4, 3)
71
+ assert f(2, 3)
72
+ assert f(0, -1)
73
+ assert f("a", "b")
74
+ pytest.raises(TypeError, f, 1, 2, 3)
75
+ pytest.raises(TypeError, f, 1)
76
+ pytest.raises(TypeError, f)
77
+ pytest.raises(TypeError, factory, [1, 2, 3])
78
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
79
+
80
+ def test_show_diedges(self):
81
+ factory = nx.classes.filters.show_diedges
82
+ f = factory([(1, 2), (3, 4)])
83
+ assert f(1, 2)
84
+ assert f(3, 4)
85
+ assert not f(4, 3)
86
+ assert not f(2, 3)
87
+ assert not f(0, -1)
88
+ assert not f("a", "b")
89
+ pytest.raises(TypeError, f, 1, 2, 3)
90
+ pytest.raises(TypeError, f, 1)
91
+ pytest.raises(TypeError, f)
92
+ pytest.raises(TypeError, factory, [1, 2, 3])
93
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
94
+
95
+ def test_hide_multiedges(self):
96
+ factory = nx.classes.filters.hide_multiedges
97
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
98
+ assert not f(1, 2, 0)
99
+ assert not f(1, 2, 1)
100
+ assert f(1, 2, 2)
101
+ assert f(3, 4, 0)
102
+ assert not f(3, 4, 1)
103
+ assert not f(4, 3, 1)
104
+ assert f(4, 3, 0)
105
+ assert f(2, 3, 0)
106
+ assert f(0, -1, 0)
107
+ assert f("a", "b", 0)
108
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
109
+ pytest.raises(TypeError, f, 1, 2)
110
+ pytest.raises(TypeError, f, 1)
111
+ pytest.raises(TypeError, f)
112
+ pytest.raises(TypeError, factory, [1, 2, 3])
113
+ pytest.raises(ValueError, factory, [(1, 2)])
114
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
115
+
116
+ def test_show_multiedges(self):
117
+ factory = nx.classes.filters.show_multiedges
118
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
119
+ assert f(1, 2, 0)
120
+ assert f(1, 2, 1)
121
+ assert not f(1, 2, 2)
122
+ assert not f(3, 4, 0)
123
+ assert f(3, 4, 1)
124
+ assert f(4, 3, 1)
125
+ assert not f(4, 3, 0)
126
+ assert not f(2, 3, 0)
127
+ assert not f(0, -1, 0)
128
+ assert not f("a", "b", 0)
129
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
130
+ pytest.raises(TypeError, f, 1, 2)
131
+ pytest.raises(TypeError, f, 1)
132
+ pytest.raises(TypeError, f)
133
+ pytest.raises(TypeError, factory, [1, 2, 3])
134
+ pytest.raises(ValueError, factory, [(1, 2)])
135
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
136
+
137
+ def test_hide_multidiedges(self):
138
+ factory = nx.classes.filters.hide_multidiedges
139
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
140
+ assert not f(1, 2, 0)
141
+ assert not f(1, 2, 1)
142
+ assert f(1, 2, 2)
143
+ assert f(3, 4, 0)
144
+ assert not f(3, 4, 1)
145
+ assert f(4, 3, 1)
146
+ assert f(4, 3, 0)
147
+ assert f(2, 3, 0)
148
+ assert f(0, -1, 0)
149
+ assert f("a", "b", 0)
150
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
151
+ pytest.raises(TypeError, f, 1, 2)
152
+ pytest.raises(TypeError, f, 1)
153
+ pytest.raises(TypeError, f)
154
+ pytest.raises(TypeError, factory, [1, 2, 3])
155
+ pytest.raises(ValueError, factory, [(1, 2)])
156
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
157
+
158
+ def test_show_multidiedges(self):
159
+ factory = nx.classes.filters.show_multidiedges
160
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
161
+ assert f(1, 2, 0)
162
+ assert f(1, 2, 1)
163
+ assert not f(1, 2, 2)
164
+ assert not f(3, 4, 0)
165
+ assert f(3, 4, 1)
166
+ assert not f(4, 3, 1)
167
+ assert not f(4, 3, 0)
168
+ assert not f(2, 3, 0)
169
+ assert not f(0, -1, 0)
170
+ assert not f("a", "b", 0)
171
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
172
+ pytest.raises(TypeError, f, 1, 2)
173
+ pytest.raises(TypeError, f, 1)
174
+ pytest.raises(TypeError, f)
175
+ pytest.raises(TypeError, factory, [1, 2, 3])
176
+ pytest.raises(ValueError, factory, [(1, 2)])
177
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_function.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal, nodes_equal
7
+
8
+
9
+ def test_degree_histogram_empty():
10
+ G = nx.Graph()
11
+ assert nx.degree_histogram(G) == []
12
+
13
+
14
+ class TestFunction:
15
+ def setup_method(self):
16
+ self.G = nx.Graph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}, name="Test")
17
+ self.Gdegree = {0: 3, 1: 2, 2: 2, 3: 1, 4: 0}
18
+ self.Gnodes = list(range(5))
19
+ self.Gedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
20
+ self.DG = nx.DiGraph({0: [1, 2, 3], 1: [1, 2, 0], 4: []})
21
+ self.DGin_degree = {0: 1, 1: 2, 2: 2, 3: 1, 4: 0}
22
+ self.DGout_degree = {0: 3, 1: 3, 2: 0, 3: 0, 4: 0}
23
+ self.DGnodes = list(range(5))
24
+ self.DGedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
25
+
26
+ def test_nodes(self):
27
+ assert nodes_equal(self.G.nodes(), list(nx.nodes(self.G)))
28
+ assert nodes_equal(self.DG.nodes(), list(nx.nodes(self.DG)))
29
+
30
+ def test_edges(self):
31
+ assert edges_equal(self.G.edges(), list(nx.edges(self.G)))
32
+ assert sorted(self.DG.edges()) == sorted(nx.edges(self.DG))
33
+ assert edges_equal(
34
+ self.G.edges(nbunch=[0, 1, 3]), list(nx.edges(self.G, nbunch=[0, 1, 3]))
35
+ )
36
+ assert sorted(self.DG.edges(nbunch=[0, 1, 3])) == sorted(
37
+ nx.edges(self.DG, nbunch=[0, 1, 3])
38
+ )
39
+
40
+ def test_degree(self):
41
+ assert edges_equal(self.G.degree(), list(nx.degree(self.G)))
42
+ assert sorted(self.DG.degree()) == sorted(nx.degree(self.DG))
43
+ assert edges_equal(
44
+ self.G.degree(nbunch=[0, 1]), list(nx.degree(self.G, nbunch=[0, 1]))
45
+ )
46
+ assert sorted(self.DG.degree(nbunch=[0, 1])) == sorted(
47
+ nx.degree(self.DG, nbunch=[0, 1])
48
+ )
49
+ assert edges_equal(
50
+ self.G.degree(weight="weight"), list(nx.degree(self.G, weight="weight"))
51
+ )
52
+ assert sorted(self.DG.degree(weight="weight")) == sorted(
53
+ nx.degree(self.DG, weight="weight")
54
+ )
55
+
56
+ def test_neighbors(self):
57
+ assert list(self.G.neighbors(1)) == list(nx.neighbors(self.G, 1))
58
+ assert list(self.DG.neighbors(1)) == list(nx.neighbors(self.DG, 1))
59
+
60
+ def test_number_of_nodes(self):
61
+ assert self.G.number_of_nodes() == nx.number_of_nodes(self.G)
62
+ assert self.DG.number_of_nodes() == nx.number_of_nodes(self.DG)
63
+
64
+ def test_number_of_edges(self):
65
+ assert self.G.number_of_edges() == nx.number_of_edges(self.G)
66
+ assert self.DG.number_of_edges() == nx.number_of_edges(self.DG)
67
+
68
+ def test_is_directed(self):
69
+ assert self.G.is_directed() == nx.is_directed(self.G)
70
+ assert self.DG.is_directed() == nx.is_directed(self.DG)
71
+
72
+ def test_add_star(self):
73
+ G = self.G.copy()
74
+ nlist = [12, 13, 14, 15]
75
+ nx.add_star(G, nlist)
76
+ assert edges_equal(G.edges(nlist), [(12, 13), (12, 14), (12, 15)])
77
+
78
+ G = self.G.copy()
79
+ nx.add_star(G, nlist, weight=2.0)
80
+ assert edges_equal(
81
+ G.edges(nlist, data=True),
82
+ [
83
+ (12, 13, {"weight": 2.0}),
84
+ (12, 14, {"weight": 2.0}),
85
+ (12, 15, {"weight": 2.0}),
86
+ ],
87
+ )
88
+
89
+ G = self.G.copy()
90
+ nlist = [12]
91
+ nx.add_star(G, nlist)
92
+ assert nodes_equal(G, list(self.G) + nlist)
93
+
94
+ G = self.G.copy()
95
+ nlist = []
96
+ nx.add_star(G, nlist)
97
+ assert nodes_equal(G.nodes, self.Gnodes)
98
+ assert edges_equal(G.edges, self.G.edges)
99
+
100
+ def test_add_path(self):
101
+ G = self.G.copy()
102
+ nlist = [12, 13, 14, 15]
103
+ nx.add_path(G, nlist)
104
+ assert edges_equal(G.edges(nlist), [(12, 13), (13, 14), (14, 15)])
105
+ G = self.G.copy()
106
+ nx.add_path(G, nlist, weight=2.0)
107
+ assert edges_equal(
108
+ G.edges(nlist, data=True),
109
+ [
110
+ (12, 13, {"weight": 2.0}),
111
+ (13, 14, {"weight": 2.0}),
112
+ (14, 15, {"weight": 2.0}),
113
+ ],
114
+ )
115
+
116
+ G = self.G.copy()
117
+ nlist = ["node"]
118
+ nx.add_path(G, nlist)
119
+ assert edges_equal(G.edges(nlist), [])
120
+ assert nodes_equal(G, list(self.G) + ["node"])
121
+
122
+ G = self.G.copy()
123
+ nlist = iter(["node"])
124
+ nx.add_path(G, nlist)
125
+ assert edges_equal(G.edges(["node"]), [])
126
+ assert nodes_equal(G, list(self.G) + ["node"])
127
+
128
+ G = self.G.copy()
129
+ nlist = [12]
130
+ nx.add_path(G, nlist)
131
+ assert edges_equal(G.edges(nlist), [])
132
+ assert nodes_equal(G, list(self.G) + [12])
133
+
134
+ G = self.G.copy()
135
+ nlist = iter([12])
136
+ nx.add_path(G, nlist)
137
+ assert edges_equal(G.edges([12]), [])
138
+ assert nodes_equal(G, list(self.G) + [12])
139
+
140
+ G = self.G.copy()
141
+ nlist = []
142
+ nx.add_path(G, nlist)
143
+ assert edges_equal(G.edges, self.G.edges)
144
+ assert nodes_equal(G, list(self.G))
145
+
146
+ G = self.G.copy()
147
+ nlist = iter([])
148
+ nx.add_path(G, nlist)
149
+ assert edges_equal(G.edges, self.G.edges)
150
+ assert nodes_equal(G, list(self.G))
151
+
152
+ def test_add_cycle(self):
153
+ G = self.G.copy()
154
+ nlist = [12, 13, 14, 15]
155
+ oklists = [
156
+ [(12, 13), (12, 15), (13, 14), (14, 15)],
157
+ [(12, 13), (13, 14), (14, 15), (15, 12)],
158
+ ]
159
+ nx.add_cycle(G, nlist)
160
+ assert sorted(G.edges(nlist)) in oklists
161
+ G = self.G.copy()
162
+ oklists = [
163
+ [
164
+ (12, 13, {"weight": 1.0}),
165
+ (12, 15, {"weight": 1.0}),
166
+ (13, 14, {"weight": 1.0}),
167
+ (14, 15, {"weight": 1.0}),
168
+ ],
169
+ [
170
+ (12, 13, {"weight": 1.0}),
171
+ (13, 14, {"weight": 1.0}),
172
+ (14, 15, {"weight": 1.0}),
173
+ (15, 12, {"weight": 1.0}),
174
+ ],
175
+ ]
176
+ nx.add_cycle(G, nlist, weight=1.0)
177
+ assert sorted(G.edges(nlist, data=True)) in oklists
178
+
179
+ G = self.G.copy()
180
+ nlist = [12]
181
+ nx.add_cycle(G, nlist)
182
+ assert nodes_equal(G, list(self.G) + nlist)
183
+
184
+ G = self.G.copy()
185
+ nlist = []
186
+ nx.add_cycle(G, nlist)
187
+ assert nodes_equal(G.nodes, self.Gnodes)
188
+ assert edges_equal(G.edges, self.G.edges)
189
+
190
+ def test_subgraph(self):
191
+ assert (
192
+ self.G.subgraph([0, 1, 2, 4]).adj == nx.subgraph(self.G, [0, 1, 2, 4]).adj
193
+ )
194
+ assert (
195
+ self.DG.subgraph([0, 1, 2, 4]).adj == nx.subgraph(self.DG, [0, 1, 2, 4]).adj
196
+ )
197
+ assert (
198
+ self.G.subgraph([0, 1, 2, 4]).adj
199
+ == nx.induced_subgraph(self.G, [0, 1, 2, 4]).adj
200
+ )
201
+ assert (
202
+ self.DG.subgraph([0, 1, 2, 4]).adj
203
+ == nx.induced_subgraph(self.DG, [0, 1, 2, 4]).adj
204
+ )
205
+ # subgraph-subgraph chain is allowed in function interface
206
+ H = nx.induced_subgraph(self.G.subgraph([0, 1, 2, 4]), [0, 1, 4])
207
+ assert H._graph is not self.G
208
+ assert H.adj == self.G.subgraph([0, 1, 4]).adj
209
+
210
+ def test_edge_subgraph(self):
211
+ assert (
212
+ self.G.edge_subgraph([(1, 2), (0, 3)]).adj
213
+ == nx.edge_subgraph(self.G, [(1, 2), (0, 3)]).adj
214
+ )
215
+ assert (
216
+ self.DG.edge_subgraph([(1, 2), (0, 3)]).adj
217
+ == nx.edge_subgraph(self.DG, [(1, 2), (0, 3)]).adj
218
+ )
219
+
220
+ def test_create_empty_copy(self):
221
+ G = nx.create_empty_copy(self.G, with_data=False)
222
+ assert nodes_equal(G, list(self.G))
223
+ assert G.graph == {}
224
+ assert G._node == {}.fromkeys(self.G.nodes(), {})
225
+ assert G._adj == {}.fromkeys(self.G.nodes(), {})
226
+ G = nx.create_empty_copy(self.G)
227
+ assert nodes_equal(G, list(self.G))
228
+ assert G.graph == self.G.graph
229
+ assert G._node == self.G._node
230
+ assert G._adj == {}.fromkeys(self.G.nodes(), {})
231
+
232
+ def test_degree_histogram(self):
233
+ assert nx.degree_histogram(self.G) == [1, 1, 1, 1, 1]
234
+
235
+ def test_density(self):
236
+ assert nx.density(self.G) == 0.5
237
+ assert nx.density(self.DG) == 0.3
238
+ G = nx.Graph()
239
+ G.add_node(1)
240
+ assert nx.density(G) == 0.0
241
+
242
+ def test_density_selfloop(self):
243
+ G = nx.Graph()
244
+ G.add_edge(1, 1)
245
+ assert nx.density(G) == 0.0
246
+ G.add_edge(1, 2)
247
+ assert nx.density(G) == 2.0
248
+
249
+ def test_freeze(self):
250
+ G = nx.freeze(self.G)
251
+ assert G.frozen
252
+ pytest.raises(nx.NetworkXError, G.add_node, 1)
253
+ pytest.raises(nx.NetworkXError, G.add_nodes_from, [1])
254
+ pytest.raises(nx.NetworkXError, G.remove_node, 1)
255
+ pytest.raises(nx.NetworkXError, G.remove_nodes_from, [1])
256
+ pytest.raises(nx.NetworkXError, G.add_edge, 1, 2)
257
+ pytest.raises(nx.NetworkXError, G.add_edges_from, [(1, 2)])
258
+ pytest.raises(nx.NetworkXError, G.remove_edge, 1, 2)
259
+ pytest.raises(nx.NetworkXError, G.remove_edges_from, [(1, 2)])
260
+ pytest.raises(nx.NetworkXError, G.clear_edges)
261
+ pytest.raises(nx.NetworkXError, G.clear)
262
+
263
+ def test_is_frozen(self):
264
+ assert not nx.is_frozen(self.G)
265
+ G = nx.freeze(self.G)
266
+ assert G.frozen == nx.is_frozen(self.G)
267
+ assert G.frozen
268
+
269
+ def test_node_attributes_are_still_mutable_on_frozen_graph(self):
270
+ G = nx.freeze(nx.path_graph(3))
271
+ node = G.nodes[0]
272
+ node["node_attribute"] = True
273
+ assert node["node_attribute"] == True
274
+
275
+ def test_edge_attributes_are_still_mutable_on_frozen_graph(self):
276
+ G = nx.freeze(nx.path_graph(3))
277
+ edge = G.edges[(0, 1)]
278
+ edge["edge_attribute"] = True
279
+ assert edge["edge_attribute"] == True
280
+
281
+ def test_neighbors_complete_graph(self):
282
+ graph = nx.complete_graph(100)
283
+ pop = random.sample(list(graph), 1)
284
+ nbors = list(nx.neighbors(graph, pop[0]))
285
+ # should be all the other vertices in the graph
286
+ assert len(nbors) == len(graph) - 1
287
+
288
+ graph = nx.path_graph(100)
289
+ node = random.sample(list(graph), 1)[0]
290
+ nbors = list(nx.neighbors(graph, node))
291
+ # should be all the other vertices in the graph
292
+ if node != 0 and node != 99:
293
+ assert len(nbors) == 2
294
+ else:
295
+ assert len(nbors) == 1
296
+
297
+ # create a star graph with 99 outer nodes
298
+ graph = nx.star_graph(99)
299
+ nbors = list(nx.neighbors(graph, 0))
300
+ assert len(nbors) == 99
301
+
302
+ def test_non_neighbors(self):
303
+ graph = nx.complete_graph(100)
304
+ pop = random.sample(list(graph), 1)
305
+ nbors = nx.non_neighbors(graph, pop[0])
306
+ # should be all the other vertices in the graph
307
+ assert len(nbors) == 0
308
+
309
+ graph = nx.path_graph(100)
310
+ node = random.sample(list(graph), 1)[0]
311
+ nbors = nx.non_neighbors(graph, node)
312
+ # should be all the other vertices in the graph
313
+ if node != 0 and node != 99:
314
+ assert len(nbors) == 97
315
+ else:
316
+ assert len(nbors) == 98
317
+
318
+ # create a star graph with 99 outer nodes
319
+ graph = nx.star_graph(99)
320
+ nbors = nx.non_neighbors(graph, 0)
321
+ assert len(nbors) == 0
322
+
323
+ # disconnected graph
324
+ graph = nx.Graph()
325
+ graph.add_nodes_from(range(10))
326
+ nbors = nx.non_neighbors(graph, 0)
327
+ assert len(nbors) == 9
328
+
329
+ def test_non_edges(self):
330
+ # All possible edges exist
331
+ graph = nx.complete_graph(5)
332
+ nedges = list(nx.non_edges(graph))
333
+ assert len(nedges) == 0
334
+
335
+ graph = nx.path_graph(4)
336
+ expected = [(0, 2), (0, 3), (1, 3)]
337
+ nedges = list(nx.non_edges(graph))
338
+ for u, v in expected:
339
+ assert (u, v) in nedges or (v, u) in nedges
340
+
341
+ graph = nx.star_graph(4)
342
+ expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
343
+ nedges = list(nx.non_edges(graph))
344
+ for u, v in expected:
345
+ assert (u, v) in nedges or (v, u) in nedges
346
+
347
+ # Directed graphs
348
+ graph = nx.DiGraph()
349
+ graph.add_edges_from([(0, 2), (2, 0), (2, 1)])
350
+ expected = [(0, 1), (1, 0), (1, 2)]
351
+ nedges = list(nx.non_edges(graph))
352
+ for e in expected:
353
+ assert e in nedges
354
+
355
+ def test_is_weighted(self):
356
+ G = nx.Graph()
357
+ assert not nx.is_weighted(G)
358
+
359
+ G = nx.path_graph(4)
360
+ assert not nx.is_weighted(G)
361
+ assert not nx.is_weighted(G, (2, 3))
362
+
363
+ G.add_node(4)
364
+ G.add_edge(3, 4, weight=4)
365
+ assert not nx.is_weighted(G)
366
+ assert nx.is_weighted(G, (3, 4))
367
+
368
+ G = nx.DiGraph()
369
+ G.add_weighted_edges_from(
370
+ [
371
+ ("0", "3", 3),
372
+ ("0", "1", -5),
373
+ ("1", "0", -5),
374
+ ("0", "2", 2),
375
+ ("1", "2", 4),
376
+ ("2", "3", 1),
377
+ ]
378
+ )
379
+ assert nx.is_weighted(G)
380
+ assert nx.is_weighted(G, ("1", "0"))
381
+
382
+ G = G.to_undirected()
383
+ assert nx.is_weighted(G)
384
+ assert nx.is_weighted(G, ("1", "0"))
385
+
386
+ pytest.raises(nx.NetworkXError, nx.is_weighted, G, (1, 2))
387
+
388
+ def test_is_negatively_weighted(self):
389
+ G = nx.Graph()
390
+ assert not nx.is_negatively_weighted(G)
391
+
392
+ G.add_node(1)
393
+ G.add_nodes_from([2, 3, 4, 5])
394
+ assert not nx.is_negatively_weighted(G)
395
+
396
+ G.add_edge(1, 2, weight=4)
397
+ assert not nx.is_negatively_weighted(G, (1, 2))
398
+
399
+ G.add_edges_from([(1, 3), (2, 4), (2, 6)])
400
+ G[1][3]["color"] = "blue"
401
+ assert not nx.is_negatively_weighted(G)
402
+ assert not nx.is_negatively_weighted(G, (1, 3))
403
+
404
+ G[2][4]["weight"] = -2
405
+ assert nx.is_negatively_weighted(G, (2, 4))
406
+ assert nx.is_negatively_weighted(G)
407
+
408
+ G = nx.DiGraph()
409
+ G.add_weighted_edges_from(
410
+ [
411
+ ("0", "3", 3),
412
+ ("0", "1", -5),
413
+ ("1", "0", -2),
414
+ ("0", "2", 2),
415
+ ("1", "2", -3),
416
+ ("2", "3", 1),
417
+ ]
418
+ )
419
+ assert nx.is_negatively_weighted(G)
420
+ assert not nx.is_negatively_weighted(G, ("0", "3"))
421
+ assert nx.is_negatively_weighted(G, ("1", "0"))
422
+
423
+ pytest.raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4))
424
+
425
+
426
+ class TestCommonNeighbors:
427
+ @classmethod
428
+ def setup_class(cls):
429
+ cls.func = staticmethod(nx.common_neighbors)
430
+
431
+ def test_func(G, u, v, expected):
432
+ result = sorted(cls.func(G, u, v))
433
+ assert result == expected
434
+
435
+ cls.test = staticmethod(test_func)
436
+
437
+ def test_K5(self):
438
+ G = nx.complete_graph(5)
439
+ self.test(G, 0, 1, [2, 3, 4])
440
+
441
+ def test_P3(self):
442
+ G = nx.path_graph(3)
443
+ self.test(G, 0, 2, [1])
444
+
445
+ def test_S4(self):
446
+ G = nx.star_graph(4)
447
+ self.test(G, 1, 2, [0])
448
+
449
+ def test_digraph(self):
450
+ with pytest.raises(nx.NetworkXNotImplemented):
451
+ G = nx.DiGraph()
452
+ G.add_edges_from([(0, 1), (1, 2)])
453
+ self.func(G, 0, 2)
454
+
455
+ def test_nonexistent_nodes(self):
456
+ G = nx.complete_graph(5)
457
+ pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 5, 4)
458
+ pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 4, 5)
459
+ pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 5, 6)
460
+
461
+ def test_custom1(self):
462
+ """Case of no common neighbors."""
463
+ G = nx.Graph()
464
+ G.add_nodes_from([0, 1])
465
+ self.test(G, 0, 1, [])
466
+
467
+ def test_custom2(self):
468
+ """Case of equal nodes."""
469
+ G = nx.complete_graph(4)
470
+ self.test(G, 0, 0, [1, 2, 3])
471
+
472
+
473
+ @pytest.mark.parametrize(
474
+ "graph_type", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
475
+ )
476
+ def test_set_node_attributes(graph_type):
477
+ # Test single value
478
+ G = nx.path_graph(3, create_using=graph_type)
479
+ vals = 100
480
+ attr = "hello"
481
+ nx.set_node_attributes(G, vals, attr)
482
+ assert G.nodes[0][attr] == vals
483
+ assert G.nodes[1][attr] == vals
484
+ assert G.nodes[2][attr] == vals
485
+
486
+ # Test dictionary
487
+ G = nx.path_graph(3, create_using=graph_type)
488
+ vals = dict(zip(sorted(G.nodes()), range(len(G))))
489
+ attr = "hi"
490
+ nx.set_node_attributes(G, vals, attr)
491
+ assert G.nodes[0][attr] == 0
492
+ assert G.nodes[1][attr] == 1
493
+ assert G.nodes[2][attr] == 2
494
+
495
+ # Test dictionary of dictionaries
496
+ G = nx.path_graph(3, create_using=graph_type)
497
+ d = {"hi": 0, "hello": 200}
498
+ vals = dict.fromkeys(G.nodes(), d)
499
+ vals.pop(0)
500
+ nx.set_node_attributes(G, vals)
501
+ assert G.nodes[0] == {}
502
+ assert G.nodes[1]["hi"] == 0
503
+ assert G.nodes[2]["hello"] == 200
504
+
505
+
506
+ @pytest.mark.parametrize(
507
+ ("values", "name"),
508
+ (
509
+ ({0: "red", 1: "blue"}, "color"), # values dictionary
510
+ ({0: {"color": "red"}, 1: {"color": "blue"}}, None), # dict-of-dict
511
+ ),
512
+ )
513
+ def test_set_node_attributes_ignores_extra_nodes(values, name):
514
+ """
515
+ When `values` is a dict or dict-of-dict keyed by nodes, ensure that keys
516
+ that correspond to nodes not in G are ignored.
517
+ """
518
+ G = nx.Graph()
519
+ G.add_node(0)
520
+ nx.set_node_attributes(G, values, name)
521
+ assert G.nodes[0]["color"] == "red"
522
+ assert 1 not in G.nodes
523
+
524
+
525
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
526
+ def test_set_edge_attributes(graph_type):
527
+ # Test single value
528
+ G = nx.path_graph(3, create_using=graph_type)
529
+ attr = "hello"
530
+ vals = 3
531
+ nx.set_edge_attributes(G, vals, attr)
532
+ assert G[0][1][attr] == vals
533
+ assert G[1][2][attr] == vals
534
+
535
+ # Test multiple values
536
+ G = nx.path_graph(3, create_using=graph_type)
537
+ attr = "hi"
538
+ edges = [(0, 1), (1, 2)]
539
+ vals = dict(zip(edges, range(len(edges))))
540
+ nx.set_edge_attributes(G, vals, attr)
541
+ assert G[0][1][attr] == 0
542
+ assert G[1][2][attr] == 1
543
+
544
+ # Test dictionary of dictionaries
545
+ G = nx.path_graph(3, create_using=graph_type)
546
+ d = {"hi": 0, "hello": 200}
547
+ edges = [(0, 1)]
548
+ vals = dict.fromkeys(edges, d)
549
+ nx.set_edge_attributes(G, vals)
550
+ assert G[0][1]["hi"] == 0
551
+ assert G[0][1]["hello"] == 200
552
+ assert G[1][2] == {}
553
+
554
+
555
+ @pytest.mark.parametrize(
556
+ ("values", "name"),
557
+ (
558
+ ({(0, 1): 1.0, (0, 2): 2.0}, "weight"), # values dict
559
+ ({(0, 1): {"weight": 1.0}, (0, 2): {"weight": 2.0}}, None), # values dod
560
+ ),
561
+ )
562
+ def test_set_edge_attributes_ignores_extra_edges(values, name):
563
+ """If `values` is a dict or dict-of-dicts containing edges that are not in
564
+ G, data associate with these edges should be ignored.
565
+ """
566
+ G = nx.Graph([(0, 1)])
567
+ nx.set_edge_attributes(G, values, name)
568
+ assert G[0][1]["weight"] == 1.0
569
+ assert (0, 2) not in G.edges
570
+
571
+
572
+ @pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
573
+ def test_set_edge_attributes_multi(graph_type):
574
+ # Test single value
575
+ G = nx.path_graph(3, create_using=graph_type)
576
+ attr = "hello"
577
+ vals = 3
578
+ nx.set_edge_attributes(G, vals, attr)
579
+ assert G[0][1][0][attr] == vals
580
+ assert G[1][2][0][attr] == vals
581
+
582
+ # Test multiple values
583
+ G = nx.path_graph(3, create_using=graph_type)
584
+ attr = "hi"
585
+ edges = [(0, 1, 0), (1, 2, 0)]
586
+ vals = dict(zip(edges, range(len(edges))))
587
+ nx.set_edge_attributes(G, vals, attr)
588
+ assert G[0][1][0][attr] == 0
589
+ assert G[1][2][0][attr] == 1
590
+
591
+ # Test dictionary of dictionaries
592
+ G = nx.path_graph(3, create_using=graph_type)
593
+ d = {"hi": 0, "hello": 200}
594
+ edges = [(0, 1, 0)]
595
+ vals = dict.fromkeys(edges, d)
596
+ nx.set_edge_attributes(G, vals)
597
+ assert G[0][1][0]["hi"] == 0
598
+ assert G[0][1][0]["hello"] == 200
599
+ assert G[1][2][0] == {}
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ ("values", "name"),
604
+ (
605
+ ({(0, 1, 0): 1.0, (0, 2, 0): 2.0}, "weight"), # values dict
606
+ ({(0, 1, 0): {"weight": 1.0}, (0, 2, 0): {"weight": 2.0}}, None), # values dod
607
+ ),
608
+ )
609
+ def test_set_edge_attributes_multi_ignores_extra_edges(values, name):
610
+ """If `values` is a dict or dict-of-dicts containing edges that are not in
611
+ G, data associate with these edges should be ignored.
612
+ """
613
+ G = nx.MultiGraph([(0, 1, 0), (0, 1, 1)])
614
+ nx.set_edge_attributes(G, values, name)
615
+ assert G[0][1][0]["weight"] == 1.0
616
+ assert G[0][1][1] == {}
617
+ assert (0, 2) not in G.edges()
618
+
619
+
620
+ def test_get_node_attributes():
621
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
622
+ for G in graphs:
623
+ G = nx.path_graph(3, create_using=G)
624
+ attr = "hello"
625
+ vals = 100
626
+ nx.set_node_attributes(G, vals, attr)
627
+ attrs = nx.get_node_attributes(G, attr)
628
+ assert attrs[0] == vals
629
+ assert attrs[1] == vals
630
+ assert attrs[2] == vals
631
+ default_val = 1
632
+ G.add_node(4)
633
+ attrs = nx.get_node_attributes(G, attr, default=default_val)
634
+ assert attrs[4] == default_val
635
+
636
+
637
+ def test_get_edge_attributes():
638
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
639
+ for G in graphs:
640
+ G = nx.path_graph(3, create_using=G)
641
+ attr = "hello"
642
+ vals = 100
643
+ nx.set_edge_attributes(G, vals, attr)
644
+ attrs = nx.get_edge_attributes(G, attr)
645
+ assert len(attrs) == 2
646
+
647
+ for edge in G.edges:
648
+ assert attrs[edge] == vals
649
+
650
+ default_val = vals
651
+ G.add_edge(4, 5)
652
+ deafult_attrs = nx.get_edge_attributes(G, attr, default=default_val)
653
+ assert len(deafult_attrs) == 3
654
+
655
+ for edge in G.edges:
656
+ assert deafult_attrs[edge] == vals
657
+
658
+
659
+ def test_is_empty():
660
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
661
+ for G in graphs:
662
+ assert nx.is_empty(G)
663
+ G.add_nodes_from(range(5))
664
+ assert nx.is_empty(G)
665
+ G.add_edges_from([(1, 2), (3, 4)])
666
+ assert not nx.is_empty(G)
667
+
668
+
669
+ @pytest.mark.parametrize(
670
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
671
+ )
672
+ def test_selfloops(graph_type):
673
+ G = nx.complete_graph(3, create_using=graph_type)
674
+ G.add_edge(0, 0)
675
+ assert nodes_equal(nx.nodes_with_selfloops(G), [0])
676
+ assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
677
+ assert edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {})])
678
+ assert nx.number_of_selfloops(G) == 1
679
+
680
+
681
+ @pytest.mark.parametrize(
682
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
683
+ )
684
+ def test_selfloop_edges_attr(graph_type):
685
+ G = nx.complete_graph(3, create_using=graph_type)
686
+ G.add_edge(0, 0)
687
+ G.add_edge(1, 1, weight=2)
688
+ assert edges_equal(
689
+ nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
690
+ )
691
+ assert edges_equal(nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)])
692
+
693
+
694
+ def test_selfloop_edges_multi_with_data_and_keys():
695
+ G = nx.complete_graph(3, create_using=nx.MultiGraph)
696
+ G.add_edge(0, 0, weight=10)
697
+ G.add_edge(0, 0, weight=100)
698
+ assert edges_equal(
699
+ nx.selfloop_edges(G, data="weight", keys=True), [(0, 0, 0, 10), (0, 0, 1, 100)]
700
+ )
701
+
702
+
703
+ @pytest.mark.parametrize("graph_type", [nx.Graph, nx.DiGraph])
704
+ def test_selfloops_removal(graph_type):
705
+ G = nx.complete_graph(3, create_using=graph_type)
706
+ G.add_edge(0, 0)
707
+ G.remove_edges_from(nx.selfloop_edges(G, keys=True))
708
+ G.add_edge(0, 0)
709
+ G.remove_edges_from(nx.selfloop_edges(G, data=True))
710
+ G.add_edge(0, 0)
711
+ G.remove_edges_from(nx.selfloop_edges(G, keys=True, data=True))
712
+
713
+
714
+ @pytest.mark.parametrize("graph_type", [nx.MultiGraph, nx.MultiDiGraph])
715
+ def test_selfloops_removal_multi(graph_type):
716
+ """test removing selfloops behavior vis-a-vis altering a dict while iterating.
717
+ cf. gh-4068"""
718
+ G = nx.complete_graph(3, create_using=graph_type)
719
+ # Defaults - see gh-4080
720
+ G.add_edge(0, 0)
721
+ G.add_edge(0, 0)
722
+ G.remove_edges_from(nx.selfloop_edges(G))
723
+ assert (0, 0) not in G.edges()
724
+ # With keys
725
+ G.add_edge(0, 0)
726
+ G.add_edge(0, 0)
727
+ with pytest.raises(RuntimeError):
728
+ G.remove_edges_from(nx.selfloop_edges(G, keys=True))
729
+ # With data
730
+ G.add_edge(0, 0)
731
+ G.add_edge(0, 0)
732
+ with pytest.raises(TypeError):
733
+ G.remove_edges_from(nx.selfloop_edges(G, data=True))
734
+ # With keys and data
735
+ G.add_edge(0, 0)
736
+ G.add_edge(0, 0)
737
+ with pytest.raises(RuntimeError):
738
+ G.remove_edges_from(nx.selfloop_edges(G, data=True, keys=True))
739
+
740
+
741
+ def test_pathweight():
742
+ valid_path = [1, 2, 3]
743
+ invalid_path = [1, 3, 2]
744
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
745
+ edges = [
746
+ (1, 2, {"cost": 5, "dist": 6}),
747
+ (2, 3, {"cost": 3, "dist": 4}),
748
+ (1, 2, {"cost": 1, "dist": 2}),
749
+ ]
750
+ for graph in graphs:
751
+ graph.add_edges_from(edges)
752
+ assert nx.path_weight(graph, valid_path, "cost") == 4
753
+ assert nx.path_weight(graph, valid_path, "dist") == 6
754
+ pytest.raises(nx.NetworkXNoPath, nx.path_weight, graph, invalid_path, "cost")
755
+
756
+
757
+ @pytest.mark.parametrize(
758
+ "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
759
+ )
760
+ def test_ispath(G):
761
+ G.add_edges_from([(1, 2), (2, 3), (1, 2), (3, 4)])
762
+ valid_path = [1, 2, 3, 4]
763
+ invalid_path = [1, 2, 4, 3] # wrong node order
764
+ another_invalid_path = [1, 2, 3, 4, 5] # contains node not in G
765
+ assert nx.is_path(G, valid_path)
766
+ assert not nx.is_path(G, invalid_path)
767
+ assert not nx.is_path(G, another_invalid_path)
768
+
769
+
770
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
771
+ def test_restricted_view(G):
772
+ G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)])
773
+ G.add_node(4)
774
+ H = nx.restricted_view(G, [0, 2, 5], [(1, 2), (3, 4)])
775
+ assert set(H.nodes()) == {1, 3, 4}
776
+ assert set(H.edges()) == {(1, 1)}
777
+
778
+
779
+ @pytest.mark.parametrize("G", (nx.MultiGraph(), nx.MultiDiGraph()))
780
+ def test_restricted_view_multi(G):
781
+ G.add_edges_from(
782
+ [(0, 1, 0), (0, 2, 0), (0, 3, 0), (0, 1, 1), (1, 0, 0), (1, 1, 0), (1, 2, 0)]
783
+ )
784
+ G.add_node(4)
785
+ H = nx.restricted_view(G, [0, 2, 5], [(1, 2, 0), (3, 4, 0)])
786
+ assert set(H.nodes()) == {1, 3, 4}
787
+ assert set(H.edges()) == {(1, 1)}
env-llmeval/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()
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_reportviews.py ADDED
@@ -0,0 +1,1427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from copy import deepcopy
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.classes import reportviews as rv
8
+ from networkx.classes.reportviews import NodeDataView
9
+
10
+
11
+ # Nodes
12
+ class TestNodeView:
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9)
16
+ cls.nv = cls.G.nodes # NodeView(G)
17
+
18
+ def test_pickle(self):
19
+ import pickle
20
+
21
+ nv = self.nv
22
+ pnv = pickle.loads(pickle.dumps(nv, -1))
23
+ assert nv == pnv
24
+ assert nv.__slots__ == pnv.__slots__
25
+
26
+ def test_str(self):
27
+ assert str(self.nv) == "[0, 1, 2, 3, 4, 5, 6, 7, 8]"
28
+
29
+ def test_repr(self):
30
+ assert repr(self.nv) == "NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
31
+
32
+ def test_contains(self):
33
+ G = self.G.copy()
34
+ nv = G.nodes
35
+ assert 7 in nv
36
+ assert 9 not in nv
37
+ G.remove_node(7)
38
+ G.add_node(9)
39
+ assert 7 not in nv
40
+ assert 9 in nv
41
+
42
+ def test_getitem(self):
43
+ G = self.G.copy()
44
+ nv = G.nodes
45
+ G.nodes[3]["foo"] = "bar"
46
+ assert nv[7] == {}
47
+ assert nv[3] == {"foo": "bar"}
48
+ # slicing
49
+ with pytest.raises(nx.NetworkXError):
50
+ G.nodes[0:5]
51
+
52
+ def test_iter(self):
53
+ nv = self.nv
54
+ for i, n in enumerate(nv):
55
+ assert i == n
56
+ inv = iter(nv)
57
+ assert next(inv) == 0
58
+ assert iter(nv) != nv
59
+ assert iter(inv) == inv
60
+ inv2 = iter(nv)
61
+ next(inv2)
62
+ assert list(inv) == list(inv2)
63
+ # odd case where NodeView calls NodeDataView with data=False
64
+ nnv = nv(data=False)
65
+ for i, n in enumerate(nnv):
66
+ assert i == n
67
+
68
+ def test_call(self):
69
+ nodes = self.nv
70
+ assert nodes is nodes()
71
+ assert nodes is not nodes(data=True)
72
+ assert nodes is not nodes(data="weight")
73
+
74
+
75
+ class TestNodeDataView:
76
+ @classmethod
77
+ def setup_class(cls):
78
+ cls.G = nx.path_graph(9)
79
+ cls.nv = NodeDataView(cls.G)
80
+ cls.ndv = cls.G.nodes.data(True)
81
+ cls.nwv = cls.G.nodes.data("foo")
82
+
83
+ def test_viewtype(self):
84
+ nv = self.G.nodes
85
+ ndvfalse = nv.data(False)
86
+ assert nv is ndvfalse
87
+ assert nv is not self.ndv
88
+
89
+ def test_pickle(self):
90
+ import pickle
91
+
92
+ nv = self.nv
93
+ pnv = pickle.loads(pickle.dumps(nv, -1))
94
+ assert nv == pnv
95
+ assert nv.__slots__ == pnv.__slots__
96
+
97
+ def test_str(self):
98
+ msg = str([(n, {}) for n in range(9)])
99
+ assert str(self.ndv) == msg
100
+
101
+ def test_repr(self):
102
+ expected = "NodeDataView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
103
+ assert repr(self.nv) == expected
104
+ expected = (
105
+ "NodeDataView({0: {}, 1: {}, 2: {}, 3: {}, "
106
+ + "4: {}, 5: {}, 6: {}, 7: {}, 8: {}})"
107
+ )
108
+ assert repr(self.ndv) == expected
109
+ expected = (
110
+ "NodeDataView({0: None, 1: None, 2: None, 3: None, 4: None, "
111
+ + "5: None, 6: None, 7: None, 8: None}, data='foo')"
112
+ )
113
+ assert repr(self.nwv) == expected
114
+
115
+ def test_contains(self):
116
+ G = self.G.copy()
117
+ nv = G.nodes.data()
118
+ nwv = G.nodes.data("foo")
119
+ G.nodes[3]["foo"] = "bar"
120
+ assert (7, {}) in nv
121
+ assert (3, {"foo": "bar"}) in nv
122
+ assert (3, "bar") in nwv
123
+ assert (7, None) in nwv
124
+ # default
125
+ nwv_def = G.nodes(data="foo", default="biz")
126
+ assert (7, "biz") in nwv_def
127
+ assert (3, "bar") in nwv_def
128
+
129
+ def test_getitem(self):
130
+ G = self.G.copy()
131
+ nv = G.nodes
132
+ G.nodes[3]["foo"] = "bar"
133
+ assert nv[3] == {"foo": "bar"}
134
+ # default
135
+ nwv_def = G.nodes(data="foo", default="biz")
136
+ assert nwv_def[7], "biz"
137
+ assert nwv_def[3] == "bar"
138
+ # slicing
139
+ with pytest.raises(nx.NetworkXError):
140
+ G.nodes.data()[0:5]
141
+
142
+ def test_iter(self):
143
+ G = self.G.copy()
144
+ nv = G.nodes.data()
145
+ ndv = G.nodes.data(True)
146
+ nwv = G.nodes.data("foo")
147
+ for i, (n, d) in enumerate(nv):
148
+ assert i == n
149
+ assert d == {}
150
+ inv = iter(nv)
151
+ assert next(inv) == (0, {})
152
+ G.nodes[3]["foo"] = "bar"
153
+ # default
154
+ for n, d in nv:
155
+ if n == 3:
156
+ assert d == {"foo": "bar"}
157
+ else:
158
+ assert d == {}
159
+ # data=True
160
+ for n, d in ndv:
161
+ if n == 3:
162
+ assert d == {"foo": "bar"}
163
+ else:
164
+ assert d == {}
165
+ # data='foo'
166
+ for n, d in nwv:
167
+ if n == 3:
168
+ assert d == "bar"
169
+ else:
170
+ assert d is None
171
+ # data='foo', default=1
172
+ for n, d in G.nodes.data("foo", default=1):
173
+ if n == 3:
174
+ assert d == "bar"
175
+ else:
176
+ assert d == 1
177
+
178
+
179
+ def test_nodedataview_unhashable():
180
+ G = nx.path_graph(9)
181
+ G.nodes[3]["foo"] = "bar"
182
+ nvs = [G.nodes.data()]
183
+ nvs.append(G.nodes.data(True))
184
+ H = G.copy()
185
+ H.nodes[4]["foo"] = {1, 2, 3}
186
+ nvs.append(H.nodes.data(True))
187
+ # raise unhashable
188
+ for nv in nvs:
189
+ pytest.raises(TypeError, set, nv)
190
+ pytest.raises(TypeError, eval, "nv | nv", locals())
191
+ # no raise... hashable
192
+ Gn = G.nodes.data(False)
193
+ set(Gn)
194
+ Gn | Gn
195
+ Gn = G.nodes.data("foo")
196
+ set(Gn)
197
+ Gn | Gn
198
+
199
+
200
+ class TestNodeViewSetOps:
201
+ @classmethod
202
+ def setup_class(cls):
203
+ cls.G = nx.path_graph(9)
204
+ cls.G.nodes[3]["foo"] = "bar"
205
+ cls.nv = cls.G.nodes
206
+
207
+ def n_its(self, nodes):
208
+ return set(nodes)
209
+
210
+ def test_len(self):
211
+ G = self.G.copy()
212
+ nv = G.nodes
213
+ assert len(nv) == 9
214
+ G.remove_node(7)
215
+ assert len(nv) == 8
216
+ G.add_node(9)
217
+ assert len(nv) == 9
218
+
219
+ def test_and(self):
220
+ # print("G & H nodes:", gnv & hnv)
221
+ nv = self.nv
222
+ some_nodes = self.n_its(range(5, 12))
223
+ assert nv & some_nodes == self.n_its(range(5, 9))
224
+ assert some_nodes & nv == self.n_its(range(5, 9))
225
+
226
+ def test_or(self):
227
+ # print("G | H nodes:", gnv | hnv)
228
+ nv = self.nv
229
+ some_nodes = self.n_its(range(5, 12))
230
+ assert nv | some_nodes == self.n_its(range(12))
231
+ assert some_nodes | nv == self.n_its(range(12))
232
+
233
+ def test_xor(self):
234
+ # print("G ^ H nodes:", gnv ^ hnv)
235
+ nv = self.nv
236
+ some_nodes = self.n_its(range(5, 12))
237
+ nodes = {0, 1, 2, 3, 4, 9, 10, 11}
238
+ assert nv ^ some_nodes == self.n_its(nodes)
239
+ assert some_nodes ^ nv == self.n_its(nodes)
240
+
241
+ def test_sub(self):
242
+ # print("G - H nodes:", gnv - hnv)
243
+ nv = self.nv
244
+ some_nodes = self.n_its(range(5, 12))
245
+ assert nv - some_nodes == self.n_its(range(5))
246
+ assert some_nodes - nv == self.n_its(range(9, 12))
247
+
248
+
249
+ class TestNodeDataViewSetOps(TestNodeViewSetOps):
250
+ @classmethod
251
+ def setup_class(cls):
252
+ cls.G = nx.path_graph(9)
253
+ cls.G.nodes[3]["foo"] = "bar"
254
+ cls.nv = cls.G.nodes.data("foo")
255
+
256
+ def n_its(self, nodes):
257
+ return {(node, "bar" if node == 3 else None) for node in nodes}
258
+
259
+
260
+ class TestNodeDataViewDefaultSetOps(TestNodeDataViewSetOps):
261
+ @classmethod
262
+ def setup_class(cls):
263
+ cls.G = nx.path_graph(9)
264
+ cls.G.nodes[3]["foo"] = "bar"
265
+ cls.nv = cls.G.nodes.data("foo", default=1)
266
+
267
+ def n_its(self, nodes):
268
+ return {(node, "bar" if node == 3 else 1) for node in nodes}
269
+
270
+
271
+ # Edges Data View
272
+ class TestEdgeDataView:
273
+ @classmethod
274
+ def setup_class(cls):
275
+ cls.G = nx.path_graph(9)
276
+ cls.eview = nx.reportviews.EdgeView
277
+
278
+ def test_pickle(self):
279
+ import pickle
280
+
281
+ ev = self.eview(self.G)(data=True)
282
+ pev = pickle.loads(pickle.dumps(ev, -1))
283
+ assert list(ev) == list(pev)
284
+ assert ev.__slots__ == pev.__slots__
285
+
286
+ def modify_edge(self, G, e, **kwds):
287
+ G._adj[e[0]][e[1]].update(kwds)
288
+
289
+ def test_str(self):
290
+ ev = self.eview(self.G)(data=True)
291
+ rep = str([(n, n + 1, {}) for n in range(8)])
292
+ assert str(ev) == rep
293
+
294
+ def test_repr(self):
295
+ ev = self.eview(self.G)(data=True)
296
+ rep = (
297
+ "EdgeDataView([(0, 1, {}), (1, 2, {}), "
298
+ + "(2, 3, {}), (3, 4, {}), "
299
+ + "(4, 5, {}), (5, 6, {}), "
300
+ + "(6, 7, {}), (7, 8, {})])"
301
+ )
302
+ assert repr(ev) == rep
303
+
304
+ def test_iterdata(self):
305
+ G = self.G.copy()
306
+ evr = self.eview(G)
307
+ ev = evr(data=True)
308
+ ev_def = evr(data="foo", default=1)
309
+
310
+ for u, v, d in ev:
311
+ pass
312
+ assert d == {}
313
+
314
+ for u, v, wt in ev_def:
315
+ pass
316
+ assert wt == 1
317
+
318
+ self.modify_edge(G, (2, 3), foo="bar")
319
+ for e in ev:
320
+ assert len(e) == 3
321
+ if set(e[:2]) == {2, 3}:
322
+ assert e[2] == {"foo": "bar"}
323
+ checked = True
324
+ else:
325
+ assert e[2] == {}
326
+ assert checked
327
+
328
+ for e in ev_def:
329
+ assert len(e) == 3
330
+ if set(e[:2]) == {2, 3}:
331
+ assert e[2] == "bar"
332
+ checked_wt = True
333
+ else:
334
+ assert e[2] == 1
335
+ assert checked_wt
336
+
337
+ def test_iter(self):
338
+ evr = self.eview(self.G)
339
+ ev = evr()
340
+ for u, v in ev:
341
+ pass
342
+ iev = iter(ev)
343
+ assert next(iev) == (0, 1)
344
+ assert iter(ev) != ev
345
+ assert iter(iev) == iev
346
+
347
+ def test_contains(self):
348
+ evr = self.eview(self.G)
349
+ ev = evr()
350
+ if self.G.is_directed():
351
+ assert (1, 2) in ev and (2, 1) not in ev
352
+ else:
353
+ assert (1, 2) in ev and (2, 1) in ev
354
+ assert (1, 4) not in ev
355
+ assert (1, 90) not in ev
356
+ assert (90, 1) not in ev
357
+
358
+ def test_contains_with_nbunch(self):
359
+ evr = self.eview(self.G)
360
+ ev = evr(nbunch=[0, 2])
361
+ if self.G.is_directed():
362
+ assert (0, 1) in ev
363
+ assert (1, 2) not in ev
364
+ assert (2, 3) in ev
365
+ else:
366
+ assert (0, 1) in ev
367
+ assert (1, 2) in ev
368
+ assert (2, 3) in ev
369
+ assert (3, 4) not in ev
370
+ assert (4, 5) not in ev
371
+ assert (5, 6) not in ev
372
+ assert (7, 8) not in ev
373
+ assert (8, 9) not in ev
374
+
375
+ def test_len(self):
376
+ evr = self.eview(self.G)
377
+ ev = evr(data="foo")
378
+ assert len(ev) == 8
379
+ assert len(evr(1)) == 2
380
+ assert len(evr([1, 2, 3])) == 4
381
+
382
+ assert len(self.G.edges(1)) == 2
383
+ assert len(self.G.edges()) == 8
384
+ assert len(self.G.edges) == 8
385
+
386
+ H = self.G.copy()
387
+ H.add_edge(1, 1)
388
+ assert len(H.edges(1)) == 3
389
+ assert len(H.edges()) == 9
390
+ assert len(H.edges) == 9
391
+
392
+
393
+ class TestOutEdgeDataView(TestEdgeDataView):
394
+ @classmethod
395
+ def setup_class(cls):
396
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
397
+ cls.eview = nx.reportviews.OutEdgeView
398
+
399
+ def test_repr(self):
400
+ ev = self.eview(self.G)(data=True)
401
+ rep = (
402
+ "OutEdgeDataView([(0, 1, {}), (1, 2, {}), "
403
+ + "(2, 3, {}), (3, 4, {}), "
404
+ + "(4, 5, {}), (5, 6, {}), "
405
+ + "(6, 7, {}), (7, 8, {})])"
406
+ )
407
+ assert repr(ev) == rep
408
+
409
+ def test_len(self):
410
+ evr = self.eview(self.G)
411
+ ev = evr(data="foo")
412
+ assert len(ev) == 8
413
+ assert len(evr(1)) == 1
414
+ assert len(evr([1, 2, 3])) == 3
415
+
416
+ assert len(self.G.edges(1)) == 1
417
+ assert len(self.G.edges()) == 8
418
+ assert len(self.G.edges) == 8
419
+
420
+ H = self.G.copy()
421
+ H.add_edge(1, 1)
422
+ assert len(H.edges(1)) == 2
423
+ assert len(H.edges()) == 9
424
+ assert len(H.edges) == 9
425
+
426
+ def test_contains_with_nbunch(self):
427
+ evr = self.eview(self.G)
428
+ ev = evr(nbunch=[0, 2])
429
+ assert (0, 1) in ev
430
+ assert (1, 2) not in ev
431
+ assert (2, 3) in ev
432
+ assert (3, 4) not in ev
433
+ assert (4, 5) not in ev
434
+ assert (5, 6) not in ev
435
+ assert (7, 8) not in ev
436
+ assert (8, 9) not in ev
437
+
438
+
439
+ class TestInEdgeDataView(TestOutEdgeDataView):
440
+ @classmethod
441
+ def setup_class(cls):
442
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
443
+ cls.eview = nx.reportviews.InEdgeView
444
+
445
+ def test_repr(self):
446
+ ev = self.eview(self.G)(data=True)
447
+ rep = (
448
+ "InEdgeDataView([(0, 1, {}), (1, 2, {}), "
449
+ + "(2, 3, {}), (3, 4, {}), "
450
+ + "(4, 5, {}), (5, 6, {}), "
451
+ + "(6, 7, {}), (7, 8, {})])"
452
+ )
453
+ assert repr(ev) == rep
454
+
455
+ def test_contains_with_nbunch(self):
456
+ evr = self.eview(self.G)
457
+ ev = evr(nbunch=[0, 2])
458
+ assert (0, 1) not in ev
459
+ assert (1, 2) in ev
460
+ assert (2, 3) not in ev
461
+ assert (3, 4) not in ev
462
+ assert (4, 5) not in ev
463
+ assert (5, 6) not in ev
464
+ assert (7, 8) not in ev
465
+ assert (8, 9) not in ev
466
+
467
+
468
+ class TestMultiEdgeDataView(TestEdgeDataView):
469
+ @classmethod
470
+ def setup_class(cls):
471
+ cls.G = nx.path_graph(9, create_using=nx.MultiGraph())
472
+ cls.eview = nx.reportviews.MultiEdgeView
473
+
474
+ def modify_edge(self, G, e, **kwds):
475
+ G._adj[e[0]][e[1]][0].update(kwds)
476
+
477
+ def test_repr(self):
478
+ ev = self.eview(self.G)(data=True)
479
+ rep = (
480
+ "MultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
481
+ + "(2, 3, {}), (3, 4, {}), "
482
+ + "(4, 5, {}), (5, 6, {}), "
483
+ + "(6, 7, {}), (7, 8, {})])"
484
+ )
485
+ assert repr(ev) == rep
486
+
487
+ def test_contains_with_nbunch(self):
488
+ evr = self.eview(self.G)
489
+ ev = evr(nbunch=[0, 2])
490
+ assert (0, 1) in ev
491
+ assert (1, 2) in ev
492
+ assert (2, 3) in ev
493
+ assert (3, 4) not in ev
494
+ assert (4, 5) not in ev
495
+ assert (5, 6) not in ev
496
+ assert (7, 8) not in ev
497
+ assert (8, 9) not in ev
498
+
499
+
500
+ class TestOutMultiEdgeDataView(TestOutEdgeDataView):
501
+ @classmethod
502
+ def setup_class(cls):
503
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
504
+ cls.eview = nx.reportviews.OutMultiEdgeView
505
+
506
+ def modify_edge(self, G, e, **kwds):
507
+ G._adj[e[0]][e[1]][0].update(kwds)
508
+
509
+ def test_repr(self):
510
+ ev = self.eview(self.G)(data=True)
511
+ rep = (
512
+ "OutMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
513
+ + "(2, 3, {}), (3, 4, {}), "
514
+ + "(4, 5, {}), (5, 6, {}), "
515
+ + "(6, 7, {}), (7, 8, {})])"
516
+ )
517
+ assert repr(ev) == rep
518
+
519
+ def test_contains_with_nbunch(self):
520
+ evr = self.eview(self.G)
521
+ ev = evr(nbunch=[0, 2])
522
+ assert (0, 1) in ev
523
+ assert (1, 2) not in ev
524
+ assert (2, 3) in ev
525
+ assert (3, 4) not in ev
526
+ assert (4, 5) not in ev
527
+ assert (5, 6) not in ev
528
+ assert (7, 8) not in ev
529
+ assert (8, 9) not in ev
530
+
531
+
532
+ class TestInMultiEdgeDataView(TestOutMultiEdgeDataView):
533
+ @classmethod
534
+ def setup_class(cls):
535
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
536
+ cls.eview = nx.reportviews.InMultiEdgeView
537
+
538
+ def test_repr(self):
539
+ ev = self.eview(self.G)(data=True)
540
+ rep = (
541
+ "InMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
542
+ + "(2, 3, {}), (3, 4, {}), "
543
+ + "(4, 5, {}), (5, 6, {}), "
544
+ + "(6, 7, {}), (7, 8, {})])"
545
+ )
546
+ assert repr(ev) == rep
547
+
548
+ def test_contains_with_nbunch(self):
549
+ evr = self.eview(self.G)
550
+ ev = evr(nbunch=[0, 2])
551
+ assert (0, 1) not in ev
552
+ assert (1, 2) in ev
553
+ assert (2, 3) not in ev
554
+ assert (3, 4) not in ev
555
+ assert (4, 5) not in ev
556
+ assert (5, 6) not in ev
557
+ assert (7, 8) not in ev
558
+ assert (8, 9) not in ev
559
+
560
+
561
+ # Edge Views
562
+ class TestEdgeView:
563
+ @classmethod
564
+ def setup_class(cls):
565
+ cls.G = nx.path_graph(9)
566
+ cls.eview = nx.reportviews.EdgeView
567
+
568
+ def test_pickle(self):
569
+ import pickle
570
+
571
+ ev = self.eview(self.G)
572
+ pev = pickle.loads(pickle.dumps(ev, -1))
573
+ assert ev == pev
574
+ assert ev.__slots__ == pev.__slots__
575
+
576
+ def modify_edge(self, G, e, **kwds):
577
+ G._adj[e[0]][e[1]].update(kwds)
578
+
579
+ def test_str(self):
580
+ ev = self.eview(self.G)
581
+ rep = str([(n, n + 1) for n in range(8)])
582
+ assert str(ev) == rep
583
+
584
+ def test_repr(self):
585
+ ev = self.eview(self.G)
586
+ rep = (
587
+ "EdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
588
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
589
+ )
590
+ assert repr(ev) == rep
591
+
592
+ def test_getitem(self):
593
+ G = self.G.copy()
594
+ ev = G.edges
595
+ G.edges[0, 1]["foo"] = "bar"
596
+ assert ev[0, 1] == {"foo": "bar"}
597
+
598
+ # slicing
599
+ with pytest.raises(nx.NetworkXError, match=".*does not support slicing"):
600
+ G.edges[0:5]
601
+
602
+ # Invalid edge
603
+ with pytest.raises(KeyError, match=r".*edge.*is not in the graph."):
604
+ G.edges[0, 9]
605
+
606
+ def test_call(self):
607
+ ev = self.eview(self.G)
608
+ assert id(ev) == id(ev())
609
+ assert id(ev) == id(ev(data=False))
610
+ assert id(ev) != id(ev(data=True))
611
+ assert id(ev) != id(ev(nbunch=1))
612
+
613
+ def test_data(self):
614
+ ev = self.eview(self.G)
615
+ assert id(ev) != id(ev.data())
616
+ assert id(ev) == id(ev.data(data=False))
617
+ assert id(ev) != id(ev.data(data=True))
618
+ assert id(ev) != id(ev.data(nbunch=1))
619
+
620
+ def test_iter(self):
621
+ ev = self.eview(self.G)
622
+ for u, v in ev:
623
+ pass
624
+ iev = iter(ev)
625
+ assert next(iev) == (0, 1)
626
+ assert iter(ev) != ev
627
+ assert iter(iev) == iev
628
+
629
+ def test_contains(self):
630
+ ev = self.eview(self.G)
631
+ edv = ev()
632
+ if self.G.is_directed():
633
+ assert (1, 2) in ev and (2, 1) not in ev
634
+ assert (1, 2) in edv and (2, 1) not in edv
635
+ else:
636
+ assert (1, 2) in ev and (2, 1) in ev
637
+ assert (1, 2) in edv and (2, 1) in edv
638
+ assert (1, 4) not in ev
639
+ assert (1, 4) not in edv
640
+ # edge not in graph
641
+ assert (1, 90) not in ev
642
+ assert (90, 1) not in ev
643
+ assert (1, 90) not in edv
644
+ assert (90, 1) not in edv
645
+
646
+ def test_contains_with_nbunch(self):
647
+ ev = self.eview(self.G)
648
+ evn = ev(nbunch=[0, 2])
649
+ assert (0, 1) in evn
650
+ assert (1, 2) in evn
651
+ assert (2, 3) in evn
652
+ assert (3, 4) not in evn
653
+ assert (4, 5) not in evn
654
+ assert (5, 6) not in evn
655
+ assert (7, 8) not in evn
656
+ assert (8, 9) not in evn
657
+
658
+ def test_len(self):
659
+ ev = self.eview(self.G)
660
+ num_ed = 9 if self.G.is_multigraph() else 8
661
+ assert len(ev) == num_ed
662
+
663
+ H = self.G.copy()
664
+ H.add_edge(1, 1)
665
+ assert len(H.edges(1)) == 3 + H.is_multigraph() - H.is_directed()
666
+ assert len(H.edges()) == num_ed + 1
667
+ assert len(H.edges) == num_ed + 1
668
+
669
+ def test_and(self):
670
+ # print("G & H edges:", gnv & hnv)
671
+ ev = self.eview(self.G)
672
+ some_edges = {(0, 1), (1, 0), (0, 2)}
673
+ if self.G.is_directed():
674
+ assert some_edges & ev, {(0, 1)}
675
+ assert ev & some_edges, {(0, 1)}
676
+ else:
677
+ assert ev & some_edges == {(0, 1), (1, 0)}
678
+ assert some_edges & ev == {(0, 1), (1, 0)}
679
+ return
680
+
681
+ def test_or(self):
682
+ # print("G | H edges:", gnv | hnv)
683
+ ev = self.eview(self.G)
684
+ some_edges = {(0, 1), (1, 0), (0, 2)}
685
+ result1 = {(n, n + 1) for n in range(8)}
686
+ result1.update(some_edges)
687
+ result2 = {(n + 1, n) for n in range(8)}
688
+ result2.update(some_edges)
689
+ assert (ev | some_edges) in (result1, result2)
690
+ assert (some_edges | ev) in (result1, result2)
691
+
692
+ def test_xor(self):
693
+ # print("G ^ H edges:", gnv ^ hnv)
694
+ ev = self.eview(self.G)
695
+ some_edges = {(0, 1), (1, 0), (0, 2)}
696
+ if self.G.is_directed():
697
+ result = {(n, n + 1) for n in range(1, 8)}
698
+ result.update({(1, 0), (0, 2)})
699
+ assert ev ^ some_edges == result
700
+ else:
701
+ result = {(n, n + 1) for n in range(1, 8)}
702
+ result.update({(0, 2)})
703
+ assert ev ^ some_edges == result
704
+ return
705
+
706
+ def test_sub(self):
707
+ # print("G - H edges:", gnv - hnv)
708
+ ev = self.eview(self.G)
709
+ some_edges = {(0, 1), (1, 0), (0, 2)}
710
+ result = {(n, n + 1) for n in range(8)}
711
+ result.remove((0, 1))
712
+ assert ev - some_edges, result
713
+
714
+
715
+ class TestOutEdgeView(TestEdgeView):
716
+ @classmethod
717
+ def setup_class(cls):
718
+ cls.G = nx.path_graph(9, nx.DiGraph())
719
+ cls.eview = nx.reportviews.OutEdgeView
720
+
721
+ def test_repr(self):
722
+ ev = self.eview(self.G)
723
+ rep = (
724
+ "OutEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
725
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
726
+ )
727
+ assert repr(ev) == rep
728
+
729
+ def test_contains_with_nbunch(self):
730
+ ev = self.eview(self.G)
731
+ evn = ev(nbunch=[0, 2])
732
+ assert (0, 1) in evn
733
+ assert (1, 2) not in evn
734
+ assert (2, 3) in evn
735
+ assert (3, 4) not in evn
736
+ assert (4, 5) not in evn
737
+ assert (5, 6) not in evn
738
+ assert (7, 8) not in evn
739
+ assert (8, 9) not in evn
740
+
741
+
742
+ class TestInEdgeView(TestEdgeView):
743
+ @classmethod
744
+ def setup_class(cls):
745
+ cls.G = nx.path_graph(9, nx.DiGraph())
746
+ cls.eview = nx.reportviews.InEdgeView
747
+
748
+ def test_repr(self):
749
+ ev = self.eview(self.G)
750
+ rep = (
751
+ "InEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
752
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
753
+ )
754
+ assert repr(ev) == rep
755
+
756
+ def test_contains_with_nbunch(self):
757
+ ev = self.eview(self.G)
758
+ evn = ev(nbunch=[0, 2])
759
+ assert (0, 1) not in evn
760
+ assert (1, 2) in evn
761
+ assert (2, 3) not in evn
762
+ assert (3, 4) not in evn
763
+ assert (4, 5) not in evn
764
+ assert (5, 6) not in evn
765
+ assert (7, 8) not in evn
766
+ assert (8, 9) not in evn
767
+
768
+
769
+ class TestMultiEdgeView(TestEdgeView):
770
+ @classmethod
771
+ def setup_class(cls):
772
+ cls.G = nx.path_graph(9, nx.MultiGraph())
773
+ cls.G.add_edge(1, 2, key=3, foo="bar")
774
+ cls.eview = nx.reportviews.MultiEdgeView
775
+
776
+ def modify_edge(self, G, e, **kwds):
777
+ if len(e) == 2:
778
+ e = e + (0,)
779
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
780
+
781
+ def test_str(self):
782
+ ev = self.eview(self.G)
783
+ replist = [(n, n + 1, 0) for n in range(8)]
784
+ replist.insert(2, (1, 2, 3))
785
+ rep = str(replist)
786
+ assert str(ev) == rep
787
+
788
+ def test_getitem(self):
789
+ G = self.G.copy()
790
+ ev = G.edges
791
+ G.edges[0, 1, 0]["foo"] = "bar"
792
+ assert ev[0, 1, 0] == {"foo": "bar"}
793
+
794
+ # slicing
795
+ with pytest.raises(nx.NetworkXError):
796
+ G.edges[0:5]
797
+
798
+ def test_repr(self):
799
+ ev = self.eview(self.G)
800
+ rep = (
801
+ "MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
802
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
803
+ )
804
+ assert repr(ev) == rep
805
+
806
+ def test_call(self):
807
+ ev = self.eview(self.G)
808
+ assert id(ev) == id(ev(keys=True))
809
+ assert id(ev) == id(ev(data=False, keys=True))
810
+ assert id(ev) != id(ev(keys=False))
811
+ assert id(ev) != id(ev(data=True))
812
+ assert id(ev) != id(ev(nbunch=1))
813
+
814
+ def test_data(self):
815
+ ev = self.eview(self.G)
816
+ assert id(ev) != id(ev.data())
817
+ assert id(ev) == id(ev.data(data=False, keys=True))
818
+ assert id(ev) != id(ev.data(keys=False))
819
+ assert id(ev) != id(ev.data(data=True))
820
+ assert id(ev) != id(ev.data(nbunch=1))
821
+
822
+ def test_iter(self):
823
+ ev = self.eview(self.G)
824
+ for u, v, k in ev:
825
+ pass
826
+ iev = iter(ev)
827
+ assert next(iev) == (0, 1, 0)
828
+ assert iter(ev) != ev
829
+ assert iter(iev) == iev
830
+
831
+ def test_iterkeys(self):
832
+ G = self.G
833
+ evr = self.eview(G)
834
+ ev = evr(keys=True)
835
+ for u, v, k in ev:
836
+ pass
837
+ assert k == 0
838
+ ev = evr(keys=True, data="foo", default=1)
839
+ for u, v, k, wt in ev:
840
+ pass
841
+ assert wt == 1
842
+
843
+ self.modify_edge(G, (2, 3, 0), foo="bar")
844
+ ev = evr(keys=True, data=True)
845
+ for e in ev:
846
+ assert len(e) == 4
847
+ print("edge:", e)
848
+ if set(e[:2]) == {2, 3}:
849
+ print(self.G._adj[2][3])
850
+ assert e[2] == 0
851
+ assert e[3] == {"foo": "bar"}
852
+ checked = True
853
+ elif set(e[:3]) == {1, 2, 3}:
854
+ assert e[2] == 3
855
+ assert e[3] == {"foo": "bar"}
856
+ checked_multi = True
857
+ else:
858
+ assert e[2] == 0
859
+ assert e[3] == {}
860
+ assert checked
861
+ assert checked_multi
862
+ ev = evr(keys=True, data="foo", default=1)
863
+ for e in ev:
864
+ if set(e[:2]) == {1, 2} and e[2] == 3:
865
+ assert e[3] == "bar"
866
+ if set(e[:2]) == {1, 2} and e[2] == 0:
867
+ assert e[3] == 1
868
+ if set(e[:2]) == {2, 3}:
869
+ assert e[2] == 0
870
+ assert e[3] == "bar"
871
+ assert len(e) == 4
872
+ checked_wt = True
873
+ assert checked_wt
874
+ ev = evr(keys=True)
875
+ for e in ev:
876
+ assert len(e) == 3
877
+ elist = sorted([(i, i + 1, 0) for i in range(8)] + [(1, 2, 3)])
878
+ assert sorted(ev) == elist
879
+ # test that the keyword arguments are passed correctly
880
+ ev = evr((1, 2), "foo", keys=True, default=1)
881
+ with pytest.raises(TypeError):
882
+ evr((1, 2), "foo", True, 1)
883
+ with pytest.raises(TypeError):
884
+ evr((1, 2), "foo", True, default=1)
885
+ for e in ev:
886
+ if set(e[:2]) == {1, 2}:
887
+ assert e[2] in {0, 3}
888
+ if e[2] == 3:
889
+ assert e[3] == "bar"
890
+ else: # e[2] == 0
891
+ assert e[3] == 1
892
+ if G.is_directed():
893
+ assert len(list(ev)) == 3
894
+ else:
895
+ assert len(list(ev)) == 4
896
+
897
+ def test_or(self):
898
+ # print("G | H edges:", gnv | hnv)
899
+ ev = self.eview(self.G)
900
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
901
+ result = {(n, n + 1, 0) for n in range(8)}
902
+ result.update(some_edges)
903
+ result.update({(1, 2, 3)})
904
+ assert ev | some_edges == result
905
+ assert some_edges | ev == result
906
+
907
+ def test_sub(self):
908
+ # print("G - H edges:", gnv - hnv)
909
+ ev = self.eview(self.G)
910
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
911
+ result = {(n, n + 1, 0) for n in range(8)}
912
+ result.remove((0, 1, 0))
913
+ result.update({(1, 2, 3)})
914
+ assert ev - some_edges, result
915
+ assert some_edges - ev, result
916
+
917
+ def test_xor(self):
918
+ # print("G ^ H edges:", gnv ^ hnv)
919
+ ev = self.eview(self.G)
920
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
921
+ if self.G.is_directed():
922
+ result = {(n, n + 1, 0) for n in range(1, 8)}
923
+ result.update({(1, 0, 0), (0, 2, 0), (1, 2, 3)})
924
+ assert ev ^ some_edges == result
925
+ assert some_edges ^ ev == result
926
+ else:
927
+ result = {(n, n + 1, 0) for n in range(1, 8)}
928
+ result.update({(0, 2, 0), (1, 2, 3)})
929
+ assert ev ^ some_edges == result
930
+ assert some_edges ^ ev == result
931
+
932
+ def test_and(self):
933
+ # print("G & H edges:", gnv & hnv)
934
+ ev = self.eview(self.G)
935
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
936
+ if self.G.is_directed():
937
+ assert ev & some_edges == {(0, 1, 0)}
938
+ assert some_edges & ev == {(0, 1, 0)}
939
+ else:
940
+ assert ev & some_edges == {(0, 1, 0), (1, 0, 0)}
941
+ assert some_edges & ev == {(0, 1, 0), (1, 0, 0)}
942
+
943
+ def test_contains_with_nbunch(self):
944
+ ev = self.eview(self.G)
945
+ evn = ev(nbunch=[0, 2])
946
+ assert (0, 1) in evn
947
+ assert (1, 2) in evn
948
+ assert (2, 3) in evn
949
+ assert (3, 4) not in evn
950
+ assert (4, 5) not in evn
951
+ assert (5, 6) not in evn
952
+ assert (7, 8) not in evn
953
+ assert (8, 9) not in evn
954
+
955
+
956
+ class TestOutMultiEdgeView(TestMultiEdgeView):
957
+ @classmethod
958
+ def setup_class(cls):
959
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
960
+ cls.G.add_edge(1, 2, key=3, foo="bar")
961
+ cls.eview = nx.reportviews.OutMultiEdgeView
962
+
963
+ def modify_edge(self, G, e, **kwds):
964
+ if len(e) == 2:
965
+ e = e + (0,)
966
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
967
+
968
+ def test_repr(self):
969
+ ev = self.eview(self.G)
970
+ rep = (
971
+ "OutMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0),"
972
+ + " (3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
973
+ )
974
+ assert repr(ev) == rep
975
+
976
+ def test_contains_with_nbunch(self):
977
+ ev = self.eview(self.G)
978
+ evn = ev(nbunch=[0, 2])
979
+ assert (0, 1) in evn
980
+ assert (1, 2) not in evn
981
+ assert (2, 3) in evn
982
+ assert (3, 4) not in evn
983
+ assert (4, 5) not in evn
984
+ assert (5, 6) not in evn
985
+ assert (7, 8) not in evn
986
+ assert (8, 9) not in evn
987
+
988
+
989
+ class TestInMultiEdgeView(TestMultiEdgeView):
990
+ @classmethod
991
+ def setup_class(cls):
992
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
993
+ cls.G.add_edge(1, 2, key=3, foo="bar")
994
+ cls.eview = nx.reportviews.InMultiEdgeView
995
+
996
+ def modify_edge(self, G, e, **kwds):
997
+ if len(e) == 2:
998
+ e = e + (0,)
999
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
1000
+
1001
+ def test_repr(self):
1002
+ ev = self.eview(self.G)
1003
+ rep = (
1004
+ "InMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
1005
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
1006
+ )
1007
+ assert repr(ev) == rep
1008
+
1009
+ def test_contains_with_nbunch(self):
1010
+ ev = self.eview(self.G)
1011
+ evn = ev(nbunch=[0, 2])
1012
+ assert (0, 1) not in evn
1013
+ assert (1, 2) in evn
1014
+ assert (2, 3) not in evn
1015
+ assert (3, 4) not in evn
1016
+ assert (4, 5) not in evn
1017
+ assert (5, 6) not in evn
1018
+ assert (7, 8) not in evn
1019
+ assert (8, 9) not in evn
1020
+
1021
+
1022
+ # Degrees
1023
+ class TestDegreeView:
1024
+ GRAPH = nx.Graph
1025
+ dview = nx.reportviews.DegreeView
1026
+
1027
+ @classmethod
1028
+ def setup_class(cls):
1029
+ cls.G = nx.path_graph(6, cls.GRAPH())
1030
+ cls.G.add_edge(1, 3, foo=2)
1031
+ cls.G.add_edge(1, 3, foo=3)
1032
+
1033
+ def test_pickle(self):
1034
+ import pickle
1035
+
1036
+ deg = self.G.degree
1037
+ pdeg = pickle.loads(pickle.dumps(deg, -1))
1038
+ assert dict(deg) == dict(pdeg)
1039
+
1040
+ def test_str(self):
1041
+ dv = self.dview(self.G)
1042
+ rep = str([(0, 1), (1, 3), (2, 2), (3, 3), (4, 2), (5, 1)])
1043
+ assert str(dv) == rep
1044
+ dv = self.G.degree()
1045
+ assert str(dv) == rep
1046
+
1047
+ def test_repr(self):
1048
+ dv = self.dview(self.G)
1049
+ rep = "DegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1050
+ assert repr(dv) == rep
1051
+
1052
+ def test_iter(self):
1053
+ dv = self.dview(self.G)
1054
+ for n, d in dv:
1055
+ pass
1056
+ idv = iter(dv)
1057
+ assert iter(dv) != dv
1058
+ assert iter(idv) == idv
1059
+ assert next(idv) == (0, dv[0])
1060
+ assert next(idv) == (1, dv[1])
1061
+ # weighted
1062
+ dv = self.dview(self.G, weight="foo")
1063
+ for n, d in dv:
1064
+ pass
1065
+ idv = iter(dv)
1066
+ assert iter(dv) != dv
1067
+ assert iter(idv) == idv
1068
+ assert next(idv) == (0, dv[0])
1069
+ assert next(idv) == (1, dv[1])
1070
+
1071
+ def test_nbunch(self):
1072
+ dv = self.dview(self.G)
1073
+ dvn = dv(0)
1074
+ assert dvn == 1
1075
+ dvn = dv([2, 3])
1076
+ assert sorted(dvn) == [(2, 2), (3, 3)]
1077
+
1078
+ def test_getitem(self):
1079
+ dv = self.dview(self.G)
1080
+ assert dv[0] == 1
1081
+ assert dv[1] == 3
1082
+ assert dv[2] == 2
1083
+ assert dv[3] == 3
1084
+ dv = self.dview(self.G, weight="foo")
1085
+ assert dv[0] == 1
1086
+ assert dv[1] == 5
1087
+ assert dv[2] == 2
1088
+ assert dv[3] == 5
1089
+
1090
+ def test_weight(self):
1091
+ dv = self.dview(self.G)
1092
+ dvw = dv(0, weight="foo")
1093
+ assert dvw == 1
1094
+ dvw = dv(1, weight="foo")
1095
+ assert dvw == 5
1096
+ dvw = dv([2, 3], weight="foo")
1097
+ assert sorted(dvw) == [(2, 2), (3, 5)]
1098
+ dvd = dict(dv(weight="foo"))
1099
+ assert dvd[0] == 1
1100
+ assert dvd[1] == 5
1101
+ assert dvd[2] == 2
1102
+ assert dvd[3] == 5
1103
+
1104
+ def test_len(self):
1105
+ dv = self.dview(self.G)
1106
+ assert len(dv) == 6
1107
+
1108
+
1109
+ class TestDiDegreeView(TestDegreeView):
1110
+ GRAPH = nx.DiGraph
1111
+ dview = nx.reportviews.DiDegreeView
1112
+
1113
+ def test_repr(self):
1114
+ dv = self.G.degree()
1115
+ rep = "DiDegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1116
+ assert repr(dv) == rep
1117
+
1118
+
1119
+ class TestOutDegreeView(TestDegreeView):
1120
+ GRAPH = nx.DiGraph
1121
+ dview = nx.reportviews.OutDegreeView
1122
+
1123
+ def test_str(self):
1124
+ dv = self.dview(self.G)
1125
+ rep = str([(0, 1), (1, 2), (2, 1), (3, 1), (4, 1), (5, 0)])
1126
+ assert str(dv) == rep
1127
+ dv = self.G.out_degree()
1128
+ assert str(dv) == rep
1129
+
1130
+ def test_repr(self):
1131
+ dv = self.G.out_degree()
1132
+ rep = "OutDegreeView({0: 1, 1: 2, 2: 1, 3: 1, 4: 1, 5: 0})"
1133
+ assert repr(dv) == rep
1134
+
1135
+ def test_nbunch(self):
1136
+ dv = self.dview(self.G)
1137
+ dvn = dv(0)
1138
+ assert dvn == 1
1139
+ dvn = dv([2, 3])
1140
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1141
+
1142
+ def test_getitem(self):
1143
+ dv = self.dview(self.G)
1144
+ assert dv[0] == 1
1145
+ assert dv[1] == 2
1146
+ assert dv[2] == 1
1147
+ assert dv[3] == 1
1148
+ dv = self.dview(self.G, weight="foo")
1149
+ assert dv[0] == 1
1150
+ assert dv[1] == 4
1151
+ assert dv[2] == 1
1152
+ assert dv[3] == 1
1153
+
1154
+ def test_weight(self):
1155
+ dv = self.dview(self.G)
1156
+ dvw = dv(0, weight="foo")
1157
+ assert dvw == 1
1158
+ dvw = dv(1, weight="foo")
1159
+ assert dvw == 4
1160
+ dvw = dv([2, 3], weight="foo")
1161
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1162
+ dvd = dict(dv(weight="foo"))
1163
+ assert dvd[0] == 1
1164
+ assert dvd[1] == 4
1165
+ assert dvd[2] == 1
1166
+ assert dvd[3] == 1
1167
+
1168
+
1169
+ class TestInDegreeView(TestDegreeView):
1170
+ GRAPH = nx.DiGraph
1171
+ dview = nx.reportviews.InDegreeView
1172
+
1173
+ def test_str(self):
1174
+ dv = self.dview(self.G)
1175
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 2), (4, 1), (5, 1)])
1176
+ assert str(dv) == rep
1177
+ dv = self.G.in_degree()
1178
+ assert str(dv) == rep
1179
+
1180
+ def test_repr(self):
1181
+ dv = self.G.in_degree()
1182
+ rep = "InDegreeView({0: 0, 1: 1, 2: 1, 3: 2, 4: 1, 5: 1})"
1183
+ assert repr(dv) == rep
1184
+
1185
+ def test_nbunch(self):
1186
+ dv = self.dview(self.G)
1187
+ dvn = dv(0)
1188
+ assert dvn == 0
1189
+ dvn = dv([2, 3])
1190
+ assert sorted(dvn) == [(2, 1), (3, 2)]
1191
+
1192
+ def test_getitem(self):
1193
+ dv = self.dview(self.G)
1194
+ assert dv[0] == 0
1195
+ assert dv[1] == 1
1196
+ assert dv[2] == 1
1197
+ assert dv[3] == 2
1198
+ dv = self.dview(self.G, weight="foo")
1199
+ assert dv[0] == 0
1200
+ assert dv[1] == 1
1201
+ assert dv[2] == 1
1202
+ assert dv[3] == 4
1203
+
1204
+ def test_weight(self):
1205
+ dv = self.dview(self.G)
1206
+ dvw = dv(0, weight="foo")
1207
+ assert dvw == 0
1208
+ dvw = dv(1, weight="foo")
1209
+ assert dvw == 1
1210
+ dvw = dv([2, 3], weight="foo")
1211
+ assert sorted(dvw) == [(2, 1), (3, 4)]
1212
+ dvd = dict(dv(weight="foo"))
1213
+ assert dvd[0] == 0
1214
+ assert dvd[1] == 1
1215
+ assert dvd[2] == 1
1216
+ assert dvd[3] == 4
1217
+
1218
+
1219
+ class TestMultiDegreeView(TestDegreeView):
1220
+ GRAPH = nx.MultiGraph
1221
+ dview = nx.reportviews.MultiDegreeView
1222
+
1223
+ def test_str(self):
1224
+ dv = self.dview(self.G)
1225
+ rep = str([(0, 1), (1, 4), (2, 2), (3, 4), (4, 2), (5, 1)])
1226
+ assert str(dv) == rep
1227
+ dv = self.G.degree()
1228
+ assert str(dv) == rep
1229
+
1230
+ def test_repr(self):
1231
+ dv = self.G.degree()
1232
+ rep = "MultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1233
+ assert repr(dv) == rep
1234
+
1235
+ def test_nbunch(self):
1236
+ dv = self.dview(self.G)
1237
+ dvn = dv(0)
1238
+ assert dvn == 1
1239
+ dvn = dv([2, 3])
1240
+ assert sorted(dvn) == [(2, 2), (3, 4)]
1241
+
1242
+ def test_getitem(self):
1243
+ dv = self.dview(self.G)
1244
+ assert dv[0] == 1
1245
+ assert dv[1] == 4
1246
+ assert dv[2] == 2
1247
+ assert dv[3] == 4
1248
+ dv = self.dview(self.G, weight="foo")
1249
+ assert dv[0] == 1
1250
+ assert dv[1] == 7
1251
+ assert dv[2] == 2
1252
+ assert dv[3] == 7
1253
+
1254
+ def test_weight(self):
1255
+ dv = self.dview(self.G)
1256
+ dvw = dv(0, weight="foo")
1257
+ assert dvw == 1
1258
+ dvw = dv(1, weight="foo")
1259
+ assert dvw == 7
1260
+ dvw = dv([2, 3], weight="foo")
1261
+ assert sorted(dvw) == [(2, 2), (3, 7)]
1262
+ dvd = dict(dv(weight="foo"))
1263
+ assert dvd[0] == 1
1264
+ assert dvd[1] == 7
1265
+ assert dvd[2] == 2
1266
+ assert dvd[3] == 7
1267
+
1268
+
1269
+ class TestDiMultiDegreeView(TestMultiDegreeView):
1270
+ GRAPH = nx.MultiDiGraph
1271
+ dview = nx.reportviews.DiMultiDegreeView
1272
+
1273
+ def test_repr(self):
1274
+ dv = self.G.degree()
1275
+ rep = "DiMultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1276
+ assert repr(dv) == rep
1277
+
1278
+
1279
+ class TestOutMultiDegreeView(TestDegreeView):
1280
+ GRAPH = nx.MultiDiGraph
1281
+ dview = nx.reportviews.OutMultiDegreeView
1282
+
1283
+ def test_str(self):
1284
+ dv = self.dview(self.G)
1285
+ rep = str([(0, 1), (1, 3), (2, 1), (3, 1), (4, 1), (5, 0)])
1286
+ assert str(dv) == rep
1287
+ dv = self.G.out_degree()
1288
+ assert str(dv) == rep
1289
+
1290
+ def test_repr(self):
1291
+ dv = self.G.out_degree()
1292
+ rep = "OutMultiDegreeView({0: 1, 1: 3, 2: 1, 3: 1, 4: 1, 5: 0})"
1293
+ assert repr(dv) == rep
1294
+
1295
+ def test_nbunch(self):
1296
+ dv = self.dview(self.G)
1297
+ dvn = dv(0)
1298
+ assert dvn == 1
1299
+ dvn = dv([2, 3])
1300
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1301
+
1302
+ def test_getitem(self):
1303
+ dv = self.dview(self.G)
1304
+ assert dv[0] == 1
1305
+ assert dv[1] == 3
1306
+ assert dv[2] == 1
1307
+ assert dv[3] == 1
1308
+ dv = self.dview(self.G, weight="foo")
1309
+ assert dv[0] == 1
1310
+ assert dv[1] == 6
1311
+ assert dv[2] == 1
1312
+ assert dv[3] == 1
1313
+
1314
+ def test_weight(self):
1315
+ dv = self.dview(self.G)
1316
+ dvw = dv(0, weight="foo")
1317
+ assert dvw == 1
1318
+ dvw = dv(1, weight="foo")
1319
+ assert dvw == 6
1320
+ dvw = dv([2, 3], weight="foo")
1321
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1322
+ dvd = dict(dv(weight="foo"))
1323
+ assert dvd[0] == 1
1324
+ assert dvd[1] == 6
1325
+ assert dvd[2] == 1
1326
+ assert dvd[3] == 1
1327
+
1328
+
1329
+ class TestInMultiDegreeView(TestDegreeView):
1330
+ GRAPH = nx.MultiDiGraph
1331
+ dview = nx.reportviews.InMultiDegreeView
1332
+
1333
+ def test_str(self):
1334
+ dv = self.dview(self.G)
1335
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 3), (4, 1), (5, 1)])
1336
+ assert str(dv) == rep
1337
+ dv = self.G.in_degree()
1338
+ assert str(dv) == rep
1339
+
1340
+ def test_repr(self):
1341
+ dv = self.G.in_degree()
1342
+ rep = "InMultiDegreeView({0: 0, 1: 1, 2: 1, 3: 3, 4: 1, 5: 1})"
1343
+ assert repr(dv) == rep
1344
+
1345
+ def test_nbunch(self):
1346
+ dv = self.dview(self.G)
1347
+ dvn = dv(0)
1348
+ assert dvn == 0
1349
+ dvn = dv([2, 3])
1350
+ assert sorted(dvn) == [(2, 1), (3, 3)]
1351
+
1352
+ def test_getitem(self):
1353
+ dv = self.dview(self.G)
1354
+ assert dv[0] == 0
1355
+ assert dv[1] == 1
1356
+ assert dv[2] == 1
1357
+ assert dv[3] == 3
1358
+ dv = self.dview(self.G, weight="foo")
1359
+ assert dv[0] == 0
1360
+ assert dv[1] == 1
1361
+ assert dv[2] == 1
1362
+ assert dv[3] == 6
1363
+
1364
+ def test_weight(self):
1365
+ dv = self.dview(self.G)
1366
+ dvw = dv(0, weight="foo")
1367
+ assert dvw == 0
1368
+ dvw = dv(1, weight="foo")
1369
+ assert dvw == 1
1370
+ dvw = dv([2, 3], weight="foo")
1371
+ assert sorted(dvw) == [(2, 1), (3, 6)]
1372
+ dvd = dict(dv(weight="foo"))
1373
+ assert dvd[0] == 0
1374
+ assert dvd[1] == 1
1375
+ assert dvd[2] == 1
1376
+ assert dvd[3] == 6
1377
+
1378
+
1379
+ @pytest.mark.parametrize(
1380
+ ("reportview", "err_msg_terms"),
1381
+ (
1382
+ (rv.NodeView, "list(G.nodes"),
1383
+ (rv.NodeDataView, "list(G.nodes.data"),
1384
+ (rv.EdgeView, "list(G.edges"),
1385
+ # Directed EdgeViews
1386
+ (rv.InEdgeView, "list(G.in_edges"),
1387
+ (rv.OutEdgeView, "list(G.edges"),
1388
+ # Multi EdgeViews
1389
+ (rv.MultiEdgeView, "list(G.edges"),
1390
+ (rv.InMultiEdgeView, "list(G.in_edges"),
1391
+ (rv.OutMultiEdgeView, "list(G.edges"),
1392
+ ),
1393
+ )
1394
+ def test_slicing_reportviews(reportview, err_msg_terms):
1395
+ G = nx.complete_graph(3)
1396
+ view = reportview(G)
1397
+ with pytest.raises(nx.NetworkXError) as exc:
1398
+ view[0:2]
1399
+ errmsg = str(exc.value)
1400
+ assert type(view).__name__ in errmsg
1401
+ assert err_msg_terms in errmsg
1402
+
1403
+
1404
+ @pytest.mark.parametrize(
1405
+ "graph", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
1406
+ )
1407
+ def test_cache_dict_get_set_state(graph):
1408
+ G = nx.path_graph(5, graph())
1409
+ G.nodes, G.edges, G.adj, G.degree
1410
+ if G.is_directed():
1411
+ G.pred, G.succ, G.in_edges, G.out_edges, G.in_degree, G.out_degree
1412
+ cached_dict = G.__dict__
1413
+ assert "nodes" in cached_dict
1414
+ assert "edges" in cached_dict
1415
+ assert "adj" in cached_dict
1416
+ assert "degree" in cached_dict
1417
+ if G.is_directed():
1418
+ assert "pred" in cached_dict
1419
+ assert "succ" in cached_dict
1420
+ assert "in_edges" in cached_dict
1421
+ assert "out_edges" in cached_dict
1422
+ assert "in_degree" in cached_dict
1423
+ assert "out_degree" in cached_dict
1424
+
1425
+ # Raises error if the cached properties and views do not work
1426
+ pickle.loads(pickle.dumps(G, -1))
1427
+ deepcopy(G)
env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png ADDED

Git LFS Details

  • SHA256: 1508bda48445c23ab882f801f1c0dd0472f97ae414245c3ab1094005fda4455a
  • Pointer size: 130 Bytes
  • Size of remote file: 21.9 kB
env-llmeval/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73fc416df0164923607751cb759f4ae81deb5f6550bf25be59c86de3b747e41d
3
+ size 8887
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networkx.linalg.attrmatrix import *
2
+ from networkx.linalg import attrmatrix
3
+ from networkx.linalg.spectrum import *
4
+ from networkx.linalg import spectrum
5
+ from networkx.linalg.graphmatrix import *
6
+ from networkx.linalg import graphmatrix
7
+ from networkx.linalg.laplacianmatrix import *
8
+ from networkx.linalg import laplacianmatrix
9
+ from networkx.linalg.algebraicconnectivity import *
10
+ from networkx.linalg.modularitymatrix import *
11
+ from networkx.linalg import modularitymatrix
12
+ from networkx.linalg.bethehessianmatrix import *
13
+ from networkx.linalg import bethehessianmatrix
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (713 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/bethehessianmatrix.cpython-310.pyc ADDED
Binary file (2.97 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/graphmatrix.cpython-310.pyc ADDED
Binary file (5.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc ADDED
Binary file (4.72 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Algebraic connectivity and Fiedler vectors of undirected graphs.
3
+ """
4
+ from functools import partial
5
+
6
+ import networkx as nx
7
+ from networkx.utils import (
8
+ not_implemented_for,
9
+ np_random_state,
10
+ reverse_cuthill_mckee_ordering,
11
+ )
12
+
13
+ __all__ = [
14
+ "algebraic_connectivity",
15
+ "fiedler_vector",
16
+ "spectral_ordering",
17
+ "spectral_bisection",
18
+ ]
19
+
20
+
21
+ class _PCGSolver:
22
+ """Preconditioned conjugate gradient method.
23
+
24
+ To solve Ax = b:
25
+ M = A.diagonal() # or some other preconditioner
26
+ solver = _PCGSolver(lambda x: A * x, lambda x: M * x)
27
+ x = solver.solve(b)
28
+
29
+ The inputs A and M are functions which compute
30
+ matrix multiplication on the argument.
31
+ A - multiply by the matrix A in Ax=b
32
+ M - multiply by M, the preconditioner surrogate for A
33
+
34
+ Warning: There is no limit on number of iterations.
35
+ """
36
+
37
+ def __init__(self, A, M):
38
+ self._A = A
39
+ self._M = M
40
+
41
+ def solve(self, B, tol):
42
+ import numpy as np
43
+
44
+ # Densifying step - can this be kept sparse?
45
+ B = np.asarray(B)
46
+ X = np.ndarray(B.shape, order="F")
47
+ for j in range(B.shape[1]):
48
+ X[:, j] = self._solve(B[:, j], tol)
49
+ return X
50
+
51
+ def _solve(self, b, tol):
52
+ import numpy as np
53
+ import scipy as sp
54
+
55
+ A = self._A
56
+ M = self._M
57
+ tol *= sp.linalg.blas.dasum(b)
58
+ # Initialize.
59
+ x = np.zeros(b.shape)
60
+ r = b.copy()
61
+ z = M(r)
62
+ rz = sp.linalg.blas.ddot(r, z)
63
+ p = z.copy()
64
+ # Iterate.
65
+ while True:
66
+ Ap = A(p)
67
+ alpha = rz / sp.linalg.blas.ddot(p, Ap)
68
+ x = sp.linalg.blas.daxpy(p, x, a=alpha)
69
+ r = sp.linalg.blas.daxpy(Ap, r, a=-alpha)
70
+ if sp.linalg.blas.dasum(r) < tol:
71
+ return x
72
+ z = M(r)
73
+ beta = sp.linalg.blas.ddot(r, z)
74
+ beta, rz = beta / rz, beta
75
+ p = sp.linalg.blas.daxpy(p, z, a=beta)
76
+
77
+
78
+ class _LUSolver:
79
+ """LU factorization.
80
+
81
+ To solve Ax = b:
82
+ solver = _LUSolver(A)
83
+ x = solver.solve(b)
84
+
85
+ optional argument `tol` on solve method is ignored but included
86
+ to match _PCGsolver API.
87
+ """
88
+
89
+ def __init__(self, A):
90
+ import scipy as sp
91
+
92
+ self._LU = sp.sparse.linalg.splu(
93
+ A,
94
+ permc_spec="MMD_AT_PLUS_A",
95
+ diag_pivot_thresh=0.0,
96
+ options={"Equil": True, "SymmetricMode": True},
97
+ )
98
+
99
+ def solve(self, B, tol=None):
100
+ import numpy as np
101
+
102
+ B = np.asarray(B)
103
+ X = np.ndarray(B.shape, order="F")
104
+ for j in range(B.shape[1]):
105
+ X[:, j] = self._LU.solve(B[:, j])
106
+ return X
107
+
108
+
109
+ def _preprocess_graph(G, weight):
110
+ """Compute edge weights and eliminate zero-weight edges."""
111
+ if G.is_directed():
112
+ H = nx.MultiGraph()
113
+ H.add_nodes_from(G)
114
+ H.add_weighted_edges_from(
115
+ ((u, v, e.get(weight, 1.0)) for u, v, e in G.edges(data=True) if u != v),
116
+ weight=weight,
117
+ )
118
+ G = H
119
+ if not G.is_multigraph():
120
+ edges = (
121
+ (u, v, abs(e.get(weight, 1.0))) for u, v, e in G.edges(data=True) if u != v
122
+ )
123
+ else:
124
+ edges = (
125
+ (u, v, sum(abs(e.get(weight, 1.0)) for e in G[u][v].values()))
126
+ for u, v in G.edges()
127
+ if u != v
128
+ )
129
+ H = nx.Graph()
130
+ H.add_nodes_from(G)
131
+ H.add_weighted_edges_from((u, v, e) for u, v, e in edges if e != 0)
132
+ return H
133
+
134
+
135
+ def _rcm_estimate(G, nodelist):
136
+ """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering."""
137
+ import numpy as np
138
+
139
+ G = G.subgraph(nodelist)
140
+ order = reverse_cuthill_mckee_ordering(G)
141
+ n = len(nodelist)
142
+ index = dict(zip(nodelist, range(n)))
143
+ x = np.ndarray(n, dtype=float)
144
+ for i, u in enumerate(order):
145
+ x[index[u]] = i
146
+ x -= (n - 1) / 2.0
147
+ return x
148
+
149
+
150
+ def _tracemin_fiedler(L, X, normalized, tol, method):
151
+ """Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
152
+
153
+ The Fiedler vector of a connected undirected graph is the eigenvector
154
+ corresponding to the second smallest eigenvalue of the Laplacian matrix
155
+ of the graph. This function starts with the Laplacian L, not the Graph.
156
+
157
+ Parameters
158
+ ----------
159
+ L : Laplacian of a possibly weighted or normalized, but undirected graph
160
+
161
+ X : Initial guess for a solution. Usually a matrix of random numbers.
162
+ This function allows more than one column in X to identify more than
163
+ one eigenvector if desired.
164
+
165
+ normalized : bool
166
+ Whether the normalized Laplacian matrix is used.
167
+
168
+ tol : float
169
+ Tolerance of relative residual in eigenvalue computation.
170
+ Warning: There is no limit on number of iterations.
171
+
172
+ method : string
173
+ Should be 'tracemin_pcg' or 'tracemin_lu'.
174
+ Otherwise exception is raised.
175
+
176
+ Returns
177
+ -------
178
+ sigma, X : Two NumPy arrays of floats.
179
+ The lowest eigenvalues and corresponding eigenvectors of L.
180
+ The size of input X determines the size of these outputs.
181
+ As this is for Fiedler vectors, the zero eigenvalue (and
182
+ constant eigenvector) are avoided.
183
+ """
184
+ import numpy as np
185
+ import scipy as sp
186
+
187
+ n = X.shape[0]
188
+
189
+ if normalized:
190
+ # Form the normalized Laplacian matrix and determine the eigenvector of
191
+ # its nullspace.
192
+ e = np.sqrt(L.diagonal())
193
+ # TODO: rm csr_array wrapper when spdiags array creation becomes available
194
+ D = sp.sparse.csr_array(sp.sparse.spdiags(1 / e, 0, n, n, format="csr"))
195
+ L = D @ L @ D
196
+ e *= 1.0 / np.linalg.norm(e, 2)
197
+
198
+ if normalized:
199
+
200
+ def project(X):
201
+ """Make X orthogonal to the nullspace of L."""
202
+ X = np.asarray(X)
203
+ for j in range(X.shape[1]):
204
+ X[:, j] -= (X[:, j] @ e) * e
205
+
206
+ else:
207
+
208
+ def project(X):
209
+ """Make X orthogonal to the nullspace of L."""
210
+ X = np.asarray(X)
211
+ for j in range(X.shape[1]):
212
+ X[:, j] -= X[:, j].sum() / n
213
+
214
+ if method == "tracemin_pcg":
215
+ D = L.diagonal().astype(float)
216
+ solver = _PCGSolver(lambda x: L @ x, lambda x: D * x)
217
+ elif method == "tracemin_lu":
218
+ # Convert A to CSC to suppress SparseEfficiencyWarning.
219
+ A = sp.sparse.csc_array(L, dtype=float, copy=True)
220
+ # Force A to be nonsingular. Since A is the Laplacian matrix of a
221
+ # connected graph, its rank deficiency is one, and thus one diagonal
222
+ # element needs to modified. Changing to infinity forces a zero in the
223
+ # corresponding element in the solution.
224
+ i = (A.indptr[1:] - A.indptr[:-1]).argmax()
225
+ A[i, i] = np.inf
226
+ solver = _LUSolver(A)
227
+ else:
228
+ raise nx.NetworkXError(f"Unknown linear system solver: {method}")
229
+
230
+ # Initialize.
231
+ Lnorm = abs(L).sum(axis=1).flatten().max()
232
+ project(X)
233
+ W = np.ndarray(X.shape, order="F")
234
+
235
+ while True:
236
+ # Orthonormalize X.
237
+ X = np.linalg.qr(X)[0]
238
+ # Compute iteration matrix H.
239
+ W[:, :] = L @ X
240
+ H = X.T @ W
241
+ sigma, Y = sp.linalg.eigh(H, overwrite_a=True)
242
+ # Compute the Ritz vectors.
243
+ X = X @ Y
244
+ # Test for convergence exploiting the fact that L * X == W * Y.
245
+ res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm
246
+ if res < tol:
247
+ break
248
+ # Compute X = L \ X / (X' * (L \ X)).
249
+ # L \ X can have an arbitrary projection on the nullspace of L,
250
+ # which will be eliminated.
251
+ W[:, :] = solver.solve(X, tol)
252
+ X = (sp.linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order.
253
+ project(X)
254
+
255
+ return sigma, np.asarray(X)
256
+
257
+
258
+ def _get_fiedler_func(method):
259
+ """Returns a function that solves the Fiedler eigenvalue problem."""
260
+ import numpy as np
261
+
262
+ if method == "tracemin": # old style keyword <v2.1
263
+ method = "tracemin_pcg"
264
+ if method in ("tracemin_pcg", "tracemin_lu"):
265
+
266
+ def find_fiedler(L, x, normalized, tol, seed):
267
+ q = 1 if method == "tracemin_pcg" else min(4, L.shape[0] - 1)
268
+ X = np.asarray(seed.normal(size=(q, L.shape[0]))).T
269
+ sigma, X = _tracemin_fiedler(L, X, normalized, tol, method)
270
+ return sigma[0], X[:, 0]
271
+
272
+ elif method == "lanczos" or method == "lobpcg":
273
+
274
+ def find_fiedler(L, x, normalized, tol, seed):
275
+ import scipy as sp
276
+
277
+ L = sp.sparse.csc_array(L, dtype=float)
278
+ n = L.shape[0]
279
+ if normalized:
280
+ # TODO: rm csc_array wrapping when spdiags array becomes available
281
+ D = sp.sparse.csc_array(
282
+ sp.sparse.spdiags(
283
+ 1.0 / np.sqrt(L.diagonal()), [0], n, n, format="csc"
284
+ )
285
+ )
286
+ L = D @ L @ D
287
+ if method == "lanczos" or n < 10:
288
+ # Avoid LOBPCG when n < 10 due to
289
+ # https://github.com/scipy/scipy/issues/3592
290
+ # https://github.com/scipy/scipy/pull/3594
291
+ sigma, X = sp.sparse.linalg.eigsh(
292
+ L, 2, which="SM", tol=tol, return_eigenvectors=True
293
+ )
294
+ return sigma[1], X[:, 1]
295
+ else:
296
+ X = np.asarray(np.atleast_2d(x).T)
297
+ # TODO: rm csr_array wrapping when spdiags array becomes available
298
+ M = sp.sparse.csr_array(sp.sparse.spdiags(1.0 / L.diagonal(), 0, n, n))
299
+ Y = np.ones(n)
300
+ if normalized:
301
+ Y /= D.diagonal()
302
+ sigma, X = sp.sparse.linalg.lobpcg(
303
+ L, X, M=M, Y=np.atleast_2d(Y).T, tol=tol, maxiter=n, largest=False
304
+ )
305
+ return sigma[0], X[:, 0]
306
+
307
+ else:
308
+ raise nx.NetworkXError(f"unknown method {method!r}.")
309
+
310
+ return find_fiedler
311
+
312
+
313
+ @not_implemented_for("directed")
314
+ @np_random_state(5)
315
+ @nx._dispatchable(edge_attrs="weight")
316
+ def algebraic_connectivity(
317
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
318
+ ):
319
+ r"""Returns the algebraic connectivity of an undirected graph.
320
+
321
+ The algebraic connectivity of a connected undirected graph is the second
322
+ smallest eigenvalue of its Laplacian matrix.
323
+
324
+ Parameters
325
+ ----------
326
+ G : NetworkX graph
327
+ An undirected graph.
328
+
329
+ weight : object, optional (default: None)
330
+ The data key used to determine the weight of each edge. If None, then
331
+ each edge has unit weight.
332
+
333
+ normalized : bool, optional (default: False)
334
+ Whether the normalized Laplacian matrix is used.
335
+
336
+ tol : float, optional (default: 1e-8)
337
+ Tolerance of relative residual in eigenvalue computation.
338
+
339
+ method : string, optional (default: 'tracemin_pcg')
340
+ Method of eigenvalue computation. It must be one of the tracemin
341
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
342
+ or 'lobpcg' (LOBPCG).
343
+
344
+ The TraceMIN algorithm uses a linear system solver. The following
345
+ values allow specifying the solver to be used.
346
+
347
+ =============== ========================================
348
+ Value Solver
349
+ =============== ========================================
350
+ 'tracemin_pcg' Preconditioned conjugate gradient method
351
+ 'tracemin_lu' LU factorization
352
+ =============== ========================================
353
+
354
+ seed : integer, random_state, or None (default)
355
+ Indicator of random number generation state.
356
+ See :ref:`Randomness<randomness>`.
357
+
358
+ Returns
359
+ -------
360
+ algebraic_connectivity : float
361
+ Algebraic connectivity.
362
+
363
+ Raises
364
+ ------
365
+ NetworkXNotImplemented
366
+ If G is directed.
367
+
368
+ NetworkXError
369
+ If G has less than two nodes.
370
+
371
+ Notes
372
+ -----
373
+ Edge weights are interpreted by their absolute values. For MultiGraph's,
374
+ weights of parallel edges are summed. Zero-weighted edges are ignored.
375
+
376
+ See Also
377
+ --------
378
+ laplacian_matrix
379
+
380
+ Examples
381
+ --------
382
+ For undirected graphs algebraic connectivity can tell us if a graph is connected or not
383
+ `G` is connected iff ``algebraic_connectivity(G) > 0``:
384
+
385
+ >>> G = nx.complete_graph(5)
386
+ >>> nx.algebraic_connectivity(G) > 0
387
+ True
388
+ >>> G.add_node(10) # G is no longer connected
389
+ >>> nx.algebraic_connectivity(G) > 0
390
+ False
391
+
392
+ """
393
+ if len(G) < 2:
394
+ raise nx.NetworkXError("graph has less than two nodes.")
395
+ G = _preprocess_graph(G, weight)
396
+ if not nx.is_connected(G):
397
+ return 0.0
398
+
399
+ L = nx.laplacian_matrix(G)
400
+ if L.shape[0] == 2:
401
+ return 2.0 * float(L[0, 0]) if not normalized else 2.0
402
+
403
+ find_fiedler = _get_fiedler_func(method)
404
+ x = None if method != "lobpcg" else _rcm_estimate(G, G)
405
+ sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
406
+ return float(sigma)
407
+
408
+
409
+ @not_implemented_for("directed")
410
+ @np_random_state(5)
411
+ @nx._dispatchable(edge_attrs="weight")
412
+ def fiedler_vector(
413
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
414
+ ):
415
+ """Returns the Fiedler vector of a connected undirected graph.
416
+
417
+ The Fiedler vector of a connected undirected graph is the eigenvector
418
+ corresponding to the second smallest eigenvalue of the Laplacian matrix
419
+ of the graph.
420
+
421
+ Parameters
422
+ ----------
423
+ G : NetworkX graph
424
+ An undirected graph.
425
+
426
+ weight : object, optional (default: None)
427
+ The data key used to determine the weight of each edge. If None, then
428
+ each edge has unit weight.
429
+
430
+ normalized : bool, optional (default: False)
431
+ Whether the normalized Laplacian matrix is used.
432
+
433
+ tol : float, optional (default: 1e-8)
434
+ Tolerance of relative residual in eigenvalue computation.
435
+
436
+ method : string, optional (default: 'tracemin_pcg')
437
+ Method of eigenvalue computation. It must be one of the tracemin
438
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
439
+ or 'lobpcg' (LOBPCG).
440
+
441
+ The TraceMIN algorithm uses a linear system solver. The following
442
+ values allow specifying the solver to be used.
443
+
444
+ =============== ========================================
445
+ Value Solver
446
+ =============== ========================================
447
+ 'tracemin_pcg' Preconditioned conjugate gradient method
448
+ 'tracemin_lu' LU factorization
449
+ =============== ========================================
450
+
451
+ seed : integer, random_state, or None (default)
452
+ Indicator of random number generation state.
453
+ See :ref:`Randomness<randomness>`.
454
+
455
+ Returns
456
+ -------
457
+ fiedler_vector : NumPy array of floats.
458
+ Fiedler vector.
459
+
460
+ Raises
461
+ ------
462
+ NetworkXNotImplemented
463
+ If G is directed.
464
+
465
+ NetworkXError
466
+ If G has less than two nodes or is not connected.
467
+
468
+ Notes
469
+ -----
470
+ Edge weights are interpreted by their absolute values. For MultiGraph's,
471
+ weights of parallel edges are summed. Zero-weighted edges are ignored.
472
+
473
+ See Also
474
+ --------
475
+ laplacian_matrix
476
+
477
+ Examples
478
+ --------
479
+ Given a connected graph the signs of the values in the Fiedler vector can be
480
+ used to partition the graph into two components.
481
+
482
+ >>> G = nx.barbell_graph(5, 0)
483
+ >>> nx.fiedler_vector(G, normalized=True, seed=1)
484
+ array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899,
485
+ 0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129])
486
+
487
+ The connected components are the two 5-node cliques of the barbell graph.
488
+ """
489
+ import numpy as np
490
+
491
+ if len(G) < 2:
492
+ raise nx.NetworkXError("graph has less than two nodes.")
493
+ G = _preprocess_graph(G, weight)
494
+ if not nx.is_connected(G):
495
+ raise nx.NetworkXError("graph is not connected.")
496
+
497
+ if len(G) == 2:
498
+ return np.array([1.0, -1.0])
499
+
500
+ find_fiedler = _get_fiedler_func(method)
501
+ L = nx.laplacian_matrix(G)
502
+ x = None if method != "lobpcg" else _rcm_estimate(G, G)
503
+ sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
504
+ return fiedler
505
+
506
+
507
+ @np_random_state(5)
508
+ @nx._dispatchable(edge_attrs="weight")
509
+ def spectral_ordering(
510
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
511
+ ):
512
+ """Compute the spectral_ordering of a graph.
513
+
514
+ The spectral ordering of a graph is an ordering of its nodes where nodes
515
+ in the same weakly connected components appear contiguous and ordered by
516
+ their corresponding elements in the Fiedler vector of the component.
517
+
518
+ Parameters
519
+ ----------
520
+ G : NetworkX graph
521
+ A graph.
522
+
523
+ weight : object, optional (default: None)
524
+ The data key used to determine the weight of each edge. If None, then
525
+ each edge has unit weight.
526
+
527
+ normalized : bool, optional (default: False)
528
+ Whether the normalized Laplacian matrix is used.
529
+
530
+ tol : float, optional (default: 1e-8)
531
+ Tolerance of relative residual in eigenvalue computation.
532
+
533
+ method : string, optional (default: 'tracemin_pcg')
534
+ Method of eigenvalue computation. It must be one of the tracemin
535
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
536
+ or 'lobpcg' (LOBPCG).
537
+
538
+ The TraceMIN algorithm uses a linear system solver. The following
539
+ values allow specifying the solver to be used.
540
+
541
+ =============== ========================================
542
+ Value Solver
543
+ =============== ========================================
544
+ 'tracemin_pcg' Preconditioned conjugate gradient method
545
+ 'tracemin_lu' LU factorization
546
+ =============== ========================================
547
+
548
+ seed : integer, random_state, or None (default)
549
+ Indicator of random number generation state.
550
+ See :ref:`Randomness<randomness>`.
551
+
552
+ Returns
553
+ -------
554
+ spectral_ordering : NumPy array of floats.
555
+ Spectral ordering of nodes.
556
+
557
+ Raises
558
+ ------
559
+ NetworkXError
560
+ If G is empty.
561
+
562
+ Notes
563
+ -----
564
+ Edge weights are interpreted by their absolute values. For MultiGraph's,
565
+ weights of parallel edges are summed. Zero-weighted edges are ignored.
566
+
567
+ See Also
568
+ --------
569
+ laplacian_matrix
570
+ """
571
+ if len(G) == 0:
572
+ raise nx.NetworkXError("graph is empty.")
573
+ G = _preprocess_graph(G, weight)
574
+
575
+ find_fiedler = _get_fiedler_func(method)
576
+ order = []
577
+ for component in nx.connected_components(G):
578
+ size = len(component)
579
+ if size > 2:
580
+ L = nx.laplacian_matrix(G, component)
581
+ x = None if method != "lobpcg" else _rcm_estimate(G, component)
582
+ sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
583
+ sort_info = zip(fiedler, range(size), component)
584
+ order.extend(u for x, c, u in sorted(sort_info))
585
+ else:
586
+ order.extend(component)
587
+
588
+ return order
589
+
590
+
591
+ @nx._dispatchable(edge_attrs="weight")
592
+ def spectral_bisection(
593
+ G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
594
+ ):
595
+ """Bisect the graph using the Fiedler vector.
596
+
597
+ This method uses the Fiedler vector to bisect a graph.
598
+ The partition is defined by the nodes which are associated with
599
+ either positive or negative values in the vector.
600
+
601
+ Parameters
602
+ ----------
603
+ G : NetworkX Graph
604
+
605
+ weight : str, optional (default: weight)
606
+ The data key used to determine the weight of each edge. If None, then
607
+ each edge has unit weight.
608
+
609
+ normalized : bool, optional (default: False)
610
+ Whether the normalized Laplacian matrix is used.
611
+
612
+ tol : float, optional (default: 1e-8)
613
+ Tolerance of relative residual in eigenvalue computation.
614
+
615
+ method : string, optional (default: 'tracemin_pcg')
616
+ Method of eigenvalue computation. It must be one of the tracemin
617
+ options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
618
+ or 'lobpcg' (LOBPCG).
619
+
620
+ The TraceMIN algorithm uses a linear system solver. The following
621
+ values allow specifying the solver to be used.
622
+
623
+ =============== ========================================
624
+ Value Solver
625
+ =============== ========================================
626
+ 'tracemin_pcg' Preconditioned conjugate gradient method
627
+ 'tracemin_lu' LU factorization
628
+ =============== ========================================
629
+
630
+ seed : integer, random_state, or None (default)
631
+ Indicator of random number generation state.
632
+ See :ref:`Randomness<randomness>`.
633
+
634
+ Returns
635
+ -------
636
+ bisection : tuple of sets
637
+ Sets with the bisection of nodes
638
+
639
+ Examples
640
+ --------
641
+ >>> G = nx.barbell_graph(3, 0)
642
+ >>> nx.spectral_bisection(G)
643
+ ({0, 1, 2}, {3, 4, 5})
644
+
645
+ References
646
+ ----------
647
+ .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370
648
+ Oxford University Press 2011.
649
+ """
650
+ import numpy as np
651
+
652
+ v = nx.fiedler_vector(G, weight, normalized, tol, method, seed)
653
+ nodes = np.array(list(G))
654
+ pos_vals = v >= 0
655
+
656
+ return set(nodes[~pos_vals].tolist()), set(nodes[pos_vals].tolist())
env-llmeval/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adjacency matrix and incidence matrix of graphs.
3
+ """
4
+ import networkx as nx
5
+
6
+ __all__ = ["incidence_matrix", "adjacency_matrix"]
7
+
8
+
9
+ @nx._dispatchable(edge_attrs="weight")
10
+ def incidence_matrix(
11
+ G, nodelist=None, edgelist=None, oriented=False, weight=None, *, dtype=None
12
+ ):
13
+ """Returns incidence matrix of G.
14
+
15
+ The incidence matrix assigns each row to a node and each column to an edge.
16
+ For a standard incidence matrix a 1 appears wherever a row's node is
17
+ incident on the column's edge. For an oriented incidence matrix each
18
+ edge is assigned an orientation (arbitrarily for undirected and aligning to
19
+ direction for directed). A -1 appears for the source (tail) of an edge and
20
+ 1 for the destination (head) of the edge. The elements are zero otherwise.
21
+
22
+ Parameters
23
+ ----------
24
+ G : graph
25
+ A NetworkX graph
26
+
27
+ nodelist : list, optional (default= all nodes in G)
28
+ The rows are ordered according to the nodes in nodelist.
29
+ If nodelist is None, then the ordering is produced by G.nodes().
30
+
31
+ edgelist : list, optional (default= all edges in G)
32
+ The columns are ordered according to the edges in edgelist.
33
+ If edgelist is None, then the ordering is produced by G.edges().
34
+
35
+ oriented: bool, optional (default=False)
36
+ If True, matrix elements are +1 or -1 for the head or tail node
37
+ respectively of each edge. If False, +1 occurs at both nodes.
38
+
39
+ weight : string or None, optional (default=None)
40
+ The edge data key used to provide each value in the matrix.
41
+ If None, then each edge has weight 1. Edge weights, if used,
42
+ should be positive so that the orientation can provide the sign.
43
+
44
+ dtype : a NumPy dtype or None (default=None)
45
+ The dtype of the output sparse array. This type should be a compatible
46
+ type of the weight argument, eg. if weight would return a float this
47
+ argument should also be a float.
48
+ If None, then the default for SciPy is used.
49
+
50
+ Returns
51
+ -------
52
+ A : SciPy sparse array
53
+ The incidence matrix of G.
54
+
55
+ Notes
56
+ -----
57
+ For MultiGraph/MultiDiGraph, the edges in edgelist should be
58
+ (u,v,key) 3-tuples.
59
+
60
+ "Networks are the best discrete model for so many problems in
61
+ applied mathematics" [1]_.
62
+
63
+ References
64
+ ----------
65
+ .. [1] Gil Strang, Network applications: A = incidence matrix,
66
+ http://videolectures.net/mit18085f07_strang_lec03/
67
+ """
68
+ import scipy as sp
69
+
70
+ if nodelist is None:
71
+ nodelist = list(G)
72
+ if edgelist is None:
73
+ if G.is_multigraph():
74
+ edgelist = list(G.edges(keys=True))
75
+ else:
76
+ edgelist = list(G.edges())
77
+ A = sp.sparse.lil_array((len(nodelist), len(edgelist)), dtype=dtype)
78
+ node_index = {node: i for i, node in enumerate(nodelist)}
79
+ for ei, e in enumerate(edgelist):
80
+ (u, v) = e[:2]
81
+ if u == v:
82
+ continue # self loops give zero column
83
+ try:
84
+ ui = node_index[u]
85
+ vi = node_index[v]
86
+ except KeyError as err:
87
+ raise nx.NetworkXError(
88
+ f"node {u} or {v} in edgelist but not in nodelist"
89
+ ) from err
90
+ if weight is None:
91
+ wt = 1
92
+ else:
93
+ if G.is_multigraph():
94
+ ekey = e[2]
95
+ wt = G[u][v][ekey].get(weight, 1)
96
+ else:
97
+ wt = G[u][v].get(weight, 1)
98
+ if oriented:
99
+ A[ui, ei] = -wt
100
+ A[vi, ei] = wt
101
+ else:
102
+ A[ui, ei] = wt
103
+ A[vi, ei] = wt
104
+ return A.asformat("csc")
105
+
106
+
107
+ @nx._dispatchable(edge_attrs="weight")
108
+ def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"):
109
+ """Returns adjacency matrix of G.
110
+
111
+ Parameters
112
+ ----------
113
+ G : graph
114
+ A NetworkX graph
115
+
116
+ nodelist : list, optional
117
+ The rows and columns are ordered according to the nodes in nodelist.
118
+ If nodelist is None, then the ordering is produced by G.nodes().
119
+
120
+ dtype : NumPy data-type, optional
121
+ The desired data-type for the array.
122
+ If None, then the NumPy default is used.
123
+
124
+ weight : string or None, optional (default='weight')
125
+ The edge data key used to provide each value in the matrix.
126
+ If None, then each edge has weight 1.
127
+
128
+ Returns
129
+ -------
130
+ A : SciPy sparse array
131
+ Adjacency matrix representation of G.
132
+
133
+ Notes
134
+ -----
135
+ For directed graphs, entry i,j corresponds to an edge from i to j.
136
+
137
+ If you want a pure Python adjacency matrix representation try
138
+ networkx.convert.to_dict_of_dicts which will return a
139
+ dictionary-of-dictionaries format that can be addressed as a
140
+ sparse matrix.
141
+
142
+ For MultiGraph/MultiDiGraph with parallel edges the weights are summed.
143
+ See `to_numpy_array` for other options.
144
+
145
+ The convention used for self-loop edges in graphs is to assign the
146
+ diagonal matrix entry value to the edge weight attribute
147
+ (or the number 1 if the edge has no weight attribute). If the
148
+ alternate convention of doubling the edge weight is desired the
149
+ resulting SciPy sparse array can be modified as follows:
150
+
151
+ >>> G = nx.Graph([(1, 1)])
152
+ >>> A = nx.adjacency_matrix(G)
153
+ >>> print(A.todense())
154
+ [[1]]
155
+ >>> A.setdiag(A.diagonal() * 2)
156
+ >>> print(A.todense())
157
+ [[2]]
158
+
159
+ See Also
160
+ --------
161
+ to_numpy_array
162
+ to_scipy_sparse_array
163
+ to_dict_of_dicts
164
+ adjacency_spectrum
165
+ """
166
+ return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight)
env-llmeval/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Laplacian matrix of graphs.
2
+
3
+ All calculations here are done using the out-degree. For Laplacians using
4
+ in-degree, use `G.reverse(copy=False)` instead of `G` and take the transpose.
5
+
6
+ The `laplacian_matrix` function provides an unnormalized matrix,
7
+ while `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
8
+ and `directed_combinatorial_laplacian_matrix` are all normalized.
9
+ """
10
+ import networkx as nx
11
+ from networkx.utils import not_implemented_for
12
+
13
+ __all__ = [
14
+ "laplacian_matrix",
15
+ "normalized_laplacian_matrix",
16
+ "total_spanning_tree_weight",
17
+ "directed_laplacian_matrix",
18
+ "directed_combinatorial_laplacian_matrix",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable(edge_attrs="weight")
23
+ def laplacian_matrix(G, nodelist=None, weight="weight"):
24
+ """Returns the Laplacian matrix of G.
25
+
26
+ The graph Laplacian is the matrix L = D - A, where
27
+ A is the adjacency matrix and D is the diagonal matrix of node degrees.
28
+
29
+ Parameters
30
+ ----------
31
+ G : graph
32
+ A NetworkX graph
33
+
34
+ nodelist : list, optional
35
+ The rows and columns are ordered according to the nodes in nodelist.
36
+ If nodelist is None, then the ordering is produced by G.nodes().
37
+
38
+ weight : string or None, optional (default='weight')
39
+ The edge data key used to compute each value in the matrix.
40
+ If None, then each edge has weight 1.
41
+
42
+ Returns
43
+ -------
44
+ L : SciPy sparse array
45
+ The Laplacian matrix of G.
46
+
47
+ Notes
48
+ -----
49
+ For MultiGraph, the edges weights are summed.
50
+
51
+ This returns an unnormalized matrix. For a normalized output,
52
+ use `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
53
+ or `directed_combinatorial_laplacian_matrix`.
54
+
55
+ This calculation uses the out-degree of the graph `G`. To use the
56
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
57
+ take the transpose.
58
+
59
+ See Also
60
+ --------
61
+ :func:`~networkx.convert_matrix.to_numpy_array`
62
+ normalized_laplacian_matrix
63
+ directed_laplacian_matrix
64
+ directed_combinatorial_laplacian_matrix
65
+ :func:`~networkx.linalg.spectrum.laplacian_spectrum`
66
+
67
+ Examples
68
+ --------
69
+ For graphs with multiple connected components, L is permutation-similar
70
+ to a block diagonal matrix where each block is the respective Laplacian
71
+ matrix for each component.
72
+
73
+ >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
74
+ >>> print(nx.laplacian_matrix(G).toarray())
75
+ [[ 1 -1 0 0 0]
76
+ [-1 2 -1 0 0]
77
+ [ 0 -1 1 0 0]
78
+ [ 0 0 0 1 -1]
79
+ [ 0 0 0 -1 1]]
80
+
81
+ >>> edges = [
82
+ ... (1, 2),
83
+ ... (2, 1),
84
+ ... (2, 4),
85
+ ... (4, 3),
86
+ ... (3, 4),
87
+ ... ]
88
+ >>> DiG = nx.DiGraph(edges)
89
+ >>> print(nx.laplacian_matrix(DiG).toarray())
90
+ [[ 1 -1 0 0]
91
+ [-1 2 -1 0]
92
+ [ 0 0 1 -1]
93
+ [ 0 0 -1 1]]
94
+
95
+ Notice that node 4 is represented by the third column and row. This is because
96
+ by default the row/column order is the order of `G.nodes` (i.e. the node added
97
+ order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
98
+ To control the node order of the matrix, use the `nodelist` argument.
99
+
100
+ >>> print(nx.laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
101
+ [[ 1 -1 0 0]
102
+ [-1 2 0 -1]
103
+ [ 0 0 1 -1]
104
+ [ 0 0 -1 1]]
105
+
106
+ This calculation uses the out-degree of the graph `G`. To use the
107
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
108
+ take the transpose.
109
+
110
+ >>> print(nx.laplacian_matrix(DiG.reverse(copy=False)).toarray().T)
111
+ [[ 1 -1 0 0]
112
+ [-1 1 -1 0]
113
+ [ 0 0 2 -1]
114
+ [ 0 0 -1 1]]
115
+
116
+ References
117
+ ----------
118
+ .. [1] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
119
+ The Science of Search Engine Rankings. Princeton University Press, 2006.
120
+
121
+ """
122
+ import scipy as sp
123
+
124
+ if nodelist is None:
125
+ nodelist = list(G)
126
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
127
+ n, m = A.shape
128
+ # TODO: rm csr_array wrapper when spdiags can produce arrays
129
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, m, n, format="csr"))
130
+ return D - A
131
+
132
+
133
+ @nx._dispatchable(edge_attrs="weight")
134
+ def normalized_laplacian_matrix(G, nodelist=None, weight="weight"):
135
+ r"""Returns the normalized Laplacian matrix of G.
136
+
137
+ The normalized graph Laplacian is the matrix
138
+
139
+ .. math::
140
+
141
+ N = D^{-1/2} L D^{-1/2}
142
+
143
+ where `L` is the graph Laplacian and `D` is the diagonal matrix of
144
+ node degrees [1]_.
145
+
146
+ Parameters
147
+ ----------
148
+ G : graph
149
+ A NetworkX graph
150
+
151
+ nodelist : list, optional
152
+ The rows and columns are ordered according to the nodes in nodelist.
153
+ If nodelist is None, then the ordering is produced by G.nodes().
154
+
155
+ weight : string or None, optional (default='weight')
156
+ The edge data key used to compute each value in the matrix.
157
+ If None, then each edge has weight 1.
158
+
159
+ Returns
160
+ -------
161
+ N : SciPy sparse array
162
+ The normalized Laplacian matrix of G.
163
+
164
+ Notes
165
+ -----
166
+ For MultiGraph, the edges weights are summed.
167
+ See :func:`to_numpy_array` for other options.
168
+
169
+ If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is
170
+ the adjacency matrix [2]_.
171
+
172
+ This calculation uses the out-degree of the graph `G`. To use the
173
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
174
+ take the transpose.
175
+
176
+ For an unnormalized output, use `laplacian_matrix`.
177
+
178
+ Examples
179
+ --------
180
+
181
+ >>> import numpy as np
182
+ >>> edges = [
183
+ ... (1, 2),
184
+ ... (2, 1),
185
+ ... (2, 4),
186
+ ... (4, 3),
187
+ ... (3, 4),
188
+ ... ]
189
+ >>> DiG = nx.DiGraph(edges)
190
+ >>> print(nx.normalized_laplacian_matrix(DiG).toarray())
191
+ [[ 1. -0.70710678 0. 0. ]
192
+ [-0.70710678 1. -0.70710678 0. ]
193
+ [ 0. 0. 1. -1. ]
194
+ [ 0. 0. -1. 1. ]]
195
+
196
+ Notice that node 4 is represented by the third column and row. This is because
197
+ by default the row/column order is the order of `G.nodes` (i.e. the node added
198
+ order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
199
+ To control the node order of the matrix, use the `nodelist` argument.
200
+
201
+ >>> print(nx.normalized_laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
202
+ [[ 1. -0.70710678 0. 0. ]
203
+ [-0.70710678 1. 0. -0.70710678]
204
+ [ 0. 0. 1. -1. ]
205
+ [ 0. 0. -1. 1. ]]
206
+ >>> G = nx.Graph(edges)
207
+ >>> print(nx.normalized_laplacian_matrix(G).toarray())
208
+ [[ 1. -0.70710678 0. 0. ]
209
+ [-0.70710678 1. -0.5 0. ]
210
+ [ 0. -0.5 1. -0.70710678]
211
+ [ 0. 0. -0.70710678 1. ]]
212
+
213
+ See Also
214
+ --------
215
+ laplacian_matrix
216
+ normalized_laplacian_spectrum
217
+ directed_laplacian_matrix
218
+ directed_combinatorial_laplacian_matrix
219
+
220
+ References
221
+ ----------
222
+ .. [1] Fan Chung-Graham, Spectral Graph Theory,
223
+ CBMS Regional Conference Series in Mathematics, Number 92, 1997.
224
+ .. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized
225
+ Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98,
226
+ March 2007.
227
+ .. [3] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
228
+ The Science of Search Engine Rankings. Princeton University Press, 2006.
229
+ """
230
+ import numpy as np
231
+ import scipy as sp
232
+
233
+ if nodelist is None:
234
+ nodelist = list(G)
235
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
236
+ n, _ = A.shape
237
+ diags = A.sum(axis=1)
238
+ # TODO: rm csr_array wrapper when spdiags can produce arrays
239
+ D = sp.sparse.csr_array(sp.sparse.spdiags(diags, 0, n, n, format="csr"))
240
+ L = D - A
241
+ with np.errstate(divide="ignore"):
242
+ diags_sqrt = 1.0 / np.sqrt(diags)
243
+ diags_sqrt[np.isinf(diags_sqrt)] = 0
244
+ # TODO: rm csr_array wrapper when spdiags can produce arrays
245
+ DH = sp.sparse.csr_array(sp.sparse.spdiags(diags_sqrt, 0, n, n, format="csr"))
246
+ return DH @ (L @ DH)
247
+
248
+
249
+ @nx._dispatchable(edge_attrs="weight")
250
+ def total_spanning_tree_weight(G, weight=None, root=None):
251
+ """
252
+ Returns the total weight of all spanning trees of `G`.
253
+
254
+ Kirchoff's Tree Matrix Theorem [1]_, [2]_ states that the determinant of any
255
+ cofactor of the Laplacian matrix of a graph is the number of spanning trees
256
+ in the graph. For a weighted Laplacian matrix, it is the sum across all
257
+ spanning trees of the multiplicative weight of each tree. That is, the
258
+ weight of each tree is the product of its edge weights.
259
+
260
+ For unweighted graphs, the total weight equals the number of spanning trees in `G`.
261
+
262
+ For directed graphs, the total weight follows by summing over all directed
263
+ spanning trees in `G` that start in the `root` node [3]_.
264
+
265
+ .. deprecated:: 3.3
266
+
267
+ ``total_spanning_tree_weight`` is deprecated and will be removed in v3.5.
268
+ Use ``nx.number_of_spanning_trees(G)`` instead.
269
+
270
+ Parameters
271
+ ----------
272
+ G : NetworkX Graph
273
+
274
+ weight : string or None, optional (default=None)
275
+ The key for the edge attribute holding the edge weight.
276
+ If None, then each edge has weight 1.
277
+
278
+ root : node (only required for directed graphs)
279
+ A node in the directed graph `G`.
280
+
281
+ Returns
282
+ -------
283
+ total_weight : float
284
+ Undirected graphs:
285
+ The sum of the total multiplicative weights for all spanning trees in `G`.
286
+ Directed graphs:
287
+ The sum of the total multiplicative weights for all spanning trees of `G`,
288
+ rooted at node `root`.
289
+
290
+ Raises
291
+ ------
292
+ NetworkXPointlessConcept
293
+ If `G` does not contain any nodes.
294
+
295
+ NetworkXError
296
+ If the graph `G` is not (weakly) connected,
297
+ or if `G` is directed and the root node is not specified or not in G.
298
+
299
+ Examples
300
+ --------
301
+ >>> G = nx.complete_graph(5)
302
+ >>> round(nx.total_spanning_tree_weight(G))
303
+ 125
304
+
305
+ >>> G = nx.Graph()
306
+ >>> G.add_edge(1, 2, weight=2)
307
+ >>> G.add_edge(1, 3, weight=1)
308
+ >>> G.add_edge(2, 3, weight=1)
309
+ >>> round(nx.total_spanning_tree_weight(G, "weight"))
310
+ 5
311
+
312
+ Notes
313
+ -----
314
+ Self-loops are excluded. Multi-edges are contracted in one edge
315
+ equal to the sum of the weights.
316
+
317
+ References
318
+ ----------
319
+ .. [1] Wikipedia
320
+ "Kirchhoff's theorem."
321
+ https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem
322
+ .. [2] Kirchhoff, G. R.
323
+ Über die Auflösung der Gleichungen, auf welche man
324
+ bei der Untersuchung der linearen Vertheilung
325
+ Galvanischer Ströme geführt wird
326
+ Annalen der Physik und Chemie, vol. 72, pp. 497-508, 1847.
327
+ .. [3] Margoliash, J.
328
+ "Matrix-Tree Theorem for Directed Graphs"
329
+ https://www.math.uchicago.edu/~may/VIGRE/VIGRE2010/REUPapers/Margoliash.pdf
330
+ """
331
+ import warnings
332
+
333
+ warnings.warn(
334
+ (
335
+ "\n\ntotal_spanning_tree_weight is deprecated and will be removed in v3.5.\n"
336
+ "Use `nx.number_of_spanning_trees(G)` instead."
337
+ ),
338
+ category=DeprecationWarning,
339
+ stacklevel=3,
340
+ )
341
+
342
+ return nx.number_of_spanning_trees(G, weight=weight, root=root)
343
+
344
+
345
+ ###############################################################################
346
+ # Code based on work from https://github.com/bjedwards
347
+
348
+
349
+ @not_implemented_for("undirected")
350
+ @not_implemented_for("multigraph")
351
+ @nx._dispatchable(edge_attrs="weight")
352
+ def directed_laplacian_matrix(
353
+ G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
354
+ ):
355
+ r"""Returns the directed Laplacian matrix of G.
356
+
357
+ The graph directed Laplacian is the matrix
358
+
359
+ .. math::
360
+
361
+ L = I - \frac{1}{2} \left (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} \right )
362
+
363
+ where `I` is the identity matrix, `P` is the transition matrix of the
364
+ graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
365
+ zeros elsewhere [1]_.
366
+
367
+ Depending on the value of walk_type, `P` can be the transition matrix
368
+ induced by a random walk, a lazy random walk, or a random walk with
369
+ teleportation (PageRank).
370
+
371
+ Parameters
372
+ ----------
373
+ G : DiGraph
374
+ A NetworkX graph
375
+
376
+ nodelist : list, optional
377
+ The rows and columns are ordered according to the nodes in nodelist.
378
+ If nodelist is None, then the ordering is produced by G.nodes().
379
+
380
+ weight : string or None, optional (default='weight')
381
+ The edge data key used to compute each value in the matrix.
382
+ If None, then each edge has weight 1.
383
+
384
+ walk_type : string or None, optional (default=None)
385
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
386
+ (the default), then a value is selected according to the properties of `G`:
387
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
388
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
389
+ - ``walk_type="pagerank"`` for all other cases.
390
+
391
+ alpha : real
392
+ (1 - alpha) is the teleportation probability used with pagerank
393
+
394
+ Returns
395
+ -------
396
+ L : NumPy matrix
397
+ Normalized Laplacian of G.
398
+
399
+ Notes
400
+ -----
401
+ Only implemented for DiGraphs
402
+
403
+ The result is always a symmetric matrix.
404
+
405
+ This calculation uses the out-degree of the graph `G`. To use the
406
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
407
+ take the transpose.
408
+
409
+ See Also
410
+ --------
411
+ laplacian_matrix
412
+ normalized_laplacian_matrix
413
+ directed_combinatorial_laplacian_matrix
414
+
415
+ References
416
+ ----------
417
+ .. [1] Fan Chung (2005).
418
+ Laplacians and the Cheeger inequality for directed graphs.
419
+ Annals of Combinatorics, 9(1), 2005
420
+ """
421
+ import numpy as np
422
+ import scipy as sp
423
+
424
+ # NOTE: P has type ndarray if walk_type=="pagerank", else csr_array
425
+ P = _transition_matrix(
426
+ G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
427
+ )
428
+
429
+ n, m = P.shape
430
+
431
+ evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
432
+ v = evecs.flatten().real
433
+ p = v / v.sum()
434
+ # p>=0 by Perron-Frobenius Thm. Use abs() to fix roundoff across zero gh-6865
435
+ sqrtp = np.sqrt(np.abs(p))
436
+ Q = (
437
+ # TODO: rm csr_array wrapper when spdiags creates arrays
438
+ sp.sparse.csr_array(sp.sparse.spdiags(sqrtp, 0, n, n))
439
+ @ P
440
+ # TODO: rm csr_array wrapper when spdiags creates arrays
441
+ @ sp.sparse.csr_array(sp.sparse.spdiags(1.0 / sqrtp, 0, n, n))
442
+ )
443
+ # NOTE: This could be sparsified for the non-pagerank cases
444
+ I = np.identity(len(G))
445
+
446
+ return I - (Q + Q.T) / 2.0
447
+
448
+
449
+ @not_implemented_for("undirected")
450
+ @not_implemented_for("multigraph")
451
+ @nx._dispatchable(edge_attrs="weight")
452
+ def directed_combinatorial_laplacian_matrix(
453
+ G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
454
+ ):
455
+ r"""Return the directed combinatorial Laplacian matrix of G.
456
+
457
+ The graph directed combinatorial Laplacian is the matrix
458
+
459
+ .. math::
460
+
461
+ L = \Phi - \frac{1}{2} \left (\Phi P + P^T \Phi \right)
462
+
463
+ where `P` is the transition matrix of the graph and `\Phi` a matrix
464
+ with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
465
+
466
+ Depending on the value of walk_type, `P` can be the transition matrix
467
+ induced by a random walk, a lazy random walk, or a random walk with
468
+ teleportation (PageRank).
469
+
470
+ Parameters
471
+ ----------
472
+ G : DiGraph
473
+ A NetworkX graph
474
+
475
+ nodelist : list, optional
476
+ The rows and columns are ordered according to the nodes in nodelist.
477
+ If nodelist is None, then the ordering is produced by G.nodes().
478
+
479
+ weight : string or None, optional (default='weight')
480
+ The edge data key used to compute each value in the matrix.
481
+ If None, then each edge has weight 1.
482
+
483
+ walk_type : string or None, optional (default=None)
484
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
485
+ (the default), then a value is selected according to the properties of `G`:
486
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
487
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
488
+ - ``walk_type="pagerank"`` for all other cases.
489
+
490
+ alpha : real
491
+ (1 - alpha) is the teleportation probability used with pagerank
492
+
493
+ Returns
494
+ -------
495
+ L : NumPy matrix
496
+ Combinatorial Laplacian of G.
497
+
498
+ Notes
499
+ -----
500
+ Only implemented for DiGraphs
501
+
502
+ The result is always a symmetric matrix.
503
+
504
+ This calculation uses the out-degree of the graph `G`. To use the
505
+ in-degree for calculations instead, use `G.reverse(copy=False)` and
506
+ take the transpose.
507
+
508
+ See Also
509
+ --------
510
+ laplacian_matrix
511
+ normalized_laplacian_matrix
512
+ directed_laplacian_matrix
513
+
514
+ References
515
+ ----------
516
+ .. [1] Fan Chung (2005).
517
+ Laplacians and the Cheeger inequality for directed graphs.
518
+ Annals of Combinatorics, 9(1), 2005
519
+ """
520
+ import scipy as sp
521
+
522
+ P = _transition_matrix(
523
+ G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
524
+ )
525
+
526
+ n, m = P.shape
527
+
528
+ evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
529
+ v = evecs.flatten().real
530
+ p = v / v.sum()
531
+ # NOTE: could be improved by not densifying
532
+ # TODO: Rm csr_array wrapper when spdiags array creation becomes available
533
+ Phi = sp.sparse.csr_array(sp.sparse.spdiags(p, 0, n, n)).toarray()
534
+
535
+ return Phi - (Phi @ P + P.T @ Phi) / 2.0
536
+
537
+
538
+ def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha=0.95):
539
+ """Returns the transition matrix of G.
540
+
541
+ This is a row stochastic giving the transition probabilities while
542
+ performing a random walk on the graph. Depending on the value of walk_type,
543
+ P can be the transition matrix induced by a random walk, a lazy random walk,
544
+ or a random walk with teleportation (PageRank).
545
+
546
+ Parameters
547
+ ----------
548
+ G : DiGraph
549
+ A NetworkX graph
550
+
551
+ nodelist : list, optional
552
+ The rows and columns are ordered according to the nodes in nodelist.
553
+ If nodelist is None, then the ordering is produced by G.nodes().
554
+
555
+ weight : string or None, optional (default='weight')
556
+ The edge data key used to compute each value in the matrix.
557
+ If None, then each edge has weight 1.
558
+
559
+ walk_type : string or None, optional (default=None)
560
+ One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
561
+ (the default), then a value is selected according to the properties of `G`:
562
+ - ``walk_type="random"`` if `G` is strongly connected and aperiodic
563
+ - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
564
+ - ``walk_type="pagerank"`` for all other cases.
565
+
566
+ alpha : real
567
+ (1 - alpha) is the teleportation probability used with pagerank
568
+
569
+ Returns
570
+ -------
571
+ P : numpy.ndarray
572
+ transition matrix of G.
573
+
574
+ Raises
575
+ ------
576
+ NetworkXError
577
+ If walk_type not specified or alpha not in valid range
578
+ """
579
+ import numpy as np
580
+ import scipy as sp
581
+
582
+ if walk_type is None:
583
+ if nx.is_strongly_connected(G):
584
+ if nx.is_aperiodic(G):
585
+ walk_type = "random"
586
+ else:
587
+ walk_type = "lazy"
588
+ else:
589
+ walk_type = "pagerank"
590
+
591
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
592
+ n, m = A.shape
593
+ if walk_type in ["random", "lazy"]:
594
+ # TODO: Rm csr_array wrapper when spdiags array creation becomes available
595
+ DI = sp.sparse.csr_array(sp.sparse.spdiags(1.0 / A.sum(axis=1), 0, n, n))
596
+ if walk_type == "random":
597
+ P = DI @ A
598
+ else:
599
+ # TODO: Rm csr_array wrapper when identity array creation becomes available
600
+ I = sp.sparse.csr_array(sp.sparse.identity(n))
601
+ P = (I + DI @ A) / 2.0
602
+
603
+ elif walk_type == "pagerank":
604
+ if not (0 < alpha < 1):
605
+ raise nx.NetworkXError("alpha must be between 0 and 1")
606
+ # this is using a dense representation. NOTE: This should be sparsified!
607
+ A = A.toarray()
608
+ # add constant to dangling nodes' row
609
+ A[A.sum(axis=1) == 0, :] = 1 / n
610
+ # normalize
611
+ A = A / A.sum(axis=1)[np.newaxis, :].T
612
+ P = alpha * A + (1 - alpha) / n
613
+ else:
614
+ raise nx.NetworkXError("walk_type must be random, lazy, or pagerank")
615
+
616
+ return P
env-llmeval/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modularity matrix of graphs.
2
+ """
3
+ import networkx as nx
4
+ from networkx.utils import not_implemented_for
5
+
6
+ __all__ = ["modularity_matrix", "directed_modularity_matrix"]
7
+
8
+
9
+ @not_implemented_for("directed")
10
+ @not_implemented_for("multigraph")
11
+ @nx._dispatchable(edge_attrs="weight")
12
+ def modularity_matrix(G, nodelist=None, weight=None):
13
+ r"""Returns the modularity matrix of G.
14
+
15
+ The modularity matrix is the matrix B = A - <A>, where A is the adjacency
16
+ matrix and <A> is the average adjacency matrix, assuming that the graph
17
+ is described by the configuration model.
18
+
19
+ More specifically, the element B_ij of B is defined as
20
+
21
+ .. math::
22
+ A_{ij} - {k_i k_j \over 2 m}
23
+
24
+ where k_i is the degree of node i, and where m is the number of edges
25
+ in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
26
+ k_j and m are computed using its value.
27
+
28
+ Parameters
29
+ ----------
30
+ G : Graph
31
+ A NetworkX graph
32
+
33
+ nodelist : list, optional
34
+ The rows and columns are ordered according to the nodes in nodelist.
35
+ If nodelist is None, then the ordering is produced by G.nodes().
36
+
37
+ weight : string or None, optional (default=None)
38
+ The edge attribute that holds the numerical value used for
39
+ the edge weight. If None then all edge weights are 1.
40
+
41
+ Returns
42
+ -------
43
+ B : Numpy array
44
+ The modularity matrix of G.
45
+
46
+ Examples
47
+ --------
48
+ >>> k = [3, 2, 2, 1, 0]
49
+ >>> G = nx.havel_hakimi_graph(k)
50
+ >>> B = nx.modularity_matrix(G)
51
+
52
+
53
+ See Also
54
+ --------
55
+ to_numpy_array
56
+ modularity_spectrum
57
+ adjacency_matrix
58
+ directed_modularity_matrix
59
+
60
+ References
61
+ ----------
62
+ .. [1] M. E. J. Newman, "Modularity and community structure in networks",
63
+ Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
64
+ """
65
+ import numpy as np
66
+
67
+ if nodelist is None:
68
+ nodelist = list(G)
69
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
70
+ k = A.sum(axis=1)
71
+ m = k.sum() * 0.5
72
+ # Expected adjacency matrix
73
+ X = np.outer(k, k) / (2 * m)
74
+
75
+ return A - X
76
+
77
+
78
+ @not_implemented_for("undirected")
79
+ @not_implemented_for("multigraph")
80
+ @nx._dispatchable(edge_attrs="weight")
81
+ def directed_modularity_matrix(G, nodelist=None, weight=None):
82
+ """Returns the directed modularity matrix of G.
83
+
84
+ The modularity matrix is the matrix B = A - <A>, where A is the adjacency
85
+ matrix and <A> is the expected adjacency matrix, assuming that the graph
86
+ is described by the configuration model.
87
+
88
+ More specifically, the element B_ij of B is defined as
89
+
90
+ .. math::
91
+ B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
92
+
93
+ where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree
94
+ of node j, with m the number of edges in the graph. When weight is set
95
+ to a name of an attribute edge, Aij, k_i, k_j and m are computed using
96
+ its value.
97
+
98
+ Parameters
99
+ ----------
100
+ G : DiGraph
101
+ A NetworkX DiGraph
102
+
103
+ nodelist : list, optional
104
+ The rows and columns are ordered according to the nodes in nodelist.
105
+ If nodelist is None, then the ordering is produced by G.nodes().
106
+
107
+ weight : string or None, optional (default=None)
108
+ The edge attribute that holds the numerical value used for
109
+ the edge weight. If None then all edge weights are 1.
110
+
111
+ Returns
112
+ -------
113
+ B : Numpy array
114
+ The modularity matrix of G.
115
+
116
+ Examples
117
+ --------
118
+ >>> G = nx.DiGraph()
119
+ >>> G.add_edges_from(
120
+ ... (
121
+ ... (1, 2),
122
+ ... (1, 3),
123
+ ... (3, 1),
124
+ ... (3, 2),
125
+ ... (3, 5),
126
+ ... (4, 5),
127
+ ... (4, 6),
128
+ ... (5, 4),
129
+ ... (5, 6),
130
+ ... (6, 4),
131
+ ... )
132
+ ... )
133
+ >>> B = nx.directed_modularity_matrix(G)
134
+
135
+
136
+ Notes
137
+ -----
138
+ NetworkX defines the element A_ij of the adjacency matrix as 1 if there
139
+ is a link going from node i to node j. Leicht and Newman use the opposite
140
+ definition. This explains the different expression for B_ij.
141
+
142
+ See Also
143
+ --------
144
+ to_numpy_array
145
+ modularity_spectrum
146
+ adjacency_matrix
147
+ modularity_matrix
148
+
149
+ References
150
+ ----------
151
+ .. [1] E. A. Leicht, M. E. J. Newman,
152
+ "Community structure in directed networks",
153
+ Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
154
+ """
155
+ import numpy as np
156
+
157
+ if nodelist is None:
158
+ nodelist = list(G)
159
+ A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
160
+ k_in = A.sum(axis=0)
161
+ k_out = A.sum(axis=1)
162
+ m = k_in.sum()
163
+ # Expected adjacency matrix
164
+ X = np.outer(k_out, k_in) / m
165
+
166
+ return A - X
env-llmeval/lib/python3.10/site-packages/networkx/linalg/spectrum.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Eigenvalue spectrum of graphs.
3
+ """
4
+ import networkx as nx
5
+
6
+ __all__ = [
7
+ "laplacian_spectrum",
8
+ "adjacency_spectrum",
9
+ "modularity_spectrum",
10
+ "normalized_laplacian_spectrum",
11
+ "bethe_hessian_spectrum",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(edge_attrs="weight")
16
+ def laplacian_spectrum(G, weight="weight"):
17
+ """Returns eigenvalues of the Laplacian of G
18
+
19
+ Parameters
20
+ ----------
21
+ G : graph
22
+ A NetworkX graph
23
+
24
+ weight : string or None, optional (default='weight')
25
+ The edge data key used to compute each value in the matrix.
26
+ If None, then each edge has weight 1.
27
+
28
+ Returns
29
+ -------
30
+ evals : NumPy array
31
+ Eigenvalues
32
+
33
+ Notes
34
+ -----
35
+ For MultiGraph/MultiDiGraph, the edges weights are summed.
36
+ See :func:`~networkx.convert_matrix.to_numpy_array` for other options.
37
+
38
+ See Also
39
+ --------
40
+ laplacian_matrix
41
+
42
+ Examples
43
+ --------
44
+ The multiplicity of 0 as an eigenvalue of the laplacian matrix is equal
45
+ to the number of connected components of G.
46
+
47
+ >>> G = nx.Graph() # Create a graph with 5 nodes and 3 connected components
48
+ >>> G.add_nodes_from(range(5))
49
+ >>> G.add_edges_from([(0, 2), (3, 4)])
50
+ >>> nx.laplacian_spectrum(G)
51
+ array([0., 0., 0., 2., 2.])
52
+
53
+ """
54
+ import scipy as sp
55
+
56
+ return sp.linalg.eigvalsh(nx.laplacian_matrix(G, weight=weight).todense())
57
+
58
+
59
+ @nx._dispatchable(edge_attrs="weight")
60
+ def normalized_laplacian_spectrum(G, weight="weight"):
61
+ """Return eigenvalues of the normalized Laplacian of G
62
+
63
+ Parameters
64
+ ----------
65
+ G : graph
66
+ A NetworkX graph
67
+
68
+ weight : string or None, optional (default='weight')
69
+ The edge data key used to compute each value in the matrix.
70
+ If None, then each edge has weight 1.
71
+
72
+ Returns
73
+ -------
74
+ evals : NumPy array
75
+ Eigenvalues
76
+
77
+ Notes
78
+ -----
79
+ For MultiGraph/MultiDiGraph, the edges weights are summed.
80
+ See to_numpy_array for other options.
81
+
82
+ See Also
83
+ --------
84
+ normalized_laplacian_matrix
85
+ """
86
+ import scipy as sp
87
+
88
+ return sp.linalg.eigvalsh(
89
+ nx.normalized_laplacian_matrix(G, weight=weight).todense()
90
+ )
91
+
92
+
93
+ @nx._dispatchable(edge_attrs="weight")
94
+ def adjacency_spectrum(G, weight="weight"):
95
+ """Returns eigenvalues of the adjacency matrix of G.
96
+
97
+ Parameters
98
+ ----------
99
+ G : graph
100
+ A NetworkX graph
101
+
102
+ weight : string or None, optional (default='weight')
103
+ The edge data key used to compute each value in the matrix.
104
+ If None, then each edge has weight 1.
105
+
106
+ Returns
107
+ -------
108
+ evals : NumPy array
109
+ Eigenvalues
110
+
111
+ Notes
112
+ -----
113
+ For MultiGraph/MultiDiGraph, the edges weights are summed.
114
+ See to_numpy_array for other options.
115
+
116
+ See Also
117
+ --------
118
+ adjacency_matrix
119
+ """
120
+ import scipy as sp
121
+
122
+ return sp.linalg.eigvals(nx.adjacency_matrix(G, weight=weight).todense())
123
+
124
+
125
+ @nx._dispatchable
126
+ def modularity_spectrum(G):
127
+ """Returns eigenvalues of the modularity matrix of G.
128
+
129
+ Parameters
130
+ ----------
131
+ G : Graph
132
+ A NetworkX Graph or DiGraph
133
+
134
+ Returns
135
+ -------
136
+ evals : NumPy array
137
+ Eigenvalues
138
+
139
+ See Also
140
+ --------
141
+ modularity_matrix
142
+
143
+ References
144
+ ----------
145
+ .. [1] M. E. J. Newman, "Modularity and community structure in networks",
146
+ Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
147
+ """
148
+ import scipy as sp
149
+
150
+ if G.is_directed():
151
+ return sp.linalg.eigvals(nx.directed_modularity_matrix(G))
152
+ else:
153
+ return sp.linalg.eigvals(nx.modularity_matrix(G))
154
+
155
+
156
+ @nx._dispatchable
157
+ def bethe_hessian_spectrum(G, r=None):
158
+ """Returns eigenvalues of the Bethe Hessian matrix of G.
159
+
160
+ Parameters
161
+ ----------
162
+ G : Graph
163
+ A NetworkX Graph or DiGraph
164
+
165
+ r : float
166
+ Regularizer parameter
167
+
168
+ Returns
169
+ -------
170
+ evals : NumPy array
171
+ Eigenvalues
172
+
173
+ See Also
174
+ --------
175
+ bethe_hessian_matrix
176
+
177
+ References
178
+ ----------
179
+ .. [1] A. Saade, F. Krzakala and L. Zdeborová
180
+ "Spectral clustering of graphs with the bethe hessian",
181
+ Advances in Neural Information Processing Systems. 2014.
182
+ """
183
+ import scipy as sp
184
+
185
+ return sp.linalg.eigvalsh(nx.bethe_hessian_matrix(G, r).todense())
env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_bethehessian.cpython-310.pyc ADDED
Binary file (1.4 kB). View file