ZTWHHH commited on
Commit
a1cb99a
·
verified ·
1 Parent(s): ba0f478

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. evalkit_cambrian/lib/python3.10/_compression.py +162 -0
  2. evalkit_cambrian/lib/python3.10/_py_abc.py +147 -0
  3. evalkit_cambrian/lib/python3.10/_sitebuiltins.py +103 -0
  4. evalkit_cambrian/lib/python3.10/cmd.py +401 -0
  5. evalkit_cambrian/lib/python3.10/imp.py +346 -0
  6. evalkit_cambrian/lib/python3.10/inspect.py +0 -0
  7. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/__init__.cpython-310.pyc +0 -0
  8. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/conftest.cpython-310.pyc +0 -0
  9. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/convert.cpython-310.pyc +0 -0
  10. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/convert_matrix.cpython-310.pyc +0 -0
  11. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/exception.cpython-310.pyc +0 -0
  12. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/lazy_imports.cpython-310.pyc +0 -0
  13. evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/relabel.cpython-310.pyc +0 -0
  14. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/__init__.py +13 -0
  15. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/coreviews.py +431 -0
  16. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/digraph.py +1352 -0
  17. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/filters.py +95 -0
  18. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/function.py +1407 -0
  19. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/graph.py +2058 -0
  20. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/graphviews.py +269 -0
  21. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/multidigraph.py +966 -0
  22. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/multigraph.py +1283 -0
  23. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/reportviews.py +1447 -0
  24. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/__init__.py +0 -0
  25. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py +185 -0
  26. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py +177 -0
  27. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_graph_historical.py +13 -0
  28. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_multidigraph.py +459 -0
  29. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_multigraph.py +528 -0
  30. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_reportviews.py +1435 -0
  31. evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_subgraphviews.py +362 -0
  32. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc +0 -0
  33. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc +0 -0
  34. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc +0 -0
  35. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc +0 -0
  36. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc +0 -0
  37. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc +0 -0
  38. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc +0 -0
  39. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc +0 -0
  40. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc +0 -0
  41. evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/test_random_clustered.py +33 -0
  42. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc +0 -0
  43. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc +0 -0
  44. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc +0 -0
  45. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc +0 -0
  46. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc +0 -0
  47. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc +0 -0
  48. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc +0 -0
  49. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc +0 -0
  50. evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc +0 -0
evalkit_cambrian/lib/python3.10/_compression.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal classes used by the gzip, lzma and bz2 modules"""
2
+
3
+ import io
4
+ import sys
5
+
6
+ BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE # Compressed data read chunk size
7
+
8
+
9
+ class BaseStream(io.BufferedIOBase):
10
+ """Mode-checking helper functions."""
11
+
12
+ def _check_not_closed(self):
13
+ if self.closed:
14
+ raise ValueError("I/O operation on closed file")
15
+
16
+ def _check_can_read(self):
17
+ if not self.readable():
18
+ raise io.UnsupportedOperation("File not open for reading")
19
+
20
+ def _check_can_write(self):
21
+ if not self.writable():
22
+ raise io.UnsupportedOperation("File not open for writing")
23
+
24
+ def _check_can_seek(self):
25
+ if not self.readable():
26
+ raise io.UnsupportedOperation("Seeking is only supported "
27
+ "on files open for reading")
28
+ if not self.seekable():
29
+ raise io.UnsupportedOperation("The underlying file object "
30
+ "does not support seeking")
31
+
32
+
33
+ class DecompressReader(io.RawIOBase):
34
+ """Adapts the decompressor API to a RawIOBase reader API"""
35
+
36
+ def readable(self):
37
+ return True
38
+
39
+ def __init__(self, fp, decomp_factory, trailing_error=(), **decomp_args):
40
+ self._fp = fp
41
+ self._eof = False
42
+ self._pos = 0 # Current offset in decompressed stream
43
+
44
+ # Set to size of decompressed stream once it is known, for SEEK_END
45
+ self._size = -1
46
+
47
+ # Save the decompressor factory and arguments.
48
+ # If the file contains multiple compressed streams, each
49
+ # stream will need a separate decompressor object. A new decompressor
50
+ # object is also needed when implementing a backwards seek().
51
+ self._decomp_factory = decomp_factory
52
+ self._decomp_args = decomp_args
53
+ self._decompressor = self._decomp_factory(**self._decomp_args)
54
+
55
+ # Exception class to catch from decompressor signifying invalid
56
+ # trailing data to ignore
57
+ self._trailing_error = trailing_error
58
+
59
+ def close(self):
60
+ self._decompressor = None
61
+ return super().close()
62
+
63
+ def seekable(self):
64
+ return self._fp.seekable()
65
+
66
+ def readinto(self, b):
67
+ with memoryview(b) as view, view.cast("B") as byte_view:
68
+ data = self.read(len(byte_view))
69
+ byte_view[:len(data)] = data
70
+ return len(data)
71
+
72
+ def read(self, size=-1):
73
+ if size < 0:
74
+ return self.readall()
75
+
76
+ if not size or self._eof:
77
+ return b""
78
+ data = None # Default if EOF is encountered
79
+ # Depending on the input data, our call to the decompressor may not
80
+ # return any data. In this case, try again after reading another block.
81
+ while True:
82
+ if self._decompressor.eof:
83
+ rawblock = (self._decompressor.unused_data or
84
+ self._fp.read(BUFFER_SIZE))
85
+ if not rawblock:
86
+ break
87
+ # Continue to next stream.
88
+ self._decompressor = self._decomp_factory(
89
+ **self._decomp_args)
90
+ try:
91
+ data = self._decompressor.decompress(rawblock, size)
92
+ except self._trailing_error:
93
+ # Trailing data isn't a valid compressed stream; ignore it.
94
+ break
95
+ else:
96
+ if self._decompressor.needs_input:
97
+ rawblock = self._fp.read(BUFFER_SIZE)
98
+ if not rawblock:
99
+ raise EOFError("Compressed file ended before the "
100
+ "end-of-stream marker was reached")
101
+ else:
102
+ rawblock = b""
103
+ data = self._decompressor.decompress(rawblock, size)
104
+ if data:
105
+ break
106
+ if not data:
107
+ self._eof = True
108
+ self._size = self._pos
109
+ return b""
110
+ self._pos += len(data)
111
+ return data
112
+
113
+ def readall(self):
114
+ chunks = []
115
+ # sys.maxsize means the max length of output buffer is unlimited,
116
+ # so that the whole input buffer can be decompressed within one
117
+ # .decompress() call.
118
+ while data := self.read(sys.maxsize):
119
+ chunks.append(data)
120
+
121
+ return b"".join(chunks)
122
+
123
+ # Rewind the file to the beginning of the data stream.
124
+ def _rewind(self):
125
+ self._fp.seek(0)
126
+ self._eof = False
127
+ self._pos = 0
128
+ self._decompressor = self._decomp_factory(**self._decomp_args)
129
+
130
+ def seek(self, offset, whence=io.SEEK_SET):
131
+ # Recalculate offset as an absolute file position.
132
+ if whence == io.SEEK_SET:
133
+ pass
134
+ elif whence == io.SEEK_CUR:
135
+ offset = self._pos + offset
136
+ elif whence == io.SEEK_END:
137
+ # Seeking relative to EOF - we need to know the file's size.
138
+ if self._size < 0:
139
+ while self.read(io.DEFAULT_BUFFER_SIZE):
140
+ pass
141
+ offset = self._size + offset
142
+ else:
143
+ raise ValueError("Invalid value for whence: {}".format(whence))
144
+
145
+ # Make it so that offset is the number of bytes to skip forward.
146
+ if offset < self._pos:
147
+ self._rewind()
148
+ else:
149
+ offset -= self._pos
150
+
151
+ # Read and discard data until we reach the desired position.
152
+ while offset > 0:
153
+ data = self.read(min(io.DEFAULT_BUFFER_SIZE, offset))
154
+ if not data:
155
+ break
156
+ offset -= len(data)
157
+
158
+ return self._pos
159
+
160
+ def tell(self):
161
+ """Return the current file position."""
162
+ return self._pos
evalkit_cambrian/lib/python3.10/_py_abc.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _weakrefset import WeakSet
2
+
3
+
4
+ def get_cache_token():
5
+ """Returns the current ABC cache token.
6
+
7
+ The token is an opaque object (supporting equality testing) identifying the
8
+ current version of the ABC cache for virtual subclasses. The token changes
9
+ with every call to ``register()`` on any ABC.
10
+ """
11
+ return ABCMeta._abc_invalidation_counter
12
+
13
+
14
+ class ABCMeta(type):
15
+ """Metaclass for defining Abstract Base Classes (ABCs).
16
+
17
+ Use this metaclass to create an ABC. An ABC can be subclassed
18
+ directly, and then acts as a mix-in class. You can also register
19
+ unrelated concrete classes (even built-in classes) and unrelated
20
+ ABCs as 'virtual subclasses' -- these and their descendants will
21
+ be considered subclasses of the registering ABC by the built-in
22
+ issubclass() function, but the registering ABC won't show up in
23
+ their MRO (Method Resolution Order) nor will method
24
+ implementations defined by the registering ABC be callable (not
25
+ even via super()).
26
+ """
27
+
28
+ # A global counter that is incremented each time a class is
29
+ # registered as a virtual subclass of anything. It forces the
30
+ # negative cache to be cleared before its next use.
31
+ # Note: this counter is private. Use `abc.get_cache_token()` for
32
+ # external code.
33
+ _abc_invalidation_counter = 0
34
+
35
+ def __new__(mcls, name, bases, namespace, /, **kwargs):
36
+ cls = super().__new__(mcls, name, bases, namespace, **kwargs)
37
+ # Compute set of abstract method names
38
+ abstracts = {name
39
+ for name, value in namespace.items()
40
+ if getattr(value, "__isabstractmethod__", False)}
41
+ for base in bases:
42
+ for name in getattr(base, "__abstractmethods__", set()):
43
+ value = getattr(cls, name, None)
44
+ if getattr(value, "__isabstractmethod__", False):
45
+ abstracts.add(name)
46
+ cls.__abstractmethods__ = frozenset(abstracts)
47
+ # Set up inheritance registry
48
+ cls._abc_registry = WeakSet()
49
+ cls._abc_cache = WeakSet()
50
+ cls._abc_negative_cache = WeakSet()
51
+ cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
52
+ return cls
53
+
54
+ def register(cls, subclass):
55
+ """Register a virtual subclass of an ABC.
56
+
57
+ Returns the subclass, to allow usage as a class decorator.
58
+ """
59
+ if not isinstance(subclass, type):
60
+ raise TypeError("Can only register classes")
61
+ if issubclass(subclass, cls):
62
+ return subclass # Already a subclass
63
+ # Subtle: test for cycles *after* testing for "already a subclass";
64
+ # this means we allow X.register(X) and interpret it as a no-op.
65
+ if issubclass(cls, subclass):
66
+ # This would create a cycle, which is bad for the algorithm below
67
+ raise RuntimeError("Refusing to create an inheritance cycle")
68
+ cls._abc_registry.add(subclass)
69
+ ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
70
+ return subclass
71
+
72
+ def _dump_registry(cls, file=None):
73
+ """Debug helper to print the ABC registry."""
74
+ print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
75
+ print(f"Inv. counter: {get_cache_token()}", file=file)
76
+ for name in cls.__dict__:
77
+ if name.startswith("_abc_"):
78
+ value = getattr(cls, name)
79
+ if isinstance(value, WeakSet):
80
+ value = set(value)
81
+ print(f"{name}: {value!r}", file=file)
82
+
83
+ def _abc_registry_clear(cls):
84
+ """Clear the registry (for debugging or testing)."""
85
+ cls._abc_registry.clear()
86
+
87
+ def _abc_caches_clear(cls):
88
+ """Clear the caches (for debugging or testing)."""
89
+ cls._abc_cache.clear()
90
+ cls._abc_negative_cache.clear()
91
+
92
+ def __instancecheck__(cls, instance):
93
+ """Override for isinstance(instance, cls)."""
94
+ # Inline the cache checking
95
+ subclass = instance.__class__
96
+ if subclass in cls._abc_cache:
97
+ return True
98
+ subtype = type(instance)
99
+ if subtype is subclass:
100
+ if (cls._abc_negative_cache_version ==
101
+ ABCMeta._abc_invalidation_counter and
102
+ subclass in cls._abc_negative_cache):
103
+ return False
104
+ # Fall back to the subclass check.
105
+ return cls.__subclasscheck__(subclass)
106
+ return any(cls.__subclasscheck__(c) for c in (subclass, subtype))
107
+
108
+ def __subclasscheck__(cls, subclass):
109
+ """Override for issubclass(subclass, cls)."""
110
+ if not isinstance(subclass, type):
111
+ raise TypeError('issubclass() arg 1 must be a class')
112
+ # Check cache
113
+ if subclass in cls._abc_cache:
114
+ return True
115
+ # Check negative cache; may have to invalidate
116
+ if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
117
+ # Invalidate the negative cache
118
+ cls._abc_negative_cache = WeakSet()
119
+ cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
120
+ elif subclass in cls._abc_negative_cache:
121
+ return False
122
+ # Check the subclass hook
123
+ ok = cls.__subclasshook__(subclass)
124
+ if ok is not NotImplemented:
125
+ assert isinstance(ok, bool)
126
+ if ok:
127
+ cls._abc_cache.add(subclass)
128
+ else:
129
+ cls._abc_negative_cache.add(subclass)
130
+ return ok
131
+ # Check if it's a direct subclass
132
+ if cls in getattr(subclass, '__mro__', ()):
133
+ cls._abc_cache.add(subclass)
134
+ return True
135
+ # Check if it's a subclass of a registered class (recursive)
136
+ for rcls in cls._abc_registry:
137
+ if issubclass(subclass, rcls):
138
+ cls._abc_cache.add(subclass)
139
+ return True
140
+ # Check if it's a subclass of a subclass (recursive)
141
+ for scls in cls.__subclasses__():
142
+ if issubclass(subclass, scls):
143
+ cls._abc_cache.add(subclass)
144
+ return True
145
+ # No dice; update negative cache
146
+ cls._abc_negative_cache.add(subclass)
147
+ return False
evalkit_cambrian/lib/python3.10/_sitebuiltins.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The objects used by the site module to add custom builtins.
3
+ """
4
+
5
+ # Those objects are almost immortal and they keep a reference to their module
6
+ # globals. Defining them in the site module would keep too many references
7
+ # alive.
8
+ # Note this means this module should also avoid keep things alive in its
9
+ # globals.
10
+
11
+ import sys
12
+
13
+ class Quitter(object):
14
+ def __init__(self, name, eof):
15
+ self.name = name
16
+ self.eof = eof
17
+ def __repr__(self):
18
+ return 'Use %s() or %s to exit' % (self.name, self.eof)
19
+ def __call__(self, code=None):
20
+ # Shells like IDLE catch the SystemExit, but listen when their
21
+ # stdin wrapper is closed.
22
+ try:
23
+ sys.stdin.close()
24
+ except:
25
+ pass
26
+ raise SystemExit(code)
27
+
28
+
29
+ class _Printer(object):
30
+ """interactive prompt objects for printing the license text, a list of
31
+ contributors and the copyright notice."""
32
+
33
+ MAXLINES = 23
34
+
35
+ def __init__(self, name, data, files=(), dirs=()):
36
+ import os
37
+ self.__name = name
38
+ self.__data = data
39
+ self.__lines = None
40
+ self.__filenames = [os.path.join(dir, filename)
41
+ for dir in dirs
42
+ for filename in files]
43
+
44
+ def __setup(self):
45
+ if self.__lines:
46
+ return
47
+ data = None
48
+ for filename in self.__filenames:
49
+ try:
50
+ with open(filename, encoding='utf-8') as fp:
51
+ data = fp.read()
52
+ break
53
+ except OSError:
54
+ pass
55
+ if not data:
56
+ data = self.__data
57
+ self.__lines = data.split('\n')
58
+ self.__linecnt = len(self.__lines)
59
+
60
+ def __repr__(self):
61
+ self.__setup()
62
+ if len(self.__lines) <= self.MAXLINES:
63
+ return "\n".join(self.__lines)
64
+ else:
65
+ return "Type %s() to see the full %s text" % ((self.__name,)*2)
66
+
67
+ def __call__(self):
68
+ self.__setup()
69
+ prompt = 'Hit Return for more, or q (and Return) to quit: '
70
+ lineno = 0
71
+ while 1:
72
+ try:
73
+ for i in range(lineno, lineno + self.MAXLINES):
74
+ print(self.__lines[i])
75
+ except IndexError:
76
+ break
77
+ else:
78
+ lineno += self.MAXLINES
79
+ key = None
80
+ while key is None:
81
+ key = input(prompt)
82
+ if key not in ('', 'q'):
83
+ key = None
84
+ if key == 'q':
85
+ break
86
+
87
+
88
+ class _Helper(object):
89
+ """Define the builtin 'help'.
90
+
91
+ This is a wrapper around pydoc.help that provides a helpful message
92
+ when 'help' is typed at the Python interactive prompt.
93
+
94
+ Calling help() at the Python prompt starts an interactive help session.
95
+ Calling help(thing) prints help for the python object 'thing'.
96
+ """
97
+
98
+ def __repr__(self):
99
+ return "Type help() for interactive help, " \
100
+ "or help(object) for help about object."
101
+ def __call__(self, *args, **kwds):
102
+ import pydoc
103
+ return pydoc.help(*args, **kwds)
evalkit_cambrian/lib/python3.10/cmd.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A generic class to build line-oriented command interpreters.
2
+
3
+ Interpreters constructed with this class obey the following conventions:
4
+
5
+ 1. End of file on input is processed as the command 'EOF'.
6
+ 2. A command is parsed out of each line by collecting the prefix composed
7
+ of characters in the identchars member.
8
+ 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method
9
+ is passed a single argument consisting of the remainder of the line.
10
+ 4. Typing an empty line repeats the last command. (Actually, it calls the
11
+ method `emptyline', which may be overridden in a subclass.)
12
+ 5. There is a predefined `help' method. Given an argument `topic', it
13
+ calls the command `help_topic'. With no arguments, it lists all topics
14
+ with defined help_ functions, broken into up to three topics; documented
15
+ commands, miscellaneous help topics, and undocumented commands.
16
+ 6. The command '?' is a synonym for `help'. The command '!' is a synonym
17
+ for `shell', if a do_shell method exists.
18
+ 7. If completion is enabled, completing commands will be done automatically,
19
+ and completing of commands args is done by calling complete_foo() with
20
+ arguments text, line, begidx, endidx. text is string we are matching
21
+ against, all returned matches must begin with it. line is the current
22
+ input line (lstripped), begidx and endidx are the beginning and end
23
+ indexes of the text being matched, which could be used to provide
24
+ different completion depending upon which position the argument is in.
25
+
26
+ The `default' method may be overridden to intercept commands for which there
27
+ is no do_ method.
28
+
29
+ The `completedefault' method may be overridden to intercept completions for
30
+ commands that have no complete_ method.
31
+
32
+ The data member `self.ruler' sets the character used to draw separator lines
33
+ in the help messages. If empty, no ruler line is drawn. It defaults to "=".
34
+
35
+ If the value of `self.intro' is nonempty when the cmdloop method is called,
36
+ it is printed out on interpreter startup. This value may be overridden
37
+ via an optional argument to the cmdloop() method.
38
+
39
+ The data members `self.doc_header', `self.misc_header', and
40
+ `self.undoc_header' set the headers used for the help function's
41
+ listings of documented functions, miscellaneous topics, and undocumented
42
+ functions respectively.
43
+ """
44
+
45
+ import string, sys
46
+
47
+ __all__ = ["Cmd"]
48
+
49
+ PROMPT = '(Cmd) '
50
+ IDENTCHARS = string.ascii_letters + string.digits + '_'
51
+
52
+ class Cmd:
53
+ """A simple framework for writing line-oriented command interpreters.
54
+
55
+ These are often useful for test harnesses, administrative tools, and
56
+ prototypes that will later be wrapped in a more sophisticated interface.
57
+
58
+ A Cmd instance or subclass instance is a line-oriented interpreter
59
+ framework. There is no good reason to instantiate Cmd itself; rather,
60
+ it's useful as a superclass of an interpreter class you define yourself
61
+ in order to inherit Cmd's methods and encapsulate action methods.
62
+
63
+ """
64
+ prompt = PROMPT
65
+ identchars = IDENTCHARS
66
+ ruler = '='
67
+ lastcmd = ''
68
+ intro = None
69
+ doc_leader = ""
70
+ doc_header = "Documented commands (type help <topic>):"
71
+ misc_header = "Miscellaneous help topics:"
72
+ undoc_header = "Undocumented commands:"
73
+ nohelp = "*** No help on %s"
74
+ use_rawinput = 1
75
+
76
+ def __init__(self, completekey='tab', stdin=None, stdout=None):
77
+ """Instantiate a line-oriented interpreter framework.
78
+
79
+ The optional argument 'completekey' is the readline name of a
80
+ completion key; it defaults to the Tab key. If completekey is
81
+ not None and the readline module is available, command completion
82
+ is done automatically. The optional arguments stdin and stdout
83
+ specify alternate input and output file objects; if not specified,
84
+ sys.stdin and sys.stdout are used.
85
+
86
+ """
87
+ if stdin is not None:
88
+ self.stdin = stdin
89
+ else:
90
+ self.stdin = sys.stdin
91
+ if stdout is not None:
92
+ self.stdout = stdout
93
+ else:
94
+ self.stdout = sys.stdout
95
+ self.cmdqueue = []
96
+ self.completekey = completekey
97
+
98
+ def cmdloop(self, intro=None):
99
+ """Repeatedly issue a prompt, accept input, parse an initial prefix
100
+ off the received input, and dispatch to action methods, passing them
101
+ the remainder of the line as argument.
102
+
103
+ """
104
+
105
+ self.preloop()
106
+ if self.use_rawinput and self.completekey:
107
+ try:
108
+ import readline
109
+ self.old_completer = readline.get_completer()
110
+ readline.set_completer(self.complete)
111
+ readline.parse_and_bind(self.completekey+": complete")
112
+ except ImportError:
113
+ pass
114
+ try:
115
+ if intro is not None:
116
+ self.intro = intro
117
+ if self.intro:
118
+ self.stdout.write(str(self.intro)+"\n")
119
+ stop = None
120
+ while not stop:
121
+ if self.cmdqueue:
122
+ line = self.cmdqueue.pop(0)
123
+ else:
124
+ if self.use_rawinput:
125
+ try:
126
+ line = input(self.prompt)
127
+ except EOFError:
128
+ line = 'EOF'
129
+ else:
130
+ self.stdout.write(self.prompt)
131
+ self.stdout.flush()
132
+ line = self.stdin.readline()
133
+ if not len(line):
134
+ line = 'EOF'
135
+ else:
136
+ line = line.rstrip('\r\n')
137
+ line = self.precmd(line)
138
+ stop = self.onecmd(line)
139
+ stop = self.postcmd(stop, line)
140
+ self.postloop()
141
+ finally:
142
+ if self.use_rawinput and self.completekey:
143
+ try:
144
+ import readline
145
+ readline.set_completer(self.old_completer)
146
+ except ImportError:
147
+ pass
148
+
149
+
150
+ def precmd(self, line):
151
+ """Hook method executed just before the command line is
152
+ interpreted, but after the input prompt is generated and issued.
153
+
154
+ """
155
+ return line
156
+
157
+ def postcmd(self, stop, line):
158
+ """Hook method executed just after a command dispatch is finished."""
159
+ return stop
160
+
161
+ def preloop(self):
162
+ """Hook method executed once when the cmdloop() method is called."""
163
+ pass
164
+
165
+ def postloop(self):
166
+ """Hook method executed once when the cmdloop() method is about to
167
+ return.
168
+
169
+ """
170
+ pass
171
+
172
+ def parseline(self, line):
173
+ """Parse the line into a command name and a string containing
174
+ the arguments. Returns a tuple containing (command, args, line).
175
+ 'command' and 'args' may be None if the line couldn't be parsed.
176
+ """
177
+ line = line.strip()
178
+ if not line:
179
+ return None, None, line
180
+ elif line[0] == '?':
181
+ line = 'help ' + line[1:]
182
+ elif line[0] == '!':
183
+ if hasattr(self, 'do_shell'):
184
+ line = 'shell ' + line[1:]
185
+ else:
186
+ return None, None, line
187
+ i, n = 0, len(line)
188
+ while i < n and line[i] in self.identchars: i = i+1
189
+ cmd, arg = line[:i], line[i:].strip()
190
+ return cmd, arg, line
191
+
192
+ def onecmd(self, line):
193
+ """Interpret the argument as though it had been typed in response
194
+ to the prompt.
195
+
196
+ This may be overridden, but should not normally need to be;
197
+ see the precmd() and postcmd() methods for useful execution hooks.
198
+ The return value is a flag indicating whether interpretation of
199
+ commands by the interpreter should stop.
200
+
201
+ """
202
+ cmd, arg, line = self.parseline(line)
203
+ if not line:
204
+ return self.emptyline()
205
+ if cmd is None:
206
+ return self.default(line)
207
+ self.lastcmd = line
208
+ if line == 'EOF' :
209
+ self.lastcmd = ''
210
+ if cmd == '':
211
+ return self.default(line)
212
+ else:
213
+ try:
214
+ func = getattr(self, 'do_' + cmd)
215
+ except AttributeError:
216
+ return self.default(line)
217
+ return func(arg)
218
+
219
+ def emptyline(self):
220
+ """Called when an empty line is entered in response to the prompt.
221
+
222
+ If this method is not overridden, it repeats the last nonempty
223
+ command entered.
224
+
225
+ """
226
+ if self.lastcmd:
227
+ return self.onecmd(self.lastcmd)
228
+
229
+ def default(self, line):
230
+ """Called on an input line when the command prefix is not recognized.
231
+
232
+ If this method is not overridden, it prints an error message and
233
+ returns.
234
+
235
+ """
236
+ self.stdout.write('*** Unknown syntax: %s\n'%line)
237
+
238
+ def completedefault(self, *ignored):
239
+ """Method called to complete an input line when no command-specific
240
+ complete_*() method is available.
241
+
242
+ By default, it returns an empty list.
243
+
244
+ """
245
+ return []
246
+
247
+ def completenames(self, text, *ignored):
248
+ dotext = 'do_'+text
249
+ return [a[3:] for a in self.get_names() if a.startswith(dotext)]
250
+
251
+ def complete(self, text, state):
252
+ """Return the next possible completion for 'text'.
253
+
254
+ If a command has not been entered, then complete against command list.
255
+ Otherwise try to call complete_<command> to get list of completions.
256
+ """
257
+ if state == 0:
258
+ import readline
259
+ origline = readline.get_line_buffer()
260
+ line = origline.lstrip()
261
+ stripped = len(origline) - len(line)
262
+ begidx = readline.get_begidx() - stripped
263
+ endidx = readline.get_endidx() - stripped
264
+ if begidx>0:
265
+ cmd, args, foo = self.parseline(line)
266
+ if cmd == '':
267
+ compfunc = self.completedefault
268
+ else:
269
+ try:
270
+ compfunc = getattr(self, 'complete_' + cmd)
271
+ except AttributeError:
272
+ compfunc = self.completedefault
273
+ else:
274
+ compfunc = self.completenames
275
+ self.completion_matches = compfunc(text, line, begidx, endidx)
276
+ try:
277
+ return self.completion_matches[state]
278
+ except IndexError:
279
+ return None
280
+
281
+ def get_names(self):
282
+ # This method used to pull in base class attributes
283
+ # at a time dir() didn't do it yet.
284
+ return dir(self.__class__)
285
+
286
+ def complete_help(self, *args):
287
+ commands = set(self.completenames(*args))
288
+ topics = set(a[5:] for a in self.get_names()
289
+ if a.startswith('help_' + args[0]))
290
+ return list(commands | topics)
291
+
292
+ def do_help(self, arg):
293
+ 'List available commands with "help" or detailed help with "help cmd".'
294
+ if arg:
295
+ # XXX check arg syntax
296
+ try:
297
+ func = getattr(self, 'help_' + arg)
298
+ except AttributeError:
299
+ try:
300
+ doc=getattr(self, 'do_' + arg).__doc__
301
+ if doc:
302
+ self.stdout.write("%s\n"%str(doc))
303
+ return
304
+ except AttributeError:
305
+ pass
306
+ self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
307
+ return
308
+ func()
309
+ else:
310
+ names = self.get_names()
311
+ cmds_doc = []
312
+ cmds_undoc = []
313
+ help = {}
314
+ for name in names:
315
+ if name[:5] == 'help_':
316
+ help[name[5:]]=1
317
+ names.sort()
318
+ # There can be duplicates if routines overridden
319
+ prevname = ''
320
+ for name in names:
321
+ if name[:3] == 'do_':
322
+ if name == prevname:
323
+ continue
324
+ prevname = name
325
+ cmd=name[3:]
326
+ if cmd in help:
327
+ cmds_doc.append(cmd)
328
+ del help[cmd]
329
+ elif getattr(self, name).__doc__:
330
+ cmds_doc.append(cmd)
331
+ else:
332
+ cmds_undoc.append(cmd)
333
+ self.stdout.write("%s\n"%str(self.doc_leader))
334
+ self.print_topics(self.doc_header, cmds_doc, 15,80)
335
+ self.print_topics(self.misc_header, list(help.keys()),15,80)
336
+ self.print_topics(self.undoc_header, cmds_undoc, 15,80)
337
+
338
+ def print_topics(self, header, cmds, cmdlen, maxcol):
339
+ if cmds:
340
+ self.stdout.write("%s\n"%str(header))
341
+ if self.ruler:
342
+ self.stdout.write("%s\n"%str(self.ruler * len(header)))
343
+ self.columnize(cmds, maxcol-1)
344
+ self.stdout.write("\n")
345
+
346
+ def columnize(self, list, displaywidth=80):
347
+ """Display a list of strings as a compact set of columns.
348
+
349
+ Each column is only as wide as necessary.
350
+ Columns are separated by two spaces (one was not legible enough).
351
+ """
352
+ if not list:
353
+ self.stdout.write("<empty>\n")
354
+ return
355
+
356
+ nonstrings = [i for i in range(len(list))
357
+ if not isinstance(list[i], str)]
358
+ if nonstrings:
359
+ raise TypeError("list[i] not a string for i in %s"
360
+ % ", ".join(map(str, nonstrings)))
361
+ size = len(list)
362
+ if size == 1:
363
+ self.stdout.write('%s\n'%str(list[0]))
364
+ return
365
+ # Try every row count from 1 upwards
366
+ for nrows in range(1, len(list)):
367
+ ncols = (size+nrows-1) // nrows
368
+ colwidths = []
369
+ totwidth = -2
370
+ for col in range(ncols):
371
+ colwidth = 0
372
+ for row in range(nrows):
373
+ i = row + nrows*col
374
+ if i >= size:
375
+ break
376
+ x = list[i]
377
+ colwidth = max(colwidth, len(x))
378
+ colwidths.append(colwidth)
379
+ totwidth += colwidth + 2
380
+ if totwidth > displaywidth:
381
+ break
382
+ if totwidth <= displaywidth:
383
+ break
384
+ else:
385
+ nrows = len(list)
386
+ ncols = 1
387
+ colwidths = [0]
388
+ for row in range(nrows):
389
+ texts = []
390
+ for col in range(ncols):
391
+ i = row + nrows*col
392
+ if i >= size:
393
+ x = ""
394
+ else:
395
+ x = list[i]
396
+ texts.append(x)
397
+ while texts and not texts[-1]:
398
+ del texts[-1]
399
+ for col in range(len(texts)):
400
+ texts[col] = texts[col].ljust(colwidths[col])
401
+ self.stdout.write("%s\n"%str(" ".join(texts)))
evalkit_cambrian/lib/python3.10/imp.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module provides the components needed to build your own __import__
2
+ function. Undocumented functions are obsolete.
3
+
4
+ In most cases it is preferred you consider using the importlib module's
5
+ functionality over this module.
6
+
7
+ """
8
+ # (Probably) need to stay in _imp
9
+ from _imp import (lock_held, acquire_lock, release_lock,
10
+ get_frozen_object, is_frozen_package,
11
+ init_frozen, is_builtin, is_frozen,
12
+ _fix_co_filename)
13
+ try:
14
+ from _imp import create_dynamic
15
+ except ImportError:
16
+ # Platform doesn't support dynamic loading.
17
+ create_dynamic = None
18
+
19
+ from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
20
+ from importlib._bootstrap_external import SourcelessFileLoader
21
+
22
+ from importlib import machinery
23
+ from importlib import util
24
+ import importlib
25
+ import os
26
+ import sys
27
+ import tokenize
28
+ import types
29
+ import warnings
30
+
31
+ warnings.warn("the imp module is deprecated in favour of importlib and slated "
32
+ "for removal in Python 3.12; "
33
+ "see the module's documentation for alternative uses",
34
+ DeprecationWarning, stacklevel=2)
35
+
36
+ # DEPRECATED
37
+ SEARCH_ERROR = 0
38
+ PY_SOURCE = 1
39
+ PY_COMPILED = 2
40
+ C_EXTENSION = 3
41
+ PY_RESOURCE = 4
42
+ PKG_DIRECTORY = 5
43
+ C_BUILTIN = 6
44
+ PY_FROZEN = 7
45
+ PY_CODERESOURCE = 8
46
+ IMP_HOOK = 9
47
+
48
+
49
+ def new_module(name):
50
+ """**DEPRECATED**
51
+
52
+ Create a new module.
53
+
54
+ The module is not entered into sys.modules.
55
+
56
+ """
57
+ return types.ModuleType(name)
58
+
59
+
60
+ def get_magic():
61
+ """**DEPRECATED**
62
+
63
+ Return the magic number for .pyc files.
64
+ """
65
+ return util.MAGIC_NUMBER
66
+
67
+
68
+ def get_tag():
69
+ """Return the magic tag for .pyc files."""
70
+ return sys.implementation.cache_tag
71
+
72
+
73
+ def cache_from_source(path, debug_override=None):
74
+ """**DEPRECATED**
75
+
76
+ Given the path to a .py file, return the path to its .pyc file.
77
+
78
+ The .py file does not need to exist; this simply returns the path to the
79
+ .pyc file calculated as if the .py file were imported.
80
+
81
+ If debug_override is not None, then it must be a boolean and is used in
82
+ place of sys.flags.optimize.
83
+
84
+ If sys.implementation.cache_tag is None then NotImplementedError is raised.
85
+
86
+ """
87
+ with warnings.catch_warnings():
88
+ warnings.simplefilter('ignore')
89
+ return util.cache_from_source(path, debug_override)
90
+
91
+
92
+ def source_from_cache(path):
93
+ """**DEPRECATED**
94
+
95
+ Given the path to a .pyc. file, return the path to its .py file.
96
+
97
+ The .pyc file does not need to exist; this simply returns the path to
98
+ the .py file calculated to correspond to the .pyc file. If path does
99
+ not conform to PEP 3147 format, ValueError will be raised. If
100
+ sys.implementation.cache_tag is None then NotImplementedError is raised.
101
+
102
+ """
103
+ return util.source_from_cache(path)
104
+
105
+
106
+ def get_suffixes():
107
+ """**DEPRECATED**"""
108
+ extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
109
+ source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
110
+ bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
111
+
112
+ return extensions + source + bytecode
113
+
114
+
115
+ class NullImporter:
116
+
117
+ """**DEPRECATED**
118
+
119
+ Null import object.
120
+
121
+ """
122
+
123
+ def __init__(self, path):
124
+ if path == '':
125
+ raise ImportError('empty pathname', path='')
126
+ elif os.path.isdir(path):
127
+ raise ImportError('existing directory', path=path)
128
+
129
+ def find_module(self, fullname):
130
+ """Always returns None."""
131
+ return None
132
+
133
+
134
+ class _HackedGetData:
135
+
136
+ """Compatibility support for 'file' arguments of various load_*()
137
+ functions."""
138
+
139
+ def __init__(self, fullname, path, file=None):
140
+ super().__init__(fullname, path)
141
+ self.file = file
142
+
143
+ def get_data(self, path):
144
+ """Gross hack to contort loader to deal w/ load_*()'s bad API."""
145
+ if self.file and path == self.path:
146
+ # The contract of get_data() requires us to return bytes. Reopen the
147
+ # file in binary mode if needed.
148
+ if not self.file.closed:
149
+ file = self.file
150
+ if 'b' not in file.mode:
151
+ file.close()
152
+ if self.file.closed:
153
+ self.file = file = open(self.path, 'rb')
154
+
155
+ with file:
156
+ return file.read()
157
+ else:
158
+ return super().get_data(path)
159
+
160
+
161
+ class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
162
+
163
+ """Compatibility support for implementing load_source()."""
164
+
165
+
166
+ def load_source(name, pathname, file=None):
167
+ loader = _LoadSourceCompatibility(name, pathname, file)
168
+ spec = util.spec_from_file_location(name, pathname, loader=loader)
169
+ if name in sys.modules:
170
+ module = _exec(spec, sys.modules[name])
171
+ else:
172
+ module = _load(spec)
173
+ # To allow reloading to potentially work, use a non-hacked loader which
174
+ # won't rely on a now-closed file object.
175
+ module.__loader__ = machinery.SourceFileLoader(name, pathname)
176
+ module.__spec__.loader = module.__loader__
177
+ return module
178
+
179
+
180
+ class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
181
+
182
+ """Compatibility support for implementing load_compiled()."""
183
+
184
+
185
+ def load_compiled(name, pathname, file=None):
186
+ """**DEPRECATED**"""
187
+ loader = _LoadCompiledCompatibility(name, pathname, file)
188
+ spec = util.spec_from_file_location(name, pathname, loader=loader)
189
+ if name in sys.modules:
190
+ module = _exec(spec, sys.modules[name])
191
+ else:
192
+ module = _load(spec)
193
+ # To allow reloading to potentially work, use a non-hacked loader which
194
+ # won't rely on a now-closed file object.
195
+ module.__loader__ = SourcelessFileLoader(name, pathname)
196
+ module.__spec__.loader = module.__loader__
197
+ return module
198
+
199
+
200
+ def load_package(name, path):
201
+ """**DEPRECATED**"""
202
+ if os.path.isdir(path):
203
+ extensions = (machinery.SOURCE_SUFFIXES[:] +
204
+ machinery.BYTECODE_SUFFIXES[:])
205
+ for extension in extensions:
206
+ init_path = os.path.join(path, '__init__' + extension)
207
+ if os.path.exists(init_path):
208
+ path = init_path
209
+ break
210
+ else:
211
+ raise ValueError('{!r} is not a package'.format(path))
212
+ spec = util.spec_from_file_location(name, path,
213
+ submodule_search_locations=[])
214
+ if name in sys.modules:
215
+ return _exec(spec, sys.modules[name])
216
+ else:
217
+ return _load(spec)
218
+
219
+
220
+ def load_module(name, file, filename, details):
221
+ """**DEPRECATED**
222
+
223
+ Load a module, given information returned by find_module().
224
+
225
+ The module name must include the full package name, if any.
226
+
227
+ """
228
+ suffix, mode, type_ = details
229
+ if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
230
+ raise ValueError('invalid file open mode {!r}'.format(mode))
231
+ elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
232
+ msg = 'file object required for import (type code {})'.format(type_)
233
+ raise ValueError(msg)
234
+ elif type_ == PY_SOURCE:
235
+ return load_source(name, filename, file)
236
+ elif type_ == PY_COMPILED:
237
+ return load_compiled(name, filename, file)
238
+ elif type_ == C_EXTENSION and load_dynamic is not None:
239
+ if file is None:
240
+ with open(filename, 'rb') as opened_file:
241
+ return load_dynamic(name, filename, opened_file)
242
+ else:
243
+ return load_dynamic(name, filename, file)
244
+ elif type_ == PKG_DIRECTORY:
245
+ return load_package(name, filename)
246
+ elif type_ == C_BUILTIN:
247
+ return init_builtin(name)
248
+ elif type_ == PY_FROZEN:
249
+ return init_frozen(name)
250
+ else:
251
+ msg = "Don't know how to import {} (type code {})".format(name, type_)
252
+ raise ImportError(msg, name=name)
253
+
254
+
255
+ def find_module(name, path=None):
256
+ """**DEPRECATED**
257
+
258
+ Search for a module.
259
+
260
+ If path is omitted or None, search for a built-in, frozen or special
261
+ module and continue search in sys.path. The module name cannot
262
+ contain '.'; to search for a submodule of a package, pass the
263
+ submodule name and the package's __path__.
264
+
265
+ """
266
+ if not isinstance(name, str):
267
+ raise TypeError("'name' must be a str, not {}".format(type(name)))
268
+ elif not isinstance(path, (type(None), list)):
269
+ # Backwards-compatibility
270
+ raise RuntimeError("'path' must be None or a list, "
271
+ "not {}".format(type(path)))
272
+
273
+ if path is None:
274
+ if is_builtin(name):
275
+ return None, None, ('', '', C_BUILTIN)
276
+ elif is_frozen(name):
277
+ return None, None, ('', '', PY_FROZEN)
278
+ else:
279
+ path = sys.path
280
+
281
+ for entry in path:
282
+ package_directory = os.path.join(entry, name)
283
+ for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
284
+ package_file_name = '__init__' + suffix
285
+ file_path = os.path.join(package_directory, package_file_name)
286
+ if os.path.isfile(file_path):
287
+ return None, package_directory, ('', '', PKG_DIRECTORY)
288
+ for suffix, mode, type_ in get_suffixes():
289
+ file_name = name + suffix
290
+ file_path = os.path.join(entry, file_name)
291
+ if os.path.isfile(file_path):
292
+ break
293
+ else:
294
+ continue
295
+ break # Break out of outer loop when breaking out of inner loop.
296
+ else:
297
+ raise ImportError(_ERR_MSG.format(name), name=name)
298
+
299
+ encoding = None
300
+ if 'b' not in mode:
301
+ with open(file_path, 'rb') as file:
302
+ encoding = tokenize.detect_encoding(file.readline)[0]
303
+ file = open(file_path, mode, encoding=encoding)
304
+ return file, file_path, (suffix, mode, type_)
305
+
306
+
307
+ def reload(module):
308
+ """**DEPRECATED**
309
+
310
+ Reload the module and return it.
311
+
312
+ The module must have been successfully imported before.
313
+
314
+ """
315
+ return importlib.reload(module)
316
+
317
+
318
+ def init_builtin(name):
319
+ """**DEPRECATED**
320
+
321
+ Load and return a built-in module by name, or None is such module doesn't
322
+ exist
323
+ """
324
+ try:
325
+ return _builtin_from_name(name)
326
+ except ImportError:
327
+ return None
328
+
329
+
330
+ if create_dynamic:
331
+ def load_dynamic(name, path, file=None):
332
+ """**DEPRECATED**
333
+
334
+ Load an extension module.
335
+ """
336
+ import importlib.machinery
337
+ loader = importlib.machinery.ExtensionFileLoader(name, path)
338
+
339
+ # Issue #24748: Skip the sys.modules check in _load_module_shim;
340
+ # always load new extension
341
+ spec = importlib.machinery.ModuleSpec(
342
+ name=name, loader=loader, origin=path)
343
+ return _load(spec)
344
+
345
+ else:
346
+ load_dynamic = None
evalkit_cambrian/lib/python3.10/inspect.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.29 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (6.04 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/convert.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/convert_matrix.cpython-310.pyc ADDED
Binary file (41.2 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/exception.cpython-310.pyc ADDED
Binary file (4.76 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/lazy_imports.cpython-310.pyc ADDED
Binary file (5.86 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/__pycache__/relabel.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .graph import Graph
2
+ from .digraph import DiGraph
3
+ from .multigraph import MultiGraph
4
+ from .multidigraph import MultiDiGraph
5
+
6
+ from .function import *
7
+ from .graphviews import subgraph_view, reverse_view
8
+
9
+ from networkx.classes import filters
10
+
11
+ from networkx.classes import coreviews
12
+ from networkx.classes import graphviews
13
+ from networkx.classes import reportviews
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/coreviews.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Views of core data structures such as nested Mappings (e.g. dict-of-dicts).
2
+ These ``Views`` often restrict element access, with either the entire view or
3
+ layers of nested mappings being read-only.
4
+ """
5
+
6
+ from collections.abc import Mapping
7
+
8
+ __all__ = [
9
+ "AtlasView",
10
+ "AdjacencyView",
11
+ "MultiAdjacencyView",
12
+ "UnionAtlas",
13
+ "UnionAdjacency",
14
+ "UnionMultiInner",
15
+ "UnionMultiAdjacency",
16
+ "FilterAtlas",
17
+ "FilterAdjacency",
18
+ "FilterMultiInner",
19
+ "FilterMultiAdjacency",
20
+ ]
21
+
22
+
23
+ class AtlasView(Mapping):
24
+ """An AtlasView is a Read-only Mapping of Mappings.
25
+
26
+ It is a View into a dict-of-dict data structure.
27
+ The inner level of dict is read-write. But the
28
+ outer level is read-only.
29
+
30
+ See Also
31
+ ========
32
+ AdjacencyView: View into dict-of-dict-of-dict
33
+ MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
34
+ """
35
+
36
+ __slots__ = ("_atlas",)
37
+
38
+ def __getstate__(self):
39
+ return {"_atlas": self._atlas}
40
+
41
+ def __setstate__(self, state):
42
+ self._atlas = state["_atlas"]
43
+
44
+ def __init__(self, d):
45
+ self._atlas = d
46
+
47
+ def __len__(self):
48
+ return len(self._atlas)
49
+
50
+ def __iter__(self):
51
+ return iter(self._atlas)
52
+
53
+ def __getitem__(self, key):
54
+ return self._atlas[key]
55
+
56
+ def copy(self):
57
+ return {n: self[n].copy() for n in self._atlas}
58
+
59
+ def __str__(self):
60
+ return str(self._atlas) # {nbr: self[nbr] for nbr in self})
61
+
62
+ def __repr__(self):
63
+ return f"{self.__class__.__name__}({self._atlas!r})"
64
+
65
+
66
+ class AdjacencyView(AtlasView):
67
+ """An AdjacencyView is a Read-only Map of Maps of Maps.
68
+
69
+ It is a View into a dict-of-dict-of-dict data structure.
70
+ The inner level of dict is read-write. But the
71
+ outer levels are read-only.
72
+
73
+ See Also
74
+ ========
75
+ AtlasView: View into dict-of-dict
76
+ MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
77
+ """
78
+
79
+ __slots__ = () # Still uses AtlasView slots names _atlas
80
+
81
+ def __getitem__(self, name):
82
+ return AtlasView(self._atlas[name])
83
+
84
+ def copy(self):
85
+ return {n: self[n].copy() for n in self._atlas}
86
+
87
+
88
+ class MultiAdjacencyView(AdjacencyView):
89
+ """An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.
90
+
91
+ It is a View into a dict-of-dict-of-dict-of-dict data structure.
92
+ The inner level of dict is read-write. But the
93
+ outer levels are read-only.
94
+
95
+ See Also
96
+ ========
97
+ AtlasView: View into dict-of-dict
98
+ AdjacencyView: View into dict-of-dict-of-dict
99
+ """
100
+
101
+ __slots__ = () # Still uses AtlasView slots names _atlas
102
+
103
+ def __getitem__(self, name):
104
+ return AdjacencyView(self._atlas[name])
105
+
106
+ def copy(self):
107
+ return {n: self[n].copy() for n in self._atlas}
108
+
109
+
110
+ class UnionAtlas(Mapping):
111
+ """A read-only union of two atlases (dict-of-dict).
112
+
113
+ The two dict-of-dicts represent the inner dict of
114
+ an Adjacency: `G.succ[node]` and `G.pred[node]`.
115
+ The inner level of dict of both hold attribute key:value
116
+ pairs and is read-write. But the outer level is read-only.
117
+
118
+ See Also
119
+ ========
120
+ UnionAdjacency: View into dict-of-dict-of-dict
121
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
122
+ """
123
+
124
+ __slots__ = ("_succ", "_pred")
125
+
126
+ def __getstate__(self):
127
+ return {"_succ": self._succ, "_pred": self._pred}
128
+
129
+ def __setstate__(self, state):
130
+ self._succ = state["_succ"]
131
+ self._pred = state["_pred"]
132
+
133
+ def __init__(self, succ, pred):
134
+ self._succ = succ
135
+ self._pred = pred
136
+
137
+ def __len__(self):
138
+ return len(self._succ.keys() | self._pred.keys())
139
+
140
+ def __iter__(self):
141
+ return iter(set(self._succ.keys()) | set(self._pred.keys()))
142
+
143
+ def __getitem__(self, key):
144
+ try:
145
+ return self._succ[key]
146
+ except KeyError:
147
+ return self._pred[key]
148
+
149
+ def copy(self):
150
+ result = {nbr: dd.copy() for nbr, dd in self._succ.items()}
151
+ for nbr, dd in self._pred.items():
152
+ if nbr in result:
153
+ result[nbr].update(dd)
154
+ else:
155
+ result[nbr] = dd.copy()
156
+ return result
157
+
158
+ def __str__(self):
159
+ return str({nbr: self[nbr] for nbr in self})
160
+
161
+ def __repr__(self):
162
+ return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
163
+
164
+
165
+ class UnionAdjacency(Mapping):
166
+ """A read-only union of dict Adjacencies as a Map of Maps of Maps.
167
+
168
+ The two input dict-of-dict-of-dicts represent the union of
169
+ `G.succ` and `G.pred`. Return values are UnionAtlas
170
+ The inner level of dict is read-write. But the
171
+ middle and outer levels are read-only.
172
+
173
+ succ : a dict-of-dict-of-dict {node: nbrdict}
174
+ pred : a dict-of-dict-of-dict {node: nbrdict}
175
+ The keys for the two dicts should be the same
176
+
177
+ See Also
178
+ ========
179
+ UnionAtlas: View into dict-of-dict
180
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
181
+ """
182
+
183
+ __slots__ = ("_succ", "_pred")
184
+
185
+ def __getstate__(self):
186
+ return {"_succ": self._succ, "_pred": self._pred}
187
+
188
+ def __setstate__(self, state):
189
+ self._succ = state["_succ"]
190
+ self._pred = state["_pred"]
191
+
192
+ def __init__(self, succ, pred):
193
+ # keys must be the same for two input dicts
194
+ assert len(set(succ.keys()) ^ set(pred.keys())) == 0
195
+ self._succ = succ
196
+ self._pred = pred
197
+
198
+ def __len__(self):
199
+ return len(self._succ) # length of each dict should be the same
200
+
201
+ def __iter__(self):
202
+ return iter(self._succ)
203
+
204
+ def __getitem__(self, nbr):
205
+ return UnionAtlas(self._succ[nbr], self._pred[nbr])
206
+
207
+ def copy(self):
208
+ return {n: self[n].copy() for n in self._succ}
209
+
210
+ def __str__(self):
211
+ return str({nbr: self[nbr] for nbr in self})
212
+
213
+ def __repr__(self):
214
+ return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
215
+
216
+
217
+ class UnionMultiInner(UnionAtlas):
218
+ """A read-only union of two inner dicts of MultiAdjacencies.
219
+
220
+ The two input dict-of-dict-of-dicts represent the union of
221
+ `G.succ[node]` and `G.pred[node]` for MultiDiGraphs.
222
+ Return values are UnionAtlas.
223
+ The inner level of dict is read-write. But the outer levels are read-only.
224
+
225
+ See Also
226
+ ========
227
+ UnionAtlas: View into dict-of-dict
228
+ UnionAdjacency: View into dict-of-dict-of-dict
229
+ UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
230
+ """
231
+
232
+ __slots__ = () # Still uses UnionAtlas slots names _succ, _pred
233
+
234
+ def __getitem__(self, node):
235
+ in_succ = node in self._succ
236
+ in_pred = node in self._pred
237
+ if in_succ:
238
+ if in_pred:
239
+ return UnionAtlas(self._succ[node], self._pred[node])
240
+ return UnionAtlas(self._succ[node], {})
241
+ return UnionAtlas({}, self._pred[node])
242
+
243
+ def copy(self):
244
+ nodes = set(self._succ.keys()) | set(self._pred.keys())
245
+ return {n: self[n].copy() for n in nodes}
246
+
247
+
248
+ class UnionMultiAdjacency(UnionAdjacency):
249
+ """A read-only union of two dict MultiAdjacencies.
250
+
251
+ The two input dict-of-dict-of-dict-of-dicts represent the union of
252
+ `G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency.
253
+ The inner level of dict is read-write. But the outer levels are read-only.
254
+
255
+ See Also
256
+ ========
257
+ UnionAtlas: View into dict-of-dict
258
+ UnionMultiInner: View into dict-of-dict-of-dict
259
+ """
260
+
261
+ __slots__ = () # Still uses UnionAdjacency slots names _succ, _pred
262
+
263
+ def __getitem__(self, node):
264
+ return UnionMultiInner(self._succ[node], self._pred[node])
265
+
266
+
267
+ class FilterAtlas(Mapping): # nodedict, nbrdict, keydict
268
+ """A read-only Mapping of Mappings with filtering criteria for nodes.
269
+
270
+ It is a view into a dict-of-dict data structure, and it selects only
271
+ nodes that meet the criteria defined by ``NODE_OK``.
272
+
273
+ See Also
274
+ ========
275
+ FilterAdjacency
276
+ FilterMultiInner
277
+ FilterMultiAdjacency
278
+ """
279
+
280
+ def __init__(self, d, NODE_OK):
281
+ self._atlas = d
282
+ self.NODE_OK = NODE_OK
283
+
284
+ def __len__(self):
285
+ # check whether NODE_OK stores the number of nodes as `length`
286
+ # or the nodes themselves as a set `nodes`. If not, count the nodes.
287
+ if hasattr(self.NODE_OK, "length"):
288
+ return self.NODE_OK.length
289
+ if hasattr(self.NODE_OK, "nodes"):
290
+ return len(self.NODE_OK.nodes & self._atlas.keys())
291
+ return sum(1 for n in self._atlas if self.NODE_OK(n))
292
+
293
+ def __iter__(self):
294
+ try: # check that NODE_OK has attr 'nodes'
295
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
296
+ except AttributeError:
297
+ node_ok_shorter = False
298
+ if node_ok_shorter:
299
+ return (n for n in self.NODE_OK.nodes if n in self._atlas)
300
+ return (n for n in self._atlas if self.NODE_OK(n))
301
+
302
+ def __getitem__(self, key):
303
+ if key in self._atlas and self.NODE_OK(key):
304
+ return self._atlas[key]
305
+ raise KeyError(f"Key {key} not found")
306
+
307
+ def __str__(self):
308
+ return str({nbr: self[nbr] for nbr in self})
309
+
310
+ def __repr__(self):
311
+ return f"{self.__class__.__name__}({self._atlas!r}, {self.NODE_OK!r})"
312
+
313
+
314
+ class FilterAdjacency(Mapping): # edgedict
315
+ """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
316
+
317
+ It is a view into a dict-of-dict-of-dict data structure, and it selects nodes
318
+ and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``,
319
+ respectively.
320
+
321
+ See Also
322
+ ========
323
+ FilterAtlas
324
+ FilterMultiInner
325
+ FilterMultiAdjacency
326
+ """
327
+
328
+ def __init__(self, d, NODE_OK, EDGE_OK):
329
+ self._atlas = d
330
+ self.NODE_OK = NODE_OK
331
+ self.EDGE_OK = EDGE_OK
332
+
333
+ def __len__(self):
334
+ # check whether NODE_OK stores the number of nodes as `length`
335
+ # or the nodes themselves as a set `nodes`. If not, count the nodes.
336
+ if hasattr(self.NODE_OK, "length"):
337
+ return self.NODE_OK.length
338
+ if hasattr(self.NODE_OK, "nodes"):
339
+ return len(self.NODE_OK.nodes & self._atlas.keys())
340
+ return sum(1 for n in self._atlas if self.NODE_OK(n))
341
+
342
+ def __iter__(self):
343
+ try: # check that NODE_OK has attr 'nodes'
344
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
345
+ except AttributeError:
346
+ node_ok_shorter = False
347
+ if node_ok_shorter:
348
+ return (n for n in self.NODE_OK.nodes if n in self._atlas)
349
+ return (n for n in self._atlas if self.NODE_OK(n))
350
+
351
+ def __getitem__(self, node):
352
+ if node in self._atlas and self.NODE_OK(node):
353
+
354
+ def new_node_ok(nbr):
355
+ return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr)
356
+
357
+ return FilterAtlas(self._atlas[node], new_node_ok)
358
+ raise KeyError(f"Key {node} not found")
359
+
360
+ def __str__(self):
361
+ return str({nbr: self[nbr] for nbr in self})
362
+
363
+ def __repr__(self):
364
+ name = self.__class__.__name__
365
+ return f"{name}({self._atlas!r}, {self.NODE_OK!r}, {self.EDGE_OK!r})"
366
+
367
+
368
+ class FilterMultiInner(FilterAdjacency): # muliedge_seconddict
369
+ """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
370
+
371
+ It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes
372
+ and edges that meet specific criteria defined by ``NODE_OK`` and ``EDGE_OK``.
373
+
374
+ See Also
375
+ ========
376
+ FilterAtlas
377
+ FilterAdjacency
378
+ FilterMultiAdjacency
379
+ """
380
+
381
+ def __iter__(self):
382
+ try: # check that NODE_OK has attr 'nodes'
383
+ node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
384
+ except AttributeError:
385
+ node_ok_shorter = False
386
+ if node_ok_shorter:
387
+ my_nodes = (n for n in self.NODE_OK.nodes if n in self._atlas)
388
+ else:
389
+ my_nodes = (n for n in self._atlas if self.NODE_OK(n))
390
+ for n in my_nodes:
391
+ some_keys_ok = False
392
+ for key in self._atlas[n]:
393
+ if self.EDGE_OK(n, key):
394
+ some_keys_ok = True
395
+ break
396
+ if some_keys_ok is True:
397
+ yield n
398
+
399
+ def __getitem__(self, nbr):
400
+ if nbr in self._atlas and self.NODE_OK(nbr):
401
+
402
+ def new_node_ok(key):
403
+ return self.EDGE_OK(nbr, key)
404
+
405
+ return FilterAtlas(self._atlas[nbr], new_node_ok)
406
+ raise KeyError(f"Key {nbr} not found")
407
+
408
+
409
+ class FilterMultiAdjacency(FilterAdjacency): # multiedgedict
410
+ """A read-only Mapping of Mappings with filtering criteria
411
+ for nodes and edges.
412
+
413
+ It is a view into a dict-of-dict-of-dict-of-dict data structure,
414
+ and it selects nodes and edges that satisfy specific criteria
415
+ defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
416
+
417
+ See Also
418
+ ========
419
+ FilterAtlas
420
+ FilterAdjacency
421
+ FilterMultiInner
422
+ """
423
+
424
+ def __getitem__(self, node):
425
+ if node in self._atlas and self.NODE_OK(node):
426
+
427
+ def edge_ok(nbr, key):
428
+ return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr, key)
429
+
430
+ return FilterMultiInner(self._atlas[node], self.NODE_OK, edge_ok)
431
+ raise KeyError(f"Key {node} not found")
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/digraph.py ADDED
@@ -0,0 +1,1352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for directed graphs."""
2
+
3
+ from copy import deepcopy
4
+ from functools import cached_property
5
+
6
+ import networkx as nx
7
+ from networkx import convert
8
+ from networkx.classes.coreviews import AdjacencyView
9
+ from networkx.classes.graph import Graph
10
+ from networkx.classes.reportviews import (
11
+ DiDegreeView,
12
+ InDegreeView,
13
+ InEdgeView,
14
+ OutDegreeView,
15
+ OutEdgeView,
16
+ )
17
+ from networkx.exception import NetworkXError
18
+
19
+ __all__ = ["DiGraph"]
20
+
21
+
22
+ class _CachedPropertyResetterAdjAndSucc:
23
+ """Data Descriptor class that syncs and resets cached properties adj and succ
24
+
25
+ The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ`
26
+ are set to new objects. In addition, the attributes `_succ` and `_adj`
27
+ are synced so these two names point to the same object.
28
+
29
+ Warning: most of the time, when ``G._adj`` is set, ``G._pred`` should also
30
+ be set to maintain a valid data structure. They share datadicts.
31
+
32
+ This object sits on a class and ensures that any instance of that
33
+ class clears its cached properties "succ" and "adj" whenever the
34
+ underlying instance attributes "_succ" or "_adj" are set to a new object.
35
+ It only affects the set process of the obj._adj and obj._succ attribute.
36
+ All get/del operations act as they normally would.
37
+
38
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
39
+ """
40
+
41
+ def __set__(self, obj, value):
42
+ od = obj.__dict__
43
+ od["_adj"] = value
44
+ od["_succ"] = value
45
+ # reset cached properties
46
+ props = [
47
+ "adj",
48
+ "succ",
49
+ "edges",
50
+ "out_edges",
51
+ "degree",
52
+ "out_degree",
53
+ "in_degree",
54
+ ]
55
+ for prop in props:
56
+ if prop in od:
57
+ del od[prop]
58
+
59
+
60
+ class _CachedPropertyResetterPred:
61
+ """Data Descriptor class for _pred that resets ``pred`` cached_property when needed
62
+
63
+ This assumes that the ``cached_property`` ``G.pred`` should be reset whenever
64
+ ``G._pred`` is set to a new value.
65
+
66
+ Warning: most of the time, when ``G._pred`` is set, ``G._adj`` should also
67
+ be set to maintain a valid data structure. They share datadicts.
68
+
69
+ This object sits on a class and ensures that any instance of that
70
+ class clears its cached property "pred" whenever the underlying
71
+ instance attribute "_pred" is set to a new object. It only affects
72
+ the set process of the obj._pred attribute. All get/del operations
73
+ act as they normally would.
74
+
75
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
76
+ """
77
+
78
+ def __set__(self, obj, value):
79
+ od = obj.__dict__
80
+ od["_pred"] = value
81
+ # reset cached properties
82
+ props = ["pred", "in_edges", "degree", "out_degree", "in_degree"]
83
+ for prop in props:
84
+ if prop in od:
85
+ del od[prop]
86
+
87
+
88
+ class DiGraph(Graph):
89
+ """
90
+ Base class for directed graphs.
91
+
92
+ A DiGraph stores nodes and edges with optional data, or attributes.
93
+
94
+ DiGraphs hold directed edges. Self loops are allowed but multiple
95
+ (parallel) edges are not.
96
+
97
+ Nodes can be arbitrary (hashable) Python objects with optional
98
+ key/value attributes. By convention `None` is not used as a node.
99
+
100
+ Edges are represented as links between nodes with optional
101
+ key/value attributes.
102
+
103
+ Parameters
104
+ ----------
105
+ incoming_graph_data : input graph (optional, default: None)
106
+ Data to initialize graph. If None (default) an empty
107
+ graph is created. The data can be any format that is supported
108
+ by the to_networkx_graph() function, currently including edge list,
109
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
110
+ sparse matrix, or PyGraphviz graph.
111
+
112
+ attr : keyword arguments, optional (default= no attributes)
113
+ Attributes to add to graph as key=value pairs.
114
+
115
+ See Also
116
+ --------
117
+ Graph
118
+ MultiGraph
119
+ MultiDiGraph
120
+
121
+ Examples
122
+ --------
123
+ Create an empty graph structure (a "null graph") with no nodes and
124
+ no edges.
125
+
126
+ >>> G = nx.DiGraph()
127
+
128
+ G can be grown in several ways.
129
+
130
+ **Nodes:**
131
+
132
+ Add one node at a time:
133
+
134
+ >>> G.add_node(1)
135
+
136
+ Add the nodes from any container (a list, dict, set or
137
+ even the lines from a file or the nodes from another graph).
138
+
139
+ >>> G.add_nodes_from([2, 3])
140
+ >>> G.add_nodes_from(range(100, 110))
141
+ >>> H = nx.path_graph(10)
142
+ >>> G.add_nodes_from(H)
143
+
144
+ In addition to strings and integers any hashable Python object
145
+ (except None) can represent a node, e.g. a customized node object,
146
+ or even another Graph.
147
+
148
+ >>> G.add_node(H)
149
+
150
+ **Edges:**
151
+
152
+ G can also be grown by adding edges.
153
+
154
+ Add one edge,
155
+
156
+ >>> G.add_edge(1, 2)
157
+
158
+ a list of edges,
159
+
160
+ >>> G.add_edges_from([(1, 2), (1, 3)])
161
+
162
+ or a collection of edges,
163
+
164
+ >>> G.add_edges_from(H.edges)
165
+
166
+ If some edges connect nodes not yet in the graph, the nodes
167
+ are added automatically. There are no errors when adding
168
+ nodes or edges that already exist.
169
+
170
+ **Attributes:**
171
+
172
+ Each graph, node, and edge can hold key/value attribute pairs
173
+ in an associated attribute dictionary (the keys must be hashable).
174
+ By default these are empty, but can be added or changed using
175
+ add_edge, add_node or direct manipulation of the attribute
176
+ dictionaries named graph, node and edge respectively.
177
+
178
+ >>> G = nx.DiGraph(day="Friday")
179
+ >>> G.graph
180
+ {'day': 'Friday'}
181
+
182
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
183
+
184
+ >>> G.add_node(1, time="5pm")
185
+ >>> G.add_nodes_from([3], time="2pm")
186
+ >>> G.nodes[1]
187
+ {'time': '5pm'}
188
+ >>> G.nodes[1]["room"] = 714
189
+ >>> del G.nodes[1]["room"] # remove attribute
190
+ >>> list(G.nodes(data=True))
191
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
192
+
193
+ Add edge attributes using add_edge(), add_edges_from(), subscript
194
+ notation, or G.edges.
195
+
196
+ >>> G.add_edge(1, 2, weight=4.7)
197
+ >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
198
+ >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
199
+ >>> G[1][2]["weight"] = 4.7
200
+ >>> G.edges[1, 2]["weight"] = 4
201
+
202
+ Warning: we protect the graph data structure by making `G.edges[1, 2]` a
203
+ read-only dict-like structure. However, you can assign to attributes
204
+ in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
205
+ data attributes: `G.edges[1, 2]['weight'] = 4`
206
+ (For multigraphs: `MG.edges[u, v, key][name] = value`).
207
+
208
+ **Shortcuts:**
209
+
210
+ Many common graph features allow python syntax to speed reporting.
211
+
212
+ >>> 1 in G # check if node in graph
213
+ True
214
+ >>> [n for n in G if n < 3] # iterate through nodes
215
+ [1, 2]
216
+ >>> len(G) # number of nodes in graph
217
+ 5
218
+
219
+ Often the best way to traverse all edges of a graph is via the neighbors.
220
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
221
+
222
+ >>> for n, nbrsdict in G.adjacency():
223
+ ... for nbr, eattr in nbrsdict.items():
224
+ ... if "weight" in eattr:
225
+ ... # Do something useful with the edges
226
+ ... pass
227
+
228
+ But the edges reporting object is often more convenient:
229
+
230
+ >>> for u, v, weight in G.edges(data="weight"):
231
+ ... if weight is not None:
232
+ ... # Do something useful with the edges
233
+ ... pass
234
+
235
+ **Reporting:**
236
+
237
+ Simple graph information is obtained using object-attributes and methods.
238
+ Reporting usually provides views instead of containers to reduce memory
239
+ usage. The views update as the graph is updated similarly to dict-views.
240
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
241
+ via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
242
+ (e.g. `nodes.items()`, `nodes.data('color')`,
243
+ `nodes.data('color', default='blue')` and similarly for `edges`)
244
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
245
+
246
+ For details on these and other miscellaneous methods, see below.
247
+
248
+ **Subclasses (Advanced):**
249
+
250
+ The Graph class uses a dict-of-dict-of-dict data structure.
251
+ The outer dict (node_dict) holds adjacency information keyed by node.
252
+ The next dict (adjlist_dict) represents the adjacency information and holds
253
+ edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
254
+ the edge data and holds edge attribute values keyed by attribute names.
255
+
256
+ Each of these three dicts can be replaced in a subclass by a user defined
257
+ dict-like object. In general, the dict-like features should be
258
+ maintained but extra features can be added. To replace one of the
259
+ dicts create a new graph class by changing the class(!) variable
260
+ holding the factory for that dict-like structure. The variable names are
261
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
262
+ adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
263
+
264
+ node_dict_factory : function, (default: dict)
265
+ Factory function to be used to create the dict containing node
266
+ attributes, keyed by node id.
267
+ It should require no arguments and return a dict-like object
268
+
269
+ node_attr_dict_factory: function, (default: dict)
270
+ Factory function to be used to create the node attribute
271
+ dict which holds attribute values keyed by attribute name.
272
+ It should require no arguments and return a dict-like object
273
+
274
+ adjlist_outer_dict_factory : function, (default: dict)
275
+ Factory function to be used to create the outer-most dict
276
+ in the data structure that holds adjacency info keyed by node.
277
+ It should require no arguments and return a dict-like object.
278
+
279
+ adjlist_inner_dict_factory : function, optional (default: dict)
280
+ Factory function to be used to create the adjacency list
281
+ dict which holds edge data keyed by neighbor.
282
+ It should require no arguments and return a dict-like object
283
+
284
+ edge_attr_dict_factory : function, optional (default: dict)
285
+ Factory function to be used to create the edge attribute
286
+ dict which holds attribute values keyed by attribute name.
287
+ It should require no arguments and return a dict-like object.
288
+
289
+ graph_attr_dict_factory : function, (default: dict)
290
+ Factory function to be used to create the graph attribute
291
+ dict which holds attribute values keyed by attribute name.
292
+ It should require no arguments and return a dict-like object.
293
+
294
+ Typically, if your extension doesn't impact the data structure all
295
+ methods will inherited without issue except: `to_directed/to_undirected`.
296
+ By default these methods create a DiGraph/Graph class and you probably
297
+ want them to create your extension of a DiGraph/Graph. To facilitate
298
+ this we define two class variables that you can set in your subclass.
299
+
300
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
301
+ Class to create a new graph structure in the `to_directed` method.
302
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
303
+
304
+ to_undirected_class : callable, (default: Graph or MultiGraph)
305
+ Class to create a new graph structure in the `to_undirected` method.
306
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
307
+
308
+ **Subclassing Example**
309
+
310
+ Create a low memory graph class that effectively disallows edge
311
+ attributes by using a single attribute dict for all edges.
312
+ This reduces the memory used, but you lose edge attributes.
313
+
314
+ >>> class ThinGraph(nx.Graph):
315
+ ... all_edge_dict = {"weight": 1}
316
+ ...
317
+ ... def single_edge_dict(self):
318
+ ... return self.all_edge_dict
319
+ ...
320
+ ... edge_attr_dict_factory = single_edge_dict
321
+ >>> G = ThinGraph()
322
+ >>> G.add_edge(2, 1)
323
+ >>> G[2][1]
324
+ {'weight': 1}
325
+ >>> G.add_edge(2, 2)
326
+ >>> G[2][1] is G[2][2]
327
+ True
328
+ """
329
+
330
+ _adj = _CachedPropertyResetterAdjAndSucc() # type: ignore[assignment]
331
+ _succ = _adj # type: ignore[has-type]
332
+ _pred = _CachedPropertyResetterPred()
333
+
334
+ def __init__(self, incoming_graph_data=None, **attr):
335
+ """Initialize a graph with edges, name, or graph attributes.
336
+
337
+ Parameters
338
+ ----------
339
+ incoming_graph_data : input graph (optional, default: None)
340
+ Data to initialize graph. If None (default) an empty
341
+ graph is created. The data can be an edge list, or any
342
+ NetworkX graph object. If the corresponding optional Python
343
+ packages are installed the data can also be a 2D NumPy array, a
344
+ SciPy sparse array, or a PyGraphviz graph.
345
+
346
+ attr : keyword arguments, optional (default= no attributes)
347
+ Attributes to add to graph as key=value pairs.
348
+
349
+ See Also
350
+ --------
351
+ convert
352
+
353
+ Examples
354
+ --------
355
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
356
+ >>> G = nx.Graph(name="my graph")
357
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
358
+ >>> G = nx.Graph(e)
359
+
360
+ Arbitrary graph attribute pairs (key=value) may be assigned
361
+
362
+ >>> G = nx.Graph(e, day="Friday")
363
+ >>> G.graph
364
+ {'day': 'Friday'}
365
+
366
+ """
367
+ self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
368
+ self._node = self.node_dict_factory() # dictionary for node attr
369
+ # We store two adjacency lists:
370
+ # the predecessors of node n are stored in the dict self._pred
371
+ # the successors of node n are stored in the dict self._succ=self._adj
372
+ self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict successor
373
+ self._pred = self.adjlist_outer_dict_factory() # predecessor
374
+ # Note: self._succ = self._adj # successor
375
+
376
+ self.__networkx_cache__ = {}
377
+ # attempt to load graph with data
378
+ if incoming_graph_data is not None:
379
+ convert.to_networkx_graph(incoming_graph_data, create_using=self)
380
+ # load graph attributes (must be after convert)
381
+ self.graph.update(attr)
382
+
383
+ @cached_property
384
+ def adj(self):
385
+ """Graph adjacency object holding the neighbors of each node.
386
+
387
+ This object is a read-only dict-like structure with node keys
388
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
389
+ to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
390
+ the color of the edge `(3, 2)` to `"blue"`.
391
+
392
+ Iterating over G.adj behaves like a dict. Useful idioms include
393
+ `for nbr, datadict in G.adj[n].items():`.
394
+
395
+ The neighbor information is also provided by subscripting the graph.
396
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
397
+
398
+ For directed graphs, `G.adj` holds outgoing (successor) info.
399
+ """
400
+ return AdjacencyView(self._succ)
401
+
402
+ @cached_property
403
+ def succ(self):
404
+ """Graph adjacency object holding the successors of each node.
405
+
406
+ This object is a read-only dict-like structure with node keys
407
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
408
+ to the edge-data-dict. So `G.succ[3][2]['color'] = 'blue'` sets
409
+ the color of the edge `(3, 2)` to `"blue"`.
410
+
411
+ Iterating over G.succ behaves like a dict. Useful idioms include
412
+ `for nbr, datadict in G.succ[n].items():`. A data-view not provided
413
+ by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`
414
+ and a default can be set via a `default` argument to the `data` method.
415
+
416
+ The neighbor information is also provided by subscripting the graph.
417
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
418
+
419
+ For directed graphs, `G.adj` is identical to `G.succ`.
420
+ """
421
+ return AdjacencyView(self._succ)
422
+
423
+ @cached_property
424
+ def pred(self):
425
+ """Graph adjacency object holding the predecessors of each node.
426
+
427
+ This object is a read-only dict-like structure with node keys
428
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
429
+ to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
430
+ the color of the edge `(3, 2)` to `"blue"`.
431
+
432
+ Iterating over G.pred behaves like a dict. Useful idioms include
433
+ `for nbr, datadict in G.pred[n].items():`. A data-view not provided
434
+ by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
435
+ A default can be set via a `default` argument to the `data` method.
436
+ """
437
+ return AdjacencyView(self._pred)
438
+
439
+ def add_node(self, node_for_adding, **attr):
440
+ """Add a single node `node_for_adding` and update node attributes.
441
+
442
+ Parameters
443
+ ----------
444
+ node_for_adding : node
445
+ A node can be any hashable Python object except None.
446
+ attr : keyword arguments, optional
447
+ Set or change node attributes using key=value.
448
+
449
+ See Also
450
+ --------
451
+ add_nodes_from
452
+
453
+ Examples
454
+ --------
455
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
456
+ >>> G.add_node(1)
457
+ >>> G.add_node("Hello")
458
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
459
+ >>> G.add_node(K3)
460
+ >>> G.number_of_nodes()
461
+ 3
462
+
463
+ Use keywords set/change node attributes:
464
+
465
+ >>> G.add_node(1, size=10)
466
+ >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
467
+
468
+ Notes
469
+ -----
470
+ A hashable object is one that can be used as a key in a Python
471
+ dictionary. This includes strings, numbers, tuples of strings
472
+ and numbers, etc.
473
+
474
+ On many platforms hashable items also include mutables such as
475
+ NetworkX Graphs, though one should be careful that the hash
476
+ doesn't change on mutables.
477
+ """
478
+ if node_for_adding not in self._succ:
479
+ if node_for_adding is None:
480
+ raise ValueError("None cannot be a node")
481
+ self._succ[node_for_adding] = self.adjlist_inner_dict_factory()
482
+ self._pred[node_for_adding] = self.adjlist_inner_dict_factory()
483
+ attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
484
+ attr_dict.update(attr)
485
+ else: # update attr even if node already exists
486
+ self._node[node_for_adding].update(attr)
487
+ nx._clear_cache(self)
488
+
489
+ def add_nodes_from(self, nodes_for_adding, **attr):
490
+ """Add multiple nodes.
491
+
492
+ Parameters
493
+ ----------
494
+ nodes_for_adding : iterable container
495
+ A container of nodes (list, dict, set, etc.).
496
+ OR
497
+ A container of (node, attribute dict) tuples.
498
+ Node attributes are updated using the attribute dict.
499
+ attr : keyword arguments, optional (default= no attributes)
500
+ Update attributes for all nodes in nodes.
501
+ Node attributes specified in nodes as a tuple take
502
+ precedence over attributes specified via keyword arguments.
503
+
504
+ See Also
505
+ --------
506
+ add_node
507
+
508
+ Notes
509
+ -----
510
+ When adding nodes from an iterator over the graph you are changing,
511
+ a `RuntimeError` can be raised with message:
512
+ `RuntimeError: dictionary changed size during iteration`. This
513
+ happens when the graph's underlying dictionary is modified during
514
+ iteration. To avoid this error, evaluate the iterator into a separate
515
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
516
+ object to `G.add_nodes_from`.
517
+
518
+ Examples
519
+ --------
520
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
521
+ >>> G.add_nodes_from("Hello")
522
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
523
+ >>> G.add_nodes_from(K3)
524
+ >>> sorted(G.nodes(), key=str)
525
+ [0, 1, 2, 'H', 'e', 'l', 'o']
526
+
527
+ Use keywords to update specific node attributes for every node.
528
+
529
+ >>> G.add_nodes_from([1, 2], size=10)
530
+ >>> G.add_nodes_from([3, 4], weight=0.4)
531
+
532
+ Use (node, attrdict) tuples to update attributes for specific nodes.
533
+
534
+ >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
535
+ >>> G.nodes[1]["size"]
536
+ 11
537
+ >>> H = nx.Graph()
538
+ >>> H.add_nodes_from(G.nodes(data=True))
539
+ >>> H.nodes[1]["size"]
540
+ 11
541
+
542
+ Evaluate an iterator over a graph if using it to modify the same graph
543
+
544
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
545
+ >>> # wrong way - will raise RuntimeError
546
+ >>> # G.add_nodes_from(n + 1 for n in G.nodes)
547
+ >>> # correct way
548
+ >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
549
+ """
550
+ for n in nodes_for_adding:
551
+ try:
552
+ newnode = n not in self._node
553
+ newdict = attr
554
+ except TypeError:
555
+ n, ndict = n
556
+ newnode = n not in self._node
557
+ newdict = attr.copy()
558
+ newdict.update(ndict)
559
+ if newnode:
560
+ if n is None:
561
+ raise ValueError("None cannot be a node")
562
+ self._succ[n] = self.adjlist_inner_dict_factory()
563
+ self._pred[n] = self.adjlist_inner_dict_factory()
564
+ self._node[n] = self.node_attr_dict_factory()
565
+ self._node[n].update(newdict)
566
+ nx._clear_cache(self)
567
+
568
+ def remove_node(self, n):
569
+ """Remove node n.
570
+
571
+ Removes the node n and all adjacent edges.
572
+ Attempting to remove a nonexistent node will raise an exception.
573
+
574
+ Parameters
575
+ ----------
576
+ n : node
577
+ A node in the graph
578
+
579
+ Raises
580
+ ------
581
+ NetworkXError
582
+ If n is not in the graph.
583
+
584
+ See Also
585
+ --------
586
+ remove_nodes_from
587
+
588
+ Examples
589
+ --------
590
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
591
+ >>> list(G.edges)
592
+ [(0, 1), (1, 2)]
593
+ >>> G.remove_node(1)
594
+ >>> list(G.edges)
595
+ []
596
+
597
+ """
598
+ try:
599
+ nbrs = self._succ[n]
600
+ del self._node[n]
601
+ except KeyError as err: # NetworkXError if n not in self
602
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
603
+ for u in nbrs:
604
+ del self._pred[u][n] # remove all edges n-u in digraph
605
+ del self._succ[n] # remove node from succ
606
+ for u in self._pred[n]:
607
+ del self._succ[u][n] # remove all edges n-u in digraph
608
+ del self._pred[n] # remove node from pred
609
+ nx._clear_cache(self)
610
+
611
+ def remove_nodes_from(self, nodes):
612
+ """Remove multiple nodes.
613
+
614
+ Parameters
615
+ ----------
616
+ nodes : iterable container
617
+ A container of nodes (list, dict, set, etc.). If a node
618
+ in the container is not in the graph it is silently ignored.
619
+
620
+ See Also
621
+ --------
622
+ remove_node
623
+
624
+ Notes
625
+ -----
626
+ When removing nodes from an iterator over the graph you are changing,
627
+ a `RuntimeError` will be raised with message:
628
+ `RuntimeError: dictionary changed size during iteration`. This
629
+ happens when the graph's underlying dictionary is modified during
630
+ iteration. To avoid this error, evaluate the iterator into a separate
631
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
632
+ object to `G.remove_nodes_from`.
633
+
634
+ Examples
635
+ --------
636
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
637
+ >>> e = list(G.nodes)
638
+ >>> e
639
+ [0, 1, 2]
640
+ >>> G.remove_nodes_from(e)
641
+ >>> list(G.nodes)
642
+ []
643
+
644
+ Evaluate an iterator over a graph if using it to modify the same graph
645
+
646
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
647
+ >>> # this command will fail, as the graph's dict is modified during iteration
648
+ >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
649
+ >>> # this command will work, since the dictionary underlying graph is not modified
650
+ >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
651
+ """
652
+ for n in nodes:
653
+ try:
654
+ succs = self._succ[n]
655
+ del self._node[n]
656
+ for u in succs:
657
+ del self._pred[u][n] # remove all edges n-u in digraph
658
+ del self._succ[n] # now remove node
659
+ for u in self._pred[n]:
660
+ del self._succ[u][n] # remove all edges n-u in digraph
661
+ del self._pred[n] # now remove node
662
+ except KeyError:
663
+ pass # silent failure on remove
664
+ nx._clear_cache(self)
665
+
666
+ def add_edge(self, u_of_edge, v_of_edge, **attr):
667
+ """Add an edge between u and v.
668
+
669
+ The nodes u and v will be automatically added if they are
670
+ not already in the graph.
671
+
672
+ Edge attributes can be specified with keywords or by directly
673
+ accessing the edge's attribute dictionary. See examples below.
674
+
675
+ Parameters
676
+ ----------
677
+ u_of_edge, v_of_edge : nodes
678
+ Nodes can be, for example, strings or numbers.
679
+ Nodes must be hashable (and not None) Python objects.
680
+ attr : keyword arguments, optional
681
+ Edge data (or labels or objects) can be assigned using
682
+ keyword arguments.
683
+
684
+ See Also
685
+ --------
686
+ add_edges_from : add a collection of edges
687
+
688
+ Notes
689
+ -----
690
+ Adding an edge that already exists updates the edge data.
691
+
692
+ Many NetworkX algorithms designed for weighted graphs use
693
+ an edge attribute (by default `weight`) to hold a numerical value.
694
+
695
+ Examples
696
+ --------
697
+ The following all add the edge e=(1, 2) to graph G:
698
+
699
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
700
+ >>> e = (1, 2)
701
+ >>> G.add_edge(1, 2) # explicit two-node form
702
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
703
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
704
+
705
+ Associate data to edges using keywords:
706
+
707
+ >>> G.add_edge(1, 2, weight=3)
708
+ >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
709
+
710
+ For non-string attribute keys, use subscript notation.
711
+
712
+ >>> G.add_edge(1, 2)
713
+ >>> G[1][2].update({0: 5})
714
+ >>> G.edges[1, 2].update({0: 5})
715
+ """
716
+ u, v = u_of_edge, v_of_edge
717
+ # add nodes
718
+ if u not in self._succ:
719
+ if u is None:
720
+ raise ValueError("None cannot be a node")
721
+ self._succ[u] = self.adjlist_inner_dict_factory()
722
+ self._pred[u] = self.adjlist_inner_dict_factory()
723
+ self._node[u] = self.node_attr_dict_factory()
724
+ if v not in self._succ:
725
+ if v is None:
726
+ raise ValueError("None cannot be a node")
727
+ self._succ[v] = self.adjlist_inner_dict_factory()
728
+ self._pred[v] = self.adjlist_inner_dict_factory()
729
+ self._node[v] = self.node_attr_dict_factory()
730
+ # add the edge
731
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
732
+ datadict.update(attr)
733
+ self._succ[u][v] = datadict
734
+ self._pred[v][u] = datadict
735
+ nx._clear_cache(self)
736
+
737
+ def add_edges_from(self, ebunch_to_add, **attr):
738
+ """Add all the edges in ebunch_to_add.
739
+
740
+ Parameters
741
+ ----------
742
+ ebunch_to_add : container of edges
743
+ Each edge given in the container will be added to the
744
+ graph. The edges must be given as 2-tuples (u, v) or
745
+ 3-tuples (u, v, d) where d is a dictionary containing edge data.
746
+ attr : keyword arguments, optional
747
+ Edge data (or labels or objects) can be assigned using
748
+ keyword arguments.
749
+
750
+ See Also
751
+ --------
752
+ add_edge : add a single edge
753
+ add_weighted_edges_from : convenient way to add weighted edges
754
+
755
+ Notes
756
+ -----
757
+ Adding the same edge twice has no effect but any edge data
758
+ will be updated when each duplicate edge is added.
759
+
760
+ Edge attributes specified in an ebunch take precedence over
761
+ attributes specified via keyword arguments.
762
+
763
+ When adding edges from an iterator over the graph you are changing,
764
+ a `RuntimeError` can be raised with message:
765
+ `RuntimeError: dictionary changed size during iteration`. This
766
+ happens when the graph's underlying dictionary is modified during
767
+ iteration. To avoid this error, evaluate the iterator into a separate
768
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
769
+ object to `G.add_edges_from`.
770
+
771
+ Examples
772
+ --------
773
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
774
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
775
+ >>> e = zip(range(0, 3), range(1, 4))
776
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
777
+
778
+ Associate data to edges
779
+
780
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
781
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
782
+
783
+ Evaluate an iterator over a graph if using it to modify the same graph
784
+
785
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
786
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
787
+ >>> # wrong way - will raise RuntimeError
788
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
789
+ >>> # right way - note that there will be no self-edge for node 5
790
+ >>> G.add_edges_from(list((5, n) for n in G.nodes))
791
+ """
792
+ for e in ebunch_to_add:
793
+ ne = len(e)
794
+ if ne == 3:
795
+ u, v, dd = e
796
+ elif ne == 2:
797
+ u, v = e
798
+ dd = {}
799
+ else:
800
+ raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
801
+ if u not in self._succ:
802
+ if u is None:
803
+ raise ValueError("None cannot be a node")
804
+ self._succ[u] = self.adjlist_inner_dict_factory()
805
+ self._pred[u] = self.adjlist_inner_dict_factory()
806
+ self._node[u] = self.node_attr_dict_factory()
807
+ if v not in self._succ:
808
+ if v is None:
809
+ raise ValueError("None cannot be a node")
810
+ self._succ[v] = self.adjlist_inner_dict_factory()
811
+ self._pred[v] = self.adjlist_inner_dict_factory()
812
+ self._node[v] = self.node_attr_dict_factory()
813
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
814
+ datadict.update(attr)
815
+ datadict.update(dd)
816
+ self._succ[u][v] = datadict
817
+ self._pred[v][u] = datadict
818
+ nx._clear_cache(self)
819
+
820
+ def remove_edge(self, u, v):
821
+ """Remove the edge between u and v.
822
+
823
+ Parameters
824
+ ----------
825
+ u, v : nodes
826
+ Remove the edge between nodes u and v.
827
+
828
+ Raises
829
+ ------
830
+ NetworkXError
831
+ If there is not an edge between u and v.
832
+
833
+ See Also
834
+ --------
835
+ remove_edges_from : remove a collection of edges
836
+
837
+ Examples
838
+ --------
839
+ >>> G = nx.Graph() # or DiGraph, etc
840
+ >>> nx.add_path(G, [0, 1, 2, 3])
841
+ >>> G.remove_edge(0, 1)
842
+ >>> e = (1, 2)
843
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
844
+ >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
845
+ >>> G.remove_edge(*e[:2]) # select first part of edge tuple
846
+ """
847
+ try:
848
+ del self._succ[u][v]
849
+ del self._pred[v][u]
850
+ except KeyError as err:
851
+ raise NetworkXError(f"The edge {u}-{v} not in graph.") from err
852
+ nx._clear_cache(self)
853
+
854
+ def remove_edges_from(self, ebunch):
855
+ """Remove all edges specified in ebunch.
856
+
857
+ Parameters
858
+ ----------
859
+ ebunch: list or container of edge tuples
860
+ Each edge given in the list or container will be removed
861
+ from the graph. The edges can be:
862
+
863
+ - 2-tuples (u, v) edge between u and v.
864
+ - 3-tuples (u, v, k) where k is ignored.
865
+
866
+ See Also
867
+ --------
868
+ remove_edge : remove a single edge
869
+
870
+ Notes
871
+ -----
872
+ Will fail silently if an edge in ebunch is not in the graph.
873
+
874
+ Examples
875
+ --------
876
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
877
+ >>> ebunch = [(1, 2), (2, 3)]
878
+ >>> G.remove_edges_from(ebunch)
879
+ """
880
+ for e in ebunch:
881
+ u, v = e[:2] # ignore edge data
882
+ if u in self._succ and v in self._succ[u]:
883
+ del self._succ[u][v]
884
+ del self._pred[v][u]
885
+ nx._clear_cache(self)
886
+
887
+ def has_successor(self, u, v):
888
+ """Returns True if node u has successor v.
889
+
890
+ This is true if graph has the edge u->v.
891
+ """
892
+ return u in self._succ and v in self._succ[u]
893
+
894
+ def has_predecessor(self, u, v):
895
+ """Returns True if node u has predecessor v.
896
+
897
+ This is true if graph has the edge u<-v.
898
+ """
899
+ return u in self._pred and v in self._pred[u]
900
+
901
+ def successors(self, n):
902
+ """Returns an iterator over successor nodes of n.
903
+
904
+ A successor of n is a node m such that there exists a directed
905
+ edge from n to m.
906
+
907
+ Parameters
908
+ ----------
909
+ n : node
910
+ A node in the graph
911
+
912
+ Raises
913
+ ------
914
+ NetworkXError
915
+ If n is not in the graph.
916
+
917
+ See Also
918
+ --------
919
+ predecessors
920
+
921
+ Notes
922
+ -----
923
+ neighbors() and successors() are the same.
924
+ """
925
+ try:
926
+ return iter(self._succ[n])
927
+ except KeyError as err:
928
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
929
+
930
+ # digraph definitions
931
+ neighbors = successors
932
+
933
+ def predecessors(self, n):
934
+ """Returns an iterator over predecessor nodes of n.
935
+
936
+ A predecessor of n is a node m such that there exists a directed
937
+ edge from m to n.
938
+
939
+ Parameters
940
+ ----------
941
+ n : node
942
+ A node in the graph
943
+
944
+ Raises
945
+ ------
946
+ NetworkXError
947
+ If n is not in the graph.
948
+
949
+ See Also
950
+ --------
951
+ successors
952
+ """
953
+ try:
954
+ return iter(self._pred[n])
955
+ except KeyError as err:
956
+ raise NetworkXError(f"The node {n} is not in the digraph.") from err
957
+
958
+ @cached_property
959
+ def edges(self):
960
+ """An OutEdgeView of the DiGraph as G.edges or G.edges().
961
+
962
+ edges(self, nbunch=None, data=False, default=None)
963
+
964
+ The OutEdgeView provides set-like operations on the edge-tuples
965
+ as well as edge attribute lookup. When called, it also provides
966
+ an EdgeDataView object which allows control of access to edge
967
+ attributes (but does not provide set-like operations).
968
+ Hence, `G.edges[u, v]['color']` provides the value of the color
969
+ attribute for edge `(u, v)` while
970
+ `for (u, v, c) in G.edges.data('color', default='red'):`
971
+ iterates through all the edges yielding the color attribute
972
+ with default `'red'` if no color attribute exists.
973
+
974
+ Parameters
975
+ ----------
976
+ nbunch : single node, container, or all nodes (default= all nodes)
977
+ The view will only report edges from these nodes.
978
+ data : string or bool, optional (default=False)
979
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
980
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
981
+ If False, return 2-tuple (u, v).
982
+ default : value, optional (default=None)
983
+ Value used for edges that don't have the requested attribute.
984
+ Only relevant if data is not True or False.
985
+
986
+ Returns
987
+ -------
988
+ edges : OutEdgeView
989
+ A view of edge attributes, usually it iterates over (u, v)
990
+ or (u, v, d) tuples of edges, but can also be used for
991
+ attribute lookup as `edges[u, v]['foo']`.
992
+
993
+ See Also
994
+ --------
995
+ in_edges, out_edges
996
+
997
+ Notes
998
+ -----
999
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
1000
+ For directed graphs this returns the out-edges.
1001
+
1002
+ Examples
1003
+ --------
1004
+ >>> G = nx.DiGraph() # or MultiDiGraph, etc
1005
+ >>> nx.add_path(G, [0, 1, 2])
1006
+ >>> G.add_edge(2, 3, weight=5)
1007
+ >>> [e for e in G.edges]
1008
+ [(0, 1), (1, 2), (2, 3)]
1009
+ >>> G.edges.data() # default data is {} (empty dict)
1010
+ OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
1011
+ >>> G.edges.data("weight", default=1)
1012
+ OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
1013
+ >>> G.edges([0, 2]) # only edges originating from these nodes
1014
+ OutEdgeDataView([(0, 1), (2, 3)])
1015
+ >>> G.edges(0) # only edges from node 0
1016
+ OutEdgeDataView([(0, 1)])
1017
+
1018
+ """
1019
+ return OutEdgeView(self)
1020
+
1021
+ # alias out_edges to edges
1022
+ @cached_property
1023
+ def out_edges(self):
1024
+ return OutEdgeView(self)
1025
+
1026
+ out_edges.__doc__ = edges.__doc__
1027
+
1028
+ @cached_property
1029
+ def in_edges(self):
1030
+ """A view of the in edges of the graph as G.in_edges or G.in_edges().
1031
+
1032
+ in_edges(self, nbunch=None, data=False, default=None):
1033
+
1034
+ Parameters
1035
+ ----------
1036
+ nbunch : single node, container, or all nodes (default= all nodes)
1037
+ The view will only report edges incident to these nodes.
1038
+ data : string or bool, optional (default=False)
1039
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
1040
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
1041
+ If False, return 2-tuple (u, v).
1042
+ default : value, optional (default=None)
1043
+ Value used for edges that don't have the requested attribute.
1044
+ Only relevant if data is not True or False.
1045
+
1046
+ Returns
1047
+ -------
1048
+ in_edges : InEdgeView or InEdgeDataView
1049
+ A view of edge attributes, usually it iterates over (u, v)
1050
+ or (u, v, d) tuples of edges, but can also be used for
1051
+ attribute lookup as `edges[u, v]['foo']`.
1052
+
1053
+ Examples
1054
+ --------
1055
+ >>> G = nx.DiGraph()
1056
+ >>> G.add_edge(1, 2, color="blue")
1057
+ >>> G.in_edges()
1058
+ InEdgeView([(1, 2)])
1059
+ >>> G.in_edges(nbunch=2)
1060
+ InEdgeDataView([(1, 2)])
1061
+
1062
+ See Also
1063
+ --------
1064
+ edges
1065
+ """
1066
+ return InEdgeView(self)
1067
+
1068
+ @cached_property
1069
+ def degree(self):
1070
+ """A DegreeView for the Graph as G.degree or G.degree().
1071
+
1072
+ The node degree is the number of edges adjacent to the node.
1073
+ The weighted node degree is the sum of the edge weights for
1074
+ edges incident to that node.
1075
+
1076
+ This object provides an iterator for (node, degree) as well as
1077
+ lookup for the degree for a single node.
1078
+
1079
+ Parameters
1080
+ ----------
1081
+ nbunch : single node, container, or all nodes (default= all nodes)
1082
+ The view will only report edges incident to these nodes.
1083
+
1084
+ weight : string or None, optional (default=None)
1085
+ The name of an edge attribute that holds the numerical value used
1086
+ as a weight. If None, then each edge has weight 1.
1087
+ The degree is the sum of the edge weights adjacent to the node.
1088
+
1089
+ Returns
1090
+ -------
1091
+ DiDegreeView or int
1092
+ If multiple nodes are requested (the default), returns a `DiDegreeView`
1093
+ mapping nodes to their degree.
1094
+ If a single node is requested, returns the degree of the node as an integer.
1095
+
1096
+ See Also
1097
+ --------
1098
+ in_degree, out_degree
1099
+
1100
+ Examples
1101
+ --------
1102
+ >>> G = nx.DiGraph() # or MultiDiGraph
1103
+ >>> nx.add_path(G, [0, 1, 2, 3])
1104
+ >>> G.degree(0) # node 0 with degree 1
1105
+ 1
1106
+ >>> list(G.degree([0, 1, 2]))
1107
+ [(0, 1), (1, 2), (2, 2)]
1108
+
1109
+ """
1110
+ return DiDegreeView(self)
1111
+
1112
+ @cached_property
1113
+ def in_degree(self):
1114
+ """An InDegreeView for (node, in_degree) or in_degree for single node.
1115
+
1116
+ The node in_degree is the number of edges pointing to the node.
1117
+ The weighted node degree is the sum of the edge weights for
1118
+ edges incident to that node.
1119
+
1120
+ This object provides an iteration over (node, in_degree) as well as
1121
+ lookup for the degree for a single node.
1122
+
1123
+ Parameters
1124
+ ----------
1125
+ nbunch : single node, container, or all nodes (default= all nodes)
1126
+ The view will only report edges incident to these nodes.
1127
+
1128
+ weight : string or None, optional (default=None)
1129
+ The name of an edge attribute that holds the numerical value used
1130
+ as a weight. If None, then each edge has weight 1.
1131
+ The degree is the sum of the edge weights adjacent to the node.
1132
+
1133
+ Returns
1134
+ -------
1135
+ If a single node is requested
1136
+ deg : int
1137
+ In-degree of the node
1138
+
1139
+ OR if multiple nodes are requested
1140
+ nd_iter : iterator
1141
+ The iterator returns two-tuples of (node, in-degree).
1142
+
1143
+ See Also
1144
+ --------
1145
+ degree, out_degree
1146
+
1147
+ Examples
1148
+ --------
1149
+ >>> G = nx.DiGraph()
1150
+ >>> nx.add_path(G, [0, 1, 2, 3])
1151
+ >>> G.in_degree(0) # node 0 with degree 0
1152
+ 0
1153
+ >>> list(G.in_degree([0, 1, 2]))
1154
+ [(0, 0), (1, 1), (2, 1)]
1155
+
1156
+ """
1157
+ return InDegreeView(self)
1158
+
1159
+ @cached_property
1160
+ def out_degree(self):
1161
+ """An OutDegreeView for (node, out_degree)
1162
+
1163
+ The node out_degree is the number of edges pointing out of the node.
1164
+ The weighted node degree is the sum of the edge weights for
1165
+ edges incident to that node.
1166
+
1167
+ This object provides an iterator over (node, out_degree) as well as
1168
+ lookup for the degree for a single node.
1169
+
1170
+ Parameters
1171
+ ----------
1172
+ nbunch : single node, container, or all nodes (default= all nodes)
1173
+ The view will only report edges incident to these nodes.
1174
+
1175
+ weight : string or None, optional (default=None)
1176
+ The name of an edge attribute that holds the numerical value used
1177
+ as a weight. If None, then each edge has weight 1.
1178
+ The degree is the sum of the edge weights adjacent to the node.
1179
+
1180
+ Returns
1181
+ -------
1182
+ If a single node is requested
1183
+ deg : int
1184
+ Out-degree of the node
1185
+
1186
+ OR if multiple nodes are requested
1187
+ nd_iter : iterator
1188
+ The iterator returns two-tuples of (node, out-degree).
1189
+
1190
+ See Also
1191
+ --------
1192
+ degree, in_degree
1193
+
1194
+ Examples
1195
+ --------
1196
+ >>> G = nx.DiGraph()
1197
+ >>> nx.add_path(G, [0, 1, 2, 3])
1198
+ >>> G.out_degree(0) # node 0 with degree 1
1199
+ 1
1200
+ >>> list(G.out_degree([0, 1, 2]))
1201
+ [(0, 1), (1, 1), (2, 1)]
1202
+
1203
+ """
1204
+ return OutDegreeView(self)
1205
+
1206
+ def clear(self):
1207
+ """Remove all nodes and edges from the graph.
1208
+
1209
+ This also removes the name, and all graph, node, and edge attributes.
1210
+
1211
+ Examples
1212
+ --------
1213
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1214
+ >>> G.clear()
1215
+ >>> list(G.nodes)
1216
+ []
1217
+ >>> list(G.edges)
1218
+ []
1219
+
1220
+ """
1221
+ self._succ.clear()
1222
+ self._pred.clear()
1223
+ self._node.clear()
1224
+ self.graph.clear()
1225
+ nx._clear_cache(self)
1226
+
1227
+ def clear_edges(self):
1228
+ """Remove all edges from the graph without altering nodes.
1229
+
1230
+ Examples
1231
+ --------
1232
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1233
+ >>> G.clear_edges()
1234
+ >>> list(G.nodes)
1235
+ [0, 1, 2, 3]
1236
+ >>> list(G.edges)
1237
+ []
1238
+
1239
+ """
1240
+ for predecessor_dict in self._pred.values():
1241
+ predecessor_dict.clear()
1242
+ for successor_dict in self._succ.values():
1243
+ successor_dict.clear()
1244
+ nx._clear_cache(self)
1245
+
1246
+ def is_multigraph(self):
1247
+ """Returns True if graph is a multigraph, False otherwise."""
1248
+ return False
1249
+
1250
+ def is_directed(self):
1251
+ """Returns True if graph is directed, False otherwise."""
1252
+ return True
1253
+
1254
+ def to_undirected(self, reciprocal=False, as_view=False):
1255
+ """Returns an undirected representation of the digraph.
1256
+
1257
+ Parameters
1258
+ ----------
1259
+ reciprocal : bool (optional)
1260
+ If True only keep edges that appear in both directions
1261
+ in the original digraph.
1262
+ as_view : bool (optional, default=False)
1263
+ If True return an undirected view of the original directed graph.
1264
+
1265
+ Returns
1266
+ -------
1267
+ G : Graph
1268
+ An undirected graph with the same name and nodes and
1269
+ with edge (u, v, data) if either (u, v, data) or (v, u, data)
1270
+ is in the digraph. If both edges exist in digraph and
1271
+ their edge data is different, only one edge is created
1272
+ with an arbitrary choice of which edge data to use.
1273
+ You must check and correct for this manually if desired.
1274
+
1275
+ See Also
1276
+ --------
1277
+ Graph, copy, add_edge, add_edges_from
1278
+
1279
+ Notes
1280
+ -----
1281
+ If edges in both directions (u, v) and (v, u) exist in the
1282
+ graph, attributes for the new undirected edge will be a combination of
1283
+ the attributes of the directed edges. The edge data is updated
1284
+ in the (arbitrary) order that the edges are encountered. For
1285
+ more customized control of the edge attributes use add_edge().
1286
+
1287
+ This returns a "deepcopy" of the edge, node, and
1288
+ graph attributes which attempts to completely copy
1289
+ all of the data and references.
1290
+
1291
+ This is in contrast to the similar G=DiGraph(D) which returns a
1292
+ shallow copy of the data.
1293
+
1294
+ See the Python copy module for more information on shallow
1295
+ and deep copies, https://docs.python.org/3/library/copy.html.
1296
+
1297
+ Warning: If you have subclassed DiGraph to use dict-like objects
1298
+ in the data structure, those changes do not transfer to the
1299
+ Graph created by this method.
1300
+
1301
+ Examples
1302
+ --------
1303
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
1304
+ >>> H = G.to_directed()
1305
+ >>> list(H.edges)
1306
+ [(0, 1), (1, 0)]
1307
+ >>> G2 = H.to_undirected()
1308
+ >>> list(G2.edges)
1309
+ [(0, 1)]
1310
+ """
1311
+ graph_class = self.to_undirected_class()
1312
+ if as_view is True:
1313
+ return nx.graphviews.generic_graph_view(self, graph_class)
1314
+ # deepcopy when not a view
1315
+ G = graph_class()
1316
+ G.graph.update(deepcopy(self.graph))
1317
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1318
+ if reciprocal is True:
1319
+ G.add_edges_from(
1320
+ (u, v, deepcopy(d))
1321
+ for u, nbrs in self._adj.items()
1322
+ for v, d in nbrs.items()
1323
+ if v in self._pred[u]
1324
+ )
1325
+ else:
1326
+ G.add_edges_from(
1327
+ (u, v, deepcopy(d))
1328
+ for u, nbrs in self._adj.items()
1329
+ for v, d in nbrs.items()
1330
+ )
1331
+ return G
1332
+
1333
+ def reverse(self, copy=True):
1334
+ """Returns the reverse of the graph.
1335
+
1336
+ The reverse is a graph with the same nodes and edges
1337
+ but with the directions of the edges reversed.
1338
+
1339
+ Parameters
1340
+ ----------
1341
+ copy : bool optional (default=True)
1342
+ If True, return a new DiGraph holding the reversed edges.
1343
+ If False, the reverse graph is created using a view of
1344
+ the original graph.
1345
+ """
1346
+ if copy:
1347
+ H = self.__class__()
1348
+ H.graph.update(deepcopy(self.graph))
1349
+ H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items())
1350
+ H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True))
1351
+ return H
1352
+ return nx.reverse_view(self)
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/filters.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filter factories to hide or show sets of nodes and edges.
2
+
3
+ These filters return the function used when creating `SubGraph`.
4
+ """
5
+
6
+ __all__ = [
7
+ "no_filter",
8
+ "hide_nodes",
9
+ "hide_edges",
10
+ "hide_multiedges",
11
+ "hide_diedges",
12
+ "hide_multidiedges",
13
+ "show_nodes",
14
+ "show_edges",
15
+ "show_multiedges",
16
+ "show_diedges",
17
+ "show_multidiedges",
18
+ ]
19
+
20
+
21
+ def no_filter(*items):
22
+ """Returns a filter function that always evaluates to True."""
23
+ return True
24
+
25
+
26
+ def hide_nodes(nodes):
27
+ """Returns a filter function that hides specific nodes."""
28
+ nodes = set(nodes)
29
+ return lambda node: node not in nodes
30
+
31
+
32
+ def hide_diedges(edges):
33
+ """Returns a filter function that hides specific directed edges."""
34
+ edges = {(u, v) for u, v in edges}
35
+ return lambda u, v: (u, v) not in edges
36
+
37
+
38
+ def hide_edges(edges):
39
+ """Returns a filter function that hides specific undirected edges."""
40
+ alledges = set(edges) | {(v, u) for (u, v) in edges}
41
+ return lambda u, v: (u, v) not in alledges
42
+
43
+
44
+ def hide_multidiedges(edges):
45
+ """Returns a filter function that hides specific multi-directed edges."""
46
+ edges = {(u, v, k) for u, v, k in edges}
47
+ return lambda u, v, k: (u, v, k) not in edges
48
+
49
+
50
+ def hide_multiedges(edges):
51
+ """Returns a filter function that hides specific multi-undirected edges."""
52
+ alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
53
+ return lambda u, v, k: (u, v, k) not in alledges
54
+
55
+
56
+ # write show_nodes as a class to make SubGraph pickleable
57
+ class show_nodes:
58
+ """Filter class to show specific nodes.
59
+
60
+ Attach the set of nodes as an attribute to speed up this commonly used filter
61
+
62
+ Note that another allowed attribute for filters is to store the number of nodes
63
+ on the filter as attribute `length` (used in `__len__`). It is a user
64
+ responsibility to ensure this attribute is accurate if present.
65
+ """
66
+
67
+ def __init__(self, nodes):
68
+ self.nodes = set(nodes)
69
+
70
+ def __call__(self, node):
71
+ return node in self.nodes
72
+
73
+
74
+ def show_diedges(edges):
75
+ """Returns a filter function that shows specific directed edges."""
76
+ edges = {(u, v) for u, v in edges}
77
+ return lambda u, v: (u, v) in edges
78
+
79
+
80
+ def show_edges(edges):
81
+ """Returns a filter function that shows specific undirected edges."""
82
+ alledges = set(edges) | {(v, u) for (u, v) in edges}
83
+ return lambda u, v: (u, v) in alledges
84
+
85
+
86
+ def show_multidiedges(edges):
87
+ """Returns a filter function that shows specific multi-directed edges."""
88
+ edges = {(u, v, k) for u, v, k in edges}
89
+ return lambda u, v, k: (u, v, k) in edges
90
+
91
+
92
+ def show_multiedges(edges):
93
+ """Returns a filter function that shows specific multi-undirected edges."""
94
+ alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
95
+ return lambda u, v, k: (u, v, k) in alledges
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/function.py ADDED
@@ -0,0 +1,1407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functional interface to graph methods and assorted utilities."""
2
+
3
+ from collections import Counter
4
+ from itertools import chain
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for, pairwise
8
+
9
+ __all__ = [
10
+ "nodes",
11
+ "edges",
12
+ "degree",
13
+ "degree_histogram",
14
+ "neighbors",
15
+ "number_of_nodes",
16
+ "number_of_edges",
17
+ "density",
18
+ "is_directed",
19
+ "freeze",
20
+ "is_frozen",
21
+ "subgraph",
22
+ "induced_subgraph",
23
+ "edge_subgraph",
24
+ "restricted_view",
25
+ "to_directed",
26
+ "to_undirected",
27
+ "add_star",
28
+ "add_path",
29
+ "add_cycle",
30
+ "create_empty_copy",
31
+ "set_node_attributes",
32
+ "get_node_attributes",
33
+ "remove_node_attributes",
34
+ "set_edge_attributes",
35
+ "get_edge_attributes",
36
+ "remove_edge_attributes",
37
+ "all_neighbors",
38
+ "non_neighbors",
39
+ "non_edges",
40
+ "common_neighbors",
41
+ "is_weighted",
42
+ "is_negatively_weighted",
43
+ "is_empty",
44
+ "selfloop_edges",
45
+ "nodes_with_selfloops",
46
+ "number_of_selfloops",
47
+ "path_weight",
48
+ "is_path",
49
+ ]
50
+
51
+
52
+ def nodes(G):
53
+ """Returns a NodeView over the graph nodes.
54
+
55
+ This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
56
+ """
57
+ return G.nodes()
58
+
59
+
60
+ def edges(G, nbunch=None):
61
+ """Returns an edge view of edges incident to nodes in nbunch.
62
+
63
+ Return all edges if nbunch is unspecified or nbunch=None.
64
+
65
+ For digraphs, edges=out_edges
66
+
67
+ This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
68
+ """
69
+ return G.edges(nbunch)
70
+
71
+
72
+ def degree(G, nbunch=None, weight=None):
73
+ """Returns a degree view of single node or of nbunch of nodes.
74
+ If nbunch is omitted, then return degrees of *all* nodes.
75
+
76
+ This function wraps the :func:`G.degree <networkx.Graph.degree>` property.
77
+ """
78
+ return G.degree(nbunch, weight)
79
+
80
+
81
+ def neighbors(G, n):
82
+ """Returns an iterator over all neighbors of node n.
83
+
84
+ This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
85
+ """
86
+ return G.neighbors(n)
87
+
88
+
89
+ def number_of_nodes(G):
90
+ """Returns the number of nodes in the graph.
91
+
92
+ This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
93
+ """
94
+ return G.number_of_nodes()
95
+
96
+
97
+ def number_of_edges(G):
98
+ """Returns the number of edges in the graph.
99
+
100
+ This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
101
+ """
102
+ return G.number_of_edges()
103
+
104
+
105
+ def density(G):
106
+ r"""Returns the density of a graph.
107
+
108
+ The density for undirected graphs is
109
+
110
+ .. math::
111
+
112
+ d = \frac{2m}{n(n-1)},
113
+
114
+ and for directed graphs is
115
+
116
+ .. math::
117
+
118
+ d = \frac{m}{n(n-1)},
119
+
120
+ where `n` is the number of nodes and `m` is the number of edges in `G`.
121
+
122
+ Notes
123
+ -----
124
+ The density is 0 for a graph without edges and 1 for a complete graph.
125
+ The density of multigraphs can be higher than 1.
126
+
127
+ Self loops are counted in the total number of edges so graphs with self
128
+ loops can have density higher than 1.
129
+ """
130
+ n = number_of_nodes(G)
131
+ m = number_of_edges(G)
132
+ if m == 0 or n <= 1:
133
+ return 0
134
+ d = m / (n * (n - 1))
135
+ if not G.is_directed():
136
+ d *= 2
137
+ return d
138
+
139
+
140
+ def degree_histogram(G):
141
+ """Returns a list of the frequency of each degree value.
142
+
143
+ Parameters
144
+ ----------
145
+ G : Networkx graph
146
+ A graph
147
+
148
+ Returns
149
+ -------
150
+ hist : list
151
+ A list of frequencies of degrees.
152
+ The degree values are the index in the list.
153
+
154
+ Notes
155
+ -----
156
+ Note: the bins are width one, hence len(list) can be large
157
+ (Order(number_of_edges))
158
+ """
159
+ counts = Counter(d for n, d in G.degree())
160
+ return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
161
+
162
+
163
+ def is_directed(G):
164
+ """Return True if graph is directed."""
165
+ return G.is_directed()
166
+
167
+
168
+ def frozen(*args, **kwargs):
169
+ """Dummy method for raising errors when trying to modify frozen graphs"""
170
+ raise nx.NetworkXError("Frozen graph can't be modified")
171
+
172
+
173
+ def freeze(G):
174
+ """Modify graph to prevent further change by adding or removing
175
+ nodes or edges.
176
+
177
+ Node and edge data can still be modified.
178
+
179
+ Parameters
180
+ ----------
181
+ G : graph
182
+ A NetworkX graph
183
+
184
+ Examples
185
+ --------
186
+ >>> G = nx.path_graph(4)
187
+ >>> G = nx.freeze(G)
188
+ >>> try:
189
+ ... G.add_edge(4, 5)
190
+ ... except nx.NetworkXError as err:
191
+ ... print(str(err))
192
+ Frozen graph can't be modified
193
+
194
+ Notes
195
+ -----
196
+ To "unfreeze" a graph you must make a copy by creating a new graph object:
197
+
198
+ >>> graph = nx.path_graph(4)
199
+ >>> frozen_graph = nx.freeze(graph)
200
+ >>> unfrozen_graph = nx.Graph(frozen_graph)
201
+ >>> nx.is_frozen(unfrozen_graph)
202
+ False
203
+
204
+ See Also
205
+ --------
206
+ is_frozen
207
+ """
208
+ G.add_node = frozen
209
+ G.add_nodes_from = frozen
210
+ G.remove_node = frozen
211
+ G.remove_nodes_from = frozen
212
+ G.add_edge = frozen
213
+ G.add_edges_from = frozen
214
+ G.add_weighted_edges_from = frozen
215
+ G.remove_edge = frozen
216
+ G.remove_edges_from = frozen
217
+ G.clear = frozen
218
+ G.clear_edges = frozen
219
+ G.frozen = True
220
+ return G
221
+
222
+
223
+ def is_frozen(G):
224
+ """Returns True if graph is frozen.
225
+
226
+ Parameters
227
+ ----------
228
+ G : graph
229
+ A NetworkX graph
230
+
231
+ See Also
232
+ --------
233
+ freeze
234
+ """
235
+ try:
236
+ return G.frozen
237
+ except AttributeError:
238
+ return False
239
+
240
+
241
+ def add_star(G_to_add_to, nodes_for_star, **attr):
242
+ """Add a star to Graph G_to_add_to.
243
+
244
+ The first node in `nodes_for_star` is the middle of the star.
245
+ It is connected to all other nodes.
246
+
247
+ Parameters
248
+ ----------
249
+ G_to_add_to : graph
250
+ A NetworkX graph
251
+ nodes_for_star : iterable container
252
+ A container of nodes.
253
+ attr : keyword arguments, optional (default= no attributes)
254
+ Attributes to add to every edge in star.
255
+
256
+ See Also
257
+ --------
258
+ add_path, add_cycle
259
+
260
+ Examples
261
+ --------
262
+ >>> G = nx.Graph()
263
+ >>> nx.add_star(G, [0, 1, 2, 3])
264
+ >>> nx.add_star(G, [10, 11, 12], weight=2)
265
+ """
266
+ nlist = iter(nodes_for_star)
267
+ try:
268
+ v = next(nlist)
269
+ except StopIteration:
270
+ return
271
+ G_to_add_to.add_node(v)
272
+ edges = ((v, n) for n in nlist)
273
+ G_to_add_to.add_edges_from(edges, **attr)
274
+
275
+
276
+ def add_path(G_to_add_to, nodes_for_path, **attr):
277
+ """Add a path to the Graph G_to_add_to.
278
+
279
+ Parameters
280
+ ----------
281
+ G_to_add_to : graph
282
+ A NetworkX graph
283
+ nodes_for_path : iterable container
284
+ A container of nodes. A path will be constructed from
285
+ the nodes (in order) and added to the graph.
286
+ attr : keyword arguments, optional (default= no attributes)
287
+ Attributes to add to every edge in path.
288
+
289
+ See Also
290
+ --------
291
+ add_star, add_cycle
292
+
293
+ Examples
294
+ --------
295
+ >>> G = nx.Graph()
296
+ >>> nx.add_path(G, [0, 1, 2, 3])
297
+ >>> nx.add_path(G, [10, 11, 12], weight=7)
298
+ """
299
+ nlist = iter(nodes_for_path)
300
+ try:
301
+ first_node = next(nlist)
302
+ except StopIteration:
303
+ return
304
+ G_to_add_to.add_node(first_node)
305
+ G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
306
+
307
+
308
+ def add_cycle(G_to_add_to, nodes_for_cycle, **attr):
309
+ """Add a cycle to the Graph G_to_add_to.
310
+
311
+ Parameters
312
+ ----------
313
+ G_to_add_to : graph
314
+ A NetworkX graph
315
+ nodes_for_cycle: iterable container
316
+ A container of nodes. A cycle will be constructed from
317
+ the nodes (in order) and added to the graph.
318
+ attr : keyword arguments, optional (default= no attributes)
319
+ Attributes to add to every edge in cycle.
320
+
321
+ See Also
322
+ --------
323
+ add_path, add_star
324
+
325
+ Examples
326
+ --------
327
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
328
+ >>> nx.add_cycle(G, [0, 1, 2, 3])
329
+ >>> nx.add_cycle(G, [10, 11, 12], weight=7)
330
+ """
331
+ nlist = iter(nodes_for_cycle)
332
+ try:
333
+ first_node = next(nlist)
334
+ except StopIteration:
335
+ return
336
+ G_to_add_to.add_node(first_node)
337
+ G_to_add_to.add_edges_from(
338
+ pairwise(chain((first_node,), nlist), cyclic=True), **attr
339
+ )
340
+
341
+
342
+ def subgraph(G, nbunch):
343
+ """Returns the subgraph induced on nodes in nbunch.
344
+
345
+ Parameters
346
+ ----------
347
+ G : graph
348
+ A NetworkX graph
349
+
350
+ nbunch : list, iterable
351
+ A container of nodes that will be iterated through once (thus
352
+ it should be an iterator or be iterable). Each element of the
353
+ container should be a valid node type: any hashable type except
354
+ None. If nbunch is None, return all edges data in the graph.
355
+ Nodes in nbunch that are not in the graph will be (quietly)
356
+ ignored.
357
+
358
+ Notes
359
+ -----
360
+ subgraph(G) calls G.subgraph()
361
+ """
362
+ return G.subgraph(nbunch)
363
+
364
+
365
+ def induced_subgraph(G, nbunch):
366
+ """Returns a SubGraph view of `G` showing only nodes in nbunch.
367
+
368
+ The induced subgraph of a graph on a set of nodes N is the
369
+ graph with nodes N and edges from G which have both ends in N.
370
+
371
+ Parameters
372
+ ----------
373
+ G : NetworkX Graph
374
+ nbunch : node, container of nodes or None (for all nodes)
375
+
376
+ Returns
377
+ -------
378
+ subgraph : SubGraph View
379
+ A read-only view of the subgraph in `G` induced by the nodes.
380
+ Changes to the graph `G` will be reflected in the view.
381
+
382
+ Notes
383
+ -----
384
+ To create a mutable subgraph with its own copies of nodes
385
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
386
+
387
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
388
+ `G.remove_nodes_from(n in G if n not in set(nbunch))`
389
+
390
+ If you are going to compute subgraphs of your subgraphs you could
391
+ end up with a chain of views that can be very slow once the chain
392
+ has about 15 views in it. If they are all induced subgraphs, you
393
+ can short-cut the chain by making them all subgraphs of the original
394
+ graph. The graph class method `G.subgraph` does this when `G` is
395
+ a subgraph. In contrast, this function allows you to choose to build
396
+ chains or not, as you wish. The returned subgraph is a view on `G`.
397
+
398
+ Examples
399
+ --------
400
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
401
+ >>> H = nx.induced_subgraph(G, [0, 1, 3])
402
+ >>> list(H.edges)
403
+ [(0, 1)]
404
+ >>> list(H.nodes)
405
+ [0, 1, 3]
406
+ """
407
+ induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
408
+ return nx.subgraph_view(G, filter_node=induced_nodes)
409
+
410
+
411
+ def edge_subgraph(G, edges):
412
+ """Returns a view of the subgraph induced by the specified edges.
413
+
414
+ The induced subgraph contains each edge in `edges` and each
415
+ node incident to any of those edges.
416
+
417
+ Parameters
418
+ ----------
419
+ G : NetworkX Graph
420
+ edges : iterable
421
+ An iterable of edges. Edges not present in `G` are ignored.
422
+
423
+ Returns
424
+ -------
425
+ subgraph : SubGraph View
426
+ A read-only edge-induced subgraph of `G`.
427
+ Changes to `G` are reflected in the view.
428
+
429
+ Notes
430
+ -----
431
+ To create a mutable subgraph with its own copies of nodes
432
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
433
+
434
+ If you create a subgraph of a subgraph recursively you can end up
435
+ with a chain of subgraphs that becomes very slow with about 15
436
+ nested subgraph views. Luckily the edge_subgraph filter nests
437
+ nicely so you can use the original graph as G in this function
438
+ to avoid chains. We do not rule out chains programmatically so
439
+ that odd cases like an `edge_subgraph` of a `restricted_view`
440
+ can be created.
441
+
442
+ Examples
443
+ --------
444
+ >>> G = nx.path_graph(5)
445
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
446
+ >>> list(H.nodes)
447
+ [0, 1, 3, 4]
448
+ >>> list(H.edges)
449
+ [(0, 1), (3, 4)]
450
+ """
451
+ nxf = nx.filters
452
+ edges = set(edges)
453
+ nodes = set()
454
+ for e in edges:
455
+ nodes.update(e[:2])
456
+ induced_nodes = nxf.show_nodes(nodes)
457
+ if G.is_multigraph():
458
+ if G.is_directed():
459
+ induced_edges = nxf.show_multidiedges(edges)
460
+ else:
461
+ induced_edges = nxf.show_multiedges(edges)
462
+ else:
463
+ if G.is_directed():
464
+ induced_edges = nxf.show_diedges(edges)
465
+ else:
466
+ induced_edges = nxf.show_edges(edges)
467
+ return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
468
+
469
+
470
+ def restricted_view(G, nodes, edges):
471
+ """Returns a view of `G` with hidden nodes and edges.
472
+
473
+ The resulting subgraph filters out node `nodes` and edges `edges`.
474
+ Filtered out nodes also filter out any of their edges.
475
+
476
+ Parameters
477
+ ----------
478
+ G : NetworkX Graph
479
+ nodes : iterable
480
+ An iterable of nodes. Nodes not present in `G` are ignored.
481
+ edges : iterable
482
+ An iterable of edges. Edges not present in `G` are ignored.
483
+
484
+ Returns
485
+ -------
486
+ subgraph : SubGraph View
487
+ A read-only restricted view of `G` filtering out nodes and edges.
488
+ Changes to `G` are reflected in the view.
489
+
490
+ Notes
491
+ -----
492
+ To create a mutable subgraph with its own copies of nodes
493
+ edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
494
+
495
+ If you create a subgraph of a subgraph recursively you may end up
496
+ with a chain of subgraph views. Such chains can get quite slow
497
+ for lengths near 15. To avoid long chains, try to make your subgraph
498
+ based on the original graph. We do not rule out chains programmatically
499
+ so that odd cases like an `edge_subgraph` of a `restricted_view`
500
+ can be created.
501
+
502
+ Examples
503
+ --------
504
+ >>> G = nx.path_graph(5)
505
+ >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)])
506
+ >>> list(H.nodes)
507
+ [1, 2, 3, 4]
508
+ >>> list(H.edges)
509
+ [(2, 3)]
510
+ """
511
+ nxf = nx.filters
512
+ hide_nodes = nxf.hide_nodes(nodes)
513
+ if G.is_multigraph():
514
+ if G.is_directed():
515
+ hide_edges = nxf.hide_multidiedges(edges)
516
+ else:
517
+ hide_edges = nxf.hide_multiedges(edges)
518
+ else:
519
+ if G.is_directed():
520
+ hide_edges = nxf.hide_diedges(edges)
521
+ else:
522
+ hide_edges = nxf.hide_edges(edges)
523
+ return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
524
+
525
+
526
+ def to_directed(graph):
527
+ """Returns a directed view of the graph `graph`.
528
+
529
+ Identical to graph.to_directed(as_view=True)
530
+ Note that graph.to_directed defaults to `as_view=False`
531
+ while this function always provides a view.
532
+ """
533
+ return graph.to_directed(as_view=True)
534
+
535
+
536
+ def to_undirected(graph):
537
+ """Returns an undirected view of the graph `graph`.
538
+
539
+ Identical to graph.to_undirected(as_view=True)
540
+ Note that graph.to_undirected defaults to `as_view=False`
541
+ while this function always provides a view.
542
+ """
543
+ return graph.to_undirected(as_view=True)
544
+
545
+
546
+ def create_empty_copy(G, with_data=True):
547
+ """Returns a copy of the graph G with all of the edges removed.
548
+
549
+ Parameters
550
+ ----------
551
+ G : graph
552
+ A NetworkX graph
553
+
554
+ with_data : bool (default=True)
555
+ Propagate Graph and Nodes data to the new graph.
556
+
557
+ See Also
558
+ --------
559
+ empty_graph
560
+
561
+ """
562
+ H = G.__class__()
563
+ H.add_nodes_from(G.nodes(data=with_data))
564
+ if with_data:
565
+ H.graph.update(G.graph)
566
+ return H
567
+
568
+
569
+ def set_node_attributes(G, values, name=None):
570
+ """Sets node attributes from a given value or dictionary of values.
571
+
572
+ .. Warning:: The call order of arguments `values` and `name`
573
+ switched between v1.x & v2.x.
574
+
575
+ Parameters
576
+ ----------
577
+ G : NetworkX Graph
578
+
579
+ values : scalar value, dict-like
580
+ What the node attribute should be set to. If `values` is
581
+ not a dictionary, then it is treated as a single attribute value
582
+ that is then applied to every node in `G`. This means that if
583
+ you provide a mutable object, like a list, updates to that object
584
+ will be reflected in the node attribute for every node.
585
+ The attribute name will be `name`.
586
+
587
+ If `values` is a dict or a dict of dict, it should be keyed
588
+ by node to either an attribute value or a dict of attribute key/value
589
+ pairs used to update the node's attributes.
590
+
591
+ name : string (optional, default=None)
592
+ Name of the node attribute to set if values is a scalar.
593
+
594
+ Examples
595
+ --------
596
+ After computing some property of the nodes of a graph, you may want
597
+ to assign a node attribute to store the value of that property for
598
+ each node::
599
+
600
+ >>> G = nx.path_graph(3)
601
+ >>> bb = nx.betweenness_centrality(G)
602
+ >>> isinstance(bb, dict)
603
+ True
604
+ >>> nx.set_node_attributes(G, bb, "betweenness")
605
+ >>> G.nodes[1]["betweenness"]
606
+ 1.0
607
+
608
+ If you provide a list as the second argument, updates to the list
609
+ will be reflected in the node attribute for each node::
610
+
611
+ >>> G = nx.path_graph(3)
612
+ >>> labels = []
613
+ >>> nx.set_node_attributes(G, labels, "labels")
614
+ >>> labels.append("foo")
615
+ >>> G.nodes[0]["labels"]
616
+ ['foo']
617
+ >>> G.nodes[1]["labels"]
618
+ ['foo']
619
+ >>> G.nodes[2]["labels"]
620
+ ['foo']
621
+
622
+ If you provide a dictionary of dictionaries as the second argument,
623
+ the outer dictionary is assumed to be keyed by node to an inner
624
+ dictionary of node attributes for that node::
625
+
626
+ >>> G = nx.path_graph(3)
627
+ >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}}
628
+ >>> nx.set_node_attributes(G, attrs)
629
+ >>> G.nodes[0]["attr1"]
630
+ 20
631
+ >>> G.nodes[0]["attr2"]
632
+ 'nothing'
633
+ >>> G.nodes[1]["attr2"]
634
+ 3
635
+ >>> G.nodes[2]
636
+ {}
637
+
638
+ Note that if the dictionary contains nodes that are not in `G`, the
639
+ values are silently ignored::
640
+
641
+ >>> G = nx.Graph()
642
+ >>> G.add_node(0)
643
+ >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color")
644
+ >>> G.nodes[0]["color"]
645
+ 'red'
646
+ >>> 1 in G.nodes
647
+ False
648
+
649
+ """
650
+ # Set node attributes based on type of `values`
651
+ if name is not None: # `values` must not be a dict of dict
652
+ try: # `values` is a dict
653
+ for n, v in values.items():
654
+ try:
655
+ G.nodes[n][name] = values[n]
656
+ except KeyError:
657
+ pass
658
+ except AttributeError: # `values` is a constant
659
+ for n in G:
660
+ G.nodes[n][name] = values
661
+ else: # `values` must be dict of dict
662
+ for n, d in values.items():
663
+ try:
664
+ G.nodes[n].update(d)
665
+ except KeyError:
666
+ pass
667
+ nx._clear_cache(G)
668
+
669
+
670
+ def get_node_attributes(G, name, default=None):
671
+ """Get node attributes from graph
672
+
673
+ Parameters
674
+ ----------
675
+ G : NetworkX Graph
676
+
677
+ name : string
678
+ Attribute name
679
+
680
+ default: object (default=None)
681
+ Default value of the node attribute if there is no value set for that
682
+ node in graph. If `None` then nodes without this attribute are not
683
+ included in the returned dict.
684
+
685
+ Returns
686
+ -------
687
+ Dictionary of attributes keyed by node.
688
+
689
+ Examples
690
+ --------
691
+ >>> G = nx.Graph()
692
+ >>> G.add_nodes_from([1, 2, 3], color="red")
693
+ >>> color = nx.get_node_attributes(G, "color")
694
+ >>> color[1]
695
+ 'red'
696
+ >>> G.add_node(4)
697
+ >>> color = nx.get_node_attributes(G, "color", default="yellow")
698
+ >>> color[4]
699
+ 'yellow'
700
+ """
701
+ if default is not None:
702
+ return {n: d.get(name, default) for n, d in G.nodes.items()}
703
+ return {n: d[name] for n, d in G.nodes.items() if name in d}
704
+
705
+
706
+ def remove_node_attributes(G, *attr_names, nbunch=None):
707
+ """Remove node attributes from all nodes in the graph.
708
+
709
+ Parameters
710
+ ----------
711
+ G : NetworkX Graph
712
+
713
+ *attr_names : List of Strings
714
+ The attribute names to remove from the graph.
715
+
716
+ nbunch : List of Nodes
717
+ Remove the node attributes only from the nodes in this list.
718
+
719
+ Examples
720
+ --------
721
+ >>> G = nx.Graph()
722
+ >>> G.add_nodes_from([1, 2, 3], color="blue")
723
+ >>> nx.get_node_attributes(G, "color")
724
+ {1: 'blue', 2: 'blue', 3: 'blue'}
725
+ >>> nx.remove_node_attributes(G, "color")
726
+ >>> nx.get_node_attributes(G, "color")
727
+ {}
728
+ """
729
+
730
+ if nbunch is None:
731
+ nbunch = G.nodes()
732
+
733
+ for attr in attr_names:
734
+ for n, d in G.nodes(data=True):
735
+ if n in nbunch:
736
+ try:
737
+ del d[attr]
738
+ except KeyError:
739
+ pass
740
+
741
+
742
+ def set_edge_attributes(G, values, name=None):
743
+ """Sets edge attributes from a given value or dictionary of values.
744
+
745
+ .. Warning:: The call order of arguments `values` and `name`
746
+ switched between v1.x & v2.x.
747
+
748
+ Parameters
749
+ ----------
750
+ G : NetworkX Graph
751
+
752
+ values : scalar value, dict-like
753
+ What the edge attribute should be set to. If `values` is
754
+ not a dictionary, then it is treated as a single attribute value
755
+ that is then applied to every edge in `G`. This means that if
756
+ you provide a mutable object, like a list, updates to that object
757
+ will be reflected in the edge attribute for each edge. The attribute
758
+ name will be `name`.
759
+
760
+ If `values` is a dict or a dict of dict, it should be keyed
761
+ by edge tuple to either an attribute value or a dict of attribute
762
+ key/value pairs used to update the edge's attributes.
763
+ For multigraphs, the edge tuples must be of the form ``(u, v, key)``,
764
+ where `u` and `v` are nodes and `key` is the edge key.
765
+ For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
766
+
767
+ name : string (optional, default=None)
768
+ Name of the edge attribute to set if values is a scalar.
769
+
770
+ Examples
771
+ --------
772
+ After computing some property of the edges of a graph, you may want
773
+ to assign a edge attribute to store the value of that property for
774
+ each edge::
775
+
776
+ >>> G = nx.path_graph(3)
777
+ >>> bb = nx.edge_betweenness_centrality(G, normalized=False)
778
+ >>> nx.set_edge_attributes(G, bb, "betweenness")
779
+ >>> G.edges[1, 2]["betweenness"]
780
+ 2.0
781
+
782
+ If you provide a list as the second argument, updates to the list
783
+ will be reflected in the edge attribute for each edge::
784
+
785
+ >>> labels = []
786
+ >>> nx.set_edge_attributes(G, labels, "labels")
787
+ >>> labels.append("foo")
788
+ >>> G.edges[0, 1]["labels"]
789
+ ['foo']
790
+ >>> G.edges[1, 2]["labels"]
791
+ ['foo']
792
+
793
+ If you provide a dictionary of dictionaries as the second argument,
794
+ the entire dictionary will be used to update edge attributes::
795
+
796
+ >>> G = nx.path_graph(3)
797
+ >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}}
798
+ >>> nx.set_edge_attributes(G, attrs)
799
+ >>> G[0][1]["attr1"]
800
+ 20
801
+ >>> G[0][1]["attr2"]
802
+ 'nothing'
803
+ >>> G[1][2]["attr2"]
804
+ 3
805
+
806
+ The attributes of one Graph can be used to set those of another.
807
+
808
+ >>> H = nx.path_graph(3)
809
+ >>> nx.set_edge_attributes(H, G.edges)
810
+
811
+ Note that if the dict contains edges that are not in `G`, they are
812
+ silently ignored::
813
+
814
+ >>> G = nx.Graph([(0, 1)])
815
+ >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}})
816
+ >>> (1, 2) in G.edges()
817
+ False
818
+
819
+ For multigraphs, the `values` dict is expected to be keyed by 3-tuples
820
+ including the edge key::
821
+
822
+ >>> MG = nx.MultiGraph()
823
+ >>> edges = [(0, 1), (0, 1)]
824
+ >>> MG.add_edges_from(edges) # Returns list of edge keys
825
+ [0, 1]
826
+ >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
827
+ >>> nx.set_edge_attributes(MG, attributes)
828
+ >>> MG[0][1][0]["cost"]
829
+ 21
830
+ >>> MG[0][1][1]["cost"]
831
+ 7
832
+
833
+ If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
834
+ multiedge to a 2-tuple edge and the last multiedge's attribute value will
835
+ overwrite the previous values. Continuing from the previous case we get::
836
+
837
+ >>> H = nx.path_graph([0, 1, 2])
838
+ >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
839
+ >>> nx.get_edge_attributes(H, "cost")
840
+ {(0, 1): 7}
841
+
842
+ """
843
+ if name is not None:
844
+ # `values` does not contain attribute names
845
+ try:
846
+ # if `values` is a dict using `.items()` => {edge: value}
847
+ if G.is_multigraph():
848
+ for (u, v, key), value in values.items():
849
+ try:
850
+ G._adj[u][v][key][name] = value
851
+ except KeyError:
852
+ pass
853
+ else:
854
+ for (u, v), value in values.items():
855
+ try:
856
+ G._adj[u][v][name] = value
857
+ except KeyError:
858
+ pass
859
+ except AttributeError:
860
+ # treat `values` as a constant
861
+ for u, v, data in G.edges(data=True):
862
+ data[name] = values
863
+ else:
864
+ # `values` consists of doct-of-dict {edge: {attr: value}} shape
865
+ if G.is_multigraph():
866
+ for (u, v, key), d in values.items():
867
+ try:
868
+ G._adj[u][v][key].update(d)
869
+ except KeyError:
870
+ pass
871
+ else:
872
+ for (u, v), d in values.items():
873
+ try:
874
+ G._adj[u][v].update(d)
875
+ except KeyError:
876
+ pass
877
+ nx._clear_cache(G)
878
+
879
+
880
+ def get_edge_attributes(G, name, default=None):
881
+ """Get edge attributes from graph
882
+
883
+ Parameters
884
+ ----------
885
+ G : NetworkX Graph
886
+
887
+ name : string
888
+ Attribute name
889
+
890
+ default: object (default=None)
891
+ Default value of the edge attribute if there is no value set for that
892
+ edge in graph. If `None` then edges without this attribute are not
893
+ included in the returned dict.
894
+
895
+ Returns
896
+ -------
897
+ Dictionary of attributes keyed by edge. For (di)graphs, the keys are
898
+ 2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
899
+ the form: (u, v, key).
900
+
901
+ Examples
902
+ --------
903
+ >>> G = nx.Graph()
904
+ >>> nx.add_path(G, [1, 2, 3], color="red")
905
+ >>> color = nx.get_edge_attributes(G, "color")
906
+ >>> color[(1, 2)]
907
+ 'red'
908
+ >>> G.add_edge(3, 4)
909
+ >>> color = nx.get_edge_attributes(G, "color", default="yellow")
910
+ >>> color[(3, 4)]
911
+ 'yellow'
912
+ """
913
+ if G.is_multigraph():
914
+ edges = G.edges(keys=True, data=True)
915
+ else:
916
+ edges = G.edges(data=True)
917
+ if default is not None:
918
+ return {x[:-1]: x[-1].get(name, default) for x in edges}
919
+ return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
920
+
921
+
922
+ def remove_edge_attributes(G, *attr_names, ebunch=None):
923
+ """Remove edge attributes from all edges in the graph.
924
+
925
+ Parameters
926
+ ----------
927
+ G : NetworkX Graph
928
+
929
+ *attr_names : List of Strings
930
+ The attribute names to remove from the graph.
931
+
932
+ Examples
933
+ --------
934
+ >>> G = nx.path_graph(3)
935
+ >>> nx.set_edge_attributes(G, {(u, v): u + v for u, v in G.edges()}, name="weight")
936
+ >>> nx.get_edge_attributes(G, "weight")
937
+ {(0, 1): 1, (1, 2): 3}
938
+ >>> remove_edge_attributes(G, "weight")
939
+ >>> nx.get_edge_attributes(G, "weight")
940
+ {}
941
+ """
942
+ if ebunch is None:
943
+ ebunch = G.edges(keys=True) if G.is_multigraph() else G.edges()
944
+
945
+ for attr in attr_names:
946
+ edges = (
947
+ G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
948
+ )
949
+ for *e, d in edges:
950
+ if tuple(e) in ebunch:
951
+ try:
952
+ del d[attr]
953
+ except KeyError:
954
+ pass
955
+
956
+
957
+ def all_neighbors(graph, node):
958
+ """Returns all of the neighbors of a node in the graph.
959
+
960
+ If the graph is directed returns predecessors as well as successors.
961
+
962
+ Parameters
963
+ ----------
964
+ graph : NetworkX graph
965
+ Graph to find neighbors.
966
+
967
+ node : node
968
+ The node whose neighbors will be returned.
969
+
970
+ Returns
971
+ -------
972
+ neighbors : iterator
973
+ Iterator of neighbors
974
+ """
975
+ if graph.is_directed():
976
+ values = chain(graph.predecessors(node), graph.successors(node))
977
+ else:
978
+ values = graph.neighbors(node)
979
+ return values
980
+
981
+
982
+ def non_neighbors(graph, node):
983
+ """Returns the non-neighbors of the node in the graph.
984
+
985
+ Parameters
986
+ ----------
987
+ graph : NetworkX graph
988
+ Graph to find neighbors.
989
+
990
+ node : node
991
+ The node whose neighbors will be returned.
992
+
993
+ Returns
994
+ -------
995
+ non_neighbors : set
996
+ Set of nodes in the graph that are not neighbors of the node.
997
+ """
998
+ return graph._adj.keys() - graph._adj[node].keys() - {node}
999
+
1000
+
1001
+ def non_edges(graph):
1002
+ """Returns the nonexistent edges in the graph.
1003
+
1004
+ Parameters
1005
+ ----------
1006
+ graph : NetworkX graph.
1007
+ Graph to find nonexistent edges.
1008
+
1009
+ Returns
1010
+ -------
1011
+ non_edges : iterator
1012
+ Iterator of edges that are not in the graph.
1013
+ """
1014
+ if graph.is_directed():
1015
+ for u in graph:
1016
+ for v in non_neighbors(graph, u):
1017
+ yield (u, v)
1018
+ else:
1019
+ nodes = set(graph)
1020
+ while nodes:
1021
+ u = nodes.pop()
1022
+ for v in nodes - set(graph[u]):
1023
+ yield (u, v)
1024
+
1025
+
1026
+ @not_implemented_for("directed")
1027
+ def common_neighbors(G, u, v):
1028
+ """Returns the common neighbors of two nodes in a graph.
1029
+
1030
+ Parameters
1031
+ ----------
1032
+ G : graph
1033
+ A NetworkX undirected graph.
1034
+
1035
+ u, v : nodes
1036
+ Nodes in the graph.
1037
+
1038
+ Returns
1039
+ -------
1040
+ cnbors : set
1041
+ Set of common neighbors of u and v in the graph.
1042
+
1043
+ Raises
1044
+ ------
1045
+ NetworkXError
1046
+ If u or v is not a node in the graph.
1047
+
1048
+ Examples
1049
+ --------
1050
+ >>> G = nx.complete_graph(5)
1051
+ >>> sorted(nx.common_neighbors(G, 0, 1))
1052
+ [2, 3, 4]
1053
+ """
1054
+ if u not in G:
1055
+ raise nx.NetworkXError("u is not in the graph.")
1056
+ if v not in G:
1057
+ raise nx.NetworkXError("v is not in the graph.")
1058
+
1059
+ return G._adj[u].keys() & G._adj[v].keys() - {u, v}
1060
+
1061
+
1062
+ def is_weighted(G, edge=None, weight="weight"):
1063
+ """Returns True if `G` has weighted edges.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ G : graph
1068
+ A NetworkX graph.
1069
+
1070
+ edge : tuple, optional
1071
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1072
+ None, then every edge in `G` is tested.
1073
+
1074
+ weight: string, optional
1075
+ The attribute name used to query for edge weights.
1076
+
1077
+ Returns
1078
+ -------
1079
+ bool
1080
+ A boolean signifying if `G`, or the specified edge, is weighted.
1081
+
1082
+ Raises
1083
+ ------
1084
+ NetworkXError
1085
+ If the specified edge does not exist.
1086
+
1087
+ Examples
1088
+ --------
1089
+ >>> G = nx.path_graph(4)
1090
+ >>> nx.is_weighted(G)
1091
+ False
1092
+ >>> nx.is_weighted(G, (2, 3))
1093
+ False
1094
+
1095
+ >>> G = nx.DiGraph()
1096
+ >>> G.add_edge(1, 2, weight=1)
1097
+ >>> nx.is_weighted(G)
1098
+ True
1099
+
1100
+ """
1101
+ if edge is not None:
1102
+ data = G.get_edge_data(*edge)
1103
+ if data is None:
1104
+ msg = f"Edge {edge!r} does not exist."
1105
+ raise nx.NetworkXError(msg)
1106
+ return weight in data
1107
+
1108
+ if is_empty(G):
1109
+ # Special handling required since: all([]) == True
1110
+ return False
1111
+
1112
+ return all(weight in data for u, v, data in G.edges(data=True))
1113
+
1114
+
1115
+ @nx._dispatchable(edge_attrs="weight")
1116
+ def is_negatively_weighted(G, edge=None, weight="weight"):
1117
+ """Returns True if `G` has negatively weighted edges.
1118
+
1119
+ Parameters
1120
+ ----------
1121
+ G : graph
1122
+ A NetworkX graph.
1123
+
1124
+ edge : tuple, optional
1125
+ A 2-tuple specifying the only edge in `G` that will be tested. If
1126
+ None, then every edge in `G` is tested.
1127
+
1128
+ weight: string, optional
1129
+ The attribute name used to query for edge weights.
1130
+
1131
+ Returns
1132
+ -------
1133
+ bool
1134
+ A boolean signifying if `G`, or the specified edge, is negatively
1135
+ weighted.
1136
+
1137
+ Raises
1138
+ ------
1139
+ NetworkXError
1140
+ If the specified edge does not exist.
1141
+
1142
+ Examples
1143
+ --------
1144
+ >>> G = nx.Graph()
1145
+ >>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
1146
+ >>> G.add_edge(1, 2, weight=4)
1147
+ >>> nx.is_negatively_weighted(G, (1, 2))
1148
+ False
1149
+ >>> G[2][4]["weight"] = -2
1150
+ >>> nx.is_negatively_weighted(G)
1151
+ True
1152
+ >>> G = nx.DiGraph()
1153
+ >>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)]
1154
+ >>> G.add_weighted_edges_from(edges)
1155
+ >>> nx.is_negatively_weighted(G)
1156
+ True
1157
+
1158
+ """
1159
+ if edge is not None:
1160
+ data = G.get_edge_data(*edge)
1161
+ if data is None:
1162
+ msg = f"Edge {edge!r} does not exist."
1163
+ raise nx.NetworkXError(msg)
1164
+ return weight in data and data[weight] < 0
1165
+
1166
+ return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
1167
+
1168
+
1169
+ def is_empty(G):
1170
+ """Returns True if `G` has no edges.
1171
+
1172
+ Parameters
1173
+ ----------
1174
+ G : graph
1175
+ A NetworkX graph.
1176
+
1177
+ Returns
1178
+ -------
1179
+ bool
1180
+ True if `G` has no edges, and False otherwise.
1181
+
1182
+ Notes
1183
+ -----
1184
+ An empty graph can have nodes but not edges. The empty graph with zero
1185
+ nodes is known as the null graph. This is an $O(n)$ operation where n
1186
+ is the number of nodes in the graph.
1187
+
1188
+ """
1189
+ return not any(G._adj.values())
1190
+
1191
+
1192
+ def nodes_with_selfloops(G):
1193
+ """Returns an iterator over nodes with self loops.
1194
+
1195
+ A node with a self loop has an edge with both ends adjacent
1196
+ to that node.
1197
+
1198
+ Returns
1199
+ -------
1200
+ nodelist : iterator
1201
+ A iterator over nodes with self loops.
1202
+
1203
+ See Also
1204
+ --------
1205
+ selfloop_edges, number_of_selfloops
1206
+
1207
+ Examples
1208
+ --------
1209
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1210
+ >>> G.add_edge(1, 1)
1211
+ >>> G.add_edge(1, 2)
1212
+ >>> list(nx.nodes_with_selfloops(G))
1213
+ [1]
1214
+
1215
+ """
1216
+ return (n for n, nbrs in G._adj.items() if n in nbrs)
1217
+
1218
+
1219
+ def selfloop_edges(G, data=False, keys=False, default=None):
1220
+ """Returns an iterator over selfloop edges.
1221
+
1222
+ A selfloop edge has the same node at both ends.
1223
+
1224
+ Parameters
1225
+ ----------
1226
+ G : graph
1227
+ A NetworkX graph.
1228
+ data : string or bool, optional (default=False)
1229
+ Return selfloop edges as two tuples (u, v) (data=False)
1230
+ or three-tuples (u, v, datadict) (data=True)
1231
+ or three-tuples (u, v, datavalue) (data='attrname')
1232
+ keys : bool, optional (default=False)
1233
+ If True, return edge keys with each edge.
1234
+ default : value, optional (default=None)
1235
+ Value used for edges that don't have the requested attribute.
1236
+ Only relevant if data is not True or False.
1237
+
1238
+ Returns
1239
+ -------
1240
+ edgeiter : iterator over edge tuples
1241
+ An iterator over all selfloop edges.
1242
+
1243
+ See Also
1244
+ --------
1245
+ nodes_with_selfloops, number_of_selfloops
1246
+
1247
+ Examples
1248
+ --------
1249
+ >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc
1250
+ >>> ekey = G.add_edge(1, 1)
1251
+ >>> ekey = G.add_edge(1, 2)
1252
+ >>> list(nx.selfloop_edges(G))
1253
+ [(1, 1)]
1254
+ >>> list(nx.selfloop_edges(G, data=True))
1255
+ [(1, 1, {})]
1256
+ >>> list(nx.selfloop_edges(G, keys=True))
1257
+ [(1, 1, 0)]
1258
+ >>> list(nx.selfloop_edges(G, keys=True, data=True))
1259
+ [(1, 1, 0, {})]
1260
+ """
1261
+ if data is True:
1262
+ if G.is_multigraph():
1263
+ if keys is True:
1264
+ return (
1265
+ (n, n, k, d)
1266
+ for n, nbrs in G._adj.items()
1267
+ if n in nbrs
1268
+ for k, d in nbrs[n].items()
1269
+ )
1270
+ else:
1271
+ return (
1272
+ (n, n, d)
1273
+ for n, nbrs in G._adj.items()
1274
+ if n in nbrs
1275
+ for d in nbrs[n].values()
1276
+ )
1277
+ else:
1278
+ return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs)
1279
+ elif data is not False:
1280
+ if G.is_multigraph():
1281
+ if keys is True:
1282
+ return (
1283
+ (n, n, k, d.get(data, default))
1284
+ for n, nbrs in G._adj.items()
1285
+ if n in nbrs
1286
+ for k, d in nbrs[n].items()
1287
+ )
1288
+ else:
1289
+ return (
1290
+ (n, n, d.get(data, default))
1291
+ for n, nbrs in G._adj.items()
1292
+ if n in nbrs
1293
+ for d in nbrs[n].values()
1294
+ )
1295
+ else:
1296
+ return (
1297
+ (n, n, nbrs[n].get(data, default))
1298
+ for n, nbrs in G._adj.items()
1299
+ if n in nbrs
1300
+ )
1301
+ else:
1302
+ if G.is_multigraph():
1303
+ if keys is True:
1304
+ return (
1305
+ (n, n, k)
1306
+ for n, nbrs in G._adj.items()
1307
+ if n in nbrs
1308
+ for k in nbrs[n]
1309
+ )
1310
+ else:
1311
+ return (
1312
+ (n, n)
1313
+ for n, nbrs in G._adj.items()
1314
+ if n in nbrs
1315
+ for i in range(len(nbrs[n])) # for easy edge removal (#4068)
1316
+ )
1317
+ else:
1318
+ return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
1319
+
1320
+
1321
+ def number_of_selfloops(G):
1322
+ """Returns the number of selfloop edges.
1323
+
1324
+ A selfloop edge has the same node at both ends.
1325
+
1326
+ Returns
1327
+ -------
1328
+ nloops : int
1329
+ The number of selfloops.
1330
+
1331
+ See Also
1332
+ --------
1333
+ nodes_with_selfloops, selfloop_edges
1334
+
1335
+ Examples
1336
+ --------
1337
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1338
+ >>> G.add_edge(1, 1)
1339
+ >>> G.add_edge(1, 2)
1340
+ >>> nx.number_of_selfloops(G)
1341
+ 1
1342
+ """
1343
+ return sum(1 for _ in nx.selfloop_edges(G))
1344
+
1345
+
1346
+ def is_path(G, path):
1347
+ """Returns whether or not the specified path exists.
1348
+
1349
+ For it to return True, every node on the path must exist and
1350
+ each consecutive pair must be connected via one or more edges.
1351
+
1352
+ Parameters
1353
+ ----------
1354
+ G : graph
1355
+ A NetworkX graph.
1356
+
1357
+ path : list
1358
+ A list of nodes which defines the path to traverse
1359
+
1360
+ Returns
1361
+ -------
1362
+ bool
1363
+ True if `path` is a valid path in `G`
1364
+
1365
+ """
1366
+ try:
1367
+ return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path))
1368
+ except (KeyError, TypeError):
1369
+ return False
1370
+
1371
+
1372
+ def path_weight(G, path, weight):
1373
+ """Returns total cost associated with specified path and weight
1374
+
1375
+ Parameters
1376
+ ----------
1377
+ G : graph
1378
+ A NetworkX graph.
1379
+
1380
+ path: list
1381
+ A list of node labels which defines the path to traverse
1382
+
1383
+ weight: string
1384
+ A string indicating which edge attribute to use for path cost
1385
+
1386
+ Returns
1387
+ -------
1388
+ cost: int or float
1389
+ An integer or a float representing the total cost with respect to the
1390
+ specified weight of the specified path
1391
+
1392
+ Raises
1393
+ ------
1394
+ NetworkXNoPath
1395
+ If the specified edge does not exist.
1396
+ """
1397
+ multigraph = G.is_multigraph()
1398
+ cost = 0
1399
+
1400
+ if not nx.is_path(G, path):
1401
+ raise nx.NetworkXNoPath("path does not exist")
1402
+ for node, nbr in nx.utils.pairwise(path):
1403
+ if multigraph:
1404
+ cost += min(v[weight] for v in G._adj[node][nbr].values())
1405
+ else:
1406
+ cost += G._adj[node][nbr][weight]
1407
+ return cost
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/graph.py ADDED
@@ -0,0 +1,2058 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for undirected graphs.
2
+
3
+ The Graph class allows any hashable object as a node
4
+ and can associate key/value attribute pairs with each undirected edge.
5
+
6
+ Self-loops are allowed but multiple edges are not (see MultiGraph).
7
+
8
+ For directed graphs see DiGraph and MultiDiGraph.
9
+ """
10
+
11
+ from copy import deepcopy
12
+ from functools import cached_property
13
+
14
+ import networkx as nx
15
+ from networkx import convert
16
+ from networkx.classes.coreviews import AdjacencyView
17
+ from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
18
+ from networkx.exception import NetworkXError
19
+
20
+ __all__ = ["Graph"]
21
+
22
+
23
+ class _CachedPropertyResetterAdj:
24
+ """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
25
+
26
+ This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
27
+ ``G._adj`` is set to a new value.
28
+
29
+ This object sits on a class and ensures that any instance of that
30
+ class clears its cached property "adj" whenever the underlying
31
+ instance attribute "_adj" is set to a new object. It only affects
32
+ the set process of the obj._adj attribute. All get/del operations
33
+ act as they normally would.
34
+
35
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
36
+ """
37
+
38
+ def __set__(self, obj, value):
39
+ od = obj.__dict__
40
+ od["_adj"] = value
41
+ # reset cached properties
42
+ props = ["adj", "edges", "degree"]
43
+ for prop in props:
44
+ if prop in od:
45
+ del od[prop]
46
+
47
+
48
+ class _CachedPropertyResetterNode:
49
+ """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
50
+
51
+ This assumes that the ``cached_property`` ``G.node`` should be reset whenever
52
+ ``G._node`` is set to a new value.
53
+
54
+ This object sits on a class and ensures that any instance of that
55
+ class clears its cached property "nodes" whenever the underlying
56
+ instance attribute "_node" is set to a new object. It only affects
57
+ the set process of the obj._adj attribute. All get/del operations
58
+ act as they normally would.
59
+
60
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
61
+ """
62
+
63
+ def __set__(self, obj, value):
64
+ od = obj.__dict__
65
+ od["_node"] = value
66
+ # reset cached properties
67
+ if "nodes" in od:
68
+ del od["nodes"]
69
+
70
+
71
+ class Graph:
72
+ """
73
+ Base class for undirected graphs.
74
+
75
+ A Graph stores nodes and edges with optional data, or attributes.
76
+
77
+ Graphs hold undirected edges. Self loops are allowed but multiple
78
+ (parallel) edges are not.
79
+
80
+ Nodes can be arbitrary (hashable) Python objects with optional
81
+ key/value attributes, except that `None` is not allowed as a node.
82
+
83
+ Edges are represented as links between nodes with optional
84
+ key/value attributes.
85
+
86
+ Parameters
87
+ ----------
88
+ incoming_graph_data : input graph (optional, default: None)
89
+ Data to initialize graph. If None (default) an empty
90
+ graph is created. The data can be any format that is supported
91
+ by the to_networkx_graph() function, currently including edge list,
92
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
93
+ sparse matrix, or PyGraphviz graph.
94
+
95
+ attr : keyword arguments, optional (default= no attributes)
96
+ Attributes to add to graph as key=value pairs.
97
+
98
+ See Also
99
+ --------
100
+ DiGraph
101
+ MultiGraph
102
+ MultiDiGraph
103
+
104
+ Examples
105
+ --------
106
+ Create an empty graph structure (a "null graph") with no nodes and
107
+ no edges.
108
+
109
+ >>> G = nx.Graph()
110
+
111
+ G can be grown in several ways.
112
+
113
+ **Nodes:**
114
+
115
+ Add one node at a time:
116
+
117
+ >>> G.add_node(1)
118
+
119
+ Add the nodes from any container (a list, dict, set or
120
+ even the lines from a file or the nodes from another graph).
121
+
122
+ >>> G.add_nodes_from([2, 3])
123
+ >>> G.add_nodes_from(range(100, 110))
124
+ >>> H = nx.path_graph(10)
125
+ >>> G.add_nodes_from(H)
126
+
127
+ In addition to strings and integers any hashable Python object
128
+ (except None) can represent a node, e.g. a customized node object,
129
+ or even another Graph.
130
+
131
+ >>> G.add_node(H)
132
+
133
+ **Edges:**
134
+
135
+ G can also be grown by adding edges.
136
+
137
+ Add one edge,
138
+
139
+ >>> G.add_edge(1, 2)
140
+
141
+ a list of edges,
142
+
143
+ >>> G.add_edges_from([(1, 2), (1, 3)])
144
+
145
+ or a collection of edges,
146
+
147
+ >>> G.add_edges_from(H.edges)
148
+
149
+ If some edges connect nodes not yet in the graph, the nodes
150
+ are added automatically. There are no errors when adding
151
+ nodes or edges that already exist.
152
+
153
+ **Attributes:**
154
+
155
+ Each graph, node, and edge can hold key/value attribute pairs
156
+ in an associated attribute dictionary (the keys must be hashable).
157
+ By default these are empty, but can be added or changed using
158
+ add_edge, add_node or direct manipulation of the attribute
159
+ dictionaries named graph, node and edge respectively.
160
+
161
+ >>> G = nx.Graph(day="Friday")
162
+ >>> G.graph
163
+ {'day': 'Friday'}
164
+
165
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
166
+
167
+ >>> G.add_node(1, time="5pm")
168
+ >>> G.add_nodes_from([3], time="2pm")
169
+ >>> G.nodes[1]
170
+ {'time': '5pm'}
171
+ >>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes
172
+ >>> del G.nodes[1]["room"] # remove attribute
173
+ >>> list(G.nodes(data=True))
174
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
175
+
176
+ Add edge attributes using add_edge(), add_edges_from(), subscript
177
+ notation, or G.edges.
178
+
179
+ >>> G.add_edge(1, 2, weight=4.7)
180
+ >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
181
+ >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
182
+ >>> G[1][2]["weight"] = 4.7
183
+ >>> G.edges[1, 2]["weight"] = 4
184
+
185
+ Warning: we protect the graph data structure by making `G.edges` a
186
+ read-only dict-like structure. However, you can assign to attributes
187
+ in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
188
+ data attributes: `G.edges[1, 2]['weight'] = 4`
189
+ (For multigraphs: `MG.edges[u, v, key][name] = value`).
190
+
191
+ **Shortcuts:**
192
+
193
+ Many common graph features allow python syntax to speed reporting.
194
+
195
+ >>> 1 in G # check if node in graph
196
+ True
197
+ >>> [n for n in G if n < 3] # iterate through nodes
198
+ [1, 2]
199
+ >>> len(G) # number of nodes in graph
200
+ 5
201
+
202
+ Often the best way to traverse all edges of a graph is via the neighbors.
203
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
204
+
205
+ >>> for n, nbrsdict in G.adjacency():
206
+ ... for nbr, eattr in nbrsdict.items():
207
+ ... if "weight" in eattr:
208
+ ... # Do something useful with the edges
209
+ ... pass
210
+
211
+ But the edges() method is often more convenient:
212
+
213
+ >>> for u, v, weight in G.edges.data("weight"):
214
+ ... if weight is not None:
215
+ ... # Do something useful with the edges
216
+ ... pass
217
+
218
+ **Reporting:**
219
+
220
+ Simple graph information is obtained using object-attributes and methods.
221
+ Reporting typically provides views instead of containers to reduce memory
222
+ usage. The views update as the graph is updated similarly to dict-views.
223
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
224
+ via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
225
+ (e.g. `nodes.items()`, `nodes.data('color')`,
226
+ `nodes.data('color', default='blue')` and similarly for `edges`)
227
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
228
+
229
+ For details on these and other miscellaneous methods, see below.
230
+
231
+ **Subclasses (Advanced):**
232
+
233
+ The Graph class uses a dict-of-dict-of-dict data structure.
234
+ The outer dict (node_dict) holds adjacency information keyed by node.
235
+ The next dict (adjlist_dict) represents the adjacency information and holds
236
+ edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
237
+ the edge data and holds edge attribute values keyed by attribute names.
238
+
239
+ Each of these three dicts can be replaced in a subclass by a user defined
240
+ dict-like object. In general, the dict-like features should be
241
+ maintained but extra features can be added. To replace one of the
242
+ dicts create a new graph class by changing the class(!) variable
243
+ holding the factory for that dict-like structure.
244
+
245
+ node_dict_factory : function, (default: dict)
246
+ Factory function to be used to create the dict containing node
247
+ attributes, keyed by node id.
248
+ It should require no arguments and return a dict-like object
249
+
250
+ node_attr_dict_factory: function, (default: dict)
251
+ Factory function to be used to create the node attribute
252
+ dict which holds attribute values keyed by attribute name.
253
+ It should require no arguments and return a dict-like object
254
+
255
+ adjlist_outer_dict_factory : function, (default: dict)
256
+ Factory function to be used to create the outer-most dict
257
+ in the data structure that holds adjacency info keyed by node.
258
+ It should require no arguments and return a dict-like object.
259
+
260
+ adjlist_inner_dict_factory : function, (default: dict)
261
+ Factory function to be used to create the adjacency list
262
+ dict which holds edge data keyed by neighbor.
263
+ It should require no arguments and return a dict-like object
264
+
265
+ edge_attr_dict_factory : function, (default: dict)
266
+ Factory function to be used to create the edge attribute
267
+ dict which holds attribute values keyed by attribute name.
268
+ It should require no arguments and return a dict-like object.
269
+
270
+ graph_attr_dict_factory : function, (default: dict)
271
+ Factory function to be used to create the graph attribute
272
+ dict which holds attribute values keyed by attribute name.
273
+ It should require no arguments and return a dict-like object.
274
+
275
+ Typically, if your extension doesn't impact the data structure all
276
+ methods will inherit without issue except: `to_directed/to_undirected`.
277
+ By default these methods create a DiGraph/Graph class and you probably
278
+ want them to create your extension of a DiGraph/Graph. To facilitate
279
+ this we define two class variables that you can set in your subclass.
280
+
281
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
282
+ Class to create a new graph structure in the `to_directed` method.
283
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
284
+
285
+ to_undirected_class : callable, (default: Graph or MultiGraph)
286
+ Class to create a new graph structure in the `to_undirected` method.
287
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
288
+
289
+ **Subclassing Example**
290
+
291
+ Create a low memory graph class that effectively disallows edge
292
+ attributes by using a single attribute dict for all edges.
293
+ This reduces the memory used, but you lose edge attributes.
294
+
295
+ >>> class ThinGraph(nx.Graph):
296
+ ... all_edge_dict = {"weight": 1}
297
+ ...
298
+ ... def single_edge_dict(self):
299
+ ... return self.all_edge_dict
300
+ ...
301
+ ... edge_attr_dict_factory = single_edge_dict
302
+ >>> G = ThinGraph()
303
+ >>> G.add_edge(2, 1)
304
+ >>> G[2][1]
305
+ {'weight': 1}
306
+ >>> G.add_edge(2, 2)
307
+ >>> G[2][1] is G[2][2]
308
+ True
309
+ """
310
+
311
+ __networkx_backend__ = "networkx"
312
+
313
+ _adj = _CachedPropertyResetterAdj()
314
+ _node = _CachedPropertyResetterNode()
315
+
316
+ node_dict_factory = dict
317
+ node_attr_dict_factory = dict
318
+ adjlist_outer_dict_factory = dict
319
+ adjlist_inner_dict_factory = dict
320
+ edge_attr_dict_factory = dict
321
+ graph_attr_dict_factory = dict
322
+
323
+ def to_directed_class(self):
324
+ """Returns the class to use for empty directed copies.
325
+
326
+ If you subclass the base classes, use this to designate
327
+ what directed class to use for `to_directed()` copies.
328
+ """
329
+ return nx.DiGraph
330
+
331
+ def to_undirected_class(self):
332
+ """Returns the class to use for empty undirected copies.
333
+
334
+ If you subclass the base classes, use this to designate
335
+ what directed class to use for `to_directed()` copies.
336
+ """
337
+ return Graph
338
+
339
+ def __init__(self, incoming_graph_data=None, **attr):
340
+ """Initialize a graph with edges, name, or graph attributes.
341
+
342
+ Parameters
343
+ ----------
344
+ incoming_graph_data : input graph (optional, default: None)
345
+ Data to initialize graph. If None (default) an empty
346
+ graph is created. The data can be an edge list, or any
347
+ NetworkX graph object. If the corresponding optional Python
348
+ packages are installed the data can also be a 2D NumPy array, a
349
+ SciPy sparse array, or a PyGraphviz graph.
350
+
351
+ attr : keyword arguments, optional (default= no attributes)
352
+ Attributes to add to graph as key=value pairs.
353
+
354
+ See Also
355
+ --------
356
+ convert
357
+
358
+ Examples
359
+ --------
360
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
361
+ >>> G = nx.Graph(name="my graph")
362
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
363
+ >>> G = nx.Graph(e)
364
+
365
+ Arbitrary graph attribute pairs (key=value) may be assigned
366
+
367
+ >>> G = nx.Graph(e, day="Friday")
368
+ >>> G.graph
369
+ {'day': 'Friday'}
370
+
371
+ """
372
+ self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
373
+ self._node = self.node_dict_factory() # empty node attribute dict
374
+ self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict
375
+ self.__networkx_cache__ = {}
376
+ # attempt to load graph with data
377
+ if incoming_graph_data is not None:
378
+ convert.to_networkx_graph(incoming_graph_data, create_using=self)
379
+ # load graph attributes (must be after convert)
380
+ self.graph.update(attr)
381
+
382
+ @cached_property
383
+ def adj(self):
384
+ """Graph adjacency object holding the neighbors of each node.
385
+
386
+ This object is a read-only dict-like structure with node keys
387
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
388
+ to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
389
+ the color of the edge `(3, 2)` to `"blue"`.
390
+
391
+ Iterating over G.adj behaves like a dict. Useful idioms include
392
+ `for nbr, datadict in G.adj[n].items():`.
393
+
394
+ The neighbor information is also provided by subscripting the graph.
395
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
396
+
397
+ For directed graphs, `G.adj` holds outgoing (successor) info.
398
+ """
399
+ return AdjacencyView(self._adj)
400
+
401
+ @property
402
+ def name(self):
403
+ """String identifier of the graph.
404
+
405
+ This graph attribute appears in the attribute dict G.graph
406
+ keyed by the string `"name"`. as well as an attribute (technically
407
+ a property) `G.name`. This is entirely user controlled.
408
+ """
409
+ return self.graph.get("name", "")
410
+
411
+ @name.setter
412
+ def name(self, s):
413
+ self.graph["name"] = s
414
+ nx._clear_cache(self)
415
+
416
+ def __str__(self):
417
+ """Returns a short summary of the graph.
418
+
419
+ Returns
420
+ -------
421
+ info : string
422
+ Graph information including the graph name (if any), graph type, and the
423
+ number of nodes and edges.
424
+
425
+ Examples
426
+ --------
427
+ >>> G = nx.Graph(name="foo")
428
+ >>> str(G)
429
+ "Graph named 'foo' with 0 nodes and 0 edges"
430
+
431
+ >>> G = nx.path_graph(3)
432
+ >>> str(G)
433
+ 'Graph with 3 nodes and 2 edges'
434
+
435
+ """
436
+ return "".join(
437
+ [
438
+ type(self).__name__,
439
+ f" named {self.name!r}" if self.name else "",
440
+ f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
441
+ ]
442
+ )
443
+
444
+ def __iter__(self):
445
+ """Iterate over the nodes. Use: 'for n in G'.
446
+
447
+ Returns
448
+ -------
449
+ niter : iterator
450
+ An iterator over all nodes in the graph.
451
+
452
+ Examples
453
+ --------
454
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
455
+ >>> [n for n in G]
456
+ [0, 1, 2, 3]
457
+ >>> list(G)
458
+ [0, 1, 2, 3]
459
+ """
460
+ return iter(self._node)
461
+
462
+ def __contains__(self, n):
463
+ """Returns True if n is a node, False otherwise. Use: 'n in G'.
464
+
465
+ Examples
466
+ --------
467
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
468
+ >>> 1 in G
469
+ True
470
+ """
471
+ try:
472
+ return n in self._node
473
+ except TypeError:
474
+ return False
475
+
476
+ def __len__(self):
477
+ """Returns the number of nodes in the graph. Use: 'len(G)'.
478
+
479
+ Returns
480
+ -------
481
+ nnodes : int
482
+ The number of nodes in the graph.
483
+
484
+ See Also
485
+ --------
486
+ number_of_nodes: identical method
487
+ order: identical method
488
+
489
+ Examples
490
+ --------
491
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
492
+ >>> len(G)
493
+ 4
494
+
495
+ """
496
+ return len(self._node)
497
+
498
+ def __getitem__(self, n):
499
+ """Returns a dict of neighbors of node n. Use: 'G[n]'.
500
+
501
+ Parameters
502
+ ----------
503
+ n : node
504
+ A node in the graph.
505
+
506
+ Returns
507
+ -------
508
+ adj_dict : dictionary
509
+ The adjacency dictionary for nodes connected to n.
510
+
511
+ Notes
512
+ -----
513
+ G[n] is the same as G.adj[n] and similar to G.neighbors(n)
514
+ (which is an iterator over G.adj[n])
515
+
516
+ Examples
517
+ --------
518
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
519
+ >>> G[0]
520
+ AtlasView({1: {}})
521
+ """
522
+ return self.adj[n]
523
+
524
+ def add_node(self, node_for_adding, **attr):
525
+ """Add a single node `node_for_adding` and update node attributes.
526
+
527
+ Parameters
528
+ ----------
529
+ node_for_adding : node
530
+ A node can be any hashable Python object except None.
531
+ attr : keyword arguments, optional
532
+ Set or change node attributes using key=value.
533
+
534
+ See Also
535
+ --------
536
+ add_nodes_from
537
+
538
+ Examples
539
+ --------
540
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
541
+ >>> G.add_node(1)
542
+ >>> G.add_node("Hello")
543
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
544
+ >>> G.add_node(K3)
545
+ >>> G.number_of_nodes()
546
+ 3
547
+
548
+ Use keywords set/change node attributes:
549
+
550
+ >>> G.add_node(1, size=10)
551
+ >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
552
+
553
+ Notes
554
+ -----
555
+ A hashable object is one that can be used as a key in a Python
556
+ dictionary. This includes strings, numbers, tuples of strings
557
+ and numbers, etc.
558
+
559
+ On many platforms hashable items also include mutables such as
560
+ NetworkX Graphs, though one should be careful that the hash
561
+ doesn't change on mutables.
562
+ """
563
+ if node_for_adding not in self._node:
564
+ if node_for_adding is None:
565
+ raise ValueError("None cannot be a node")
566
+ self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
567
+ attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
568
+ attr_dict.update(attr)
569
+ else: # update attr even if node already exists
570
+ self._node[node_for_adding].update(attr)
571
+ nx._clear_cache(self)
572
+
573
+ def add_nodes_from(self, nodes_for_adding, **attr):
574
+ """Add multiple nodes.
575
+
576
+ Parameters
577
+ ----------
578
+ nodes_for_adding : iterable container
579
+ A container of nodes (list, dict, set, etc.).
580
+ OR
581
+ A container of (node, attribute dict) tuples.
582
+ Node attributes are updated using the attribute dict.
583
+ attr : keyword arguments, optional (default= no attributes)
584
+ Update attributes for all nodes in nodes.
585
+ Node attributes specified in nodes as a tuple take
586
+ precedence over attributes specified via keyword arguments.
587
+
588
+ See Also
589
+ --------
590
+ add_node
591
+
592
+ Notes
593
+ -----
594
+ When adding nodes from an iterator over the graph you are changing,
595
+ a `RuntimeError` can be raised with message:
596
+ `RuntimeError: dictionary changed size during iteration`. This
597
+ happens when the graph's underlying dictionary is modified during
598
+ iteration. To avoid this error, evaluate the iterator into a separate
599
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
600
+ object to `G.add_nodes_from`.
601
+
602
+ Examples
603
+ --------
604
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
605
+ >>> G.add_nodes_from("Hello")
606
+ >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
607
+ >>> G.add_nodes_from(K3)
608
+ >>> sorted(G.nodes(), key=str)
609
+ [0, 1, 2, 'H', 'e', 'l', 'o']
610
+
611
+ Use keywords to update specific node attributes for every node.
612
+
613
+ >>> G.add_nodes_from([1, 2], size=10)
614
+ >>> G.add_nodes_from([3, 4], weight=0.4)
615
+
616
+ Use (node, attrdict) tuples to update attributes for specific nodes.
617
+
618
+ >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
619
+ >>> G.nodes[1]["size"]
620
+ 11
621
+ >>> H = nx.Graph()
622
+ >>> H.add_nodes_from(G.nodes(data=True))
623
+ >>> H.nodes[1]["size"]
624
+ 11
625
+
626
+ Evaluate an iterator over a graph if using it to modify the same graph
627
+
628
+ >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
629
+ >>> # wrong way - will raise RuntimeError
630
+ >>> # G.add_nodes_from(n + 1 for n in G.nodes)
631
+ >>> # correct way
632
+ >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
633
+ """
634
+ for n in nodes_for_adding:
635
+ try:
636
+ newnode = n not in self._node
637
+ newdict = attr
638
+ except TypeError:
639
+ n, ndict = n
640
+ newnode = n not in self._node
641
+ newdict = attr.copy()
642
+ newdict.update(ndict)
643
+ if newnode:
644
+ if n is None:
645
+ raise ValueError("None cannot be a node")
646
+ self._adj[n] = self.adjlist_inner_dict_factory()
647
+ self._node[n] = self.node_attr_dict_factory()
648
+ self._node[n].update(newdict)
649
+ nx._clear_cache(self)
650
+
651
+ def remove_node(self, n):
652
+ """Remove node n.
653
+
654
+ Removes the node n and all adjacent edges.
655
+ Attempting to remove a nonexistent node will raise an exception.
656
+
657
+ Parameters
658
+ ----------
659
+ n : node
660
+ A node in the graph
661
+
662
+ Raises
663
+ ------
664
+ NetworkXError
665
+ If n is not in the graph.
666
+
667
+ See Also
668
+ --------
669
+ remove_nodes_from
670
+
671
+ Examples
672
+ --------
673
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
674
+ >>> list(G.edges)
675
+ [(0, 1), (1, 2)]
676
+ >>> G.remove_node(1)
677
+ >>> list(G.edges)
678
+ []
679
+
680
+ """
681
+ adj = self._adj
682
+ try:
683
+ nbrs = list(adj[n]) # list handles self-loops (allows mutation)
684
+ del self._node[n]
685
+ except KeyError as err: # NetworkXError if n not in self
686
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
687
+ for u in nbrs:
688
+ del adj[u][n] # remove all edges n-u in graph
689
+ del adj[n] # now remove node
690
+ nx._clear_cache(self)
691
+
692
+ def remove_nodes_from(self, nodes):
693
+ """Remove multiple nodes.
694
+
695
+ Parameters
696
+ ----------
697
+ nodes : iterable container
698
+ A container of nodes (list, dict, set, etc.). If a node
699
+ in the container is not in the graph it is silently
700
+ ignored.
701
+
702
+ See Also
703
+ --------
704
+ remove_node
705
+
706
+ Notes
707
+ -----
708
+ When removing nodes from an iterator over the graph you are changing,
709
+ a `RuntimeError` will be raised with message:
710
+ `RuntimeError: dictionary changed size during iteration`. This
711
+ happens when the graph's underlying dictionary is modified during
712
+ iteration. To avoid this error, evaluate the iterator into a separate
713
+ object, e.g. by using `list(iterator_of_nodes)`, and pass this
714
+ object to `G.remove_nodes_from`.
715
+
716
+ Examples
717
+ --------
718
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
719
+ >>> e = list(G.nodes)
720
+ >>> e
721
+ [0, 1, 2]
722
+ >>> G.remove_nodes_from(e)
723
+ >>> list(G.nodes)
724
+ []
725
+
726
+ Evaluate an iterator over a graph if using it to modify the same graph
727
+
728
+ >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
729
+ >>> # this command will fail, as the graph's dict is modified during iteration
730
+ >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
731
+ >>> # this command will work, since the dictionary underlying graph is not modified
732
+ >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
733
+ """
734
+ adj = self._adj
735
+ for n in nodes:
736
+ try:
737
+ del self._node[n]
738
+ for u in list(adj[n]): # list handles self-loops
739
+ del adj[u][n] # (allows mutation of dict in loop)
740
+ del adj[n]
741
+ except KeyError:
742
+ pass
743
+ nx._clear_cache(self)
744
+
745
+ @cached_property
746
+ def nodes(self):
747
+ """A NodeView of the Graph as G.nodes or G.nodes().
748
+
749
+ Can be used as `G.nodes` for data lookup and for set-like operations.
750
+ Can also be used as `G.nodes(data='color', default=None)` to return a
751
+ NodeDataView which reports specific node data but no set operations.
752
+ It presents a dict-like interface as well with `G.nodes.items()`
753
+ iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
754
+ providing the value of the `foo` attribute for node `3`. In addition,
755
+ a view `G.nodes.data('foo')` provides a dict-like interface to the
756
+ `foo` attribute of each node. `G.nodes.data('foo', default=1)`
757
+ provides a default for nodes that do not have attribute `foo`.
758
+
759
+ Parameters
760
+ ----------
761
+ data : string or bool, optional (default=False)
762
+ The node attribute returned in 2-tuple (n, ddict[data]).
763
+ If True, return entire node attribute dict as (n, ddict).
764
+ If False, return just the nodes n.
765
+
766
+ default : value, optional (default=None)
767
+ Value used for nodes that don't have the requested attribute.
768
+ Only relevant if data is not True or False.
769
+
770
+ Returns
771
+ -------
772
+ NodeView
773
+ Allows set-like operations over the nodes as well as node
774
+ attribute dict lookup and calling to get a NodeDataView.
775
+ A NodeDataView iterates over `(n, data)` and has no set operations.
776
+ A NodeView iterates over `n` and includes set operations.
777
+
778
+ When called, if data is False, an iterator over nodes.
779
+ Otherwise an iterator of 2-tuples (node, attribute value)
780
+ where the attribute is specified in `data`.
781
+ If data is True then the attribute becomes the
782
+ entire data dictionary.
783
+
784
+ Notes
785
+ -----
786
+ If your node data is not needed, it is simpler and equivalent
787
+ to use the expression ``for n in G``, or ``list(G)``.
788
+
789
+ Examples
790
+ --------
791
+ There are two simple ways of getting a list of all nodes in the graph:
792
+
793
+ >>> G = nx.path_graph(3)
794
+ >>> list(G.nodes)
795
+ [0, 1, 2]
796
+ >>> list(G)
797
+ [0, 1, 2]
798
+
799
+ To get the node data along with the nodes:
800
+
801
+ >>> G.add_node(1, time="5pm")
802
+ >>> G.nodes[0]["foo"] = "bar"
803
+ >>> list(G.nodes(data=True))
804
+ [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
805
+ >>> list(G.nodes.data())
806
+ [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
807
+
808
+ >>> list(G.nodes(data="foo"))
809
+ [(0, 'bar'), (1, None), (2, None)]
810
+ >>> list(G.nodes.data("foo"))
811
+ [(0, 'bar'), (1, None), (2, None)]
812
+
813
+ >>> list(G.nodes(data="time"))
814
+ [(0, None), (1, '5pm'), (2, None)]
815
+ >>> list(G.nodes.data("time"))
816
+ [(0, None), (1, '5pm'), (2, None)]
817
+
818
+ >>> list(G.nodes(data="time", default="Not Available"))
819
+ [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
820
+ >>> list(G.nodes.data("time", default="Not Available"))
821
+ [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
822
+
823
+ If some of your nodes have an attribute and the rest are assumed
824
+ to have a default attribute value you can create a dictionary
825
+ from node/attribute pairs using the `default` keyword argument
826
+ to guarantee the value is never None::
827
+
828
+ >>> G = nx.Graph()
829
+ >>> G.add_node(0)
830
+ >>> G.add_node(1, weight=2)
831
+ >>> G.add_node(2, weight=3)
832
+ >>> dict(G.nodes(data="weight", default=1))
833
+ {0: 1, 1: 2, 2: 3}
834
+
835
+ """
836
+ return NodeView(self)
837
+
838
+ def number_of_nodes(self):
839
+ """Returns the number of nodes in the graph.
840
+
841
+ Returns
842
+ -------
843
+ nnodes : int
844
+ The number of nodes in the graph.
845
+
846
+ See Also
847
+ --------
848
+ order: identical method
849
+ __len__: identical method
850
+
851
+ Examples
852
+ --------
853
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
854
+ >>> G.number_of_nodes()
855
+ 3
856
+ """
857
+ return len(self._node)
858
+
859
+ def order(self):
860
+ """Returns the number of nodes in the graph.
861
+
862
+ Returns
863
+ -------
864
+ nnodes : int
865
+ The number of nodes in the graph.
866
+
867
+ See Also
868
+ --------
869
+ number_of_nodes: identical method
870
+ __len__: identical method
871
+
872
+ Examples
873
+ --------
874
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
875
+ >>> G.order()
876
+ 3
877
+ """
878
+ return len(self._node)
879
+
880
+ def has_node(self, n):
881
+ """Returns True if the graph contains the node n.
882
+
883
+ Identical to `n in G`
884
+
885
+ Parameters
886
+ ----------
887
+ n : node
888
+
889
+ Examples
890
+ --------
891
+ >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
892
+ >>> G.has_node(0)
893
+ True
894
+
895
+ It is more readable and simpler to use
896
+
897
+ >>> 0 in G
898
+ True
899
+
900
+ """
901
+ try:
902
+ return n in self._node
903
+ except TypeError:
904
+ return False
905
+
906
+ def add_edge(self, u_of_edge, v_of_edge, **attr):
907
+ """Add an edge between u and v.
908
+
909
+ The nodes u and v will be automatically added if they are
910
+ not already in the graph.
911
+
912
+ Edge attributes can be specified with keywords or by directly
913
+ accessing the edge's attribute dictionary. See examples below.
914
+
915
+ Parameters
916
+ ----------
917
+ u_of_edge, v_of_edge : nodes
918
+ Nodes can be, for example, strings or numbers.
919
+ Nodes must be hashable (and not None) Python objects.
920
+ attr : keyword arguments, optional
921
+ Edge data (or labels or objects) can be assigned using
922
+ keyword arguments.
923
+
924
+ See Also
925
+ --------
926
+ add_edges_from : add a collection of edges
927
+
928
+ Notes
929
+ -----
930
+ Adding an edge that already exists updates the edge data.
931
+
932
+ Many NetworkX algorithms designed for weighted graphs use
933
+ an edge attribute (by default `weight`) to hold a numerical value.
934
+
935
+ Examples
936
+ --------
937
+ The following all add the edge e=(1, 2) to graph G:
938
+
939
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
940
+ >>> e = (1, 2)
941
+ >>> G.add_edge(1, 2) # explicit two-node form
942
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
943
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
944
+
945
+ Associate data to edges using keywords:
946
+
947
+ >>> G.add_edge(1, 2, weight=3)
948
+ >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
949
+
950
+ For non-string attribute keys, use subscript notation.
951
+
952
+ >>> G.add_edge(1, 2)
953
+ >>> G[1][2].update({0: 5})
954
+ >>> G.edges[1, 2].update({0: 5})
955
+ """
956
+ u, v = u_of_edge, v_of_edge
957
+ # add nodes
958
+ if u not in self._node:
959
+ if u is None:
960
+ raise ValueError("None cannot be a node")
961
+ self._adj[u] = self.adjlist_inner_dict_factory()
962
+ self._node[u] = self.node_attr_dict_factory()
963
+ if v not in self._node:
964
+ if v is None:
965
+ raise ValueError("None cannot be a node")
966
+ self._adj[v] = self.adjlist_inner_dict_factory()
967
+ self._node[v] = self.node_attr_dict_factory()
968
+ # add the edge
969
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
970
+ datadict.update(attr)
971
+ self._adj[u][v] = datadict
972
+ self._adj[v][u] = datadict
973
+ nx._clear_cache(self)
974
+
975
+ def add_edges_from(self, ebunch_to_add, **attr):
976
+ """Add all the edges in ebunch_to_add.
977
+
978
+ Parameters
979
+ ----------
980
+ ebunch_to_add : container of edges
981
+ Each edge given in the container will be added to the
982
+ graph. The edges must be given as 2-tuples (u, v) or
983
+ 3-tuples (u, v, d) where d is a dictionary containing edge data.
984
+ attr : keyword arguments, optional
985
+ Edge data (or labels or objects) can be assigned using
986
+ keyword arguments.
987
+
988
+ See Also
989
+ --------
990
+ add_edge : add a single edge
991
+ add_weighted_edges_from : convenient way to add weighted edges
992
+
993
+ Notes
994
+ -----
995
+ Adding the same edge twice has no effect but any edge data
996
+ will be updated when each duplicate edge is added.
997
+
998
+ Edge attributes specified in an ebunch take precedence over
999
+ attributes specified via keyword arguments.
1000
+
1001
+ When adding edges from an iterator over the graph you are changing,
1002
+ a `RuntimeError` can be raised with message:
1003
+ `RuntimeError: dictionary changed size during iteration`. This
1004
+ happens when the graph's underlying dictionary is modified during
1005
+ iteration. To avoid this error, evaluate the iterator into a separate
1006
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
1007
+ object to `G.add_edges_from`.
1008
+
1009
+ Examples
1010
+ --------
1011
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1012
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
1013
+ >>> e = zip(range(0, 3), range(1, 4))
1014
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
1015
+
1016
+ Associate data to edges
1017
+
1018
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
1019
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
1020
+
1021
+ Evaluate an iterator over a graph if using it to modify the same graph
1022
+
1023
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
1024
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
1025
+ >>> # wrong way - will raise RuntimeError
1026
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
1027
+ >>> # correct way - note that there will be no self-edge for node 5
1028
+ >>> G.add_edges_from(list((5, n) for n in G.nodes))
1029
+ """
1030
+ for e in ebunch_to_add:
1031
+ ne = len(e)
1032
+ if ne == 3:
1033
+ u, v, dd = e
1034
+ elif ne == 2:
1035
+ u, v = e
1036
+ dd = {} # doesn't need edge_attr_dict_factory
1037
+ else:
1038
+ raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
1039
+ if u not in self._node:
1040
+ if u is None:
1041
+ raise ValueError("None cannot be a node")
1042
+ self._adj[u] = self.adjlist_inner_dict_factory()
1043
+ self._node[u] = self.node_attr_dict_factory()
1044
+ if v not in self._node:
1045
+ if v is None:
1046
+ raise ValueError("None cannot be a node")
1047
+ self._adj[v] = self.adjlist_inner_dict_factory()
1048
+ self._node[v] = self.node_attr_dict_factory()
1049
+ datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
1050
+ datadict.update(attr)
1051
+ datadict.update(dd)
1052
+ self._adj[u][v] = datadict
1053
+ self._adj[v][u] = datadict
1054
+ nx._clear_cache(self)
1055
+
1056
+ def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
1057
+ """Add weighted edges in `ebunch_to_add` with specified weight attr
1058
+
1059
+ Parameters
1060
+ ----------
1061
+ ebunch_to_add : container of edges
1062
+ Each edge given in the list or container will be added
1063
+ to the graph. The edges must be given as 3-tuples (u, v, w)
1064
+ where w is a number.
1065
+ weight : string, optional (default= 'weight')
1066
+ The attribute name for the edge weights to be added.
1067
+ attr : keyword arguments, optional (default= no attributes)
1068
+ Edge attributes to add/update for all edges.
1069
+
1070
+ See Also
1071
+ --------
1072
+ add_edge : add a single edge
1073
+ add_edges_from : add multiple edges
1074
+
1075
+ Notes
1076
+ -----
1077
+ Adding the same edge twice for Graph/DiGraph simply updates
1078
+ the edge data. For MultiGraph/MultiDiGraph, duplicate edges
1079
+ are stored.
1080
+
1081
+ When adding edges from an iterator over the graph you are changing,
1082
+ a `RuntimeError` can be raised with message:
1083
+ `RuntimeError: dictionary changed size during iteration`. This
1084
+ happens when the graph's underlying dictionary is modified during
1085
+ iteration. To avoid this error, evaluate the iterator into a separate
1086
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
1087
+ object to `G.add_weighted_edges_from`.
1088
+
1089
+ Examples
1090
+ --------
1091
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1092
+ >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
1093
+
1094
+ Evaluate an iterator over edges before passing it
1095
+
1096
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
1097
+ >>> weight = 0.1
1098
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
1099
+ >>> # wrong way - will raise RuntimeError
1100
+ >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
1101
+ >>> # correct way - note that there will be no self-edge for node 5
1102
+ >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
1103
+ """
1104
+ self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
1105
+ nx._clear_cache(self)
1106
+
1107
+ def remove_edge(self, u, v):
1108
+ """Remove the edge between u and v.
1109
+
1110
+ Parameters
1111
+ ----------
1112
+ u, v : nodes
1113
+ Remove the edge between nodes u and v.
1114
+
1115
+ Raises
1116
+ ------
1117
+ NetworkXError
1118
+ If there is not an edge between u and v.
1119
+
1120
+ See Also
1121
+ --------
1122
+ remove_edges_from : remove a collection of edges
1123
+
1124
+ Examples
1125
+ --------
1126
+ >>> G = nx.path_graph(4) # or DiGraph, etc
1127
+ >>> G.remove_edge(0, 1)
1128
+ >>> e = (1, 2)
1129
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
1130
+ >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
1131
+ >>> G.remove_edge(*e[:2]) # select first part of edge tuple
1132
+ """
1133
+ try:
1134
+ del self._adj[u][v]
1135
+ if u != v: # self-loop needs only one entry removed
1136
+ del self._adj[v][u]
1137
+ except KeyError as err:
1138
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
1139
+ nx._clear_cache(self)
1140
+
1141
+ def remove_edges_from(self, ebunch):
1142
+ """Remove all edges specified in ebunch.
1143
+
1144
+ Parameters
1145
+ ----------
1146
+ ebunch: list or container of edge tuples
1147
+ Each edge given in the list or container will be removed
1148
+ from the graph. The edges can be:
1149
+
1150
+ - 2-tuples (u, v) edge between u and v.
1151
+ - 3-tuples (u, v, k) where k is ignored.
1152
+
1153
+ See Also
1154
+ --------
1155
+ remove_edge : remove a single edge
1156
+
1157
+ Notes
1158
+ -----
1159
+ Will fail silently if an edge in ebunch is not in the graph.
1160
+
1161
+ Examples
1162
+ --------
1163
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1164
+ >>> ebunch = [(1, 2), (2, 3)]
1165
+ >>> G.remove_edges_from(ebunch)
1166
+ """
1167
+ adj = self._adj
1168
+ for e in ebunch:
1169
+ u, v = e[:2] # ignore edge data if present
1170
+ if u in adj and v in adj[u]:
1171
+ del adj[u][v]
1172
+ if u != v: # self loop needs only one entry removed
1173
+ del adj[v][u]
1174
+ nx._clear_cache(self)
1175
+
1176
+ def update(self, edges=None, nodes=None):
1177
+ """Update the graph using nodes/edges/graphs as input.
1178
+
1179
+ Like dict.update, this method takes a graph as input, adding the
1180
+ graph's nodes and edges to this graph. It can also take two inputs:
1181
+ edges and nodes. Finally it can take either edges or nodes.
1182
+ To specify only nodes the keyword `nodes` must be used.
1183
+
1184
+ The collections of edges and nodes are treated similarly to
1185
+ the add_edges_from/add_nodes_from methods. When iterated, they
1186
+ should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
1187
+
1188
+ Parameters
1189
+ ----------
1190
+ edges : Graph object, collection of edges, or None
1191
+ The first parameter can be a graph or some edges. If it has
1192
+ attributes `nodes` and `edges`, then it is taken to be a
1193
+ Graph-like object and those attributes are used as collections
1194
+ of nodes and edges to be added to the graph.
1195
+ If the first parameter does not have those attributes, it is
1196
+ treated as a collection of edges and added to the graph.
1197
+ If the first argument is None, no edges are added.
1198
+ nodes : collection of nodes, or None
1199
+ The second parameter is treated as a collection of nodes
1200
+ to be added to the graph unless it is None.
1201
+ If `edges is None` and `nodes is None` an exception is raised.
1202
+ If the first parameter is a Graph, then `nodes` is ignored.
1203
+
1204
+ Examples
1205
+ --------
1206
+ >>> G = nx.path_graph(5)
1207
+ >>> G.update(nx.complete_graph(range(4, 10)))
1208
+ >>> from itertools import combinations
1209
+ >>> edges = (
1210
+ ... (u, v, {"power": u * v})
1211
+ ... for u, v in combinations(range(10, 20), 2)
1212
+ ... if u * v < 225
1213
+ ... )
1214
+ >>> nodes = [1000] # for singleton, use a container
1215
+ >>> G.update(edges, nodes)
1216
+
1217
+ Notes
1218
+ -----
1219
+ It you want to update the graph using an adjacency structure
1220
+ it is straightforward to obtain the edges/nodes from adjacency.
1221
+ The following examples provide common cases, your adjacency may
1222
+ be slightly different and require tweaks of these examples::
1223
+
1224
+ >>> # dict-of-set/list/tuple
1225
+ >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
1226
+ >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
1227
+ >>> G.update(edges=e, nodes=adj)
1228
+
1229
+ >>> DG = nx.DiGraph()
1230
+ >>> # dict-of-dict-of-attribute
1231
+ >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
1232
+ >>> e = [
1233
+ ... (u, v, {"weight": d})
1234
+ ... for u, nbrs in adj.items()
1235
+ ... for v, d in nbrs.items()
1236
+ ... ]
1237
+ >>> DG.update(edges=e, nodes=adj)
1238
+
1239
+ >>> # dict-of-dict-of-dict
1240
+ >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
1241
+ >>> e = [
1242
+ ... (u, v, {"weight": d})
1243
+ ... for u, nbrs in adj.items()
1244
+ ... for v, d in nbrs.items()
1245
+ ... ]
1246
+ >>> DG.update(edges=e, nodes=adj)
1247
+
1248
+ >>> # predecessor adjacency (dict-of-set)
1249
+ >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
1250
+ >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
1251
+
1252
+ >>> # MultiGraph dict-of-dict-of-dict-of-attribute
1253
+ >>> MDG = nx.MultiDiGraph()
1254
+ >>> adj = {
1255
+ ... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
1256
+ ... 3: {2: {0: {"weight": 0.7}}},
1257
+ ... }
1258
+ >>> e = [
1259
+ ... (u, v, ekey, d)
1260
+ ... for u, nbrs in adj.items()
1261
+ ... for v, keydict in nbrs.items()
1262
+ ... for ekey, d in keydict.items()
1263
+ ... ]
1264
+ >>> MDG.update(edges=e)
1265
+
1266
+ See Also
1267
+ --------
1268
+ add_edges_from: add multiple edges to a graph
1269
+ add_nodes_from: add multiple nodes to a graph
1270
+ """
1271
+ if edges is not None:
1272
+ if nodes is not None:
1273
+ self.add_nodes_from(nodes)
1274
+ self.add_edges_from(edges)
1275
+ else:
1276
+ # check if edges is a Graph object
1277
+ try:
1278
+ graph_nodes = edges.nodes
1279
+ graph_edges = edges.edges
1280
+ except AttributeError:
1281
+ # edge not Graph-like
1282
+ self.add_edges_from(edges)
1283
+ else: # edges is Graph-like
1284
+ self.add_nodes_from(graph_nodes.data())
1285
+ self.add_edges_from(graph_edges.data())
1286
+ self.graph.update(edges.graph)
1287
+ elif nodes is not None:
1288
+ self.add_nodes_from(nodes)
1289
+ else:
1290
+ raise NetworkXError("update needs nodes or edges input")
1291
+
1292
+ def has_edge(self, u, v):
1293
+ """Returns True if the edge (u, v) is in the graph.
1294
+
1295
+ This is the same as `v in G[u]` without KeyError exceptions.
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ u, v : nodes
1300
+ Nodes can be, for example, strings or numbers.
1301
+ Nodes must be hashable (and not None) Python objects.
1302
+
1303
+ Returns
1304
+ -------
1305
+ edge_ind : bool
1306
+ True if edge is in the graph, False otherwise.
1307
+
1308
+ Examples
1309
+ --------
1310
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1311
+ >>> G.has_edge(0, 1) # using two nodes
1312
+ True
1313
+ >>> e = (0, 1)
1314
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
1315
+ True
1316
+ >>> e = (0, 1, {"weight": 7})
1317
+ >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
1318
+ True
1319
+
1320
+ The following syntax are equivalent:
1321
+
1322
+ >>> G.has_edge(0, 1)
1323
+ True
1324
+ >>> 1 in G[0] # though this gives KeyError if 0 not in G
1325
+ True
1326
+
1327
+ """
1328
+ try:
1329
+ return v in self._adj[u]
1330
+ except KeyError:
1331
+ return False
1332
+
1333
+ def neighbors(self, n):
1334
+ """Returns an iterator over all neighbors of node n.
1335
+
1336
+ This is identical to `iter(G[n])`
1337
+
1338
+ Parameters
1339
+ ----------
1340
+ n : node
1341
+ A node in the graph
1342
+
1343
+ Returns
1344
+ -------
1345
+ neighbors : iterator
1346
+ An iterator over all neighbors of node n
1347
+
1348
+ Raises
1349
+ ------
1350
+ NetworkXError
1351
+ If the node n is not in the graph.
1352
+
1353
+ Examples
1354
+ --------
1355
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1356
+ >>> [n for n in G.neighbors(0)]
1357
+ [1]
1358
+
1359
+ Notes
1360
+ -----
1361
+ Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
1362
+
1363
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1364
+ >>> G.add_edge("a", "b", weight=7)
1365
+ >>> G["a"]
1366
+ AtlasView({'b': {'weight': 7}})
1367
+ >>> G = nx.path_graph(4)
1368
+ >>> [n for n in G[0]]
1369
+ [1]
1370
+ """
1371
+ try:
1372
+ return iter(self._adj[n])
1373
+ except KeyError as err:
1374
+ raise NetworkXError(f"The node {n} is not in the graph.") from err
1375
+
1376
+ @cached_property
1377
+ def edges(self):
1378
+ """An EdgeView of the Graph as G.edges or G.edges().
1379
+
1380
+ edges(self, nbunch=None, data=False, default=None)
1381
+
1382
+ The EdgeView provides set-like operations on the edge-tuples
1383
+ as well as edge attribute lookup. When called, it also provides
1384
+ an EdgeDataView object which allows control of access to edge
1385
+ attributes (but does not provide set-like operations).
1386
+ Hence, `G.edges[u, v]['color']` provides the value of the color
1387
+ attribute for edge `(u, v)` while
1388
+ `for (u, v, c) in G.edges.data('color', default='red'):`
1389
+ iterates through all the edges yielding the color attribute
1390
+ with default `'red'` if no color attribute exists.
1391
+
1392
+ Parameters
1393
+ ----------
1394
+ nbunch : single node, container, or all nodes (default= all nodes)
1395
+ The view will only report edges from these nodes.
1396
+ data : string or bool, optional (default=False)
1397
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
1398
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
1399
+ If False, return 2-tuple (u, v).
1400
+ default : value, optional (default=None)
1401
+ Value used for edges that don't have the requested attribute.
1402
+ Only relevant if data is not True or False.
1403
+
1404
+ Returns
1405
+ -------
1406
+ edges : EdgeView
1407
+ A view of edge attributes, usually it iterates over (u, v)
1408
+ or (u, v, d) tuples of edges, but can also be used for
1409
+ attribute lookup as `edges[u, v]['foo']`.
1410
+
1411
+ Notes
1412
+ -----
1413
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
1414
+ For directed graphs this returns the out-edges.
1415
+
1416
+ Examples
1417
+ --------
1418
+ >>> G = nx.path_graph(3) # or MultiGraph, etc
1419
+ >>> G.add_edge(2, 3, weight=5)
1420
+ >>> [e for e in G.edges]
1421
+ [(0, 1), (1, 2), (2, 3)]
1422
+ >>> G.edges.data() # default data is {} (empty dict)
1423
+ EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
1424
+ >>> G.edges.data("weight", default=1)
1425
+ EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
1426
+ >>> G.edges([0, 3]) # only edges from these nodes
1427
+ EdgeDataView([(0, 1), (3, 2)])
1428
+ >>> G.edges(0) # only edges from node 0
1429
+ EdgeDataView([(0, 1)])
1430
+ """
1431
+ return EdgeView(self)
1432
+
1433
+ def get_edge_data(self, u, v, default=None):
1434
+ """Returns the attribute dictionary associated with edge (u, v).
1435
+
1436
+ This is identical to `G[u][v]` except the default is returned
1437
+ instead of an exception if the edge doesn't exist.
1438
+
1439
+ Parameters
1440
+ ----------
1441
+ u, v : nodes
1442
+ default: any Python object (default=None)
1443
+ Value to return if the edge (u, v) is not found.
1444
+
1445
+ Returns
1446
+ -------
1447
+ edge_dict : dictionary
1448
+ The edge attribute dictionary.
1449
+
1450
+ Examples
1451
+ --------
1452
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1453
+ >>> G[0][1]
1454
+ {}
1455
+
1456
+ Warning: Assigning to `G[u][v]` is not permitted.
1457
+ But it is safe to assign attributes `G[u][v]['foo']`
1458
+
1459
+ >>> G[0][1]["weight"] = 7
1460
+ >>> G[0][1]["weight"]
1461
+ 7
1462
+ >>> G[1][0]["weight"]
1463
+ 7
1464
+
1465
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1466
+ >>> G.get_edge_data(0, 1) # default edge data is {}
1467
+ {}
1468
+ >>> e = (0, 1)
1469
+ >>> G.get_edge_data(*e) # tuple form
1470
+ {}
1471
+ >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
1472
+ 0
1473
+ """
1474
+ try:
1475
+ return self._adj[u][v]
1476
+ except KeyError:
1477
+ return default
1478
+
1479
+ def adjacency(self):
1480
+ """Returns an iterator over (node, adjacency dict) tuples for all nodes.
1481
+
1482
+ For directed graphs, only outgoing neighbors/adjacencies are included.
1483
+
1484
+ Returns
1485
+ -------
1486
+ adj_iter : iterator
1487
+ An iterator over (node, adjacency dictionary) for all nodes in
1488
+ the graph.
1489
+
1490
+ Examples
1491
+ --------
1492
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1493
+ >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
1494
+ [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
1495
+
1496
+ """
1497
+ return iter(self._adj.items())
1498
+
1499
+ @cached_property
1500
+ def degree(self):
1501
+ """A DegreeView for the Graph as G.degree or G.degree().
1502
+
1503
+ The node degree is the number of edges adjacent to the node.
1504
+ The weighted node degree is the sum of the edge weights for
1505
+ edges incident to that node.
1506
+
1507
+ This object provides an iterator for (node, degree) as well as
1508
+ lookup for the degree for a single node.
1509
+
1510
+ Parameters
1511
+ ----------
1512
+ nbunch : single node, container, or all nodes (default= all nodes)
1513
+ The view will only report edges incident to these nodes.
1514
+
1515
+ weight : string or None, optional (default=None)
1516
+ The name of an edge attribute that holds the numerical value used
1517
+ as a weight. If None, then each edge has weight 1.
1518
+ The degree is the sum of the edge weights adjacent to the node.
1519
+
1520
+ Returns
1521
+ -------
1522
+ DegreeView or int
1523
+ If multiple nodes are requested (the default), returns a `DegreeView`
1524
+ mapping nodes to their degree.
1525
+ If a single node is requested, returns the degree of the node as an integer.
1526
+
1527
+ Examples
1528
+ --------
1529
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1530
+ >>> G.degree[0] # node 0 has degree 1
1531
+ 1
1532
+ >>> list(G.degree([0, 1, 2]))
1533
+ [(0, 1), (1, 2), (2, 2)]
1534
+ """
1535
+ return DegreeView(self)
1536
+
1537
+ def clear(self):
1538
+ """Remove all nodes and edges from the graph.
1539
+
1540
+ This also removes the name, and all graph, node, and edge attributes.
1541
+
1542
+ Examples
1543
+ --------
1544
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1545
+ >>> G.clear()
1546
+ >>> list(G.nodes)
1547
+ []
1548
+ >>> list(G.edges)
1549
+ []
1550
+
1551
+ """
1552
+ self._adj.clear()
1553
+ self._node.clear()
1554
+ self.graph.clear()
1555
+ nx._clear_cache(self)
1556
+
1557
+ def clear_edges(self):
1558
+ """Remove all edges from the graph without altering nodes.
1559
+
1560
+ Examples
1561
+ --------
1562
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1563
+ >>> G.clear_edges()
1564
+ >>> list(G.nodes)
1565
+ [0, 1, 2, 3]
1566
+ >>> list(G.edges)
1567
+ []
1568
+ """
1569
+ for nbr_dict in self._adj.values():
1570
+ nbr_dict.clear()
1571
+ nx._clear_cache(self)
1572
+
1573
+ def is_multigraph(self):
1574
+ """Returns True if graph is a multigraph, False otherwise."""
1575
+ return False
1576
+
1577
+ def is_directed(self):
1578
+ """Returns True if graph is directed, False otherwise."""
1579
+ return False
1580
+
1581
+ def copy(self, as_view=False):
1582
+ """Returns a copy of the graph.
1583
+
1584
+ The copy method by default returns an independent shallow copy
1585
+ of the graph and attributes. That is, if an attribute is a
1586
+ container, that container is shared by the original an the copy.
1587
+ Use Python's `copy.deepcopy` for new containers.
1588
+
1589
+ If `as_view` is True then a view is returned instead of a copy.
1590
+
1591
+ Notes
1592
+ -----
1593
+ All copies reproduce the graph structure, but data attributes
1594
+ may be handled in different ways. There are four types of copies
1595
+ of a graph that people might want.
1596
+
1597
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1598
+ all data attributes and any objects they might contain.
1599
+ The entire graph object is new so that changes in the copy
1600
+ do not affect the original object. (see Python's copy.deepcopy)
1601
+
1602
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1603
+ is copied but the edge, node and graph attribute dicts are
1604
+ references to those in the original graph. This saves
1605
+ time and memory but could cause confusion if you change an attribute
1606
+ in one graph and it changes the attribute in the other.
1607
+ NetworkX does not provide this level of shallow copy.
1608
+
1609
+ Independent Shallow -- This copy creates new independent attribute
1610
+ dicts and then does a shallow copy of the attributes. That is, any
1611
+ attributes that are containers are shared between the new graph
1612
+ and the original. This is exactly what `dict.copy()` provides.
1613
+ You can obtain this style copy using:
1614
+
1615
+ >>> G = nx.path_graph(5)
1616
+ >>> H = G.copy()
1617
+ >>> H = G.copy(as_view=False)
1618
+ >>> H = nx.Graph(G)
1619
+ >>> H = G.__class__(G)
1620
+
1621
+ Fresh Data -- For fresh data, the graph structure is copied while
1622
+ new empty data attribute dicts are created. The resulting graph
1623
+ is independent of the original and it has no edge, node or graph
1624
+ attributes. Fresh copies are not enabled. Instead use:
1625
+
1626
+ >>> H = G.__class__()
1627
+ >>> H.add_nodes_from(G)
1628
+ >>> H.add_edges_from(G.edges)
1629
+
1630
+ View -- Inspired by dict-views, graph-views act like read-only
1631
+ versions of the original graph, providing a copy of the original
1632
+ structure without requiring any memory for copying the information.
1633
+
1634
+ See the Python copy module for more information on shallow
1635
+ and deep copies, https://docs.python.org/3/library/copy.html.
1636
+
1637
+ Parameters
1638
+ ----------
1639
+ as_view : bool, optional (default=False)
1640
+ If True, the returned graph-view provides a read-only view
1641
+ of the original graph without actually copying any data.
1642
+
1643
+ Returns
1644
+ -------
1645
+ G : Graph
1646
+ A copy of the graph.
1647
+
1648
+ See Also
1649
+ --------
1650
+ to_directed: return a directed copy of the graph.
1651
+
1652
+ Examples
1653
+ --------
1654
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1655
+ >>> H = G.copy()
1656
+
1657
+ """
1658
+ if as_view is True:
1659
+ return nx.graphviews.generic_graph_view(self)
1660
+ G = self.__class__()
1661
+ G.graph.update(self.graph)
1662
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1663
+ G.add_edges_from(
1664
+ (u, v, datadict.copy())
1665
+ for u, nbrs in self._adj.items()
1666
+ for v, datadict in nbrs.items()
1667
+ )
1668
+ return G
1669
+
1670
+ def to_directed(self, as_view=False):
1671
+ """Returns a directed representation of the graph.
1672
+
1673
+ Returns
1674
+ -------
1675
+ G : DiGraph
1676
+ A directed graph with the same name, same nodes, and with
1677
+ each edge (u, v, data) replaced by two directed edges
1678
+ (u, v, data) and (v, u, data).
1679
+
1680
+ Notes
1681
+ -----
1682
+ This returns a "deepcopy" of the edge, node, and
1683
+ graph attributes which attempts to completely copy
1684
+ all of the data and references.
1685
+
1686
+ This is in contrast to the similar D=DiGraph(G) which returns a
1687
+ shallow copy of the data.
1688
+
1689
+ See the Python copy module for more information on shallow
1690
+ and deep copies, https://docs.python.org/3/library/copy.html.
1691
+
1692
+ Warning: If you have subclassed Graph to use dict-like objects
1693
+ in the data structure, those changes do not transfer to the
1694
+ DiGraph created by this method.
1695
+
1696
+ Examples
1697
+ --------
1698
+ >>> G = nx.Graph() # or MultiGraph, etc
1699
+ >>> G.add_edge(0, 1)
1700
+ >>> H = G.to_directed()
1701
+ >>> list(H.edges)
1702
+ [(0, 1), (1, 0)]
1703
+
1704
+ If already directed, return a (deep) copy
1705
+
1706
+ >>> G = nx.DiGraph() # or MultiDiGraph, etc
1707
+ >>> G.add_edge(0, 1)
1708
+ >>> H = G.to_directed()
1709
+ >>> list(H.edges)
1710
+ [(0, 1)]
1711
+ """
1712
+ graph_class = self.to_directed_class()
1713
+ if as_view is True:
1714
+ return nx.graphviews.generic_graph_view(self, graph_class)
1715
+ # deepcopy when not a view
1716
+ G = graph_class()
1717
+ G.graph.update(deepcopy(self.graph))
1718
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1719
+ G.add_edges_from(
1720
+ (u, v, deepcopy(data))
1721
+ for u, nbrs in self._adj.items()
1722
+ for v, data in nbrs.items()
1723
+ )
1724
+ return G
1725
+
1726
+ def to_undirected(self, as_view=False):
1727
+ """Returns an undirected copy of the graph.
1728
+
1729
+ Parameters
1730
+ ----------
1731
+ as_view : bool (optional, default=False)
1732
+ If True return a view of the original undirected graph.
1733
+
1734
+ Returns
1735
+ -------
1736
+ G : Graph/MultiGraph
1737
+ A deepcopy of the graph.
1738
+
1739
+ See Also
1740
+ --------
1741
+ Graph, copy, add_edge, add_edges_from
1742
+
1743
+ Notes
1744
+ -----
1745
+ This returns a "deepcopy" of the edge, node, and
1746
+ graph attributes which attempts to completely copy
1747
+ all of the data and references.
1748
+
1749
+ This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
1750
+ shallow copy of the data.
1751
+
1752
+ See the Python copy module for more information on shallow
1753
+ and deep copies, https://docs.python.org/3/library/copy.html.
1754
+
1755
+ Warning: If you have subclassed DiGraph to use dict-like objects
1756
+ in the data structure, those changes do not transfer to the
1757
+ Graph created by this method.
1758
+
1759
+ Examples
1760
+ --------
1761
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
1762
+ >>> H = G.to_directed()
1763
+ >>> list(H.edges)
1764
+ [(0, 1), (1, 0)]
1765
+ >>> G2 = H.to_undirected()
1766
+ >>> list(G2.edges)
1767
+ [(0, 1)]
1768
+ """
1769
+ graph_class = self.to_undirected_class()
1770
+ if as_view is True:
1771
+ return nx.graphviews.generic_graph_view(self, graph_class)
1772
+ # deepcopy when not a view
1773
+ G = graph_class()
1774
+ G.graph.update(deepcopy(self.graph))
1775
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1776
+ G.add_edges_from(
1777
+ (u, v, deepcopy(d))
1778
+ for u, nbrs in self._adj.items()
1779
+ for v, d in nbrs.items()
1780
+ )
1781
+ return G
1782
+
1783
+ def subgraph(self, nodes):
1784
+ """Returns a SubGraph view of the subgraph induced on `nodes`.
1785
+
1786
+ The induced subgraph of the graph contains the nodes in `nodes`
1787
+ and the edges between those nodes.
1788
+
1789
+ Parameters
1790
+ ----------
1791
+ nodes : list, iterable
1792
+ A container of nodes which will be iterated through once.
1793
+
1794
+ Returns
1795
+ -------
1796
+ G : SubGraph View
1797
+ A subgraph view of the graph. The graph structure cannot be
1798
+ changed but node/edge attributes can and are shared with the
1799
+ original graph.
1800
+
1801
+ Notes
1802
+ -----
1803
+ The graph, edge and node attributes are shared with the original graph.
1804
+ Changes to the graph structure is ruled out by the view, but changes
1805
+ to attributes are reflected in the original graph.
1806
+
1807
+ To create a subgraph with its own copy of the edge/node attributes use:
1808
+ G.subgraph(nodes).copy()
1809
+
1810
+ For an inplace reduction of a graph to a subgraph you can remove nodes:
1811
+ G.remove_nodes_from([n for n in G if n not in set(nodes)])
1812
+
1813
+ Subgraph views are sometimes NOT what you want. In most cases where
1814
+ you want to do more than simply look at the induced edges, it makes
1815
+ more sense to just create the subgraph as its own graph with code like:
1816
+
1817
+ ::
1818
+
1819
+ # Create a subgraph SG based on a (possibly multigraph) G
1820
+ SG = G.__class__()
1821
+ SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
1822
+ if SG.is_multigraph():
1823
+ SG.add_edges_from(
1824
+ (n, nbr, key, d)
1825
+ for n, nbrs in G.adj.items()
1826
+ if n in largest_wcc
1827
+ for nbr, keydict in nbrs.items()
1828
+ if nbr in largest_wcc
1829
+ for key, d in keydict.items()
1830
+ )
1831
+ else:
1832
+ SG.add_edges_from(
1833
+ (n, nbr, d)
1834
+ for n, nbrs in G.adj.items()
1835
+ if n in largest_wcc
1836
+ for nbr, d in nbrs.items()
1837
+ if nbr in largest_wcc
1838
+ )
1839
+ SG.graph.update(G.graph)
1840
+
1841
+ Examples
1842
+ --------
1843
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1844
+ >>> H = G.subgraph([0, 1, 2])
1845
+ >>> list(H.edges)
1846
+ [(0, 1), (1, 2)]
1847
+ """
1848
+ induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
1849
+ # if already a subgraph, don't make a chain
1850
+ subgraph = nx.subgraph_view
1851
+ if hasattr(self, "_NODE_OK"):
1852
+ return subgraph(
1853
+ self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
1854
+ )
1855
+ return subgraph(self, filter_node=induced_nodes)
1856
+
1857
+ def edge_subgraph(self, edges):
1858
+ """Returns the subgraph induced by the specified edges.
1859
+
1860
+ The induced subgraph contains each edge in `edges` and each
1861
+ node incident to any one of those edges.
1862
+
1863
+ Parameters
1864
+ ----------
1865
+ edges : iterable
1866
+ An iterable of edges in this graph.
1867
+
1868
+ Returns
1869
+ -------
1870
+ G : Graph
1871
+ An edge-induced subgraph of this graph with the same edge
1872
+ attributes.
1873
+
1874
+ Notes
1875
+ -----
1876
+ The graph, edge, and node attributes in the returned subgraph
1877
+ view are references to the corresponding attributes in the original
1878
+ graph. The view is read-only.
1879
+
1880
+ To create a full graph version of the subgraph with its own copy
1881
+ of the edge or node attributes, use::
1882
+
1883
+ G.edge_subgraph(edges).copy()
1884
+
1885
+ Examples
1886
+ --------
1887
+ >>> G = nx.path_graph(5)
1888
+ >>> H = G.edge_subgraph([(0, 1), (3, 4)])
1889
+ >>> list(H.nodes)
1890
+ [0, 1, 3, 4]
1891
+ >>> list(H.edges)
1892
+ [(0, 1), (3, 4)]
1893
+
1894
+ """
1895
+ return nx.edge_subgraph(self, edges)
1896
+
1897
+ def size(self, weight=None):
1898
+ """Returns the number of edges or total of all edge weights.
1899
+
1900
+ Parameters
1901
+ ----------
1902
+ weight : string or None, optional (default=None)
1903
+ The edge attribute that holds the numerical value used
1904
+ as a weight. If None, then each edge has weight 1.
1905
+
1906
+ Returns
1907
+ -------
1908
+ size : numeric
1909
+ The number of edges or
1910
+ (if weight keyword is provided) the total weight sum.
1911
+
1912
+ If weight is None, returns an int. Otherwise a float
1913
+ (or more general numeric if the weights are more general).
1914
+
1915
+ See Also
1916
+ --------
1917
+ number_of_edges
1918
+
1919
+ Examples
1920
+ --------
1921
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1922
+ >>> G.size()
1923
+ 3
1924
+
1925
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1926
+ >>> G.add_edge("a", "b", weight=2)
1927
+ >>> G.add_edge("b", "c", weight=4)
1928
+ >>> G.size()
1929
+ 2
1930
+ >>> G.size(weight="weight")
1931
+ 6.0
1932
+ """
1933
+ s = sum(d for v, d in self.degree(weight=weight))
1934
+ # If `weight` is None, the sum of the degrees is guaranteed to be
1935
+ # even, so we can perform integer division and hence return an
1936
+ # integer. Otherwise, the sum of the weighted degrees is not
1937
+ # guaranteed to be an integer, so we perform "real" division.
1938
+ return s // 2 if weight is None else s / 2
1939
+
1940
+ def number_of_edges(self, u=None, v=None):
1941
+ """Returns the number of edges between two nodes.
1942
+
1943
+ Parameters
1944
+ ----------
1945
+ u, v : nodes, optional (default=all edges)
1946
+ If u and v are specified, return the number of edges between
1947
+ u and v. Otherwise return the total number of all edges.
1948
+
1949
+ Returns
1950
+ -------
1951
+ nedges : int
1952
+ The number of edges in the graph. If nodes `u` and `v` are
1953
+ specified return the number of edges between those nodes. If
1954
+ the graph is directed, this only returns the number of edges
1955
+ from `u` to `v`.
1956
+
1957
+ See Also
1958
+ --------
1959
+ size
1960
+
1961
+ Examples
1962
+ --------
1963
+ For undirected graphs, this method counts the total number of
1964
+ edges in the graph:
1965
+
1966
+ >>> G = nx.path_graph(4)
1967
+ >>> G.number_of_edges()
1968
+ 3
1969
+
1970
+ If you specify two nodes, this counts the total number of edges
1971
+ joining the two nodes:
1972
+
1973
+ >>> G.number_of_edges(0, 1)
1974
+ 1
1975
+
1976
+ For directed graphs, this method can count the total number of
1977
+ directed edges from `u` to `v`:
1978
+
1979
+ >>> G = nx.DiGraph()
1980
+ >>> G.add_edge(0, 1)
1981
+ >>> G.add_edge(1, 0)
1982
+ >>> G.number_of_edges(0, 1)
1983
+ 1
1984
+
1985
+ """
1986
+ if u is None:
1987
+ return int(self.size())
1988
+ if v in self._adj[u]:
1989
+ return 1
1990
+ return 0
1991
+
1992
+ def nbunch_iter(self, nbunch=None):
1993
+ """Returns an iterator over nodes contained in nbunch that are
1994
+ also in the graph.
1995
+
1996
+ The nodes in nbunch are checked for membership in the graph
1997
+ and if not are silently ignored.
1998
+
1999
+ Parameters
2000
+ ----------
2001
+ nbunch : single node, container, or all nodes (default= all nodes)
2002
+ The view will only report edges incident to these nodes.
2003
+
2004
+ Returns
2005
+ -------
2006
+ niter : iterator
2007
+ An iterator over nodes in nbunch that are also in the graph.
2008
+ If nbunch is None, iterate over all nodes in the graph.
2009
+
2010
+ Raises
2011
+ ------
2012
+ NetworkXError
2013
+ If nbunch is not a node or sequence of nodes.
2014
+ If a node in nbunch is not hashable.
2015
+
2016
+ See Also
2017
+ --------
2018
+ Graph.__iter__
2019
+
2020
+ Notes
2021
+ -----
2022
+ When nbunch is an iterator, the returned iterator yields values
2023
+ directly from nbunch, becoming exhausted when nbunch is exhausted.
2024
+
2025
+ To test whether nbunch is a single node, one can use
2026
+ "if nbunch in self:", even after processing with this routine.
2027
+
2028
+ If nbunch is not a node or a (possibly empty) sequence/iterator
2029
+ or None, a :exc:`NetworkXError` is raised. Also, if any object in
2030
+ nbunch is not hashable, a :exc:`NetworkXError` is raised.
2031
+ """
2032
+ if nbunch is None: # include all nodes via iterator
2033
+ bunch = iter(self._adj)
2034
+ elif nbunch in self: # if nbunch is a single node
2035
+ bunch = iter([nbunch])
2036
+ else: # if nbunch is a sequence of nodes
2037
+
2038
+ def bunch_iter(nlist, adj):
2039
+ try:
2040
+ for n in nlist:
2041
+ if n in adj:
2042
+ yield n
2043
+ except TypeError as err:
2044
+ exc, message = err, err.args[0]
2045
+ # capture error for non-sequence/iterator nbunch.
2046
+ if "iter" in message:
2047
+ exc = NetworkXError(
2048
+ "nbunch is not a node or a sequence of nodes."
2049
+ )
2050
+ # capture error for unhashable node.
2051
+ if "hashable" in message:
2052
+ exc = NetworkXError(
2053
+ f"Node {n} in sequence nbunch is not a valid node."
2054
+ )
2055
+ raise exc
2056
+
2057
+ bunch = bunch_iter(nbunch, self._adj)
2058
+ return bunch
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/graphviews.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """View of Graphs as SubGraph, Reverse, Directed, Undirected.
2
+
3
+ In some algorithms it is convenient to temporarily morph
4
+ a graph to exclude some nodes or edges. It should be better
5
+ to do that via a view than to remove and then re-add.
6
+ In other algorithms it is convenient to temporarily morph
7
+ a graph to reverse directed edges, or treat a directed graph
8
+ as undirected, etc. This module provides those graph views.
9
+
10
+ The resulting views are essentially read-only graphs that
11
+ report data from the original graph object. We provide an
12
+ attribute G._graph which points to the underlying graph object.
13
+
14
+ Note: Since graphviews look like graphs, one can end up with
15
+ view-of-view-of-view chains. Be careful with chains because
16
+ they become very slow with about 15 nested views.
17
+ For the common simple case of node induced subgraphs created
18
+ from the graph class, we short-cut the chain by returning a
19
+ subgraph of the original graph directly rather than a subgraph
20
+ of a subgraph. We are careful not to disrupt any edge filter in
21
+ the middle subgraph. In general, determining how to short-cut
22
+ the chain is tricky and much harder with restricted_views than
23
+ with induced subgraphs.
24
+ Often it is easiest to use .copy() to avoid chains.
25
+ """
26
+
27
+ import networkx as nx
28
+ from networkx.classes.coreviews import (
29
+ FilterAdjacency,
30
+ FilterAtlas,
31
+ FilterMultiAdjacency,
32
+ UnionAdjacency,
33
+ UnionMultiAdjacency,
34
+ )
35
+ from networkx.classes.filters import no_filter
36
+ from networkx.exception import NetworkXError
37
+ from networkx.utils import not_implemented_for
38
+
39
+ __all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
40
+
41
+
42
+ def generic_graph_view(G, create_using=None):
43
+ """Returns a read-only view of `G`.
44
+
45
+ The graph `G` and its attributes are not copied but viewed through the new graph object
46
+ of the same class as `G` (or of the class specified in `create_using`).
47
+
48
+ Parameters
49
+ ----------
50
+ G : graph
51
+ A directed/undirected graph/multigraph.
52
+
53
+ create_using : NetworkX graph constructor, optional (default=None)
54
+ Graph type to create. If graph instance, then cleared before populated.
55
+ If `None`, then the appropriate Graph type is inferred from `G`.
56
+
57
+ Returns
58
+ -------
59
+ newG : graph
60
+ A view of the input graph `G` and its attributes as viewed through
61
+ the `create_using` class.
62
+
63
+ Raises
64
+ ------
65
+ NetworkXError
66
+ If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
67
+
68
+ Notes
69
+ -----
70
+ The returned graph view is read-only (cannot modify the graph).
71
+ Yet the view reflects any changes in `G`. The intent is to mimic dict views.
72
+
73
+ Examples
74
+ --------
75
+ >>> G = nx.Graph()
76
+ >>> G.add_edge(1, 2, weight=0.3)
77
+ >>> G.add_edge(2, 3, weight=0.5)
78
+ >>> G.edges(data=True)
79
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
80
+
81
+ The view exposes the attributes from the original graph.
82
+
83
+ >>> viewG = nx.graphviews.generic_graph_view(G)
84
+ >>> viewG.edges(data=True)
85
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
86
+
87
+ Changes to `G` are reflected in `viewG`.
88
+
89
+ >>> G.remove_edge(2, 3)
90
+ >>> G.edges(data=True)
91
+ EdgeDataView([(1, 2, {'weight': 0.3})])
92
+
93
+ >>> viewG.edges(data=True)
94
+ EdgeDataView([(1, 2, {'weight': 0.3})])
95
+
96
+ We can change the graph type with the `create_using` parameter.
97
+
98
+ >>> type(G)
99
+ <class 'networkx.classes.graph.Graph'>
100
+ >>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph)
101
+ >>> type(viewDG)
102
+ <class 'networkx.classes.digraph.DiGraph'>
103
+ """
104
+ if create_using is None:
105
+ newG = G.__class__()
106
+ else:
107
+ newG = nx.empty_graph(0, create_using)
108
+ if G.is_multigraph() != newG.is_multigraph():
109
+ raise NetworkXError("Multigraph for G must agree with create_using")
110
+ newG = nx.freeze(newG)
111
+
112
+ # create view by assigning attributes from G
113
+ newG._graph = G
114
+ newG.graph = G.graph
115
+
116
+ newG._node = G._node
117
+ if newG.is_directed():
118
+ if G.is_directed():
119
+ newG._succ = G._succ
120
+ newG._pred = G._pred
121
+ # newG._adj is synced with _succ
122
+ else:
123
+ newG._succ = G._adj
124
+ newG._pred = G._adj
125
+ # newG._adj is synced with _succ
126
+ elif G.is_directed():
127
+ if G.is_multigraph():
128
+ newG._adj = UnionMultiAdjacency(G._succ, G._pred)
129
+ else:
130
+ newG._adj = UnionAdjacency(G._succ, G._pred)
131
+ else:
132
+ newG._adj = G._adj
133
+ return newG
134
+
135
+
136
+ def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter):
137
+ """View of `G` applying a filter on nodes and edges.
138
+
139
+ `subgraph_view` provides a read-only view of the input graph that excludes
140
+ nodes and edges based on the outcome of two filter functions `filter_node`
141
+ and `filter_edge`.
142
+
143
+ The `filter_node` function takes one argument --- the node --- and returns
144
+ `True` if the node should be included in the subgraph, and `False` if it
145
+ should not be included.
146
+
147
+ The `filter_edge` function takes two (or three arguments if `G` is a
148
+ multi-graph) --- the nodes describing an edge, plus the edge-key if
149
+ parallel edges are possible --- and returns `True` if the edge should be
150
+ included in the subgraph, and `False` if it should not be included.
151
+
152
+ Both node and edge filter functions are called on graph elements as they
153
+ are queried, meaning there is no up-front cost to creating the view.
154
+
155
+ Parameters
156
+ ----------
157
+ G : networkx.Graph
158
+ A directed/undirected graph/multigraph
159
+
160
+ filter_node : callable, optional
161
+ A function taking a node as input, which returns `True` if the node
162
+ should appear in the view.
163
+
164
+ filter_edge : callable, optional
165
+ A function taking as input the two nodes describing an edge (plus the
166
+ edge-key if `G` is a multi-graph), which returns `True` if the edge
167
+ should appear in the view.
168
+
169
+ Returns
170
+ -------
171
+ graph : networkx.Graph
172
+ A read-only graph view of the input graph.
173
+
174
+ Examples
175
+ --------
176
+ >>> G = nx.path_graph(6)
177
+
178
+ Filter functions operate on the node, and return `True` if the node should
179
+ appear in the view:
180
+
181
+ >>> def filter_node(n1):
182
+ ... return n1 != 5
183
+ >>> view = nx.subgraph_view(G, filter_node=filter_node)
184
+ >>> view.nodes()
185
+ NodeView((0, 1, 2, 3, 4))
186
+
187
+ We can use a closure pattern to filter graph elements based on additional
188
+ data --- for example, filtering on edge data attached to the graph:
189
+
190
+ >>> G[3][4]["cross_me"] = False
191
+ >>> def filter_edge(n1, n2):
192
+ ... return G[n1][n2].get("cross_me", True)
193
+ >>> view = nx.subgraph_view(G, filter_edge=filter_edge)
194
+ >>> view.edges()
195
+ EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
196
+
197
+ >>> view = nx.subgraph_view(
198
+ ... G,
199
+ ... filter_node=filter_node,
200
+ ... filter_edge=filter_edge,
201
+ ... )
202
+ >>> view.nodes()
203
+ NodeView((0, 1, 2, 3, 4))
204
+ >>> view.edges()
205
+ EdgeView([(0, 1), (1, 2), (2, 3)])
206
+ """
207
+ newG = nx.freeze(G.__class__())
208
+ newG._NODE_OK = filter_node
209
+ newG._EDGE_OK = filter_edge
210
+
211
+ # create view by assigning attributes from G
212
+ newG._graph = G
213
+ newG.graph = G.graph
214
+
215
+ newG._node = FilterAtlas(G._node, filter_node)
216
+ if G.is_multigraph():
217
+ Adj = FilterMultiAdjacency
218
+
219
+ def reverse_edge(u, v, k=None):
220
+ return filter_edge(v, u, k)
221
+
222
+ else:
223
+ Adj = FilterAdjacency
224
+
225
+ def reverse_edge(u, v, k=None):
226
+ return filter_edge(v, u)
227
+
228
+ if G.is_directed():
229
+ newG._succ = Adj(G._succ, filter_node, filter_edge)
230
+ newG._pred = Adj(G._pred, filter_node, reverse_edge)
231
+ # newG._adj is synced with _succ
232
+ else:
233
+ newG._adj = Adj(G._adj, filter_node, filter_edge)
234
+ return newG
235
+
236
+
237
+ @not_implemented_for("undirected")
238
+ def reverse_view(G):
239
+ """View of `G` with edge directions reversed
240
+
241
+ `reverse_view` returns a read-only view of the input graph where
242
+ edge directions are reversed.
243
+
244
+ Identical to digraph.reverse(copy=False)
245
+
246
+ Parameters
247
+ ----------
248
+ G : networkx.DiGraph
249
+
250
+ Returns
251
+ -------
252
+ graph : networkx.DiGraph
253
+
254
+ Examples
255
+ --------
256
+ >>> G = nx.DiGraph()
257
+ >>> G.add_edge(1, 2)
258
+ >>> G.add_edge(2, 3)
259
+ >>> G.edges()
260
+ OutEdgeView([(1, 2), (2, 3)])
261
+
262
+ >>> view = nx.reverse_view(G)
263
+ >>> view.edges()
264
+ OutEdgeView([(2, 1), (3, 2)])
265
+ """
266
+ newG = generic_graph_view(G)
267
+ newG._succ, newG._pred = G._pred, G._succ
268
+ # newG._adj is synced with _succ
269
+ return newG
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/multidigraph.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiDiGraph."""
2
+
3
+ from copy import deepcopy
4
+ from functools import cached_property
5
+
6
+ import networkx as nx
7
+ from networkx import convert
8
+ from networkx.classes.coreviews import MultiAdjacencyView
9
+ from networkx.classes.digraph import DiGraph
10
+ from networkx.classes.multigraph import MultiGraph
11
+ from networkx.classes.reportviews import (
12
+ DiMultiDegreeView,
13
+ InMultiDegreeView,
14
+ InMultiEdgeView,
15
+ OutMultiDegreeView,
16
+ OutMultiEdgeView,
17
+ )
18
+ from networkx.exception import NetworkXError
19
+
20
+ __all__ = ["MultiDiGraph"]
21
+
22
+
23
+ class MultiDiGraph(MultiGraph, DiGraph):
24
+ """A directed graph class that can store multiedges.
25
+
26
+ Multiedges are multiple edges between two nodes. Each edge
27
+ can hold optional data or attributes.
28
+
29
+ A MultiDiGraph holds directed edges. Self loops are allowed.
30
+
31
+ Nodes can be arbitrary (hashable) Python objects with optional
32
+ key/value attributes. By convention `None` is not used as a node.
33
+
34
+ Edges are represented as links between nodes with optional
35
+ key/value attributes.
36
+
37
+ Parameters
38
+ ----------
39
+ incoming_graph_data : input graph (optional, default: None)
40
+ Data to initialize graph. If None (default) an empty
41
+ graph is created. The data can be any format that is supported
42
+ by the to_networkx_graph() function, currently including edge list,
43
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
44
+ sparse matrix, or PyGraphviz graph.
45
+
46
+ multigraph_input : bool or None (default None)
47
+ Note: Only used when `incoming_graph_data` is a dict.
48
+ If True, `incoming_graph_data` is assumed to be a
49
+ dict-of-dict-of-dict-of-dict structure keyed by
50
+ node to neighbor to edge keys to edge data for multi-edges.
51
+ A NetworkXError is raised if this is not the case.
52
+ If False, :func:`to_networkx_graph` is used to try to determine
53
+ the dict's graph data structure as either a dict-of-dict-of-dict
54
+ keyed by node to neighbor to edge data, or a dict-of-iterable
55
+ keyed by node to neighbors.
56
+ If None, the treatment for True is tried, but if it fails,
57
+ the treatment for False is tried.
58
+
59
+ attr : keyword arguments, optional (default= no attributes)
60
+ Attributes to add to graph as key=value pairs.
61
+
62
+ See Also
63
+ --------
64
+ Graph
65
+ DiGraph
66
+ MultiGraph
67
+
68
+ Examples
69
+ --------
70
+ Create an empty graph structure (a "null graph") with no nodes and
71
+ no edges.
72
+
73
+ >>> G = nx.MultiDiGraph()
74
+
75
+ G can be grown in several ways.
76
+
77
+ **Nodes:**
78
+
79
+ Add one node at a time:
80
+
81
+ >>> G.add_node(1)
82
+
83
+ Add the nodes from any container (a list, dict, set or
84
+ even the lines from a file or the nodes from another graph).
85
+
86
+ >>> G.add_nodes_from([2, 3])
87
+ >>> G.add_nodes_from(range(100, 110))
88
+ >>> H = nx.path_graph(10)
89
+ >>> G.add_nodes_from(H)
90
+
91
+ In addition to strings and integers any hashable Python object
92
+ (except None) can represent a node, e.g. a customized node object,
93
+ or even another Graph.
94
+
95
+ >>> G.add_node(H)
96
+
97
+ **Edges:**
98
+
99
+ G can also be grown by adding edges.
100
+
101
+ Add one edge,
102
+
103
+ >>> key = G.add_edge(1, 2)
104
+
105
+ a list of edges,
106
+
107
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
108
+
109
+ or a collection of edges,
110
+
111
+ >>> keys = G.add_edges_from(H.edges)
112
+
113
+ If some edges connect nodes not yet in the graph, the nodes
114
+ are added automatically. If an edge already exists, an additional
115
+ edge is created and stored using a key to identify the edge.
116
+ By default the key is the lowest unused integer.
117
+
118
+ >>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
119
+ >>> G[4]
120
+ AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
121
+
122
+ **Attributes:**
123
+
124
+ Each graph, node, and edge can hold key/value attribute pairs
125
+ in an associated attribute dictionary (the keys must be hashable).
126
+ By default these are empty, but can be added or changed using
127
+ add_edge, add_node or direct manipulation of the attribute
128
+ dictionaries named graph, node and edge respectively.
129
+
130
+ >>> G = nx.MultiDiGraph(day="Friday")
131
+ >>> G.graph
132
+ {'day': 'Friday'}
133
+
134
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
135
+
136
+ >>> G.add_node(1, time="5pm")
137
+ >>> G.add_nodes_from([3], time="2pm")
138
+ >>> G.nodes[1]
139
+ {'time': '5pm'}
140
+ >>> G.nodes[1]["room"] = 714
141
+ >>> del G.nodes[1]["room"] # remove attribute
142
+ >>> list(G.nodes(data=True))
143
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
144
+
145
+ Add edge attributes using add_edge(), add_edges_from(), subscript
146
+ notation, or G.edges.
147
+
148
+ >>> key = G.add_edge(1, 2, weight=4.7)
149
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
150
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
151
+ >>> G[1][2][0]["weight"] = 4.7
152
+ >>> G.edges[1, 2, 0]["weight"] = 4
153
+
154
+ Warning: we protect the graph data structure by making `G.edges[1,
155
+ 2, 0]` a read-only dict-like structure. However, you can assign to
156
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
157
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
158
+ (for multigraphs the edge key is required: `MG.edges[u, v,
159
+ key][name] = value`).
160
+
161
+ **Shortcuts:**
162
+
163
+ Many common graph features allow python syntax to speed reporting.
164
+
165
+ >>> 1 in G # check if node in graph
166
+ True
167
+ >>> [n for n in G if n < 3] # iterate through nodes
168
+ [1, 2]
169
+ >>> len(G) # number of nodes in graph
170
+ 5
171
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
172
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
173
+
174
+ Often the best way to traverse all edges of a graph is via the neighbors.
175
+ The neighbors are available as an adjacency-view `G.adj` object or via
176
+ the method `G.adjacency()`.
177
+
178
+ >>> for n, nbrsdict in G.adjacency():
179
+ ... for nbr, keydict in nbrsdict.items():
180
+ ... for key, eattr in keydict.items():
181
+ ... if "weight" in eattr:
182
+ ... # Do something useful with the edges
183
+ ... pass
184
+
185
+ But the edges() method is often more convenient:
186
+
187
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
188
+ ... if weight is not None:
189
+ ... # Do something useful with the edges
190
+ ... pass
191
+
192
+ **Reporting:**
193
+
194
+ Simple graph information is obtained using methods and object-attributes.
195
+ Reporting usually provides views instead of containers to reduce memory
196
+ usage. The views update as the graph is updated similarly to dict-views.
197
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
198
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
199
+ (e.g. `nodes.items()`, `nodes.data('color')`,
200
+ `nodes.data('color', default='blue')` and similarly for `edges`)
201
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
202
+
203
+ For details on these and other miscellaneous methods, see below.
204
+
205
+ **Subclasses (Advanced):**
206
+
207
+ The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
208
+ The outer dict (node_dict) holds adjacency information keyed by node.
209
+ The next dict (adjlist_dict) represents the adjacency information
210
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
211
+ each edge_attr dict keyed by edge key. The inner dict
212
+ (edge_attr_dict) represents the edge data and holds edge attribute
213
+ values keyed by attribute names.
214
+
215
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
216
+ structure can be replaced by a user defined dict-like object.
217
+ In general, the dict-like features should be maintained but
218
+ extra features can be added. To replace one of the dicts create
219
+ a new graph class by changing the class(!) variable holding the
220
+ factory for that dict-like structure. The variable names are
221
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
222
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
223
+ and graph_attr_dict_factory.
224
+
225
+ node_dict_factory : function, (default: dict)
226
+ Factory function to be used to create the dict containing node
227
+ attributes, keyed by node id.
228
+ It should require no arguments and return a dict-like object
229
+
230
+ node_attr_dict_factory: function, (default: dict)
231
+ Factory function to be used to create the node attribute
232
+ dict which holds attribute values keyed by attribute name.
233
+ It should require no arguments and return a dict-like object
234
+
235
+ adjlist_outer_dict_factory : function, (default: dict)
236
+ Factory function to be used to create the outer-most dict
237
+ in the data structure that holds adjacency info keyed by node.
238
+ It should require no arguments and return a dict-like object.
239
+
240
+ adjlist_inner_dict_factory : function, (default: dict)
241
+ Factory function to be used to create the adjacency list
242
+ dict which holds multiedge key dicts keyed by neighbor.
243
+ It should require no arguments and return a dict-like object.
244
+
245
+ edge_key_dict_factory : function, (default: dict)
246
+ Factory function to be used to create the edge key dict
247
+ which holds edge data keyed by edge key.
248
+ It should require no arguments and return a dict-like object.
249
+
250
+ edge_attr_dict_factory : function, (default: dict)
251
+ Factory function to be used to create the edge attribute
252
+ dict which holds attribute values keyed by attribute name.
253
+ It should require no arguments and return a dict-like object.
254
+
255
+ graph_attr_dict_factory : function, (default: dict)
256
+ Factory function to be used to create the graph attribute
257
+ dict which holds attribute values keyed by attribute name.
258
+ It should require no arguments and return a dict-like object.
259
+
260
+ Typically, if your extension doesn't impact the data structure all
261
+ methods will inherited without issue except: `to_directed/to_undirected`.
262
+ By default these methods create a DiGraph/Graph class and you probably
263
+ want them to create your extension of a DiGraph/Graph. To facilitate
264
+ this we define two class variables that you can set in your subclass.
265
+
266
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
267
+ Class to create a new graph structure in the `to_directed` method.
268
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
269
+
270
+ to_undirected_class : callable, (default: Graph or MultiGraph)
271
+ Class to create a new graph structure in the `to_undirected` method.
272
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
273
+
274
+ **Subclassing Example**
275
+
276
+ Create a low memory graph class that effectively disallows edge
277
+ attributes by using a single attribute dict for all edges.
278
+ This reduces the memory used, but you lose edge attributes.
279
+
280
+ >>> class ThinGraph(nx.Graph):
281
+ ... all_edge_dict = {"weight": 1}
282
+ ...
283
+ ... def single_edge_dict(self):
284
+ ... return self.all_edge_dict
285
+ ...
286
+ ... edge_attr_dict_factory = single_edge_dict
287
+ >>> G = ThinGraph()
288
+ >>> G.add_edge(2, 1)
289
+ >>> G[2][1]
290
+ {'weight': 1}
291
+ >>> G.add_edge(2, 2)
292
+ >>> G[2][1] is G[2][2]
293
+ True
294
+ """
295
+
296
+ # node_dict_factory = dict # already assigned in Graph
297
+ # adjlist_outer_dict_factory = dict
298
+ # adjlist_inner_dict_factory = dict
299
+ edge_key_dict_factory = dict
300
+ # edge_attr_dict_factory = dict
301
+
302
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
303
+ """Initialize a graph with edges, name, or graph attributes.
304
+
305
+ Parameters
306
+ ----------
307
+ incoming_graph_data : input graph
308
+ Data to initialize graph. If incoming_graph_data=None (default)
309
+ an empty graph is created. The data can be an edge list, or any
310
+ NetworkX graph object. If the corresponding optional Python
311
+ packages are installed the data can also be a 2D NumPy array, a
312
+ SciPy sparse array, or a PyGraphviz graph.
313
+
314
+ multigraph_input : bool or None (default None)
315
+ Note: Only used when `incoming_graph_data` is a dict.
316
+ If True, `incoming_graph_data` is assumed to be a
317
+ dict-of-dict-of-dict-of-dict structure keyed by
318
+ node to neighbor to edge keys to edge data for multi-edges.
319
+ A NetworkXError is raised if this is not the case.
320
+ If False, :func:`to_networkx_graph` is used to try to determine
321
+ the dict's graph data structure as either a dict-of-dict-of-dict
322
+ keyed by node to neighbor to edge data, or a dict-of-iterable
323
+ keyed by node to neighbors.
324
+ If None, the treatment for True is tried, but if it fails,
325
+ the treatment for False is tried.
326
+
327
+ attr : keyword arguments, optional (default= no attributes)
328
+ Attributes to add to graph as key=value pairs.
329
+
330
+ See Also
331
+ --------
332
+ convert
333
+
334
+ Examples
335
+ --------
336
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
337
+ >>> G = nx.Graph(name="my graph")
338
+ >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
339
+ >>> G = nx.Graph(e)
340
+
341
+ Arbitrary graph attribute pairs (key=value) may be assigned
342
+
343
+ >>> G = nx.Graph(e, day="Friday")
344
+ >>> G.graph
345
+ {'day': 'Friday'}
346
+
347
+ """
348
+ # multigraph_input can be None/True/False. So check "is not False"
349
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
350
+ DiGraph.__init__(self)
351
+ try:
352
+ convert.from_dict_of_dicts(
353
+ incoming_graph_data, create_using=self, multigraph_input=True
354
+ )
355
+ self.graph.update(attr)
356
+ except Exception as err:
357
+ if multigraph_input is True:
358
+ raise nx.NetworkXError(
359
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
360
+ )
361
+ DiGraph.__init__(self, incoming_graph_data, **attr)
362
+ else:
363
+ DiGraph.__init__(self, incoming_graph_data, **attr)
364
+
365
+ @cached_property
366
+ def adj(self):
367
+ """Graph adjacency object holding the neighbors of each node.
368
+
369
+ This object is a read-only dict-like structure with node keys
370
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
371
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
372
+ the color of the edge `(3, 2, 0)` to `"blue"`.
373
+
374
+ Iterating over G.adj behaves like a dict. Useful idioms include
375
+ `for nbr, datadict in G.adj[n].items():`.
376
+
377
+ The neighbor information is also provided by subscripting the graph.
378
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
379
+
380
+ For directed graphs, `G.adj` holds outgoing (successor) info.
381
+ """
382
+ return MultiAdjacencyView(self._succ)
383
+
384
+ @cached_property
385
+ def succ(self):
386
+ """Graph adjacency object holding the successors of each node.
387
+
388
+ This object is a read-only dict-like structure with node keys
389
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
390
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
391
+ the color of the edge `(3, 2, 0)` to `"blue"`.
392
+
393
+ Iterating over G.adj behaves like a dict. Useful idioms include
394
+ `for nbr, datadict in G.adj[n].items():`.
395
+
396
+ The neighbor information is also provided by subscripting the graph.
397
+ So `for nbr, foovalue in G[node].data('foo', default=1):` works.
398
+
399
+ For directed graphs, `G.succ` is identical to `G.adj`.
400
+ """
401
+ return MultiAdjacencyView(self._succ)
402
+
403
+ @cached_property
404
+ def pred(self):
405
+ """Graph adjacency object holding the predecessors of each node.
406
+
407
+ This object is a read-only dict-like structure with node keys
408
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
409
+ to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
410
+ the color of the edge `(3, 2, 0)` to `"blue"`.
411
+
412
+ Iterating over G.adj behaves like a dict. Useful idioms include
413
+ `for nbr, datadict in G.adj[n].items():`.
414
+ """
415
+ return MultiAdjacencyView(self._pred)
416
+
417
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
418
+ """Add an edge between u and v.
419
+
420
+ The nodes u and v will be automatically added if they are
421
+ not already in the graph.
422
+
423
+ Edge attributes can be specified with keywords or by directly
424
+ accessing the edge's attribute dictionary. See examples below.
425
+
426
+ Parameters
427
+ ----------
428
+ u_for_edge, v_for_edge : nodes
429
+ Nodes can be, for example, strings or numbers.
430
+ Nodes must be hashable (and not None) Python objects.
431
+ key : hashable identifier, optional (default=lowest unused integer)
432
+ Used to distinguish multiedges between a pair of nodes.
433
+ attr : keyword arguments, optional
434
+ Edge data (or labels or objects) can be assigned using
435
+ keyword arguments.
436
+
437
+ Returns
438
+ -------
439
+ The edge key assigned to the edge.
440
+
441
+ See Also
442
+ --------
443
+ add_edges_from : add a collection of edges
444
+
445
+ Notes
446
+ -----
447
+ To replace/update edge data, use the optional key argument
448
+ to identify a unique edge. Otherwise a new edge will be created.
449
+
450
+ NetworkX algorithms designed for weighted graphs cannot use
451
+ multigraphs directly because it is not clear how to handle
452
+ multiedge weights. Convert to Graph using edge attribute
453
+ 'weight' to enable weighted graph algorithms.
454
+
455
+ Default keys are generated using the method `new_edge_key()`.
456
+ This method can be overridden by subclassing the base class and
457
+ providing a custom `new_edge_key()` method.
458
+
459
+ Examples
460
+ --------
461
+ The following all add the edge e=(1, 2) to graph G:
462
+
463
+ >>> G = nx.MultiDiGraph()
464
+ >>> e = (1, 2)
465
+ >>> key = G.add_edge(1, 2) # explicit two-node form
466
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
467
+ 1
468
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
469
+ [2]
470
+
471
+ Associate data to edges using keywords:
472
+
473
+ >>> key = G.add_edge(1, 2, weight=3)
474
+ >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
475
+ >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
476
+
477
+ For non-string attribute keys, use subscript notation.
478
+
479
+ >>> ekey = G.add_edge(1, 2)
480
+ >>> G[1][2][0].update({0: 5})
481
+ >>> G.edges[1, 2, 0].update({0: 5})
482
+ """
483
+ u, v = u_for_edge, v_for_edge
484
+ # add nodes
485
+ if u not in self._succ:
486
+ if u is None:
487
+ raise ValueError("None cannot be a node")
488
+ self._succ[u] = self.adjlist_inner_dict_factory()
489
+ self._pred[u] = self.adjlist_inner_dict_factory()
490
+ self._node[u] = self.node_attr_dict_factory()
491
+ if v not in self._succ:
492
+ if v is None:
493
+ raise ValueError("None cannot be a node")
494
+ self._succ[v] = self.adjlist_inner_dict_factory()
495
+ self._pred[v] = self.adjlist_inner_dict_factory()
496
+ self._node[v] = self.node_attr_dict_factory()
497
+ if key is None:
498
+ key = self.new_edge_key(u, v)
499
+ if v in self._succ[u]:
500
+ keydict = self._adj[u][v]
501
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
502
+ datadict.update(attr)
503
+ keydict[key] = datadict
504
+ else:
505
+ # selfloops work this way without special treatment
506
+ datadict = self.edge_attr_dict_factory()
507
+ datadict.update(attr)
508
+ keydict = self.edge_key_dict_factory()
509
+ keydict[key] = datadict
510
+ self._succ[u][v] = keydict
511
+ self._pred[v][u] = keydict
512
+ nx._clear_cache(self)
513
+ return key
514
+
515
+ def remove_edge(self, u, v, key=None):
516
+ """Remove an edge between u and v.
517
+
518
+ Parameters
519
+ ----------
520
+ u, v : nodes
521
+ Remove an edge between nodes u and v.
522
+ key : hashable identifier, optional (default=None)
523
+ Used to distinguish multiple edges between a pair of nodes.
524
+ If None, remove a single edge between u and v. If there are
525
+ multiple edges, removes the last edge added in terms of
526
+ insertion order.
527
+
528
+ Raises
529
+ ------
530
+ NetworkXError
531
+ If there is not an edge between u and v, or
532
+ if there is no edge with the specified key.
533
+
534
+ See Also
535
+ --------
536
+ remove_edges_from : remove a collection of edges
537
+
538
+ Examples
539
+ --------
540
+ >>> G = nx.MultiDiGraph()
541
+ >>> nx.add_path(G, [0, 1, 2, 3])
542
+ >>> G.remove_edge(0, 1)
543
+ >>> e = (1, 2)
544
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
545
+
546
+ For multiple edges
547
+
548
+ >>> G = nx.MultiDiGraph()
549
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
550
+ [0, 1, 2]
551
+
552
+ When ``key=None`` (the default), edges are removed in the opposite
553
+ order that they were added:
554
+
555
+ >>> G.remove_edge(1, 2)
556
+ >>> G.edges(keys=True)
557
+ OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
558
+
559
+ For edges with keys
560
+
561
+ >>> G = nx.MultiDiGraph()
562
+ >>> G.add_edge(1, 2, key="first")
563
+ 'first'
564
+ >>> G.add_edge(1, 2, key="second")
565
+ 'second'
566
+ >>> G.remove_edge(1, 2, key="first")
567
+ >>> G.edges(keys=True)
568
+ OutMultiEdgeView([(1, 2, 'second')])
569
+
570
+ """
571
+ try:
572
+ d = self._adj[u][v]
573
+ except KeyError as err:
574
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
575
+ # remove the edge with specified data
576
+ if key is None:
577
+ d.popitem()
578
+ else:
579
+ try:
580
+ del d[key]
581
+ except KeyError as err:
582
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
583
+ raise NetworkXError(msg) from err
584
+ if len(d) == 0:
585
+ # remove the key entries if last edge
586
+ del self._succ[u][v]
587
+ del self._pred[v][u]
588
+ nx._clear_cache(self)
589
+
590
+ @cached_property
591
+ def edges(self):
592
+ """An OutMultiEdgeView of the Graph as G.edges or G.edges().
593
+
594
+ edges(self, nbunch=None, data=False, keys=False, default=None)
595
+
596
+ The OutMultiEdgeView provides set-like operations on the edge-tuples
597
+ as well as edge attribute lookup. When called, it also provides
598
+ an EdgeDataView object which allows control of access to edge
599
+ attributes (but does not provide set-like operations).
600
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
601
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
602
+ ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
603
+ iterates through all the edges yielding the color attribute with
604
+ default `'red'` if no color attribute exists.
605
+
606
+ Edges are returned as tuples with optional data and keys
607
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
608
+ provided, the tuples will just be (node, neighbor, data), but
609
+ multiple tuples with the same node and neighbor will be
610
+ generated when multiple edges between two nodes exist.
611
+
612
+ Parameters
613
+ ----------
614
+ nbunch : single node, container, or all nodes (default= all nodes)
615
+ The view will only report edges from these nodes.
616
+ data : string or bool, optional (default=False)
617
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
618
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
619
+ If False, return 2-tuple (u, v).
620
+ keys : bool, optional (default=False)
621
+ If True, return edge keys with each edge, creating (u, v, k,
622
+ d) tuples when data is also requested (the default) and (u,
623
+ v, k) tuples when data is not requested.
624
+ default : value, optional (default=None)
625
+ Value used for edges that don't have the requested attribute.
626
+ Only relevant if data is not True or False.
627
+
628
+ Returns
629
+ -------
630
+ edges : OutMultiEdgeView
631
+ A view of edge attributes, usually it iterates over (u, v)
632
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
633
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
634
+
635
+ Notes
636
+ -----
637
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
638
+ For directed graphs this returns the out-edges.
639
+
640
+ Examples
641
+ --------
642
+ >>> G = nx.MultiDiGraph()
643
+ >>> nx.add_path(G, [0, 1, 2])
644
+ >>> key = G.add_edge(2, 3, weight=5)
645
+ >>> key2 = G.add_edge(1, 2) # second edge between these nodes
646
+ >>> [e for e in G.edges()]
647
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
648
+ >>> list(G.edges(data=True)) # default data is {} (empty dict)
649
+ [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
650
+ >>> list(G.edges(data="weight", default=1))
651
+ [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
652
+ >>> list(G.edges(keys=True)) # default keys are integers
653
+ [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
654
+ >>> list(G.edges(data=True, keys=True))
655
+ [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
656
+ >>> list(G.edges(data="weight", default=1, keys=True))
657
+ [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
658
+ >>> list(G.edges([0, 2]))
659
+ [(0, 1), (2, 3)]
660
+ >>> list(G.edges(0))
661
+ [(0, 1)]
662
+ >>> list(G.edges(1))
663
+ [(1, 2), (1, 2)]
664
+
665
+ See Also
666
+ --------
667
+ in_edges, out_edges
668
+ """
669
+ return OutMultiEdgeView(self)
670
+
671
+ # alias out_edges to edges
672
+ @cached_property
673
+ def out_edges(self):
674
+ return OutMultiEdgeView(self)
675
+
676
+ out_edges.__doc__ = edges.__doc__
677
+
678
+ @cached_property
679
+ def in_edges(self):
680
+ """A view of the in edges of the graph as G.in_edges or G.in_edges().
681
+
682
+ in_edges(self, nbunch=None, data=False, keys=False, default=None)
683
+
684
+ Parameters
685
+ ----------
686
+ nbunch : single node, container, or all nodes (default= all nodes)
687
+ The view will only report edges incident to these nodes.
688
+ data : string or bool, optional (default=False)
689
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
690
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
691
+ If False, return 2-tuple (u, v).
692
+ keys : bool, optional (default=False)
693
+ If True, return edge keys with each edge, creating 3-tuples
694
+ (u, v, k) or with data, 4-tuples (u, v, k, d).
695
+ default : value, optional (default=None)
696
+ Value used for edges that don't have the requested attribute.
697
+ Only relevant if data is not True or False.
698
+
699
+ Returns
700
+ -------
701
+ in_edges : InMultiEdgeView or InMultiEdgeDataView
702
+ A view of edge attributes, usually it iterates over (u, v)
703
+ or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
704
+ used for attribute lookup as `edges[u, v, k]['foo']`.
705
+
706
+ See Also
707
+ --------
708
+ edges
709
+ """
710
+ return InMultiEdgeView(self)
711
+
712
+ @cached_property
713
+ def degree(self):
714
+ """A DegreeView for the Graph as G.degree or G.degree().
715
+
716
+ The node degree is the number of edges adjacent to the node.
717
+ The weighted node degree is the sum of the edge weights for
718
+ edges incident to that node.
719
+
720
+ This object provides an iterator for (node, degree) as well as
721
+ lookup for the degree for a single node.
722
+
723
+ Parameters
724
+ ----------
725
+ nbunch : single node, container, or all nodes (default= all nodes)
726
+ The view will only report edges incident to these nodes.
727
+
728
+ weight : string or None, optional (default=None)
729
+ The name of an edge attribute that holds the numerical value used
730
+ as a weight. If None, then each edge has weight 1.
731
+ The degree is the sum of the edge weights adjacent to the node.
732
+
733
+ Returns
734
+ -------
735
+ DiMultiDegreeView or int
736
+ If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
737
+ mapping nodes to their degree.
738
+ If a single node is requested, returns the degree of the node as an integer.
739
+
740
+ See Also
741
+ --------
742
+ out_degree, in_degree
743
+
744
+ Examples
745
+ --------
746
+ >>> G = nx.MultiDiGraph()
747
+ >>> nx.add_path(G, [0, 1, 2, 3])
748
+ >>> G.degree(0) # node 0 with degree 1
749
+ 1
750
+ >>> list(G.degree([0, 1, 2]))
751
+ [(0, 1), (1, 2), (2, 2)]
752
+ >>> G.add_edge(0, 1) # parallel edge
753
+ 1
754
+ >>> list(G.degree([0, 1, 2])) # parallel edges are counted
755
+ [(0, 2), (1, 3), (2, 2)]
756
+
757
+ """
758
+ return DiMultiDegreeView(self)
759
+
760
+ @cached_property
761
+ def in_degree(self):
762
+ """A DegreeView for (node, in_degree) or in_degree for single node.
763
+
764
+ The node in-degree is the number of edges pointing into the node.
765
+ The weighted node degree is the sum of the edge weights for
766
+ edges incident to that node.
767
+
768
+ This object provides an iterator for (node, degree) as well as
769
+ lookup for the degree for a single node.
770
+
771
+ Parameters
772
+ ----------
773
+ nbunch : single node, container, or all nodes (default= all nodes)
774
+ The view will only report edges incident to these nodes.
775
+
776
+ weight : string or None, optional (default=None)
777
+ The edge attribute that holds the numerical value used
778
+ as a weight. If None, then each edge has weight 1.
779
+ The degree is the sum of the edge weights adjacent to the node.
780
+
781
+ Returns
782
+ -------
783
+ If a single node is requested
784
+ deg : int
785
+ Degree of the node
786
+
787
+ OR if multiple nodes are requested
788
+ nd_iter : iterator
789
+ The iterator returns two-tuples of (node, in-degree).
790
+
791
+ See Also
792
+ --------
793
+ degree, out_degree
794
+
795
+ Examples
796
+ --------
797
+ >>> G = nx.MultiDiGraph()
798
+ >>> nx.add_path(G, [0, 1, 2, 3])
799
+ >>> G.in_degree(0) # node 0 with degree 0
800
+ 0
801
+ >>> list(G.in_degree([0, 1, 2]))
802
+ [(0, 0), (1, 1), (2, 1)]
803
+ >>> G.add_edge(0, 1) # parallel edge
804
+ 1
805
+ >>> list(G.in_degree([0, 1, 2])) # parallel edges counted
806
+ [(0, 0), (1, 2), (2, 1)]
807
+
808
+ """
809
+ return InMultiDegreeView(self)
810
+
811
+ @cached_property
812
+ def out_degree(self):
813
+ """Returns an iterator for (node, out-degree) or out-degree for single node.
814
+
815
+ out_degree(self, nbunch=None, weight=None)
816
+
817
+ The node out-degree is the number of edges pointing out of the node.
818
+ This function returns the out-degree for a single node or an iterator
819
+ for a bunch of nodes or if nothing is passed as argument.
820
+
821
+ Parameters
822
+ ----------
823
+ nbunch : single node, container, or all nodes (default= all nodes)
824
+ The view will only report edges incident to these nodes.
825
+
826
+ weight : string or None, optional (default=None)
827
+ The edge attribute that holds the numerical value used
828
+ as a weight. If None, then each edge has weight 1.
829
+ The degree is the sum of the edge weights.
830
+
831
+ Returns
832
+ -------
833
+ If a single node is requested
834
+ deg : int
835
+ Degree of the node
836
+
837
+ OR if multiple nodes are requested
838
+ nd_iter : iterator
839
+ The iterator returns two-tuples of (node, out-degree).
840
+
841
+ See Also
842
+ --------
843
+ degree, in_degree
844
+
845
+ Examples
846
+ --------
847
+ >>> G = nx.MultiDiGraph()
848
+ >>> nx.add_path(G, [0, 1, 2, 3])
849
+ >>> G.out_degree(0) # node 0 with degree 1
850
+ 1
851
+ >>> list(G.out_degree([0, 1, 2]))
852
+ [(0, 1), (1, 1), (2, 1)]
853
+ >>> G.add_edge(0, 1) # parallel edge
854
+ 1
855
+ >>> list(G.out_degree([0, 1, 2])) # counts parallel edges
856
+ [(0, 2), (1, 1), (2, 1)]
857
+
858
+ """
859
+ return OutMultiDegreeView(self)
860
+
861
+ def is_multigraph(self):
862
+ """Returns True if graph is a multigraph, False otherwise."""
863
+ return True
864
+
865
+ def is_directed(self):
866
+ """Returns True if graph is directed, False otherwise."""
867
+ return True
868
+
869
+ def to_undirected(self, reciprocal=False, as_view=False):
870
+ """Returns an undirected representation of the digraph.
871
+
872
+ Parameters
873
+ ----------
874
+ reciprocal : bool (optional)
875
+ If True only keep edges that appear in both directions
876
+ in the original digraph.
877
+ as_view : bool (optional, default=False)
878
+ If True return an undirected view of the original directed graph.
879
+
880
+ Returns
881
+ -------
882
+ G : MultiGraph
883
+ An undirected graph with the same name and nodes and
884
+ with edge (u, v, data) if either (u, v, data) or (v, u, data)
885
+ is in the digraph. If both edges exist in digraph and
886
+ their edge data is different, only one edge is created
887
+ with an arbitrary choice of which edge data to use.
888
+ You must check and correct for this manually if desired.
889
+
890
+ See Also
891
+ --------
892
+ MultiGraph, copy, add_edge, add_edges_from
893
+
894
+ Notes
895
+ -----
896
+ This returns a "deepcopy" of the edge, node, and
897
+ graph attributes which attempts to completely copy
898
+ all of the data and references.
899
+
900
+ This is in contrast to the similar D=MultiDiGraph(G) which
901
+ returns a shallow copy of the data.
902
+
903
+ See the Python copy module for more information on shallow
904
+ and deep copies, https://docs.python.org/3/library/copy.html.
905
+
906
+ Warning: If you have subclassed MultiDiGraph to use dict-like
907
+ objects in the data structure, those changes do not transfer
908
+ to the MultiGraph created by this method.
909
+
910
+ Examples
911
+ --------
912
+ >>> G = nx.path_graph(2) # or MultiGraph, etc
913
+ >>> H = G.to_directed()
914
+ >>> list(H.edges)
915
+ [(0, 1), (1, 0)]
916
+ >>> G2 = H.to_undirected()
917
+ >>> list(G2.edges)
918
+ [(0, 1)]
919
+ """
920
+ graph_class = self.to_undirected_class()
921
+ if as_view is True:
922
+ return nx.graphviews.generic_graph_view(self, graph_class)
923
+ # deepcopy when not a view
924
+ G = graph_class()
925
+ G.graph.update(deepcopy(self.graph))
926
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
927
+ if reciprocal is True:
928
+ G.add_edges_from(
929
+ (u, v, key, deepcopy(data))
930
+ for u, nbrs in self._adj.items()
931
+ for v, keydict in nbrs.items()
932
+ for key, data in keydict.items()
933
+ if v in self._pred[u] and key in self._pred[u][v]
934
+ )
935
+ else:
936
+ G.add_edges_from(
937
+ (u, v, key, deepcopy(data))
938
+ for u, nbrs in self._adj.items()
939
+ for v, keydict in nbrs.items()
940
+ for key, data in keydict.items()
941
+ )
942
+ return G
943
+
944
+ def reverse(self, copy=True):
945
+ """Returns the reverse of the graph.
946
+
947
+ The reverse is a graph with the same nodes and edges
948
+ but with the directions of the edges reversed.
949
+
950
+ Parameters
951
+ ----------
952
+ copy : bool optional (default=True)
953
+ If True, return a new DiGraph holding the reversed edges.
954
+ If False, the reverse graph is created using a view of
955
+ the original graph.
956
+ """
957
+ if copy:
958
+ H = self.__class__()
959
+ H.graph.update(deepcopy(self.graph))
960
+ H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
961
+ H.add_edges_from(
962
+ (v, u, k, deepcopy(d))
963
+ for u, v, k, d in self.edges(keys=True, data=True)
964
+ )
965
+ return H
966
+ return nx.reverse_view(self)
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/multigraph.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for MultiGraph."""
2
+
3
+ from copy import deepcopy
4
+ from functools import cached_property
5
+
6
+ import networkx as nx
7
+ from networkx import NetworkXError, convert
8
+ from networkx.classes.coreviews import MultiAdjacencyView
9
+ from networkx.classes.graph import Graph
10
+ from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
11
+
12
+ __all__ = ["MultiGraph"]
13
+
14
+
15
+ class MultiGraph(Graph):
16
+ """
17
+ An undirected graph class that can store multiedges.
18
+
19
+ Multiedges are multiple edges between two nodes. Each edge
20
+ can hold optional data or attributes.
21
+
22
+ A MultiGraph holds undirected edges. Self loops are allowed.
23
+
24
+ Nodes can be arbitrary (hashable) Python objects with optional
25
+ key/value attributes. By convention `None` is not used as a node.
26
+
27
+ Edges are represented as links between nodes with optional
28
+ key/value attributes, in a MultiGraph each edge has a key to
29
+ distinguish between multiple edges that have the same source and
30
+ destination nodes.
31
+
32
+ Parameters
33
+ ----------
34
+ incoming_graph_data : input graph (optional, default: None)
35
+ Data to initialize graph. If None (default) an empty
36
+ graph is created. The data can be any format that is supported
37
+ by the to_networkx_graph() function, currently including edge list,
38
+ dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
39
+ SciPy sparse array, or PyGraphviz graph.
40
+
41
+ multigraph_input : bool or None (default None)
42
+ Note: Only used when `incoming_graph_data` is a dict.
43
+ If True, `incoming_graph_data` is assumed to be a
44
+ dict-of-dict-of-dict-of-dict structure keyed by
45
+ node to neighbor to edge keys to edge data for multi-edges.
46
+ A NetworkXError is raised if this is not the case.
47
+ If False, :func:`to_networkx_graph` is used to try to determine
48
+ the dict's graph data structure as either a dict-of-dict-of-dict
49
+ keyed by node to neighbor to edge data, or a dict-of-iterable
50
+ keyed by node to neighbors.
51
+ If None, the treatment for True is tried, but if it fails,
52
+ the treatment for False is tried.
53
+
54
+ attr : keyword arguments, optional (default= no attributes)
55
+ Attributes to add to graph as key=value pairs.
56
+
57
+ See Also
58
+ --------
59
+ Graph
60
+ DiGraph
61
+ MultiDiGraph
62
+
63
+ Examples
64
+ --------
65
+ Create an empty graph structure (a "null graph") with no nodes and
66
+ no edges.
67
+
68
+ >>> G = nx.MultiGraph()
69
+
70
+ G can be grown in several ways.
71
+
72
+ **Nodes:**
73
+
74
+ Add one node at a time:
75
+
76
+ >>> G.add_node(1)
77
+
78
+ Add the nodes from any container (a list, dict, set or
79
+ even the lines from a file or the nodes from another graph).
80
+
81
+ >>> G.add_nodes_from([2, 3])
82
+ >>> G.add_nodes_from(range(100, 110))
83
+ >>> H = nx.path_graph(10)
84
+ >>> G.add_nodes_from(H)
85
+
86
+ In addition to strings and integers any hashable Python object
87
+ (except None) can represent a node, e.g. a customized node object,
88
+ or even another Graph.
89
+
90
+ >>> G.add_node(H)
91
+
92
+ **Edges:**
93
+
94
+ G can also be grown by adding edges.
95
+
96
+ Add one edge,
97
+
98
+ >>> key = G.add_edge(1, 2)
99
+
100
+ a list of edges,
101
+
102
+ >>> keys = G.add_edges_from([(1, 2), (1, 3)])
103
+
104
+ or a collection of edges,
105
+
106
+ >>> keys = G.add_edges_from(H.edges)
107
+
108
+ If some edges connect nodes not yet in the graph, the nodes
109
+ are added automatically. If an edge already exists, an additional
110
+ edge is created and stored using a key to identify the edge.
111
+ By default the key is the lowest unused integer.
112
+
113
+ >>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
114
+ >>> G[4]
115
+ AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
116
+
117
+ **Attributes:**
118
+
119
+ Each graph, node, and edge can hold key/value attribute pairs
120
+ in an associated attribute dictionary (the keys must be hashable).
121
+ By default these are empty, but can be added or changed using
122
+ add_edge, add_node or direct manipulation of the attribute
123
+ dictionaries named graph, node and edge respectively.
124
+
125
+ >>> G = nx.MultiGraph(day="Friday")
126
+ >>> G.graph
127
+ {'day': 'Friday'}
128
+
129
+ Add node attributes using add_node(), add_nodes_from() or G.nodes
130
+
131
+ >>> G.add_node(1, time="5pm")
132
+ >>> G.add_nodes_from([3], time="2pm")
133
+ >>> G.nodes[1]
134
+ {'time': '5pm'}
135
+ >>> G.nodes[1]["room"] = 714
136
+ >>> del G.nodes[1]["room"] # remove attribute
137
+ >>> list(G.nodes(data=True))
138
+ [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
139
+
140
+ Add edge attributes using add_edge(), add_edges_from(), subscript
141
+ notation, or G.edges.
142
+
143
+ >>> key = G.add_edge(1, 2, weight=4.7)
144
+ >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
145
+ >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
146
+ >>> G[1][2][0]["weight"] = 4.7
147
+ >>> G.edges[1, 2, 0]["weight"] = 4
148
+
149
+ Warning: we protect the graph data structure by making `G.edges[1,
150
+ 2, 0]` a read-only dict-like structure. However, you can assign to
151
+ attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
152
+ to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
153
+
154
+ **Shortcuts:**
155
+
156
+ Many common graph features allow python syntax to speed reporting.
157
+
158
+ >>> 1 in G # check if node in graph
159
+ True
160
+ >>> [n for n in G if n < 3] # iterate through nodes
161
+ [1, 2]
162
+ >>> len(G) # number of nodes in graph
163
+ 5
164
+ >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
165
+ AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
166
+
167
+ Often the best way to traverse all edges of a graph is via the neighbors.
168
+ The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
169
+
170
+ >>> for n, nbrsdict in G.adjacency():
171
+ ... for nbr, keydict in nbrsdict.items():
172
+ ... for key, eattr in keydict.items():
173
+ ... if "weight" in eattr:
174
+ ... # Do something useful with the edges
175
+ ... pass
176
+
177
+ But the edges() method is often more convenient:
178
+
179
+ >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
180
+ ... if weight is not None:
181
+ ... # Do something useful with the edges
182
+ ... pass
183
+
184
+ **Reporting:**
185
+
186
+ Simple graph information is obtained using methods and object-attributes.
187
+ Reporting usually provides views instead of containers to reduce memory
188
+ usage. The views update as the graph is updated similarly to dict-views.
189
+ The objects `nodes`, `edges` and `adj` provide access to data attributes
190
+ via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
191
+ (e.g. `nodes.items()`, `nodes.data('color')`,
192
+ `nodes.data('color', default='blue')` and similarly for `edges`)
193
+ Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
194
+
195
+ For details on these and other miscellaneous methods, see below.
196
+
197
+ **Subclasses (Advanced):**
198
+
199
+ The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
200
+ The outer dict (node_dict) holds adjacency information keyed by node.
201
+ The next dict (adjlist_dict) represents the adjacency information
202
+ and holds edge_key dicts keyed by neighbor. The edge_key dict holds
203
+ each edge_attr dict keyed by edge key. The inner dict
204
+ (edge_attr_dict) represents the edge data and holds edge attribute
205
+ values keyed by attribute names.
206
+
207
+ Each of these four dicts in the dict-of-dict-of-dict-of-dict
208
+ structure can be replaced by a user defined dict-like object.
209
+ In general, the dict-like features should be maintained but
210
+ extra features can be added. To replace one of the dicts create
211
+ a new graph class by changing the class(!) variable holding the
212
+ factory for that dict-like structure. The variable names are
213
+ node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
214
+ adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
215
+ and graph_attr_dict_factory.
216
+
217
+ node_dict_factory : function, (default: dict)
218
+ Factory function to be used to create the dict containing node
219
+ attributes, keyed by node id.
220
+ It should require no arguments and return a dict-like object
221
+
222
+ node_attr_dict_factory: function, (default: dict)
223
+ Factory function to be used to create the node attribute
224
+ dict which holds attribute values keyed by attribute name.
225
+ It should require no arguments and return a dict-like object
226
+
227
+ adjlist_outer_dict_factory : function, (default: dict)
228
+ Factory function to be used to create the outer-most dict
229
+ in the data structure that holds adjacency info keyed by node.
230
+ It should require no arguments and return a dict-like object.
231
+
232
+ adjlist_inner_dict_factory : function, (default: dict)
233
+ Factory function to be used to create the adjacency list
234
+ dict which holds multiedge key dicts keyed by neighbor.
235
+ It should require no arguments and return a dict-like object.
236
+
237
+ edge_key_dict_factory : function, (default: dict)
238
+ Factory function to be used to create the edge key dict
239
+ which holds edge data keyed by edge key.
240
+ It should require no arguments and return a dict-like object.
241
+
242
+ edge_attr_dict_factory : function, (default: dict)
243
+ Factory function to be used to create the edge attribute
244
+ dict which holds attribute values keyed by attribute name.
245
+ It should require no arguments and return a dict-like object.
246
+
247
+ graph_attr_dict_factory : function, (default: dict)
248
+ Factory function to be used to create the graph attribute
249
+ dict which holds attribute values keyed by attribute name.
250
+ It should require no arguments and return a dict-like object.
251
+
252
+ Typically, if your extension doesn't impact the data structure all
253
+ methods will inherited without issue except: `to_directed/to_undirected`.
254
+ By default these methods create a DiGraph/Graph class and you probably
255
+ want them to create your extension of a DiGraph/Graph. To facilitate
256
+ this we define two class variables that you can set in your subclass.
257
+
258
+ to_directed_class : callable, (default: DiGraph or MultiDiGraph)
259
+ Class to create a new graph structure in the `to_directed` method.
260
+ If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
261
+
262
+ to_undirected_class : callable, (default: Graph or MultiGraph)
263
+ Class to create a new graph structure in the `to_undirected` method.
264
+ If `None`, a NetworkX class (Graph or MultiGraph) is used.
265
+
266
+ **Subclassing Example**
267
+
268
+ Create a low memory graph class that effectively disallows edge
269
+ attributes by using a single attribute dict for all edges.
270
+ This reduces the memory used, but you lose edge attributes.
271
+
272
+ >>> class ThinGraph(nx.Graph):
273
+ ... all_edge_dict = {"weight": 1}
274
+ ...
275
+ ... def single_edge_dict(self):
276
+ ... return self.all_edge_dict
277
+ ...
278
+ ... edge_attr_dict_factory = single_edge_dict
279
+ >>> G = ThinGraph()
280
+ >>> G.add_edge(2, 1)
281
+ >>> G[2][1]
282
+ {'weight': 1}
283
+ >>> G.add_edge(2, 2)
284
+ >>> G[2][1] is G[2][2]
285
+ True
286
+ """
287
+
288
+ # node_dict_factory = dict # already assigned in Graph
289
+ # adjlist_outer_dict_factory = dict
290
+ # adjlist_inner_dict_factory = dict
291
+ edge_key_dict_factory = dict
292
+ # edge_attr_dict_factory = dict
293
+
294
+ def to_directed_class(self):
295
+ """Returns the class to use for empty directed copies.
296
+
297
+ If you subclass the base classes, use this to designate
298
+ what directed class to use for `to_directed()` copies.
299
+ """
300
+ return nx.MultiDiGraph
301
+
302
+ def to_undirected_class(self):
303
+ """Returns the class to use for empty undirected copies.
304
+
305
+ If you subclass the base classes, use this to designate
306
+ what directed class to use for `to_directed()` copies.
307
+ """
308
+ return MultiGraph
309
+
310
+ def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
311
+ """Initialize a graph with edges, name, or graph attributes.
312
+
313
+ Parameters
314
+ ----------
315
+ incoming_graph_data : input graph
316
+ Data to initialize graph. If incoming_graph_data=None (default)
317
+ an empty graph is created. The data can be an edge list, or any
318
+ NetworkX graph object. If the corresponding optional Python
319
+ packages are installed the data can also be a 2D NumPy array, a
320
+ SciPy sparse array, or a PyGraphviz graph.
321
+
322
+ multigraph_input : bool or None (default None)
323
+ Note: Only used when `incoming_graph_data` is a dict.
324
+ If True, `incoming_graph_data` is assumed to be a
325
+ dict-of-dict-of-dict-of-dict structure keyed by
326
+ node to neighbor to edge keys to edge data for multi-edges.
327
+ A NetworkXError is raised if this is not the case.
328
+ If False, :func:`to_networkx_graph` is used to try to determine
329
+ the dict's graph data structure as either a dict-of-dict-of-dict
330
+ keyed by node to neighbor to edge data, or a dict-of-iterable
331
+ keyed by node to neighbors.
332
+ If None, the treatment for True is tried, but if it fails,
333
+ the treatment for False is tried.
334
+
335
+ attr : keyword arguments, optional (default= no attributes)
336
+ Attributes to add to graph as key=value pairs.
337
+
338
+ See Also
339
+ --------
340
+ convert
341
+
342
+ Examples
343
+ --------
344
+ >>> G = nx.MultiGraph()
345
+ >>> G = nx.MultiGraph(name="my graph")
346
+ >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
347
+ >>> G = nx.MultiGraph(e)
348
+
349
+ Arbitrary graph attribute pairs (key=value) may be assigned
350
+
351
+ >>> G = nx.MultiGraph(e, day="Friday")
352
+ >>> G.graph
353
+ {'day': 'Friday'}
354
+
355
+ """
356
+ # multigraph_input can be None/True/False. So check "is not False"
357
+ if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
358
+ Graph.__init__(self)
359
+ try:
360
+ convert.from_dict_of_dicts(
361
+ incoming_graph_data, create_using=self, multigraph_input=True
362
+ )
363
+ self.graph.update(attr)
364
+ except Exception as err:
365
+ if multigraph_input is True:
366
+ raise nx.NetworkXError(
367
+ f"converting multigraph_input raised:\n{type(err)}: {err}"
368
+ )
369
+ Graph.__init__(self, incoming_graph_data, **attr)
370
+ else:
371
+ Graph.__init__(self, incoming_graph_data, **attr)
372
+
373
+ @cached_property
374
+ def adj(self):
375
+ """Graph adjacency object holding the neighbors of each node.
376
+
377
+ This object is a read-only dict-like structure with node keys
378
+ and neighbor-dict values. The neighbor-dict is keyed by neighbor
379
+ to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
380
+ the color of the edge `(3, 2, 0)` to `"blue"`.
381
+
382
+ Iterating over G.adj behaves like a dict. Useful idioms include
383
+ `for nbr, edgesdict in G.adj[n].items():`.
384
+
385
+ The neighbor information is also provided by subscripting the graph.
386
+
387
+ Examples
388
+ --------
389
+ >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
390
+ >>> G = nx.MultiGraph(e)
391
+ >>> G.edges[1, 2, 0]["weight"] = 3
392
+ >>> result = set()
393
+ >>> for edgekey, data in G[1][2].items():
394
+ ... result.add(data.get("weight", 1))
395
+ >>> result
396
+ {1, 3}
397
+
398
+ For directed graphs, `G.adj` holds outgoing (successor) info.
399
+ """
400
+ return MultiAdjacencyView(self._adj)
401
+
402
+ def new_edge_key(self, u, v):
403
+ """Returns an unused key for edges between nodes `u` and `v`.
404
+
405
+ The nodes `u` and `v` do not need to be already in the graph.
406
+
407
+ Notes
408
+ -----
409
+ In the standard MultiGraph class the new key is the number of existing
410
+ edges between `u` and `v` (increased if necessary to ensure unused).
411
+ The first edge will have key 0, then 1, etc. If an edge is removed
412
+ further new_edge_keys may not be in this order.
413
+
414
+ Parameters
415
+ ----------
416
+ u, v : nodes
417
+
418
+ Returns
419
+ -------
420
+ key : int
421
+ """
422
+ try:
423
+ keydict = self._adj[u][v]
424
+ except KeyError:
425
+ return 0
426
+ key = len(keydict)
427
+ while key in keydict:
428
+ key += 1
429
+ return key
430
+
431
+ def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
432
+ """Add an edge between u and v.
433
+
434
+ The nodes u and v will be automatically added if they are
435
+ not already in the graph.
436
+
437
+ Edge attributes can be specified with keywords or by directly
438
+ accessing the edge's attribute dictionary. See examples below.
439
+
440
+ Parameters
441
+ ----------
442
+ u_for_edge, v_for_edge : nodes
443
+ Nodes can be, for example, strings or numbers.
444
+ Nodes must be hashable (and not None) Python objects.
445
+ key : hashable identifier, optional (default=lowest unused integer)
446
+ Used to distinguish multiedges between a pair of nodes.
447
+ attr : keyword arguments, optional
448
+ Edge data (or labels or objects) can be assigned using
449
+ keyword arguments.
450
+
451
+ Returns
452
+ -------
453
+ The edge key assigned to the edge.
454
+
455
+ See Also
456
+ --------
457
+ add_edges_from : add a collection of edges
458
+
459
+ Notes
460
+ -----
461
+ To replace/update edge data, use the optional key argument
462
+ to identify a unique edge. Otherwise a new edge will be created.
463
+
464
+ NetworkX algorithms designed for weighted graphs cannot use
465
+ multigraphs directly because it is not clear how to handle
466
+ multiedge weights. Convert to Graph using edge attribute
467
+ 'weight' to enable weighted graph algorithms.
468
+
469
+ Default keys are generated using the method `new_edge_key()`.
470
+ This method can be overridden by subclassing the base class and
471
+ providing a custom `new_edge_key()` method.
472
+
473
+ Examples
474
+ --------
475
+ The following each add an additional edge e=(1, 2) to graph G:
476
+
477
+ >>> G = nx.MultiGraph()
478
+ >>> e = (1, 2)
479
+ >>> ekey = G.add_edge(1, 2) # explicit two-node form
480
+ >>> G.add_edge(*e) # single edge as tuple of two nodes
481
+ 1
482
+ >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
483
+ [2]
484
+
485
+ Associate data to edges using keywords:
486
+
487
+ >>> ekey = G.add_edge(1, 2, weight=3)
488
+ >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
489
+ >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
490
+
491
+ For non-string attribute keys, use subscript notation.
492
+
493
+ >>> ekey = G.add_edge(1, 2)
494
+ >>> G[1][2][0].update({0: 5})
495
+ >>> G.edges[1, 2, 0].update({0: 5})
496
+ """
497
+ u, v = u_for_edge, v_for_edge
498
+ # add nodes
499
+ if u not in self._adj:
500
+ if u is None:
501
+ raise ValueError("None cannot be a node")
502
+ self._adj[u] = self.adjlist_inner_dict_factory()
503
+ self._node[u] = self.node_attr_dict_factory()
504
+ if v not in self._adj:
505
+ if v is None:
506
+ raise ValueError("None cannot be a node")
507
+ self._adj[v] = self.adjlist_inner_dict_factory()
508
+ self._node[v] = self.node_attr_dict_factory()
509
+ if key is None:
510
+ key = self.new_edge_key(u, v)
511
+ if v in self._adj[u]:
512
+ keydict = self._adj[u][v]
513
+ datadict = keydict.get(key, self.edge_attr_dict_factory())
514
+ datadict.update(attr)
515
+ keydict[key] = datadict
516
+ else:
517
+ # selfloops work this way without special treatment
518
+ datadict = self.edge_attr_dict_factory()
519
+ datadict.update(attr)
520
+ keydict = self.edge_key_dict_factory()
521
+ keydict[key] = datadict
522
+ self._adj[u][v] = keydict
523
+ self._adj[v][u] = keydict
524
+ nx._clear_cache(self)
525
+ return key
526
+
527
+ def add_edges_from(self, ebunch_to_add, **attr):
528
+ """Add all the edges in ebunch_to_add.
529
+
530
+ Parameters
531
+ ----------
532
+ ebunch_to_add : container of edges
533
+ Each edge given in the container will be added to the
534
+ graph. The edges can be:
535
+
536
+ - 2-tuples (u, v) or
537
+ - 3-tuples (u, v, d) for an edge data dict d, or
538
+ - 3-tuples (u, v, k) for not iterable key k, or
539
+ - 4-tuples (u, v, k, d) for an edge with data and key k
540
+
541
+ attr : keyword arguments, optional
542
+ Edge data (or labels or objects) can be assigned using
543
+ keyword arguments.
544
+
545
+ Returns
546
+ -------
547
+ A list of edge keys assigned to the edges in `ebunch`.
548
+
549
+ See Also
550
+ --------
551
+ add_edge : add a single edge
552
+ add_weighted_edges_from : convenient way to add weighted edges
553
+
554
+ Notes
555
+ -----
556
+ Adding the same edge twice has no effect but any edge data
557
+ will be updated when each duplicate edge is added.
558
+
559
+ Edge attributes specified in an ebunch take precedence over
560
+ attributes specified via keyword arguments.
561
+
562
+ Default keys are generated using the method ``new_edge_key()``.
563
+ This method can be overridden by subclassing the base class and
564
+ providing a custom ``new_edge_key()`` method.
565
+
566
+ When adding edges from an iterator over the graph you are changing,
567
+ a `RuntimeError` can be raised with message:
568
+ `RuntimeError: dictionary changed size during iteration`. This
569
+ happens when the graph's underlying dictionary is modified during
570
+ iteration. To avoid this error, evaluate the iterator into a separate
571
+ object, e.g. by using `list(iterator_of_edges)`, and pass this
572
+ object to `G.add_edges_from`.
573
+
574
+ Examples
575
+ --------
576
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
577
+ >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
578
+ >>> e = zip(range(0, 3), range(1, 4))
579
+ >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
580
+
581
+ Associate data to edges
582
+
583
+ >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
584
+ >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
585
+
586
+ Evaluate an iterator over a graph if using it to modify the same graph
587
+
588
+ >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
589
+ >>> # Grow graph by one new node, adding edges to all existing nodes.
590
+ >>> # wrong way - will raise RuntimeError
591
+ >>> # G.add_edges_from(((5, n) for n in G.nodes))
592
+ >>> # right way - note that there will be no self-edge for node 5
593
+ >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
594
+ """
595
+ keylist = []
596
+ for e in ebunch_to_add:
597
+ ne = len(e)
598
+ if ne == 4:
599
+ u, v, key, dd = e
600
+ elif ne == 3:
601
+ u, v, dd = e
602
+ key = None
603
+ elif ne == 2:
604
+ u, v = e
605
+ dd = {}
606
+ key = None
607
+ else:
608
+ msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
609
+ raise NetworkXError(msg)
610
+ ddd = {}
611
+ ddd.update(attr)
612
+ try:
613
+ ddd.update(dd)
614
+ except (TypeError, ValueError):
615
+ if ne != 3:
616
+ raise
617
+ key = dd # ne == 3 with 3rd value not dict, must be a key
618
+ key = self.add_edge(u, v, key)
619
+ self[u][v][key].update(ddd)
620
+ keylist.append(key)
621
+ nx._clear_cache(self)
622
+ return keylist
623
+
624
+ def remove_edge(self, u, v, key=None):
625
+ """Remove an edge between u and v.
626
+
627
+ Parameters
628
+ ----------
629
+ u, v : nodes
630
+ Remove an edge between nodes u and v.
631
+ key : hashable identifier, optional (default=None)
632
+ Used to distinguish multiple edges between a pair of nodes.
633
+ If None, remove a single edge between u and v. If there are
634
+ multiple edges, removes the last edge added in terms of
635
+ insertion order.
636
+
637
+ Raises
638
+ ------
639
+ NetworkXError
640
+ If there is not an edge between u and v, or
641
+ if there is no edge with the specified key.
642
+
643
+ See Also
644
+ --------
645
+ remove_edges_from : remove a collection of edges
646
+
647
+ Examples
648
+ --------
649
+ >>> G = nx.MultiGraph()
650
+ >>> nx.add_path(G, [0, 1, 2, 3])
651
+ >>> G.remove_edge(0, 1)
652
+ >>> e = (1, 2)
653
+ >>> G.remove_edge(*e) # unpacks e from an edge tuple
654
+
655
+ For multiple edges
656
+
657
+ >>> G = nx.MultiGraph() # or MultiDiGraph, etc
658
+ >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
659
+ [0, 1, 2]
660
+
661
+ When ``key=None`` (the default), edges are removed in the opposite
662
+ order that they were added:
663
+
664
+ >>> G.remove_edge(1, 2)
665
+ >>> G.edges(keys=True)
666
+ MultiEdgeView([(1, 2, 0), (1, 2, 1)])
667
+ >>> G.remove_edge(2, 1) # edges are not directed
668
+ >>> G.edges(keys=True)
669
+ MultiEdgeView([(1, 2, 0)])
670
+
671
+ For edges with keys
672
+
673
+ >>> G = nx.MultiGraph()
674
+ >>> G.add_edge(1, 2, key="first")
675
+ 'first'
676
+ >>> G.add_edge(1, 2, key="second")
677
+ 'second'
678
+ >>> G.remove_edge(1, 2, key="first")
679
+ >>> G.edges(keys=True)
680
+ MultiEdgeView([(1, 2, 'second')])
681
+
682
+ """
683
+ try:
684
+ d = self._adj[u][v]
685
+ except KeyError as err:
686
+ raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
687
+ # remove the edge with specified data
688
+ if key is None:
689
+ d.popitem()
690
+ else:
691
+ try:
692
+ del d[key]
693
+ except KeyError as err:
694
+ msg = f"The edge {u}-{v} with key {key} is not in the graph."
695
+ raise NetworkXError(msg) from err
696
+ if len(d) == 0:
697
+ # remove the key entries if last edge
698
+ del self._adj[u][v]
699
+ if u != v: # check for selfloop
700
+ del self._adj[v][u]
701
+ nx._clear_cache(self)
702
+
703
+ def remove_edges_from(self, ebunch):
704
+ """Remove all edges specified in ebunch.
705
+
706
+ Parameters
707
+ ----------
708
+ ebunch: list or container of edge tuples
709
+ Each edge given in the list or container will be removed
710
+ from the graph. The edges can be:
711
+
712
+ - 2-tuples (u, v) A single edge between u and v is removed.
713
+ - 3-tuples (u, v, key) The edge identified by key is removed.
714
+ - 4-tuples (u, v, key, data) where data is ignored.
715
+
716
+ See Also
717
+ --------
718
+ remove_edge : remove a single edge
719
+
720
+ Notes
721
+ -----
722
+ Will fail silently if an edge in ebunch is not in the graph.
723
+
724
+ Examples
725
+ --------
726
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
727
+ >>> ebunch = [(1, 2), (2, 3)]
728
+ >>> G.remove_edges_from(ebunch)
729
+
730
+ Removing multiple copies of edges
731
+
732
+ >>> G = nx.MultiGraph()
733
+ >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
734
+ >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
735
+ >>> list(G.edges())
736
+ [(1, 2)]
737
+ >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
738
+ >>> list(G.edges) # now empty graph
739
+ []
740
+
741
+ When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
742
+ u and v in the graph, the most recent edge (in terms of insertion
743
+ order) is removed.
744
+
745
+ >>> G = nx.MultiGraph()
746
+ >>> for key in ("x", "y", "a"):
747
+ ... k = G.add_edge(0, 1, key=key)
748
+ >>> G.edges(keys=True)
749
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
750
+ >>> G.remove_edges_from([(0, 1)])
751
+ >>> G.edges(keys=True)
752
+ MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
753
+
754
+ """
755
+ for e in ebunch:
756
+ try:
757
+ self.remove_edge(*e[:3])
758
+ except NetworkXError:
759
+ pass
760
+ nx._clear_cache(self)
761
+
762
+ def has_edge(self, u, v, key=None):
763
+ """Returns True if the graph has an edge between nodes u and v.
764
+
765
+ This is the same as `v in G[u] or key in G[u][v]`
766
+ without KeyError exceptions.
767
+
768
+ Parameters
769
+ ----------
770
+ u, v : nodes
771
+ Nodes can be, for example, strings or numbers.
772
+
773
+ key : hashable identifier, optional (default=None)
774
+ If specified return True only if the edge with
775
+ key is found.
776
+
777
+ Returns
778
+ -------
779
+ edge_ind : bool
780
+ True if edge is in the graph, False otherwise.
781
+
782
+ Examples
783
+ --------
784
+ Can be called either using two nodes u, v, an edge tuple (u, v),
785
+ or an edge tuple (u, v, key).
786
+
787
+ >>> G = nx.MultiGraph() # or MultiDiGraph
788
+ >>> nx.add_path(G, [0, 1, 2, 3])
789
+ >>> G.has_edge(0, 1) # using two nodes
790
+ True
791
+ >>> e = (0, 1)
792
+ >>> G.has_edge(*e) # e is a 2-tuple (u, v)
793
+ True
794
+ >>> G.add_edge(0, 1, key="a")
795
+ 'a'
796
+ >>> G.has_edge(0, 1, key="a") # specify key
797
+ True
798
+ >>> G.has_edge(1, 0, key="a") # edges aren't directed
799
+ True
800
+ >>> e = (0, 1, "a")
801
+ >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
802
+ True
803
+
804
+ The following syntax are equivalent:
805
+
806
+ >>> G.has_edge(0, 1)
807
+ True
808
+ >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
809
+ True
810
+ >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
811
+ True
812
+
813
+ """
814
+ try:
815
+ if key is None:
816
+ return v in self._adj[u]
817
+ else:
818
+ return key in self._adj[u][v]
819
+ except KeyError:
820
+ return False
821
+
822
+ @cached_property
823
+ def edges(self):
824
+ """Returns an iterator over the edges.
825
+
826
+ edges(self, nbunch=None, data=False, keys=False, default=None)
827
+
828
+ The MultiEdgeView provides set-like operations on the edge-tuples
829
+ as well as edge attribute lookup. When called, it also provides
830
+ an EdgeDataView object which allows control of access to edge
831
+ attributes (but does not provide set-like operations).
832
+ Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
833
+ attribute for the edge from ``u`` to ``v`` with key ``k`` while
834
+ ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
835
+ iterates through all the edges yielding the color attribute with
836
+ default `'red'` if no color attribute exists.
837
+
838
+ Edges are returned as tuples with optional data and keys
839
+ in the order (node, neighbor, key, data). If ``keys=True`` is not
840
+ provided, the tuples will just be (node, neighbor, data), but
841
+ multiple tuples with the same node and neighbor will be generated
842
+ when multiple edges exist between two nodes.
843
+
844
+ Parameters
845
+ ----------
846
+ nbunch : single node, container, or all nodes (default= all nodes)
847
+ The view will only report edges from these nodes.
848
+ data : string or bool, optional (default=False)
849
+ The edge attribute returned in 3-tuple (u, v, ddict[data]).
850
+ If True, return edge attribute dict in 3-tuple (u, v, ddict).
851
+ If False, return 2-tuple (u, v).
852
+ keys : bool, optional (default=False)
853
+ If True, return edge keys with each edge, creating (u, v, k)
854
+ tuples or (u, v, k, d) tuples if data is also requested.
855
+ default : value, optional (default=None)
856
+ Value used for edges that don't have the requested attribute.
857
+ Only relevant if data is not True or False.
858
+
859
+ Returns
860
+ -------
861
+ edges : MultiEdgeView
862
+ A view of edge attributes, usually it iterates over (u, v)
863
+ (u, v, k) or (u, v, k, d) tuples of edges, but can also be
864
+ used for attribute lookup as ``edges[u, v, k]['foo']``.
865
+
866
+ Notes
867
+ -----
868
+ Nodes in nbunch that are not in the graph will be (quietly) ignored.
869
+ For directed graphs this returns the out-edges.
870
+
871
+ Examples
872
+ --------
873
+ >>> G = nx.MultiGraph()
874
+ >>> nx.add_path(G, [0, 1, 2])
875
+ >>> key = G.add_edge(2, 3, weight=5)
876
+ >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
877
+ >>> [e for e in G.edges()]
878
+ [(0, 1), (1, 2), (1, 2), (2, 3)]
879
+ >>> G.edges.data() # default data is {} (empty dict)
880
+ MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
881
+ >>> G.edges.data("weight", default=1)
882
+ MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
883
+ >>> G.edges(keys=True) # default keys are integers
884
+ MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
885
+ >>> G.edges.data(keys=True)
886
+ MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
887
+ >>> G.edges.data("weight", default=1, keys=True)
888
+ MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
889
+ >>> G.edges([0, 3]) # Note ordering of tuples from listed sources
890
+ MultiEdgeDataView([(0, 1), (3, 2)])
891
+ >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
892
+ MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
893
+ >>> G.edges(0)
894
+ MultiEdgeDataView([(0, 1)])
895
+ """
896
+ return MultiEdgeView(self)
897
+
898
+ def get_edge_data(self, u, v, key=None, default=None):
899
+ """Returns the attribute dictionary associated with edge (u, v,
900
+ key).
901
+
902
+ If a key is not provided, returns a dictionary mapping edge keys
903
+ to attribute dictionaries for each edge between u and v.
904
+
905
+ This is identical to `G[u][v][key]` except the default is returned
906
+ instead of an exception is the edge doesn't exist.
907
+
908
+ Parameters
909
+ ----------
910
+ u, v : nodes
911
+
912
+ default : any Python object (default=None)
913
+ Value to return if the specific edge (u, v, key) is not
914
+ found, OR if there are no edges between u and v and no key
915
+ is specified.
916
+
917
+ key : hashable identifier, optional (default=None)
918
+ Return data only for the edge with specified key, as an
919
+ attribute dictionary (rather than a dictionary mapping keys
920
+ to attribute dictionaries).
921
+
922
+ Returns
923
+ -------
924
+ edge_dict : dictionary
925
+ The edge attribute dictionary, OR a dictionary mapping edge
926
+ keys to attribute dictionaries for each of those edges if no
927
+ specific key is provided (even if there's only one edge
928
+ between u and v).
929
+
930
+ Examples
931
+ --------
932
+ >>> G = nx.MultiGraph() # or MultiDiGraph
933
+ >>> key = G.add_edge(0, 1, key="a", weight=7)
934
+ >>> G[0][1]["a"] # key='a'
935
+ {'weight': 7}
936
+ >>> G.edges[0, 1, "a"] # key='a'
937
+ {'weight': 7}
938
+
939
+ Warning: we protect the graph data structure by making
940
+ `G.edges` and `G[1][2]` read-only dict-like structures.
941
+ However, you can assign values to attributes in e.g.
942
+ `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
943
+ bracket as shown next. You need to specify all edge info
944
+ to assign to the edge data associated with an edge.
945
+
946
+ >>> G[0][1]["a"]["weight"] = 10
947
+ >>> G.edges[0, 1, "a"]["weight"] = 10
948
+ >>> G[0][1]["a"]["weight"]
949
+ 10
950
+ >>> G.edges[1, 0, "a"]["weight"]
951
+ 10
952
+
953
+ >>> G = nx.MultiGraph() # or MultiDiGraph
954
+ >>> nx.add_path(G, [0, 1, 2, 3])
955
+ >>> G.edges[0, 1, 0]["weight"] = 5
956
+ >>> G.get_edge_data(0, 1)
957
+ {0: {'weight': 5}}
958
+ >>> e = (0, 1)
959
+ >>> G.get_edge_data(*e) # tuple form
960
+ {0: {'weight': 5}}
961
+ >>> G.get_edge_data(3, 0) # edge not in graph, returns None
962
+ >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
963
+ 0
964
+ >>> G.get_edge_data(1, 0, 0) # specific key gives back
965
+ {'weight': 5}
966
+ """
967
+ try:
968
+ if key is None:
969
+ return self._adj[u][v]
970
+ else:
971
+ return self._adj[u][v][key]
972
+ except KeyError:
973
+ return default
974
+
975
+ @cached_property
976
+ def degree(self):
977
+ """A DegreeView for the Graph as G.degree or G.degree().
978
+
979
+ The node degree is the number of edges adjacent to the node.
980
+ The weighted node degree is the sum of the edge weights for
981
+ edges incident to that node.
982
+
983
+ This object provides an iterator for (node, degree) as well as
984
+ lookup for the degree for a single node.
985
+
986
+ Parameters
987
+ ----------
988
+ nbunch : single node, container, or all nodes (default= all nodes)
989
+ The view will only report edges incident to these nodes.
990
+
991
+ weight : string or None, optional (default=None)
992
+ The name of an edge attribute that holds the numerical value used
993
+ as a weight. If None, then each edge has weight 1.
994
+ The degree is the sum of the edge weights adjacent to the node.
995
+
996
+ Returns
997
+ -------
998
+ MultiDegreeView or int
999
+ If multiple nodes are requested (the default), returns a `MultiDegreeView`
1000
+ mapping nodes to their degree.
1001
+ If a single node is requested, returns the degree of the node as an integer.
1002
+
1003
+ Examples
1004
+ --------
1005
+ >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
1006
+ >>> nx.add_path(G, [0, 1, 2, 3])
1007
+ >>> G.degree(0) # node 0 with degree 1
1008
+ 1
1009
+ >>> list(G.degree([0, 1]))
1010
+ [(0, 1), (1, 2)]
1011
+
1012
+ """
1013
+ return MultiDegreeView(self)
1014
+
1015
+ def is_multigraph(self):
1016
+ """Returns True if graph is a multigraph, False otherwise."""
1017
+ return True
1018
+
1019
+ def is_directed(self):
1020
+ """Returns True if graph is directed, False otherwise."""
1021
+ return False
1022
+
1023
+ def copy(self, as_view=False):
1024
+ """Returns a copy of the graph.
1025
+
1026
+ The copy method by default returns an independent shallow copy
1027
+ of the graph and attributes. That is, if an attribute is a
1028
+ container, that container is shared by the original an the copy.
1029
+ Use Python's `copy.deepcopy` for new containers.
1030
+
1031
+ If `as_view` is True then a view is returned instead of a copy.
1032
+
1033
+ Notes
1034
+ -----
1035
+ All copies reproduce the graph structure, but data attributes
1036
+ may be handled in different ways. There are four types of copies
1037
+ of a graph that people might want.
1038
+
1039
+ Deepcopy -- A "deepcopy" copies the graph structure as well as
1040
+ all data attributes and any objects they might contain.
1041
+ The entire graph object is new so that changes in the copy
1042
+ do not affect the original object. (see Python's copy.deepcopy)
1043
+
1044
+ Data Reference (Shallow) -- For a shallow copy the graph structure
1045
+ is copied but the edge, node and graph attribute dicts are
1046
+ references to those in the original graph. This saves
1047
+ time and memory but could cause confusion if you change an attribute
1048
+ in one graph and it changes the attribute in the other.
1049
+ NetworkX does not provide this level of shallow copy.
1050
+
1051
+ Independent Shallow -- This copy creates new independent attribute
1052
+ dicts and then does a shallow copy of the attributes. That is, any
1053
+ attributes that are containers are shared between the new graph
1054
+ and the original. This is exactly what `dict.copy()` provides.
1055
+ You can obtain this style copy using:
1056
+
1057
+ >>> G = nx.path_graph(5)
1058
+ >>> H = G.copy()
1059
+ >>> H = G.copy(as_view=False)
1060
+ >>> H = nx.Graph(G)
1061
+ >>> H = G.__class__(G)
1062
+
1063
+ Fresh Data -- For fresh data, the graph structure is copied while
1064
+ new empty data attribute dicts are created. The resulting graph
1065
+ is independent of the original and it has no edge, node or graph
1066
+ attributes. Fresh copies are not enabled. Instead use:
1067
+
1068
+ >>> H = G.__class__()
1069
+ >>> H.add_nodes_from(G)
1070
+ >>> H.add_edges_from(G.edges)
1071
+
1072
+ View -- Inspired by dict-views, graph-views act like read-only
1073
+ versions of the original graph, providing a copy of the original
1074
+ structure without requiring any memory for copying the information.
1075
+
1076
+ See the Python copy module for more information on shallow
1077
+ and deep copies, https://docs.python.org/3/library/copy.html.
1078
+
1079
+ Parameters
1080
+ ----------
1081
+ as_view : bool, optional (default=False)
1082
+ If True, the returned graph-view provides a read-only view
1083
+ of the original graph without actually copying any data.
1084
+
1085
+ Returns
1086
+ -------
1087
+ G : Graph
1088
+ A copy of the graph.
1089
+
1090
+ See Also
1091
+ --------
1092
+ to_directed: return a directed copy of the graph.
1093
+
1094
+ Examples
1095
+ --------
1096
+ >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
1097
+ >>> H = G.copy()
1098
+
1099
+ """
1100
+ if as_view is True:
1101
+ return nx.graphviews.generic_graph_view(self)
1102
+ G = self.__class__()
1103
+ G.graph.update(self.graph)
1104
+ G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
1105
+ G.add_edges_from(
1106
+ (u, v, key, datadict.copy())
1107
+ for u, nbrs in self._adj.items()
1108
+ for v, keydict in nbrs.items()
1109
+ for key, datadict in keydict.items()
1110
+ )
1111
+ return G
1112
+
1113
+ def to_directed(self, as_view=False):
1114
+ """Returns a directed representation of the graph.
1115
+
1116
+ Returns
1117
+ -------
1118
+ G : MultiDiGraph
1119
+ A directed graph with the same name, same nodes, and with
1120
+ each edge (u, v, k, data) replaced by two directed edges
1121
+ (u, v, k, data) and (v, u, k, data).
1122
+
1123
+ Notes
1124
+ -----
1125
+ This returns a "deepcopy" of the edge, node, and
1126
+ graph attributes which attempts to completely copy
1127
+ all of the data and references.
1128
+
1129
+ This is in contrast to the similar D=MultiDiGraph(G) which
1130
+ returns a shallow copy of the data.
1131
+
1132
+ See the Python copy module for more information on shallow
1133
+ and deep copies, https://docs.python.org/3/library/copy.html.
1134
+
1135
+ Warning: If you have subclassed MultiGraph to use dict-like objects
1136
+ in the data structure, those changes do not transfer to the
1137
+ MultiDiGraph created by this method.
1138
+
1139
+ Examples
1140
+ --------
1141
+ >>> G = nx.MultiGraph()
1142
+ >>> G.add_edge(0, 1)
1143
+ 0
1144
+ >>> G.add_edge(0, 1)
1145
+ 1
1146
+ >>> H = G.to_directed()
1147
+ >>> list(H.edges)
1148
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
1149
+
1150
+ If already directed, return a (deep) copy
1151
+
1152
+ >>> G = nx.MultiDiGraph()
1153
+ >>> G.add_edge(0, 1)
1154
+ 0
1155
+ >>> H = G.to_directed()
1156
+ >>> list(H.edges)
1157
+ [(0, 1, 0)]
1158
+ """
1159
+ graph_class = self.to_directed_class()
1160
+ if as_view is True:
1161
+ return nx.graphviews.generic_graph_view(self, graph_class)
1162
+ # deepcopy when not a view
1163
+ G = graph_class()
1164
+ G.graph.update(deepcopy(self.graph))
1165
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1166
+ G.add_edges_from(
1167
+ (u, v, key, deepcopy(datadict))
1168
+ for u, nbrs in self.adj.items()
1169
+ for v, keydict in nbrs.items()
1170
+ for key, datadict in keydict.items()
1171
+ )
1172
+ return G
1173
+
1174
+ def to_undirected(self, as_view=False):
1175
+ """Returns an undirected copy of the graph.
1176
+
1177
+ Returns
1178
+ -------
1179
+ G : Graph/MultiGraph
1180
+ A deepcopy of the graph.
1181
+
1182
+ See Also
1183
+ --------
1184
+ copy, add_edge, add_edges_from
1185
+
1186
+ Notes
1187
+ -----
1188
+ This returns a "deepcopy" of the edge, node, and
1189
+ graph attributes which attempts to completely copy
1190
+ all of the data and references.
1191
+
1192
+ This is in contrast to the similar `G = nx.MultiGraph(D)`
1193
+ which returns a shallow copy of the data.
1194
+
1195
+ See the Python copy module for more information on shallow
1196
+ and deep copies, https://docs.python.org/3/library/copy.html.
1197
+
1198
+ Warning: If you have subclassed MultiGraph to use dict-like
1199
+ objects in the data structure, those changes do not transfer
1200
+ to the MultiGraph created by this method.
1201
+
1202
+ Examples
1203
+ --------
1204
+ >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
1205
+ >>> H = G.to_directed()
1206
+ >>> list(H.edges)
1207
+ [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
1208
+ >>> G2 = H.to_undirected()
1209
+ >>> list(G2.edges)
1210
+ [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
1211
+ """
1212
+ graph_class = self.to_undirected_class()
1213
+ if as_view is True:
1214
+ return nx.graphviews.generic_graph_view(self, graph_class)
1215
+ # deepcopy when not a view
1216
+ G = graph_class()
1217
+ G.graph.update(deepcopy(self.graph))
1218
+ G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
1219
+ G.add_edges_from(
1220
+ (u, v, key, deepcopy(datadict))
1221
+ for u, nbrs in self._adj.items()
1222
+ for v, keydict in nbrs.items()
1223
+ for key, datadict in keydict.items()
1224
+ )
1225
+ return G
1226
+
1227
+ def number_of_edges(self, u=None, v=None):
1228
+ """Returns the number of edges between two nodes.
1229
+
1230
+ Parameters
1231
+ ----------
1232
+ u, v : nodes, optional (Default=all edges)
1233
+ If u and v are specified, return the number of edges between
1234
+ u and v. Otherwise return the total number of all edges.
1235
+
1236
+ Returns
1237
+ -------
1238
+ nedges : int
1239
+ The number of edges in the graph. If nodes `u` and `v` are
1240
+ specified return the number of edges between those nodes. If
1241
+ the graph is directed, this only returns the number of edges
1242
+ from `u` to `v`.
1243
+
1244
+ See Also
1245
+ --------
1246
+ size
1247
+
1248
+ Examples
1249
+ --------
1250
+ For undirected multigraphs, this method counts the total number
1251
+ of edges in the graph::
1252
+
1253
+ >>> G = nx.MultiGraph()
1254
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
1255
+ [0, 1, 0]
1256
+ >>> G.number_of_edges()
1257
+ 3
1258
+
1259
+ If you specify two nodes, this counts the total number of edges
1260
+ joining the two nodes::
1261
+
1262
+ >>> G.number_of_edges(0, 1)
1263
+ 2
1264
+
1265
+ For directed multigraphs, this method can count the total number
1266
+ of directed edges from `u` to `v`::
1267
+
1268
+ >>> G = nx.MultiDiGraph()
1269
+ >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
1270
+ [0, 1, 0]
1271
+ >>> G.number_of_edges(0, 1)
1272
+ 2
1273
+ >>> G.number_of_edges(1, 0)
1274
+ 1
1275
+
1276
+ """
1277
+ if u is None:
1278
+ return self.size()
1279
+ try:
1280
+ edgedata = self._adj[u][v]
1281
+ except KeyError:
1282
+ return 0 # no such edge
1283
+ return len(edgedata)
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/reportviews.py ADDED
@@ -0,0 +1,1447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ View Classes provide node, edge and degree "views" of a graph.
3
+
4
+ Views for nodes, edges and degree are provided for all base graph classes.
5
+ A view means a read-only object that is quick to create, automatically
6
+ updated when the graph changes, and provides basic access like `n in V`,
7
+ `for n in V`, `V[n]` and sometimes set operations.
8
+
9
+ The views are read-only iterable containers that are updated as the
10
+ graph is updated. As with dicts, the graph should not be updated
11
+ while iterating through the view. Views can be iterated multiple times.
12
+
13
+ Edge and Node views also allow data attribute lookup.
14
+ The resulting attribute dict is writable as `G.edges[3, 4]['color']='red'`
15
+ Degree views allow lookup of degree values for single nodes.
16
+ Weighted degree is supported with the `weight` argument.
17
+
18
+ NodeView
19
+ ========
20
+
21
+ `V = G.nodes` (or `V = G.nodes()`) allows `len(V)`, `n in V`, set
22
+ operations e.g. "G.nodes & H.nodes", and `dd = G.nodes[n]`, where
23
+ `dd` is the node data dict. Iteration is over the nodes by default.
24
+
25
+ NodeDataView
26
+ ============
27
+
28
+ To iterate over (node, data) pairs, use arguments to `G.nodes()`
29
+ to create a DataView e.g. `DV = G.nodes(data='color', default='red')`.
30
+ The DataView iterates as `for n, color in DV` and allows
31
+ `(n, 'red') in DV`. Using `DV = G.nodes(data=True)`, the DataViews
32
+ use the full datadict in writeable form also allowing contain testing as
33
+ `(n, {'color': 'red'}) in VD`. DataViews allow set operations when
34
+ data attributes are hashable.
35
+
36
+ DegreeView
37
+ ==========
38
+
39
+ `V = G.degree` allows iteration over (node, degree) pairs as well
40
+ as lookup: `deg=V[n]`. There are many flavors of DegreeView
41
+ for In/Out/Directed/Multi. For Directed Graphs, `G.degree`
42
+ counts both in and out going edges. `G.out_degree` and
43
+ `G.in_degree` count only specific directions.
44
+ Weighted degree using edge data attributes is provide via
45
+ `V = G.degree(weight='attr_name')` where any string with the
46
+ attribute name can be used. `weight=None` is the default.
47
+ No set operations are implemented for degrees, use NodeView.
48
+
49
+ The argument `nbunch` restricts iteration to nodes in nbunch.
50
+ The DegreeView can still lookup any node even if nbunch is specified.
51
+
52
+ EdgeView
53
+ ========
54
+
55
+ `V = G.edges` or `V = G.edges()` allows iteration over edges as well as
56
+ `e in V`, set operations and edge data lookup `dd = G.edges[2, 3]`.
57
+ Iteration is over 2-tuples `(u, v)` for Graph/DiGraph. For multigraphs
58
+ edges 3-tuples `(u, v, key)` are the default but 2-tuples can be obtained
59
+ via `V = G.edges(keys=False)`.
60
+
61
+ Set operations for directed graphs treat the edges as a set of 2-tuples.
62
+ For undirected graphs, 2-tuples are not a unique representation of edges.
63
+ So long as the set being compared to contains unique representations
64
+ of its edges, the set operations will act as expected. If the other
65
+ set contains both `(0, 1)` and `(1, 0)` however, the result of set
66
+ operations may contain both representations of the same edge.
67
+
68
+ EdgeDataView
69
+ ============
70
+
71
+ Edge data can be reported using an EdgeDataView typically created
72
+ by calling an EdgeView: `DV = G.edges(data='weight', default=1)`.
73
+ The EdgeDataView allows iteration over edge tuples, membership checking
74
+ but no set operations.
75
+
76
+ Iteration depends on `data` and `default` and for multigraph `keys`
77
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
78
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
79
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
80
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key`
81
+ to create 3-tuples and 4-tuples.
82
+
83
+ The argument `nbunch` restricts edges to those incident to nodes in nbunch.
84
+ """
85
+
86
+ from abc import ABC
87
+ from collections.abc import Mapping, Set
88
+
89
+ import networkx as nx
90
+
91
+ __all__ = [
92
+ "NodeView",
93
+ "NodeDataView",
94
+ "EdgeView",
95
+ "OutEdgeView",
96
+ "InEdgeView",
97
+ "EdgeDataView",
98
+ "OutEdgeDataView",
99
+ "InEdgeDataView",
100
+ "MultiEdgeView",
101
+ "OutMultiEdgeView",
102
+ "InMultiEdgeView",
103
+ "MultiEdgeDataView",
104
+ "OutMultiEdgeDataView",
105
+ "InMultiEdgeDataView",
106
+ "DegreeView",
107
+ "DiDegreeView",
108
+ "InDegreeView",
109
+ "OutDegreeView",
110
+ "MultiDegreeView",
111
+ "DiMultiDegreeView",
112
+ "InMultiDegreeView",
113
+ "OutMultiDegreeView",
114
+ ]
115
+
116
+
117
+ # NodeViews
118
+ class NodeView(Mapping, Set):
119
+ """A NodeView class to act as G.nodes for a NetworkX Graph
120
+
121
+ Set operations act on the nodes without considering data.
122
+ Iteration is over nodes. Node data can be looked up like a dict.
123
+ Use NodeDataView to iterate over node data or to specify a data
124
+ attribute for lookup. NodeDataView is created by calling the NodeView.
125
+
126
+ Parameters
127
+ ----------
128
+ graph : NetworkX graph-like class
129
+
130
+ Examples
131
+ --------
132
+ >>> G = nx.path_graph(3)
133
+ >>> NV = G.nodes()
134
+ >>> 2 in NV
135
+ True
136
+ >>> for n in NV:
137
+ ... print(n)
138
+ 0
139
+ 1
140
+ 2
141
+ >>> assert NV & {1, 2, 3} == {1, 2}
142
+
143
+ >>> G.add_node(2, color="blue")
144
+ >>> NV[2]
145
+ {'color': 'blue'}
146
+ >>> G.add_node(8, color="red")
147
+ >>> NDV = G.nodes(data=True)
148
+ >>> (2, NV[2]) in NDV
149
+ True
150
+ >>> for n, dd in NDV:
151
+ ... print((n, dd.get("color", "aqua")))
152
+ (0, 'aqua')
153
+ (1, 'aqua')
154
+ (2, 'blue')
155
+ (8, 'red')
156
+ >>> NDV[2] == NV[2]
157
+ True
158
+
159
+ >>> NVdata = G.nodes(data="color", default="aqua")
160
+ >>> (2, NVdata[2]) in NVdata
161
+ True
162
+ >>> for n, dd in NVdata:
163
+ ... print((n, dd))
164
+ (0, 'aqua')
165
+ (1, 'aqua')
166
+ (2, 'blue')
167
+ (8, 'red')
168
+ >>> NVdata[2] == NV[2] # NVdata gets 'color', NV gets datadict
169
+ False
170
+ """
171
+
172
+ __slots__ = ("_nodes",)
173
+
174
+ def __getstate__(self):
175
+ return {"_nodes": self._nodes}
176
+
177
+ def __setstate__(self, state):
178
+ self._nodes = state["_nodes"]
179
+
180
+ def __init__(self, graph):
181
+ self._nodes = graph._node
182
+
183
+ # Mapping methods
184
+ def __len__(self):
185
+ return len(self._nodes)
186
+
187
+ def __iter__(self):
188
+ return iter(self._nodes)
189
+
190
+ def __getitem__(self, n):
191
+ if isinstance(n, slice):
192
+ raise nx.NetworkXError(
193
+ f"{type(self).__name__} does not support slicing, "
194
+ f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]"
195
+ )
196
+ return self._nodes[n]
197
+
198
+ # Set methods
199
+ def __contains__(self, n):
200
+ return n in self._nodes
201
+
202
+ @classmethod
203
+ def _from_iterable(cls, it):
204
+ return set(it)
205
+
206
+ # DataView method
207
+ def __call__(self, data=False, default=None):
208
+ if data is False:
209
+ return self
210
+ return NodeDataView(self._nodes, data, default)
211
+
212
+ def data(self, data=True, default=None):
213
+ """
214
+ Return a read-only view of node data.
215
+
216
+ Parameters
217
+ ----------
218
+ data : bool or node data key, default=True
219
+ If ``data=True`` (the default), return a `NodeDataView` object that
220
+ maps each node to *all* of its attributes. `data` may also be an
221
+ arbitrary key, in which case the `NodeDataView` maps each node to
222
+ the value for the keyed attribute. In this case, if a node does
223
+ not have the `data` attribute, the `default` value is used.
224
+ default : object, default=None
225
+ The value used when a node does not have a specific attribute.
226
+
227
+ Returns
228
+ -------
229
+ NodeDataView
230
+ The layout of the returned NodeDataView depends on the value of the
231
+ `data` parameter.
232
+
233
+ Notes
234
+ -----
235
+ If ``data=False``, returns a `NodeView` object without data.
236
+
237
+ See Also
238
+ --------
239
+ NodeDataView
240
+
241
+ Examples
242
+ --------
243
+ >>> G = nx.Graph()
244
+ >>> G.add_nodes_from(
245
+ ... [
246
+ ... (0, {"color": "red", "weight": 10}),
247
+ ... (1, {"color": "blue"}),
248
+ ... (2, {"color": "yellow", "weight": 2}),
249
+ ... ]
250
+ ... )
251
+
252
+ Accessing node data with ``data=True`` (the default) returns a
253
+ NodeDataView mapping each node to all of its attributes:
254
+
255
+ >>> G.nodes.data()
256
+ NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}})
257
+
258
+ If `data` represents a key in the node attribute dict, a NodeDataView mapping
259
+ the nodes to the value for that specific key is returned:
260
+
261
+ >>> G.nodes.data("color")
262
+ NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color')
263
+
264
+ If a specific key is not found in an attribute dict, the value specified
265
+ by `default` is returned:
266
+
267
+ >>> G.nodes.data("weight", default=-999)
268
+ NodeDataView({0: 10, 1: -999, 2: 2}, data='weight')
269
+
270
+ Note that there is no check that the `data` key is in any of the
271
+ node attribute dictionaries:
272
+
273
+ >>> G.nodes.data("height")
274
+ NodeDataView({0: None, 1: None, 2: None}, data='height')
275
+ """
276
+ if data is False:
277
+ return self
278
+ return NodeDataView(self._nodes, data, default)
279
+
280
+ def __str__(self):
281
+ return str(list(self))
282
+
283
+ def __repr__(self):
284
+ return f"{self.__class__.__name__}({tuple(self)})"
285
+
286
+
287
+ class NodeDataView(Set):
288
+ """A DataView class for nodes of a NetworkX Graph
289
+
290
+ The main use for this class is to iterate through node-data pairs.
291
+ The data can be the entire data-dictionary for each node, or it
292
+ can be a specific attribute (with default) for each node.
293
+ Set operations are enabled with NodeDataView, but don't work in
294
+ cases where the data is not hashable. Use with caution.
295
+ Typically, set operations on nodes use NodeView, not NodeDataView.
296
+ That is, they use `G.nodes` instead of `G.nodes(data='foo')`.
297
+
298
+ Parameters
299
+ ==========
300
+ graph : NetworkX graph-like class
301
+ data : bool or string (default=False)
302
+ default : object (default=None)
303
+ """
304
+
305
+ __slots__ = ("_nodes", "_data", "_default")
306
+
307
+ def __getstate__(self):
308
+ return {"_nodes": self._nodes, "_data": self._data, "_default": self._default}
309
+
310
+ def __setstate__(self, state):
311
+ self._nodes = state["_nodes"]
312
+ self._data = state["_data"]
313
+ self._default = state["_default"]
314
+
315
+ def __init__(self, nodedict, data=False, default=None):
316
+ self._nodes = nodedict
317
+ self._data = data
318
+ self._default = default
319
+
320
+ @classmethod
321
+ def _from_iterable(cls, it):
322
+ try:
323
+ return set(it)
324
+ except TypeError as err:
325
+ if "unhashable" in str(err):
326
+ msg = " : Could be b/c data=True or your values are unhashable"
327
+ raise TypeError(str(err) + msg) from err
328
+ raise
329
+
330
+ def __len__(self):
331
+ return len(self._nodes)
332
+
333
+ def __iter__(self):
334
+ data = self._data
335
+ if data is False:
336
+ return iter(self._nodes)
337
+ if data is True:
338
+ return iter(self._nodes.items())
339
+ return (
340
+ (n, dd[data] if data in dd else self._default)
341
+ for n, dd in self._nodes.items()
342
+ )
343
+
344
+ def __contains__(self, n):
345
+ try:
346
+ node_in = n in self._nodes
347
+ except TypeError:
348
+ n, d = n
349
+ return n in self._nodes and self[n] == d
350
+ if node_in is True:
351
+ return node_in
352
+ try:
353
+ n, d = n
354
+ except (TypeError, ValueError):
355
+ return False
356
+ return n in self._nodes and self[n] == d
357
+
358
+ def __getitem__(self, n):
359
+ if isinstance(n, slice):
360
+ raise nx.NetworkXError(
361
+ f"{type(self).__name__} does not support slicing, "
362
+ f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]"
363
+ )
364
+ ddict = self._nodes[n]
365
+ data = self._data
366
+ if data is False or data is True:
367
+ return ddict
368
+ return ddict[data] if data in ddict else self._default
369
+
370
+ def __str__(self):
371
+ return str(list(self))
372
+
373
+ def __repr__(self):
374
+ name = self.__class__.__name__
375
+ if self._data is False:
376
+ return f"{name}({tuple(self)})"
377
+ if self._data is True:
378
+ return f"{name}({dict(self)})"
379
+ return f"{name}({dict(self)}, data={self._data!r})"
380
+
381
+
382
+ # DegreeViews
383
+ class DiDegreeView:
384
+ """A View class for degree of nodes in a NetworkX Graph
385
+
386
+ The functionality is like dict.items() with (node, degree) pairs.
387
+ Additional functionality includes read-only lookup of node degree,
388
+ and calling with optional features nbunch (for only a subset of nodes)
389
+ and weight (use edge weights to compute degree).
390
+
391
+ Parameters
392
+ ==========
393
+ graph : NetworkX graph-like class
394
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
395
+ weight : bool or string (default=None)
396
+
397
+ Notes
398
+ -----
399
+ DegreeView can still lookup any node even if nbunch is specified.
400
+
401
+ Examples
402
+ --------
403
+ >>> G = nx.path_graph(3)
404
+ >>> DV = G.degree()
405
+ >>> assert DV[2] == 1
406
+ >>> assert sum(deg for n, deg in DV) == 4
407
+
408
+ >>> DVweight = G.degree(weight="span")
409
+ >>> G.add_edge(1, 2, span=34)
410
+ >>> DVweight[2]
411
+ 34
412
+ >>> DVweight[0] # default edge weight is 1
413
+ 1
414
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
415
+ 70
416
+
417
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
418
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
419
+ """
420
+
421
+ def __init__(self, G, nbunch=None, weight=None):
422
+ self._graph = G
423
+ self._succ = G._succ if hasattr(G, "_succ") else G._adj
424
+ self._pred = G._pred if hasattr(G, "_pred") else G._adj
425
+ self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch))
426
+ self._weight = weight
427
+
428
+ def __call__(self, nbunch=None, weight=None):
429
+ if nbunch is None:
430
+ if weight == self._weight:
431
+ return self
432
+ return self.__class__(self._graph, None, weight)
433
+ try:
434
+ if nbunch in self._nodes:
435
+ if weight == self._weight:
436
+ return self[nbunch]
437
+ return self.__class__(self._graph, None, weight)[nbunch]
438
+ except TypeError:
439
+ pass
440
+ return self.__class__(self._graph, nbunch, weight)
441
+
442
+ def __getitem__(self, n):
443
+ weight = self._weight
444
+ succs = self._succ[n]
445
+ preds = self._pred[n]
446
+ if weight is None:
447
+ return len(succs) + len(preds)
448
+ return sum(dd.get(weight, 1) for dd in succs.values()) + sum(
449
+ dd.get(weight, 1) for dd in preds.values()
450
+ )
451
+
452
+ def __iter__(self):
453
+ weight = self._weight
454
+ if weight is None:
455
+ for n in self._nodes:
456
+ succs = self._succ[n]
457
+ preds = self._pred[n]
458
+ yield (n, len(succs) + len(preds))
459
+ else:
460
+ for n in self._nodes:
461
+ succs = self._succ[n]
462
+ preds = self._pred[n]
463
+ deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum(
464
+ dd.get(weight, 1) for dd in preds.values()
465
+ )
466
+ yield (n, deg)
467
+
468
+ def __len__(self):
469
+ return len(self._nodes)
470
+
471
+ def __str__(self):
472
+ return str(list(self))
473
+
474
+ def __repr__(self):
475
+ return f"{self.__class__.__name__}({dict(self)})"
476
+
477
+
478
+ class DegreeView(DiDegreeView):
479
+ """A DegreeView class to act as G.degree for a NetworkX Graph
480
+
481
+ Typical usage focuses on iteration over `(node, degree)` pairs.
482
+ The degree is by default the number of edges incident to the node.
483
+ Optional argument `weight` enables weighted degree using the edge
484
+ attribute named in the `weight` argument. Reporting and iteration
485
+ can also be restricted to a subset of nodes using `nbunch`.
486
+
487
+ Additional functionality include node lookup so that `G.degree[n]`
488
+ reported the (possibly weighted) degree of node `n`. Calling the
489
+ view creates a view with different arguments `nbunch` or `weight`.
490
+
491
+ Parameters
492
+ ==========
493
+ graph : NetworkX graph-like class
494
+ nbunch : node, container of nodes, or None meaning all nodes (default=None)
495
+ weight : string or None (default=None)
496
+
497
+ Notes
498
+ -----
499
+ DegreeView can still lookup any node even if nbunch is specified.
500
+
501
+ Examples
502
+ --------
503
+ >>> G = nx.path_graph(3)
504
+ >>> DV = G.degree()
505
+ >>> assert DV[2] == 1
506
+ >>> assert G.degree[2] == 1
507
+ >>> assert sum(deg for n, deg in DV) == 4
508
+
509
+ >>> DVweight = G.degree(weight="span")
510
+ >>> G.add_edge(1, 2, span=34)
511
+ >>> DVweight[2]
512
+ 34
513
+ >>> DVweight[0] # default edge weight is 1
514
+ 1
515
+ >>> sum(span for n, span in DVweight) # sum weighted degrees
516
+ 70
517
+
518
+ >>> DVnbunch = G.degree(nbunch=(1, 2))
519
+ >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only
520
+ """
521
+
522
+ def __getitem__(self, n):
523
+ weight = self._weight
524
+ nbrs = self._succ[n]
525
+ if weight is None:
526
+ return len(nbrs) + (n in nbrs)
527
+ return sum(dd.get(weight, 1) for dd in nbrs.values()) + (
528
+ n in nbrs and nbrs[n].get(weight, 1)
529
+ )
530
+
531
+ def __iter__(self):
532
+ weight = self._weight
533
+ if weight is None:
534
+ for n in self._nodes:
535
+ nbrs = self._succ[n]
536
+ yield (n, len(nbrs) + (n in nbrs))
537
+ else:
538
+ for n in self._nodes:
539
+ nbrs = self._succ[n]
540
+ deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + (
541
+ n in nbrs and nbrs[n].get(weight, 1)
542
+ )
543
+ yield (n, deg)
544
+
545
+
546
+ class OutDegreeView(DiDegreeView):
547
+ """A DegreeView class to report out_degree for a DiGraph; See DegreeView"""
548
+
549
+ def __getitem__(self, n):
550
+ weight = self._weight
551
+ nbrs = self._succ[n]
552
+ if self._weight is None:
553
+ return len(nbrs)
554
+ return sum(dd.get(self._weight, 1) for dd in nbrs.values())
555
+
556
+ def __iter__(self):
557
+ weight = self._weight
558
+ if weight is None:
559
+ for n in self._nodes:
560
+ succs = self._succ[n]
561
+ yield (n, len(succs))
562
+ else:
563
+ for n in self._nodes:
564
+ succs = self._succ[n]
565
+ deg = sum(dd.get(weight, 1) for dd in succs.values())
566
+ yield (n, deg)
567
+
568
+
569
+ class InDegreeView(DiDegreeView):
570
+ """A DegreeView class to report in_degree for a DiGraph; See DegreeView"""
571
+
572
+ def __getitem__(self, n):
573
+ weight = self._weight
574
+ nbrs = self._pred[n]
575
+ if weight is None:
576
+ return len(nbrs)
577
+ return sum(dd.get(weight, 1) for dd in nbrs.values())
578
+
579
+ def __iter__(self):
580
+ weight = self._weight
581
+ if weight is None:
582
+ for n in self._nodes:
583
+ preds = self._pred[n]
584
+ yield (n, len(preds))
585
+ else:
586
+ for n in self._nodes:
587
+ preds = self._pred[n]
588
+ deg = sum(dd.get(weight, 1) for dd in preds.values())
589
+ yield (n, deg)
590
+
591
+
592
+ class MultiDegreeView(DiDegreeView):
593
+ """A DegreeView class for undirected multigraphs; See DegreeView"""
594
+
595
+ def __getitem__(self, n):
596
+ weight = self._weight
597
+ nbrs = self._succ[n]
598
+ if weight is None:
599
+ return sum(len(keys) for keys in nbrs.values()) + (
600
+ n in nbrs and len(nbrs[n])
601
+ )
602
+ # edge weighted graph - degree is sum of nbr edge weights
603
+ deg = sum(
604
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
605
+ )
606
+ if n in nbrs:
607
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
608
+ return deg
609
+
610
+ def __iter__(self):
611
+ weight = self._weight
612
+ if weight is None:
613
+ for n in self._nodes:
614
+ nbrs = self._succ[n]
615
+ deg = sum(len(keys) for keys in nbrs.values()) + (
616
+ n in nbrs and len(nbrs[n])
617
+ )
618
+ yield (n, deg)
619
+ else:
620
+ for n in self._nodes:
621
+ nbrs = self._succ[n]
622
+ deg = sum(
623
+ d.get(weight, 1)
624
+ for key_dict in nbrs.values()
625
+ for d in key_dict.values()
626
+ )
627
+ if n in nbrs:
628
+ deg += sum(d.get(weight, 1) for d in nbrs[n].values())
629
+ yield (n, deg)
630
+
631
+
632
+ class DiMultiDegreeView(DiDegreeView):
633
+ """A DegreeView class for MultiDiGraph; See DegreeView"""
634
+
635
+ def __getitem__(self, n):
636
+ weight = self._weight
637
+ succs = self._succ[n]
638
+ preds = self._pred[n]
639
+ if weight is None:
640
+ return sum(len(keys) for keys in succs.values()) + sum(
641
+ len(keys) for keys in preds.values()
642
+ )
643
+ # edge weighted graph - degree is sum of nbr edge weights
644
+ deg = sum(
645
+ d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values()
646
+ ) + sum(
647
+ d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values()
648
+ )
649
+ return deg
650
+
651
+ def __iter__(self):
652
+ weight = self._weight
653
+ if weight is None:
654
+ for n in self._nodes:
655
+ succs = self._succ[n]
656
+ preds = self._pred[n]
657
+ deg = sum(len(keys) for keys in succs.values()) + sum(
658
+ len(keys) for keys in preds.values()
659
+ )
660
+ yield (n, deg)
661
+ else:
662
+ for n in self._nodes:
663
+ succs = self._succ[n]
664
+ preds = self._pred[n]
665
+ deg = sum(
666
+ d.get(weight, 1)
667
+ for key_dict in succs.values()
668
+ for d in key_dict.values()
669
+ ) + sum(
670
+ d.get(weight, 1)
671
+ for key_dict in preds.values()
672
+ for d in key_dict.values()
673
+ )
674
+ yield (n, deg)
675
+
676
+
677
+ class InMultiDegreeView(DiDegreeView):
678
+ """A DegreeView class for inward degree of MultiDiGraph; See DegreeView"""
679
+
680
+ def __getitem__(self, n):
681
+ weight = self._weight
682
+ nbrs = self._pred[n]
683
+ if weight is None:
684
+ return sum(len(data) for data in nbrs.values())
685
+ # edge weighted graph - degree is sum of nbr edge weights
686
+ return sum(
687
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
688
+ )
689
+
690
+ def __iter__(self):
691
+ weight = self._weight
692
+ if weight is None:
693
+ for n in self._nodes:
694
+ nbrs = self._pred[n]
695
+ deg = sum(len(data) for data in nbrs.values())
696
+ yield (n, deg)
697
+ else:
698
+ for n in self._nodes:
699
+ nbrs = self._pred[n]
700
+ deg = sum(
701
+ d.get(weight, 1)
702
+ for key_dict in nbrs.values()
703
+ for d in key_dict.values()
704
+ )
705
+ yield (n, deg)
706
+
707
+
708
+ class OutMultiDegreeView(DiDegreeView):
709
+ """A DegreeView class for outward degree of MultiDiGraph; See DegreeView"""
710
+
711
+ def __getitem__(self, n):
712
+ weight = self._weight
713
+ nbrs = self._succ[n]
714
+ if weight is None:
715
+ return sum(len(data) for data in nbrs.values())
716
+ # edge weighted graph - degree is sum of nbr edge weights
717
+ return sum(
718
+ d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values()
719
+ )
720
+
721
+ def __iter__(self):
722
+ weight = self._weight
723
+ if weight is None:
724
+ for n in self._nodes:
725
+ nbrs = self._succ[n]
726
+ deg = sum(len(data) for data in nbrs.values())
727
+ yield (n, deg)
728
+ else:
729
+ for n in self._nodes:
730
+ nbrs = self._succ[n]
731
+ deg = sum(
732
+ d.get(weight, 1)
733
+ for key_dict in nbrs.values()
734
+ for d in key_dict.values()
735
+ )
736
+ yield (n, deg)
737
+
738
+
739
+ # A base class for all edge views. Ensures all edge view and edge data view
740
+ # objects/classes are captured by `isinstance(obj, EdgeViewABC)` and
741
+ # `issubclass(cls, EdgeViewABC)` respectively
742
+ class EdgeViewABC(ABC):
743
+ pass
744
+
745
+
746
+ # EdgeDataViews
747
+ class OutEdgeDataView(EdgeViewABC):
748
+ """EdgeDataView for outward edges of DiGraph; See EdgeDataView"""
749
+
750
+ __slots__ = (
751
+ "_viewer",
752
+ "_nbunch",
753
+ "_data",
754
+ "_default",
755
+ "_adjdict",
756
+ "_nodes_nbrs",
757
+ "_report",
758
+ )
759
+
760
+ def __getstate__(self):
761
+ return {
762
+ "viewer": self._viewer,
763
+ "nbunch": self._nbunch,
764
+ "data": self._data,
765
+ "default": self._default,
766
+ }
767
+
768
+ def __setstate__(self, state):
769
+ self.__init__(**state)
770
+
771
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None):
772
+ self._viewer = viewer
773
+ adjdict = self._adjdict = viewer._adjdict
774
+ if nbunch is None:
775
+ self._nodes_nbrs = adjdict.items
776
+ else:
777
+ # dict retains order of nodes but acts like a set
778
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
779
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
780
+ self._nbunch = nbunch
781
+ self._data = data
782
+ self._default = default
783
+ # Set _report based on data and default
784
+ if data is True:
785
+ self._report = lambda n, nbr, dd: (n, nbr, dd)
786
+ elif data is False:
787
+ self._report = lambda n, nbr, dd: (n, nbr)
788
+ else: # data is attribute name
789
+ self._report = (
790
+ lambda n, nbr, dd: (n, nbr, dd[data])
791
+ if data in dd
792
+ else (n, nbr, default)
793
+ )
794
+
795
+ def __len__(self):
796
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
797
+
798
+ def __iter__(self):
799
+ return (
800
+ self._report(n, nbr, dd)
801
+ for n, nbrs in self._nodes_nbrs()
802
+ for nbr, dd in nbrs.items()
803
+ )
804
+
805
+ def __contains__(self, e):
806
+ u, v = e[:2]
807
+ if self._nbunch is not None and u not in self._nbunch:
808
+ return False # this edge doesn't start in nbunch
809
+ try:
810
+ ddict = self._adjdict[u][v]
811
+ except KeyError:
812
+ return False
813
+ return e == self._report(u, v, ddict)
814
+
815
+ def __str__(self):
816
+ return str(list(self))
817
+
818
+ def __repr__(self):
819
+ return f"{self.__class__.__name__}({list(self)})"
820
+
821
+
822
+ class EdgeDataView(OutEdgeDataView):
823
+ """A EdgeDataView class for edges of Graph
824
+
825
+ This view is primarily used to iterate over the edges reporting
826
+ edges as node-tuples with edge data optionally reported. The
827
+ argument `nbunch` allows restriction to edges incident to nodes
828
+ in that container/singleton. The default (nbunch=None)
829
+ reports all edges. The arguments `data` and `default` control
830
+ what edge data is reported. The default `data is False` reports
831
+ only node-tuples for each edge. If `data is True` the entire edge
832
+ data dict is returned. Otherwise `data` is assumed to hold the name
833
+ of the edge attribute to report with default `default` if that
834
+ edge attribute is not present.
835
+
836
+ Parameters
837
+ ----------
838
+ nbunch : container of nodes, node or None (default None)
839
+ data : False, True or string (default False)
840
+ default : default value (default None)
841
+
842
+ Examples
843
+ --------
844
+ >>> G = nx.path_graph(3)
845
+ >>> G.add_edge(1, 2, foo="bar")
846
+ >>> list(G.edges(data="foo", default="biz"))
847
+ [(0, 1, 'biz'), (1, 2, 'bar')]
848
+ >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz")
849
+ """
850
+
851
+ __slots__ = ()
852
+
853
+ def __len__(self):
854
+ return sum(1 for e in self)
855
+
856
+ def __iter__(self):
857
+ seen = {}
858
+ for n, nbrs in self._nodes_nbrs():
859
+ for nbr, dd in nbrs.items():
860
+ if nbr not in seen:
861
+ yield self._report(n, nbr, dd)
862
+ seen[n] = 1
863
+ del seen
864
+
865
+ def __contains__(self, e):
866
+ u, v = e[:2]
867
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
868
+ return False # this edge doesn't start and it doesn't end in nbunch
869
+ try:
870
+ ddict = self._adjdict[u][v]
871
+ except KeyError:
872
+ return False
873
+ return e == self._report(u, v, ddict)
874
+
875
+
876
+ class InEdgeDataView(OutEdgeDataView):
877
+ """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView"""
878
+
879
+ __slots__ = ()
880
+
881
+ def __iter__(self):
882
+ return (
883
+ self._report(nbr, n, dd)
884
+ for n, nbrs in self._nodes_nbrs()
885
+ for nbr, dd in nbrs.items()
886
+ )
887
+
888
+ def __contains__(self, e):
889
+ u, v = e[:2]
890
+ if self._nbunch is not None and v not in self._nbunch:
891
+ return False # this edge doesn't end in nbunch
892
+ try:
893
+ ddict = self._adjdict[v][u]
894
+ except KeyError:
895
+ return False
896
+ return e == self._report(u, v, ddict)
897
+
898
+
899
+ class OutMultiEdgeDataView(OutEdgeDataView):
900
+ """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
901
+
902
+ __slots__ = ("keys",)
903
+
904
+ def __getstate__(self):
905
+ return {
906
+ "viewer": self._viewer,
907
+ "nbunch": self._nbunch,
908
+ "keys": self.keys,
909
+ "data": self._data,
910
+ "default": self._default,
911
+ }
912
+
913
+ def __setstate__(self, state):
914
+ self.__init__(**state)
915
+
916
+ def __init__(self, viewer, nbunch=None, data=False, *, default=None, keys=False):
917
+ self._viewer = viewer
918
+ adjdict = self._adjdict = viewer._adjdict
919
+ self.keys = keys
920
+ if nbunch is None:
921
+ self._nodes_nbrs = adjdict.items
922
+ else:
923
+ # dict retains order of nodes but acts like a set
924
+ nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch))
925
+ self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch]
926
+ self._nbunch = nbunch
927
+ self._data = data
928
+ self._default = default
929
+ # Set _report based on data and default
930
+ if data is True:
931
+ if keys is True:
932
+ self._report = lambda n, nbr, k, dd: (n, nbr, k, dd)
933
+ else:
934
+ self._report = lambda n, nbr, k, dd: (n, nbr, dd)
935
+ elif data is False:
936
+ if keys is True:
937
+ self._report = lambda n, nbr, k, dd: (n, nbr, k)
938
+ else:
939
+ self._report = lambda n, nbr, k, dd: (n, nbr)
940
+ else: # data is attribute name
941
+ if keys is True:
942
+ self._report = (
943
+ lambda n, nbr, k, dd: (n, nbr, k, dd[data])
944
+ if data in dd
945
+ else (n, nbr, k, default)
946
+ )
947
+ else:
948
+ self._report = (
949
+ lambda n, nbr, k, dd: (n, nbr, dd[data])
950
+ if data in dd
951
+ else (n, nbr, default)
952
+ )
953
+
954
+ def __len__(self):
955
+ return sum(1 for e in self)
956
+
957
+ def __iter__(self):
958
+ return (
959
+ self._report(n, nbr, k, dd)
960
+ for n, nbrs in self._nodes_nbrs()
961
+ for nbr, kd in nbrs.items()
962
+ for k, dd in kd.items()
963
+ )
964
+
965
+ def __contains__(self, e):
966
+ u, v = e[:2]
967
+ if self._nbunch is not None and u not in self._nbunch:
968
+ return False # this edge doesn't start in nbunch
969
+ try:
970
+ kdict = self._adjdict[u][v]
971
+ except KeyError:
972
+ return False
973
+ if self.keys is True:
974
+ k = e[2]
975
+ try:
976
+ dd = kdict[k]
977
+ except KeyError:
978
+ return False
979
+ return e == self._report(u, v, k, dd)
980
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
981
+
982
+
983
+ class MultiEdgeDataView(OutMultiEdgeDataView):
984
+ """An EdgeDataView class for edges of MultiGraph; See EdgeDataView"""
985
+
986
+ __slots__ = ()
987
+
988
+ def __iter__(self):
989
+ seen = {}
990
+ for n, nbrs in self._nodes_nbrs():
991
+ for nbr, kd in nbrs.items():
992
+ if nbr not in seen:
993
+ for k, dd in kd.items():
994
+ yield self._report(n, nbr, k, dd)
995
+ seen[n] = 1
996
+ del seen
997
+
998
+ def __contains__(self, e):
999
+ u, v = e[:2]
1000
+ if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch:
1001
+ return False # this edge doesn't start and doesn't end in nbunch
1002
+ try:
1003
+ kdict = self._adjdict[u][v]
1004
+ except KeyError:
1005
+ try:
1006
+ kdict = self._adjdict[v][u]
1007
+ except KeyError:
1008
+ return False
1009
+ if self.keys is True:
1010
+ k = e[2]
1011
+ try:
1012
+ dd = kdict[k]
1013
+ except KeyError:
1014
+ return False
1015
+ return e == self._report(u, v, k, dd)
1016
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1017
+
1018
+
1019
+ class InMultiEdgeDataView(OutMultiEdgeDataView):
1020
+ """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView"""
1021
+
1022
+ __slots__ = ()
1023
+
1024
+ def __iter__(self):
1025
+ return (
1026
+ self._report(nbr, n, k, dd)
1027
+ for n, nbrs in self._nodes_nbrs()
1028
+ for nbr, kd in nbrs.items()
1029
+ for k, dd in kd.items()
1030
+ )
1031
+
1032
+ def __contains__(self, e):
1033
+ u, v = e[:2]
1034
+ if self._nbunch is not None and v not in self._nbunch:
1035
+ return False # this edge doesn't end in nbunch
1036
+ try:
1037
+ kdict = self._adjdict[v][u]
1038
+ except KeyError:
1039
+ return False
1040
+ if self.keys is True:
1041
+ k = e[2]
1042
+ dd = kdict[k]
1043
+ return e == self._report(u, v, k, dd)
1044
+ return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
1045
+
1046
+
1047
+ # EdgeViews have set operations and no data reported
1048
+ class OutEdgeView(Set, Mapping, EdgeViewABC):
1049
+ """A EdgeView class for outward edges of a DiGraph"""
1050
+
1051
+ __slots__ = ("_adjdict", "_graph", "_nodes_nbrs")
1052
+
1053
+ def __getstate__(self):
1054
+ return {"_graph": self._graph, "_adjdict": self._adjdict}
1055
+
1056
+ def __setstate__(self, state):
1057
+ self._graph = state["_graph"]
1058
+ self._adjdict = state["_adjdict"]
1059
+ self._nodes_nbrs = self._adjdict.items
1060
+
1061
+ @classmethod
1062
+ def _from_iterable(cls, it):
1063
+ return set(it)
1064
+
1065
+ dataview = OutEdgeDataView
1066
+
1067
+ def __init__(self, G):
1068
+ self._graph = G
1069
+ self._adjdict = G._succ if hasattr(G, "succ") else G._adj
1070
+ self._nodes_nbrs = self._adjdict.items
1071
+
1072
+ # Set methods
1073
+ def __len__(self):
1074
+ return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
1075
+
1076
+ def __iter__(self):
1077
+ for n, nbrs in self._nodes_nbrs():
1078
+ for nbr in nbrs:
1079
+ yield (n, nbr)
1080
+
1081
+ def __contains__(self, e):
1082
+ try:
1083
+ u, v = e
1084
+ return v in self._adjdict[u]
1085
+ except KeyError:
1086
+ return False
1087
+
1088
+ # Mapping Methods
1089
+ def __getitem__(self, e):
1090
+ if isinstance(e, slice):
1091
+ raise nx.NetworkXError(
1092
+ f"{type(self).__name__} does not support slicing, "
1093
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1094
+ )
1095
+ u, v = e
1096
+ try:
1097
+ return self._adjdict[u][v]
1098
+ except KeyError as ex: # Customize msg to indicate exception origin
1099
+ raise KeyError(f"The edge {e} is not in the graph.")
1100
+
1101
+ # EdgeDataView methods
1102
+ def __call__(self, nbunch=None, data=False, *, default=None):
1103
+ if nbunch is None and data is False:
1104
+ return self
1105
+ return self.dataview(self, nbunch, data, default=default)
1106
+
1107
+ def data(self, data=True, default=None, nbunch=None):
1108
+ """
1109
+ Return a read-only view of edge data.
1110
+
1111
+ Parameters
1112
+ ----------
1113
+ data : bool or edge attribute key
1114
+ If ``data=True``, then the data view maps each edge to a dictionary
1115
+ containing all of its attributes. If `data` is a key in the edge
1116
+ dictionary, then the data view maps each edge to its value for
1117
+ the keyed attribute. In this case, if the edge doesn't have the
1118
+ attribute, the `default` value is returned.
1119
+ default : object, default=None
1120
+ The value used when an edge does not have a specific attribute
1121
+ nbunch : container of nodes, optional (default=None)
1122
+ Allows restriction to edges only involving certain nodes. All edges
1123
+ are considered by default.
1124
+
1125
+ Returns
1126
+ -------
1127
+ dataview
1128
+ Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView`
1129
+ for DiGraphs, `MultiEdgeDataView` for MultiGraphs and
1130
+ `OutMultiEdgeDataView` for MultiDiGraphs.
1131
+
1132
+ Notes
1133
+ -----
1134
+ If ``data=False``, returns an `EdgeView` without any edge data.
1135
+
1136
+ See Also
1137
+ --------
1138
+ EdgeDataView
1139
+ OutEdgeDataView
1140
+ MultiEdgeDataView
1141
+ OutMultiEdgeDataView
1142
+
1143
+ Examples
1144
+ --------
1145
+ >>> G = nx.Graph()
1146
+ >>> G.add_edges_from(
1147
+ ... [
1148
+ ... (0, 1, {"dist": 3, "capacity": 20}),
1149
+ ... (1, 2, {"dist": 4}),
1150
+ ... (2, 0, {"dist": 5}),
1151
+ ... ]
1152
+ ... )
1153
+
1154
+ Accessing edge data with ``data=True`` (the default) returns an
1155
+ edge data view object listing each edge with all of its attributes:
1156
+
1157
+ >>> G.edges.data()
1158
+ EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})])
1159
+
1160
+ If `data` represents a key in the edge attribute dict, a dataview listing
1161
+ each edge with its value for that specific key is returned:
1162
+
1163
+ >>> G.edges.data("dist")
1164
+ EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)])
1165
+
1166
+ `nbunch` can be used to limit the edges:
1167
+
1168
+ >>> G.edges.data("dist", nbunch=[0])
1169
+ EdgeDataView([(0, 1, 3), (0, 2, 5)])
1170
+
1171
+ If a specific key is not found in an edge attribute dict, the value
1172
+ specified by `default` is used:
1173
+
1174
+ >>> G.edges.data("capacity")
1175
+ EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)])
1176
+
1177
+ Note that there is no check that the `data` key is present in any of
1178
+ the edge attribute dictionaries:
1179
+
1180
+ >>> G.edges.data("speed")
1181
+ EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)])
1182
+ """
1183
+ if nbunch is None and data is False:
1184
+ return self
1185
+ return self.dataview(self, nbunch, data, default=default)
1186
+
1187
+ # String Methods
1188
+ def __str__(self):
1189
+ return str(list(self))
1190
+
1191
+ def __repr__(self):
1192
+ return f"{self.__class__.__name__}({list(self)})"
1193
+
1194
+
1195
+ class EdgeView(OutEdgeView):
1196
+ """A EdgeView class for edges of a Graph
1197
+
1198
+ This densely packed View allows iteration over edges, data lookup
1199
+ like a dict and set operations on edges represented by node-tuples.
1200
+ In addition, edge data can be controlled by calling this object
1201
+ possibly creating an EdgeDataView. Typically edges are iterated over
1202
+ and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples
1203
+ for multigraphs. Those edge representations can also be using to
1204
+ lookup the data dict for any edge. Set operations also are available
1205
+ where those tuples are the elements of the set.
1206
+ Calling this object with optional arguments `data`, `default` and `keys`
1207
+ controls the form of the tuple (see EdgeDataView). Optional argument
1208
+ `nbunch` allows restriction to edges only involving certain nodes.
1209
+
1210
+ If `data is False` (the default) then iterate over 2-tuples `(u, v)`.
1211
+ If `data is True` iterate over 3-tuples `(u, v, datadict)`.
1212
+ Otherwise iterate over `(u, v, datadict.get(data, default))`.
1213
+ For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above.
1214
+
1215
+ Parameters
1216
+ ==========
1217
+ graph : NetworkX graph-like class
1218
+ nbunch : (default= all nodes in graph) only report edges with these nodes
1219
+ keys : (only for MultiGraph. default=False) report edge key in tuple
1220
+ data : bool or string (default=False) see above
1221
+ default : object (default=None)
1222
+
1223
+ Examples
1224
+ ========
1225
+ >>> G = nx.path_graph(4)
1226
+ >>> EV = G.edges()
1227
+ >>> (2, 3) in EV
1228
+ True
1229
+ >>> for u, v in EV:
1230
+ ... print((u, v))
1231
+ (0, 1)
1232
+ (1, 2)
1233
+ (2, 3)
1234
+ >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)}
1235
+
1236
+ >>> EVdata = G.edges(data="color", default="aqua")
1237
+ >>> G.add_edge(2, 3, color="blue")
1238
+ >>> assert (2, 3, "blue") in EVdata
1239
+ >>> for u, v, c in EVdata:
1240
+ ... print(f"({u}, {v}) has color: {c}")
1241
+ (0, 1) has color: aqua
1242
+ (1, 2) has color: aqua
1243
+ (2, 3) has color: blue
1244
+
1245
+ >>> EVnbunch = G.edges(nbunch=2)
1246
+ >>> assert (2, 3) in EVnbunch
1247
+ >>> assert (0, 1) not in EVnbunch
1248
+ >>> for u, v in EVnbunch:
1249
+ ... assert u == 2 or v == 2
1250
+
1251
+ >>> MG = nx.path_graph(4, create_using=nx.MultiGraph)
1252
+ >>> EVmulti = MG.edges(keys=True)
1253
+ >>> (2, 3, 0) in EVmulti
1254
+ True
1255
+ >>> (2, 3) in EVmulti # 2-tuples work even when keys is True
1256
+ True
1257
+ >>> key = MG.add_edge(2, 3)
1258
+ >>> for u, v, k in EVmulti:
1259
+ ... print((u, v, k))
1260
+ (0, 1, 0)
1261
+ (1, 2, 0)
1262
+ (2, 3, 0)
1263
+ (2, 3, 1)
1264
+ """
1265
+
1266
+ __slots__ = ()
1267
+
1268
+ dataview = EdgeDataView
1269
+
1270
+ def __len__(self):
1271
+ num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs())
1272
+ return sum(num_nbrs) // 2
1273
+
1274
+ def __iter__(self):
1275
+ seen = {}
1276
+ for n, nbrs in self._nodes_nbrs():
1277
+ for nbr in list(nbrs):
1278
+ if nbr not in seen:
1279
+ yield (n, nbr)
1280
+ seen[n] = 1
1281
+ del seen
1282
+
1283
+ def __contains__(self, e):
1284
+ try:
1285
+ u, v = e[:2]
1286
+ return v in self._adjdict[u] or u in self._adjdict[v]
1287
+ except (KeyError, ValueError):
1288
+ return False
1289
+
1290
+
1291
+ class InEdgeView(OutEdgeView):
1292
+ """A EdgeView class for inward edges of a DiGraph"""
1293
+
1294
+ __slots__ = ()
1295
+
1296
+ def __setstate__(self, state):
1297
+ self._graph = state["_graph"]
1298
+ self._adjdict = state["_adjdict"]
1299
+ self._nodes_nbrs = self._adjdict.items
1300
+
1301
+ dataview = InEdgeDataView
1302
+
1303
+ def __init__(self, G):
1304
+ self._graph = G
1305
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1306
+ self._nodes_nbrs = self._adjdict.items
1307
+
1308
+ def __iter__(self):
1309
+ for n, nbrs in self._nodes_nbrs():
1310
+ for nbr in nbrs:
1311
+ yield (nbr, n)
1312
+
1313
+ def __contains__(self, e):
1314
+ try:
1315
+ u, v = e
1316
+ return u in self._adjdict[v]
1317
+ except KeyError:
1318
+ return False
1319
+
1320
+ def __getitem__(self, e):
1321
+ if isinstance(e, slice):
1322
+ raise nx.NetworkXError(
1323
+ f"{type(self).__name__} does not support slicing, "
1324
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1325
+ )
1326
+ u, v = e
1327
+ return self._adjdict[v][u]
1328
+
1329
+
1330
+ class OutMultiEdgeView(OutEdgeView):
1331
+ """A EdgeView class for outward edges of a MultiDiGraph"""
1332
+
1333
+ __slots__ = ()
1334
+
1335
+ dataview = OutMultiEdgeDataView
1336
+
1337
+ def __len__(self):
1338
+ return sum(
1339
+ len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items()
1340
+ )
1341
+
1342
+ def __iter__(self):
1343
+ for n, nbrs in self._nodes_nbrs():
1344
+ for nbr, kdict in nbrs.items():
1345
+ for key in kdict:
1346
+ yield (n, nbr, key)
1347
+
1348
+ def __contains__(self, e):
1349
+ N = len(e)
1350
+ if N == 3:
1351
+ u, v, k = e
1352
+ elif N == 2:
1353
+ u, v = e
1354
+ k = 0
1355
+ else:
1356
+ raise ValueError("MultiEdge must have length 2 or 3")
1357
+ try:
1358
+ return k in self._adjdict[u][v]
1359
+ except KeyError:
1360
+ return False
1361
+
1362
+ def __getitem__(self, e):
1363
+ if isinstance(e, slice):
1364
+ raise nx.NetworkXError(
1365
+ f"{type(self).__name__} does not support slicing, "
1366
+ f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
1367
+ )
1368
+ u, v, k = e
1369
+ return self._adjdict[u][v][k]
1370
+
1371
+ def __call__(self, nbunch=None, data=False, *, default=None, keys=False):
1372
+ if nbunch is None and data is False and keys is True:
1373
+ return self
1374
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1375
+
1376
+ def data(self, data=True, default=None, nbunch=None, keys=False):
1377
+ if nbunch is None and data is False and keys is True:
1378
+ return self
1379
+ return self.dataview(self, nbunch, data, default=default, keys=keys)
1380
+
1381
+
1382
+ class MultiEdgeView(OutMultiEdgeView):
1383
+ """A EdgeView class for edges of a MultiGraph"""
1384
+
1385
+ __slots__ = ()
1386
+
1387
+ dataview = MultiEdgeDataView
1388
+
1389
+ def __len__(self):
1390
+ return sum(1 for e in self)
1391
+
1392
+ def __iter__(self):
1393
+ seen = {}
1394
+ for n, nbrs in self._nodes_nbrs():
1395
+ for nbr, kd in nbrs.items():
1396
+ if nbr not in seen:
1397
+ for k, dd in kd.items():
1398
+ yield (n, nbr, k)
1399
+ seen[n] = 1
1400
+ del seen
1401
+
1402
+
1403
+ class InMultiEdgeView(OutMultiEdgeView):
1404
+ """A EdgeView class for inward edges of a MultiDiGraph"""
1405
+
1406
+ __slots__ = ()
1407
+
1408
+ def __setstate__(self, state):
1409
+ self._graph = state["_graph"]
1410
+ self._adjdict = state["_adjdict"]
1411
+ self._nodes_nbrs = self._adjdict.items
1412
+
1413
+ dataview = InMultiEdgeDataView
1414
+
1415
+ def __init__(self, G):
1416
+ self._graph = G
1417
+ self._adjdict = G._pred if hasattr(G, "pred") else G._adj
1418
+ self._nodes_nbrs = self._adjdict.items
1419
+
1420
+ def __iter__(self):
1421
+ for n, nbrs in self._nodes_nbrs():
1422
+ for nbr, kdict in nbrs.items():
1423
+ for key in kdict:
1424
+ yield (nbr, n, key)
1425
+
1426
+ def __contains__(self, e):
1427
+ N = len(e)
1428
+ if N == 3:
1429
+ u, v, k = e
1430
+ elif N == 2:
1431
+ u, v = e
1432
+ k = 0
1433
+ else:
1434
+ raise ValueError("MultiEdge must have length 2 or 3")
1435
+ try:
1436
+ return k in self._adjdict[v][u]
1437
+ except KeyError:
1438
+ return False
1439
+
1440
+ def __getitem__(self, e):
1441
+ if isinstance(e, slice):
1442
+ raise nx.NetworkXError(
1443
+ f"{type(self).__name__} does not support slicing, "
1444
+ f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]"
1445
+ )
1446
+ u, v, k = e
1447
+ return self._adjdict[v][u][k]
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/__init__.py ADDED
File without changes
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains utilities for testing the dispatching feature
2
+
3
+ # A full test of all dispatchable algorithms is performed by
4
+ # modifying the pytest invocation and setting an environment variable
5
+ # NETWORKX_TEST_BACKEND=nx_loopback pytest
6
+ # This is comprehensive, but only tests the `test_override_dispatch`
7
+ # function in networkx.classes.backends.
8
+
9
+ # To test the `_dispatchable` function directly, several tests scattered throughout
10
+ # NetworkX have been augmented to test normal and dispatch mode.
11
+ # Searching for `dispatch_interface` should locate the specific tests.
12
+
13
+ import networkx as nx
14
+ from networkx import DiGraph, Graph, MultiDiGraph, MultiGraph, PlanarEmbedding
15
+ from networkx.classes.reportviews import NodeView
16
+
17
+
18
+ class LoopbackGraph(Graph):
19
+ __networkx_backend__ = "nx_loopback"
20
+
21
+
22
+ class LoopbackDiGraph(DiGraph):
23
+ __networkx_backend__ = "nx_loopback"
24
+
25
+
26
+ class LoopbackMultiGraph(MultiGraph):
27
+ __networkx_backend__ = "nx_loopback"
28
+
29
+
30
+ class LoopbackMultiDiGraph(MultiDiGraph):
31
+ __networkx_backend__ = "nx_loopback"
32
+
33
+
34
+ class LoopbackPlanarEmbedding(PlanarEmbedding):
35
+ __networkx_backend__ = "nx_loopback"
36
+
37
+
38
+ def convert(graph):
39
+ if isinstance(graph, PlanarEmbedding):
40
+ return LoopbackPlanarEmbedding(graph)
41
+ if isinstance(graph, MultiDiGraph):
42
+ return LoopbackMultiDiGraph(graph)
43
+ if isinstance(graph, MultiGraph):
44
+ return LoopbackMultiGraph(graph)
45
+ if isinstance(graph, DiGraph):
46
+ return LoopbackDiGraph(graph)
47
+ if isinstance(graph, Graph):
48
+ return LoopbackGraph(graph)
49
+ raise TypeError(f"Unsupported type of graph: {type(graph)}")
50
+
51
+
52
+ class LoopbackBackendInterface:
53
+ def __getattr__(self, item):
54
+ try:
55
+ return nx.utils.backends._registered_algorithms[item].orig_func
56
+ except KeyError:
57
+ raise AttributeError(item) from None
58
+
59
+ @staticmethod
60
+ def convert_from_nx(
61
+ graph,
62
+ *,
63
+ edge_attrs=None,
64
+ node_attrs=None,
65
+ preserve_edge_attrs=None,
66
+ preserve_node_attrs=None,
67
+ preserve_graph_attrs=None,
68
+ name=None,
69
+ graph_name=None,
70
+ ):
71
+ if name in {
72
+ # Raise if input graph changes. See test_dag.py::test_topological_sort6
73
+ "lexicographical_topological_sort",
74
+ "topological_generations",
75
+ "topological_sort",
76
+ # Would be nice to some day avoid these cutoffs of full testing
77
+ }:
78
+ return graph
79
+ if isinstance(graph, NodeView):
80
+ # Convert to a Graph with only nodes (no edges)
81
+ new_graph = Graph()
82
+ new_graph.add_nodes_from(graph.items())
83
+ graph = new_graph
84
+ G = LoopbackGraph()
85
+ elif not isinstance(graph, Graph):
86
+ raise TypeError(
87
+ f"Bad type for graph argument {graph_name} in {name}: {type(graph)}"
88
+ )
89
+ elif graph.__class__ in {Graph, LoopbackGraph}:
90
+ G = LoopbackGraph()
91
+ elif graph.__class__ in {DiGraph, LoopbackDiGraph}:
92
+ G = LoopbackDiGraph()
93
+ elif graph.__class__ in {MultiGraph, LoopbackMultiGraph}:
94
+ G = LoopbackMultiGraph()
95
+ elif graph.__class__ in {MultiDiGraph, LoopbackMultiDiGraph}:
96
+ G = LoopbackMultiDiGraph()
97
+ elif graph.__class__ in {PlanarEmbedding, LoopbackPlanarEmbedding}:
98
+ G = LoopbackDiGraph() # or LoopbackPlanarEmbedding
99
+ else:
100
+ # Would be nice to handle these better some day
101
+ # nx.algorithms.approximation.kcomponents._AntiGraph
102
+ # nx.classes.tests.test_multidigraph.MultiDiGraphSubClass
103
+ # nx.classes.tests.test_multigraph.MultiGraphSubClass
104
+ G = graph.__class__()
105
+
106
+ if preserve_graph_attrs:
107
+ G.graph.update(graph.graph)
108
+
109
+ # add nodes
110
+ G.add_nodes_from(graph)
111
+ if preserve_node_attrs:
112
+ for n, dd in G._node.items():
113
+ dd.update(graph.nodes[n])
114
+ elif node_attrs:
115
+ for n, dd in G._node.items():
116
+ dd.update(
117
+ (attr, graph._node[n].get(attr, default))
118
+ for attr, default in node_attrs.items()
119
+ if default is not None or attr in graph._node[n]
120
+ )
121
+
122
+ # tools to build datadict and keydict
123
+ if preserve_edge_attrs:
124
+
125
+ def G_new_datadict(old_dd):
126
+ return G.edge_attr_dict_factory(old_dd)
127
+ elif edge_attrs:
128
+
129
+ def G_new_datadict(old_dd):
130
+ return G.edge_attr_dict_factory(
131
+ (attr, old_dd.get(attr, default))
132
+ for attr, default in edge_attrs.items()
133
+ if default is not None or attr in old_dd
134
+ )
135
+ else:
136
+
137
+ def G_new_datadict(old_dd):
138
+ return G.edge_attr_dict_factory()
139
+
140
+ if G.is_multigraph():
141
+
142
+ def G_new_inner(keydict):
143
+ kd = G.adjlist_inner_dict_factory(
144
+ (k, G_new_datadict(dd)) for k, dd in keydict.items()
145
+ )
146
+ return kd
147
+ else:
148
+ G_new_inner = G_new_datadict
149
+
150
+ # add edges keeping the same order in _adj and _pred
151
+ G_adj = G._adj
152
+ if G.is_directed():
153
+ for n, nbrs in graph._adj.items():
154
+ G_adj[n].update((nbr, G_new_inner(dd)) for nbr, dd in nbrs.items())
155
+ # ensure same datadict for pred and adj; and pred order of graph._pred
156
+ G_pred = G._pred
157
+ for n, nbrs in graph._pred.items():
158
+ G_pred[n].update((nbr, G_adj[nbr][n]) for nbr in nbrs)
159
+ else: # undirected
160
+ for n, nbrs in graph._adj.items():
161
+ # ensure same datadict for both ways; and adj order of graph._adj
162
+ G_adj[n].update(
163
+ (nbr, G_adj[nbr][n] if n in G_adj[nbr] else G_new_inner(dd))
164
+ for nbr, dd in nbrs.items()
165
+ )
166
+
167
+ return G
168
+
169
+ @staticmethod
170
+ def convert_to_nx(obj, *, name=None):
171
+ return obj
172
+
173
+ @staticmethod
174
+ def on_start_tests(items):
175
+ # Verify that items can be xfailed
176
+ for item in items:
177
+ assert hasattr(item, "add_marker")
178
+
179
+ def can_run(self, name, args, kwargs):
180
+ # It is unnecessary to define this function if algorithms are fully supported.
181
+ # We include it for illustration purposes.
182
+ return hasattr(self, name)
183
+
184
+
185
+ backend_interface = LoopbackBackendInterface()
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestFilterFactory:
7
+ def test_no_filter(self):
8
+ nf = nx.filters.no_filter
9
+ assert nf()
10
+ assert nf(1)
11
+ assert nf(2, 1)
12
+
13
+ def test_hide_nodes(self):
14
+ f = nx.classes.filters.hide_nodes([1, 2, 3])
15
+ assert not f(1)
16
+ assert not f(2)
17
+ assert not f(3)
18
+ assert f(4)
19
+ assert f(0)
20
+ assert f("a")
21
+ pytest.raises(TypeError, f, 1, 2)
22
+ pytest.raises(TypeError, f)
23
+
24
+ def test_show_nodes(self):
25
+ f = nx.classes.filters.show_nodes([1, 2, 3])
26
+ assert f(1)
27
+ assert f(2)
28
+ assert f(3)
29
+ assert not f(4)
30
+ assert not f(0)
31
+ assert not f("a")
32
+ pytest.raises(TypeError, f, 1, 2)
33
+ pytest.raises(TypeError, f)
34
+
35
+ def test_hide_edges(self):
36
+ factory = nx.classes.filters.hide_edges
37
+ f = factory([(1, 2), (3, 4)])
38
+ assert not f(1, 2)
39
+ assert not f(3, 4)
40
+ assert not f(4, 3)
41
+ assert f(2, 3)
42
+ assert f(0, -1)
43
+ assert f("a", "b")
44
+ pytest.raises(TypeError, f, 1, 2, 3)
45
+ pytest.raises(TypeError, f, 1)
46
+ pytest.raises(TypeError, f)
47
+ pytest.raises(TypeError, factory, [1, 2, 3])
48
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
49
+
50
+ def test_show_edges(self):
51
+ factory = nx.classes.filters.show_edges
52
+ f = factory([(1, 2), (3, 4)])
53
+ assert f(1, 2)
54
+ assert f(3, 4)
55
+ assert f(4, 3)
56
+ assert not f(2, 3)
57
+ assert not f(0, -1)
58
+ assert not f("a", "b")
59
+ pytest.raises(TypeError, f, 1, 2, 3)
60
+ pytest.raises(TypeError, f, 1)
61
+ pytest.raises(TypeError, f)
62
+ pytest.raises(TypeError, factory, [1, 2, 3])
63
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
64
+
65
+ def test_hide_diedges(self):
66
+ factory = nx.classes.filters.hide_diedges
67
+ f = factory([(1, 2), (3, 4)])
68
+ assert not f(1, 2)
69
+ assert not f(3, 4)
70
+ assert f(4, 3)
71
+ assert f(2, 3)
72
+ assert f(0, -1)
73
+ assert f("a", "b")
74
+ pytest.raises(TypeError, f, 1, 2, 3)
75
+ pytest.raises(TypeError, f, 1)
76
+ pytest.raises(TypeError, f)
77
+ pytest.raises(TypeError, factory, [1, 2, 3])
78
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
79
+
80
+ def test_show_diedges(self):
81
+ factory = nx.classes.filters.show_diedges
82
+ f = factory([(1, 2), (3, 4)])
83
+ assert f(1, 2)
84
+ assert f(3, 4)
85
+ assert not f(4, 3)
86
+ assert not f(2, 3)
87
+ assert not f(0, -1)
88
+ assert not f("a", "b")
89
+ pytest.raises(TypeError, f, 1, 2, 3)
90
+ pytest.raises(TypeError, f, 1)
91
+ pytest.raises(TypeError, f)
92
+ pytest.raises(TypeError, factory, [1, 2, 3])
93
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
94
+
95
+ def test_hide_multiedges(self):
96
+ factory = nx.classes.filters.hide_multiedges
97
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
98
+ assert not f(1, 2, 0)
99
+ assert not f(1, 2, 1)
100
+ assert f(1, 2, 2)
101
+ assert f(3, 4, 0)
102
+ assert not f(3, 4, 1)
103
+ assert not f(4, 3, 1)
104
+ assert f(4, 3, 0)
105
+ assert f(2, 3, 0)
106
+ assert f(0, -1, 0)
107
+ assert f("a", "b", 0)
108
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
109
+ pytest.raises(TypeError, f, 1, 2)
110
+ pytest.raises(TypeError, f, 1)
111
+ pytest.raises(TypeError, f)
112
+ pytest.raises(TypeError, factory, [1, 2, 3])
113
+ pytest.raises(ValueError, factory, [(1, 2)])
114
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
115
+
116
+ def test_show_multiedges(self):
117
+ factory = nx.classes.filters.show_multiedges
118
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
119
+ assert f(1, 2, 0)
120
+ assert f(1, 2, 1)
121
+ assert not f(1, 2, 2)
122
+ assert not f(3, 4, 0)
123
+ assert f(3, 4, 1)
124
+ assert f(4, 3, 1)
125
+ assert not f(4, 3, 0)
126
+ assert not f(2, 3, 0)
127
+ assert not f(0, -1, 0)
128
+ assert not f("a", "b", 0)
129
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
130
+ pytest.raises(TypeError, f, 1, 2)
131
+ pytest.raises(TypeError, f, 1)
132
+ pytest.raises(TypeError, f)
133
+ pytest.raises(TypeError, factory, [1, 2, 3])
134
+ pytest.raises(ValueError, factory, [(1, 2)])
135
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
136
+
137
+ def test_hide_multidiedges(self):
138
+ factory = nx.classes.filters.hide_multidiedges
139
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
140
+ assert not f(1, 2, 0)
141
+ assert not f(1, 2, 1)
142
+ assert f(1, 2, 2)
143
+ assert f(3, 4, 0)
144
+ assert not f(3, 4, 1)
145
+ assert f(4, 3, 1)
146
+ assert f(4, 3, 0)
147
+ assert f(2, 3, 0)
148
+ assert f(0, -1, 0)
149
+ assert f("a", "b", 0)
150
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
151
+ pytest.raises(TypeError, f, 1, 2)
152
+ pytest.raises(TypeError, f, 1)
153
+ pytest.raises(TypeError, f)
154
+ pytest.raises(TypeError, factory, [1, 2, 3])
155
+ pytest.raises(ValueError, factory, [(1, 2)])
156
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
157
+
158
+ def test_show_multidiedges(self):
159
+ factory = nx.classes.filters.show_multidiedges
160
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
161
+ assert f(1, 2, 0)
162
+ assert f(1, 2, 1)
163
+ assert not f(1, 2, 2)
164
+ assert not f(3, 4, 0)
165
+ assert f(3, 4, 1)
166
+ assert not f(4, 3, 1)
167
+ assert not f(4, 3, 0)
168
+ assert not f(2, 3, 0)
169
+ assert not f(0, -1, 0)
170
+ assert not f("a", "b", 0)
171
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
172
+ pytest.raises(TypeError, f, 1, 2)
173
+ pytest.raises(TypeError, f, 1)
174
+ pytest.raises(TypeError, f)
175
+ pytest.raises(TypeError, factory, [1, 2, 3])
176
+ pytest.raises(ValueError, factory, [(1, 2)])
177
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_graph_historical.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Original NetworkX graph tests"""
2
+
3
+ import networkx
4
+ import networkx as nx
5
+
6
+ from .historical_tests import HistoricalTests
7
+
8
+
9
+ class TestGraphHistorical(HistoricalTests):
10
+ @classmethod
11
+ def setup_class(cls):
12
+ HistoricalTests.setup_class()
13
+ cls.G = nx.Graph
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_multidigraph.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import UserDict
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal
7
+
8
+ from .test_multigraph import BaseMultiGraphTester
9
+ from .test_multigraph import TestEdgeSubgraph as _TestMultiGraphEdgeSubgraph
10
+ from .test_multigraph import TestMultiGraph as _TestMultiGraph
11
+
12
+
13
+ class BaseMultiDiGraphTester(BaseMultiGraphTester):
14
+ def test_edges(self):
15
+ G = self.K3
16
+ edges = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
17
+ assert sorted(G.edges()) == edges
18
+ assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
19
+ pytest.raises((KeyError, nx.NetworkXError), G.edges, -1)
20
+
21
+ def test_edges_data(self):
22
+ G = self.K3
23
+ edges = [(0, 1, {}), (0, 2, {}), (1, 0, {}), (1, 2, {}), (2, 0, {}), (2, 1, {})]
24
+ assert sorted(G.edges(data=True)) == edges
25
+ assert sorted(G.edges(0, data=True)) == [(0, 1, {}), (0, 2, {})]
26
+ pytest.raises((KeyError, nx.NetworkXError), G.neighbors, -1)
27
+
28
+ def test_edges_multi(self):
29
+ G = self.K3
30
+ assert sorted(G.edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
31
+ assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
32
+ G.add_edge(0, 1)
33
+ assert sorted(G.edges()) == [
34
+ (0, 1),
35
+ (0, 1),
36
+ (0, 2),
37
+ (1, 0),
38
+ (1, 2),
39
+ (2, 0),
40
+ (2, 1),
41
+ ]
42
+
43
+ def test_out_edges(self):
44
+ G = self.K3
45
+ assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
46
+ assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
47
+ pytest.raises((KeyError, nx.NetworkXError), G.out_edges, -1)
48
+ assert sorted(G.out_edges(0, keys=True)) == [(0, 1, 0), (0, 2, 0)]
49
+
50
+ def test_out_edges_multi(self):
51
+ G = self.K3
52
+ assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
53
+ assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
54
+ G.add_edge(0, 1, 2)
55
+ assert sorted(G.out_edges()) == [
56
+ (0, 1),
57
+ (0, 1),
58
+ (0, 2),
59
+ (1, 0),
60
+ (1, 2),
61
+ (2, 0),
62
+ (2, 1),
63
+ ]
64
+
65
+ def test_out_edges_data(self):
66
+ G = self.K3
67
+ assert sorted(G.edges(0, data=True)) == [(0, 1, {}), (0, 2, {})]
68
+ G.remove_edge(0, 1)
69
+ G.add_edge(0, 1, data=1)
70
+ assert sorted(G.edges(0, data=True)) == [(0, 1, {"data": 1}), (0, 2, {})]
71
+ assert sorted(G.edges(0, data="data")) == [(0, 1, 1), (0, 2, None)]
72
+ assert sorted(G.edges(0, data="data", default=-1)) == [(0, 1, 1), (0, 2, -1)]
73
+
74
+ def test_in_edges(self):
75
+ G = self.K3
76
+ assert sorted(G.in_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
77
+ assert sorted(G.in_edges(0)) == [(1, 0), (2, 0)]
78
+ pytest.raises((KeyError, nx.NetworkXError), G.in_edges, -1)
79
+ G.add_edge(0, 1, 2)
80
+ assert sorted(G.in_edges()) == [
81
+ (0, 1),
82
+ (0, 1),
83
+ (0, 2),
84
+ (1, 0),
85
+ (1, 2),
86
+ (2, 0),
87
+ (2, 1),
88
+ ]
89
+ assert sorted(G.in_edges(0, keys=True)) == [(1, 0, 0), (2, 0, 0)]
90
+
91
+ def test_in_edges_no_keys(self):
92
+ G = self.K3
93
+ assert sorted(G.in_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
94
+ assert sorted(G.in_edges(0)) == [(1, 0), (2, 0)]
95
+ G.add_edge(0, 1, 2)
96
+ assert sorted(G.in_edges()) == [
97
+ (0, 1),
98
+ (0, 1),
99
+ (0, 2),
100
+ (1, 0),
101
+ (1, 2),
102
+ (2, 0),
103
+ (2, 1),
104
+ ]
105
+
106
+ assert sorted(G.in_edges(data=True, keys=False)) == [
107
+ (0, 1, {}),
108
+ (0, 1, {}),
109
+ (0, 2, {}),
110
+ (1, 0, {}),
111
+ (1, 2, {}),
112
+ (2, 0, {}),
113
+ (2, 1, {}),
114
+ ]
115
+
116
+ def test_in_edges_data(self):
117
+ G = self.K3
118
+ assert sorted(G.in_edges(0, data=True)) == [(1, 0, {}), (2, 0, {})]
119
+ G.remove_edge(1, 0)
120
+ G.add_edge(1, 0, data=1)
121
+ assert sorted(G.in_edges(0, data=True)) == [(1, 0, {"data": 1}), (2, 0, {})]
122
+ assert sorted(G.in_edges(0, data="data")) == [(1, 0, 1), (2, 0, None)]
123
+ assert sorted(G.in_edges(0, data="data", default=-1)) == [(1, 0, 1), (2, 0, -1)]
124
+
125
+ def is_shallow(self, H, G):
126
+ # graph
127
+ assert G.graph["foo"] == H.graph["foo"]
128
+ G.graph["foo"].append(1)
129
+ assert G.graph["foo"] == H.graph["foo"]
130
+ # node
131
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
132
+ G.nodes[0]["foo"].append(1)
133
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
134
+ # edge
135
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
136
+ G[1][2][0]["foo"].append(1)
137
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
138
+
139
+ def is_deep(self, H, G):
140
+ # graph
141
+ assert G.graph["foo"] == H.graph["foo"]
142
+ G.graph["foo"].append(1)
143
+ assert G.graph["foo"] != H.graph["foo"]
144
+ # node
145
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
146
+ G.nodes[0]["foo"].append(1)
147
+ assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
148
+ # edge
149
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
150
+ G[1][2][0]["foo"].append(1)
151
+ assert G[1][2][0]["foo"] != H[1][2][0]["foo"]
152
+
153
+ def test_to_undirected(self):
154
+ # MultiDiGraph -> MultiGraph changes number of edges so it is
155
+ # not a copy operation... use is_shallow, not is_shallow_copy
156
+ G = self.K3
157
+ self.add_attributes(G)
158
+ H = nx.MultiGraph(G)
159
+ # self.is_shallow(H,G)
160
+ # the result is traversal order dependent so we
161
+ # can't use the is_shallow() test here.
162
+ try:
163
+ assert edges_equal(H.edges(), [(0, 1), (1, 2), (2, 0)])
164
+ except AssertionError:
165
+ assert edges_equal(H.edges(), [(0, 1), (1, 2), (1, 2), (2, 0)])
166
+ H = G.to_undirected()
167
+ self.is_deep(H, G)
168
+
169
+ def test_has_successor(self):
170
+ G = self.K3
171
+ assert G.has_successor(0, 1)
172
+ assert not G.has_successor(0, -1)
173
+
174
+ def test_successors(self):
175
+ G = self.K3
176
+ assert sorted(G.successors(0)) == [1, 2]
177
+ pytest.raises((KeyError, nx.NetworkXError), G.successors, -1)
178
+
179
+ def test_has_predecessor(self):
180
+ G = self.K3
181
+ assert G.has_predecessor(0, 1)
182
+ assert not G.has_predecessor(0, -1)
183
+
184
+ def test_predecessors(self):
185
+ G = self.K3
186
+ assert sorted(G.predecessors(0)) == [1, 2]
187
+ pytest.raises((KeyError, nx.NetworkXError), G.predecessors, -1)
188
+
189
+ def test_degree(self):
190
+ G = self.K3
191
+ assert sorted(G.degree()) == [(0, 4), (1, 4), (2, 4)]
192
+ assert dict(G.degree()) == {0: 4, 1: 4, 2: 4}
193
+ assert G.degree(0) == 4
194
+ assert list(G.degree(iter([0]))) == [(0, 4)]
195
+ G.add_edge(0, 1, weight=0.3, other=1.2)
196
+ assert sorted(G.degree(weight="weight")) == [(0, 4.3), (1, 4.3), (2, 4)]
197
+ assert sorted(G.degree(weight="other")) == [(0, 5.2), (1, 5.2), (2, 4)]
198
+
199
+ def test_in_degree(self):
200
+ G = self.K3
201
+ assert sorted(G.in_degree()) == [(0, 2), (1, 2), (2, 2)]
202
+ assert dict(G.in_degree()) == {0: 2, 1: 2, 2: 2}
203
+ assert G.in_degree(0) == 2
204
+ assert list(G.in_degree(iter([0]))) == [(0, 2)]
205
+ assert G.in_degree(0, weight="weight") == 2
206
+
207
+ def test_out_degree(self):
208
+ G = self.K3
209
+ assert sorted(G.out_degree()) == [(0, 2), (1, 2), (2, 2)]
210
+ assert dict(G.out_degree()) == {0: 2, 1: 2, 2: 2}
211
+ assert G.out_degree(0) == 2
212
+ assert list(G.out_degree(iter([0]))) == [(0, 2)]
213
+ assert G.out_degree(0, weight="weight") == 2
214
+
215
+ def test_size(self):
216
+ G = self.K3
217
+ assert G.size() == 6
218
+ assert G.number_of_edges() == 6
219
+ G.add_edge(0, 1, weight=0.3, other=1.2)
220
+ assert round(G.size(weight="weight"), 2) == 6.3
221
+ assert round(G.size(weight="other"), 2) == 7.2
222
+
223
+ def test_to_undirected_reciprocal(self):
224
+ G = self.Graph()
225
+ G.add_edge(1, 2)
226
+ assert G.to_undirected().has_edge(1, 2)
227
+ assert not G.to_undirected(reciprocal=True).has_edge(1, 2)
228
+ G.add_edge(2, 1)
229
+ assert G.to_undirected(reciprocal=True).has_edge(1, 2)
230
+
231
+ def test_reverse_copy(self):
232
+ G = nx.MultiDiGraph([(0, 1), (0, 1)])
233
+ R = G.reverse()
234
+ assert sorted(R.edges()) == [(1, 0), (1, 0)]
235
+ R.remove_edge(1, 0)
236
+ assert sorted(R.edges()) == [(1, 0)]
237
+ assert sorted(G.edges()) == [(0, 1), (0, 1)]
238
+
239
+ def test_reverse_nocopy(self):
240
+ G = nx.MultiDiGraph([(0, 1), (0, 1)])
241
+ R = G.reverse(copy=False)
242
+ assert sorted(R.edges()) == [(1, 0), (1, 0)]
243
+ pytest.raises(nx.NetworkXError, R.remove_edge, 1, 0)
244
+
245
+ def test_di_attributes_cached(self):
246
+ G = self.K3.copy()
247
+ assert id(G.in_edges) == id(G.in_edges)
248
+ assert id(G.out_edges) == id(G.out_edges)
249
+ assert id(G.in_degree) == id(G.in_degree)
250
+ assert id(G.out_degree) == id(G.out_degree)
251
+ assert id(G.succ) == id(G.succ)
252
+ assert id(G.pred) == id(G.pred)
253
+
254
+
255
+ class TestMultiDiGraph(BaseMultiDiGraphTester, _TestMultiGraph):
256
+ def setup_method(self):
257
+ self.Graph = nx.MultiDiGraph
258
+ # build K3
259
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
260
+ self.k3nodes = [0, 1, 2]
261
+ self.K3 = self.Graph()
262
+ self.K3._succ = {0: {}, 1: {}, 2: {}}
263
+ # K3._adj is synced with K3._succ
264
+ self.K3._pred = {0: {}, 1: {}, 2: {}}
265
+ for u in self.k3nodes:
266
+ for v in self.k3nodes:
267
+ if u == v:
268
+ continue
269
+ d = {0: {}}
270
+ self.K3._succ[u][v] = d
271
+ self.K3._pred[v][u] = d
272
+ self.K3._node = {}
273
+ self.K3._node[0] = {}
274
+ self.K3._node[1] = {}
275
+ self.K3._node[2] = {}
276
+
277
+ def test_add_edge(self):
278
+ G = self.Graph()
279
+ G.add_edge(0, 1)
280
+ assert G._adj == {0: {1: {0: {}}}, 1: {}}
281
+ assert G._succ == {0: {1: {0: {}}}, 1: {}}
282
+ assert G._pred == {0: {}, 1: {0: {0: {}}}}
283
+ G = self.Graph()
284
+ G.add_edge(*(0, 1))
285
+ assert G._adj == {0: {1: {0: {}}}, 1: {}}
286
+ assert G._succ == {0: {1: {0: {}}}, 1: {}}
287
+ assert G._pred == {0: {}, 1: {0: {0: {}}}}
288
+ with pytest.raises(ValueError, match="None cannot be a node"):
289
+ G.add_edge(None, 3)
290
+
291
+ def test_add_edges_from(self):
292
+ G = self.Graph()
293
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})])
294
+ assert G._adj == {0: {1: {0: {}, 1: {"weight": 3}}}, 1: {}}
295
+ assert G._succ == {0: {1: {0: {}, 1: {"weight": 3}}}, 1: {}}
296
+ assert G._pred == {0: {}, 1: {0: {0: {}, 1: {"weight": 3}}}}
297
+
298
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})], weight=2)
299
+ assert G._succ == {
300
+ 0: {1: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
301
+ 1: {},
302
+ }
303
+ assert G._pred == {
304
+ 0: {},
305
+ 1: {0: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
306
+ }
307
+
308
+ G = self.Graph()
309
+ edges = [
310
+ (0, 1, {"weight": 3}),
311
+ (0, 1, (("weight", 2),)),
312
+ (0, 1, 5),
313
+ (0, 1, "s"),
314
+ ]
315
+ G.add_edges_from(edges)
316
+ keydict = {0: {"weight": 3}, 1: {"weight": 2}, 5: {}, "s": {}}
317
+ assert G._succ == {0: {1: keydict}, 1: {}}
318
+ assert G._pred == {1: {0: keydict}, 0: {}}
319
+
320
+ # too few in tuple
321
+ pytest.raises(nx.NetworkXError, G.add_edges_from, [(0,)])
322
+ # too many in tuple
323
+ pytest.raises(nx.NetworkXError, G.add_edges_from, [(0, 1, 2, 3, 4)])
324
+ # not a tuple
325
+ pytest.raises(TypeError, G.add_edges_from, [0])
326
+ with pytest.raises(ValueError, match="None cannot be a node"):
327
+ G.add_edges_from([(None, 3), (3, 2)])
328
+
329
+ def test_remove_edge(self):
330
+ G = self.K3
331
+ G.remove_edge(0, 1)
332
+ assert G._succ == {
333
+ 0: {2: {0: {}}},
334
+ 1: {0: {0: {}}, 2: {0: {}}},
335
+ 2: {0: {0: {}}, 1: {0: {}}},
336
+ }
337
+ assert G._pred == {
338
+ 0: {1: {0: {}}, 2: {0: {}}},
339
+ 1: {2: {0: {}}},
340
+ 2: {0: {0: {}}, 1: {0: {}}},
341
+ }
342
+ pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
343
+ pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, 0, 2, key=1)
344
+
345
+ def test_remove_multiedge(self):
346
+ G = self.K3
347
+ G.add_edge(0, 1, key="parallel edge")
348
+ G.remove_edge(0, 1, key="parallel edge")
349
+ assert G._adj == {
350
+ 0: {1: {0: {}}, 2: {0: {}}},
351
+ 1: {0: {0: {}}, 2: {0: {}}},
352
+ 2: {0: {0: {}}, 1: {0: {}}},
353
+ }
354
+
355
+ assert G._succ == {
356
+ 0: {1: {0: {}}, 2: {0: {}}},
357
+ 1: {0: {0: {}}, 2: {0: {}}},
358
+ 2: {0: {0: {}}, 1: {0: {}}},
359
+ }
360
+
361
+ assert G._pred == {
362
+ 0: {1: {0: {}}, 2: {0: {}}},
363
+ 1: {0: {0: {}}, 2: {0: {}}},
364
+ 2: {0: {0: {}}, 1: {0: {}}},
365
+ }
366
+ G.remove_edge(0, 1)
367
+ assert G._succ == {
368
+ 0: {2: {0: {}}},
369
+ 1: {0: {0: {}}, 2: {0: {}}},
370
+ 2: {0: {0: {}}, 1: {0: {}}},
371
+ }
372
+ assert G._pred == {
373
+ 0: {1: {0: {}}, 2: {0: {}}},
374
+ 1: {2: {0: {}}},
375
+ 2: {0: {0: {}}, 1: {0: {}}},
376
+ }
377
+ pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
378
+
379
+ def test_remove_edges_from(self):
380
+ G = self.K3
381
+ G.remove_edges_from([(0, 1)])
382
+ assert G._succ == {
383
+ 0: {2: {0: {}}},
384
+ 1: {0: {0: {}}, 2: {0: {}}},
385
+ 2: {0: {0: {}}, 1: {0: {}}},
386
+ }
387
+ assert G._pred == {
388
+ 0: {1: {0: {}}, 2: {0: {}}},
389
+ 1: {2: {0: {}}},
390
+ 2: {0: {0: {}}, 1: {0: {}}},
391
+ }
392
+ G.remove_edges_from([(0, 0)]) # silent fail
393
+
394
+
395
+ class TestEdgeSubgraph(_TestMultiGraphEdgeSubgraph):
396
+ """Unit tests for the :meth:`MultiDiGraph.edge_subgraph` method."""
397
+
398
+ def setup_method(self):
399
+ # Create a quadruply-linked path graph on five nodes.
400
+ G = nx.MultiDiGraph()
401
+ nx.add_path(G, range(5))
402
+ nx.add_path(G, range(5))
403
+ nx.add_path(G, reversed(range(5)))
404
+ nx.add_path(G, reversed(range(5)))
405
+ # Add some node, edge, and graph attributes.
406
+ for i in range(5):
407
+ G.nodes[i]["name"] = f"node{i}"
408
+ G.adj[0][1][0]["name"] = "edge010"
409
+ G.adj[0][1][1]["name"] = "edge011"
410
+ G.adj[3][4][0]["name"] = "edge340"
411
+ G.adj[3][4][1]["name"] = "edge341"
412
+ G.graph["name"] = "graph"
413
+ # Get the subgraph induced by one of the first edges and one of
414
+ # the last edges.
415
+ self.G = G
416
+ self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)])
417
+
418
+
419
+ class CustomDictClass(UserDict):
420
+ pass
421
+
422
+
423
+ class MultiDiGraphSubClass(nx.MultiDiGraph):
424
+ node_dict_factory = CustomDictClass # type: ignore[assignment]
425
+ node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
426
+ adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
427
+ adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignment]
428
+ edge_key_dict_factory = CustomDictClass # type: ignore[assignment]
429
+ edge_attr_dict_factory = CustomDictClass # type: ignore[assignment]
430
+ graph_attr_dict_factory = CustomDictClass # type: ignore[assignment]
431
+
432
+
433
+ class TestMultiDiGraphSubclass(TestMultiDiGraph):
434
+ def setup_method(self):
435
+ self.Graph = MultiDiGraphSubClass
436
+ # build K3
437
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
438
+ self.k3nodes = [0, 1, 2]
439
+ self.K3 = self.Graph()
440
+ self.K3._succ = self.K3.adjlist_outer_dict_factory(
441
+ {
442
+ 0: self.K3.adjlist_inner_dict_factory(),
443
+ 1: self.K3.adjlist_inner_dict_factory(),
444
+ 2: self.K3.adjlist_inner_dict_factory(),
445
+ }
446
+ )
447
+ # K3._adj is synced with K3._succ
448
+ self.K3._pred = {0: {}, 1: {}, 2: {}}
449
+ for u in self.k3nodes:
450
+ for v in self.k3nodes:
451
+ if u == v:
452
+ continue
453
+ d = {0: {}}
454
+ self.K3._succ[u][v] = d
455
+ self.K3._pred[v][u] = d
456
+ self.K3._node = self.K3.node_dict_factory()
457
+ self.K3._node[0] = self.K3.node_attr_dict_factory()
458
+ self.K3._node[1] = self.K3.node_attr_dict_factory()
459
+ self.K3._node[2] = self.K3.node_attr_dict_factory()
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_multigraph.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import UserDict
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal
7
+
8
+ from .test_graph import BaseAttrGraphTester
9
+ from .test_graph import TestGraph as _TestGraph
10
+
11
+
12
+ class BaseMultiGraphTester(BaseAttrGraphTester):
13
+ def test_has_edge(self):
14
+ G = self.K3
15
+ assert G.has_edge(0, 1)
16
+ assert not G.has_edge(0, -1)
17
+ assert G.has_edge(0, 1, 0)
18
+ assert not G.has_edge(0, 1, 1)
19
+
20
+ def test_get_edge_data(self):
21
+ G = self.K3
22
+ assert G.get_edge_data(0, 1) == {0: {}}
23
+ assert G[0][1] == {0: {}}
24
+ assert G[0][1][0] == {}
25
+ assert G.get_edge_data(10, 20) is None
26
+ assert G.get_edge_data(0, 1, 0) == {}
27
+
28
+ def test_adjacency(self):
29
+ G = self.K3
30
+ assert dict(G.adjacency()) == {
31
+ 0: {1: {0: {}}, 2: {0: {}}},
32
+ 1: {0: {0: {}}, 2: {0: {}}},
33
+ 2: {0: {0: {}}, 1: {0: {}}},
34
+ }
35
+
36
+ def deepcopy_edge_attr(self, H, G):
37
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
38
+ G[1][2][0]["foo"].append(1)
39
+ assert G[1][2][0]["foo"] != H[1][2][0]["foo"]
40
+
41
+ def shallow_copy_edge_attr(self, H, G):
42
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
43
+ G[1][2][0]["foo"].append(1)
44
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
45
+
46
+ def graphs_equal(self, H, G):
47
+ assert G._adj == H._adj
48
+ assert G._node == H._node
49
+ assert G.graph == H.graph
50
+ assert G.name == H.name
51
+ if not G.is_directed() and not H.is_directed():
52
+ assert H._adj[1][2][0] is H._adj[2][1][0]
53
+ assert G._adj[1][2][0] is G._adj[2][1][0]
54
+ else: # at least one is directed
55
+ if not G.is_directed():
56
+ G._pred = G._adj
57
+ G._succ = G._adj
58
+ if not H.is_directed():
59
+ H._pred = H._adj
60
+ H._succ = H._adj
61
+ assert G._pred == H._pred
62
+ assert G._succ == H._succ
63
+ assert H._succ[1][2][0] is H._pred[2][1][0]
64
+ assert G._succ[1][2][0] is G._pred[2][1][0]
65
+
66
+ def same_attrdict(self, H, G):
67
+ # same attrdict in the edgedata
68
+ old_foo = H[1][2][0]["foo"]
69
+ H.adj[1][2][0]["foo"] = "baz"
70
+ assert G._adj == H._adj
71
+ H.adj[1][2][0]["foo"] = old_foo
72
+ assert G._adj == H._adj
73
+
74
+ old_foo = H.nodes[0]["foo"]
75
+ H.nodes[0]["foo"] = "baz"
76
+ assert G._node == H._node
77
+ H.nodes[0]["foo"] = old_foo
78
+ assert G._node == H._node
79
+
80
+ def different_attrdict(self, H, G):
81
+ # used by graph_equal_but_different
82
+ old_foo = H[1][2][0]["foo"]
83
+ H.adj[1][2][0]["foo"] = "baz"
84
+ assert G._adj != H._adj
85
+ H.adj[1][2][0]["foo"] = old_foo
86
+ assert G._adj == H._adj
87
+
88
+ old_foo = H.nodes[0]["foo"]
89
+ H.nodes[0]["foo"] = "baz"
90
+ assert G._node != H._node
91
+ H.nodes[0]["foo"] = old_foo
92
+ assert G._node == H._node
93
+
94
+ def test_to_undirected(self):
95
+ G = self.K3
96
+ self.add_attributes(G)
97
+ H = nx.MultiGraph(G)
98
+ self.is_shallow_copy(H, G)
99
+ H = G.to_undirected()
100
+ self.is_deepcopy(H, G)
101
+
102
+ def test_to_directed(self):
103
+ G = self.K3
104
+ self.add_attributes(G)
105
+ H = nx.MultiDiGraph(G)
106
+ self.is_shallow_copy(H, G)
107
+ H = G.to_directed()
108
+ self.is_deepcopy(H, G)
109
+
110
+ def test_number_of_edges_selfloops(self):
111
+ G = self.K3
112
+ G.add_edge(0, 0)
113
+ G.add_edge(0, 0)
114
+ G.add_edge(0, 0, key="parallel edge")
115
+ G.remove_edge(0, 0, key="parallel edge")
116
+ assert G.number_of_edges(0, 0) == 2
117
+ G.remove_edge(0, 0)
118
+ assert G.number_of_edges(0, 0) == 1
119
+
120
+ def test_edge_lookup(self):
121
+ G = self.Graph()
122
+ G.add_edge(1, 2, foo="bar")
123
+ G.add_edge(1, 2, "key", foo="biz")
124
+ assert edges_equal(G.edges[1, 2, 0], {"foo": "bar"})
125
+ assert edges_equal(G.edges[1, 2, "key"], {"foo": "biz"})
126
+
127
+ def test_edge_attr(self):
128
+ G = self.Graph()
129
+ G.add_edge(1, 2, key="k1", foo="bar")
130
+ G.add_edge(1, 2, key="k2", foo="baz")
131
+ assert isinstance(G.get_edge_data(1, 2), G.edge_key_dict_factory)
132
+ assert all(
133
+ isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True)
134
+ )
135
+ assert edges_equal(
136
+ G.edges(keys=True, data=True),
137
+ [(1, 2, "k1", {"foo": "bar"}), (1, 2, "k2", {"foo": "baz"})],
138
+ )
139
+ assert edges_equal(
140
+ G.edges(keys=True, data="foo"), [(1, 2, "k1", "bar"), (1, 2, "k2", "baz")]
141
+ )
142
+
143
+ def test_edge_attr4(self):
144
+ G = self.Graph()
145
+ G.add_edge(1, 2, key=0, data=7, spam="bar", bar="foo")
146
+ assert edges_equal(
147
+ G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
148
+ )
149
+ G[1][2][0]["data"] = 10 # OK to set data like this
150
+ assert edges_equal(
151
+ G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
152
+ )
153
+
154
+ G.adj[1][2][0]["data"] = 20
155
+ assert edges_equal(
156
+ G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
157
+ )
158
+ G.edges[1, 2, 0]["data"] = 21 # another spelling, "edge"
159
+ assert edges_equal(
160
+ G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
161
+ )
162
+ G.adj[1][2][0]["listdata"] = [20, 200]
163
+ G.adj[1][2][0]["weight"] = 20
164
+ assert edges_equal(
165
+ G.edges(data=True),
166
+ [
167
+ (
168
+ 1,
169
+ 2,
170
+ {
171
+ "data": 21,
172
+ "spam": "bar",
173
+ "bar": "foo",
174
+ "listdata": [20, 200],
175
+ "weight": 20,
176
+ },
177
+ )
178
+ ],
179
+ )
180
+
181
+
182
+ class TestMultiGraph(BaseMultiGraphTester, _TestGraph):
183
+ def setup_method(self):
184
+ self.Graph = nx.MultiGraph
185
+ # build K3
186
+ ed1, ed2, ed3 = ({0: {}}, {0: {}}, {0: {}})
187
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
188
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
189
+ self.k3nodes = [0, 1, 2]
190
+ self.K3 = self.Graph()
191
+ self.K3._adj = self.k3adj
192
+ self.K3._node = {}
193
+ self.K3._node[0] = {}
194
+ self.K3._node[1] = {}
195
+ self.K3._node[2] = {}
196
+
197
+ def test_data_input(self):
198
+ G = self.Graph({1: [2], 2: [1]}, name="test")
199
+ assert G.name == "test"
200
+ expected = [(1, {2: {0: {}}}), (2, {1: {0: {}}})]
201
+ assert sorted(G.adj.items()) == expected
202
+
203
+ def test_data_multigraph_input(self):
204
+ # standard case with edge keys and edge data
205
+ edata0 = {"w": 200, "s": "foo"}
206
+ edata1 = {"w": 201, "s": "bar"}
207
+ keydict = {0: edata0, 1: edata1}
208
+ dododod = {"a": {"b": keydict}}
209
+
210
+ multiple_edge = [("a", "b", 0, edata0), ("a", "b", 1, edata1)]
211
+ single_edge = [("a", "b", 0, keydict)]
212
+
213
+ G = self.Graph(dododod, multigraph_input=True)
214
+ assert list(G.edges(keys=True, data=True)) == multiple_edge
215
+ G = self.Graph(dododod, multigraph_input=None)
216
+ assert list(G.edges(keys=True, data=True)) == multiple_edge
217
+ G = self.Graph(dododod, multigraph_input=False)
218
+ assert list(G.edges(keys=True, data=True)) == single_edge
219
+
220
+ # test round-trip to_dict_of_dict and MultiGraph constructor
221
+ G = self.Graph(dododod, multigraph_input=True)
222
+ H = self.Graph(nx.to_dict_of_dicts(G))
223
+ assert nx.is_isomorphic(G, H) is True # test that default is True
224
+ for mgi in [True, False]:
225
+ H = self.Graph(nx.to_dict_of_dicts(G), multigraph_input=mgi)
226
+ assert nx.is_isomorphic(G, H) == mgi
227
+
228
+ # Set up cases for when incoming_graph_data is not multigraph_input
229
+ etraits = {"w": 200, "s": "foo"}
230
+ egraphics = {"color": "blue", "shape": "box"}
231
+ edata = {"traits": etraits, "graphics": egraphics}
232
+ dodod1 = {"a": {"b": edata}}
233
+ dodod2 = {"a": {"b": etraits}}
234
+ dodod3 = {"a": {"b": {"traits": etraits, "s": "foo"}}}
235
+ dol = {"a": ["b"]}
236
+
237
+ multiple_edge = [("a", "b", "traits", etraits), ("a", "b", "graphics", egraphics)]
238
+ single_edge = [("a", "b", 0, {})] # type: ignore[var-annotated]
239
+ single_edge1 = [("a", "b", 0, edata)]
240
+ single_edge2 = [("a", "b", 0, etraits)]
241
+ single_edge3 = [("a", "b", 0, {"traits": etraits, "s": "foo"})]
242
+
243
+ cases = [ # (dod, mgi, edges)
244
+ (dodod1, True, multiple_edge),
245
+ (dodod1, False, single_edge1),
246
+ (dodod2, False, single_edge2),
247
+ (dodod3, False, single_edge3),
248
+ (dol, False, single_edge),
249
+ ]
250
+
251
+ @pytest.mark.parametrize("dod, mgi, edges", cases)
252
+ def test_non_multigraph_input(self, dod, mgi, edges):
253
+ G = self.Graph(dod, multigraph_input=mgi)
254
+ assert list(G.edges(keys=True, data=True)) == edges
255
+ G = nx.to_networkx_graph(dod, create_using=self.Graph, multigraph_input=mgi)
256
+ assert list(G.edges(keys=True, data=True)) == edges
257
+
258
+ mgi_none_cases = [
259
+ (dodod1, multiple_edge),
260
+ (dodod2, single_edge2),
261
+ (dodod3, single_edge3),
262
+ ]
263
+
264
+ @pytest.mark.parametrize("dod, edges", mgi_none_cases)
265
+ def test_non_multigraph_input_mgi_none(self, dod, edges):
266
+ # test constructor without to_networkx_graph for mgi=None
267
+ G = self.Graph(dod)
268
+ assert list(G.edges(keys=True, data=True)) == edges
269
+
270
+ raise_cases = [dodod2, dodod3, dol]
271
+
272
+ @pytest.mark.parametrize("dod", raise_cases)
273
+ def test_non_multigraph_input_raise(self, dod):
274
+ # cases where NetworkXError is raised
275
+ pytest.raises(nx.NetworkXError, self.Graph, dod, multigraph_input=True)
276
+ pytest.raises(
277
+ nx.NetworkXError,
278
+ nx.to_networkx_graph,
279
+ dod,
280
+ create_using=self.Graph,
281
+ multigraph_input=True,
282
+ )
283
+
284
+ def test_getitem(self):
285
+ G = self.K3
286
+ assert G[0] == {1: {0: {}}, 2: {0: {}}}
287
+ with pytest.raises(KeyError):
288
+ G.__getitem__("j")
289
+ with pytest.raises(TypeError):
290
+ G.__getitem__(["A"])
291
+
292
+ def test_remove_node(self):
293
+ G = self.K3
294
+ G.remove_node(0)
295
+ assert G.adj == {1: {2: {0: {}}}, 2: {1: {0: {}}}}
296
+ with pytest.raises(nx.NetworkXError):
297
+ G.remove_node(-1)
298
+
299
+ def test_add_edge(self):
300
+ G = self.Graph()
301
+ G.add_edge(0, 1)
302
+ assert G.adj == {0: {1: {0: {}}}, 1: {0: {0: {}}}}
303
+ G = self.Graph()
304
+ G.add_edge(*(0, 1))
305
+ assert G.adj == {0: {1: {0: {}}}, 1: {0: {0: {}}}}
306
+ G = self.Graph()
307
+ with pytest.raises(ValueError):
308
+ G.add_edge(None, "anything")
309
+
310
+ def test_add_edge_conflicting_key(self):
311
+ G = self.Graph()
312
+ G.add_edge(0, 1, key=1)
313
+ G.add_edge(0, 1)
314
+ assert G.number_of_edges() == 2
315
+ G = self.Graph()
316
+ G.add_edges_from([(0, 1, 1, {})])
317
+ G.add_edges_from([(0, 1)])
318
+ assert G.number_of_edges() == 2
319
+
320
+ def test_add_edges_from(self):
321
+ G = self.Graph()
322
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})])
323
+ assert G.adj == {
324
+ 0: {1: {0: {}, 1: {"weight": 3}}},
325
+ 1: {0: {0: {}, 1: {"weight": 3}}},
326
+ }
327
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})], weight=2)
328
+ assert G.adj == {
329
+ 0: {1: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
330
+ 1: {0: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
331
+ }
332
+ G = self.Graph()
333
+ edges = [
334
+ (0, 1, {"weight": 3}),
335
+ (0, 1, (("weight", 2),)),
336
+ (0, 1, 5),
337
+ (0, 1, "s"),
338
+ ]
339
+ G.add_edges_from(edges)
340
+ keydict = {0: {"weight": 3}, 1: {"weight": 2}, 5: {}, "s": {}}
341
+ assert G._adj == {0: {1: keydict}, 1: {0: keydict}}
342
+
343
+ # too few in tuple
344
+ with pytest.raises(nx.NetworkXError):
345
+ G.add_edges_from([(0,)])
346
+ # too many in tuple
347
+ with pytest.raises(nx.NetworkXError):
348
+ G.add_edges_from([(0, 1, 2, 3, 4)])
349
+ # not a tuple
350
+ with pytest.raises(TypeError):
351
+ G.add_edges_from([0])
352
+
353
+ def test_multigraph_add_edges_from_four_tuple_misordered(self):
354
+ """add_edges_from expects 4-tuples of the format (u, v, key, data_dict).
355
+
356
+ Ensure 4-tuples of form (u, v, data_dict, key) raise exception.
357
+ """
358
+ G = nx.MultiGraph()
359
+ with pytest.raises(TypeError):
360
+ # key/data values flipped in 4-tuple
361
+ G.add_edges_from([(0, 1, {"color": "red"}, 0)])
362
+
363
+ def test_remove_edge(self):
364
+ G = self.K3
365
+ G.remove_edge(0, 1)
366
+ assert G.adj == {0: {2: {0: {}}}, 1: {2: {0: {}}}, 2: {0: {0: {}}, 1: {0: {}}}}
367
+
368
+ with pytest.raises(nx.NetworkXError):
369
+ G.remove_edge(-1, 0)
370
+ with pytest.raises(nx.NetworkXError):
371
+ G.remove_edge(0, 2, key=1)
372
+
373
+ def test_remove_edges_from(self):
374
+ G = self.K3.copy()
375
+ G.remove_edges_from([(0, 1)])
376
+ kd = {0: {}}
377
+ assert G.adj == {0: {2: kd}, 1: {2: kd}, 2: {0: kd, 1: kd}}
378
+ G.remove_edges_from([(0, 0)]) # silent fail
379
+ self.K3.add_edge(0, 1)
380
+ G = self.K3.copy()
381
+ G.remove_edges_from(list(G.edges(data=True, keys=True)))
382
+ assert G.adj == {0: {}, 1: {}, 2: {}}
383
+ G = self.K3.copy()
384
+ G.remove_edges_from(list(G.edges(data=False, keys=True)))
385
+ assert G.adj == {0: {}, 1: {}, 2: {}}
386
+ G = self.K3.copy()
387
+ G.remove_edges_from(list(G.edges(data=False, keys=False)))
388
+ assert G.adj == {0: {}, 1: {}, 2: {}}
389
+ G = self.K3.copy()
390
+ G.remove_edges_from([(0, 1, 0), (0, 2, 0, {}), (1, 2)])
391
+ assert G.adj == {0: {1: {1: {}}}, 1: {0: {1: {}}}, 2: {}}
392
+
393
+ def test_remove_multiedge(self):
394
+ G = self.K3
395
+ G.add_edge(0, 1, key="parallel edge")
396
+ G.remove_edge(0, 1, key="parallel edge")
397
+ assert G.adj == {
398
+ 0: {1: {0: {}}, 2: {0: {}}},
399
+ 1: {0: {0: {}}, 2: {0: {}}},
400
+ 2: {0: {0: {}}, 1: {0: {}}},
401
+ }
402
+ G.remove_edge(0, 1)
403
+ kd = {0: {}}
404
+ assert G.adj == {0: {2: kd}, 1: {2: kd}, 2: {0: kd, 1: kd}}
405
+ with pytest.raises(nx.NetworkXError):
406
+ G.remove_edge(-1, 0)
407
+
408
+
409
+ class TestEdgeSubgraph:
410
+ """Unit tests for the :meth:`MultiGraph.edge_subgraph` method."""
411
+
412
+ def setup_method(self):
413
+ # Create a doubly-linked path graph on five nodes.
414
+ G = nx.MultiGraph()
415
+ nx.add_path(G, range(5))
416
+ nx.add_path(G, range(5))
417
+ # Add some node, edge, and graph attributes.
418
+ for i in range(5):
419
+ G.nodes[i]["name"] = f"node{i}"
420
+ G.adj[0][1][0]["name"] = "edge010"
421
+ G.adj[0][1][1]["name"] = "edge011"
422
+ G.adj[3][4][0]["name"] = "edge340"
423
+ G.adj[3][4][1]["name"] = "edge341"
424
+ G.graph["name"] = "graph"
425
+ # Get the subgraph induced by one of the first edges and one of
426
+ # the last edges.
427
+ self.G = G
428
+ self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)])
429
+
430
+ def test_correct_nodes(self):
431
+ """Tests that the subgraph has the correct nodes."""
432
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
433
+
434
+ def test_correct_edges(self):
435
+ """Tests that the subgraph has the correct edges."""
436
+ assert [(0, 1, 0, "edge010"), (3, 4, 1, "edge341")] == sorted(
437
+ self.H.edges(keys=True, data="name")
438
+ )
439
+
440
+ def test_add_node(self):
441
+ """Tests that adding a node to the original graph does not
442
+ affect the nodes of the subgraph.
443
+
444
+ """
445
+ self.G.add_node(5)
446
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
447
+
448
+ def test_remove_node(self):
449
+ """Tests that removing a node in the original graph does
450
+ affect the nodes of the subgraph.
451
+
452
+ """
453
+ self.G.remove_node(0)
454
+ assert [1, 3, 4] == sorted(self.H.nodes())
455
+
456
+ def test_node_attr_dict(self):
457
+ """Tests that the node attribute dictionary of the two graphs is
458
+ the same object.
459
+
460
+ """
461
+ for v in self.H:
462
+ assert self.G.nodes[v] == self.H.nodes[v]
463
+ # Making a change to G should make a change in H and vice versa.
464
+ self.G.nodes[0]["name"] = "foo"
465
+ assert self.G.nodes[0] == self.H.nodes[0]
466
+ self.H.nodes[1]["name"] = "bar"
467
+ assert self.G.nodes[1] == self.H.nodes[1]
468
+
469
+ def test_edge_attr_dict(self):
470
+ """Tests that the edge attribute dictionary of the two graphs is
471
+ the same object.
472
+
473
+ """
474
+ for u, v, k in self.H.edges(keys=True):
475
+ assert self.G._adj[u][v][k] == self.H._adj[u][v][k]
476
+ # Making a change to G should make a change in H and vice versa.
477
+ self.G._adj[0][1][0]["name"] = "foo"
478
+ assert self.G._adj[0][1][0]["name"] == self.H._adj[0][1][0]["name"]
479
+ self.H._adj[3][4][1]["name"] = "bar"
480
+ assert self.G._adj[3][4][1]["name"] == self.H._adj[3][4][1]["name"]
481
+
482
+ def test_graph_attr_dict(self):
483
+ """Tests that the graph attribute dictionary of the two graphs
484
+ is the same object.
485
+
486
+ """
487
+ assert self.G.graph is self.H.graph
488
+
489
+
490
+ class CustomDictClass(UserDict):
491
+ pass
492
+
493
+
494
+ class MultiGraphSubClass(nx.MultiGraph):
495
+ node_dict_factory = CustomDictClass # type: ignore[assignment]
496
+ node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
497
+ adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
498
+ adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignment]
499
+ edge_key_dict_factory = CustomDictClass # type: ignore[assignment]
500
+ edge_attr_dict_factory = CustomDictClass # type: ignore[assignment]
501
+ graph_attr_dict_factory = CustomDictClass # type: ignore[assignment]
502
+
503
+
504
+ class TestMultiGraphSubclass(TestMultiGraph):
505
+ def setup_method(self):
506
+ self.Graph = MultiGraphSubClass
507
+ # build K3
508
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
509
+ self.k3nodes = [0, 1, 2]
510
+ self.K3 = self.Graph()
511
+ self.K3._adj = self.K3.adjlist_outer_dict_factory(
512
+ {
513
+ 0: self.K3.adjlist_inner_dict_factory(),
514
+ 1: self.K3.adjlist_inner_dict_factory(),
515
+ 2: self.K3.adjlist_inner_dict_factory(),
516
+ }
517
+ )
518
+ self.K3._pred = {0: {}, 1: {}, 2: {}}
519
+ for u in self.k3nodes:
520
+ for v in self.k3nodes:
521
+ if u != v:
522
+ d = {0: {}}
523
+ self.K3._adj[u][v] = d
524
+ self.K3._adj[v][u] = d
525
+ self.K3._node = self.K3.node_dict_factory()
526
+ self.K3._node[0] = self.K3.node_attr_dict_factory()
527
+ self.K3._node[1] = self.K3.node_attr_dict_factory()
528
+ self.K3._node[2] = self.K3.node_attr_dict_factory()
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_reportviews.py ADDED
@@ -0,0 +1,1435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from copy import deepcopy
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.classes import reportviews as rv
8
+ from networkx.classes.reportviews import NodeDataView
9
+
10
+
11
+ # Nodes
12
+ class TestNodeView:
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9)
16
+ cls.nv = cls.G.nodes # NodeView(G)
17
+
18
+ def test_pickle(self):
19
+ import pickle
20
+
21
+ nv = self.nv
22
+ pnv = pickle.loads(pickle.dumps(nv, -1))
23
+ assert nv == pnv
24
+ assert nv.__slots__ == pnv.__slots__
25
+
26
+ def test_str(self):
27
+ assert str(self.nv) == "[0, 1, 2, 3, 4, 5, 6, 7, 8]"
28
+
29
+ def test_repr(self):
30
+ assert repr(self.nv) == "NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
31
+
32
+ def test_contains(self):
33
+ G = self.G.copy()
34
+ nv = G.nodes
35
+ assert 7 in nv
36
+ assert 9 not in nv
37
+ G.remove_node(7)
38
+ G.add_node(9)
39
+ assert 7 not in nv
40
+ assert 9 in nv
41
+
42
+ def test_getitem(self):
43
+ G = self.G.copy()
44
+ nv = G.nodes
45
+ G.nodes[3]["foo"] = "bar"
46
+ assert nv[7] == {}
47
+ assert nv[3] == {"foo": "bar"}
48
+ # slicing
49
+ with pytest.raises(nx.NetworkXError):
50
+ G.nodes[0:5]
51
+
52
+ def test_iter(self):
53
+ nv = self.nv
54
+ for i, n in enumerate(nv):
55
+ assert i == n
56
+ inv = iter(nv)
57
+ assert next(inv) == 0
58
+ assert iter(nv) != nv
59
+ assert iter(inv) == inv
60
+ inv2 = iter(nv)
61
+ next(inv2)
62
+ assert list(inv) == list(inv2)
63
+ # odd case where NodeView calls NodeDataView with data=False
64
+ nnv = nv(data=False)
65
+ for i, n in enumerate(nnv):
66
+ assert i == n
67
+
68
+ def test_call(self):
69
+ nodes = self.nv
70
+ assert nodes is nodes()
71
+ assert nodes is not nodes(data=True)
72
+ assert nodes is not nodes(data="weight")
73
+
74
+
75
+ class TestNodeDataView:
76
+ @classmethod
77
+ def setup_class(cls):
78
+ cls.G = nx.path_graph(9)
79
+ cls.nv = NodeDataView(cls.G)
80
+ cls.ndv = cls.G.nodes.data(True)
81
+ cls.nwv = cls.G.nodes.data("foo")
82
+
83
+ def test_viewtype(self):
84
+ nv = self.G.nodes
85
+ ndvfalse = nv.data(False)
86
+ assert nv is ndvfalse
87
+ assert nv is not self.ndv
88
+
89
+ def test_pickle(self):
90
+ import pickle
91
+
92
+ nv = self.nv
93
+ pnv = pickle.loads(pickle.dumps(nv, -1))
94
+ assert nv == pnv
95
+ assert nv.__slots__ == pnv.__slots__
96
+
97
+ def test_str(self):
98
+ msg = str([(n, {}) for n in range(9)])
99
+ assert str(self.ndv) == msg
100
+
101
+ def test_repr(self):
102
+ expected = "NodeDataView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
103
+ assert repr(self.nv) == expected
104
+ expected = (
105
+ "NodeDataView({0: {}, 1: {}, 2: {}, 3: {}, "
106
+ + "4: {}, 5: {}, 6: {}, 7: {}, 8: {}})"
107
+ )
108
+ assert repr(self.ndv) == expected
109
+ expected = (
110
+ "NodeDataView({0: None, 1: None, 2: None, 3: None, 4: None, "
111
+ + "5: None, 6: None, 7: None, 8: None}, data='foo')"
112
+ )
113
+ assert repr(self.nwv) == expected
114
+
115
+ def test_contains(self):
116
+ G = self.G.copy()
117
+ nv = G.nodes.data()
118
+ nwv = G.nodes.data("foo")
119
+ G.nodes[3]["foo"] = "bar"
120
+ assert (7, {}) in nv
121
+ assert (3, {"foo": "bar"}) in nv
122
+ assert (3, "bar") in nwv
123
+ assert (7, None) in nwv
124
+ # default
125
+ nwv_def = G.nodes(data="foo", default="biz")
126
+ assert (7, "biz") in nwv_def
127
+ assert (3, "bar") in nwv_def
128
+
129
+ def test_getitem(self):
130
+ G = self.G.copy()
131
+ nv = G.nodes
132
+ G.nodes[3]["foo"] = "bar"
133
+ assert nv[3] == {"foo": "bar"}
134
+ # default
135
+ nwv_def = G.nodes(data="foo", default="biz")
136
+ assert nwv_def[7], "biz"
137
+ assert nwv_def[3] == "bar"
138
+ # slicing
139
+ with pytest.raises(nx.NetworkXError):
140
+ G.nodes.data()[0:5]
141
+
142
+ def test_iter(self):
143
+ G = self.G.copy()
144
+ nv = G.nodes.data()
145
+ ndv = G.nodes.data(True)
146
+ nwv = G.nodes.data("foo")
147
+ for i, (n, d) in enumerate(nv):
148
+ assert i == n
149
+ assert d == {}
150
+ inv = iter(nv)
151
+ assert next(inv) == (0, {})
152
+ G.nodes[3]["foo"] = "bar"
153
+ # default
154
+ for n, d in nv:
155
+ if n == 3:
156
+ assert d == {"foo": "bar"}
157
+ else:
158
+ assert d == {}
159
+ # data=True
160
+ for n, d in ndv:
161
+ if n == 3:
162
+ assert d == {"foo": "bar"}
163
+ else:
164
+ assert d == {}
165
+ # data='foo'
166
+ for n, d in nwv:
167
+ if n == 3:
168
+ assert d == "bar"
169
+ else:
170
+ assert d is None
171
+ # data='foo', default=1
172
+ for n, d in G.nodes.data("foo", default=1):
173
+ if n == 3:
174
+ assert d == "bar"
175
+ else:
176
+ assert d == 1
177
+
178
+
179
+ def test_nodedataview_unhashable():
180
+ G = nx.path_graph(9)
181
+ G.nodes[3]["foo"] = "bar"
182
+ nvs = [G.nodes.data()]
183
+ nvs.append(G.nodes.data(True))
184
+ H = G.copy()
185
+ H.nodes[4]["foo"] = {1, 2, 3}
186
+ nvs.append(H.nodes.data(True))
187
+ # raise unhashable
188
+ for nv in nvs:
189
+ pytest.raises(TypeError, set, nv)
190
+ pytest.raises(TypeError, eval, "nv | nv", locals())
191
+ # no raise... hashable
192
+ Gn = G.nodes.data(False)
193
+ set(Gn)
194
+ Gn | Gn
195
+ Gn = G.nodes.data("foo")
196
+ set(Gn)
197
+ Gn | Gn
198
+
199
+
200
+ class TestNodeViewSetOps:
201
+ @classmethod
202
+ def setup_class(cls):
203
+ cls.G = nx.path_graph(9)
204
+ cls.G.nodes[3]["foo"] = "bar"
205
+ cls.nv = cls.G.nodes
206
+
207
+ def n_its(self, nodes):
208
+ return set(nodes)
209
+
210
+ def test_len(self):
211
+ G = self.G.copy()
212
+ nv = G.nodes
213
+ assert len(nv) == 9
214
+ G.remove_node(7)
215
+ assert len(nv) == 8
216
+ G.add_node(9)
217
+ assert len(nv) == 9
218
+
219
+ def test_and(self):
220
+ # print("G & H nodes:", gnv & hnv)
221
+ nv = self.nv
222
+ some_nodes = self.n_its(range(5, 12))
223
+ assert nv & some_nodes == self.n_its(range(5, 9))
224
+ assert some_nodes & nv == self.n_its(range(5, 9))
225
+
226
+ def test_or(self):
227
+ # print("G | H nodes:", gnv | hnv)
228
+ nv = self.nv
229
+ some_nodes = self.n_its(range(5, 12))
230
+ assert nv | some_nodes == self.n_its(range(12))
231
+ assert some_nodes | nv == self.n_its(range(12))
232
+
233
+ def test_xor(self):
234
+ # print("G ^ H nodes:", gnv ^ hnv)
235
+ nv = self.nv
236
+ some_nodes = self.n_its(range(5, 12))
237
+ nodes = {0, 1, 2, 3, 4, 9, 10, 11}
238
+ assert nv ^ some_nodes == self.n_its(nodes)
239
+ assert some_nodes ^ nv == self.n_its(nodes)
240
+
241
+ def test_sub(self):
242
+ # print("G - H nodes:", gnv - hnv)
243
+ nv = self.nv
244
+ some_nodes = self.n_its(range(5, 12))
245
+ assert nv - some_nodes == self.n_its(range(5))
246
+ assert some_nodes - nv == self.n_its(range(9, 12))
247
+
248
+
249
+ class TestNodeDataViewSetOps(TestNodeViewSetOps):
250
+ @classmethod
251
+ def setup_class(cls):
252
+ cls.G = nx.path_graph(9)
253
+ cls.G.nodes[3]["foo"] = "bar"
254
+ cls.nv = cls.G.nodes.data("foo")
255
+
256
+ def n_its(self, nodes):
257
+ return {(node, "bar" if node == 3 else None) for node in nodes}
258
+
259
+
260
+ class TestNodeDataViewDefaultSetOps(TestNodeDataViewSetOps):
261
+ @classmethod
262
+ def setup_class(cls):
263
+ cls.G = nx.path_graph(9)
264
+ cls.G.nodes[3]["foo"] = "bar"
265
+ cls.nv = cls.G.nodes.data("foo", default=1)
266
+
267
+ def n_its(self, nodes):
268
+ return {(node, "bar" if node == 3 else 1) for node in nodes}
269
+
270
+
271
+ # Edges Data View
272
+ class TestEdgeDataView:
273
+ @classmethod
274
+ def setup_class(cls):
275
+ cls.G = nx.path_graph(9)
276
+ cls.eview = nx.reportviews.EdgeView
277
+
278
+ def test_pickle(self):
279
+ import pickle
280
+
281
+ ev = self.eview(self.G)(data=True)
282
+ pev = pickle.loads(pickle.dumps(ev, -1))
283
+ assert list(ev) == list(pev)
284
+ assert ev.__slots__ == pev.__slots__
285
+
286
+ def modify_edge(self, G, e, **kwds):
287
+ G._adj[e[0]][e[1]].update(kwds)
288
+
289
+ def test_str(self):
290
+ ev = self.eview(self.G)(data=True)
291
+ rep = str([(n, n + 1, {}) for n in range(8)])
292
+ assert str(ev) == rep
293
+
294
+ def test_repr(self):
295
+ ev = self.eview(self.G)(data=True)
296
+ rep = (
297
+ "EdgeDataView([(0, 1, {}), (1, 2, {}), "
298
+ + "(2, 3, {}), (3, 4, {}), "
299
+ + "(4, 5, {}), (5, 6, {}), "
300
+ + "(6, 7, {}), (7, 8, {})])"
301
+ )
302
+ assert repr(ev) == rep
303
+
304
+ def test_iterdata(self):
305
+ G = self.G.copy()
306
+ evr = self.eview(G)
307
+ ev = evr(data=True)
308
+ ev_def = evr(data="foo", default=1)
309
+
310
+ for u, v, d in ev:
311
+ pass
312
+ assert d == {}
313
+
314
+ for u, v, wt in ev_def:
315
+ pass
316
+ assert wt == 1
317
+
318
+ self.modify_edge(G, (2, 3), foo="bar")
319
+ for e in ev:
320
+ assert len(e) == 3
321
+ if set(e[:2]) == {2, 3}:
322
+ assert e[2] == {"foo": "bar"}
323
+ checked = True
324
+ else:
325
+ assert e[2] == {}
326
+ assert checked
327
+
328
+ for e in ev_def:
329
+ assert len(e) == 3
330
+ if set(e[:2]) == {2, 3}:
331
+ assert e[2] == "bar"
332
+ checked_wt = True
333
+ else:
334
+ assert e[2] == 1
335
+ assert checked_wt
336
+
337
+ def test_iter(self):
338
+ evr = self.eview(self.G)
339
+ ev = evr()
340
+ for u, v in ev:
341
+ pass
342
+ iev = iter(ev)
343
+ assert next(iev) == (0, 1)
344
+ assert iter(ev) != ev
345
+ assert iter(iev) == iev
346
+
347
+ def test_contains(self):
348
+ evr = self.eview(self.G)
349
+ ev = evr()
350
+ if self.G.is_directed():
351
+ assert (1, 2) in ev and (2, 1) not in ev
352
+ else:
353
+ assert (1, 2) in ev and (2, 1) in ev
354
+ assert (1, 4) not in ev
355
+ assert (1, 90) not in ev
356
+ assert (90, 1) not in ev
357
+
358
+ def test_contains_with_nbunch(self):
359
+ evr = self.eview(self.G)
360
+ ev = evr(nbunch=[0, 2])
361
+ if self.G.is_directed():
362
+ assert (0, 1) in ev
363
+ assert (1, 2) not in ev
364
+ assert (2, 3) in ev
365
+ else:
366
+ assert (0, 1) in ev
367
+ assert (1, 2) in ev
368
+ assert (2, 3) in ev
369
+ assert (3, 4) not in ev
370
+ assert (4, 5) not in ev
371
+ assert (5, 6) not in ev
372
+ assert (7, 8) not in ev
373
+ assert (8, 9) not in ev
374
+
375
+ def test_len(self):
376
+ evr = self.eview(self.G)
377
+ ev = evr(data="foo")
378
+ assert len(ev) == 8
379
+ assert len(evr(1)) == 2
380
+ assert len(evr([1, 2, 3])) == 4
381
+
382
+ assert len(self.G.edges(1)) == 2
383
+ assert len(self.G.edges()) == 8
384
+ assert len(self.G.edges) == 8
385
+
386
+ H = self.G.copy()
387
+ H.add_edge(1, 1)
388
+ assert len(H.edges(1)) == 3
389
+ assert len(H.edges()) == 9
390
+ assert len(H.edges) == 9
391
+
392
+
393
+ class TestOutEdgeDataView(TestEdgeDataView):
394
+ @classmethod
395
+ def setup_class(cls):
396
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
397
+ cls.eview = nx.reportviews.OutEdgeView
398
+
399
+ def test_repr(self):
400
+ ev = self.eview(self.G)(data=True)
401
+ rep = (
402
+ "OutEdgeDataView([(0, 1, {}), (1, 2, {}), "
403
+ + "(2, 3, {}), (3, 4, {}), "
404
+ + "(4, 5, {}), (5, 6, {}), "
405
+ + "(6, 7, {}), (7, 8, {})])"
406
+ )
407
+ assert repr(ev) == rep
408
+
409
+ def test_len(self):
410
+ evr = self.eview(self.G)
411
+ ev = evr(data="foo")
412
+ assert len(ev) == 8
413
+ assert len(evr(1)) == 1
414
+ assert len(evr([1, 2, 3])) == 3
415
+
416
+ assert len(self.G.edges(1)) == 1
417
+ assert len(self.G.edges()) == 8
418
+ assert len(self.G.edges) == 8
419
+
420
+ H = self.G.copy()
421
+ H.add_edge(1, 1)
422
+ assert len(H.edges(1)) == 2
423
+ assert len(H.edges()) == 9
424
+ assert len(H.edges) == 9
425
+
426
+ def test_contains_with_nbunch(self):
427
+ evr = self.eview(self.G)
428
+ ev = evr(nbunch=[0, 2])
429
+ assert (0, 1) in ev
430
+ assert (1, 2) not in ev
431
+ assert (2, 3) in ev
432
+ assert (3, 4) not in ev
433
+ assert (4, 5) not in ev
434
+ assert (5, 6) not in ev
435
+ assert (7, 8) not in ev
436
+ assert (8, 9) not in ev
437
+
438
+
439
+ class TestInEdgeDataView(TestOutEdgeDataView):
440
+ @classmethod
441
+ def setup_class(cls):
442
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
443
+ cls.eview = nx.reportviews.InEdgeView
444
+
445
+ def test_repr(self):
446
+ ev = self.eview(self.G)(data=True)
447
+ rep = (
448
+ "InEdgeDataView([(0, 1, {}), (1, 2, {}), "
449
+ + "(2, 3, {}), (3, 4, {}), "
450
+ + "(4, 5, {}), (5, 6, {}), "
451
+ + "(6, 7, {}), (7, 8, {})])"
452
+ )
453
+ assert repr(ev) == rep
454
+
455
+ def test_contains_with_nbunch(self):
456
+ evr = self.eview(self.G)
457
+ ev = evr(nbunch=[0, 2])
458
+ assert (0, 1) not in ev
459
+ assert (1, 2) in ev
460
+ assert (2, 3) not in ev
461
+ assert (3, 4) not in ev
462
+ assert (4, 5) not in ev
463
+ assert (5, 6) not in ev
464
+ assert (7, 8) not in ev
465
+ assert (8, 9) not in ev
466
+
467
+
468
+ class TestMultiEdgeDataView(TestEdgeDataView):
469
+ @classmethod
470
+ def setup_class(cls):
471
+ cls.G = nx.path_graph(9, create_using=nx.MultiGraph())
472
+ cls.eview = nx.reportviews.MultiEdgeView
473
+
474
+ def modify_edge(self, G, e, **kwds):
475
+ G._adj[e[0]][e[1]][0].update(kwds)
476
+
477
+ def test_repr(self):
478
+ ev = self.eview(self.G)(data=True)
479
+ rep = (
480
+ "MultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
481
+ + "(2, 3, {}), (3, 4, {}), "
482
+ + "(4, 5, {}), (5, 6, {}), "
483
+ + "(6, 7, {}), (7, 8, {})])"
484
+ )
485
+ assert repr(ev) == rep
486
+
487
+ def test_contains_with_nbunch(self):
488
+ evr = self.eview(self.G)
489
+ ev = evr(nbunch=[0, 2])
490
+ assert (0, 1) in ev
491
+ assert (1, 2) in ev
492
+ assert (2, 3) in ev
493
+ assert (3, 4) not in ev
494
+ assert (4, 5) not in ev
495
+ assert (5, 6) not in ev
496
+ assert (7, 8) not in ev
497
+ assert (8, 9) not in ev
498
+
499
+
500
+ class TestOutMultiEdgeDataView(TestOutEdgeDataView):
501
+ @classmethod
502
+ def setup_class(cls):
503
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
504
+ cls.eview = nx.reportviews.OutMultiEdgeView
505
+
506
+ def modify_edge(self, G, e, **kwds):
507
+ G._adj[e[0]][e[1]][0].update(kwds)
508
+
509
+ def test_repr(self):
510
+ ev = self.eview(self.G)(data=True)
511
+ rep = (
512
+ "OutMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
513
+ + "(2, 3, {}), (3, 4, {}), "
514
+ + "(4, 5, {}), (5, 6, {}), "
515
+ + "(6, 7, {}), (7, 8, {})])"
516
+ )
517
+ assert repr(ev) == rep
518
+
519
+ def test_contains_with_nbunch(self):
520
+ evr = self.eview(self.G)
521
+ ev = evr(nbunch=[0, 2])
522
+ assert (0, 1) in ev
523
+ assert (1, 2) not in ev
524
+ assert (2, 3) in ev
525
+ assert (3, 4) not in ev
526
+ assert (4, 5) not in ev
527
+ assert (5, 6) not in ev
528
+ assert (7, 8) not in ev
529
+ assert (8, 9) not in ev
530
+
531
+
532
+ class TestInMultiEdgeDataView(TestOutMultiEdgeDataView):
533
+ @classmethod
534
+ def setup_class(cls):
535
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
536
+ cls.eview = nx.reportviews.InMultiEdgeView
537
+
538
+ def test_repr(self):
539
+ ev = self.eview(self.G)(data=True)
540
+ rep = (
541
+ "InMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
542
+ + "(2, 3, {}), (3, 4, {}), "
543
+ + "(4, 5, {}), (5, 6, {}), "
544
+ + "(6, 7, {}), (7, 8, {})])"
545
+ )
546
+ assert repr(ev) == rep
547
+
548
+ def test_contains_with_nbunch(self):
549
+ evr = self.eview(self.G)
550
+ ev = evr(nbunch=[0, 2])
551
+ assert (0, 1) not in ev
552
+ assert (1, 2) in ev
553
+ assert (2, 3) not in ev
554
+ assert (3, 4) not in ev
555
+ assert (4, 5) not in ev
556
+ assert (5, 6) not in ev
557
+ assert (7, 8) not in ev
558
+ assert (8, 9) not in ev
559
+
560
+
561
+ # Edge Views
562
+ class TestEdgeView:
563
+ @classmethod
564
+ def setup_class(cls):
565
+ cls.G = nx.path_graph(9)
566
+ cls.eview = nx.reportviews.EdgeView
567
+
568
+ def test_pickle(self):
569
+ import pickle
570
+
571
+ ev = self.eview(self.G)
572
+ pev = pickle.loads(pickle.dumps(ev, -1))
573
+ assert ev == pev
574
+ assert ev.__slots__ == pev.__slots__
575
+
576
+ def modify_edge(self, G, e, **kwds):
577
+ G._adj[e[0]][e[1]].update(kwds)
578
+
579
+ def test_str(self):
580
+ ev = self.eview(self.G)
581
+ rep = str([(n, n + 1) for n in range(8)])
582
+ assert str(ev) == rep
583
+
584
+ def test_repr(self):
585
+ ev = self.eview(self.G)
586
+ rep = (
587
+ "EdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
588
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
589
+ )
590
+ assert repr(ev) == rep
591
+
592
+ def test_getitem(self):
593
+ G = self.G.copy()
594
+ ev = G.edges
595
+ G.edges[0, 1]["foo"] = "bar"
596
+ assert ev[0, 1] == {"foo": "bar"}
597
+
598
+ # slicing
599
+ with pytest.raises(nx.NetworkXError, match=".*does not support slicing"):
600
+ G.edges[0:5]
601
+
602
+ # Invalid edge
603
+ with pytest.raises(KeyError, match=r".*edge.*is not in the graph."):
604
+ G.edges[0, 9]
605
+
606
+ def test_call(self):
607
+ ev = self.eview(self.G)
608
+ assert id(ev) == id(ev())
609
+ assert id(ev) == id(ev(data=False))
610
+ assert id(ev) != id(ev(data=True))
611
+ assert id(ev) != id(ev(nbunch=1))
612
+
613
+ def test_data(self):
614
+ ev = self.eview(self.G)
615
+ assert id(ev) != id(ev.data())
616
+ assert id(ev) == id(ev.data(data=False))
617
+ assert id(ev) != id(ev.data(data=True))
618
+ assert id(ev) != id(ev.data(nbunch=1))
619
+
620
+ def test_iter(self):
621
+ ev = self.eview(self.G)
622
+ for u, v in ev:
623
+ pass
624
+ iev = iter(ev)
625
+ assert next(iev) == (0, 1)
626
+ assert iter(ev) != ev
627
+ assert iter(iev) == iev
628
+
629
+ def test_contains(self):
630
+ ev = self.eview(self.G)
631
+ edv = ev()
632
+ if self.G.is_directed():
633
+ assert (1, 2) in ev and (2, 1) not in ev
634
+ assert (1, 2) in edv and (2, 1) not in edv
635
+ else:
636
+ assert (1, 2) in ev and (2, 1) in ev
637
+ assert (1, 2) in edv and (2, 1) in edv
638
+ assert (1, 4) not in ev
639
+ assert (1, 4) not in edv
640
+ # edge not in graph
641
+ assert (1, 90) not in ev
642
+ assert (90, 1) not in ev
643
+ assert (1, 90) not in edv
644
+ assert (90, 1) not in edv
645
+
646
+ def test_contains_with_nbunch(self):
647
+ ev = self.eview(self.G)
648
+ evn = ev(nbunch=[0, 2])
649
+ assert (0, 1) in evn
650
+ assert (1, 2) in evn
651
+ assert (2, 3) in evn
652
+ assert (3, 4) not in evn
653
+ assert (4, 5) not in evn
654
+ assert (5, 6) not in evn
655
+ assert (7, 8) not in evn
656
+ assert (8, 9) not in evn
657
+
658
+ def test_len(self):
659
+ ev = self.eview(self.G)
660
+ num_ed = 9 if self.G.is_multigraph() else 8
661
+ assert len(ev) == num_ed
662
+
663
+ H = self.G.copy()
664
+ H.add_edge(1, 1)
665
+ assert len(H.edges(1)) == 3 + H.is_multigraph() - H.is_directed()
666
+ assert len(H.edges()) == num_ed + 1
667
+ assert len(H.edges) == num_ed + 1
668
+
669
+ def test_and(self):
670
+ # print("G & H edges:", gnv & hnv)
671
+ ev = self.eview(self.G)
672
+ some_edges = {(0, 1), (1, 0), (0, 2)}
673
+ if self.G.is_directed():
674
+ assert some_edges & ev, {(0, 1)}
675
+ assert ev & some_edges, {(0, 1)}
676
+ else:
677
+ assert ev & some_edges == {(0, 1), (1, 0)}
678
+ assert some_edges & ev == {(0, 1), (1, 0)}
679
+ return
680
+
681
+ def test_or(self):
682
+ # print("G | H edges:", gnv | hnv)
683
+ ev = self.eview(self.G)
684
+ some_edges = {(0, 1), (1, 0), (0, 2)}
685
+ result1 = {(n, n + 1) for n in range(8)}
686
+ result1.update(some_edges)
687
+ result2 = {(n + 1, n) for n in range(8)}
688
+ result2.update(some_edges)
689
+ assert (ev | some_edges) in (result1, result2)
690
+ assert (some_edges | ev) in (result1, result2)
691
+
692
+ def test_xor(self):
693
+ # print("G ^ H edges:", gnv ^ hnv)
694
+ ev = self.eview(self.G)
695
+ some_edges = {(0, 1), (1, 0), (0, 2)}
696
+ if self.G.is_directed():
697
+ result = {(n, n + 1) for n in range(1, 8)}
698
+ result.update({(1, 0), (0, 2)})
699
+ assert ev ^ some_edges == result
700
+ else:
701
+ result = {(n, n + 1) for n in range(1, 8)}
702
+ result.update({(0, 2)})
703
+ assert ev ^ some_edges == result
704
+ return
705
+
706
+ def test_sub(self):
707
+ # print("G - H edges:", gnv - hnv)
708
+ ev = self.eview(self.G)
709
+ some_edges = {(0, 1), (1, 0), (0, 2)}
710
+ result = {(n, n + 1) for n in range(8)}
711
+ result.remove((0, 1))
712
+ assert ev - some_edges, result
713
+
714
+
715
+ class TestOutEdgeView(TestEdgeView):
716
+ @classmethod
717
+ def setup_class(cls):
718
+ cls.G = nx.path_graph(9, nx.DiGraph())
719
+ cls.eview = nx.reportviews.OutEdgeView
720
+
721
+ def test_repr(self):
722
+ ev = self.eview(self.G)
723
+ rep = (
724
+ "OutEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
725
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
726
+ )
727
+ assert repr(ev) == rep
728
+
729
+ def test_contains_with_nbunch(self):
730
+ ev = self.eview(self.G)
731
+ evn = ev(nbunch=[0, 2])
732
+ assert (0, 1) in evn
733
+ assert (1, 2) not in evn
734
+ assert (2, 3) in evn
735
+ assert (3, 4) not in evn
736
+ assert (4, 5) not in evn
737
+ assert (5, 6) not in evn
738
+ assert (7, 8) not in evn
739
+ assert (8, 9) not in evn
740
+
741
+
742
+ class TestInEdgeView(TestEdgeView):
743
+ @classmethod
744
+ def setup_class(cls):
745
+ cls.G = nx.path_graph(9, nx.DiGraph())
746
+ cls.eview = nx.reportviews.InEdgeView
747
+
748
+ def test_repr(self):
749
+ ev = self.eview(self.G)
750
+ rep = (
751
+ "InEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
752
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
753
+ )
754
+ assert repr(ev) == rep
755
+
756
+ def test_contains_with_nbunch(self):
757
+ ev = self.eview(self.G)
758
+ evn = ev(nbunch=[0, 2])
759
+ assert (0, 1) not in evn
760
+ assert (1, 2) in evn
761
+ assert (2, 3) not in evn
762
+ assert (3, 4) not in evn
763
+ assert (4, 5) not in evn
764
+ assert (5, 6) not in evn
765
+ assert (7, 8) not in evn
766
+ assert (8, 9) not in evn
767
+
768
+
769
+ class TestMultiEdgeView(TestEdgeView):
770
+ @classmethod
771
+ def setup_class(cls):
772
+ cls.G = nx.path_graph(9, nx.MultiGraph())
773
+ cls.G.add_edge(1, 2, key=3, foo="bar")
774
+ cls.eview = nx.reportviews.MultiEdgeView
775
+
776
+ def modify_edge(self, G, e, **kwds):
777
+ if len(e) == 2:
778
+ e = e + (0,)
779
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
780
+
781
+ def test_str(self):
782
+ ev = self.eview(self.G)
783
+ replist = [(n, n + 1, 0) for n in range(8)]
784
+ replist.insert(2, (1, 2, 3))
785
+ rep = str(replist)
786
+ assert str(ev) == rep
787
+
788
+ def test_getitem(self):
789
+ G = self.G.copy()
790
+ ev = G.edges
791
+ G.edges[0, 1, 0]["foo"] = "bar"
792
+ assert ev[0, 1, 0] == {"foo": "bar"}
793
+
794
+ # slicing
795
+ with pytest.raises(nx.NetworkXError):
796
+ G.edges[0:5]
797
+
798
+ def test_repr(self):
799
+ ev = self.eview(self.G)
800
+ rep = (
801
+ "MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
802
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
803
+ )
804
+ assert repr(ev) == rep
805
+
806
+ def test_call(self):
807
+ ev = self.eview(self.G)
808
+ assert id(ev) == id(ev(keys=True))
809
+ assert id(ev) == id(ev(data=False, keys=True))
810
+ assert id(ev) != id(ev(keys=False))
811
+ assert id(ev) != id(ev(data=True))
812
+ assert id(ev) != id(ev(nbunch=1))
813
+
814
+ def test_data(self):
815
+ ev = self.eview(self.G)
816
+ assert id(ev) != id(ev.data())
817
+ assert id(ev) == id(ev.data(data=False, keys=True))
818
+ assert id(ev) != id(ev.data(keys=False))
819
+ assert id(ev) != id(ev.data(data=True))
820
+ assert id(ev) != id(ev.data(nbunch=1))
821
+
822
+ def test_iter(self):
823
+ ev = self.eview(self.G)
824
+ for u, v, k in ev:
825
+ pass
826
+ iev = iter(ev)
827
+ assert next(iev) == (0, 1, 0)
828
+ assert iter(ev) != ev
829
+ assert iter(iev) == iev
830
+
831
+ def test_iterkeys(self):
832
+ G = self.G
833
+ evr = self.eview(G)
834
+ ev = evr(keys=True)
835
+ for u, v, k in ev:
836
+ pass
837
+ assert k == 0
838
+ ev = evr(keys=True, data="foo", default=1)
839
+ for u, v, k, wt in ev:
840
+ pass
841
+ assert wt == 1
842
+
843
+ self.modify_edge(G, (2, 3, 0), foo="bar")
844
+ ev = evr(keys=True, data=True)
845
+ for e in ev:
846
+ assert len(e) == 4
847
+ print("edge:", e)
848
+ if set(e[:2]) == {2, 3}:
849
+ print(self.G._adj[2][3])
850
+ assert e[2] == 0
851
+ assert e[3] == {"foo": "bar"}
852
+ checked = True
853
+ elif set(e[:3]) == {1, 2, 3}:
854
+ assert e[2] == 3
855
+ assert e[3] == {"foo": "bar"}
856
+ checked_multi = True
857
+ else:
858
+ assert e[2] == 0
859
+ assert e[3] == {}
860
+ assert checked
861
+ assert checked_multi
862
+ ev = evr(keys=True, data="foo", default=1)
863
+ for e in ev:
864
+ if set(e[:2]) == {1, 2} and e[2] == 3:
865
+ assert e[3] == "bar"
866
+ if set(e[:2]) == {1, 2} and e[2] == 0:
867
+ assert e[3] == 1
868
+ if set(e[:2]) == {2, 3}:
869
+ assert e[2] == 0
870
+ assert e[3] == "bar"
871
+ assert len(e) == 4
872
+ checked_wt = True
873
+ assert checked_wt
874
+ ev = evr(keys=True)
875
+ for e in ev:
876
+ assert len(e) == 3
877
+ elist = sorted([(i, i + 1, 0) for i in range(8)] + [(1, 2, 3)])
878
+ assert sorted(ev) == elist
879
+ # test that the keyword arguments are passed correctly
880
+ ev = evr((1, 2), "foo", keys=True, default=1)
881
+ with pytest.raises(TypeError):
882
+ evr((1, 2), "foo", True, 1)
883
+ with pytest.raises(TypeError):
884
+ evr((1, 2), "foo", True, default=1)
885
+ for e in ev:
886
+ if set(e[:2]) == {1, 2}:
887
+ assert e[2] in {0, 3}
888
+ if e[2] == 3:
889
+ assert e[3] == "bar"
890
+ else: # e[2] == 0
891
+ assert e[3] == 1
892
+ if G.is_directed():
893
+ assert len(list(ev)) == 3
894
+ else:
895
+ assert len(list(ev)) == 4
896
+
897
+ def test_or(self):
898
+ # print("G | H edges:", gnv | hnv)
899
+ ev = self.eview(self.G)
900
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
901
+ result = {(n, n + 1, 0) for n in range(8)}
902
+ result.update(some_edges)
903
+ result.update({(1, 2, 3)})
904
+ assert ev | some_edges == result
905
+ assert some_edges | ev == result
906
+
907
+ def test_sub(self):
908
+ # print("G - H edges:", gnv - hnv)
909
+ ev = self.eview(self.G)
910
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
911
+ result = {(n, n + 1, 0) for n in range(8)}
912
+ result.remove((0, 1, 0))
913
+ result.update({(1, 2, 3)})
914
+ assert ev - some_edges, result
915
+ assert some_edges - ev, result
916
+
917
+ def test_xor(self):
918
+ # print("G ^ H edges:", gnv ^ hnv)
919
+ ev = self.eview(self.G)
920
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
921
+ if self.G.is_directed():
922
+ result = {(n, n + 1, 0) for n in range(1, 8)}
923
+ result.update({(1, 0, 0), (0, 2, 0), (1, 2, 3)})
924
+ assert ev ^ some_edges == result
925
+ assert some_edges ^ ev == result
926
+ else:
927
+ result = {(n, n + 1, 0) for n in range(1, 8)}
928
+ result.update({(0, 2, 0), (1, 2, 3)})
929
+ assert ev ^ some_edges == result
930
+ assert some_edges ^ ev == result
931
+
932
+ def test_and(self):
933
+ # print("G & H edges:", gnv & hnv)
934
+ ev = self.eview(self.G)
935
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
936
+ if self.G.is_directed():
937
+ assert ev & some_edges == {(0, 1, 0)}
938
+ assert some_edges & ev == {(0, 1, 0)}
939
+ else:
940
+ assert ev & some_edges == {(0, 1, 0), (1, 0, 0)}
941
+ assert some_edges & ev == {(0, 1, 0), (1, 0, 0)}
942
+
943
+ def test_contains_with_nbunch(self):
944
+ ev = self.eview(self.G)
945
+ evn = ev(nbunch=[0, 2])
946
+ assert (0, 1) in evn
947
+ assert (1, 2) in evn
948
+ assert (2, 3) in evn
949
+ assert (3, 4) not in evn
950
+ assert (4, 5) not in evn
951
+ assert (5, 6) not in evn
952
+ assert (7, 8) not in evn
953
+ assert (8, 9) not in evn
954
+
955
+
956
+ class TestOutMultiEdgeView(TestMultiEdgeView):
957
+ @classmethod
958
+ def setup_class(cls):
959
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
960
+ cls.G.add_edge(1, 2, key=3, foo="bar")
961
+ cls.eview = nx.reportviews.OutMultiEdgeView
962
+
963
+ def modify_edge(self, G, e, **kwds):
964
+ if len(e) == 2:
965
+ e = e + (0,)
966
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
967
+
968
+ def test_repr(self):
969
+ ev = self.eview(self.G)
970
+ rep = (
971
+ "OutMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0),"
972
+ + " (3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
973
+ )
974
+ assert repr(ev) == rep
975
+
976
+ def test_contains_with_nbunch(self):
977
+ ev = self.eview(self.G)
978
+ evn = ev(nbunch=[0, 2])
979
+ assert (0, 1) in evn
980
+ assert (1, 2) not in evn
981
+ assert (2, 3) in evn
982
+ assert (3, 4) not in evn
983
+ assert (4, 5) not in evn
984
+ assert (5, 6) not in evn
985
+ assert (7, 8) not in evn
986
+ assert (8, 9) not in evn
987
+
988
+
989
+ class TestInMultiEdgeView(TestMultiEdgeView):
990
+ @classmethod
991
+ def setup_class(cls):
992
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
993
+ cls.G.add_edge(1, 2, key=3, foo="bar")
994
+ cls.eview = nx.reportviews.InMultiEdgeView
995
+
996
+ def modify_edge(self, G, e, **kwds):
997
+ if len(e) == 2:
998
+ e = e + (0,)
999
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
1000
+
1001
+ def test_repr(self):
1002
+ ev = self.eview(self.G)
1003
+ rep = (
1004
+ "InMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
1005
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
1006
+ )
1007
+ assert repr(ev) == rep
1008
+
1009
+ def test_contains_with_nbunch(self):
1010
+ ev = self.eview(self.G)
1011
+ evn = ev(nbunch=[0, 2])
1012
+ assert (0, 1) not in evn
1013
+ assert (1, 2) in evn
1014
+ assert (2, 3) not in evn
1015
+ assert (3, 4) not in evn
1016
+ assert (4, 5) not in evn
1017
+ assert (5, 6) not in evn
1018
+ assert (7, 8) not in evn
1019
+ assert (8, 9) not in evn
1020
+
1021
+
1022
+ # Degrees
1023
+ class TestDegreeView:
1024
+ GRAPH = nx.Graph
1025
+ dview = nx.reportviews.DegreeView
1026
+
1027
+ @classmethod
1028
+ def setup_class(cls):
1029
+ cls.G = nx.path_graph(6, cls.GRAPH())
1030
+ cls.G.add_edge(1, 3, foo=2)
1031
+ cls.G.add_edge(1, 3, foo=3)
1032
+
1033
+ def test_pickle(self):
1034
+ import pickle
1035
+
1036
+ deg = self.G.degree
1037
+ pdeg = pickle.loads(pickle.dumps(deg, -1))
1038
+ assert dict(deg) == dict(pdeg)
1039
+
1040
+ def test_str(self):
1041
+ dv = self.dview(self.G)
1042
+ rep = str([(0, 1), (1, 3), (2, 2), (3, 3), (4, 2), (5, 1)])
1043
+ assert str(dv) == rep
1044
+ dv = self.G.degree()
1045
+ assert str(dv) == rep
1046
+
1047
+ def test_repr(self):
1048
+ dv = self.dview(self.G)
1049
+ rep = "DegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1050
+ assert repr(dv) == rep
1051
+
1052
+ def test_iter(self):
1053
+ dv = self.dview(self.G)
1054
+ for n, d in dv:
1055
+ pass
1056
+ idv = iter(dv)
1057
+ assert iter(dv) != dv
1058
+ assert iter(idv) == idv
1059
+ assert next(idv) == (0, dv[0])
1060
+ assert next(idv) == (1, dv[1])
1061
+ # weighted
1062
+ dv = self.dview(self.G, weight="foo")
1063
+ for n, d in dv:
1064
+ pass
1065
+ idv = iter(dv)
1066
+ assert iter(dv) != dv
1067
+ assert iter(idv) == idv
1068
+ assert next(idv) == (0, dv[0])
1069
+ assert next(idv) == (1, dv[1])
1070
+
1071
+ def test_nbunch(self):
1072
+ dv = self.dview(self.G)
1073
+ dvn = dv(0)
1074
+ assert dvn == 1
1075
+ dvn = dv([2, 3])
1076
+ assert sorted(dvn) == [(2, 2), (3, 3)]
1077
+
1078
+ def test_getitem(self):
1079
+ dv = self.dview(self.G)
1080
+ assert dv[0] == 1
1081
+ assert dv[1] == 3
1082
+ assert dv[2] == 2
1083
+ assert dv[3] == 3
1084
+ dv = self.dview(self.G, weight="foo")
1085
+ assert dv[0] == 1
1086
+ assert dv[1] == 5
1087
+ assert dv[2] == 2
1088
+ assert dv[3] == 5
1089
+
1090
+ def test_weight(self):
1091
+ dv = self.dview(self.G)
1092
+ dvw = dv(0, weight="foo")
1093
+ assert dvw == 1
1094
+ dvw = dv(1, weight="foo")
1095
+ assert dvw == 5
1096
+ dvw = dv([2, 3], weight="foo")
1097
+ assert sorted(dvw) == [(2, 2), (3, 5)]
1098
+ dvd = dict(dv(weight="foo"))
1099
+ assert dvd[0] == 1
1100
+ assert dvd[1] == 5
1101
+ assert dvd[2] == 2
1102
+ assert dvd[3] == 5
1103
+
1104
+ def test_len(self):
1105
+ dv = self.dview(self.G)
1106
+ assert len(dv) == 6
1107
+
1108
+
1109
+ class TestDiDegreeView(TestDegreeView):
1110
+ GRAPH = nx.DiGraph
1111
+ dview = nx.reportviews.DiDegreeView
1112
+
1113
+ def test_repr(self):
1114
+ dv = self.G.degree()
1115
+ rep = "DiDegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1116
+ assert repr(dv) == rep
1117
+
1118
+
1119
+ class TestOutDegreeView(TestDegreeView):
1120
+ GRAPH = nx.DiGraph
1121
+ dview = nx.reportviews.OutDegreeView
1122
+
1123
+ def test_str(self):
1124
+ dv = self.dview(self.G)
1125
+ rep = str([(0, 1), (1, 2), (2, 1), (3, 1), (4, 1), (5, 0)])
1126
+ assert str(dv) == rep
1127
+ dv = self.G.out_degree()
1128
+ assert str(dv) == rep
1129
+
1130
+ def test_repr(self):
1131
+ dv = self.G.out_degree()
1132
+ rep = "OutDegreeView({0: 1, 1: 2, 2: 1, 3: 1, 4: 1, 5: 0})"
1133
+ assert repr(dv) == rep
1134
+
1135
+ def test_nbunch(self):
1136
+ dv = self.dview(self.G)
1137
+ dvn = dv(0)
1138
+ assert dvn == 1
1139
+ dvn = dv([2, 3])
1140
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1141
+
1142
+ def test_getitem(self):
1143
+ dv = self.dview(self.G)
1144
+ assert dv[0] == 1
1145
+ assert dv[1] == 2
1146
+ assert dv[2] == 1
1147
+ assert dv[3] == 1
1148
+ dv = self.dview(self.G, weight="foo")
1149
+ assert dv[0] == 1
1150
+ assert dv[1] == 4
1151
+ assert dv[2] == 1
1152
+ assert dv[3] == 1
1153
+
1154
+ def test_weight(self):
1155
+ dv = self.dview(self.G)
1156
+ dvw = dv(0, weight="foo")
1157
+ assert dvw == 1
1158
+ dvw = dv(1, weight="foo")
1159
+ assert dvw == 4
1160
+ dvw = dv([2, 3], weight="foo")
1161
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1162
+ dvd = dict(dv(weight="foo"))
1163
+ assert dvd[0] == 1
1164
+ assert dvd[1] == 4
1165
+ assert dvd[2] == 1
1166
+ assert dvd[3] == 1
1167
+
1168
+
1169
+ class TestInDegreeView(TestDegreeView):
1170
+ GRAPH = nx.DiGraph
1171
+ dview = nx.reportviews.InDegreeView
1172
+
1173
+ def test_str(self):
1174
+ dv = self.dview(self.G)
1175
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 2), (4, 1), (5, 1)])
1176
+ assert str(dv) == rep
1177
+ dv = self.G.in_degree()
1178
+ assert str(dv) == rep
1179
+
1180
+ def test_repr(self):
1181
+ dv = self.G.in_degree()
1182
+ rep = "InDegreeView({0: 0, 1: 1, 2: 1, 3: 2, 4: 1, 5: 1})"
1183
+ assert repr(dv) == rep
1184
+
1185
+ def test_nbunch(self):
1186
+ dv = self.dview(self.G)
1187
+ dvn = dv(0)
1188
+ assert dvn == 0
1189
+ dvn = dv([2, 3])
1190
+ assert sorted(dvn) == [(2, 1), (3, 2)]
1191
+
1192
+ def test_getitem(self):
1193
+ dv = self.dview(self.G)
1194
+ assert dv[0] == 0
1195
+ assert dv[1] == 1
1196
+ assert dv[2] == 1
1197
+ assert dv[3] == 2
1198
+ dv = self.dview(self.G, weight="foo")
1199
+ assert dv[0] == 0
1200
+ assert dv[1] == 1
1201
+ assert dv[2] == 1
1202
+ assert dv[3] == 4
1203
+
1204
+ def test_weight(self):
1205
+ dv = self.dview(self.G)
1206
+ dvw = dv(0, weight="foo")
1207
+ assert dvw == 0
1208
+ dvw = dv(1, weight="foo")
1209
+ assert dvw == 1
1210
+ dvw = dv([2, 3], weight="foo")
1211
+ assert sorted(dvw) == [(2, 1), (3, 4)]
1212
+ dvd = dict(dv(weight="foo"))
1213
+ assert dvd[0] == 0
1214
+ assert dvd[1] == 1
1215
+ assert dvd[2] == 1
1216
+ assert dvd[3] == 4
1217
+
1218
+
1219
+ class TestMultiDegreeView(TestDegreeView):
1220
+ GRAPH = nx.MultiGraph
1221
+ dview = nx.reportviews.MultiDegreeView
1222
+
1223
+ def test_str(self):
1224
+ dv = self.dview(self.G)
1225
+ rep = str([(0, 1), (1, 4), (2, 2), (3, 4), (4, 2), (5, 1)])
1226
+ assert str(dv) == rep
1227
+ dv = self.G.degree()
1228
+ assert str(dv) == rep
1229
+
1230
+ def test_repr(self):
1231
+ dv = self.G.degree()
1232
+ rep = "MultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1233
+ assert repr(dv) == rep
1234
+
1235
+ def test_nbunch(self):
1236
+ dv = self.dview(self.G)
1237
+ dvn = dv(0)
1238
+ assert dvn == 1
1239
+ dvn = dv([2, 3])
1240
+ assert sorted(dvn) == [(2, 2), (3, 4)]
1241
+
1242
+ def test_getitem(self):
1243
+ dv = self.dview(self.G)
1244
+ assert dv[0] == 1
1245
+ assert dv[1] == 4
1246
+ assert dv[2] == 2
1247
+ assert dv[3] == 4
1248
+ dv = self.dview(self.G, weight="foo")
1249
+ assert dv[0] == 1
1250
+ assert dv[1] == 7
1251
+ assert dv[2] == 2
1252
+ assert dv[3] == 7
1253
+
1254
+ def test_weight(self):
1255
+ dv = self.dview(self.G)
1256
+ dvw = dv(0, weight="foo")
1257
+ assert dvw == 1
1258
+ dvw = dv(1, weight="foo")
1259
+ assert dvw == 7
1260
+ dvw = dv([2, 3], weight="foo")
1261
+ assert sorted(dvw) == [(2, 2), (3, 7)]
1262
+ dvd = dict(dv(weight="foo"))
1263
+ assert dvd[0] == 1
1264
+ assert dvd[1] == 7
1265
+ assert dvd[2] == 2
1266
+ assert dvd[3] == 7
1267
+
1268
+
1269
+ class TestDiMultiDegreeView(TestMultiDegreeView):
1270
+ GRAPH = nx.MultiDiGraph
1271
+ dview = nx.reportviews.DiMultiDegreeView
1272
+
1273
+ def test_repr(self):
1274
+ dv = self.G.degree()
1275
+ rep = "DiMultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1276
+ assert repr(dv) == rep
1277
+
1278
+
1279
+ class TestOutMultiDegreeView(TestDegreeView):
1280
+ GRAPH = nx.MultiDiGraph
1281
+ dview = nx.reportviews.OutMultiDegreeView
1282
+
1283
+ def test_str(self):
1284
+ dv = self.dview(self.G)
1285
+ rep = str([(0, 1), (1, 3), (2, 1), (3, 1), (4, 1), (5, 0)])
1286
+ assert str(dv) == rep
1287
+ dv = self.G.out_degree()
1288
+ assert str(dv) == rep
1289
+
1290
+ def test_repr(self):
1291
+ dv = self.G.out_degree()
1292
+ rep = "OutMultiDegreeView({0: 1, 1: 3, 2: 1, 3: 1, 4: 1, 5: 0})"
1293
+ assert repr(dv) == rep
1294
+
1295
+ def test_nbunch(self):
1296
+ dv = self.dview(self.G)
1297
+ dvn = dv(0)
1298
+ assert dvn == 1
1299
+ dvn = dv([2, 3])
1300
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1301
+
1302
+ def test_getitem(self):
1303
+ dv = self.dview(self.G)
1304
+ assert dv[0] == 1
1305
+ assert dv[1] == 3
1306
+ assert dv[2] == 1
1307
+ assert dv[3] == 1
1308
+ dv = self.dview(self.G, weight="foo")
1309
+ assert dv[0] == 1
1310
+ assert dv[1] == 6
1311
+ assert dv[2] == 1
1312
+ assert dv[3] == 1
1313
+
1314
+ def test_weight(self):
1315
+ dv = self.dview(self.G)
1316
+ dvw = dv(0, weight="foo")
1317
+ assert dvw == 1
1318
+ dvw = dv(1, weight="foo")
1319
+ assert dvw == 6
1320
+ dvw = dv([2, 3], weight="foo")
1321
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1322
+ dvd = dict(dv(weight="foo"))
1323
+ assert dvd[0] == 1
1324
+ assert dvd[1] == 6
1325
+ assert dvd[2] == 1
1326
+ assert dvd[3] == 1
1327
+
1328
+
1329
+ class TestInMultiDegreeView(TestDegreeView):
1330
+ GRAPH = nx.MultiDiGraph
1331
+ dview = nx.reportviews.InMultiDegreeView
1332
+
1333
+ def test_str(self):
1334
+ dv = self.dview(self.G)
1335
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 3), (4, 1), (5, 1)])
1336
+ assert str(dv) == rep
1337
+ dv = self.G.in_degree()
1338
+ assert str(dv) == rep
1339
+
1340
+ def test_repr(self):
1341
+ dv = self.G.in_degree()
1342
+ rep = "InMultiDegreeView({0: 0, 1: 1, 2: 1, 3: 3, 4: 1, 5: 1})"
1343
+ assert repr(dv) == rep
1344
+
1345
+ def test_nbunch(self):
1346
+ dv = self.dview(self.G)
1347
+ dvn = dv(0)
1348
+ assert dvn == 0
1349
+ dvn = dv([2, 3])
1350
+ assert sorted(dvn) == [(2, 1), (3, 3)]
1351
+
1352
+ def test_getitem(self):
1353
+ dv = self.dview(self.G)
1354
+ assert dv[0] == 0
1355
+ assert dv[1] == 1
1356
+ assert dv[2] == 1
1357
+ assert dv[3] == 3
1358
+ dv = self.dview(self.G, weight="foo")
1359
+ assert dv[0] == 0
1360
+ assert dv[1] == 1
1361
+ assert dv[2] == 1
1362
+ assert dv[3] == 6
1363
+
1364
+ def test_weight(self):
1365
+ dv = self.dview(self.G)
1366
+ dvw = dv(0, weight="foo")
1367
+ assert dvw == 0
1368
+ dvw = dv(1, weight="foo")
1369
+ assert dvw == 1
1370
+ dvw = dv([2, 3], weight="foo")
1371
+ assert sorted(dvw) == [(2, 1), (3, 6)]
1372
+ dvd = dict(dv(weight="foo"))
1373
+ assert dvd[0] == 0
1374
+ assert dvd[1] == 1
1375
+ assert dvd[2] == 1
1376
+ assert dvd[3] == 6
1377
+
1378
+
1379
+ @pytest.mark.parametrize(
1380
+ ("reportview", "err_msg_terms"),
1381
+ (
1382
+ (rv.NodeView, "list(G.nodes"),
1383
+ (rv.NodeDataView, "list(G.nodes.data"),
1384
+ (rv.EdgeView, "list(G.edges"),
1385
+ # Directed EdgeViews
1386
+ (rv.InEdgeView, "list(G.in_edges"),
1387
+ (rv.OutEdgeView, "list(G.edges"),
1388
+ # Multi EdgeViews
1389
+ (rv.MultiEdgeView, "list(G.edges"),
1390
+ (rv.InMultiEdgeView, "list(G.in_edges"),
1391
+ (rv.OutMultiEdgeView, "list(G.edges"),
1392
+ ),
1393
+ )
1394
+ def test_slicing_reportviews(reportview, err_msg_terms):
1395
+ G = nx.complete_graph(3)
1396
+ view = reportview(G)
1397
+ with pytest.raises(nx.NetworkXError) as exc:
1398
+ view[0:2]
1399
+ errmsg = str(exc.value)
1400
+ assert type(view).__name__ in errmsg
1401
+ assert err_msg_terms in errmsg
1402
+
1403
+
1404
+ @pytest.mark.parametrize(
1405
+ "graph", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
1406
+ )
1407
+ def test_cache_dict_get_set_state(graph):
1408
+ G = nx.path_graph(5, graph())
1409
+ G.nodes, G.edges, G.adj, G.degree
1410
+ if G.is_directed():
1411
+ G.pred, G.succ, G.in_edges, G.out_edges, G.in_degree, G.out_degree
1412
+ cached_dict = G.__dict__
1413
+ assert "nodes" in cached_dict
1414
+ assert "edges" in cached_dict
1415
+ assert "adj" in cached_dict
1416
+ assert "degree" in cached_dict
1417
+ if G.is_directed():
1418
+ assert "pred" in cached_dict
1419
+ assert "succ" in cached_dict
1420
+ assert "in_edges" in cached_dict
1421
+ assert "out_edges" in cached_dict
1422
+ assert "in_degree" in cached_dict
1423
+ assert "out_degree" in cached_dict
1424
+
1425
+ # Raises error if the cached properties and views do not work
1426
+ pickle.loads(pickle.dumps(G, -1))
1427
+ deepcopy(G)
1428
+
1429
+
1430
+ def test_edge_views_inherit_from_EdgeViewABC():
1431
+ all_edge_view_classes = (v for v in dir(nx.reportviews) if "Edge" in v)
1432
+ for eview_class in all_edge_view_classes:
1433
+ assert issubclass(
1434
+ getattr(nx.reportviews, eview_class), nx.reportviews.EdgeViewABC
1435
+ )
evalkit_cambrian/lib/python3.10/site-packages/networkx/classes/tests/test_subgraphviews.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ class TestSubGraphView:
8
+ gview = staticmethod(nx.subgraph_view)
9
+ graph = nx.Graph
10
+ hide_edges_filter = staticmethod(nx.filters.hide_edges)
11
+ show_edges_filter = staticmethod(nx.filters.show_edges)
12
+
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9, create_using=cls.graph())
16
+ cls.hide_edges_w_hide_nodes = {(3, 4), (4, 5), (5, 6)}
17
+
18
+ def test_hidden_nodes(self):
19
+ hide_nodes = [4, 5, 111]
20
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
21
+ gview = self.gview
22
+ G = gview(self.G, filter_node=nodes_gone)
23
+ assert self.G.nodes - G.nodes == {4, 5}
24
+ assert self.G.edges - G.edges == self.hide_edges_w_hide_nodes
25
+ if G.is_directed():
26
+ assert list(G[3]) == []
27
+ assert list(G[2]) == [3]
28
+ else:
29
+ assert list(G[3]) == [2]
30
+ assert set(G[2]) == {1, 3}
31
+ pytest.raises(KeyError, G.__getitem__, 4)
32
+ pytest.raises(KeyError, G.__getitem__, 112)
33
+ pytest.raises(KeyError, G.__getitem__, 111)
34
+ assert G.degree(3) == (3 if G.is_multigraph() else 1)
35
+ assert G.size() == (7 if G.is_multigraph() else 5)
36
+
37
+ def test_hidden_edges(self):
38
+ hide_edges = [(2, 3), (8, 7), (222, 223)]
39
+ edges_gone = self.hide_edges_filter(hide_edges)
40
+ gview = self.gview
41
+ G = gview(self.G, filter_edge=edges_gone)
42
+ assert self.G.nodes == G.nodes
43
+ if G.is_directed():
44
+ assert self.G.edges - G.edges == {(2, 3)}
45
+ assert list(G[2]) == []
46
+ assert list(G.pred[3]) == []
47
+ assert list(G.pred[2]) == [1]
48
+ assert G.size() == 7
49
+ else:
50
+ assert self.G.edges - G.edges == {(2, 3), (7, 8)}
51
+ assert list(G[2]) == [1]
52
+ assert G.size() == 6
53
+ assert list(G[3]) == [4]
54
+ pytest.raises(KeyError, G.__getitem__, 221)
55
+ pytest.raises(KeyError, G.__getitem__, 222)
56
+ assert G.degree(3) == 1
57
+
58
+ def test_shown_node(self):
59
+ induced_subgraph = nx.filters.show_nodes([2, 3, 111])
60
+ gview = self.gview
61
+ G = gview(self.G, filter_node=induced_subgraph)
62
+ assert set(G.nodes) == {2, 3}
63
+ if G.is_directed():
64
+ assert list(G[3]) == []
65
+ else:
66
+ assert list(G[3]) == [2]
67
+ assert list(G[2]) == [3]
68
+ pytest.raises(KeyError, G.__getitem__, 4)
69
+ pytest.raises(KeyError, G.__getitem__, 112)
70
+ pytest.raises(KeyError, G.__getitem__, 111)
71
+ assert G.degree(3) == (3 if G.is_multigraph() else 1)
72
+ assert G.size() == (3 if G.is_multigraph() else 1)
73
+
74
+ def test_shown_edges(self):
75
+ show_edges = [(2, 3), (8, 7), (222, 223)]
76
+ edge_subgraph = self.show_edges_filter(show_edges)
77
+ G = self.gview(self.G, filter_edge=edge_subgraph)
78
+ assert self.G.nodes == G.nodes
79
+ if G.is_directed():
80
+ assert G.edges == {(2, 3)}
81
+ assert list(G[3]) == []
82
+ assert list(G[2]) == [3]
83
+ assert list(G.pred[3]) == [2]
84
+ assert list(G.pred[2]) == []
85
+ assert G.size() == 1
86
+ else:
87
+ assert G.edges == {(2, 3), (7, 8)}
88
+ assert list(G[3]) == [2]
89
+ assert list(G[2]) == [3]
90
+ assert G.size() == 2
91
+ pytest.raises(KeyError, G.__getitem__, 221)
92
+ pytest.raises(KeyError, G.__getitem__, 222)
93
+ assert G.degree(3) == 1
94
+
95
+
96
+ class TestSubDiGraphView(TestSubGraphView):
97
+ gview = staticmethod(nx.subgraph_view)
98
+ graph = nx.DiGraph
99
+ hide_edges_filter = staticmethod(nx.filters.hide_diedges)
100
+ show_edges_filter = staticmethod(nx.filters.show_diedges)
101
+ hide_edges = [(2, 3), (8, 7), (222, 223)]
102
+ excluded = {(2, 3), (3, 4), (4, 5), (5, 6)}
103
+
104
+ def test_inoutedges(self):
105
+ edges_gone = self.hide_edges_filter(self.hide_edges)
106
+ hide_nodes = [4, 5, 111]
107
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
108
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
109
+
110
+ assert self.G.in_edges - G.in_edges == self.excluded
111
+ assert self.G.out_edges - G.out_edges == self.excluded
112
+
113
+ def test_pred(self):
114
+ edges_gone = self.hide_edges_filter(self.hide_edges)
115
+ hide_nodes = [4, 5, 111]
116
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
117
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
118
+
119
+ assert list(G.pred[2]) == [1]
120
+ assert list(G.pred[6]) == []
121
+
122
+ def test_inout_degree(self):
123
+ edges_gone = self.hide_edges_filter(self.hide_edges)
124
+ hide_nodes = [4, 5, 111]
125
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
126
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
127
+
128
+ assert G.degree(2) == 1
129
+ assert G.out_degree(2) == 0
130
+ assert G.in_degree(2) == 1
131
+ assert G.size() == 4
132
+
133
+
134
+ # multigraph
135
+ class TestMultiGraphView(TestSubGraphView):
136
+ gview = staticmethod(nx.subgraph_view)
137
+ graph = nx.MultiGraph
138
+ hide_edges_filter = staticmethod(nx.filters.hide_multiedges)
139
+ show_edges_filter = staticmethod(nx.filters.show_multiedges)
140
+
141
+ @classmethod
142
+ def setup_class(cls):
143
+ cls.G = nx.path_graph(9, create_using=cls.graph())
144
+ multiedges = {(2, 3, 4), (2, 3, 5)}
145
+ cls.G.add_edges_from(multiedges)
146
+ cls.hide_edges_w_hide_nodes = {(3, 4, 0), (4, 5, 0), (5, 6, 0)}
147
+
148
+ def test_hidden_edges(self):
149
+ hide_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
150
+ edges_gone = self.hide_edges_filter(hide_edges)
151
+ G = self.gview(self.G, filter_edge=edges_gone)
152
+ assert self.G.nodes == G.nodes
153
+ if G.is_directed():
154
+ assert self.G.edges - G.edges == {(2, 3, 4)}
155
+ assert list(G[3]) == [4]
156
+ assert list(G[2]) == [3]
157
+ assert list(G.pred[3]) == [2] # only one 2 but two edges
158
+ assert list(G.pred[2]) == [1]
159
+ assert G.size() == 9
160
+ else:
161
+ assert self.G.edges - G.edges == {(2, 3, 4), (7, 8, 0)}
162
+ assert list(G[3]) == [2, 4]
163
+ assert list(G[2]) == [1, 3]
164
+ assert G.size() == 8
165
+ assert G.degree(3) == 3
166
+ pytest.raises(KeyError, G.__getitem__, 221)
167
+ pytest.raises(KeyError, G.__getitem__, 222)
168
+
169
+ def test_shown_edges(self):
170
+ show_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
171
+ edge_subgraph = self.show_edges_filter(show_edges)
172
+ G = self.gview(self.G, filter_edge=edge_subgraph)
173
+ assert self.G.nodes == G.nodes
174
+ if G.is_directed():
175
+ assert G.edges == {(2, 3, 4)}
176
+ assert list(G[3]) == []
177
+ assert list(G.pred[3]) == [2]
178
+ assert list(G.pred[2]) == []
179
+ assert G.size() == 1
180
+ else:
181
+ assert G.edges == {(2, 3, 4), (7, 8, 0)}
182
+ assert G.size() == 2
183
+ assert list(G[3]) == [2]
184
+ assert G.degree(3) == 1
185
+ assert list(G[2]) == [3]
186
+ pytest.raises(KeyError, G.__getitem__, 221)
187
+ pytest.raises(KeyError, G.__getitem__, 222)
188
+
189
+
190
+ # multidigraph
191
+ class TestMultiDiGraphView(TestMultiGraphView, TestSubDiGraphView):
192
+ gview = staticmethod(nx.subgraph_view)
193
+ graph = nx.MultiDiGraph
194
+ hide_edges_filter = staticmethod(nx.filters.hide_multidiedges)
195
+ show_edges_filter = staticmethod(nx.filters.show_multidiedges)
196
+ hide_edges = [(2, 3, 0), (8, 7, 0), (222, 223, 0)]
197
+ excluded = {(2, 3, 0), (3, 4, 0), (4, 5, 0), (5, 6, 0)}
198
+
199
+ def test_inout_degree(self):
200
+ edges_gone = self.hide_edges_filter(self.hide_edges)
201
+ hide_nodes = [4, 5, 111]
202
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
203
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
204
+
205
+ assert G.degree(2) == 3
206
+ assert G.out_degree(2) == 2
207
+ assert G.in_degree(2) == 1
208
+ assert G.size() == 6
209
+
210
+
211
+ # induced_subgraph
212
+ class TestInducedSubGraph:
213
+ @classmethod
214
+ def setup_class(cls):
215
+ cls.K3 = G = nx.complete_graph(3)
216
+ G.graph["foo"] = []
217
+ G.nodes[0]["foo"] = []
218
+ G.remove_edge(1, 2)
219
+ ll = []
220
+ G.add_edge(1, 2, foo=ll)
221
+ G.add_edge(2, 1, foo=ll)
222
+
223
+ def test_full_graph(self):
224
+ G = self.K3
225
+ H = nx.induced_subgraph(G, [0, 1, 2, 5])
226
+ assert H.name == G.name
227
+ self.graphs_equal(H, G)
228
+ self.same_attrdict(H, G)
229
+
230
+ def test_partial_subgraph(self):
231
+ G = self.K3
232
+ H = nx.induced_subgraph(G, 0)
233
+ assert dict(H.adj) == {0: {}}
234
+ assert dict(G.adj) != {0: {}}
235
+
236
+ H = nx.induced_subgraph(G, [0, 1])
237
+ assert dict(H.adj) == {0: {1: {}}, 1: {0: {}}}
238
+
239
+ def same_attrdict(self, H, G):
240
+ old_foo = H[1][2]["foo"]
241
+ H.edges[1, 2]["foo"] = "baz"
242
+ assert G.edges == H.edges
243
+ H.edges[1, 2]["foo"] = old_foo
244
+ assert G.edges == H.edges
245
+ old_foo = H.nodes[0]["foo"]
246
+ H.nodes[0]["foo"] = "baz"
247
+ assert G.nodes == H.nodes
248
+ H.nodes[0]["foo"] = old_foo
249
+ assert G.nodes == H.nodes
250
+
251
+ def graphs_equal(self, H, G):
252
+ assert G._adj == H._adj
253
+ assert G._node == H._node
254
+ assert G.graph == H.graph
255
+ assert G.name == H.name
256
+ if not G.is_directed() and not H.is_directed():
257
+ assert H._adj[1][2] is H._adj[2][1]
258
+ assert G._adj[1][2] is G._adj[2][1]
259
+ else: # at least one is directed
260
+ if not G.is_directed():
261
+ G._pred = G._adj
262
+ G._succ = G._adj
263
+ if not H.is_directed():
264
+ H._pred = H._adj
265
+ H._succ = H._adj
266
+ assert G._pred == H._pred
267
+ assert G._succ == H._succ
268
+ assert H._succ[1][2] is H._pred[2][1]
269
+ assert G._succ[1][2] is G._pred[2][1]
270
+
271
+
272
+ # edge_subgraph
273
+ class TestEdgeSubGraph:
274
+ @classmethod
275
+ def setup_class(cls):
276
+ # Create a path graph on five nodes.
277
+ cls.G = G = nx.path_graph(5)
278
+ # Add some node, edge, and graph attributes.
279
+ for i in range(5):
280
+ G.nodes[i]["name"] = f"node{i}"
281
+ G.edges[0, 1]["name"] = "edge01"
282
+ G.edges[3, 4]["name"] = "edge34"
283
+ G.graph["name"] = "graph"
284
+ # Get the subgraph induced by the first and last edges.
285
+ cls.H = nx.edge_subgraph(G, [(0, 1), (3, 4)])
286
+
287
+ def test_correct_nodes(self):
288
+ """Tests that the subgraph has the correct nodes."""
289
+ assert [(0, "node0"), (1, "node1"), (3, "node3"), (4, "node4")] == sorted(
290
+ self.H.nodes.data("name")
291
+ )
292
+
293
+ def test_correct_edges(self):
294
+ """Tests that the subgraph has the correct edges."""
295
+ assert edges_equal(
296
+ [(0, 1, "edge01"), (3, 4, "edge34")], self.H.edges.data("name")
297
+ )
298
+
299
+ def test_add_node(self):
300
+ """Tests that adding a node to the original graph does not
301
+ affect the nodes of the subgraph.
302
+
303
+ """
304
+ self.G.add_node(5)
305
+ assert [0, 1, 3, 4] == sorted(self.H.nodes)
306
+ self.G.remove_node(5)
307
+
308
+ def test_remove_node(self):
309
+ """Tests that removing a node in the original graph
310
+ removes the nodes of the subgraph.
311
+
312
+ """
313
+ self.G.remove_node(0)
314
+ assert [1, 3, 4] == sorted(self.H.nodes)
315
+ self.G.add_node(0, name="node0")
316
+ self.G.add_edge(0, 1, name="edge01")
317
+
318
+ def test_node_attr_dict(self):
319
+ """Tests that the node attribute dictionary of the two graphs is
320
+ the same object.
321
+
322
+ """
323
+ for v in self.H:
324
+ assert self.G.nodes[v] == self.H.nodes[v]
325
+ # Making a change to G should make a change in H and vice versa.
326
+ self.G.nodes[0]["name"] = "foo"
327
+ assert self.G.nodes[0] == self.H.nodes[0]
328
+ self.H.nodes[1]["name"] = "bar"
329
+ assert self.G.nodes[1] == self.H.nodes[1]
330
+ # Revert the change, so tests pass with pytest-randomly
331
+ self.G.nodes[0]["name"] = "node0"
332
+ self.H.nodes[1]["name"] = "node1"
333
+
334
+ def test_edge_attr_dict(self):
335
+ """Tests that the edge attribute dictionary of the two graphs is
336
+ the same object.
337
+
338
+ """
339
+ for u, v in self.H.edges():
340
+ assert self.G.edges[u, v] == self.H.edges[u, v]
341
+ # Making a change to G should make a change in H and vice versa.
342
+ self.G.edges[0, 1]["name"] = "foo"
343
+ assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
344
+ self.H.edges[3, 4]["name"] = "bar"
345
+ assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
346
+ # Revert the change, so tests pass with pytest-randomly
347
+ self.G.edges[0, 1]["name"] = "edge01"
348
+ self.H.edges[3, 4]["name"] = "edge34"
349
+
350
+ def test_graph_attr_dict(self):
351
+ """Tests that the graph attribute dictionary of the two graphs
352
+ is the same object.
353
+
354
+ """
355
+ assert self.G.graph is self.H.graph
356
+
357
+ def test_readonly(self):
358
+ """Tests that the subgraph cannot change the graph structure"""
359
+ pytest.raises(nx.NetworkXError, self.H.add_node, 5)
360
+ pytest.raises(nx.NetworkXError, self.H.remove_node, 0)
361
+ pytest.raises(nx.NetworkXError, self.H.add_edge, 5, 6)
362
+ pytest.raises(nx.NetworkXError, self.H.remove_edge, 0, 1)
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc ADDED
Binary file (3.58 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc ADDED
Binary file (4.96 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc ADDED
Binary file (4.82 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc ADDED
Binary file (1.56 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc ADDED
Binary file (4.18 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc ADDED
Binary file (7.42 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/generators/tests/test_random_clustered.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestRandomClusteredGraph:
7
+ def test_custom_joint_degree_sequence(self):
8
+ node = [1, 1, 1, 2, 1, 2, 0, 0]
9
+ tri = [0, 0, 0, 0, 0, 1, 1, 1]
10
+ joint_degree_sequence = zip(node, tri)
11
+ G = nx.random_clustered_graph(joint_degree_sequence)
12
+ assert G.number_of_nodes() == 8
13
+ assert G.number_of_edges() == 7
14
+
15
+ def test_tuple_joint_degree_sequence(self):
16
+ G = nx.random_clustered_graph([(1, 2), (2, 1), (1, 1), (1, 1), (1, 1), (2, 0)])
17
+ assert G.number_of_nodes() == 6
18
+ assert G.number_of_edges() == 10
19
+
20
+ def test_invalid_joint_degree_sequence_type(self):
21
+ with pytest.raises(nx.NetworkXError, match="Invalid degree sequence"):
22
+ nx.random_clustered_graph([[1, 1], [2, 1], [0, 1]])
23
+
24
+ def test_invalid_joint_degree_sequence_value(self):
25
+ with pytest.raises(nx.NetworkXError, match="Invalid degree sequence"):
26
+ nx.random_clustered_graph([[1, 1], [1, 2], [0, 1]])
27
+
28
+ def test_directed_graph_raises_error(self):
29
+ with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
30
+ nx.random_clustered_graph(
31
+ [(1, 2), (2, 1), (1, 1), (1, 1), (1, 1), (2, 0)],
32
+ create_using=nx.DiGraph,
33
+ )
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (719 Bytes). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc ADDED
Binary file (8.35 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc ADDED
Binary file (24.4 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc ADDED
Binary file (28.5 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc ADDED
Binary file (9.53 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc ADDED
Binary file (3.08 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc ADDED
Binary file (6.76 kB). View file