ZTWHHH commited on
Commit
cc08e9e
·
verified ·
1 Parent(s): f175de9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. llava_next/lib/python3.10/site-packages/google/_upb/_message.abi3.so +3 -0
  3. llava_next/lib/python3.10/site-packages/idna/__pycache__/codec.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/idna/__pycache__/compat.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/idna/__pycache__/core.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/idna/__pycache__/intranges.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/idna/__pycache__/package_data.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/idna/core.py +437 -0
  9. llava_next/lib/python3.10/site-packages/idna/intranges.py +57 -0
  10. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/__init__.py +87 -0
  11. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/centrality.py +290 -0
  12. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/edgelist.py +360 -0
  13. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/extendability.py +105 -0
  14. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/matrix.py +168 -0
  15. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/projection.py +526 -0
  16. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/spectral.py +69 -0
  17. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_covering.cpython-310.pyc +0 -0
  18. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_extendability.cpython-310.pyc +0 -0
  19. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_project.cpython-310.pyc +0 -0
  20. llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_spectral_bipartivity.cpython-310.pyc +0 -0
  21. llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/__init__.cpython-310.pyc +0 -0
  22. llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/isomorph.cpython-310.pyc +0 -0
  23. llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/isomorphvf2.cpython-310.pyc +0 -0
  24. llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/vf2userfunc.cpython-310.pyc +0 -0
  25. llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/__init__.py +27 -0
  26. llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/__pycache__/__init__.cpython-310.pyc +0 -0
  27. llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/__pycache__/contraction.cpython-310.pyc +0 -0
  28. llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/contraction.py +634 -0
  29. llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/tests/__pycache__/test_contraction.cpython-310.pyc +0 -0
  30. llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/tests/test_contraction.py +446 -0
  31. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__init__.py +5 -0
  32. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/__init__.cpython-310.pyc +0 -0
  33. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/astar.cpython-310.pyc +0 -0
  34. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/dense.cpython-310.pyc +0 -0
  35. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/generic.cpython-310.pyc +0 -0
  36. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/unweighted.cpython-310.pyc +0 -0
  37. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/weighted.cpython-310.pyc +0 -0
  38. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/astar.py +241 -0
  39. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/dense.py +260 -0
  40. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/generic.py +730 -0
  41. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__init__.py +0 -0
  42. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  43. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_astar.cpython-310.pyc +0 -0
  44. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_dense.cpython-310.pyc +0 -0
  45. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_dense_numpy.cpython-310.pyc +0 -0
  46. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_generic.cpython-310.pyc +0 -0
  47. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_unweighted.cpython-310.pyc +0 -0
  48. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_weighted.cpython-310.pyc +0 -0
  49. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_astar.py +248 -0
  50. llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense.py +212 -0
.gitattributes CHANGED
@@ -1152,3 +1152,4 @@ llava_next/lib/python3.10/site-packages/pillow.libs/libjpeg-77ae51ab.so.62.4.0 f
1152
  llava_next/lib/python3.10/site-packages/pillow.libs/libopenjp2-05423b53.so filter=lfs diff=lfs merge=lfs -text
1153
  vlmpy310/lib/python3.10/site-packages/notebook/static/373c04fd2418f5c77eea.eot filter=lfs diff=lfs merge=lfs -text
1154
  vlmpy310/lib/python3.10/site-packages/imageio/plugins/__pycache__/_tifffile.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
1152
  llava_next/lib/python3.10/site-packages/pillow.libs/libopenjp2-05423b53.so filter=lfs diff=lfs merge=lfs -text
1153
  vlmpy310/lib/python3.10/site-packages/notebook/static/373c04fd2418f5c77eea.eot filter=lfs diff=lfs merge=lfs -text
1154
  vlmpy310/lib/python3.10/site-packages/imageio/plugins/__pycache__/_tifffile.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1155
+ llava_next/lib/python3.10/site-packages/google/_upb/_message.abi3.so filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/google/_upb/_message.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff4ddd7728b504891d45bf8f69356eafae7abd53c10298e964be6b483a30bdc8
3
+ size 390840
llava_next/lib/python3.10/site-packages/idna/__pycache__/codec.cpython-310.pyc ADDED
Binary file (3.25 kB). View file
 
llava_next/lib/python3.10/site-packages/idna/__pycache__/compat.cpython-310.pyc ADDED
Binary file (727 Bytes). View file
 
llava_next/lib/python3.10/site-packages/idna/__pycache__/core.cpython-310.pyc ADDED
Binary file (9.64 kB). View file
 
llava_next/lib/python3.10/site-packages/idna/__pycache__/intranges.cpython-310.pyc ADDED
Binary file (1.96 kB). View file
 
llava_next/lib/python3.10/site-packages/idna/__pycache__/package_data.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
llava_next/lib/python3.10/site-packages/idna/core.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bisect
2
+ import re
3
+ import unicodedata
4
+ from typing import Optional, Union
5
+
6
+ from . import idnadata
7
+ from .intranges import intranges_contain
8
+
9
+ _virama_combining_class = 9
10
+ _alabel_prefix = b"xn--"
11
+ _unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]")
12
+
13
+
14
+ class IDNAError(UnicodeError):
15
+ """Base exception for all IDNA-encoding related problems"""
16
+
17
+ pass
18
+
19
+
20
+ class IDNABidiError(IDNAError):
21
+ """Exception when bidirectional requirements are not satisfied"""
22
+
23
+ pass
24
+
25
+
26
+ class InvalidCodepoint(IDNAError):
27
+ """Exception when a disallowed or unallocated codepoint is used"""
28
+
29
+ pass
30
+
31
+
32
+ class InvalidCodepointContext(IDNAError):
33
+ """Exception when the codepoint is not valid in the context it is used"""
34
+
35
+ pass
36
+
37
+
38
+ def _combining_class(cp: int) -> int:
39
+ v = unicodedata.combining(chr(cp))
40
+ if v == 0:
41
+ if not unicodedata.name(chr(cp)):
42
+ raise ValueError("Unknown character in unicodedata")
43
+ return v
44
+
45
+
46
+ def _is_script(cp: str, script: str) -> bool:
47
+ return intranges_contain(ord(cp), idnadata.scripts[script])
48
+
49
+
50
+ def _punycode(s: str) -> bytes:
51
+ return s.encode("punycode")
52
+
53
+
54
+ def _unot(s: int) -> str:
55
+ return "U+{:04X}".format(s)
56
+
57
+
58
+ def valid_label_length(label: Union[bytes, str]) -> bool:
59
+ if len(label) > 63:
60
+ return False
61
+ return True
62
+
63
+
64
+ def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool:
65
+ if len(label) > (254 if trailing_dot else 253):
66
+ return False
67
+ return True
68
+
69
+
70
+ def check_bidi(label: str, check_ltr: bool = False) -> bool:
71
+ # Bidi rules should only be applied if string contains RTL characters
72
+ bidi_label = False
73
+ for idx, cp in enumerate(label, 1):
74
+ direction = unicodedata.bidirectional(cp)
75
+ if direction == "":
76
+ # String likely comes from a newer version of Unicode
77
+ raise IDNABidiError("Unknown directionality in label {} at position {}".format(repr(label), idx))
78
+ if direction in ["R", "AL", "AN"]:
79
+ bidi_label = True
80
+ if not bidi_label and not check_ltr:
81
+ return True
82
+
83
+ # Bidi rule 1
84
+ direction = unicodedata.bidirectional(label[0])
85
+ if direction in ["R", "AL"]:
86
+ rtl = True
87
+ elif direction == "L":
88
+ rtl = False
89
+ else:
90
+ raise IDNABidiError("First codepoint in label {} must be directionality L, R or AL".format(repr(label)))
91
+
92
+ valid_ending = False
93
+ number_type: Optional[str] = None
94
+ for idx, cp in enumerate(label, 1):
95
+ direction = unicodedata.bidirectional(cp)
96
+
97
+ if rtl:
98
+ # Bidi rule 2
99
+ if direction not in [
100
+ "R",
101
+ "AL",
102
+ "AN",
103
+ "EN",
104
+ "ES",
105
+ "CS",
106
+ "ET",
107
+ "ON",
108
+ "BN",
109
+ "NSM",
110
+ ]:
111
+ raise IDNABidiError("Invalid direction for codepoint at position {} in a right-to-left label".format(idx))
112
+ # Bidi rule 3
113
+ if direction in ["R", "AL", "EN", "AN"]:
114
+ valid_ending = True
115
+ elif direction != "NSM":
116
+ valid_ending = False
117
+ # Bidi rule 4
118
+ if direction in ["AN", "EN"]:
119
+ if not number_type:
120
+ number_type = direction
121
+ else:
122
+ if number_type != direction:
123
+ raise IDNABidiError("Can not mix numeral types in a right-to-left label")
124
+ else:
125
+ # Bidi rule 5
126
+ if direction not in ["L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"]:
127
+ raise IDNABidiError("Invalid direction for codepoint at position {} in a left-to-right label".format(idx))
128
+ # Bidi rule 6
129
+ if direction in ["L", "EN"]:
130
+ valid_ending = True
131
+ elif direction != "NSM":
132
+ valid_ending = False
133
+
134
+ if not valid_ending:
135
+ raise IDNABidiError("Label ends with illegal codepoint directionality")
136
+
137
+ return True
138
+
139
+
140
+ def check_initial_combiner(label: str) -> bool:
141
+ if unicodedata.category(label[0])[0] == "M":
142
+ raise IDNAError("Label begins with an illegal combining character")
143
+ return True
144
+
145
+
146
+ def check_hyphen_ok(label: str) -> bool:
147
+ if label[2:4] == "--":
148
+ raise IDNAError("Label has disallowed hyphens in 3rd and 4th position")
149
+ if label[0] == "-" or label[-1] == "-":
150
+ raise IDNAError("Label must not start or end with a hyphen")
151
+ return True
152
+
153
+
154
+ def check_nfc(label: str) -> None:
155
+ if unicodedata.normalize("NFC", label) != label:
156
+ raise IDNAError("Label must be in Normalization Form C")
157
+
158
+
159
+ def valid_contextj(label: str, pos: int) -> bool:
160
+ cp_value = ord(label[pos])
161
+
162
+ if cp_value == 0x200C:
163
+ if pos > 0:
164
+ if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
165
+ return True
166
+
167
+ ok = False
168
+ for i in range(pos - 1, -1, -1):
169
+ joining_type = idnadata.joining_types.get(ord(label[i]))
170
+ if joining_type == ord("T"):
171
+ continue
172
+ elif joining_type in [ord("L"), ord("D")]:
173
+ ok = True
174
+ break
175
+ else:
176
+ break
177
+
178
+ if not ok:
179
+ return False
180
+
181
+ ok = False
182
+ for i in range(pos + 1, len(label)):
183
+ joining_type = idnadata.joining_types.get(ord(label[i]))
184
+ if joining_type == ord("T"):
185
+ continue
186
+ elif joining_type in [ord("R"), ord("D")]:
187
+ ok = True
188
+ break
189
+ else:
190
+ break
191
+ return ok
192
+
193
+ if cp_value == 0x200D:
194
+ if pos > 0:
195
+ if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
196
+ return True
197
+ return False
198
+
199
+ else:
200
+ return False
201
+
202
+
203
+ def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
204
+ cp_value = ord(label[pos])
205
+
206
+ if cp_value == 0x00B7:
207
+ if 0 < pos < len(label) - 1:
208
+ if ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C:
209
+ return True
210
+ return False
211
+
212
+ elif cp_value == 0x0375:
213
+ if pos < len(label) - 1 and len(label) > 1:
214
+ return _is_script(label[pos + 1], "Greek")
215
+ return False
216
+
217
+ elif cp_value == 0x05F3 or cp_value == 0x05F4:
218
+ if pos > 0:
219
+ return _is_script(label[pos - 1], "Hebrew")
220
+ return False
221
+
222
+ elif cp_value == 0x30FB:
223
+ for cp in label:
224
+ if cp == "\u30fb":
225
+ continue
226
+ if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"):
227
+ return True
228
+ return False
229
+
230
+ elif 0x660 <= cp_value <= 0x669:
231
+ for cp in label:
232
+ if 0x6F0 <= ord(cp) <= 0x06F9:
233
+ return False
234
+ return True
235
+
236
+ elif 0x6F0 <= cp_value <= 0x6F9:
237
+ for cp in label:
238
+ if 0x660 <= ord(cp) <= 0x0669:
239
+ return False
240
+ return True
241
+
242
+ return False
243
+
244
+
245
+ def check_label(label: Union[str, bytes, bytearray]) -> None:
246
+ if isinstance(label, (bytes, bytearray)):
247
+ label = label.decode("utf-8")
248
+ if len(label) == 0:
249
+ raise IDNAError("Empty Label")
250
+
251
+ check_nfc(label)
252
+ check_hyphen_ok(label)
253
+ check_initial_combiner(label)
254
+
255
+ for pos, cp in enumerate(label):
256
+ cp_value = ord(cp)
257
+ if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]):
258
+ continue
259
+ elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]):
260
+ try:
261
+ if not valid_contextj(label, pos):
262
+ raise InvalidCodepointContext(
263
+ "Joiner {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label))
264
+ )
265
+ except ValueError:
266
+ raise IDNAError(
267
+ "Unknown codepoint adjacent to joiner {} at position {} in {}".format(
268
+ _unot(cp_value), pos + 1, repr(label)
269
+ )
270
+ )
271
+ elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]):
272
+ if not valid_contexto(label, pos):
273
+ raise InvalidCodepointContext(
274
+ "Codepoint {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label))
275
+ )
276
+ else:
277
+ raise InvalidCodepoint(
278
+ "Codepoint {} at position {} of {} not allowed".format(_unot(cp_value), pos + 1, repr(label))
279
+ )
280
+
281
+ check_bidi(label)
282
+
283
+
284
+ def alabel(label: str) -> bytes:
285
+ try:
286
+ label_bytes = label.encode("ascii")
287
+ ulabel(label_bytes)
288
+ if not valid_label_length(label_bytes):
289
+ raise IDNAError("Label too long")
290
+ return label_bytes
291
+ except UnicodeEncodeError:
292
+ pass
293
+
294
+ check_label(label)
295
+ label_bytes = _alabel_prefix + _punycode(label)
296
+
297
+ if not valid_label_length(label_bytes):
298
+ raise IDNAError("Label too long")
299
+
300
+ return label_bytes
301
+
302
+
303
+ def ulabel(label: Union[str, bytes, bytearray]) -> str:
304
+ if not isinstance(label, (bytes, bytearray)):
305
+ try:
306
+ label_bytes = label.encode("ascii")
307
+ except UnicodeEncodeError:
308
+ check_label(label)
309
+ return label
310
+ else:
311
+ label_bytes = label
312
+
313
+ label_bytes = label_bytes.lower()
314
+ if label_bytes.startswith(_alabel_prefix):
315
+ label_bytes = label_bytes[len(_alabel_prefix) :]
316
+ if not label_bytes:
317
+ raise IDNAError("Malformed A-label, no Punycode eligible content found")
318
+ if label_bytes.decode("ascii")[-1] == "-":
319
+ raise IDNAError("A-label must not end with a hyphen")
320
+ else:
321
+ check_label(label_bytes)
322
+ return label_bytes.decode("ascii")
323
+
324
+ try:
325
+ label = label_bytes.decode("punycode")
326
+ except UnicodeError:
327
+ raise IDNAError("Invalid A-label")
328
+ check_label(label)
329
+ return label
330
+
331
+
332
+ def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
333
+ """Re-map the characters in the string according to UTS46 processing."""
334
+ from .uts46data import uts46data
335
+
336
+ output = ""
337
+
338
+ for pos, char in enumerate(domain):
339
+ code_point = ord(char)
340
+ try:
341
+ uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1]
342
+ status = uts46row[1]
343
+ replacement: Optional[str] = None
344
+ if len(uts46row) == 3:
345
+ replacement = uts46row[2]
346
+ if (
347
+ status == "V"
348
+ or (status == "D" and not transitional)
349
+ or (status == "3" and not std3_rules and replacement is None)
350
+ ):
351
+ output += char
352
+ elif replacement is not None and (
353
+ status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)
354
+ ):
355
+ output += replacement
356
+ elif status != "I":
357
+ raise IndexError()
358
+ except IndexError:
359
+ raise InvalidCodepoint(
360
+ "Codepoint {} not allowed at position {} in {}".format(_unot(code_point), pos + 1, repr(domain))
361
+ )
362
+
363
+ return unicodedata.normalize("NFC", output)
364
+
365
+
366
+ def encode(
367
+ s: Union[str, bytes, bytearray],
368
+ strict: bool = False,
369
+ uts46: bool = False,
370
+ std3_rules: bool = False,
371
+ transitional: bool = False,
372
+ ) -> bytes:
373
+ if not isinstance(s, str):
374
+ try:
375
+ s = str(s, "ascii")
376
+ except UnicodeDecodeError:
377
+ raise IDNAError("should pass a unicode string to the function rather than a byte string.")
378
+ if uts46:
379
+ s = uts46_remap(s, std3_rules, transitional)
380
+ trailing_dot = False
381
+ result = []
382
+ if strict:
383
+ labels = s.split(".")
384
+ else:
385
+ labels = _unicode_dots_re.split(s)
386
+ if not labels or labels == [""]:
387
+ raise IDNAError("Empty domain")
388
+ if labels[-1] == "":
389
+ del labels[-1]
390
+ trailing_dot = True
391
+ for label in labels:
392
+ s = alabel(label)
393
+ if s:
394
+ result.append(s)
395
+ else:
396
+ raise IDNAError("Empty label")
397
+ if trailing_dot:
398
+ result.append(b"")
399
+ s = b".".join(result)
400
+ if not valid_string_length(s, trailing_dot):
401
+ raise IDNAError("Domain too long")
402
+ return s
403
+
404
+
405
+ def decode(
406
+ s: Union[str, bytes, bytearray],
407
+ strict: bool = False,
408
+ uts46: bool = False,
409
+ std3_rules: bool = False,
410
+ ) -> str:
411
+ try:
412
+ if not isinstance(s, str):
413
+ s = str(s, "ascii")
414
+ except UnicodeDecodeError:
415
+ raise IDNAError("Invalid ASCII in A-label")
416
+ if uts46:
417
+ s = uts46_remap(s, std3_rules, False)
418
+ trailing_dot = False
419
+ result = []
420
+ if not strict:
421
+ labels = _unicode_dots_re.split(s)
422
+ else:
423
+ labels = s.split(".")
424
+ if not labels or labels == [""]:
425
+ raise IDNAError("Empty domain")
426
+ if not labels[-1]:
427
+ del labels[-1]
428
+ trailing_dot = True
429
+ for label in labels:
430
+ s = ulabel(label)
431
+ if s:
432
+ result.append(s)
433
+ else:
434
+ raise IDNAError("Empty label")
435
+ if trailing_dot:
436
+ result.append("")
437
+ return ".".join(result)
llava_next/lib/python3.10/site-packages/idna/intranges.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Given a list of integers, made up of (hopefully) a small number of long runs
3
+ of consecutive integers, compute a representation of the form
4
+ ((start1, end1), (start2, end2) ...). Then answer the question "was x present
5
+ in the original list?" in time O(log(# runs)).
6
+ """
7
+
8
+ import bisect
9
+ from typing import List, Tuple
10
+
11
+
12
+ def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:
13
+ """Represent a list of integers as a sequence of ranges:
14
+ ((start_0, end_0), (start_1, end_1), ...), such that the original
15
+ integers are exactly those x such that start_i <= x < end_i for some i.
16
+
17
+ Ranges are encoded as single integers (start << 32 | end), not as tuples.
18
+ """
19
+
20
+ sorted_list = sorted(list_)
21
+ ranges = []
22
+ last_write = -1
23
+ for i in range(len(sorted_list)):
24
+ if i + 1 < len(sorted_list):
25
+ if sorted_list[i] == sorted_list[i + 1] - 1:
26
+ continue
27
+ current_range = sorted_list[last_write + 1 : i + 1]
28
+ ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
29
+ last_write = i
30
+
31
+ return tuple(ranges)
32
+
33
+
34
+ def _encode_range(start: int, end: int) -> int:
35
+ return (start << 32) | end
36
+
37
+
38
+ def _decode_range(r: int) -> Tuple[int, int]:
39
+ return (r >> 32), (r & ((1 << 32) - 1))
40
+
41
+
42
+ def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:
43
+ """Determine if `int_` falls into one of the ranges in `ranges`."""
44
+ tuple_ = _encode_range(int_, 0)
45
+ pos = bisect.bisect_left(ranges, tuple_)
46
+ # we could be immediately ahead of a tuple (start, end)
47
+ # with start < int_ <= end
48
+ if pos > 0:
49
+ left, right = _decode_range(ranges[pos - 1])
50
+ if left <= int_ < right:
51
+ return True
52
+ # or we could be immediately behind a tuple (int_, end)
53
+ if pos < len(ranges):
54
+ left, _ = _decode_range(ranges[pos])
55
+ if left == int_:
56
+ return True
57
+ return False
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/__init__.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""This module provides functions and operations for bipartite
2
+ graphs. Bipartite graphs `B = (U, V, E)` have two node sets `U,V` and edges in
3
+ `E` that only connect nodes from opposite sets. It is common in the literature
4
+ to use an spatial analogy referring to the two node sets as top and bottom nodes.
5
+
6
+ The bipartite algorithms are not imported into the networkx namespace
7
+ at the top level so the easiest way to use them is with:
8
+
9
+ >>> from networkx.algorithms import bipartite
10
+
11
+ NetworkX does not have a custom bipartite graph class but the Graph()
12
+ or DiGraph() classes can be used to represent bipartite graphs. However,
13
+ you have to keep track of which set each node belongs to, and make
14
+ sure that there is no edge between nodes of the same set. The convention used
15
+ in NetworkX is to use a node attribute named `bipartite` with values 0 or 1 to
16
+ identify the sets each node belongs to. This convention is not enforced in
17
+ the source code of bipartite functions, it's only a recommendation.
18
+
19
+ For example:
20
+
21
+ >>> B = nx.Graph()
22
+ >>> # Add nodes with the node attribute "bipartite"
23
+ >>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
24
+ >>> B.add_nodes_from(["a", "b", "c"], bipartite=1)
25
+ >>> # Add edges only between nodes of opposite node sets
26
+ >>> B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
27
+
28
+ Many algorithms of the bipartite module of NetworkX require, as an argument, a
29
+ container with all the nodes that belong to one set, in addition to the bipartite
30
+ graph `B`. The functions in the bipartite package do not check that the node set
31
+ is actually correct nor that the input graph is actually bipartite.
32
+ If `B` is connected, you can find the two node sets using a two-coloring
33
+ algorithm:
34
+
35
+ >>> nx.is_connected(B)
36
+ True
37
+ >>> bottom_nodes, top_nodes = bipartite.sets(B)
38
+
39
+ However, if the input graph is not connected, there are more than one possible
40
+ colorations. This is the reason why we require the user to pass a container
41
+ with all nodes of one bipartite node set as an argument to most bipartite
42
+ functions. In the face of ambiguity, we refuse the temptation to guess and
43
+ raise an :exc:`AmbiguousSolution <networkx.AmbiguousSolution>`
44
+ Exception if the input graph for
45
+ :func:`bipartite.sets <networkx.algorithms.bipartite.basic.sets>`
46
+ is disconnected.
47
+
48
+ Using the `bipartite` node attribute, you can easily get the two node sets:
49
+
50
+ >>> top_nodes = {n for n, d in B.nodes(data=True) if d["bipartite"] == 0}
51
+ >>> bottom_nodes = set(B) - top_nodes
52
+
53
+ So you can easily use the bipartite algorithms that require, as an argument, a
54
+ container with all nodes that belong to one node set:
55
+
56
+ >>> print(round(bipartite.density(B, bottom_nodes), 2))
57
+ 0.5
58
+ >>> G = bipartite.projected_graph(B, top_nodes)
59
+
60
+ All bipartite graph generators in NetworkX build bipartite graphs with the
61
+ `bipartite` node attribute. Thus, you can use the same approach:
62
+
63
+ >>> RB = bipartite.random_graph(5, 7, 0.2)
64
+ >>> RB_top = {n for n, d in RB.nodes(data=True) if d["bipartite"] == 0}
65
+ >>> RB_bottom = set(RB) - RB_top
66
+ >>> list(RB_top)
67
+ [0, 1, 2, 3, 4]
68
+ >>> list(RB_bottom)
69
+ [5, 6, 7, 8, 9, 10, 11]
70
+
71
+ For other bipartite graph generators see
72
+ :mod:`Generators <networkx.algorithms.bipartite.generators>`.
73
+
74
+ """
75
+
76
+ from networkx.algorithms.bipartite.basic import *
77
+ from networkx.algorithms.bipartite.centrality import *
78
+ from networkx.algorithms.bipartite.cluster import *
79
+ from networkx.algorithms.bipartite.covering import *
80
+ from networkx.algorithms.bipartite.edgelist import *
81
+ from networkx.algorithms.bipartite.matching import *
82
+ from networkx.algorithms.bipartite.matrix import *
83
+ from networkx.algorithms.bipartite.projection import *
84
+ from networkx.algorithms.bipartite.redundancy import *
85
+ from networkx.algorithms.bipartite.spectral import *
86
+ from networkx.algorithms.bipartite.generators import *
87
+ from networkx.algorithms.bipartite.extendability import *
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/centrality.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"]
4
+
5
+
6
+ @nx._dispatchable(name="bipartite_degree_centrality")
7
+ def degree_centrality(G, nodes):
8
+ r"""Compute the degree centrality for nodes in a bipartite network.
9
+
10
+ The degree centrality for a node `v` is the fraction of nodes
11
+ connected to it.
12
+
13
+ Parameters
14
+ ----------
15
+ G : graph
16
+ A bipartite network
17
+
18
+ nodes : list or container
19
+ Container with all nodes in one bipartite node set.
20
+
21
+ Returns
22
+ -------
23
+ centrality : dictionary
24
+ Dictionary keyed by node with bipartite degree centrality as the value.
25
+
26
+ Examples
27
+ --------
28
+ >>> G = nx.wheel_graph(5)
29
+ >>> top_nodes = {0, 1, 2}
30
+ >>> nx.bipartite.degree_centrality(G, nodes=top_nodes)
31
+ {0: 2.0, 1: 1.5, 2: 1.5, 3: 1.0, 4: 1.0}
32
+
33
+ See Also
34
+ --------
35
+ betweenness_centrality
36
+ closeness_centrality
37
+ :func:`~networkx.algorithms.bipartite.basic.sets`
38
+ :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
39
+
40
+ Notes
41
+ -----
42
+ The nodes input parameter must contain all nodes in one bipartite node set,
43
+ but the dictionary returned contains all nodes from both bipartite node
44
+ sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
45
+ for further details on how bipartite graphs are handled in NetworkX.
46
+
47
+ For unipartite networks, the degree centrality values are
48
+ normalized by dividing by the maximum possible degree (which is
49
+ `n-1` where `n` is the number of nodes in G).
50
+
51
+ In the bipartite case, the maximum possible degree of a node in a
52
+ bipartite node set is the number of nodes in the opposite node set
53
+ [1]_. The degree centrality for a node `v` in the bipartite
54
+ sets `U` with `n` nodes and `V` with `m` nodes is
55
+
56
+ .. math::
57
+
58
+ d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U ,
59
+
60
+ d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V ,
61
+
62
+
63
+ where `deg(v)` is the degree of node `v`.
64
+
65
+ References
66
+ ----------
67
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
68
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
69
+ of Social Network Analysis. Sage Publications.
70
+ https://dx.doi.org/10.4135/9781446294413.n28
71
+ """
72
+ top = set(nodes)
73
+ bottom = set(G) - top
74
+ s = 1.0 / len(bottom)
75
+ centrality = {n: d * s for n, d in G.degree(top)}
76
+ s = 1.0 / len(top)
77
+ centrality.update({n: d * s for n, d in G.degree(bottom)})
78
+ return centrality
79
+
80
+
81
+ @nx._dispatchable(name="bipartite_betweenness_centrality")
82
+ def betweenness_centrality(G, nodes):
83
+ r"""Compute betweenness centrality for nodes in a bipartite network.
84
+
85
+ Betweenness centrality of a node `v` is the sum of the
86
+ fraction of all-pairs shortest paths that pass through `v`.
87
+
88
+ Values of betweenness are normalized by the maximum possible
89
+ value which for bipartite graphs is limited by the relative size
90
+ of the two node sets [1]_.
91
+
92
+ Let `n` be the number of nodes in the node set `U` and
93
+ `m` be the number of nodes in the node set `V`, then
94
+ nodes in `U` are normalized by dividing by
95
+
96
+ .. math::
97
+
98
+ \frac{1}{2} [m^2 (s + 1)^2 + m (s + 1)(2t - s - 1) - t (2s - t + 3)] ,
99
+
100
+ where
101
+
102
+ .. math::
103
+
104
+ s = (n - 1) \div m , t = (n - 1) \mod m ,
105
+
106
+ and nodes in `V` are normalized by dividing by
107
+
108
+ .. math::
109
+
110
+ \frac{1}{2} [n^2 (p + 1)^2 + n (p + 1)(2r - p - 1) - r (2p - r + 3)] ,
111
+
112
+ where,
113
+
114
+ .. math::
115
+
116
+ p = (m - 1) \div n , r = (m - 1) \mod n .
117
+
118
+ Parameters
119
+ ----------
120
+ G : graph
121
+ A bipartite graph
122
+
123
+ nodes : list or container
124
+ Container with all nodes in one bipartite node set.
125
+
126
+ Returns
127
+ -------
128
+ betweenness : dictionary
129
+ Dictionary keyed by node with bipartite betweenness centrality
130
+ as the value.
131
+
132
+ Examples
133
+ --------
134
+ >>> G = nx.cycle_graph(4)
135
+ >>> top_nodes = {1, 2}
136
+ >>> nx.bipartite.betweenness_centrality(G, nodes=top_nodes)
137
+ {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
138
+
139
+ See Also
140
+ --------
141
+ degree_centrality
142
+ closeness_centrality
143
+ :func:`~networkx.algorithms.bipartite.basic.sets`
144
+ :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
145
+
146
+ Notes
147
+ -----
148
+ The nodes input parameter must contain all nodes in one bipartite node set,
149
+ but the dictionary returned contains all nodes from both node sets.
150
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
151
+ for further details on how bipartite graphs are handled in NetworkX.
152
+
153
+
154
+ References
155
+ ----------
156
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
157
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
158
+ of Social Network Analysis. Sage Publications.
159
+ https://dx.doi.org/10.4135/9781446294413.n28
160
+ """
161
+ top = set(nodes)
162
+ bottom = set(G) - top
163
+ n = len(top)
164
+ m = len(bottom)
165
+ s, t = divmod(n - 1, m)
166
+ bet_max_top = (
167
+ ((m**2) * ((s + 1) ** 2))
168
+ + (m * (s + 1) * (2 * t - s - 1))
169
+ - (t * ((2 * s) - t + 3))
170
+ ) / 2.0
171
+ p, r = divmod(m - 1, n)
172
+ bet_max_bot = (
173
+ ((n**2) * ((p + 1) ** 2))
174
+ + (n * (p + 1) * (2 * r - p - 1))
175
+ - (r * ((2 * p) - r + 3))
176
+ ) / 2.0
177
+ betweenness = nx.betweenness_centrality(G, normalized=False, weight=None)
178
+ for node in top:
179
+ betweenness[node] /= bet_max_top
180
+ for node in bottom:
181
+ betweenness[node] /= bet_max_bot
182
+ return betweenness
183
+
184
+
185
+ @nx._dispatchable(name="bipartite_closeness_centrality")
186
+ def closeness_centrality(G, nodes, normalized=True):
187
+ r"""Compute the closeness centrality for nodes in a bipartite network.
188
+
189
+ The closeness of a node is the distance to all other nodes in the
190
+ graph or in the case that the graph is not connected to all other nodes
191
+ in the connected component containing that node.
192
+
193
+ Parameters
194
+ ----------
195
+ G : graph
196
+ A bipartite network
197
+
198
+ nodes : list or container
199
+ Container with all nodes in one bipartite node set.
200
+
201
+ normalized : bool, optional
202
+ If True (default) normalize by connected component size.
203
+
204
+ Returns
205
+ -------
206
+ closeness : dictionary
207
+ Dictionary keyed by node with bipartite closeness centrality
208
+ as the value.
209
+
210
+ Examples
211
+ --------
212
+ >>> G = nx.wheel_graph(5)
213
+ >>> top_nodes = {0, 1, 2}
214
+ >>> nx.bipartite.closeness_centrality(G, nodes=top_nodes)
215
+ {0: 1.5, 1: 1.2, 2: 1.2, 3: 1.0, 4: 1.0}
216
+
217
+ See Also
218
+ --------
219
+ betweenness_centrality
220
+ degree_centrality
221
+ :func:`~networkx.algorithms.bipartite.basic.sets`
222
+ :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
223
+
224
+ Notes
225
+ -----
226
+ The nodes input parameter must contain all nodes in one bipartite node set,
227
+ but the dictionary returned contains all nodes from both node sets.
228
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
229
+ for further details on how bipartite graphs are handled in NetworkX.
230
+
231
+
232
+ Closeness centrality is normalized by the minimum distance possible.
233
+ In the bipartite case the minimum distance for a node in one bipartite
234
+ node set is 1 from all nodes in the other node set and 2 from all
235
+ other nodes in its own set [1]_. Thus the closeness centrality
236
+ for node `v` in the two bipartite sets `U` with
237
+ `n` nodes and `V` with `m` nodes is
238
+
239
+ .. math::
240
+
241
+ c_{v} = \frac{m + 2(n - 1)}{d}, \mbox{for} v \in U,
242
+
243
+ c_{v} = \frac{n + 2(m - 1)}{d}, \mbox{for} v \in V,
244
+
245
+ where `d` is the sum of the distances from `v` to all
246
+ other nodes.
247
+
248
+ Higher values of closeness indicate higher centrality.
249
+
250
+ As in the unipartite case, setting normalized=True causes the
251
+ values to normalized further to n-1 / size(G)-1 where n is the
252
+ number of nodes in the connected part of graph containing the
253
+ node. If the graph is not completely connected, this algorithm
254
+ computes the closeness centrality for each connected part
255
+ separately.
256
+
257
+ References
258
+ ----------
259
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
260
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
261
+ of Social Network Analysis. Sage Publications.
262
+ https://dx.doi.org/10.4135/9781446294413.n28
263
+ """
264
+ closeness = {}
265
+ path_length = nx.single_source_shortest_path_length
266
+ top = set(nodes)
267
+ bottom = set(G) - top
268
+ n = len(top)
269
+ m = len(bottom)
270
+ for node in top:
271
+ sp = dict(path_length(G, node))
272
+ totsp = sum(sp.values())
273
+ if totsp > 0.0 and len(G) > 1:
274
+ closeness[node] = (m + 2 * (n - 1)) / totsp
275
+ if normalized:
276
+ s = (len(sp) - 1) / (len(G) - 1)
277
+ closeness[node] *= s
278
+ else:
279
+ closeness[node] = 0.0
280
+ for node in bottom:
281
+ sp = dict(path_length(G, node))
282
+ totsp = sum(sp.values())
283
+ if totsp > 0.0 and len(G) > 1:
284
+ closeness[node] = (n + 2 * (m - 1)) / totsp
285
+ if normalized:
286
+ s = (len(sp) - 1) / (len(G) - 1)
287
+ closeness[node] *= s
288
+ else:
289
+ closeness[node] = 0.0
290
+ return closeness
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/edgelist.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ********************
3
+ Bipartite Edge Lists
4
+ ********************
5
+ Read and write NetworkX graphs as bipartite edge lists.
6
+
7
+ Format
8
+ ------
9
+ You can read or write three formats of edge lists with these functions.
10
+
11
+ Node pairs with no data::
12
+
13
+ 1 2
14
+
15
+ Python dictionary as data::
16
+
17
+ 1 2 {'weight':7, 'color':'green'}
18
+
19
+ Arbitrary data::
20
+
21
+ 1 2 7 green
22
+
23
+ For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.
24
+ """
25
+
26
+ __all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"]
27
+
28
+ import networkx as nx
29
+ from networkx.utils import not_implemented_for, open_file
30
+
31
+
32
+ @open_file(1, mode="wb")
33
+ def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"):
34
+ """Write a bipartite graph as a list of edges.
35
+
36
+ Parameters
37
+ ----------
38
+ G : Graph
39
+ A NetworkX bipartite graph
40
+ path : file or string
41
+ File or filename to write. If a file is provided, it must be
42
+ opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
43
+ comments : string, optional
44
+ The character used to indicate the start of a comment
45
+ delimiter : string, optional
46
+ The string used to separate values. The default is whitespace.
47
+ data : bool or list, optional
48
+ If False write no edge data.
49
+ If True write a string representation of the edge data dictionary..
50
+ If a list (or other iterable) is provided, write the keys specified
51
+ in the list.
52
+ encoding: string, optional
53
+ Specify which encoding to use when writing file.
54
+
55
+ Examples
56
+ --------
57
+ >>> G = nx.path_graph(4)
58
+ >>> G.add_nodes_from([0, 2], bipartite=0)
59
+ >>> G.add_nodes_from([1, 3], bipartite=1)
60
+ >>> nx.write_edgelist(G, "test.edgelist")
61
+ >>> fh = open("test.edgelist", "wb")
62
+ >>> nx.write_edgelist(G, fh)
63
+ >>> nx.write_edgelist(G, "test.edgelist.gz")
64
+ >>> nx.write_edgelist(G, "test.edgelist.gz", data=False)
65
+
66
+ >>> G = nx.Graph()
67
+ >>> G.add_edge(1, 2, weight=7, color="red")
68
+ >>> nx.write_edgelist(G, "test.edgelist", data=False)
69
+ >>> nx.write_edgelist(G, "test.edgelist", data=["color"])
70
+ >>> nx.write_edgelist(G, "test.edgelist", data=["color", "weight"])
71
+
72
+ See Also
73
+ --------
74
+ write_edgelist
75
+ generate_edgelist
76
+ """
77
+ for line in generate_edgelist(G, delimiter, data):
78
+ line += "\n"
79
+ path.write(line.encode(encoding))
80
+
81
+
82
+ @not_implemented_for("directed")
83
+ def generate_edgelist(G, delimiter=" ", data=True):
84
+ """Generate a single line of the bipartite graph G in edge list format.
85
+
86
+ Parameters
87
+ ----------
88
+ G : NetworkX graph
89
+ The graph is assumed to have node attribute `part` set to 0,1 representing
90
+ the two graph parts
91
+
92
+ delimiter : string, optional
93
+ Separator for node labels
94
+
95
+ data : bool or list of keys
96
+ If False generate no edge data. If True use a dictionary
97
+ representation of edge data. If a list of keys use a list of data
98
+ values corresponding to the keys.
99
+
100
+ Returns
101
+ -------
102
+ lines : string
103
+ Lines of data in adjlist format.
104
+
105
+ Examples
106
+ --------
107
+ >>> from networkx.algorithms import bipartite
108
+ >>> G = nx.path_graph(4)
109
+ >>> G.add_nodes_from([0, 2], bipartite=0)
110
+ >>> G.add_nodes_from([1, 3], bipartite=1)
111
+ >>> G[1][2]["weight"] = 3
112
+ >>> G[2][3]["capacity"] = 12
113
+ >>> for line in bipartite.generate_edgelist(G, data=False):
114
+ ... print(line)
115
+ 0 1
116
+ 2 1
117
+ 2 3
118
+
119
+ >>> for line in bipartite.generate_edgelist(G):
120
+ ... print(line)
121
+ 0 1 {}
122
+ 2 1 {'weight': 3}
123
+ 2 3 {'capacity': 12}
124
+
125
+ >>> for line in bipartite.generate_edgelist(G, data=["weight"]):
126
+ ... print(line)
127
+ 0 1
128
+ 2 1 3
129
+ 2 3
130
+ """
131
+ try:
132
+ part0 = [n for n, d in G.nodes.items() if d["bipartite"] == 0]
133
+ except BaseException as err:
134
+ raise AttributeError("Missing node attribute `bipartite`") from err
135
+ if data is True or data is False:
136
+ for n in part0:
137
+ for edge in G.edges(n, data=data):
138
+ yield delimiter.join(map(str, edge))
139
+ else:
140
+ for n in part0:
141
+ for u, v, d in G.edges(n, data=True):
142
+ edge = [u, v]
143
+ try:
144
+ edge.extend(d[k] for k in data)
145
+ except KeyError:
146
+ pass # missing data for this edge, should warn?
147
+ yield delimiter.join(map(str, edge))
148
+
149
+
150
+ @nx._dispatchable(name="bipartite_parse_edgelist", graphs=None, returns_graph=True)
151
+ def parse_edgelist(
152
+ lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True
153
+ ):
154
+ """Parse lines of an edge list representation of a bipartite graph.
155
+
156
+ Parameters
157
+ ----------
158
+ lines : list or iterator of strings
159
+ Input data in edgelist format
160
+ comments : string, optional
161
+ Marker for comment lines
162
+ delimiter : string, optional
163
+ Separator for node labels
164
+ create_using: NetworkX graph container, optional
165
+ Use given NetworkX graph for holding nodes or edges.
166
+ nodetype : Python type, optional
167
+ Convert nodes to this type.
168
+ data : bool or list of (label,type) tuples
169
+ If False generate no edge data or if True use a dictionary
170
+ representation of edge data or a list tuples specifying dictionary
171
+ key names and types for edge data.
172
+
173
+ Returns
174
+ -------
175
+ G: NetworkX Graph
176
+ The bipartite graph corresponding to lines
177
+
178
+ Examples
179
+ --------
180
+ Edgelist with no data:
181
+
182
+ >>> from networkx.algorithms import bipartite
183
+ >>> lines = ["1 2", "2 3", "3 4"]
184
+ >>> G = bipartite.parse_edgelist(lines, nodetype=int)
185
+ >>> sorted(G.nodes())
186
+ [1, 2, 3, 4]
187
+ >>> sorted(G.nodes(data=True))
188
+ [(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {'bipartite': 1})]
189
+ >>> sorted(G.edges())
190
+ [(1, 2), (2, 3), (3, 4)]
191
+
192
+ Edgelist with data in Python dictionary representation:
193
+
194
+ >>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"]
195
+ >>> G = bipartite.parse_edgelist(lines, nodetype=int)
196
+ >>> sorted(G.nodes())
197
+ [1, 2, 3, 4]
198
+ >>> sorted(G.edges(data=True))
199
+ [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
200
+
201
+ Edgelist with data in a list:
202
+
203
+ >>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]
204
+ >>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
205
+ >>> sorted(G.nodes())
206
+ [1, 2, 3, 4]
207
+ >>> sorted(G.edges(data=True))
208
+ [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
209
+
210
+ See Also
211
+ --------
212
+ """
213
+ from ast import literal_eval
214
+
215
+ G = nx.empty_graph(0, create_using)
216
+ for line in lines:
217
+ p = line.find(comments)
218
+ if p >= 0:
219
+ line = line[:p]
220
+ if not len(line):
221
+ continue
222
+ # split line, should have 2 or more
223
+ s = line.rstrip("\n").split(delimiter)
224
+ if len(s) < 2:
225
+ continue
226
+ u = s.pop(0)
227
+ v = s.pop(0)
228
+ d = s
229
+ if nodetype is not None:
230
+ try:
231
+ u = nodetype(u)
232
+ v = nodetype(v)
233
+ except BaseException as err:
234
+ raise TypeError(
235
+ f"Failed to convert nodes {u},{v} to type {nodetype}."
236
+ ) from err
237
+
238
+ if len(d) == 0 or data is False:
239
+ # no data or data type specified
240
+ edgedata = {}
241
+ elif data is True:
242
+ # no edge types specified
243
+ try: # try to evaluate as dictionary
244
+ edgedata = dict(literal_eval(" ".join(d)))
245
+ except BaseException as err:
246
+ raise TypeError(
247
+ f"Failed to convert edge data ({d}) to dictionary."
248
+ ) from err
249
+ else:
250
+ # convert edge data to dictionary with specified keys and type
251
+ if len(d) != len(data):
252
+ raise IndexError(
253
+ f"Edge data {d} and data_keys {data} are not the same length"
254
+ )
255
+ edgedata = {}
256
+ for (edge_key, edge_type), edge_value in zip(data, d):
257
+ try:
258
+ edge_value = edge_type(edge_value)
259
+ except BaseException as err:
260
+ raise TypeError(
261
+ f"Failed to convert {edge_key} data "
262
+ f"{edge_value} to type {edge_type}."
263
+ ) from err
264
+ edgedata.update({edge_key: edge_value})
265
+ G.add_node(u, bipartite=0)
266
+ G.add_node(v, bipartite=1)
267
+ G.add_edge(u, v, **edgedata)
268
+ return G
269
+
270
+
271
+ @open_file(0, mode="rb")
272
+ @nx._dispatchable(name="bipartite_read_edgelist", graphs=None, returns_graph=True)
273
+ def read_edgelist(
274
+ path,
275
+ comments="#",
276
+ delimiter=None,
277
+ create_using=None,
278
+ nodetype=None,
279
+ data=True,
280
+ edgetype=None,
281
+ encoding="utf-8",
282
+ ):
283
+ """Read a bipartite graph from a list of edges.
284
+
285
+ Parameters
286
+ ----------
287
+ path : file or string
288
+ File or filename to read. If a file is provided, it must be
289
+ opened in 'rb' mode.
290
+ Filenames ending in .gz or .bz2 will be uncompressed.
291
+ comments : string, optional
292
+ The character used to indicate the start of a comment.
293
+ delimiter : string, optional
294
+ The string used to separate values. The default is whitespace.
295
+ create_using : Graph container, optional,
296
+ Use specified container to build graph. The default is networkx.Graph,
297
+ an undirected graph.
298
+ nodetype : int, float, str, Python type, optional
299
+ Convert node data from strings to specified type
300
+ data : bool or list of (label,type) tuples
301
+ Tuples specifying dictionary key names and types for edge data
302
+ edgetype : int, float, str, Python type, optional OBSOLETE
303
+ Convert edge data from strings to specified type and use as 'weight'
304
+ encoding: string, optional
305
+ Specify which encoding to use when reading file.
306
+
307
+ Returns
308
+ -------
309
+ G : graph
310
+ A networkx Graph or other type specified with create_using
311
+
312
+ Examples
313
+ --------
314
+ >>> from networkx.algorithms import bipartite
315
+ >>> G = nx.path_graph(4)
316
+ >>> G.add_nodes_from([0, 2], bipartite=0)
317
+ >>> G.add_nodes_from([1, 3], bipartite=1)
318
+ >>> bipartite.write_edgelist(G, "test.edgelist")
319
+ >>> G = bipartite.read_edgelist("test.edgelist")
320
+
321
+ >>> fh = open("test.edgelist", "rb")
322
+ >>> G = bipartite.read_edgelist(fh)
323
+ >>> fh.close()
324
+
325
+ >>> G = bipartite.read_edgelist("test.edgelist", nodetype=int)
326
+
327
+ Edgelist with data in a list:
328
+
329
+ >>> textline = "1 2 3"
330
+ >>> fh = open("test.edgelist", "w")
331
+ >>> d = fh.write(textline)
332
+ >>> fh.close()
333
+ >>> G = bipartite.read_edgelist(
334
+ ... "test.edgelist", nodetype=int, data=(("weight", float),)
335
+ ... )
336
+ >>> list(G)
337
+ [1, 2]
338
+ >>> list(G.edges(data=True))
339
+ [(1, 2, {'weight': 3.0})]
340
+
341
+ See parse_edgelist() for more examples of formatting.
342
+
343
+ See Also
344
+ --------
345
+ parse_edgelist
346
+
347
+ Notes
348
+ -----
349
+ Since nodes must be hashable, the function nodetype must return hashable
350
+ types (e.g. int, float, str, frozenset - or tuples of those, etc.)
351
+ """
352
+ lines = (line.decode(encoding) for line in path)
353
+ return parse_edgelist(
354
+ lines,
355
+ comments=comments,
356
+ delimiter=delimiter,
357
+ create_using=create_using,
358
+ nodetype=nodetype,
359
+ data=data,
360
+ )
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/extendability.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides a function for computing the extendability of a graph which is
2
+ undirected, simple, connected and bipartite and contains at least one perfect matching."""
3
+
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = ["maximal_extendability"]
8
+
9
+
10
+ @not_implemented_for("directed")
11
+ @not_implemented_for("multigraph")
12
+ @nx._dispatchable
13
+ def maximal_extendability(G):
14
+ """Computes the extendability of a graph.
15
+
16
+ The extendability of a graph is defined as the maximum $k$ for which `G`
17
+ is $k$-extendable. Graph `G` is $k$-extendable if and only if `G` has a
18
+ perfect matching and every set of $k$ independent edges can be extended
19
+ to a perfect matching in `G`.
20
+
21
+ Parameters
22
+ ----------
23
+ G : NetworkX Graph
24
+ A fully-connected bipartite graph without self-loops
25
+
26
+ Returns
27
+ -------
28
+ extendability : int
29
+
30
+ Raises
31
+ ------
32
+ NetworkXError
33
+ If the graph `G` is disconnected.
34
+ If the graph `G` is not bipartite.
35
+ If the graph `G` does not contain a perfect matching.
36
+ If the residual graph of `G` is not strongly connected.
37
+
38
+ Notes
39
+ -----
40
+ Definition:
41
+ Let `G` be a simple, connected, undirected and bipartite graph with a perfect
42
+ matching M and bipartition (U,V). The residual graph of `G`, denoted by $G_M$,
43
+ is the graph obtained from G by directing the edges of M from V to U and the
44
+ edges that do not belong to M from U to V.
45
+
46
+ Lemma [1]_ :
47
+ Let M be a perfect matching of `G`. `G` is $k$-extendable if and only if its residual
48
+ graph $G_M$ is strongly connected and there are $k$ vertex-disjoint directed
49
+ paths between every vertex of U and every vertex of V.
50
+
51
+ Assuming that input graph `G` is undirected, simple, connected, bipartite and contains
52
+ a perfect matching M, this function constructs the residual graph $G_M$ of G and
53
+ returns the minimum value among the maximum vertex-disjoint directed paths between
54
+ every vertex of U and every vertex of V in $G_M$. By combining the definitions
55
+ and the lemma, this value represents the extendability of the graph `G`.
56
+
57
+ Time complexity O($n^3$ $m^2$)) where $n$ is the number of vertices
58
+ and $m$ is the number of edges.
59
+
60
+ References
61
+ ----------
62
+ .. [1] "A polynomial algorithm for the extendability problem in bipartite graphs",
63
+ J. Lakhal, L. Litzler, Information Processing Letters, 1998.
64
+ .. [2] "On n-extendible graphs", M. D. Plummer, Discrete Mathematics, 31:201–210, 1980
65
+ https://doi.org/10.1016/0012-365X(80)90037-0
66
+
67
+ """
68
+ if not nx.is_connected(G):
69
+ raise nx.NetworkXError("Graph G is not connected")
70
+
71
+ if not nx.bipartite.is_bipartite(G):
72
+ raise nx.NetworkXError("Graph G is not bipartite")
73
+
74
+ U, V = nx.bipartite.sets(G)
75
+
76
+ maximum_matching = nx.bipartite.hopcroft_karp_matching(G)
77
+
78
+ if not nx.is_perfect_matching(G, maximum_matching):
79
+ raise nx.NetworkXError("Graph G does not contain a perfect matching")
80
+
81
+ # list of edges in perfect matching, directed from V to U
82
+ pm = [(node, maximum_matching[node]) for node in V & maximum_matching.keys()]
83
+
84
+ # Direct all the edges of G, from V to U if in matching, else from U to V
85
+ directed_edges = [
86
+ (x, y) if (x in V and (x, y) in pm) or (x in U and (y, x) not in pm) else (y, x)
87
+ for x, y in G.edges
88
+ ]
89
+
90
+ # Construct the residual graph of G
91
+ residual_G = nx.DiGraph()
92
+ residual_G.add_nodes_from(G)
93
+ residual_G.add_edges_from(directed_edges)
94
+
95
+ if not nx.is_strongly_connected(residual_G):
96
+ raise nx.NetworkXError("The residual graph of G is not strongly connected")
97
+
98
+ # For node-pairs between V & U, keep min of max number of node-disjoint paths
99
+ # Variable $k$ stands for the extendability of graph G
100
+ k = float("inf")
101
+ for u in U:
102
+ for v in V:
103
+ num_paths = sum(1 for _ in nx.node_disjoint_paths(residual_G, u, v))
104
+ k = k if k < num_paths else num_paths
105
+ return k
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/matrix.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ====================
3
+ Biadjacency matrices
4
+ ====================
5
+ """
6
+
7
+ import itertools
8
+
9
+ import networkx as nx
10
+ from networkx.convert_matrix import _generate_weighted_edges
11
+
12
+ __all__ = ["biadjacency_matrix", "from_biadjacency_matrix"]
13
+
14
+
15
+ @nx._dispatchable(edge_attrs="weight")
16
+ def biadjacency_matrix(
17
+ G, row_order, column_order=None, dtype=None, weight="weight", format="csr"
18
+ ):
19
+ r"""Returns the biadjacency matrix of the bipartite graph G.
20
+
21
+ Let `G = (U, V, E)` be a bipartite graph with node sets
22
+ `U = u_{1},...,u_{r}` and `V = v_{1},...,v_{s}`. The biadjacency
23
+ matrix [1]_ is the `r` x `s` matrix `B` in which `b_{i,j} = 1`
24
+ if, and only if, `(u_i, v_j) \in E`. If the parameter `weight` is
25
+ not `None` and matches the name of an edge attribute, its value is
26
+ used instead of 1.
27
+
28
+ Parameters
29
+ ----------
30
+ G : graph
31
+ A NetworkX graph
32
+
33
+ row_order : list of nodes
34
+ The rows of the matrix are ordered according to the list of nodes.
35
+
36
+ column_order : list, optional
37
+ The columns of the matrix are ordered according to the list of nodes.
38
+ If column_order is None, then the ordering of columns is arbitrary.
39
+
40
+ dtype : NumPy data-type, optional
41
+ A valid NumPy dtype used to initialize the array. If None, then the
42
+ NumPy default is used.
43
+
44
+ weight : string or None, optional (default='weight')
45
+ The edge data key used to provide each value in the matrix.
46
+ If None, then each edge has weight 1.
47
+
48
+ format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
49
+ The type of the matrix to be returned (default 'csr'). For
50
+ some algorithms different implementations of sparse matrices
51
+ can perform better. See [2]_ for details.
52
+
53
+ Returns
54
+ -------
55
+ M : SciPy sparse array
56
+ Biadjacency matrix representation of the bipartite graph G.
57
+
58
+ Notes
59
+ -----
60
+ No attempt is made to check that the input graph is bipartite.
61
+
62
+ For directed bipartite graphs only successors are considered as neighbors.
63
+ To obtain an adjacency matrix with ones (or weight values) for both
64
+ predecessors and successors you have to generate two biadjacency matrices
65
+ where the rows of one of them are the columns of the other, and then add
66
+ one to the transpose of the other.
67
+
68
+ See Also
69
+ --------
70
+ adjacency_matrix
71
+ from_biadjacency_matrix
72
+
73
+ References
74
+ ----------
75
+ .. [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
76
+ .. [2] Scipy Dev. References, "Sparse Matrices",
77
+ https://docs.scipy.org/doc/scipy/reference/sparse.html
78
+ """
79
+ import scipy as sp
80
+
81
+ nlen = len(row_order)
82
+ if nlen == 0:
83
+ raise nx.NetworkXError("row_order is empty list")
84
+ if len(row_order) != len(set(row_order)):
85
+ msg = "Ambiguous ordering: `row_order` contained duplicates."
86
+ raise nx.NetworkXError(msg)
87
+ if column_order is None:
88
+ column_order = list(set(G) - set(row_order))
89
+ mlen = len(column_order)
90
+ if len(column_order) != len(set(column_order)):
91
+ msg = "Ambiguous ordering: `column_order` contained duplicates."
92
+ raise nx.NetworkXError(msg)
93
+
94
+ row_index = dict(zip(row_order, itertools.count()))
95
+ col_index = dict(zip(column_order, itertools.count()))
96
+
97
+ if G.number_of_edges() == 0:
98
+ row, col, data = [], [], []
99
+ else:
100
+ row, col, data = zip(
101
+ *(
102
+ (row_index[u], col_index[v], d.get(weight, 1))
103
+ for u, v, d in G.edges(row_order, data=True)
104
+ if u in row_index and v in col_index
105
+ )
106
+ )
107
+ A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, mlen), dtype=dtype)
108
+ try:
109
+ return A.asformat(format)
110
+ except ValueError as err:
111
+ raise nx.NetworkXError(f"Unknown sparse array format: {format}") from err
112
+
113
+
114
+ @nx._dispatchable(graphs=None, returns_graph=True)
115
+ def from_biadjacency_matrix(A, create_using=None, edge_attribute="weight"):
116
+ r"""Creates a new bipartite graph from a biadjacency matrix given as a
117
+ SciPy sparse array.
118
+
119
+ Parameters
120
+ ----------
121
+ A: scipy sparse array
122
+ A biadjacency matrix representation of a graph
123
+
124
+ create_using: NetworkX graph
125
+ Use specified graph for result. The default is Graph()
126
+
127
+ edge_attribute: string
128
+ Name of edge attribute to store matrix numeric value. The data will
129
+ have the same type as the matrix entry (int, float, (real,imag)).
130
+
131
+ Notes
132
+ -----
133
+ The nodes are labeled with the attribute `bipartite` set to an integer
134
+ 0 or 1 representing membership in part 0 or part 1 of the bipartite graph.
135
+
136
+ If `create_using` is an instance of :class:`networkx.MultiGraph` or
137
+ :class:`networkx.MultiDiGraph` and the entries of `A` are of
138
+ type :class:`int`, then this function returns a multigraph (of the same
139
+ type as `create_using`) with parallel edges. In this case, `edge_attribute`
140
+ will be ignored.
141
+
142
+ See Also
143
+ --------
144
+ biadjacency_matrix
145
+ from_numpy_array
146
+
147
+ References
148
+ ----------
149
+ [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
150
+ """
151
+ G = nx.empty_graph(0, create_using)
152
+ n, m = A.shape
153
+ # Make sure we get even the isolated nodes of the graph.
154
+ G.add_nodes_from(range(n), bipartite=0)
155
+ G.add_nodes_from(range(n, n + m), bipartite=1)
156
+ # Create an iterable over (u, v, w) triples and for each triple, add an
157
+ # edge from u to v with weight w.
158
+ triples = ((u, n + v, d) for (u, v, d) in _generate_weighted_edges(A))
159
+ # If the entries in the adjacency matrix are integers and the graph is a
160
+ # multigraph, then create parallel edges, each with weight 1, for each
161
+ # entry in the adjacency matrix. Otherwise, create one edge for each
162
+ # positive entry in the adjacency matrix and set the weight of that edge to
163
+ # be the entry in the matrix.
164
+ if A.dtype.kind in ("i", "u") and G.is_multigraph():
165
+ chain = itertools.chain.from_iterable
166
+ triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
167
+ G.add_weighted_edges_from(triples, weight=edge_attribute)
168
+ return G
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/projection.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One-mode (unipartite) projections of bipartite graphs."""
2
+
3
+ import networkx as nx
4
+ from networkx.exception import NetworkXAlgorithmError
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = [
8
+ "projected_graph",
9
+ "weighted_projected_graph",
10
+ "collaboration_weighted_projected_graph",
11
+ "overlap_weighted_projected_graph",
12
+ "generic_weighted_projected_graph",
13
+ ]
14
+
15
+
16
+ @nx._dispatchable(
17
+ graphs="B", preserve_node_attrs=True, preserve_graph_attrs=True, returns_graph=True
18
+ )
19
+ def projected_graph(B, nodes, multigraph=False):
20
+ r"""Returns the projection of B onto one of its node sets.
21
+
22
+ Returns the graph G that is the projection of the bipartite graph B
23
+ onto the specified nodes. They retain their attributes and are connected
24
+ in G if they have a common neighbor in B.
25
+
26
+ Parameters
27
+ ----------
28
+ B : NetworkX graph
29
+ The input graph should be bipartite.
30
+
31
+ nodes : list or iterable
32
+ Nodes to project onto (the "bottom" nodes).
33
+
34
+ multigraph: bool (default=False)
35
+ If True return a multigraph where the multiple edges represent multiple
36
+ shared neighbors. They edge key in the multigraph is assigned to the
37
+ label of the neighbor.
38
+
39
+ Returns
40
+ -------
41
+ Graph : NetworkX graph or multigraph
42
+ A graph that is the projection onto the given nodes.
43
+
44
+ Examples
45
+ --------
46
+ >>> from networkx.algorithms import bipartite
47
+ >>> B = nx.path_graph(4)
48
+ >>> G = bipartite.projected_graph(B, [1, 3])
49
+ >>> list(G)
50
+ [1, 3]
51
+ >>> list(G.edges())
52
+ [(1, 3)]
53
+
54
+ If nodes `a`, and `b` are connected through both nodes 1 and 2 then
55
+ building a multigraph results in two edges in the projection onto
56
+ [`a`, `b`]:
57
+
58
+ >>> B = nx.Graph()
59
+ >>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
60
+ >>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
61
+ >>> print([sorted((u, v)) for u, v in G.edges()])
62
+ [['a', 'b'], ['a', 'b']]
63
+
64
+ Notes
65
+ -----
66
+ No attempt is made to verify that the input graph B is bipartite.
67
+ Returns a simple graph that is the projection of the bipartite graph B
68
+ onto the set of nodes given in list nodes. If multigraph=True then
69
+ a multigraph is returned with an edge for every shared neighbor.
70
+
71
+ Directed graphs are allowed as input. The output will also then
72
+ be a directed graph with edges if there is a directed path between
73
+ the nodes.
74
+
75
+ The graph and node properties are (shallow) copied to the projected graph.
76
+
77
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
78
+ for further details on how bipartite graphs are handled in NetworkX.
79
+
80
+ See Also
81
+ --------
82
+ is_bipartite,
83
+ is_bipartite_node_set,
84
+ sets,
85
+ weighted_projected_graph,
86
+ collaboration_weighted_projected_graph,
87
+ overlap_weighted_projected_graph,
88
+ generic_weighted_projected_graph
89
+ """
90
+ if B.is_multigraph():
91
+ raise nx.NetworkXError("not defined for multigraphs")
92
+ if B.is_directed():
93
+ directed = True
94
+ if multigraph:
95
+ G = nx.MultiDiGraph()
96
+ else:
97
+ G = nx.DiGraph()
98
+ else:
99
+ directed = False
100
+ if multigraph:
101
+ G = nx.MultiGraph()
102
+ else:
103
+ G = nx.Graph()
104
+ G.graph.update(B.graph)
105
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
106
+ for u in nodes:
107
+ nbrs2 = {v for nbr in B[u] for v in B[nbr] if v != u}
108
+ if multigraph:
109
+ for n in nbrs2:
110
+ if directed:
111
+ links = set(B[u]) & set(B.pred[n])
112
+ else:
113
+ links = set(B[u]) & set(B[n])
114
+ for l in links:
115
+ if not G.has_edge(u, n, l):
116
+ G.add_edge(u, n, key=l)
117
+ else:
118
+ G.add_edges_from((u, n) for n in nbrs2)
119
+ return G
120
+
121
+
122
+ @not_implemented_for("multigraph")
123
+ @nx._dispatchable(graphs="B", returns_graph=True)
124
+ def weighted_projected_graph(B, nodes, ratio=False):
125
+ r"""Returns a weighted projection of B onto one of its node sets.
126
+
127
+ The weighted projected graph is the projection of the bipartite
128
+ network B onto the specified nodes with weights representing the
129
+ number of shared neighbors or the ratio between actual shared
130
+ neighbors and possible shared neighbors if ``ratio is True`` [1]_.
131
+ The nodes retain their attributes and are connected in the resulting
132
+ graph if they have an edge to a common node in the original graph.
133
+
134
+ Parameters
135
+ ----------
136
+ B : NetworkX graph
137
+ The input graph should be bipartite.
138
+
139
+ nodes : list or iterable
140
+ Distinct nodes to project onto (the "bottom" nodes).
141
+
142
+ ratio: Bool (default=False)
143
+ If True, edge weight is the ratio between actual shared neighbors
144
+ and maximum possible shared neighbors (i.e., the size of the other
145
+ node set). If False, edges weight is the number of shared neighbors.
146
+
147
+ Returns
148
+ -------
149
+ Graph : NetworkX graph
150
+ A graph that is the projection onto the given nodes.
151
+
152
+ Examples
153
+ --------
154
+ >>> from networkx.algorithms import bipartite
155
+ >>> B = nx.path_graph(4)
156
+ >>> G = bipartite.weighted_projected_graph(B, [1, 3])
157
+ >>> list(G)
158
+ [1, 3]
159
+ >>> list(G.edges(data=True))
160
+ [(1, 3, {'weight': 1})]
161
+ >>> G = bipartite.weighted_projected_graph(B, [1, 3], ratio=True)
162
+ >>> list(G.edges(data=True))
163
+ [(1, 3, {'weight': 0.5})]
164
+
165
+ Notes
166
+ -----
167
+ No attempt is made to verify that the input graph B is bipartite, or that
168
+ the input nodes are distinct. However, if the length of the input nodes is
169
+ greater than or equal to the nodes in the graph B, an exception is raised.
170
+ If the nodes are not distinct but don't raise this error, the output weights
171
+ will be incorrect.
172
+ The graph and node properties are (shallow) copied to the projected graph.
173
+
174
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
175
+ for further details on how bipartite graphs are handled in NetworkX.
176
+
177
+ See Also
178
+ --------
179
+ is_bipartite,
180
+ is_bipartite_node_set,
181
+ sets,
182
+ collaboration_weighted_projected_graph,
183
+ overlap_weighted_projected_graph,
184
+ generic_weighted_projected_graph
185
+ projected_graph
186
+
187
+ References
188
+ ----------
189
+ .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
190
+ Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
191
+ of Social Network Analysis. Sage Publications.
192
+ """
193
+ if B.is_directed():
194
+ pred = B.pred
195
+ G = nx.DiGraph()
196
+ else:
197
+ pred = B.adj
198
+ G = nx.Graph()
199
+ G.graph.update(B.graph)
200
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
201
+ n_top = len(B) - len(nodes)
202
+
203
+ if n_top < 1:
204
+ raise NetworkXAlgorithmError(
205
+ f"the size of the nodes to project onto ({len(nodes)}) is >= the graph size ({len(B)}).\n"
206
+ "They are either not a valid bipartite partition or contain duplicates"
207
+ )
208
+
209
+ for u in nodes:
210
+ unbrs = set(B[u])
211
+ nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
212
+ for v in nbrs2:
213
+ vnbrs = set(pred[v])
214
+ common = unbrs & vnbrs
215
+ if not ratio:
216
+ weight = len(common)
217
+ else:
218
+ weight = len(common) / n_top
219
+ G.add_edge(u, v, weight=weight)
220
+ return G
221
+
222
+
223
+ @not_implemented_for("multigraph")
224
+ @nx._dispatchable(graphs="B", returns_graph=True)
225
+ def collaboration_weighted_projected_graph(B, nodes):
226
+ r"""Newman's weighted projection of B onto one of its node sets.
227
+
228
+ The collaboration weighted projection is the projection of the
229
+ bipartite network B onto the specified nodes with weights assigned
230
+ using Newman's collaboration model [1]_:
231
+
232
+ .. math::
233
+
234
+ w_{u, v} = \sum_k \frac{\delta_{u}^{k} \delta_{v}^{k}}{d_k - 1}
235
+
236
+ where `u` and `v` are nodes from the bottom bipartite node set,
237
+ and `k` is a node of the top node set.
238
+ The value `d_k` is the degree of node `k` in the bipartite
239
+ network and `\delta_{u}^{k}` is 1 if node `u` is
240
+ linked to node `k` in the original bipartite graph or 0 otherwise.
241
+
242
+ The nodes retain their attributes and are connected in the resulting
243
+ graph if have an edge to a common node in the original bipartite
244
+ graph.
245
+
246
+ Parameters
247
+ ----------
248
+ B : NetworkX graph
249
+ The input graph should be bipartite.
250
+
251
+ nodes : list or iterable
252
+ Nodes to project onto (the "bottom" nodes).
253
+
254
+ Returns
255
+ -------
256
+ Graph : NetworkX graph
257
+ A graph that is the projection onto the given nodes.
258
+
259
+ Examples
260
+ --------
261
+ >>> from networkx.algorithms import bipartite
262
+ >>> B = nx.path_graph(5)
263
+ >>> B.add_edge(1, 5)
264
+ >>> G = bipartite.collaboration_weighted_projected_graph(B, [0, 2, 4, 5])
265
+ >>> list(G)
266
+ [0, 2, 4, 5]
267
+ >>> for edge in sorted(G.edges(data=True)):
268
+ ... print(edge)
269
+ (0, 2, {'weight': 0.5})
270
+ (0, 5, {'weight': 0.5})
271
+ (2, 4, {'weight': 1.0})
272
+ (2, 5, {'weight': 0.5})
273
+
274
+ Notes
275
+ -----
276
+ No attempt is made to verify that the input graph B is bipartite.
277
+ The graph and node properties are (shallow) copied to the projected graph.
278
+
279
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
280
+ for further details on how bipartite graphs are handled in NetworkX.
281
+
282
+ See Also
283
+ --------
284
+ is_bipartite,
285
+ is_bipartite_node_set,
286
+ sets,
287
+ weighted_projected_graph,
288
+ overlap_weighted_projected_graph,
289
+ generic_weighted_projected_graph,
290
+ projected_graph
291
+
292
+ References
293
+ ----------
294
+ .. [1] Scientific collaboration networks: II.
295
+ Shortest paths, weighted networks, and centrality,
296
+ M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).
297
+ """
298
+ if B.is_directed():
299
+ pred = B.pred
300
+ G = nx.DiGraph()
301
+ else:
302
+ pred = B.adj
303
+ G = nx.Graph()
304
+ G.graph.update(B.graph)
305
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
306
+ for u in nodes:
307
+ unbrs = set(B[u])
308
+ nbrs2 = {n for nbr in unbrs for n in B[nbr] if n != u}
309
+ for v in nbrs2:
310
+ vnbrs = set(pred[v])
311
+ common_degree = (len(B[n]) for n in unbrs & vnbrs)
312
+ weight = sum(1.0 / (deg - 1) for deg in common_degree if deg > 1)
313
+ G.add_edge(u, v, weight=weight)
314
+ return G
315
+
316
+
317
+ @not_implemented_for("multigraph")
318
+ @nx._dispatchable(graphs="B", returns_graph=True)
319
+ def overlap_weighted_projected_graph(B, nodes, jaccard=True):
320
+ r"""Overlap weighted projection of B onto one of its node sets.
321
+
322
+ The overlap weighted projection is the projection of the bipartite
323
+ network B onto the specified nodes with weights representing
324
+ the Jaccard index between the neighborhoods of the two nodes in the
325
+ original bipartite network [1]_:
326
+
327
+ .. math::
328
+
329
+ w_{v, u} = \frac{|N(u) \cap N(v)|}{|N(u) \cup N(v)|}
330
+
331
+ or if the parameter 'jaccard' is False, the fraction of common
332
+ neighbors by minimum of both nodes degree in the original
333
+ bipartite graph [1]_:
334
+
335
+ .. math::
336
+
337
+ w_{v, u} = \frac{|N(u) \cap N(v)|}{min(|N(u)|, |N(v)|)}
338
+
339
+ The nodes retain their attributes and are connected in the resulting
340
+ graph if have an edge to a common node in the original bipartite graph.
341
+
342
+ Parameters
343
+ ----------
344
+ B : NetworkX graph
345
+ The input graph should be bipartite.
346
+
347
+ nodes : list or iterable
348
+ Nodes to project onto (the "bottom" nodes).
349
+
350
+ jaccard: Bool (default=True)
351
+
352
+ Returns
353
+ -------
354
+ Graph : NetworkX graph
355
+ A graph that is the projection onto the given nodes.
356
+
357
+ Examples
358
+ --------
359
+ >>> from networkx.algorithms import bipartite
360
+ >>> B = nx.path_graph(5)
361
+ >>> nodes = [0, 2, 4]
362
+ >>> G = bipartite.overlap_weighted_projected_graph(B, nodes)
363
+ >>> list(G)
364
+ [0, 2, 4]
365
+ >>> list(G.edges(data=True))
366
+ [(0, 2, {'weight': 0.5}), (2, 4, {'weight': 0.5})]
367
+ >>> G = bipartite.overlap_weighted_projected_graph(B, nodes, jaccard=False)
368
+ >>> list(G.edges(data=True))
369
+ [(0, 2, {'weight': 1.0}), (2, 4, {'weight': 1.0})]
370
+
371
+ Notes
372
+ -----
373
+ No attempt is made to verify that the input graph B is bipartite.
374
+ The graph and node properties are (shallow) copied to the projected graph.
375
+
376
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
377
+ for further details on how bipartite graphs are handled in NetworkX.
378
+
379
+ See Also
380
+ --------
381
+ is_bipartite,
382
+ is_bipartite_node_set,
383
+ sets,
384
+ weighted_projected_graph,
385
+ collaboration_weighted_projected_graph,
386
+ generic_weighted_projected_graph,
387
+ projected_graph
388
+
389
+ References
390
+ ----------
391
+ .. [1] Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation
392
+ Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook
393
+ of Social Network Analysis. Sage Publications.
394
+
395
+ """
396
+ if B.is_directed():
397
+ pred = B.pred
398
+ G = nx.DiGraph()
399
+ else:
400
+ pred = B.adj
401
+ G = nx.Graph()
402
+ G.graph.update(B.graph)
403
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
404
+ for u in nodes:
405
+ unbrs = set(B[u])
406
+ nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
407
+ for v in nbrs2:
408
+ vnbrs = set(pred[v])
409
+ if jaccard:
410
+ wt = len(unbrs & vnbrs) / len(unbrs | vnbrs)
411
+ else:
412
+ wt = len(unbrs & vnbrs) / min(len(unbrs), len(vnbrs))
413
+ G.add_edge(u, v, weight=wt)
414
+ return G
415
+
416
+
417
+ @not_implemented_for("multigraph")
418
+ @nx._dispatchable(graphs="B", preserve_all_attrs=True, returns_graph=True)
419
+ def generic_weighted_projected_graph(B, nodes, weight_function=None):
420
+ r"""Weighted projection of B with a user-specified weight function.
421
+
422
+ The bipartite network B is projected on to the specified nodes
423
+ with weights computed by a user-specified function. This function
424
+ must accept as a parameter the neighborhood sets of two nodes and
425
+ return an integer or a float.
426
+
427
+ The nodes retain their attributes and are connected in the resulting graph
428
+ if they have an edge to a common node in the original graph.
429
+
430
+ Parameters
431
+ ----------
432
+ B : NetworkX graph
433
+ The input graph should be bipartite.
434
+
435
+ nodes : list or iterable
436
+ Nodes to project onto (the "bottom" nodes).
437
+
438
+ weight_function : function
439
+ This function must accept as parameters the same input graph
440
+ that this function, and two nodes; and return an integer or a float.
441
+ The default function computes the number of shared neighbors.
442
+
443
+ Returns
444
+ -------
445
+ Graph : NetworkX graph
446
+ A graph that is the projection onto the given nodes.
447
+
448
+ Examples
449
+ --------
450
+ >>> from networkx.algorithms import bipartite
451
+ >>> # Define some custom weight functions
452
+ >>> def jaccard(G, u, v):
453
+ ... unbrs = set(G[u])
454
+ ... vnbrs = set(G[v])
455
+ ... return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs)
456
+ >>> def my_weight(G, u, v, weight="weight"):
457
+ ... w = 0
458
+ ... for nbr in set(G[u]) & set(G[v]):
459
+ ... w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1)
460
+ ... return w
461
+ >>> # A complete bipartite graph with 4 nodes and 4 edges
462
+ >>> B = nx.complete_bipartite_graph(2, 2)
463
+ >>> # Add some arbitrary weight to the edges
464
+ >>> for i, (u, v) in enumerate(B.edges()):
465
+ ... B.edges[u, v]["weight"] = i + 1
466
+ >>> for edge in B.edges(data=True):
467
+ ... print(edge)
468
+ (0, 2, {'weight': 1})
469
+ (0, 3, {'weight': 2})
470
+ (1, 2, {'weight': 3})
471
+ (1, 3, {'weight': 4})
472
+ >>> # By default, the weight is the number of shared neighbors
473
+ >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1])
474
+ >>> print(list(G.edges(data=True)))
475
+ [(0, 1, {'weight': 2})]
476
+ >>> # To specify a custom weight function use the weight_function parameter
477
+ >>> G = bipartite.generic_weighted_projected_graph(
478
+ ... B, [0, 1], weight_function=jaccard
479
+ ... )
480
+ >>> print(list(G.edges(data=True)))
481
+ [(0, 1, {'weight': 1.0})]
482
+ >>> G = bipartite.generic_weighted_projected_graph(
483
+ ... B, [0, 1], weight_function=my_weight
484
+ ... )
485
+ >>> print(list(G.edges(data=True)))
486
+ [(0, 1, {'weight': 10})]
487
+
488
+ Notes
489
+ -----
490
+ No attempt is made to verify that the input graph B is bipartite.
491
+ The graph and node properties are (shallow) copied to the projected graph.
492
+
493
+ See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
494
+ for further details on how bipartite graphs are handled in NetworkX.
495
+
496
+ See Also
497
+ --------
498
+ is_bipartite,
499
+ is_bipartite_node_set,
500
+ sets,
501
+ weighted_projected_graph,
502
+ collaboration_weighted_projected_graph,
503
+ overlap_weighted_projected_graph,
504
+ projected_graph
505
+
506
+ """
507
+ if B.is_directed():
508
+ pred = B.pred
509
+ G = nx.DiGraph()
510
+ else:
511
+ pred = B.adj
512
+ G = nx.Graph()
513
+ if weight_function is None:
514
+
515
+ def weight_function(G, u, v):
516
+ # Notice that we use set(pred[v]) for handling the directed case.
517
+ return len(set(G[u]) & set(pred[v]))
518
+
519
+ G.graph.update(B.graph)
520
+ G.add_nodes_from((n, B.nodes[n]) for n in nodes)
521
+ for u in nodes:
522
+ nbrs2 = {n for nbr in set(B[u]) for n in B[nbr]} - {u}
523
+ for v in nbrs2:
524
+ weight = weight_function(B, u, v)
525
+ G.add_edge(u, v, weight=weight)
526
+ return G
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/spectral.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Spectral bipartivity measure.
3
+ """
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = ["spectral_bipartivity"]
8
+
9
+
10
+ @nx._dispatchable(edge_attrs="weight")
11
+ def spectral_bipartivity(G, nodes=None, weight="weight"):
12
+ """Returns the spectral bipartivity.
13
+
14
+ Parameters
15
+ ----------
16
+ G : NetworkX graph
17
+
18
+ nodes : list or container optional(default is all nodes)
19
+ Nodes to return value of spectral bipartivity contribution.
20
+
21
+ weight : string or None optional (default = 'weight')
22
+ Edge data key to use for edge weights. If None, weights set to 1.
23
+
24
+ Returns
25
+ -------
26
+ sb : float or dict
27
+ A single number if the keyword nodes is not specified, or
28
+ a dictionary keyed by node with the spectral bipartivity contribution
29
+ of that node as the value.
30
+
31
+ Examples
32
+ --------
33
+ >>> from networkx.algorithms import bipartite
34
+ >>> G = nx.path_graph(4)
35
+ >>> bipartite.spectral_bipartivity(G)
36
+ 1.0
37
+
38
+ Notes
39
+ -----
40
+ This implementation uses Numpy (dense) matrices which are not efficient
41
+ for storing large sparse graphs.
42
+
43
+ See Also
44
+ --------
45
+ color
46
+
47
+ References
48
+ ----------
49
+ .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
50
+ bipartivity in complex networks", PhysRev E 72, 046105 (2005)
51
+ """
52
+ import scipy as sp
53
+
54
+ nodelist = list(G) # ordering of nodes in matrix
55
+ A = nx.to_numpy_array(G, nodelist, weight=weight)
56
+ expA = sp.linalg.expm(A)
57
+ expmA = sp.linalg.expm(-A)
58
+ coshA = 0.5 * (expA + expmA)
59
+ if nodes is None:
60
+ # return single number for entire graph
61
+ return float(coshA.diagonal().sum() / expA.diagonal().sum())
62
+ else:
63
+ # contribution for individual nodes
64
+ index = dict(zip(nodelist, range(len(nodelist))))
65
+ sb = {}
66
+ for n in nodes:
67
+ i = index[n]
68
+ sb[n] = coshA.item(i, i) / expA.item(i, i)
69
+ return sb
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_covering.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_extendability.cpython-310.pyc ADDED
Binary file (5.23 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_project.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_spectral_bipartivity.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (577 Bytes). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/isomorph.cpython-310.pyc ADDED
Binary file (7.74 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/isomorphvf2.cpython-310.pyc ADDED
Binary file (28.5 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/isomorphism/__pycache__/vf2userfunc.cpython-310.pyc ADDED
Binary file (6.47 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Subpackages related to graph-minor problems.
3
+
4
+ In graph theory, an undirected graph H is called a minor of the graph G if H
5
+ can be formed from G by deleting edges and vertices and by contracting edges
6
+ [1]_.
7
+
8
+ References
9
+ ----------
10
+ .. [1] https://en.wikipedia.org/wiki/Graph_minor
11
+ """
12
+
13
+ from networkx.algorithms.minors.contraction import (
14
+ contracted_edge,
15
+ contracted_nodes,
16
+ equivalence_classes,
17
+ identified_nodes,
18
+ quotient_graph,
19
+ )
20
+
21
+ __all__ = [
22
+ "contracted_edge",
23
+ "contracted_nodes",
24
+ "equivalence_classes",
25
+ "identified_nodes",
26
+ "quotient_graph",
27
+ ]
llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (687 Bytes). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/__pycache__/contraction.cpython-310.pyc ADDED
Binary file (20.4 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/contraction.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides functions for computing minors of a graph."""
2
+
3
+ from itertools import chain, combinations, permutations, product
4
+
5
+ import networkx as nx
6
+ from networkx import density
7
+ from networkx.exception import NetworkXException
8
+ from networkx.utils import arbitrary_element
9
+
10
+ __all__ = [
11
+ "contracted_edge",
12
+ "contracted_nodes",
13
+ "equivalence_classes",
14
+ "identified_nodes",
15
+ "quotient_graph",
16
+ ]
17
+
18
+ chaini = chain.from_iterable
19
+
20
+
21
+ def equivalence_classes(iterable, relation):
22
+ """Returns equivalence classes of `relation` when applied to `iterable`.
23
+
24
+ The equivalence classes, or blocks, consist of objects from `iterable`
25
+ which are all equivalent. They are defined to be equivalent if the
26
+ `relation` function returns `True` when passed any two objects from that
27
+ class, and `False` otherwise. To define an equivalence relation the
28
+ function must be reflexive, symmetric and transitive.
29
+
30
+ Parameters
31
+ ----------
32
+ iterable : list, tuple, or set
33
+ An iterable of elements/nodes.
34
+
35
+ relation : function
36
+ A Boolean-valued function that implements an equivalence relation
37
+ (reflexive, symmetric, transitive binary relation) on the elements
38
+ of `iterable` - it must take two elements and return `True` if
39
+ they are related, or `False` if not.
40
+
41
+ Returns
42
+ -------
43
+ set of frozensets
44
+ A set of frozensets representing the partition induced by the equivalence
45
+ relation function `relation` on the elements of `iterable`. Each
46
+ member set in the return set represents an equivalence class, or
47
+ block, of the partition.
48
+
49
+ Duplicate elements will be ignored so it makes the most sense for
50
+ `iterable` to be a :class:`set`.
51
+
52
+ Notes
53
+ -----
54
+ This function does not check that `relation` represents an equivalence
55
+ relation. You can check that your equivalence classes provide a partition
56
+ using `is_partition`.
57
+
58
+ Examples
59
+ --------
60
+ Let `X` be the set of integers from `0` to `9`, and consider an equivalence
61
+ relation `R` on `X` of congruence modulo `3`: this means that two integers
62
+ `x` and `y` in `X` are equivalent under `R` if they leave the same
63
+ remainder when divided by `3`, i.e. `(x - y) mod 3 = 0`.
64
+
65
+ The equivalence classes of this relation are `{0, 3, 6, 9}`, `{1, 4, 7}`,
66
+ `{2, 5, 8}`: `0`, `3`, `6`, `9` are all divisible by `3` and leave zero
67
+ remainder; `1`, `4`, `7` leave remainder `1`; while `2`, `5` and `8` leave
68
+ remainder `2`. We can see this by calling `equivalence_classes` with
69
+ `X` and a function implementation of `R`.
70
+
71
+ >>> X = set(range(10))
72
+ >>> def mod3(x, y):
73
+ ... return (x - y) % 3 == 0
74
+ >>> equivalence_classes(X, mod3) # doctest: +SKIP
75
+ {frozenset({1, 4, 7}), frozenset({8, 2, 5}), frozenset({0, 9, 3, 6})}
76
+ """
77
+ # For simplicity of implementation, we initialize the return value as a
78
+ # list of lists, then convert it to a set of sets at the end of the
79
+ # function.
80
+ blocks = []
81
+ # Determine the equivalence class for each element of the iterable.
82
+ for y in iterable:
83
+ # Each element y must be in *exactly one* equivalence class.
84
+ #
85
+ # Each block is guaranteed to be non-empty
86
+ for block in blocks:
87
+ x = arbitrary_element(block)
88
+ if relation(x, y):
89
+ block.append(y)
90
+ break
91
+ else:
92
+ # If the element y is not part of any known equivalence class, it
93
+ # must be in its own, so we create a new singleton equivalence
94
+ # class for it.
95
+ blocks.append([y])
96
+ return {frozenset(block) for block in blocks}
97
+
98
+
99
+ @nx._dispatchable(edge_attrs="weight", returns_graph=True)
100
+ def quotient_graph(
101
+ G,
102
+ partition,
103
+ edge_relation=None,
104
+ node_data=None,
105
+ edge_data=None,
106
+ weight="weight",
107
+ relabel=False,
108
+ create_using=None,
109
+ ):
110
+ """Returns the quotient graph of `G` under the specified equivalence
111
+ relation on nodes.
112
+
113
+ Parameters
114
+ ----------
115
+ G : NetworkX graph
116
+ The graph for which to return the quotient graph with the
117
+ specified node relation.
118
+
119
+ partition : function, or dict or list of lists, tuples or sets
120
+ If a function, this function must represent an equivalence
121
+ relation on the nodes of `G`. It must take two arguments *u*
122
+ and *v* and return True exactly when *u* and *v* are in the
123
+ same equivalence class. The equivalence classes form the nodes
124
+ in the returned graph.
125
+
126
+ If a dict of lists/tuples/sets, the keys can be any meaningful
127
+ block labels, but the values must be the block lists/tuples/sets
128
+ (one list/tuple/set per block), and the blocks must form a valid
129
+ partition of the nodes of the graph. That is, each node must be
130
+ in exactly one block of the partition.
131
+
132
+ If a list of sets, the list must form a valid partition of
133
+ the nodes of the graph. That is, each node must be in exactly
134
+ one block of the partition.
135
+
136
+ edge_relation : Boolean function with two arguments
137
+ This function must represent an edge relation on the *blocks* of
138
+ the `partition` of `G`. It must take two arguments, *B* and *C*,
139
+ each one a set of nodes, and return True exactly when there should be
140
+ an edge joining block *B* to block *C* in the returned graph.
141
+
142
+ If `edge_relation` is not specified, it is assumed to be the
143
+ following relation. Block *B* is related to block *C* if and
144
+ only if some node in *B* is adjacent to some node in *C*,
145
+ according to the edge set of `G`.
146
+
147
+ node_data : function
148
+ This function takes one argument, *B*, a set of nodes in `G`,
149
+ and must return a dictionary representing the node data
150
+ attributes to set on the node representing *B* in the quotient graph.
151
+ If None, the following node attributes will be set:
152
+
153
+ * 'graph', the subgraph of the graph `G` that this block
154
+ represents,
155
+ * 'nnodes', the number of nodes in this block,
156
+ * 'nedges', the number of edges within this block,
157
+ * 'density', the density of the subgraph of `G` that this
158
+ block represents.
159
+
160
+ edge_data : function
161
+ This function takes two arguments, *B* and *C*, each one a set
162
+ of nodes, and must return a dictionary representing the edge
163
+ data attributes to set on the edge joining *B* and *C*, should
164
+ there be an edge joining *B* and *C* in the quotient graph (if
165
+ no such edge occurs in the quotient graph as determined by
166
+ `edge_relation`, then the output of this function is ignored).
167
+
168
+ If the quotient graph would be a multigraph, this function is
169
+ not applied, since the edge data from each edge in the graph
170
+ `G` appears in the edges of the quotient graph.
171
+
172
+ weight : string or None, optional (default="weight")
173
+ The name of an edge attribute that holds the numerical value
174
+ used as a weight. If None then each edge has weight 1.
175
+
176
+ relabel : bool
177
+ If True, relabel the nodes of the quotient graph to be
178
+ nonnegative integers. Otherwise, the nodes are identified with
179
+ :class:`frozenset` instances representing the blocks given in
180
+ `partition`.
181
+
182
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
183
+ Graph type to create. If graph instance, then cleared before populated.
184
+
185
+ Returns
186
+ -------
187
+ NetworkX graph
188
+ The quotient graph of `G` under the equivalence relation
189
+ specified by `partition`. If the partition were given as a
190
+ list of :class:`set` instances and `relabel` is False,
191
+ each node will be a :class:`frozenset` corresponding to the same
192
+ :class:`set`.
193
+
194
+ Raises
195
+ ------
196
+ NetworkXException
197
+ If the given partition is not a valid partition of the nodes of
198
+ `G`.
199
+
200
+ Examples
201
+ --------
202
+ The quotient graph of the complete bipartite graph under the "same
203
+ neighbors" equivalence relation is `K_2`. Under this relation, two nodes
204
+ are equivalent if they are not adjacent but have the same neighbor set.
205
+
206
+ >>> G = nx.complete_bipartite_graph(2, 3)
207
+ >>> same_neighbors = lambda u, v: (u not in G[v] and v not in G[u] and G[u] == G[v])
208
+ >>> Q = nx.quotient_graph(G, same_neighbors)
209
+ >>> K2 = nx.complete_graph(2)
210
+ >>> nx.is_isomorphic(Q, K2)
211
+ True
212
+
213
+ The quotient graph of a directed graph under the "same strongly connected
214
+ component" equivalence relation is the condensation of the graph (see
215
+ :func:`condensation`). This example comes from the Wikipedia article
216
+ *`Strongly connected component`_*.
217
+
218
+ >>> G = nx.DiGraph()
219
+ >>> edges = [
220
+ ... "ab",
221
+ ... "be",
222
+ ... "bf",
223
+ ... "bc",
224
+ ... "cg",
225
+ ... "cd",
226
+ ... "dc",
227
+ ... "dh",
228
+ ... "ea",
229
+ ... "ef",
230
+ ... "fg",
231
+ ... "gf",
232
+ ... "hd",
233
+ ... "hf",
234
+ ... ]
235
+ >>> G.add_edges_from(tuple(x) for x in edges)
236
+ >>> components = list(nx.strongly_connected_components(G))
237
+ >>> sorted(sorted(component) for component in components)
238
+ [['a', 'b', 'e'], ['c', 'd', 'h'], ['f', 'g']]
239
+ >>>
240
+ >>> C = nx.condensation(G, components)
241
+ >>> component_of = C.graph["mapping"]
242
+ >>> same_component = lambda u, v: component_of[u] == component_of[v]
243
+ >>> Q = nx.quotient_graph(G, same_component)
244
+ >>> nx.is_isomorphic(C, Q)
245
+ True
246
+
247
+ Node identification can be represented as the quotient of a graph under the
248
+ equivalence relation that places the two nodes in one block and each other
249
+ node in its own singleton block.
250
+
251
+ >>> K24 = nx.complete_bipartite_graph(2, 4)
252
+ >>> K34 = nx.complete_bipartite_graph(3, 4)
253
+ >>> C = nx.contracted_nodes(K34, 1, 2)
254
+ >>> nodes = {1, 2}
255
+ >>> is_contracted = lambda u, v: u in nodes and v in nodes
256
+ >>> Q = nx.quotient_graph(K34, is_contracted)
257
+ >>> nx.is_isomorphic(Q, C)
258
+ True
259
+ >>> nx.is_isomorphic(Q, K24)
260
+ True
261
+
262
+ The blockmodeling technique described in [1]_ can be implemented as a
263
+ quotient graph.
264
+
265
+ >>> G = nx.path_graph(6)
266
+ >>> partition = [{0, 1}, {2, 3}, {4, 5}]
267
+ >>> M = nx.quotient_graph(G, partition, relabel=True)
268
+ >>> list(M.edges())
269
+ [(0, 1), (1, 2)]
270
+
271
+ Here is the sample example but using partition as a dict of block sets.
272
+
273
+ >>> G = nx.path_graph(6)
274
+ >>> partition = {0: {0, 1}, 2: {2, 3}, 4: {4, 5}}
275
+ >>> M = nx.quotient_graph(G, partition, relabel=True)
276
+ >>> list(M.edges())
277
+ [(0, 1), (1, 2)]
278
+
279
+ Partitions can be represented in various ways:
280
+
281
+ 0. a list/tuple/set of block lists/tuples/sets
282
+ 1. a dict with block labels as keys and blocks lists/tuples/sets as values
283
+ 2. a dict with block lists/tuples/sets as keys and block labels as values
284
+ 3. a function from nodes in the original iterable to block labels
285
+ 4. an equivalence relation function on the target iterable
286
+
287
+ As `quotient_graph` is designed to accept partitions represented as (0), (1) or
288
+ (4) only, the `equivalence_classes` function can be used to get the partitions
289
+ in the right form, in order to call `quotient_graph`.
290
+
291
+ .. _Strongly connected component: https://en.wikipedia.org/wiki/Strongly_connected_component
292
+
293
+ References
294
+ ----------
295
+ .. [1] Patrick Doreian, Vladimir Batagelj, and Anuska Ferligoj.
296
+ *Generalized Blockmodeling*.
297
+ Cambridge University Press, 2004.
298
+
299
+ """
300
+ # If the user provided an equivalence relation as a function to compute
301
+ # the blocks of the partition on the nodes of G induced by the
302
+ # equivalence relation.
303
+ if callable(partition):
304
+ # equivalence_classes always return partition of whole G.
305
+ partition = equivalence_classes(G, partition)
306
+ if not nx.community.is_partition(G, partition):
307
+ raise nx.NetworkXException(
308
+ "Input `partition` is not an equivalence relation for nodes of G"
309
+ )
310
+ return _quotient_graph(
311
+ G,
312
+ partition,
313
+ edge_relation,
314
+ node_data,
315
+ edge_data,
316
+ weight,
317
+ relabel,
318
+ create_using,
319
+ )
320
+
321
+ # If the partition is a dict, it is assumed to be one where the keys are
322
+ # user-defined block labels, and values are block lists, tuples or sets.
323
+ if isinstance(partition, dict):
324
+ partition = list(partition.values())
325
+
326
+ # If the user provided partition as a collection of sets. Then we
327
+ # need to check if partition covers all of G nodes. If the answer
328
+ # is 'No' then we need to prepare suitable subgraph view.
329
+ partition_nodes = set().union(*partition)
330
+ if len(partition_nodes) != len(G):
331
+ G = G.subgraph(partition_nodes)
332
+ # Each node in the graph/subgraph must be in exactly one block.
333
+ if not nx.community.is_partition(G, partition):
334
+ raise NetworkXException("each node must be in exactly one part of `partition`")
335
+ return _quotient_graph(
336
+ G,
337
+ partition,
338
+ edge_relation,
339
+ node_data,
340
+ edge_data,
341
+ weight,
342
+ relabel,
343
+ create_using,
344
+ )
345
+
346
+
347
+ def _quotient_graph(
348
+ G, partition, edge_relation, node_data, edge_data, weight, relabel, create_using
349
+ ):
350
+ """Construct the quotient graph assuming input has been checked"""
351
+ if create_using is None:
352
+ H = G.__class__()
353
+ else:
354
+ H = nx.empty_graph(0, create_using)
355
+ # By default set some basic information about the subgraph that each block
356
+ # represents on the nodes in the quotient graph.
357
+ if node_data is None:
358
+
359
+ def node_data(b):
360
+ S = G.subgraph(b)
361
+ return {
362
+ "graph": S,
363
+ "nnodes": len(S),
364
+ "nedges": S.number_of_edges(),
365
+ "density": density(S),
366
+ }
367
+
368
+ # Each block of the partition becomes a node in the quotient graph.
369
+ partition = [frozenset(b) for b in partition]
370
+ H.add_nodes_from((b, node_data(b)) for b in partition)
371
+ # By default, the edge relation is the relation defined as follows. B is
372
+ # adjacent to C if a node in B is adjacent to a node in C, according to the
373
+ # edge set of G.
374
+ #
375
+ # This is not a particularly efficient implementation of this relation:
376
+ # there are O(n^2) pairs to check and each check may require O(log n) time
377
+ # (to check set membership). This can certainly be parallelized.
378
+ if edge_relation is None:
379
+
380
+ def edge_relation(b, c):
381
+ return any(v in G[u] for u, v in product(b, c))
382
+
383
+ # By default, sum the weights of the edges joining pairs of nodes across
384
+ # blocks to get the weight of the edge joining those two blocks.
385
+ if edge_data is None:
386
+
387
+ def edge_data(b, c):
388
+ edgedata = (
389
+ d
390
+ for u, v, d in G.edges(b | c, data=True)
391
+ if (u in b and v in c) or (u in c and v in b)
392
+ )
393
+ return {"weight": sum(d.get(weight, 1) for d in edgedata)}
394
+
395
+ block_pairs = permutations(H, 2) if H.is_directed() else combinations(H, 2)
396
+ # In a multigraph, add one edge in the quotient graph for each edge
397
+ # in the original graph.
398
+ if H.is_multigraph():
399
+ edges = chaini(
400
+ (
401
+ (b, c, G.get_edge_data(u, v, default={}))
402
+ for u, v in product(b, c)
403
+ if v in G[u]
404
+ )
405
+ for b, c in block_pairs
406
+ if edge_relation(b, c)
407
+ )
408
+ # In a simple graph, apply the edge data function to each pair of
409
+ # blocks to determine the edge data attributes to apply to each edge
410
+ # in the quotient graph.
411
+ else:
412
+ edges = (
413
+ (b, c, edge_data(b, c)) for (b, c) in block_pairs if edge_relation(b, c)
414
+ )
415
+ H.add_edges_from(edges)
416
+ # If requested by the user, relabel the nodes to be integers,
417
+ # numbered in increasing order from zero in the same order as the
418
+ # iteration order of `partition`.
419
+ if relabel:
420
+ # Can't use nx.convert_node_labels_to_integers() here since we
421
+ # want the order of iteration to be the same for backward
422
+ # compatibility with the nx.blockmodel() function.
423
+ labels = {b: i for i, b in enumerate(partition)}
424
+ H = nx.relabel_nodes(H, labels)
425
+ return H
426
+
427
+
428
+ @nx._dispatchable(
429
+ preserve_all_attrs=True, mutates_input={"not copy": 4}, returns_graph=True
430
+ )
431
+ def contracted_nodes(G, u, v, self_loops=True, copy=True):
432
+ """Returns the graph that results from contracting `u` and `v`.
433
+
434
+ Node contraction identifies the two nodes as a single node incident to any
435
+ edge that was incident to the original two nodes.
436
+
437
+ Parameters
438
+ ----------
439
+ G : NetworkX graph
440
+ The graph whose nodes will be contracted.
441
+
442
+ u, v : nodes
443
+ Must be nodes in `G`.
444
+
445
+ self_loops : Boolean
446
+ If this is True, any edges joining `u` and `v` in `G` become
447
+ self-loops on the new node in the returned graph.
448
+
449
+ copy : Boolean
450
+ If this is True (default True), make a copy of
451
+ `G` and return that instead of directly changing `G`.
452
+
453
+
454
+ Returns
455
+ -------
456
+ Networkx graph
457
+ If Copy is True,
458
+ A new graph object of the same type as `G` (leaving `G` unmodified)
459
+ with `u` and `v` identified in a single node. The right node `v`
460
+ will be merged into the node `u`, so only `u` will appear in the
461
+ returned graph.
462
+ If copy is False,
463
+ Modifies `G` with `u` and `v` identified in a single node.
464
+ The right node `v` will be merged into the node `u`, so
465
+ only `u` will appear in the returned graph.
466
+
467
+ Notes
468
+ -----
469
+ For multigraphs, the edge keys for the realigned edges may
470
+ not be the same as the edge keys for the old edges. This is
471
+ natural because edge keys are unique only within each pair of nodes.
472
+
473
+ For non-multigraphs where `u` and `v` are adjacent to a third node
474
+ `w`, the edge (`v`, `w`) will be contracted into the edge (`u`,
475
+ `w`) with its attributes stored into a "contraction" attribute.
476
+
477
+ This function is also available as `identified_nodes`.
478
+
479
+ Examples
480
+ --------
481
+ Contracting two nonadjacent nodes of the cycle graph on four nodes `C_4`
482
+ yields the path graph (ignoring parallel edges):
483
+
484
+ >>> G = nx.cycle_graph(4)
485
+ >>> M = nx.contracted_nodes(G, 1, 3)
486
+ >>> P3 = nx.path_graph(3)
487
+ >>> nx.is_isomorphic(M, P3)
488
+ True
489
+
490
+ >>> G = nx.MultiGraph(P3)
491
+ >>> M = nx.contracted_nodes(G, 0, 2)
492
+ >>> M.edges
493
+ MultiEdgeView([(0, 1, 0), (0, 1, 1)])
494
+
495
+ >>> G = nx.Graph([(1, 2), (2, 2)])
496
+ >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False)
497
+ >>> list(H.nodes())
498
+ [1]
499
+ >>> list(H.edges())
500
+ [(1, 1)]
501
+
502
+ In a ``MultiDiGraph`` with a self loop, the in and out edges will
503
+ be treated separately as edges, so while contracting a node which
504
+ has a self loop the contraction will add multiple edges:
505
+
506
+ >>> G = nx.MultiDiGraph([(1, 2), (2, 2)])
507
+ >>> H = nx.contracted_nodes(G, 1, 2)
508
+ >>> list(H.edges()) # edge 1->2, 2->2, 2<-2 from the original Graph G
509
+ [(1, 1), (1, 1), (1, 1)]
510
+ >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False)
511
+ >>> list(H.edges()) # edge 2->2, 2<-2 from the original Graph G
512
+ [(1, 1), (1, 1)]
513
+
514
+ See Also
515
+ --------
516
+ contracted_edge
517
+ quotient_graph
518
+
519
+ """
520
+ # Copying has significant overhead and can be disabled if needed
521
+ if copy:
522
+ H = G.copy()
523
+ else:
524
+ H = G
525
+
526
+ # edge code uses G.edges(v) instead of G.adj[v] to handle multiedges
527
+ if H.is_directed():
528
+ edges_to_remap = chain(G.in_edges(v, data=True), G.out_edges(v, data=True))
529
+ else:
530
+ edges_to_remap = G.edges(v, data=True)
531
+
532
+ # If the H=G, the generators change as H changes
533
+ # This makes the edges_to_remap independent of H
534
+ if not copy:
535
+ edges_to_remap = list(edges_to_remap)
536
+
537
+ v_data = H.nodes[v]
538
+ H.remove_node(v)
539
+
540
+ for prev_w, prev_x, d in edges_to_remap:
541
+ w = prev_w if prev_w != v else u
542
+ x = prev_x if prev_x != v else u
543
+
544
+ if ({prev_w, prev_x} == {u, v}) and not self_loops:
545
+ continue
546
+
547
+ if not H.has_edge(w, x) or G.is_multigraph():
548
+ H.add_edge(w, x, **d)
549
+ else:
550
+ if "contraction" in H.edges[(w, x)]:
551
+ H.edges[(w, x)]["contraction"][(prev_w, prev_x)] = d
552
+ else:
553
+ H.edges[(w, x)]["contraction"] = {(prev_w, prev_x): d}
554
+
555
+ if "contraction" in H.nodes[u]:
556
+ H.nodes[u]["contraction"][v] = v_data
557
+ else:
558
+ H.nodes[u]["contraction"] = {v: v_data}
559
+ return H
560
+
561
+
562
+ identified_nodes = contracted_nodes
563
+
564
+
565
+ @nx._dispatchable(
566
+ preserve_edge_attrs=True, mutates_input={"not copy": 3}, returns_graph=True
567
+ )
568
+ def contracted_edge(G, edge, self_loops=True, copy=True):
569
+ """Returns the graph that results from contracting the specified edge.
570
+
571
+ Edge contraction identifies the two endpoints of the edge as a single node
572
+ incident to any edge that was incident to the original two nodes. A graph
573
+ that results from edge contraction is called a *minor* of the original
574
+ graph.
575
+
576
+ Parameters
577
+ ----------
578
+ G : NetworkX graph
579
+ The graph whose edge will be contracted.
580
+
581
+ edge : tuple
582
+ Must be a pair of nodes in `G`.
583
+
584
+ self_loops : Boolean
585
+ If this is True, any edges (including `edge`) joining the
586
+ endpoints of `edge` in `G` become self-loops on the new node in the
587
+ returned graph.
588
+
589
+ copy : Boolean (default True)
590
+ If this is True, a the contraction will be performed on a copy of `G`,
591
+ otherwise the contraction will happen in place.
592
+
593
+ Returns
594
+ -------
595
+ Networkx graph
596
+ A new graph object of the same type as `G` (leaving `G` unmodified)
597
+ with endpoints of `edge` identified in a single node. The right node
598
+ of `edge` will be merged into the left one, so only the left one will
599
+ appear in the returned graph.
600
+
601
+ Raises
602
+ ------
603
+ ValueError
604
+ If `edge` is not an edge in `G`.
605
+
606
+ Examples
607
+ --------
608
+ Attempting to contract two nonadjacent nodes yields an error:
609
+
610
+ >>> G = nx.cycle_graph(4)
611
+ >>> nx.contracted_edge(G, (1, 3))
612
+ Traceback (most recent call last):
613
+ ...
614
+ ValueError: Edge (1, 3) does not exist in graph G; cannot contract it
615
+
616
+ Contracting two adjacent nodes in the cycle graph on *n* nodes yields the
617
+ cycle graph on *n - 1* nodes:
618
+
619
+ >>> C5 = nx.cycle_graph(5)
620
+ >>> C4 = nx.cycle_graph(4)
621
+ >>> M = nx.contracted_edge(C5, (0, 1), self_loops=False)
622
+ >>> nx.is_isomorphic(M, C4)
623
+ True
624
+
625
+ See also
626
+ --------
627
+ contracted_nodes
628
+ quotient_graph
629
+
630
+ """
631
+ u, v = edge[:2]
632
+ if not G.has_edge(u, v):
633
+ raise ValueError(f"Edge {edge} does not exist in graph G; cannot contract it")
634
+ return contracted_nodes(G, u, v, self_loops=self_loops, copy=copy)
llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/tests/__pycache__/test_contraction.cpython-310.pyc ADDED
Binary file (13.3 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/minors/tests/test_contraction.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.minors.contraction` module."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import arbitrary_element, edges_equal, nodes_equal
7
+
8
+
9
+ def test_quotient_graph_complete_multipartite():
10
+ """Tests that the quotient graph of the complete *n*-partite graph
11
+ under the "same neighbors" node relation is the complete graph on *n*
12
+ nodes.
13
+
14
+ """
15
+ G = nx.complete_multipartite_graph(2, 3, 4)
16
+ # Two nodes are equivalent if they are not adjacent but have the same
17
+ # neighbor set.
18
+
19
+ def same_neighbors(u, v):
20
+ return u not in G[v] and v not in G[u] and G[u] == G[v]
21
+
22
+ expected = nx.complete_graph(3)
23
+ actual = nx.quotient_graph(G, same_neighbors)
24
+ # It won't take too long to run a graph isomorphism algorithm on such
25
+ # small graphs.
26
+ assert nx.is_isomorphic(expected, actual)
27
+
28
+
29
+ def test_quotient_graph_complete_bipartite():
30
+ """Tests that the quotient graph of the complete bipartite graph under
31
+ the "same neighbors" node relation is `K_2`.
32
+
33
+ """
34
+ G = nx.complete_bipartite_graph(2, 3)
35
+ # Two nodes are equivalent if they are not adjacent but have the same
36
+ # neighbor set.
37
+
38
+ def same_neighbors(u, v):
39
+ return u not in G[v] and v not in G[u] and G[u] == G[v]
40
+
41
+ expected = nx.complete_graph(2)
42
+ actual = nx.quotient_graph(G, same_neighbors)
43
+ # It won't take too long to run a graph isomorphism algorithm on such
44
+ # small graphs.
45
+ assert nx.is_isomorphic(expected, actual)
46
+
47
+
48
+ def test_quotient_graph_edge_relation():
49
+ """Tests for specifying an alternate edge relation for the quotient
50
+ graph.
51
+
52
+ """
53
+ G = nx.path_graph(5)
54
+
55
+ def identity(u, v):
56
+ return u == v
57
+
58
+ def same_parity(b, c):
59
+ return arbitrary_element(b) % 2 == arbitrary_element(c) % 2
60
+
61
+ actual = nx.quotient_graph(G, identity, same_parity)
62
+ expected = nx.Graph()
63
+ expected.add_edges_from([(0, 2), (0, 4), (2, 4)])
64
+ expected.add_edge(1, 3)
65
+ assert nx.is_isomorphic(actual, expected)
66
+
67
+
68
+ def test_condensation_as_quotient():
69
+ """This tests that the condensation of a graph can be viewed as the
70
+ quotient graph under the "in the same connected component" equivalence
71
+ relation.
72
+
73
+ """
74
+ # This example graph comes from the file `test_strongly_connected.py`.
75
+ G = nx.DiGraph()
76
+ G.add_edges_from(
77
+ [
78
+ (1, 2),
79
+ (2, 3),
80
+ (2, 11),
81
+ (2, 12),
82
+ (3, 4),
83
+ (4, 3),
84
+ (4, 5),
85
+ (5, 6),
86
+ (6, 5),
87
+ (6, 7),
88
+ (7, 8),
89
+ (7, 9),
90
+ (7, 10),
91
+ (8, 9),
92
+ (9, 7),
93
+ (10, 6),
94
+ (11, 2),
95
+ (11, 4),
96
+ (11, 6),
97
+ (12, 6),
98
+ (12, 11),
99
+ ]
100
+ )
101
+ scc = list(nx.strongly_connected_components(G))
102
+ C = nx.condensation(G, scc)
103
+ component_of = C.graph["mapping"]
104
+ # Two nodes are equivalent if they are in the same connected component.
105
+
106
+ def same_component(u, v):
107
+ return component_of[u] == component_of[v]
108
+
109
+ Q = nx.quotient_graph(G, same_component)
110
+ assert nx.is_isomorphic(C, Q)
111
+
112
+
113
+ def test_path():
114
+ G = nx.path_graph(6)
115
+ partition = [{0, 1}, {2, 3}, {4, 5}]
116
+ M = nx.quotient_graph(G, partition, relabel=True)
117
+ assert nodes_equal(M, [0, 1, 2])
118
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
119
+ for n in M:
120
+ assert M.nodes[n]["nedges"] == 1
121
+ assert M.nodes[n]["nnodes"] == 2
122
+ assert M.nodes[n]["density"] == 1
123
+
124
+
125
+ def test_path__partition_provided_as_dict_of_lists():
126
+ G = nx.path_graph(6)
127
+ partition = {0: [0, 1], 2: [2, 3], 4: [4, 5]}
128
+ M = nx.quotient_graph(G, partition, relabel=True)
129
+ assert nodes_equal(M, [0, 1, 2])
130
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
131
+ for n in M:
132
+ assert M.nodes[n]["nedges"] == 1
133
+ assert M.nodes[n]["nnodes"] == 2
134
+ assert M.nodes[n]["density"] == 1
135
+
136
+
137
+ def test_path__partition_provided_as_dict_of_tuples():
138
+ G = nx.path_graph(6)
139
+ partition = {0: (0, 1), 2: (2, 3), 4: (4, 5)}
140
+ M = nx.quotient_graph(G, partition, relabel=True)
141
+ assert nodes_equal(M, [0, 1, 2])
142
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
143
+ for n in M:
144
+ assert M.nodes[n]["nedges"] == 1
145
+ assert M.nodes[n]["nnodes"] == 2
146
+ assert M.nodes[n]["density"] == 1
147
+
148
+
149
+ def test_path__partition_provided_as_dict_of_sets():
150
+ G = nx.path_graph(6)
151
+ partition = {0: {0, 1}, 2: {2, 3}, 4: {4, 5}}
152
+ M = nx.quotient_graph(G, partition, relabel=True)
153
+ assert nodes_equal(M, [0, 1, 2])
154
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
155
+ for n in M:
156
+ assert M.nodes[n]["nedges"] == 1
157
+ assert M.nodes[n]["nnodes"] == 2
158
+ assert M.nodes[n]["density"] == 1
159
+
160
+
161
+ def test_multigraph_path():
162
+ G = nx.MultiGraph(nx.path_graph(6))
163
+ partition = [{0, 1}, {2, 3}, {4, 5}]
164
+ M = nx.quotient_graph(G, partition, relabel=True)
165
+ assert nodes_equal(M, [0, 1, 2])
166
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
167
+ for n in M:
168
+ assert M.nodes[n]["nedges"] == 1
169
+ assert M.nodes[n]["nnodes"] == 2
170
+ assert M.nodes[n]["density"] == 1
171
+
172
+
173
+ def test_directed_path():
174
+ G = nx.DiGraph()
175
+ nx.add_path(G, range(6))
176
+ partition = [{0, 1}, {2, 3}, {4, 5}]
177
+ M = nx.quotient_graph(G, partition, relabel=True)
178
+ assert nodes_equal(M, [0, 1, 2])
179
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
180
+ for n in M:
181
+ assert M.nodes[n]["nedges"] == 1
182
+ assert M.nodes[n]["nnodes"] == 2
183
+ assert M.nodes[n]["density"] == 0.5
184
+
185
+
186
+ def test_directed_multigraph_path():
187
+ G = nx.MultiDiGraph()
188
+ nx.add_path(G, range(6))
189
+ partition = [{0, 1}, {2, 3}, {4, 5}]
190
+ M = nx.quotient_graph(G, partition, relabel=True)
191
+ assert nodes_equal(M, [0, 1, 2])
192
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
193
+ for n in M:
194
+ assert M.nodes[n]["nedges"] == 1
195
+ assert M.nodes[n]["nnodes"] == 2
196
+ assert M.nodes[n]["density"] == 0.5
197
+
198
+
199
+ def test_overlapping_blocks():
200
+ with pytest.raises(nx.NetworkXException):
201
+ G = nx.path_graph(6)
202
+ partition = [{0, 1, 2}, {2, 3}, {4, 5}]
203
+ nx.quotient_graph(G, partition)
204
+
205
+
206
+ def test_weighted_path():
207
+ G = nx.path_graph(6)
208
+ for i in range(5):
209
+ G[i][i + 1]["w"] = i + 1
210
+ partition = [{0, 1}, {2, 3}, {4, 5}]
211
+ M = nx.quotient_graph(G, partition, weight="w", relabel=True)
212
+ assert nodes_equal(M, [0, 1, 2])
213
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
214
+ assert M[0][1]["weight"] == 2
215
+ assert M[1][2]["weight"] == 4
216
+ for n in M:
217
+ assert M.nodes[n]["nedges"] == 1
218
+ assert M.nodes[n]["nnodes"] == 2
219
+ assert M.nodes[n]["density"] == 1
220
+
221
+
222
+ def test_barbell():
223
+ G = nx.barbell_graph(3, 0)
224
+ partition = [{0, 1, 2}, {3, 4, 5}]
225
+ M = nx.quotient_graph(G, partition, relabel=True)
226
+ assert nodes_equal(M, [0, 1])
227
+ assert edges_equal(M.edges(), [(0, 1)])
228
+ for n in M:
229
+ assert M.nodes[n]["nedges"] == 3
230
+ assert M.nodes[n]["nnodes"] == 3
231
+ assert M.nodes[n]["density"] == 1
232
+
233
+
234
+ def test_barbell_plus():
235
+ G = nx.barbell_graph(3, 0)
236
+ # Add an extra edge joining the bells.
237
+ G.add_edge(0, 5)
238
+ partition = [{0, 1, 2}, {3, 4, 5}]
239
+ M = nx.quotient_graph(G, partition, relabel=True)
240
+ assert nodes_equal(M, [0, 1])
241
+ assert edges_equal(M.edges(), [(0, 1)])
242
+ assert M[0][1]["weight"] == 2
243
+ for n in M:
244
+ assert M.nodes[n]["nedges"] == 3
245
+ assert M.nodes[n]["nnodes"] == 3
246
+ assert M.nodes[n]["density"] == 1
247
+
248
+
249
+ def test_blockmodel():
250
+ G = nx.path_graph(6)
251
+ partition = [[0, 1], [2, 3], [4, 5]]
252
+ M = nx.quotient_graph(G, partition, relabel=True)
253
+ assert nodes_equal(M.nodes(), [0, 1, 2])
254
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
255
+ for n in M.nodes():
256
+ assert M.nodes[n]["nedges"] == 1
257
+ assert M.nodes[n]["nnodes"] == 2
258
+ assert M.nodes[n]["density"] == 1.0
259
+
260
+
261
+ def test_multigraph_blockmodel():
262
+ G = nx.MultiGraph(nx.path_graph(6))
263
+ partition = [[0, 1], [2, 3], [4, 5]]
264
+ M = nx.quotient_graph(G, partition, create_using=nx.MultiGraph(), relabel=True)
265
+ assert nodes_equal(M.nodes(), [0, 1, 2])
266
+ assert edges_equal(M.edges(), [(0, 1), (1, 2)])
267
+ for n in M.nodes():
268
+ assert M.nodes[n]["nedges"] == 1
269
+ assert M.nodes[n]["nnodes"] == 2
270
+ assert M.nodes[n]["density"] == 1.0
271
+
272
+
273
+ def test_quotient_graph_incomplete_partition():
274
+ G = nx.path_graph(6)
275
+ partition = []
276
+ H = nx.quotient_graph(G, partition, relabel=True)
277
+ assert nodes_equal(H.nodes(), [])
278
+ assert edges_equal(H.edges(), [])
279
+
280
+ partition = [[0, 1], [2, 3], [5]]
281
+ H = nx.quotient_graph(G, partition, relabel=True)
282
+ assert nodes_equal(H.nodes(), [0, 1, 2])
283
+ assert edges_equal(H.edges(), [(0, 1)])
284
+
285
+
286
+ def test_undirected_node_contraction():
287
+ """Tests for node contraction in an undirected graph."""
288
+ G = nx.cycle_graph(4)
289
+ actual = nx.contracted_nodes(G, 0, 1)
290
+ expected = nx.cycle_graph(3)
291
+ expected.add_edge(0, 0)
292
+ assert nx.is_isomorphic(actual, expected)
293
+
294
+
295
+ def test_directed_node_contraction():
296
+ """Tests for node contraction in a directed graph."""
297
+ G = nx.DiGraph(nx.cycle_graph(4))
298
+ actual = nx.contracted_nodes(G, 0, 1)
299
+ expected = nx.DiGraph(nx.cycle_graph(3))
300
+ expected.add_edge(0, 0)
301
+ expected.add_edge(0, 0)
302
+ assert nx.is_isomorphic(actual, expected)
303
+
304
+
305
+ def test_undirected_node_contraction_no_copy():
306
+ """Tests for node contraction in an undirected graph
307
+ by making changes in place."""
308
+ G = nx.cycle_graph(4)
309
+ actual = nx.contracted_nodes(G, 0, 1, copy=False)
310
+ expected = nx.cycle_graph(3)
311
+ expected.add_edge(0, 0)
312
+ assert nx.is_isomorphic(actual, G)
313
+ assert nx.is_isomorphic(actual, expected)
314
+
315
+
316
+ def test_directed_node_contraction_no_copy():
317
+ """Tests for node contraction in a directed graph
318
+ by making changes in place."""
319
+ G = nx.DiGraph(nx.cycle_graph(4))
320
+ actual = nx.contracted_nodes(G, 0, 1, copy=False)
321
+ expected = nx.DiGraph(nx.cycle_graph(3))
322
+ expected.add_edge(0, 0)
323
+ expected.add_edge(0, 0)
324
+ assert nx.is_isomorphic(actual, G)
325
+ assert nx.is_isomorphic(actual, expected)
326
+
327
+
328
+ def test_create_multigraph():
329
+ """Tests that using a MultiGraph creates multiple edges."""
330
+ G = nx.path_graph(3, create_using=nx.MultiGraph())
331
+ G.add_edge(0, 1)
332
+ G.add_edge(0, 0)
333
+ G.add_edge(0, 2)
334
+ actual = nx.contracted_nodes(G, 0, 2)
335
+ expected = nx.MultiGraph()
336
+ expected.add_edge(0, 1)
337
+ expected.add_edge(0, 1)
338
+ expected.add_edge(0, 1)
339
+ expected.add_edge(0, 0)
340
+ expected.add_edge(0, 0)
341
+ assert edges_equal(actual.edges, expected.edges)
342
+
343
+
344
+ def test_multigraph_keys():
345
+ """Tests that multiedge keys are reset in new graph."""
346
+ G = nx.path_graph(3, create_using=nx.MultiGraph())
347
+ G.add_edge(0, 1, 5)
348
+ G.add_edge(0, 0, 0)
349
+ G.add_edge(0, 2, 5)
350
+ actual = nx.contracted_nodes(G, 0, 2)
351
+ expected = nx.MultiGraph()
352
+ expected.add_edge(0, 1, 0)
353
+ expected.add_edge(0, 1, 5)
354
+ expected.add_edge(0, 1, 2) # keyed as 2 b/c 2 edges already in G
355
+ expected.add_edge(0, 0, 0)
356
+ expected.add_edge(0, 0, 1) # this comes from (0, 2, 5)
357
+ assert edges_equal(actual.edges, expected.edges)
358
+
359
+
360
+ def test_node_attributes():
361
+ """Tests that node contraction preserves node attributes."""
362
+ G = nx.cycle_graph(4)
363
+ # Add some data to the two nodes being contracted.
364
+ G.nodes[0]["foo"] = "bar"
365
+ G.nodes[1]["baz"] = "xyzzy"
366
+ actual = nx.contracted_nodes(G, 0, 1)
367
+ # We expect that contracting the nodes 0 and 1 in C_4 yields K_3, but
368
+ # with nodes labeled 0, 2, and 3, and with a -loop on 0.
369
+ expected = nx.complete_graph(3)
370
+ expected = nx.relabel_nodes(expected, {1: 2, 2: 3})
371
+ expected.add_edge(0, 0)
372
+ cdict = {1: {"baz": "xyzzy"}}
373
+ expected.nodes[0].update({"foo": "bar", "contraction": cdict})
374
+ assert nx.is_isomorphic(actual, expected)
375
+ assert actual.nodes == expected.nodes
376
+
377
+
378
+ def test_edge_attributes():
379
+ """Tests that node contraction preserves edge attributes."""
380
+ # Shape: src1 --> dest <-- src2
381
+ G = nx.DiGraph([("src1", "dest"), ("src2", "dest")])
382
+ G["src1"]["dest"]["value"] = "src1-->dest"
383
+ G["src2"]["dest"]["value"] = "src2-->dest"
384
+ H = nx.MultiDiGraph(G)
385
+
386
+ G = nx.contracted_nodes(G, "src1", "src2") # New Shape: src1 --> dest
387
+ assert G.edges[("src1", "dest")]["value"] == "src1-->dest"
388
+ assert (
389
+ G.edges[("src1", "dest")]["contraction"][("src2", "dest")]["value"]
390
+ == "src2-->dest"
391
+ )
392
+
393
+ H = nx.contracted_nodes(H, "src1", "src2") # New Shape: src1 -(x2)-> dest
394
+ assert len(H.edges(("src1", "dest"))) == 2
395
+
396
+
397
+ def test_without_self_loops():
398
+ """Tests for node contraction without preserving -loops."""
399
+ G = nx.cycle_graph(4)
400
+ actual = nx.contracted_nodes(G, 0, 1, self_loops=False)
401
+ expected = nx.complete_graph(3)
402
+ assert nx.is_isomorphic(actual, expected)
403
+
404
+
405
+ def test_contract_loop_graph():
406
+ """Tests for node contraction when nodes have loops."""
407
+ G = nx.cycle_graph(4)
408
+ G.add_edge(0, 0)
409
+ actual = nx.contracted_nodes(G, 0, 1)
410
+ expected = nx.complete_graph([0, 2, 3])
411
+ expected.add_edge(0, 0)
412
+ expected.add_edge(0, 0)
413
+ assert edges_equal(actual.edges, expected.edges)
414
+ actual = nx.contracted_nodes(G, 1, 0)
415
+ expected = nx.complete_graph([1, 2, 3])
416
+ expected.add_edge(1, 1)
417
+ expected.add_edge(1, 1)
418
+ assert edges_equal(actual.edges, expected.edges)
419
+
420
+
421
+ def test_undirected_edge_contraction():
422
+ """Tests for edge contraction in an undirected graph."""
423
+ G = nx.cycle_graph(4)
424
+ actual = nx.contracted_edge(G, (0, 1))
425
+ expected = nx.complete_graph(3)
426
+ expected.add_edge(0, 0)
427
+ assert nx.is_isomorphic(actual, expected)
428
+
429
+
430
+ def test_multigraph_edge_contraction():
431
+ """Tests for edge contraction in a multigraph"""
432
+ G = nx.cycle_graph(4)
433
+ actual = nx.contracted_edge(G, (0, 1, 0))
434
+ expected = nx.complete_graph(3)
435
+ expected.add_edge(0, 0)
436
+ assert nx.is_isomorphic(actual, expected)
437
+
438
+
439
+ def test_nonexistent_edge():
440
+ """Tests that attempting to contract a nonexistent edge raises an
441
+ exception.
442
+
443
+ """
444
+ with pytest.raises(ValueError):
445
+ G = nx.cycle_graph(4)
446
+ nx.contracted_edge(G, (0, 2))
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from networkx.algorithms.shortest_paths.generic import *
2
+ from networkx.algorithms.shortest_paths.unweighted import *
3
+ from networkx.algorithms.shortest_paths.weighted import *
4
+ from networkx.algorithms.shortest_paths.astar import *
5
+ from networkx.algorithms.shortest_paths.dense import *
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (465 Bytes). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/astar.cpython-310.pyc ADDED
Binary file (7.43 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/dense.cpython-310.pyc ADDED
Binary file (7.76 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/generic.cpython-310.pyc ADDED
Binary file (21.6 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/unweighted.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__pycache__/weighted.cpython-310.pyc ADDED
Binary file (74.6 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/astar.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shortest paths and path lengths using the A* ("A star") algorithm."""
2
+
3
+ from heapq import heappop, heappush
4
+ from itertools import count
5
+
6
+ import networkx as nx
7
+ from networkx.algorithms.shortest_paths.weighted import _weight_function
8
+
9
+ __all__ = ["astar_path", "astar_path_length"]
10
+
11
+
12
+ @nx._dispatchable(edge_attrs="weight", preserve_node_attrs="heuristic")
13
+ def astar_path(G, source, target, heuristic=None, weight="weight", *, cutoff=None):
14
+ """Returns a list of nodes in a shortest path between source and target
15
+ using the A* ("A-star") algorithm.
16
+
17
+ There may be more than one shortest path. This returns only one.
18
+
19
+ Parameters
20
+ ----------
21
+ G : NetworkX graph
22
+
23
+ source : node
24
+ Starting node for path
25
+
26
+ target : node
27
+ Ending node for path
28
+
29
+ heuristic : function
30
+ A function to evaluate the estimate of the distance
31
+ from the a node to the target. The function takes
32
+ two nodes arguments and must return a number.
33
+ If the heuristic is inadmissible (if it might
34
+ overestimate the cost of reaching the goal from a node),
35
+ the result may not be a shortest path.
36
+ The algorithm does not support updating heuristic
37
+ values for the same node due to caching the first
38
+ heuristic calculation per node.
39
+
40
+ weight : string or function
41
+ If this is a string, then edge weights will be accessed via the
42
+ edge attribute with this key (that is, the weight of the edge
43
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
44
+ such edge attribute exists, the weight of the edge is assumed to
45
+ be one.
46
+ If this is a function, the weight of an edge is the value
47
+ returned by the function. The function must accept exactly three
48
+ positional arguments: the two endpoints of an edge and the
49
+ dictionary of edge attributes for that edge. The function must
50
+ return a number or None to indicate a hidden edge.
51
+
52
+ cutoff : float, optional
53
+ If this is provided, the search will be bounded to this value. I.e. if
54
+ the evaluation function surpasses this value for a node n, the node will not
55
+ be expanded further and will be ignored. More formally, let h'(n) be the
56
+ heuristic function, and g(n) be the cost of reaching n from the source node. Then,
57
+ if g(n) + h'(n) > cutoff, the node will not be explored further.
58
+ Note that if the heuristic is inadmissible, it is possible that paths
59
+ are ignored even though they satisfy the cutoff.
60
+
61
+ Raises
62
+ ------
63
+ NetworkXNoPath
64
+ If no path exists between source and target.
65
+
66
+ Examples
67
+ --------
68
+ >>> G = nx.path_graph(5)
69
+ >>> print(nx.astar_path(G, 0, 4))
70
+ [0, 1, 2, 3, 4]
71
+ >>> G = nx.grid_graph(dim=[3, 3]) # nodes are two-tuples (x,y)
72
+ >>> nx.set_edge_attributes(G, {e: e[1][0] * 2 for e in G.edges()}, "cost")
73
+ >>> def dist(a, b):
74
+ ... (x1, y1) = a
75
+ ... (x2, y2) = b
76
+ ... return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
77
+ >>> print(nx.astar_path(G, (0, 0), (2, 2), heuristic=dist, weight="cost"))
78
+ [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
79
+
80
+ Notes
81
+ -----
82
+ Edge weight attributes must be numerical.
83
+ Distances are calculated as sums of weighted edges traversed.
84
+
85
+ The weight function can be used to hide edges by returning None.
86
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
87
+ will find the shortest red path.
88
+
89
+ See Also
90
+ --------
91
+ shortest_path, dijkstra_path
92
+
93
+ """
94
+ if source not in G:
95
+ raise nx.NodeNotFound(f"Source {source} is not in G")
96
+
97
+ if target not in G:
98
+ raise nx.NodeNotFound(f"Target {target} is not in G")
99
+
100
+ if heuristic is None:
101
+ # The default heuristic is h=0 - same as Dijkstra's algorithm
102
+ def heuristic(u, v):
103
+ return 0
104
+
105
+ push = heappush
106
+ pop = heappop
107
+ weight = _weight_function(G, weight)
108
+
109
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
110
+
111
+ # The queue stores priority, node, cost to reach, and parent.
112
+ # Uses Python heapq to keep in priority order.
113
+ # Add a counter to the queue to prevent the underlying heap from
114
+ # attempting to compare the nodes themselves. The hash breaks ties in the
115
+ # priority and is guaranteed unique for all nodes in the graph.
116
+ c = count()
117
+ queue = [(0, next(c), source, 0, None)]
118
+
119
+ # Maps enqueued nodes to distance of discovered paths and the
120
+ # computed heuristics to target. We avoid computing the heuristics
121
+ # more than once and inserting the node into the queue too many times.
122
+ enqueued = {}
123
+ # Maps explored nodes to parent closest to the source.
124
+ explored = {}
125
+
126
+ while queue:
127
+ # Pop the smallest item from queue.
128
+ _, __, curnode, dist, parent = pop(queue)
129
+
130
+ if curnode == target:
131
+ path = [curnode]
132
+ node = parent
133
+ while node is not None:
134
+ path.append(node)
135
+ node = explored[node]
136
+ path.reverse()
137
+ return path
138
+
139
+ if curnode in explored:
140
+ # Do not override the parent of starting node
141
+ if explored[curnode] is None:
142
+ continue
143
+
144
+ # Skip bad paths that were enqueued before finding a better one
145
+ qcost, h = enqueued[curnode]
146
+ if qcost < dist:
147
+ continue
148
+
149
+ explored[curnode] = parent
150
+
151
+ for neighbor, w in G_succ[curnode].items():
152
+ cost = weight(curnode, neighbor, w)
153
+ if cost is None:
154
+ continue
155
+ ncost = dist + cost
156
+ if neighbor in enqueued:
157
+ qcost, h = enqueued[neighbor]
158
+ # if qcost <= ncost, a less costly path from the
159
+ # neighbor to the source was already determined.
160
+ # Therefore, we won't attempt to push this neighbor
161
+ # to the queue
162
+ if qcost <= ncost:
163
+ continue
164
+ else:
165
+ h = heuristic(neighbor, target)
166
+
167
+ if cutoff and ncost + h > cutoff:
168
+ continue
169
+
170
+ enqueued[neighbor] = ncost, h
171
+ push(queue, (ncost + h, next(c), neighbor, ncost, curnode))
172
+
173
+ raise nx.NetworkXNoPath(f"Node {target} not reachable from {source}")
174
+
175
+
176
+ @nx._dispatchable(edge_attrs="weight", preserve_node_attrs="heuristic")
177
+ def astar_path_length(
178
+ G, source, target, heuristic=None, weight="weight", *, cutoff=None
179
+ ):
180
+ """Returns the length of the shortest path between source and target using
181
+ the A* ("A-star") algorithm.
182
+
183
+ Parameters
184
+ ----------
185
+ G : NetworkX graph
186
+
187
+ source : node
188
+ Starting node for path
189
+
190
+ target : node
191
+ Ending node for path
192
+
193
+ heuristic : function
194
+ A function to evaluate the estimate of the distance
195
+ from the a node to the target. The function takes
196
+ two nodes arguments and must return a number.
197
+ If the heuristic is inadmissible (if it might
198
+ overestimate the cost of reaching the goal from a node),
199
+ the result may not be a shortest path.
200
+ The algorithm does not support updating heuristic
201
+ values for the same node due to caching the first
202
+ heuristic calculation per node.
203
+
204
+ weight : string or function
205
+ If this is a string, then edge weights will be accessed via the
206
+ edge attribute with this key (that is, the weight of the edge
207
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
208
+ such edge attribute exists, the weight of the edge is assumed to
209
+ be one.
210
+ If this is a function, the weight of an edge is the value
211
+ returned by the function. The function must accept exactly three
212
+ positional arguments: the two endpoints of an edge and the
213
+ dictionary of edge attributes for that edge. The function must
214
+ return a number or None to indicate a hidden edge.
215
+
216
+ cutoff : float, optional
217
+ If this is provided, the search will be bounded to this value. I.e. if
218
+ the evaluation function surpasses this value for a node n, the node will not
219
+ be expanded further and will be ignored. More formally, let h'(n) be the
220
+ heuristic function, and g(n) be the cost of reaching n from the source node. Then,
221
+ if g(n) + h'(n) > cutoff, the node will not be explored further.
222
+ Note that if the heuristic is inadmissible, it is possible that paths
223
+ are ignored even though they satisfy the cutoff.
224
+
225
+ Raises
226
+ ------
227
+ NetworkXNoPath
228
+ If no path exists between source and target.
229
+
230
+ See Also
231
+ --------
232
+ astar_path
233
+
234
+ """
235
+ if source not in G or target not in G:
236
+ msg = f"Either source {source} or target {target} is not in G"
237
+ raise nx.NodeNotFound(msg)
238
+
239
+ weight = _weight_function(G, weight)
240
+ path = astar_path(G, source, target, heuristic, weight, cutoff=cutoff)
241
+ return sum(weight(u, v, G[u][v]) for u, v in zip(path[:-1], path[1:]))
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/dense.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floyd-Warshall algorithm for shortest paths."""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = [
6
+ "floyd_warshall",
7
+ "floyd_warshall_predecessor_and_distance",
8
+ "reconstruct_path",
9
+ "floyd_warshall_numpy",
10
+ ]
11
+
12
+
13
+ @nx._dispatchable(edge_attrs="weight")
14
+ def floyd_warshall_numpy(G, nodelist=None, weight="weight"):
15
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
16
+
17
+ This algorithm for finding shortest paths takes advantage of
18
+ matrix representations of a graph and works well for dense
19
+ graphs where all-pairs shortest path lengths are desired.
20
+ The results are returned as a NumPy array, distance[i, j],
21
+ where i and j are the indexes of two nodes in nodelist.
22
+ The entry distance[i, j] is the distance along a shortest
23
+ path from i to j. If no path exists the distance is Inf.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ nodelist : list, optional (default=G.nodes)
30
+ The rows and columns are ordered by the nodes in nodelist.
31
+ If nodelist is None then the ordering is produced by G.nodes.
32
+ Nodelist should include all nodes in G.
33
+
34
+ weight: string, optional (default='weight')
35
+ Edge data key corresponding to the edge weight.
36
+
37
+ Returns
38
+ -------
39
+ distance : 2D numpy.ndarray
40
+ A numpy array of shortest path distances between nodes.
41
+ If there is no path between two nodes the value is Inf.
42
+
43
+ Examples
44
+ --------
45
+ >>> G = nx.DiGraph()
46
+ >>> G.add_weighted_edges_from(
47
+ ... [(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)]
48
+ ... )
49
+ >>> nx.floyd_warshall_numpy(G)
50
+ array([[ 0., 5., 7., 4.],
51
+ [inf, 0., 2., -1.],
52
+ [inf, inf, 0., -3.],
53
+ [inf, inf, 8., 0.]])
54
+
55
+ Notes
56
+ -----
57
+ Floyd's algorithm is appropriate for finding shortest paths in
58
+ dense graphs or graphs with negative weights when Dijkstra's
59
+ algorithm fails. This algorithm can still fail if there are negative
60
+ cycles. It has running time $O(n^3)$ with running space of $O(n^2)$.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXError
65
+ If nodelist is not a list of the nodes in G.
66
+ """
67
+ import numpy as np
68
+
69
+ if nodelist is not None:
70
+ if not (len(nodelist) == len(G) == len(set(nodelist))):
71
+ raise nx.NetworkXError(
72
+ "nodelist must contain every node in G with no repeats."
73
+ "If you wanted a subgraph of G use G.subgraph(nodelist)"
74
+ )
75
+
76
+ # To handle cases when an edge has weight=0, we must make sure that
77
+ # nonedges are not given the value 0 as well.
78
+ A = nx.to_numpy_array(
79
+ G, nodelist, multigraph_weight=min, weight=weight, nonedge=np.inf
80
+ )
81
+ n, m = A.shape
82
+ np.fill_diagonal(A, 0) # diagonal elements should be zero
83
+ for i in range(n):
84
+ # The second term has the same shape as A due to broadcasting
85
+ A = np.minimum(A, A[i, :][np.newaxis, :] + A[:, i][:, np.newaxis])
86
+ return A
87
+
88
+
89
+ @nx._dispatchable(edge_attrs="weight")
90
+ def floyd_warshall_predecessor_and_distance(G, weight="weight"):
91
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
92
+
93
+ Parameters
94
+ ----------
95
+ G : NetworkX graph
96
+
97
+ weight: string, optional (default= 'weight')
98
+ Edge data key corresponding to the edge weight.
99
+
100
+ Returns
101
+ -------
102
+ predecessor,distance : dictionaries
103
+ Dictionaries, keyed by source and target, of predecessors and distances
104
+ in the shortest path.
105
+
106
+ Examples
107
+ --------
108
+ >>> G = nx.DiGraph()
109
+ >>> G.add_weighted_edges_from(
110
+ ... [
111
+ ... ("s", "u", 10),
112
+ ... ("s", "x", 5),
113
+ ... ("u", "v", 1),
114
+ ... ("u", "x", 2),
115
+ ... ("v", "y", 1),
116
+ ... ("x", "u", 3),
117
+ ... ("x", "v", 5),
118
+ ... ("x", "y", 2),
119
+ ... ("y", "s", 7),
120
+ ... ("y", "v", 6),
121
+ ... ]
122
+ ... )
123
+ >>> predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
124
+ >>> print(nx.reconstruct_path("s", "v", predecessors))
125
+ ['s', 'x', 'u', 'v']
126
+
127
+ Notes
128
+ -----
129
+ Floyd's algorithm is appropriate for finding shortest paths
130
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
131
+ fails. This algorithm can still fail if there are negative cycles.
132
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
133
+
134
+ See Also
135
+ --------
136
+ floyd_warshall
137
+ floyd_warshall_numpy
138
+ all_pairs_shortest_path
139
+ all_pairs_shortest_path_length
140
+ """
141
+ from collections import defaultdict
142
+
143
+ # dictionary-of-dictionaries representation for dist and pred
144
+ # use some defaultdict magick here
145
+ # for dist the default is the floating point inf value
146
+ dist = defaultdict(lambda: defaultdict(lambda: float("inf")))
147
+ for u in G:
148
+ dist[u][u] = 0
149
+ pred = defaultdict(dict)
150
+ # initialize path distance dictionary to be the adjacency matrix
151
+ # also set the distance to self to 0 (zero diagonal)
152
+ undirected = not G.is_directed()
153
+ for u, v, d in G.edges(data=True):
154
+ e_weight = d.get(weight, 1.0)
155
+ dist[u][v] = min(e_weight, dist[u][v])
156
+ pred[u][v] = u
157
+ if undirected:
158
+ dist[v][u] = min(e_weight, dist[v][u])
159
+ pred[v][u] = v
160
+ for w in G:
161
+ dist_w = dist[w] # save recomputation
162
+ for u in G:
163
+ dist_u = dist[u] # save recomputation
164
+ for v in G:
165
+ d = dist_u[w] + dist_w[v]
166
+ if dist_u[v] > d:
167
+ dist_u[v] = d
168
+ pred[u][v] = pred[w][v]
169
+ return dict(pred), dict(dist)
170
+
171
+
172
+ @nx._dispatchable(graphs=None)
173
+ def reconstruct_path(source, target, predecessors):
174
+ """Reconstruct a path from source to target using the predecessors
175
+ dict as returned by floyd_warshall_predecessor_and_distance
176
+
177
+ Parameters
178
+ ----------
179
+ source : node
180
+ Starting node for path
181
+
182
+ target : node
183
+ Ending node for path
184
+
185
+ predecessors: dictionary
186
+ Dictionary, keyed by source and target, of predecessors in the
187
+ shortest path, as returned by floyd_warshall_predecessor_and_distance
188
+
189
+ Returns
190
+ -------
191
+ path : list
192
+ A list of nodes containing the shortest path from source to target
193
+
194
+ If source and target are the same, an empty list is returned
195
+
196
+ Notes
197
+ -----
198
+ This function is meant to give more applicability to the
199
+ floyd_warshall_predecessor_and_distance function
200
+
201
+ See Also
202
+ --------
203
+ floyd_warshall_predecessor_and_distance
204
+ """
205
+ if source == target:
206
+ return []
207
+ prev = predecessors[source]
208
+ curr = prev[target]
209
+ path = [target, curr]
210
+ while curr != source:
211
+ curr = prev[curr]
212
+ path.append(curr)
213
+ return list(reversed(path))
214
+
215
+
216
+ @nx._dispatchable(edge_attrs="weight")
217
+ def floyd_warshall(G, weight="weight"):
218
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
219
+
220
+ Parameters
221
+ ----------
222
+ G : NetworkX graph
223
+
224
+ weight: string, optional (default= 'weight')
225
+ Edge data key corresponding to the edge weight.
226
+
227
+
228
+ Returns
229
+ -------
230
+ distance : dict
231
+ A dictionary, keyed by source and target, of shortest paths distances
232
+ between nodes.
233
+
234
+ Examples
235
+ --------
236
+ >>> G = nx.DiGraph()
237
+ >>> G.add_weighted_edges_from(
238
+ ... [(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)]
239
+ ... )
240
+ >>> fw = nx.floyd_warshall(G, weight="weight")
241
+ >>> results = {a: dict(b) for a, b in fw.items()}
242
+ >>> print(results)
243
+ {0: {0: 0, 1: 5, 2: 7, 3: 4}, 1: {1: 0, 2: 2, 3: -1, 0: inf}, 2: {2: 0, 3: -3, 0: inf, 1: inf}, 3: {3: 0, 2: 8, 0: inf, 1: inf}}
244
+
245
+ Notes
246
+ -----
247
+ Floyd's algorithm is appropriate for finding shortest paths
248
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
249
+ fails. This algorithm can still fail if there are negative cycles.
250
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
251
+
252
+ See Also
253
+ --------
254
+ floyd_warshall_predecessor_and_distance
255
+ floyd_warshall_numpy
256
+ all_pairs_shortest_path
257
+ all_pairs_shortest_path_length
258
+ """
259
+ # could make this its own function to reduce memory costs
260
+ return floyd_warshall_predecessor_and_distance(G, weight=weight)[1]
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/generic.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Compute the shortest paths and path lengths between nodes in the graph.
3
+
4
+ These algorithms work with undirected and directed graphs.
5
+
6
+ """
7
+
8
+ import warnings
9
+
10
+ import networkx as nx
11
+
12
+ __all__ = [
13
+ "shortest_path",
14
+ "all_shortest_paths",
15
+ "single_source_all_shortest_paths",
16
+ "all_pairs_all_shortest_paths",
17
+ "shortest_path_length",
18
+ "average_shortest_path_length",
19
+ "has_path",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable
24
+ def has_path(G, source, target):
25
+ """Returns *True* if *G* has a path from *source* to *target*.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : node
32
+ Starting node for path
33
+
34
+ target : node
35
+ Ending node for path
36
+ """
37
+ try:
38
+ nx.shortest_path(G, source, target)
39
+ except nx.NetworkXNoPath:
40
+ return False
41
+ return True
42
+
43
+
44
+ @nx._dispatchable(edge_attrs="weight")
45
+ def shortest_path(G, source=None, target=None, weight=None, method="dijkstra"):
46
+ """Compute shortest paths in the graph.
47
+
48
+ Parameters
49
+ ----------
50
+ G : NetworkX graph
51
+
52
+ source : node, optional
53
+ Starting node for path. If not specified, compute shortest
54
+ paths for each possible starting node.
55
+
56
+ target : node, optional
57
+ Ending node for path. If not specified, compute shortest
58
+ paths to all possible nodes.
59
+
60
+ weight : None, string or function, optional (default = None)
61
+ If None, every edge has weight/distance/cost 1.
62
+ If a string, use this edge attribute as the edge weight.
63
+ Any edge attribute not present defaults to 1.
64
+ If this is a function, the weight of an edge is the value
65
+ returned by the function. The function must accept exactly
66
+ three positional arguments: the two endpoints of an edge and
67
+ the dictionary of edge attributes for that edge.
68
+ The function must return a number.
69
+
70
+ method : string, optional (default = 'dijkstra')
71
+ The algorithm to use to compute the path.
72
+ Supported options: 'dijkstra', 'bellman-ford'.
73
+ Other inputs produce a ValueError.
74
+ If `weight` is None, unweighted graph methods are used, and this
75
+ suggestion is ignored.
76
+
77
+ Returns
78
+ -------
79
+ path: list or dictionary
80
+ All returned paths include both the source and target in the path.
81
+
82
+ If the source and target are both specified, return a single list
83
+ of nodes in a shortest path from the source to the target.
84
+
85
+ If only the source is specified, return a dictionary keyed by
86
+ targets with a list of nodes in a shortest path from the source
87
+ to one of the targets.
88
+
89
+ If only the target is specified, return a dictionary keyed by
90
+ sources with a list of nodes in a shortest path from one of the
91
+ sources to the target.
92
+
93
+ If neither the source nor target are specified return a dictionary
94
+ of dictionaries with path[source][target]=[list of nodes in path].
95
+
96
+ Raises
97
+ ------
98
+ NodeNotFound
99
+ If `source` is not in `G`.
100
+
101
+ ValueError
102
+ If `method` is not among the supported options.
103
+
104
+ Examples
105
+ --------
106
+ >>> G = nx.path_graph(5)
107
+ >>> print(nx.shortest_path(G, source=0, target=4))
108
+ [0, 1, 2, 3, 4]
109
+ >>> p = nx.shortest_path(G, source=0) # target not specified
110
+ >>> p[3] # shortest path from source=0 to target=3
111
+ [0, 1, 2, 3]
112
+ >>> p = nx.shortest_path(G, target=4) # source not specified
113
+ >>> p[1] # shortest path from source=1 to target=4
114
+ [1, 2, 3, 4]
115
+ >>> p = dict(nx.shortest_path(G)) # source, target not specified
116
+ >>> p[2][4] # shortest path from source=2 to target=4
117
+ [2, 3, 4]
118
+
119
+ Notes
120
+ -----
121
+ There may be more than one shortest path between a source and target.
122
+ This returns only one of them.
123
+
124
+ See Also
125
+ --------
126
+ all_pairs_shortest_path
127
+ all_pairs_dijkstra_path
128
+ all_pairs_bellman_ford_path
129
+ single_source_shortest_path
130
+ single_source_dijkstra_path
131
+ single_source_bellman_ford_path
132
+ """
133
+ if method not in ("dijkstra", "bellman-ford"):
134
+ # so we don't need to check in each branch later
135
+ raise ValueError(f"method not supported: {method}")
136
+ method = "unweighted" if weight is None else method
137
+ if source is None:
138
+ if target is None:
139
+ warnings.warn(
140
+ (
141
+ "\n\nshortest_path will return an iterator that yields\n"
142
+ "(node, path) pairs instead of a dictionary when source\n"
143
+ "and target are unspecified beginning in version 3.5\n\n"
144
+ "To keep the current behavior, use:\n\n"
145
+ "\tdict(nx.shortest_path(G))"
146
+ ),
147
+ FutureWarning,
148
+ stacklevel=3,
149
+ )
150
+
151
+ # Find paths between all pairs.
152
+ if method == "unweighted":
153
+ paths = dict(nx.all_pairs_shortest_path(G))
154
+ elif method == "dijkstra":
155
+ paths = dict(nx.all_pairs_dijkstra_path(G, weight=weight))
156
+ else: # method == 'bellman-ford':
157
+ paths = dict(nx.all_pairs_bellman_ford_path(G, weight=weight))
158
+ else:
159
+ # Find paths from all nodes co-accessible to the target.
160
+ if G.is_directed():
161
+ G = G.reverse(copy=False)
162
+ if method == "unweighted":
163
+ paths = nx.single_source_shortest_path(G, target)
164
+ elif method == "dijkstra":
165
+ paths = nx.single_source_dijkstra_path(G, target, weight=weight)
166
+ else: # method == 'bellman-ford':
167
+ paths = nx.single_source_bellman_ford_path(G, target, weight=weight)
168
+ # Now flip the paths so they go from a source to the target.
169
+ for target in paths:
170
+ paths[target] = list(reversed(paths[target]))
171
+ else:
172
+ if target is None:
173
+ # Find paths to all nodes accessible from the source.
174
+ if method == "unweighted":
175
+ paths = nx.single_source_shortest_path(G, source)
176
+ elif method == "dijkstra":
177
+ paths = nx.single_source_dijkstra_path(G, source, weight=weight)
178
+ else: # method == 'bellman-ford':
179
+ paths = nx.single_source_bellman_ford_path(G, source, weight=weight)
180
+ else:
181
+ # Find shortest source-target path.
182
+ if method == "unweighted":
183
+ paths = nx.bidirectional_shortest_path(G, source, target)
184
+ elif method == "dijkstra":
185
+ _, paths = nx.bidirectional_dijkstra(G, source, target, weight)
186
+ else: # method == 'bellman-ford':
187
+ paths = nx.bellman_ford_path(G, source, target, weight)
188
+ return paths
189
+
190
+
191
+ @nx._dispatchable(edge_attrs="weight")
192
+ def shortest_path_length(G, source=None, target=None, weight=None, method="dijkstra"):
193
+ """Compute shortest path lengths in the graph.
194
+
195
+ Parameters
196
+ ----------
197
+ G : NetworkX graph
198
+
199
+ source : node, optional
200
+ Starting node for path.
201
+ If not specified, compute shortest path lengths using all nodes as
202
+ source nodes.
203
+
204
+ target : node, optional
205
+ Ending node for path.
206
+ If not specified, compute shortest path lengths using all nodes as
207
+ target nodes.
208
+
209
+ weight : None, string or function, optional (default = None)
210
+ If None, every edge has weight/distance/cost 1.
211
+ If a string, use this edge attribute as the edge weight.
212
+ Any edge attribute not present defaults to 1.
213
+ If this is a function, the weight of an edge is the value
214
+ returned by the function. The function must accept exactly
215
+ three positional arguments: the two endpoints of an edge and
216
+ the dictionary of edge attributes for that edge.
217
+ The function must return a number.
218
+
219
+ method : string, optional (default = 'dijkstra')
220
+ The algorithm to use to compute the path length.
221
+ Supported options: 'dijkstra', 'bellman-ford'.
222
+ Other inputs produce a ValueError.
223
+ If `weight` is None, unweighted graph methods are used, and this
224
+ suggestion is ignored.
225
+
226
+ Returns
227
+ -------
228
+ length: number or iterator
229
+ If the source and target are both specified, return the length of
230
+ the shortest path from the source to the target.
231
+
232
+ If only the source is specified, return a dict keyed by target
233
+ to the shortest path length from the source to that target.
234
+
235
+ If only the target is specified, return a dict keyed by source
236
+ to the shortest path length from that source to the target.
237
+
238
+ If neither the source nor target are specified, return an iterator
239
+ over (source, dictionary) where dictionary is keyed by target to
240
+ shortest path length from source to that target.
241
+
242
+ Raises
243
+ ------
244
+ NodeNotFound
245
+ If `source` is not in `G`.
246
+
247
+ NetworkXNoPath
248
+ If no path exists between source and target.
249
+
250
+ ValueError
251
+ If `method` is not among the supported options.
252
+
253
+ Examples
254
+ --------
255
+ >>> G = nx.path_graph(5)
256
+ >>> nx.shortest_path_length(G, source=0, target=4)
257
+ 4
258
+ >>> p = nx.shortest_path_length(G, source=0) # target not specified
259
+ >>> p[4]
260
+ 4
261
+ >>> p = nx.shortest_path_length(G, target=4) # source not specified
262
+ >>> p[0]
263
+ 4
264
+ >>> p = dict(nx.shortest_path_length(G)) # source,target not specified
265
+ >>> p[0][4]
266
+ 4
267
+
268
+ Notes
269
+ -----
270
+ The length of the path is always 1 less than the number of nodes involved
271
+ in the path since the length measures the number of edges followed.
272
+
273
+ For digraphs this returns the shortest directed path length. To find path
274
+ lengths in the reverse direction use G.reverse(copy=False) first to flip
275
+ the edge orientation.
276
+
277
+ See Also
278
+ --------
279
+ all_pairs_shortest_path_length
280
+ all_pairs_dijkstra_path_length
281
+ all_pairs_bellman_ford_path_length
282
+ single_source_shortest_path_length
283
+ single_source_dijkstra_path_length
284
+ single_source_bellman_ford_path_length
285
+ """
286
+ if method not in ("dijkstra", "bellman-ford"):
287
+ # so we don't need to check in each branch later
288
+ raise ValueError(f"method not supported: {method}")
289
+ method = "unweighted" if weight is None else method
290
+ if source is None:
291
+ if target is None:
292
+ # Find paths between all pairs.
293
+ if method == "unweighted":
294
+ paths = nx.all_pairs_shortest_path_length(G)
295
+ elif method == "dijkstra":
296
+ paths = nx.all_pairs_dijkstra_path_length(G, weight=weight)
297
+ else: # method == 'bellman-ford':
298
+ paths = nx.all_pairs_bellman_ford_path_length(G, weight=weight)
299
+ else:
300
+ # Find paths from all nodes co-accessible to the target.
301
+ if G.is_directed():
302
+ G = G.reverse(copy=False)
303
+ if method == "unweighted":
304
+ path_length = nx.single_source_shortest_path_length
305
+ paths = path_length(G, target)
306
+ elif method == "dijkstra":
307
+ path_length = nx.single_source_dijkstra_path_length
308
+ paths = path_length(G, target, weight=weight)
309
+ else: # method == 'bellman-ford':
310
+ path_length = nx.single_source_bellman_ford_path_length
311
+ paths = path_length(G, target, weight=weight)
312
+ else:
313
+ if target is None:
314
+ # Find paths to all nodes accessible from the source.
315
+ if method == "unweighted":
316
+ paths = nx.single_source_shortest_path_length(G, source)
317
+ elif method == "dijkstra":
318
+ path_length = nx.single_source_dijkstra_path_length
319
+ paths = path_length(G, source, weight=weight)
320
+ else: # method == 'bellman-ford':
321
+ path_length = nx.single_source_bellman_ford_path_length
322
+ paths = path_length(G, source, weight=weight)
323
+ else:
324
+ # Find shortest source-target path.
325
+ if method == "unweighted":
326
+ p = nx.bidirectional_shortest_path(G, source, target)
327
+ paths = len(p) - 1
328
+ elif method == "dijkstra":
329
+ paths = nx.dijkstra_path_length(G, source, target, weight)
330
+ else: # method == 'bellman-ford':
331
+ paths = nx.bellman_ford_path_length(G, source, target, weight)
332
+ return paths
333
+
334
+
335
+ @nx._dispatchable(edge_attrs="weight")
336
+ def average_shortest_path_length(G, weight=None, method=None):
337
+ r"""Returns the average shortest path length.
338
+
339
+ The average shortest path length is
340
+
341
+ .. math::
342
+
343
+ a =\sum_{\substack{s,t \in V \\ s\neq t}} \frac{d(s, t)}{n(n-1)}
344
+
345
+ where `V` is the set of nodes in `G`,
346
+ `d(s, t)` is the shortest path from `s` to `t`,
347
+ and `n` is the number of nodes in `G`.
348
+
349
+ .. versionchanged:: 3.0
350
+ An exception is raised for directed graphs that are not strongly
351
+ connected.
352
+
353
+ Parameters
354
+ ----------
355
+ G : NetworkX graph
356
+
357
+ weight : None, string or function, optional (default = None)
358
+ If None, every edge has weight/distance/cost 1.
359
+ If a string, use this edge attribute as the edge weight.
360
+ Any edge attribute not present defaults to 1.
361
+ If this is a function, the weight of an edge is the value
362
+ returned by the function. The function must accept exactly
363
+ three positional arguments: the two endpoints of an edge and
364
+ the dictionary of edge attributes for that edge.
365
+ The function must return a number.
366
+
367
+ method : string, optional (default = 'unweighted' or 'dijkstra')
368
+ The algorithm to use to compute the path lengths.
369
+ Supported options are 'unweighted', 'dijkstra', 'bellman-ford',
370
+ 'floyd-warshall' and 'floyd-warshall-numpy'.
371
+ Other method values produce a ValueError.
372
+ The default method is 'unweighted' if `weight` is None,
373
+ otherwise the default method is 'dijkstra'.
374
+
375
+ Raises
376
+ ------
377
+ NetworkXPointlessConcept
378
+ If `G` is the null graph (that is, the graph on zero nodes).
379
+
380
+ NetworkXError
381
+ If `G` is not connected (or not strongly connected, in the case
382
+ of a directed graph).
383
+
384
+ ValueError
385
+ If `method` is not among the supported options.
386
+
387
+ Examples
388
+ --------
389
+ >>> G = nx.path_graph(5)
390
+ >>> nx.average_shortest_path_length(G)
391
+ 2.0
392
+
393
+ For disconnected graphs, you can compute the average shortest path
394
+ length for each component
395
+
396
+ >>> G = nx.Graph([(1, 2), (3, 4)])
397
+ >>> for C in (G.subgraph(c).copy() for c in nx.connected_components(G)):
398
+ ... print(nx.average_shortest_path_length(C))
399
+ 1.0
400
+ 1.0
401
+
402
+ """
403
+ single_source_methods = ["unweighted", "dijkstra", "bellman-ford"]
404
+ all_pairs_methods = ["floyd-warshall", "floyd-warshall-numpy"]
405
+ supported_methods = single_source_methods + all_pairs_methods
406
+
407
+ if method is None:
408
+ method = "unweighted" if weight is None else "dijkstra"
409
+ if method not in supported_methods:
410
+ raise ValueError(f"method not supported: {method}")
411
+
412
+ n = len(G)
413
+ # For the special case of the null graph, raise an exception, since
414
+ # there are no paths in the null graph.
415
+ if n == 0:
416
+ msg = (
417
+ "the null graph has no paths, thus there is no average "
418
+ "shortest path length"
419
+ )
420
+ raise nx.NetworkXPointlessConcept(msg)
421
+ # For the special case of the trivial graph, return zero immediately.
422
+ if n == 1:
423
+ return 0
424
+ # Shortest path length is undefined if the graph is not strongly connected.
425
+ if G.is_directed() and not nx.is_strongly_connected(G):
426
+ raise nx.NetworkXError("Graph is not strongly connected.")
427
+ # Shortest path length is undefined if the graph is not connected.
428
+ if not G.is_directed() and not nx.is_connected(G):
429
+ raise nx.NetworkXError("Graph is not connected.")
430
+
431
+ # Compute all-pairs shortest paths.
432
+ def path_length(v):
433
+ if method == "unweighted":
434
+ return nx.single_source_shortest_path_length(G, v)
435
+ elif method == "dijkstra":
436
+ return nx.single_source_dijkstra_path_length(G, v, weight=weight)
437
+ elif method == "bellman-ford":
438
+ return nx.single_source_bellman_ford_path_length(G, v, weight=weight)
439
+
440
+ if method in single_source_methods:
441
+ # Sum the distances for each (ordered) pair of source and target node.
442
+ s = sum(l for u in G for l in path_length(u).values())
443
+ else:
444
+ if method == "floyd-warshall":
445
+ all_pairs = nx.floyd_warshall(G, weight=weight)
446
+ s = sum(sum(t.values()) for t in all_pairs.values())
447
+ elif method == "floyd-warshall-numpy":
448
+ s = float(nx.floyd_warshall_numpy(G, weight=weight).sum())
449
+ return s / (n * (n - 1))
450
+
451
+
452
+ @nx._dispatchable(edge_attrs="weight")
453
+ def all_shortest_paths(G, source, target, weight=None, method="dijkstra"):
454
+ """Compute all shortest simple paths in the graph.
455
+
456
+ Parameters
457
+ ----------
458
+ G : NetworkX graph
459
+
460
+ source : node
461
+ Starting node for path.
462
+
463
+ target : node
464
+ Ending node for path.
465
+
466
+ weight : None, string or function, optional (default = None)
467
+ If None, every edge has weight/distance/cost 1.
468
+ If a string, use this edge attribute as the edge weight.
469
+ Any edge attribute not present defaults to 1.
470
+ If this is a function, the weight of an edge is the value
471
+ returned by the function. The function must accept exactly
472
+ three positional arguments: the two endpoints of an edge and
473
+ the dictionary of edge attributes for that edge.
474
+ The function must return a number.
475
+
476
+ method : string, optional (default = 'dijkstra')
477
+ The algorithm to use to compute the path lengths.
478
+ Supported options: 'dijkstra', 'bellman-ford'.
479
+ Other inputs produce a ValueError.
480
+ If `weight` is None, unweighted graph methods are used, and this
481
+ suggestion is ignored.
482
+
483
+ Returns
484
+ -------
485
+ paths : generator of lists
486
+ A generator of all paths between source and target.
487
+
488
+ Raises
489
+ ------
490
+ ValueError
491
+ If `method` is not among the supported options.
492
+
493
+ NetworkXNoPath
494
+ If `target` cannot be reached from `source`.
495
+
496
+ Examples
497
+ --------
498
+ >>> G = nx.Graph()
499
+ >>> nx.add_path(G, [0, 1, 2])
500
+ >>> nx.add_path(G, [0, 10, 2])
501
+ >>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)])
502
+ [[0, 1, 2], [0, 10, 2]]
503
+
504
+ Notes
505
+ -----
506
+ There may be many shortest paths between the source and target. If G
507
+ contains zero-weight cycles, this function will not produce all shortest
508
+ paths because doing so would produce infinitely many paths of unbounded
509
+ length -- instead, we only produce the shortest simple paths.
510
+
511
+ See Also
512
+ --------
513
+ shortest_path
514
+ single_source_shortest_path
515
+ all_pairs_shortest_path
516
+ """
517
+ method = "unweighted" if weight is None else method
518
+ if method == "unweighted":
519
+ pred = nx.predecessor(G, source)
520
+ elif method == "dijkstra":
521
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight)
522
+ elif method == "bellman-ford":
523
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight)
524
+ else:
525
+ raise ValueError(f"method not supported: {method}")
526
+
527
+ return _build_paths_from_predecessors({source}, target, pred)
528
+
529
+
530
+ @nx._dispatchable(edge_attrs="weight")
531
+ def single_source_all_shortest_paths(G, source, weight=None, method="dijkstra"):
532
+ """Compute all shortest simple paths from the given source in the graph.
533
+
534
+ Parameters
535
+ ----------
536
+ G : NetworkX graph
537
+
538
+ source : node
539
+ Starting node for path.
540
+
541
+ weight : None, string or function, optional (default = None)
542
+ If None, every edge has weight/distance/cost 1.
543
+ If a string, use this edge attribute as the edge weight.
544
+ Any edge attribute not present defaults to 1.
545
+ If this is a function, the weight of an edge is the value
546
+ returned by the function. The function must accept exactly
547
+ three positional arguments: the two endpoints of an edge and
548
+ the dictionary of edge attributes for that edge.
549
+ The function must return a number.
550
+
551
+ method : string, optional (default = 'dijkstra')
552
+ The algorithm to use to compute the path lengths.
553
+ Supported options: 'dijkstra', 'bellman-ford'.
554
+ Other inputs produce a ValueError.
555
+ If `weight` is None, unweighted graph methods are used, and this
556
+ suggestion is ignored.
557
+
558
+ Returns
559
+ -------
560
+ paths : generator of dictionary
561
+ A generator of all paths between source and all nodes in the graph.
562
+
563
+ Raises
564
+ ------
565
+ ValueError
566
+ If `method` is not among the supported options.
567
+
568
+ Examples
569
+ --------
570
+ >>> G = nx.Graph()
571
+ >>> nx.add_path(G, [0, 1, 2, 3, 0])
572
+ >>> dict(nx.single_source_all_shortest_paths(G, source=0))
573
+ {0: [[0]], 1: [[0, 1]], 2: [[0, 1, 2], [0, 3, 2]], 3: [[0, 3]]}
574
+
575
+ Notes
576
+ -----
577
+ There may be many shortest paths between the source and target. If G
578
+ contains zero-weight cycles, this function will not produce all shortest
579
+ paths because doing so would produce infinitely many paths of unbounded
580
+ length -- instead, we only produce the shortest simple paths.
581
+
582
+ See Also
583
+ --------
584
+ shortest_path
585
+ all_shortest_paths
586
+ single_source_shortest_path
587
+ all_pairs_shortest_path
588
+ all_pairs_all_shortest_paths
589
+ """
590
+ method = "unweighted" if weight is None else method
591
+ if method == "unweighted":
592
+ pred = nx.predecessor(G, source)
593
+ elif method == "dijkstra":
594
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight)
595
+ elif method == "bellman-ford":
596
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight)
597
+ else:
598
+ raise ValueError(f"method not supported: {method}")
599
+ for n in G:
600
+ try:
601
+ yield n, list(_build_paths_from_predecessors({source}, n, pred))
602
+ except nx.NetworkXNoPath:
603
+ pass
604
+
605
+
606
+ @nx._dispatchable(edge_attrs="weight")
607
+ def all_pairs_all_shortest_paths(G, weight=None, method="dijkstra"):
608
+ """Compute all shortest paths between all nodes.
609
+
610
+ Parameters
611
+ ----------
612
+ G : NetworkX graph
613
+
614
+ weight : None, string or function, optional (default = None)
615
+ If None, every edge has weight/distance/cost 1.
616
+ If a string, use this edge attribute as the edge weight.
617
+ Any edge attribute not present defaults to 1.
618
+ If this is a function, the weight of an edge is the value
619
+ returned by the function. The function must accept exactly
620
+ three positional arguments: the two endpoints of an edge and
621
+ the dictionary of edge attributes for that edge.
622
+ The function must return a number.
623
+
624
+ method : string, optional (default = 'dijkstra')
625
+ The algorithm to use to compute the path lengths.
626
+ Supported options: 'dijkstra', 'bellman-ford'.
627
+ Other inputs produce a ValueError.
628
+ If `weight` is None, unweighted graph methods are used, and this
629
+ suggestion is ignored.
630
+
631
+ Returns
632
+ -------
633
+ paths : generator of dictionary
634
+ Dictionary of arrays, keyed by source and target, of all shortest paths.
635
+
636
+ Raises
637
+ ------
638
+ ValueError
639
+ If `method` is not among the supported options.
640
+
641
+ Examples
642
+ --------
643
+ >>> G = nx.cycle_graph(4)
644
+ >>> dict(nx.all_pairs_all_shortest_paths(G))[0][2]
645
+ [[0, 1, 2], [0, 3, 2]]
646
+ >>> dict(nx.all_pairs_all_shortest_paths(G))[0][3]
647
+ [[0, 3]]
648
+
649
+ Notes
650
+ -----
651
+ There may be multiple shortest paths with equal lengths. Unlike
652
+ all_pairs_shortest_path, this method returns all shortest paths.
653
+
654
+ See Also
655
+ --------
656
+ all_pairs_shortest_path
657
+ single_source_all_shortest_paths
658
+ """
659
+ for n in G:
660
+ yield (
661
+ n,
662
+ dict(single_source_all_shortest_paths(G, n, weight=weight, method=method)),
663
+ )
664
+
665
+
666
+ def _build_paths_from_predecessors(sources, target, pred):
667
+ """Compute all simple paths to target, given the predecessors found in
668
+ pred, terminating when any source in sources is found.
669
+
670
+ Parameters
671
+ ----------
672
+ sources : set
673
+ Starting nodes for path.
674
+
675
+ target : node
676
+ Ending node for path.
677
+
678
+ pred : dict
679
+ A dictionary of predecessor lists, keyed by node
680
+
681
+ Returns
682
+ -------
683
+ paths : generator of lists
684
+ A generator of all paths between source and target.
685
+
686
+ Raises
687
+ ------
688
+ NetworkXNoPath
689
+ If `target` cannot be reached from `source`.
690
+
691
+ Notes
692
+ -----
693
+ There may be many paths between the sources and target. If there are
694
+ cycles among the predecessors, this function will not produce all
695
+ possible paths because doing so would produce infinitely many paths
696
+ of unbounded length -- instead, we only produce simple paths.
697
+
698
+ See Also
699
+ --------
700
+ shortest_path
701
+ single_source_shortest_path
702
+ all_pairs_shortest_path
703
+ all_shortest_paths
704
+ bellman_ford_path
705
+ """
706
+ if target not in pred:
707
+ raise nx.NetworkXNoPath(f"Target {target} cannot be reached from given sources")
708
+
709
+ seen = {target}
710
+ stack = [[target, 0]]
711
+ top = 0
712
+ while top >= 0:
713
+ node, i = stack[top]
714
+ if node in sources:
715
+ yield [p for p, n in reversed(stack[: top + 1])]
716
+ if len(pred[node]) > i:
717
+ stack[top][1] = i + 1
718
+ next = pred[node][i]
719
+ if next in seen:
720
+ continue
721
+ else:
722
+ seen.add(next)
723
+ top += 1
724
+ if top == len(stack):
725
+ stack.append([next, 0])
726
+ else:
727
+ stack[top][:] = [next, 0]
728
+ else:
729
+ seen.discard(node)
730
+ top -= 1
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_astar.cpython-310.pyc ADDED
Binary file (9.7 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_dense.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_dense_numpy.cpython-310.pyc ADDED
Binary file (2.85 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_generic.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_unweighted.cpython-310.pyc ADDED
Binary file (7.03 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_weighted.cpython-310.pyc ADDED
Binary file (30 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_astar.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+
7
+ class TestAStar:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ edges = [
11
+ ("s", "u", 10),
12
+ ("s", "x", 5),
13
+ ("u", "v", 1),
14
+ ("u", "x", 2),
15
+ ("v", "y", 1),
16
+ ("x", "u", 3),
17
+ ("x", "v", 5),
18
+ ("x", "y", 2),
19
+ ("y", "s", 7),
20
+ ("y", "v", 6),
21
+ ]
22
+ cls.XG = nx.DiGraph()
23
+ cls.XG.add_weighted_edges_from(edges)
24
+
25
+ def test_multiple_optimal_paths(self):
26
+ """Tests that A* algorithm finds any of multiple optimal paths"""
27
+ heuristic_values = {"a": 1.35, "b": 1.18, "c": 0.67, "d": 0}
28
+
29
+ def h(u, v):
30
+ return heuristic_values[u]
31
+
32
+ graph = nx.Graph()
33
+ points = ["a", "b", "c", "d"]
34
+ edges = [("a", "b", 0.18), ("a", "c", 0.68), ("b", "c", 0.50), ("c", "d", 0.67)]
35
+
36
+ graph.add_nodes_from(points)
37
+ graph.add_weighted_edges_from(edges)
38
+
39
+ path1 = ["a", "c", "d"]
40
+ path2 = ["a", "b", "c", "d"]
41
+ assert nx.astar_path(graph, "a", "d", h) in (path1, path2)
42
+
43
+ def test_astar_directed(self):
44
+ assert nx.astar_path(self.XG, "s", "v") == ["s", "x", "u", "v"]
45
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
46
+
47
+ def test_astar_directed_weight_function(self):
48
+ w1 = lambda u, v, d: d["weight"]
49
+ assert nx.astar_path(self.XG, "x", "u", weight=w1) == ["x", "u"]
50
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w1) == 3
51
+ assert nx.astar_path(self.XG, "s", "v", weight=w1) == ["s", "x", "u", "v"]
52
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w1) == 9
53
+
54
+ w2 = lambda u, v, d: None if (u, v) == ("x", "u") else d["weight"]
55
+ assert nx.astar_path(self.XG, "x", "u", weight=w2) == ["x", "y", "s", "u"]
56
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w2) == 19
57
+ assert nx.astar_path(self.XG, "s", "v", weight=w2) == ["s", "x", "v"]
58
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w2) == 10
59
+
60
+ w3 = lambda u, v, d: d["weight"] + 10
61
+ assert nx.astar_path(self.XG, "x", "u", weight=w3) == ["x", "u"]
62
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w3) == 13
63
+ assert nx.astar_path(self.XG, "s", "v", weight=w3) == ["s", "x", "v"]
64
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w3) == 30
65
+
66
+ def test_astar_multigraph(self):
67
+ G = nx.MultiDiGraph(self.XG)
68
+ G.add_weighted_edges_from((u, v, 1000) for (u, v) in list(G.edges()))
69
+ assert nx.astar_path(G, "s", "v") == ["s", "x", "u", "v"]
70
+ assert nx.astar_path_length(G, "s", "v") == 9
71
+
72
+ def test_astar_undirected(self):
73
+ GG = self.XG.to_undirected()
74
+ # make sure we get lower weight
75
+ # to_undirected might choose either edge with weight 2 or weight 3
76
+ GG["u"]["x"]["weight"] = 2
77
+ GG["y"]["v"]["weight"] = 2
78
+ assert nx.astar_path(GG, "s", "v") == ["s", "x", "u", "v"]
79
+ assert nx.astar_path_length(GG, "s", "v") == 8
80
+
81
+ def test_astar_directed2(self):
82
+ XG2 = nx.DiGraph()
83
+ edges = [
84
+ (1, 4, 1),
85
+ (4, 5, 1),
86
+ (5, 6, 1),
87
+ (6, 3, 1),
88
+ (1, 3, 50),
89
+ (1, 2, 100),
90
+ (2, 3, 100),
91
+ ]
92
+ XG2.add_weighted_edges_from(edges)
93
+ assert nx.astar_path(XG2, 1, 3) == [1, 4, 5, 6, 3]
94
+
95
+ def test_astar_undirected2(self):
96
+ XG3 = nx.Graph()
97
+ edges = [(0, 1, 2), (1, 2, 12), (2, 3, 1), (3, 4, 5), (4, 5, 1), (5, 0, 10)]
98
+ XG3.add_weighted_edges_from(edges)
99
+ assert nx.astar_path(XG3, 0, 3) == [0, 1, 2, 3]
100
+ assert nx.astar_path_length(XG3, 0, 3) == 15
101
+
102
+ def test_astar_undirected3(self):
103
+ XG4 = nx.Graph()
104
+ edges = [
105
+ (0, 1, 2),
106
+ (1, 2, 2),
107
+ (2, 3, 1),
108
+ (3, 4, 1),
109
+ (4, 5, 1),
110
+ (5, 6, 1),
111
+ (6, 7, 1),
112
+ (7, 0, 1),
113
+ ]
114
+ XG4.add_weighted_edges_from(edges)
115
+ assert nx.astar_path(XG4, 0, 2) == [0, 1, 2]
116
+ assert nx.astar_path_length(XG4, 0, 2) == 4
117
+
118
+ """ Tests that A* finds correct path when multiple paths exist
119
+ and the best one is not expanded first (GH issue #3464)
120
+ """
121
+
122
+ def test_astar_directed3(self):
123
+ heuristic_values = {"n5": 36, "n2": 4, "n1": 0, "n0": 0}
124
+
125
+ def h(u, v):
126
+ return heuristic_values[u]
127
+
128
+ edges = [("n5", "n1", 11), ("n5", "n2", 9), ("n2", "n1", 1), ("n1", "n0", 32)]
129
+ graph = nx.DiGraph()
130
+ graph.add_weighted_edges_from(edges)
131
+ answer = ["n5", "n2", "n1", "n0"]
132
+ assert nx.astar_path(graph, "n5", "n0", h) == answer
133
+
134
+ """ Tests that parent is not wrongly overridden when a node
135
+ is re-explored multiple times.
136
+ """
137
+
138
+ def test_astar_directed4(self):
139
+ edges = [
140
+ ("a", "b", 1),
141
+ ("a", "c", 1),
142
+ ("b", "d", 2),
143
+ ("c", "d", 1),
144
+ ("d", "e", 1),
145
+ ]
146
+ graph = nx.DiGraph()
147
+ graph.add_weighted_edges_from(edges)
148
+ assert nx.astar_path(graph, "a", "e") == ["a", "c", "d", "e"]
149
+
150
+ # >>> MXG4=NX.MultiGraph(XG4)
151
+ # >>> MXG4.add_edge(0,1,3)
152
+ # >>> NX.dijkstra_path(MXG4,0,2)
153
+ # [0, 1, 2]
154
+
155
+ def test_astar_w1(self):
156
+ G = nx.DiGraph()
157
+ G.add_edges_from(
158
+ [
159
+ ("s", "u"),
160
+ ("s", "x"),
161
+ ("u", "v"),
162
+ ("u", "x"),
163
+ ("v", "y"),
164
+ ("x", "u"),
165
+ ("x", "w"),
166
+ ("w", "v"),
167
+ ("x", "y"),
168
+ ("y", "s"),
169
+ ("y", "v"),
170
+ ]
171
+ )
172
+ assert nx.astar_path(G, "s", "v") == ["s", "u", "v"]
173
+ assert nx.astar_path_length(G, "s", "v") == 2
174
+
175
+ def test_astar_nopath(self):
176
+ with pytest.raises(nx.NodeNotFound):
177
+ nx.astar_path(self.XG, "s", "moon")
178
+
179
+ def test_astar_cutoff(self):
180
+ with pytest.raises(nx.NetworkXNoPath):
181
+ # optimal path_length in XG is 9
182
+ nx.astar_path(self.XG, "s", "v", cutoff=8.0)
183
+ with pytest.raises(nx.NetworkXNoPath):
184
+ nx.astar_path_length(self.XG, "s", "v", cutoff=8.0)
185
+
186
+ def test_astar_admissible_heuristic_with_cutoff(self):
187
+ heuristic_values = {"s": 36, "y": 4, "x": 0, "u": 0, "v": 0}
188
+
189
+ def h(u, v):
190
+ return heuristic_values[u]
191
+
192
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
193
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h) == 9
194
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=12) == 9
195
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=9) == 9
196
+ with pytest.raises(nx.NetworkXNoPath):
197
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=8)
198
+
199
+ def test_astar_inadmissible_heuristic_with_cutoff(self):
200
+ heuristic_values = {"s": 36, "y": 14, "x": 10, "u": 10, "v": 0}
201
+
202
+ def h(u, v):
203
+ return heuristic_values[u]
204
+
205
+ # optimal path_length in XG is 9. This heuristic gives over-estimate.
206
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h) == 10
207
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=15) == 10
208
+ with pytest.raises(nx.NetworkXNoPath):
209
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=9)
210
+ with pytest.raises(nx.NetworkXNoPath):
211
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=12)
212
+
213
+ def test_astar_cutoff2(self):
214
+ assert nx.astar_path(self.XG, "s", "v", cutoff=10.0) == ["s", "x", "u", "v"]
215
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
216
+
217
+ def test_cycle(self):
218
+ C = nx.cycle_graph(7)
219
+ assert nx.astar_path(C, 0, 3) == [0, 1, 2, 3]
220
+ assert nx.dijkstra_path(C, 0, 4) == [0, 6, 5, 4]
221
+
222
+ def test_unorderable_nodes(self):
223
+ """Tests that A* accommodates nodes that are not orderable.
224
+
225
+ For more information, see issue #554.
226
+
227
+ """
228
+ # Create the cycle graph on four nodes, with nodes represented
229
+ # as (unorderable) Python objects.
230
+ nodes = [object() for n in range(4)]
231
+ G = nx.Graph()
232
+ G.add_edges_from(pairwise(nodes, cyclic=True))
233
+ path = nx.astar_path(G, nodes[0], nodes[2])
234
+ assert len(path) == 3
235
+
236
+ def test_astar_NetworkXNoPath(self):
237
+ """Tests that exception is raised when there exists no
238
+ path between source and target"""
239
+ G = nx.gnp_random_graph(10, 0.2, seed=10)
240
+ with pytest.raises(nx.NetworkXNoPath):
241
+ nx.astar_path(G, 4, 9)
242
+
243
+ def test_astar_NodeNotFound(self):
244
+ """Tests that exception is raised when either
245
+ source or target is not in graph"""
246
+ G = nx.gnp_random_graph(10, 0.2, seed=10)
247
+ with pytest.raises(nx.NodeNotFound):
248
+ nx.astar_path_length(G, 11, 9)
llava_next/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestFloyd:
7
+ @classmethod
8
+ def setup_class(cls):
9
+ pass
10
+
11
+ def test_floyd_warshall_predecessor_and_distance(self):
12
+ XG = nx.DiGraph()
13
+ XG.add_weighted_edges_from(
14
+ [
15
+ ("s", "u", 10),
16
+ ("s", "x", 5),
17
+ ("u", "v", 1),
18
+ ("u", "x", 2),
19
+ ("v", "y", 1),
20
+ ("x", "u", 3),
21
+ ("x", "v", 5),
22
+ ("x", "y", 2),
23
+ ("y", "s", 7),
24
+ ("y", "v", 6),
25
+ ]
26
+ )
27
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
28
+ assert dist["s"]["v"] == 9
29
+ assert path["s"]["v"] == "u"
30
+ assert dist == {
31
+ "y": {"y": 0, "x": 12, "s": 7, "u": 15, "v": 6},
32
+ "x": {"y": 2, "x": 0, "s": 9, "u": 3, "v": 4},
33
+ "s": {"y": 7, "x": 5, "s": 0, "u": 8, "v": 9},
34
+ "u": {"y": 2, "x": 2, "s": 9, "u": 0, "v": 1},
35
+ "v": {"y": 1, "x": 13, "s": 8, "u": 16, "v": 0},
36
+ }
37
+
38
+ GG = XG.to_undirected()
39
+ # make sure we get lower weight
40
+ # to_undirected might choose either edge with weight 2 or weight 3
41
+ GG["u"]["x"]["weight"] = 2
42
+ path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
43
+ assert dist["s"]["v"] == 8
44
+ # skip this test, could be alternate path s-u-v
45
+ # assert_equal(path['s']['v'],'y')
46
+
47
+ G = nx.DiGraph() # no weights
48
+ G.add_edges_from(
49
+ [
50
+ ("s", "u"),
51
+ ("s", "x"),
52
+ ("u", "v"),
53
+ ("u", "x"),
54
+ ("v", "y"),
55
+ ("x", "u"),
56
+ ("x", "v"),
57
+ ("x", "y"),
58
+ ("y", "s"),
59
+ ("y", "v"),
60
+ ]
61
+ )
62
+ path, dist = nx.floyd_warshall_predecessor_and_distance(G)
63
+ assert dist["s"]["v"] == 2
64
+ # skip this test, could be alternate path s-u-v
65
+ # assert_equal(path['s']['v'],'x')
66
+
67
+ # alternate interface
68
+ dist = nx.floyd_warshall(G)
69
+ assert dist["s"]["v"] == 2
70
+
71
+ # floyd_warshall_predecessor_and_distance returns
72
+ # dicts-of-defautdicts
73
+ # make sure we don't get empty dictionary
74
+ XG = nx.DiGraph()
75
+ XG.add_weighted_edges_from(
76
+ [("v", "x", 5.0), ("y", "x", 5.0), ("v", "y", 6.0), ("x", "u", 2.0)]
77
+ )
78
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
79
+ inf = float("inf")
80
+ assert dist == {
81
+ "v": {"v": 0, "x": 5.0, "y": 6.0, "u": 7.0},
82
+ "x": {"x": 0, "u": 2.0, "v": inf, "y": inf},
83
+ "y": {"y": 0, "x": 5.0, "v": inf, "u": 7.0},
84
+ "u": {"u": 0, "v": inf, "x": inf, "y": inf},
85
+ }
86
+ assert path == {
87
+ "v": {"x": "v", "y": "v", "u": "x"},
88
+ "x": {"u": "x"},
89
+ "y": {"x": "y", "u": "x"},
90
+ }
91
+
92
+ def test_reconstruct_path(self):
93
+ with pytest.raises(KeyError):
94
+ XG = nx.DiGraph()
95
+ XG.add_weighted_edges_from(
96
+ [
97
+ ("s", "u", 10),
98
+ ("s", "x", 5),
99
+ ("u", "v", 1),
100
+ ("u", "x", 2),
101
+ ("v", "y", 1),
102
+ ("x", "u", 3),
103
+ ("x", "v", 5),
104
+ ("x", "y", 2),
105
+ ("y", "s", 7),
106
+ ("y", "v", 6),
107
+ ]
108
+ )
109
+ predecessors, _ = nx.floyd_warshall_predecessor_and_distance(XG)
110
+
111
+ path = nx.reconstruct_path("s", "v", predecessors)
112
+ assert path == ["s", "x", "u", "v"]
113
+
114
+ path = nx.reconstruct_path("s", "s", predecessors)
115
+ assert path == []
116
+
117
+ # this part raises the keyError
118
+ nx.reconstruct_path("1", "2", predecessors)
119
+
120
+ def test_cycle(self):
121
+ path, dist = nx.floyd_warshall_predecessor_and_distance(nx.cycle_graph(7))
122
+ assert dist[0][3] == 3
123
+ assert path[0][3] == 2
124
+ assert dist[0][4] == 3
125
+
126
+ def test_weighted(self):
127
+ XG3 = nx.Graph()
128
+ XG3.add_weighted_edges_from(
129
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
130
+ )
131
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG3)
132
+ assert dist[0][3] == 15
133
+ assert path[0][3] == 2
134
+
135
+ def test_weighted2(self):
136
+ XG4 = nx.Graph()
137
+ XG4.add_weighted_edges_from(
138
+ [
139
+ [0, 1, 2],
140
+ [1, 2, 2],
141
+ [2, 3, 1],
142
+ [3, 4, 1],
143
+ [4, 5, 1],
144
+ [5, 6, 1],
145
+ [6, 7, 1],
146
+ [7, 0, 1],
147
+ ]
148
+ )
149
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG4)
150
+ assert dist[0][2] == 4
151
+ assert path[0][2] == 1
152
+
153
+ def test_weight_parameter(self):
154
+ XG4 = nx.Graph()
155
+ XG4.add_edges_from(
156
+ [
157
+ (0, 1, {"heavy": 2}),
158
+ (1, 2, {"heavy": 2}),
159
+ (2, 3, {"heavy": 1}),
160
+ (3, 4, {"heavy": 1}),
161
+ (4, 5, {"heavy": 1}),
162
+ (5, 6, {"heavy": 1}),
163
+ (6, 7, {"heavy": 1}),
164
+ (7, 0, {"heavy": 1}),
165
+ ]
166
+ )
167
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG4, weight="heavy")
168
+ assert dist[0][2] == 4
169
+ assert path[0][2] == 1
170
+
171
+ def test_zero_distance(self):
172
+ XG = nx.DiGraph()
173
+ XG.add_weighted_edges_from(
174
+ [
175
+ ("s", "u", 10),
176
+ ("s", "x", 5),
177
+ ("u", "v", 1),
178
+ ("u", "x", 2),
179
+ ("v", "y", 1),
180
+ ("x", "u", 3),
181
+ ("x", "v", 5),
182
+ ("x", "y", 2),
183
+ ("y", "s", 7),
184
+ ("y", "v", 6),
185
+ ]
186
+ )
187
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
188
+
189
+ for u in XG:
190
+ assert dist[u][u] == 0
191
+
192
+ GG = XG.to_undirected()
193
+ # make sure we get lower weight
194
+ # to_undirected might choose either edge with weight 2 or weight 3
195
+ GG["u"]["x"]["weight"] = 2
196
+ path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
197
+
198
+ for u in GG:
199
+ dist[u][u] = 0
200
+
201
+ def test_zero_weight(self):
202
+ G = nx.DiGraph()
203
+ edges = [(1, 2, -2), (2, 3, -4), (1, 5, 1), (5, 4, 0), (4, 3, -5), (2, 5, -7)]
204
+ G.add_weighted_edges_from(edges)
205
+ dist = nx.floyd_warshall(G)
206
+ assert dist[1][3] == -14
207
+
208
+ G = nx.MultiDiGraph()
209
+ edges.append((2, 5, -7))
210
+ G.add_weighted_edges_from(edges)
211
+ dist = nx.floyd_warshall(G)
212
+ assert dist[1][3] == -14