Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/blinker-1.9.0.dist-info/INSTALLERAdded+1
- lib/python3.12/site-packages/blinker-1.9.0.dist-info/LICENSE.txtAdded+20
- lib/python3.12/site-packages/blinker-1.9.0.dist-info/METADATAAdded+60
- lib/python3.12/site-packages/blinker-1.9.0.dist-info/RECORDAdded+12
- lib/python3.12/site-packages/blinker-1.9.0.dist-info/WHEELAdded+4
- lib/python3.12/site-packages/executing-2.2.1.dist-info/INSTALLERAdded+1
- lib/python3.12/site-packages/executing-2.2.1.dist-info/LICENSE.txtAdded+21
- lib/python3.12/site-packages/executing-2.2.1.dist-info/METADATAAdded+171
- lib/python3.12/site-packages/executing-2.2.1.dist-info/RECORDAdded+21
- lib/python3.12/site-packages/executing-2.2.1.dist-info/WHEELAdded+6
- lib/python3.12/site-packages/executing-2.2.1.dist-info/top_level.txtAdded+1
- lib/python3.12/site-packages/networkx/__init__.pyAdded+62
- lib/python3.12/site-packages/networkx/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/__pycache__/conftest.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/__pycache__/convert.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/__pycache__/convert_matrix.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/__pycache__/exception.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/__pycache__/lazy_imports.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/__pycache__/relabel.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__init__.pyAdded+13
- lib/python3.12/site-packages/networkx/classes/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/coreviews.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/digraph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/filters.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/function.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/graph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/graphviews.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/multidigraph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/multigraph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/__pycache__/reportviews.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/coreviews.pyAdded+435
- lib/python3.12/site-packages/networkx/classes/digraph.pyAdded+1363
- lib/python3.12/site-packages/networkx/classes/filters.pyAdded+95
- lib/python3.12/site-packages/networkx/classes/function.pyAdded+1549
- lib/python3.12/site-packages/networkx/classes/graph.pyAdded+2082
- lib/python3.12/site-packages/networkx/classes/graphviews.pyAdded+269
- lib/python3.12/site-packages/networkx/classes/multidigraph.pyAdded+977
- lib/python3.12/site-packages/networkx/classes/multigraph.pyAdded+1294
- lib/python3.12/site-packages/networkx/classes/reportviews.pyAdded+1447
- lib/python3.12/site-packages/networkx/classes/tests/__init__.pyAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_coreviews.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_digraph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_digraph_historical.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_function.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_graph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_graph_historical.cpython-312.pycAdded
1pip1234567891011121314151617181920Copyright 2010 Jason Kirtland
Permission is hereby granted, free of charge, to any person obtaining acopy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall be includedin all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960Metadata-Version: 2.3Name: blinkerVersion: 1.9.0Summary: Fast, simple object-to-object and broadcast signalingAuthor: Jason KirtlandMaintainer-email: Pallets Ecosystem <contact@palletsprojects.com>Requires-Python: >=3.9Description-Content-Type: text/markdownClassifier: Development Status :: 5 - Production/StableClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: PythonClassifier: Typing :: TypedProject-URL: Chat, https://discord.gg/palletsProject-URL: Documentation, https://blinker.readthedocs.ioProject-URL: Source, https://github.com/pallets-eco/blinker/
# Blinker
Blinker provides a fast dispatching system that allows any number ofinterested parties to subscribe to events, or "signals".
## Pallets Community Ecosystem
> [!IMPORTANT]\> This project is part of the Pallets Community Ecosystem. Pallets is the open> source organization that maintains Flask; Pallets-Eco enables community> maintenance of related projects. If you are interested in helping maintain> this project, please reach out on [the Pallets Discord server][discord].>> [discord]: https://discord.gg/pallets
## Example
Signal receivers can subscribe to specific senders or receive signalssent by any sender.
```pycon>>> from blinker import signal>>> started = signal('round-started')>>> def each(round):... print(f"Round {round}")...>>> started.connect(each)
>>> def round_two(round):... print("This is round two.")...>>> started.connect(round_two, sender=2)
>>> for round in range(1, 4):... started.send(round)...Round 1!Round 2!This is round two.Round 3!```
123456789101112blinker-1.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
blinker-1.9.0.dist-info/LICENSE.txt,sha256=nrc6HzhZekqhcCXSrhvjg5Ykx5XphdTw6Xac4p-spGc,1054
blinker-1.9.0.dist-info/METADATA,sha256=uIRiM8wjjbHkCtbCyTvctU37IAZk0kEe5kxAld1dvzA,1633
blinker-1.9.0.dist-info/RECORD,,
blinker-1.9.0.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82
blinker/__init__.py,sha256=I2EdZqpy4LyjX17Hn1yzJGWCjeLaVaPzsMgHkLfj_cQ,317
blinker/__pycache__/__init__.cpython-312.pyc,,
blinker/__pycache__/_utilities.cpython-312.pyc,,
blinker/__pycache__/base.cpython-312.pyc,,
blinker/_utilities.py,sha256=0J7eeXXTUx0Ivf8asfpx0ycVkp0Eqfqnj117x2mYX9E,1675
blinker/base.py,sha256=QpDuvXXcwJF49lUBcH5BiST46Rz9wSG7VW_p7N_027M,19132
blinker/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,01234Wheel-Version: 1.0Generator: flit 3.10.1Root-Is-Purelib: trueTag: py3-none-any1pip123456789101112131415161718192021MIT License
Copyright (c) 2019 Alex Hall
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171Metadata-Version: 2.1Name: executingVersion: 2.2.1Summary: Get the currently executing AST node of a frame, and other informationHome-page: https://github.com/alexmojaki/executingAuthor: Alex HallAuthor-email: alex.mojaki@gmail.comLicense: MITClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Requires-Python: >=3.8Description-Content-Type: text/markdownLicense-File: LICENSE.txtProvides-Extra: testsRequires-Dist: asttokens>=2.1.0; extra == "tests"Requires-Dist: ipython; extra == "tests"Requires-Dist: pytest; extra == "tests"Requires-Dist: coverage; extra == "tests"Requires-Dist: coverage-enable-subprocess; extra == "tests"Requires-Dist: littleutils; extra == "tests"Requires-Dist: rich; python_version >= "3.11" and extra == "tests"
# executing
[](https://github.com/alexmojaki/executing/actions) [](https://coveralls.io/github/alexmojaki/executing?branch=master) [](https://pypi.python.org/pypi/executing)
This mini-package lets you get information about what a frame is currently doing, particularly the AST node being executed.
* [Usage](#usage) * [Getting the AST node](#getting-the-ast-node) * [Getting the source code of the node](#getting-the-source-code-of-the-node) * [Getting the `__qualname__` of the current function](#getting-the-__qualname__-of-the-current-function) * [The Source class](#the-source-class)* [Installation](#installation)* [How does it work?](#how-does-it-work)* [Is it reliable?](#is-it-reliable)* [Which nodes can it identify?](#which-nodes-can-it-identify)* [Projects that use this](#projects-that-use-this)
## Usage
### Getting the AST node
```pythonimport executing
node = executing.Source.executing(frame).node```
Then `node` will be an AST node (from the `ast` standard library module) or None if the node couldn't be identified (which may happen often and should always be checked).
`node` will always be the same instance for multiple calls with frames at the same point of execution.
If you have a traceback object, pass it directly to `Source.executing()` rather than the `tb_frame` attribute to get the correct node.
### Getting the source code of the node
For this you will need to separately install the [`asttokens`](https://github.com/gristlabs/asttokens) library, then obtain an `ASTTokens` object:
```pythonexecuting.Source.executing(frame).source.asttokens()```
or:
```pythonexecuting.Source.for_frame(frame).asttokens()```
or use one of the convenience methods:
```pythonexecuting.Source.executing(frame).text()executing.Source.executing(frame).text_range()```
### Getting the `__qualname__` of the current function
```pythonexecuting.Source.executing(frame).code_qualname()```
or:
```pythonexecuting.Source.for_frame(frame).code_qualname(frame.f_code)```
### The `Source` class
Everything goes through the `Source` class. Only one instance of the class is created for each filename. Subclassing it to add more attributes on creation or methods is recommended. The classmethods such as `executing` will respect this. See the source code and docstrings for more detail.
## Installation
pip install executing
If you don't like that you can just copy the file `executing.py`, there are no dependencies (but of course you won't get updates).
## How does it work?
Suppose the frame is executing this line:
```pythonself.foo(bar.x)```
and in particular it's currently obtaining the attribute `self.foo`. Looking at the bytecode, specifically `frame.f_code.co_code[frame.f_lasti]`, we can tell that it's loading an attribute, but it's not obvious which one. We can narrow down the statement being executed using `frame.f_lineno` and find the two `ast.Attribute` nodes representing `self.foo` and `bar.x`. How do we find out which one it is, without recreating the entire compiler in Python?
The trick is to modify the AST slightly for each candidate expression and observe the changes in the bytecode instructions. We change the AST to this:
```python(self.foo ** 'longuniqueconstant')(bar.x)``` and compile it, and the bytecode will be almost the same but there will be two new instructions:
LOAD_CONST 'longuniqueconstant' BINARY_POWER
and just before that will be a `LOAD_ATTR` instruction corresponding to `self.foo`. Seeing that it's in the same position as the original instruction lets us know we've found our match.
## Is it reliable?
Yes - if it identifies a node, you can trust that it's identified the correct one. The tests are very thorough - in addition to unit tests which check various situations directly, there are property tests against a large number of files (see the filenames printed in [this build](https://travis-ci.org/alexmojaki/executing/jobs/557970457)) with real code. Specifically, for each file, the tests: 1. Identify as many nodes as possible from all the bytecode instructions in the file, and assert that they are all distinct 2. Find all the nodes that should be identifiable, and assert that they were indeed identified somewhere
In other words, it shows that there is a one-to-one mapping between the nodes and the instructions that can be handled. This leaves very little room for a bug to creep in.
Furthermore, `executing` checks that the instructions compiled from the modified AST exactly match the original code save for a few small known exceptions. This accounts for all the quirks and optimisations in the interpreter.
## Which nodes can it identify?
Currently it works in almost all cases for the following `ast` nodes: - `Call`, e.g. `self.foo(bar)` - `Attribute`, e.g. `point.x` - `Subscript`, e.g. `lst[1]` - `BinOp`, e.g. `x + y` (doesn't include `and` and `or`) - `UnaryOp`, e.g. `-n` (includes `not` but only works sometimes) - `Compare` e.g. `a < b` (not for chains such as `0 < p < 1`)
The plan is to extend to more operations in the future.
## Projects that use this
### My Projects
- **[`stack_data`](https://github.com/alexmojaki/stack_data)**: Extracts data from stack frames and tracebacks, particularly to display more useful tracebacks than the default. Also uses another related library of mine: **[`pure_eval`](https://github.com/alexmojaki/pure_eval)**.- **[`futurecoder`](https://futurecoder.io/)**: Highlights the executing node in tracebacks using `executing` via `stack_data`, and provides debugging with `snoop`.- **[`snoop`](https://github.com/alexmojaki/snoop)**: A feature-rich and convenient debugging library. Uses `executing` to show the operation which caused an exception and to allow the `pp` function to display the source of its arguments.- **[`heartrate`](https://github.com/alexmojaki/heartrate)**: A simple real time visualisation of the execution of a Python program. Uses `executing` to highlight currently executing operations, particularly in each frame of the stack trace.- **[`sorcery`](https://github.com/alexmojaki/sorcery)**: Dark magic delights in Python. Uses `executing` to let special callables called spells know where they're being called from.
### Projects I've contributed to
- **[`IPython`](https://github.com/ipython/ipython/pull/12150)**: Highlights the executing node in tracebacks using `executing` via [`stack_data`](https://github.com/alexmojaki/stack_data).- **[`icecream`](https://github.com/gruns/icecream)**: 🍦 Sweet and creamy print debugging. Uses `executing` to identify where `ic` is called and print its arguments.- **[`friendly_traceback`](https://github.com/friendly-traceback/friendly-traceback)**: Uses `stack_data` and `executing` to pinpoint the cause of errors and provide helpful explanations.- **[`python-devtools`](https://github.com/samuelcolvin/python-devtools)**: Uses `executing` for print debugging similar to `icecream`.- **[`sentry_sdk`](https://github.com/getsentry/sentry-python)**: Add the integration `sentry_sdk.integrations.executingExecutingIntegration()` to show the function `__qualname__` in each frame in sentry events.- **[`varname`](https://github.com/pwwang/python-varname)**: Dark magics about variable names in python. Uses `executing` to find where its various magical functions like `varname` and `nameof` are called from.123456789101112131415161718192021executing-2.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
executing-2.2.1.dist-info/LICENSE.txt,sha256=pHaiyw70xBRQNApXeii5GsTH9mkTay7hSAR_q9X8QYE,1066
executing-2.2.1.dist-info/METADATA,sha256=11htGuIlvuEmxCN-sMTXaZqFgLgetVjMUAwmPSmmM_8,8914
executing-2.2.1.dist-info/RECORD,,
executing-2.2.1.dist-info/WHEEL,sha256=Ll72iyqtt6Rbxp-Q7FSafYA1LeRv98X15xcZWRsFEmY,109
executing-2.2.1.dist-info/top_level.txt,sha256=b9Rtf3NtSqc0_Kak6L_lvnbdKPA0GUim2p-XcFQsf5g,10
executing/__init__.py,sha256=agdZWnui3FaB1FepFzVWX5ydS0mlUsVeA0zBLMxhvjk,831
executing/__pycache__/__init__.cpython-312.pyc,,
executing/__pycache__/_exceptions.cpython-312.pyc,,
executing/__pycache__/_position_node_finder.cpython-312.pyc,,
executing/__pycache__/_pytest_utils.cpython-312.pyc,,
executing/__pycache__/_utils.cpython-312.pyc,,
executing/__pycache__/executing.cpython-312.pyc,,
executing/__pycache__/version.cpython-312.pyc,,
executing/_exceptions.py,sha256=nf5P5jPnSjjo_8YWlh5AOyLZHF_hNyJpDv0OG2XFYgw,568
executing/_position_node_finder.py,sha256=W1P_MdoZwVILYk7bps13vmhD4K0a9-LBFaTiRe_7s6Q,37681
executing/_pytest_utils.py,sha256=NRj90nTcExS-8R2P8M1wYm9sodhrTlq74RSd4ZvjQRE,354
executing/_utils.py,sha256=HYisPx2IaYR-uZUhn7IzQ3jUhqVikPSHjRu06i7VHq4,4119
executing/executing.py,sha256=lZuc6mmHT1UqiBAFRovBLzJfvLpZSY6F0Pimdk15Lcg,40741
executing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
executing/version.py,sha256=86znAaVowM4RwLFp-Ylrkl1sqyqYQo7a8SiNpIIUwPo,21123456Wheel-Version: 1.0Generator: setuptools (75.3.2)Root-Is-Purelib: trueTag: py2-none-anyTag: py3-none-any
1executing1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""NetworkX========
NetworkX is a Python package for the creation, manipulation, and study of thestructure, dynamics, and functions of complex networks.
See https://networkx.org for complete documentation."""
__version__ = "3.6.1"
# These are imported in order as listedfrom networkx.lazy_imports import _lazy_import
from networkx.exception import *
from networkx import utilsfrom networkx.utils import _clear_cache, _dispatchable
# load_and_call entry_points, set configsconfig = utils.backends._set_configs_from_environment()utils.config = utils.configs.config = config # type: ignore[attr-defined]
from networkx import classesfrom networkx.classes import filtersfrom networkx.classes import *
from networkx import convertfrom networkx.convert import *
from networkx import convert_matrixfrom networkx.convert_matrix import *
from networkx import relabelfrom networkx.relabel import *
from networkx import generatorsfrom networkx.generators import *
from networkx import readwritefrom networkx.readwrite import *
# Need to test with SciPy, when availablefrom networkx import algorithmsfrom networkx.algorithms import *
from networkx import linalgfrom networkx.linalg import *
from networkx import drawingfrom networkx.drawing import *
def __getattr__(name): if name == "random_tree": raise AttributeError( "nx.random_tree was removed in version 3.4. Use `nx.random_labeled_tree` instead.\n" "See: https://networkx.org/documentation/latest/release/release_3.4.html" ) raise AttributeError(f"module 'networkx' has no attribute '{name}'")12345678910111213from .graph import Graphfrom .digraph import DiGraphfrom .multigraph import MultiGraphfrom .multidigraph import MultiDiGraph
from .function import *from .graphviews import subgraph_view, reverse_view
from networkx.classes import filters
from networkx.classes import coreviewsfrom networkx.classes import graphviewsfrom networkx.classes import reportviews123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435"""Views of core data structures such as nested Mappings (e.g. dict-of-dicts).These ``Views`` often restrict element access, with either the entire view orlayers of nested mappings being read-only."""
from collections.abc import Mapping
__all__ = [ "AtlasView", "AdjacencyView", "MultiAdjacencyView", "UnionAtlas", "UnionAdjacency", "UnionMultiInner", "UnionMultiAdjacency", "FilterAtlas", "FilterAdjacency", "FilterMultiInner", "FilterMultiAdjacency",]
class AtlasView(Mapping): """An AtlasView is a Read-only Mapping of Mappings.
It is a View into a dict-of-dict data structure. The inner level of dict is read-write. But the outer level is read-only.
See Also ======== AdjacencyView: View into dict-of-dict-of-dict MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict """
__slots__ = ("_atlas",)
def __getstate__(self): return {"_atlas": self._atlas}
def __setstate__(self, state): self._atlas = state["_atlas"]
def __init__(self, d): self._atlas = d
def __len__(self): return len(self._atlas)
def __iter__(self): return iter(self._atlas)
def __getitem__(self, key): return self._atlas[key]
def copy(self): return {n: self[n].copy() for n in self._atlas}
def __str__(self): return str(self._atlas) # {nbr: self[nbr] for nbr in self})
def __repr__(self): return f"{self.__class__.__name__}({self._atlas!r})"
class AdjacencyView(AtlasView): """An AdjacencyView is a Read-only Map of Maps of Maps.
It is a View into a dict-of-dict-of-dict data structure. The inner level of dict is read-write. But the outer levels are read-only.
See Also ======== AtlasView: View into dict-of-dict MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict """
__slots__ = () # Still uses AtlasView slots names _atlas
def __getitem__(self, name): return AtlasView(self._atlas[name])
def copy(self): return {n: self[n].copy() for n in self._atlas}
class MultiAdjacencyView(AdjacencyView): """An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.
It is a View into a dict-of-dict-of-dict-of-dict data structure. The inner level of dict is read-write. But the outer levels are read-only.
See Also ======== AtlasView: View into dict-of-dict AdjacencyView: View into dict-of-dict-of-dict """
__slots__ = () # Still uses AtlasView slots names _atlas
def __getitem__(self, name): return AdjacencyView(self._atlas[name])
def copy(self): return {n: self[n].copy() for n in self._atlas}
class UnionAtlas(Mapping): """A read-only union of two atlases (dict-of-dict).
The two dict-of-dicts represent the inner dict of an Adjacency: `G.succ[node]` and `G.pred[node]`. The inner level of dict of both hold attribute key:value pairs and is read-write. But the outer level is read-only.
See Also ======== UnionAdjacency: View into dict-of-dict-of-dict UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict """
__slots__ = ("_succ", "_pred")
def __getstate__(self): return {"_succ": self._succ, "_pred": self._pred}
def __setstate__(self, state): self._succ = state["_succ"] self._pred = state["_pred"]
def __init__(self, succ, pred): self._succ = succ self._pred = pred
def __len__(self): return len(self._succ.keys() | self._pred.keys())
def __iter__(self): return iter(set(self._succ.keys()) | set(self._pred.keys()))
def __getitem__(self, key): try: return self._succ[key] except KeyError: return self._pred[key]
def copy(self): result = {nbr: dd.copy() for nbr, dd in self._succ.items()} for nbr, dd in self._pred.items(): if nbr in result: result[nbr].update(dd) else: result[nbr] = dd.copy() return result
def __str__(self): return str({nbr: self[nbr] for nbr in self})
def __repr__(self): return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
class UnionAdjacency(Mapping): """A read-only union of dict Adjacencies as a Map of Maps of Maps.
The two input dict-of-dict-of-dicts represent the union of `G.succ` and `G.pred`. Return values are UnionAtlas The inner level of dict is read-write. But the middle and outer levels are read-only.
succ : a dict-of-dict-of-dict {node: nbrdict} pred : a dict-of-dict-of-dict {node: nbrdict} The keys for the two dicts should be the same
See Also ======== UnionAtlas: View into dict-of-dict UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict """
__slots__ = ("_succ", "_pred")
def __getstate__(self): return {"_succ": self._succ, "_pred": self._pred}
def __setstate__(self, state): self._succ = state["_succ"] self._pred = state["_pred"]
def __init__(self, succ, pred): # keys must be the same for two input dicts assert len(set(succ.keys()) ^ set(pred.keys())) == 0 self._succ = succ self._pred = pred
def __len__(self): return len(self._succ) # length of each dict should be the same
def __iter__(self): return iter(self._succ)
def __getitem__(self, nbr): return UnionAtlas(self._succ[nbr], self._pred[nbr])
def copy(self): return {n: self[n].copy() for n in self._succ}
def __str__(self): return str({nbr: self[nbr] for nbr in self})
def __repr__(self): return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
class UnionMultiInner(UnionAtlas): """A read-only union of two inner dicts of MultiAdjacencies.
The two input dict-of-dict-of-dicts represent the union of `G.succ[node]` and `G.pred[node]` for MultiDiGraphs. Return values are UnionAtlas. The inner level of dict is read-write. But the outer levels are read-only.
See Also ======== UnionAtlas: View into dict-of-dict UnionAdjacency: View into dict-of-dict-of-dict UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict """
__slots__ = () # Still uses UnionAtlas slots names _succ, _pred
def __getitem__(self, node): in_succ = node in self._succ in_pred = node in self._pred if in_succ: if in_pred: return UnionAtlas(self._succ[node], self._pred[node]) return UnionAtlas(self._succ[node], {}) return UnionAtlas({}, self._pred[node])
def copy(self): nodes = set(self._succ.keys()) | set(self._pred.keys()) return {n: self[n].copy() for n in nodes}
class UnionMultiAdjacency(UnionAdjacency): """A read-only union of two dict MultiAdjacencies.
The two input dict-of-dict-of-dict-of-dicts represent the union of `G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency. The inner level of dict is read-write. But the outer levels are read-only.
See Also ======== UnionAtlas: View into dict-of-dict UnionMultiInner: View into dict-of-dict-of-dict """
__slots__ = () # Still uses UnionAdjacency slots names _succ, _pred
def __getitem__(self, node): return UnionMultiInner(self._succ[node], self._pred[node])
class FilterAtlas(Mapping): # nodedict, nbrdict, keydict """A read-only Mapping of Mappings with filtering criteria for nodes.
It is a view into a dict-of-dict data structure, and it selects only nodes that meet the criteria defined by ``NODE_OK``.
See Also ======== FilterAdjacency FilterMultiInner FilterMultiAdjacency """
def __init__(self, d, NODE_OK): self._atlas = d self.NODE_OK = NODE_OK
def __len__(self): # check whether NODE_OK stores the number of nodes as `length` # or the nodes themselves as a set `nodes`. If not, count the nodes. if hasattr(self.NODE_OK, "length"): return self.NODE_OK.length if hasattr(self.NODE_OK, "nodes"): return len(self.NODE_OK.nodes & self._atlas.keys()) return sum(1 for n in self._atlas if self.NODE_OK(n))
def __iter__(self): try: # check that NODE_OK has attr 'nodes' node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas) except AttributeError: node_ok_shorter = False if node_ok_shorter: return (n for n in self.NODE_OK.nodes if n in self._atlas) return (n for n in self._atlas if self.NODE_OK(n))
def __getitem__(self, key): if key in self._atlas and self.NODE_OK(key): return self._atlas[key] raise KeyError(f"Key {key} not found")
def __str__(self): return str({nbr: self[nbr] for nbr in self})
def __repr__(self): return f"{self.__class__.__name__}({self._atlas!r}, {self.NODE_OK!r})"
class FilterAdjacency(Mapping): # edgedict """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
It is a view into a dict-of-dict-of-dict data structure, and it selects nodes and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
See Also ======== FilterAtlas FilterMultiInner FilterMultiAdjacency """
def __init__(self, d, NODE_OK, EDGE_OK): self._atlas = d self.NODE_OK = NODE_OK self.EDGE_OK = EDGE_OK
def __len__(self): # check whether NODE_OK stores the number of nodes as `length` # or the nodes themselves as a set `nodes`. If not, count the nodes. if hasattr(self.NODE_OK, "length"): return self.NODE_OK.length if hasattr(self.NODE_OK, "nodes"): return len(self.NODE_OK.nodes & self._atlas.keys()) return sum(1 for n in self._atlas if self.NODE_OK(n))
def __iter__(self): try: # check that NODE_OK has attr 'nodes' node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas) except AttributeError: node_ok_shorter = False if node_ok_shorter: return (n for n in self.NODE_OK.nodes if n in self._atlas) return (n for n in self._atlas if self.NODE_OK(n))
def __getitem__(self, node): if node in self._atlas and self.NODE_OK(node):
def new_node_ok(nbr): return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr)
return FilterAtlas(self._atlas[node], new_node_ok) raise KeyError(f"Key {node} not found")
def __str__(self): return str({nbr: self[nbr] for nbr in self})
def __repr__(self): name = self.__class__.__name__ return f"{name}({self._atlas!r}, {self.NODE_OK!r}, {self.EDGE_OK!r})"
class FilterMultiInner(FilterAdjacency): # muliedge_seconddict """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes and edges that meet specific criteria defined by ``NODE_OK`` and ``EDGE_OK``.
See Also ======== FilterAtlas FilterAdjacency FilterMultiAdjacency """
def __iter__(self): try: # check that NODE_OK has attr 'nodes' node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas) except AttributeError: node_ok_shorter = False if node_ok_shorter: my_nodes = (n for n in self.NODE_OK.nodes if n in self._atlas) else: my_nodes = (n for n in self._atlas if self.NODE_OK(n)) for n in my_nodes: some_keys_ok = False for key in self._atlas[n]: if self.EDGE_OK(n, key): some_keys_ok = True break if some_keys_ok is True: yield n
def __getitem__(self, nbr): if ( nbr in self._atlas and self.NODE_OK(nbr) and any(self.EDGE_OK(nbr, key) for key in self._atlas[nbr]) ):
def new_node_ok(key): return self.EDGE_OK(nbr, key)
return FilterAtlas(self._atlas[nbr], new_node_ok) raise KeyError(f"Key {nbr} not found")
class FilterMultiAdjacency(FilterAdjacency): # multiedgedict """A read-only Mapping of Mappings with filtering criteria for nodes and edges.
It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
See Also ======== FilterAtlas FilterAdjacency FilterMultiInner """
def __getitem__(self, node): if node in self._atlas and self.NODE_OK(node):
def edge_ok(nbr, key): return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr, key)
return FilterMultiInner(self._atlas[node], self.NODE_OK, edge_ok) raise KeyError(f"Key {node} not found")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363"""Base class for directed graphs."""
from copy import deepcopyfrom functools import cached_property
import networkx as nxfrom networkx import convertfrom networkx.classes.coreviews import AdjacencyViewfrom networkx.classes.graph import Graphfrom networkx.classes.reportviews import ( DiDegreeView, InDegreeView, InEdgeView, OutDegreeView, OutEdgeView,)from networkx.exception import NetworkXError
__all__ = ["DiGraph"]
class _CachedPropertyResetterAdjAndSucc: """Data Descriptor class that syncs and resets cached properties adj and succ
The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ` are set to new objects. In addition, the attributes `_succ` and `_adj` are synced so these two names point to the same object.
Warning: most of the time, when ``G._adj`` is set, ``G._pred`` should also be set to maintain a valid data structure. They share datadicts.
This object sits on a class and ensures that any instance of that class clears its cached properties "succ" and "adj" whenever the underlying instance attributes "_succ" or "_adj" are set to a new object. It only affects the set process of the obj._adj and obj._succ attribute. All get/del operations act as they normally would.
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html """
def __set__(self, obj, value): od = obj.__dict__ od["_adj"] = value od["_succ"] = value # reset cached properties props = [ "adj", "succ", "edges", "out_edges", "degree", "out_degree", "in_degree", ] for prop in props: if prop in od: del od[prop]
class _CachedPropertyResetterPred: """Data Descriptor class for _pred that resets ``pred`` cached_property when needed
This assumes that the ``cached_property`` ``G.pred`` should be reset whenever ``G._pred`` is set to a new value.
Warning: most of the time, when ``G._pred`` is set, ``G._adj`` should also be set to maintain a valid data structure. They share datadicts.
This object sits on a class and ensures that any instance of that class clears its cached property "pred" whenever the underlying instance attribute "_pred" is set to a new object. It only affects the set process of the obj._pred attribute. All get/del operations act as they normally would.
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html """
def __set__(self, obj, value): od = obj.__dict__ od["_pred"] = value # reset cached properties props = ["pred", "in_edges", "degree", "out_degree", "in_degree"] for prop in props: if prop in od: del od[prop]
class DiGraph(Graph): """ Base class for directed graphs.
A DiGraph stores nodes and edges with optional data, or attributes.
DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention `None` is not used as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters ---------- incoming_graph_data : input graph (optional, default: None) Data to initialize graph. If None (default) an empty graph is created. The data can be any format that is supported by the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy sparse matrix, or PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- Graph MultiGraph MultiDiGraph
Examples -------- Create an empty graph structure (a "null graph") with no nodes and no edges.
>>> G = nx.DiGraph()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2, 3]) >>> G.add_nodes_from(range(100, 110)) >>> H = nx.path_graph(10) >>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a customized node object, or even another Graph.
>>> G.add_node(H)
**Edges:**
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1, 2), (1, 3)])
or a collection of edges,
>>> G.add_edges_from(H.edges)
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when adding nodes or edges that already exist.
**Attributes:**
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.DiGraph(day="Friday") >>> G.graph {'day': 'Friday'}
Add node attributes using add_node(), add_nodes_from() or G.nodes
>>> G.add_node(1, time="5pm") >>> G.add_nodes_from([3], time="2pm") >>> G.nodes[1] {'time': '5pm'} >>> G.nodes[1]["room"] = 714 >>> del G.nodes[1]["room"] # remove attribute >>> list(G.nodes(data=True)) [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edges.
>>> G.add_edge(1, 2, weight=4.7) >>> G.add_edges_from([(3, 4), (4, 5)], color="red") >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})]) >>> G[1][2]["weight"] = 4.7 >>> G.edges[1, 2]["weight"] = 4
Warning: we protect the graph data structure by making `G.edges[1, 2]` a read-only dict-like structure. However, you can assign to attributes in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change data attributes: `G.edges[1, 2]['weight'] = 4` (For multigraphs: `MG.edges[u, v, key][name] = value`).
**Shortcuts:**
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph True >>> [n for n in G if n < 3] # iterate through nodes [1, 2] >>> len(G) # number of nodes in graph 5
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
>>> for n, nbrsdict in G.adjacency(): ... for nbr, eattr in nbrsdict.items(): ... if "weight" in eattr: ... # Do something useful with the edges ... pass
But the edges reporting object is often more convenient:
>>> for u, v, weight in G.edges(data="weight"): ... if weight is not None: ... # Do something useful with the edges ... pass
**Reporting:**
Simple graph information is obtained using object-attributes and methods. Reporting usually provides views instead of containers to reduce memory usage. The views update as the graph is updated similarly to dict-views. The objects `nodes`, `edges` and `adj` provide access to data attributes via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration (e.g. `nodes.items()`, `nodes.data('color')`, `nodes.data('color', default='blue')` and similarly for `edges`) Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
For details on these and other miscellaneous methods, see below.
**Subclasses (Advanced):**
The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these three dicts can be replaced in a subclass by a user defined dict-like object. In general, the dict-like features should be maintained but extra features can be added. To replace one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory : function, (default: dict) Factory function to be used to create the dict containing node attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object
adjlist_outer_dict_factory : function, (default: dict) Factory function to be used to create the outer-most dict in the data structure that holds adjacency info keyed by node. It should require no arguments and return a dict-like object.
adjlist_inner_dict_factory : function, optional (default: dict) Factory function to be used to create the adjacency list dict which holds edge data keyed by neighbor. It should require no arguments and return a dict-like object
edge_attr_dict_factory : function, optional (default: dict) Factory function to be used to create the edge attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
graph_attr_dict_factory : function, (default: dict) Factory function to be used to create the graph attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
Typically, if your extension doesn't impact the data structure all methods will inherited without issue except: `to_directed/to_undirected`. By default these methods create a DiGraph/Graph class and you probably want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you can set in your subclass.
to_directed_class : callable, (default: DiGraph or MultiDiGraph) Class to create a new graph structure in the `to_directed` method. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class : callable, (default: Graph or MultiGraph) Class to create a new graph structure in the `to_undirected` method. If `None`, a NetworkX class (Graph or MultiGraph) is used.
**Subclassing Example**
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all edges. This reduces the memory used, but you lose edge attributes.
>>> class ThinGraph(nx.Graph): ... all_edge_dict = {"weight": 1} ... ... def single_edge_dict(self): ... return self.all_edge_dict ... ... edge_attr_dict_factory = single_edge_dict >>> G = ThinGraph() >>> G.add_edge(2, 1) >>> G[2][1] {'weight': 1} >>> G.add_edge(2, 2) >>> G[2][1] is G[2][2] True """
_adj = _CachedPropertyResetterAdjAndSucc() # type: ignore[assignment] _succ = _adj # type: ignore[has-type] _pred = _CachedPropertyResetterPred()
# This __new__ method just does what Python itself does automatically. # We include it here as part of the dispatchable/backend interface. # If your goal is to understand how the graph classes work, you can ignore # this method, even when subclassing the base classes. If you are subclassing # in order to provide a backend that allows class instantiation, this method # can be overridden to return your own backend graph class. @nx._dispatchable(name="digraph__new__", graphs=None, returns_graph=True) def __new__(cls, *args, **kwargs): return object.__new__(cls)
def __init__(self, incoming_graph_data=None, **attr): """Initialize a graph with edges, name, or graph attributes.
Parameters ---------- incoming_graph_data : input graph (optional, default: None) Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a 2D NumPy array, a SciPy sparse array, or a PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- convert
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G = nx.Graph(name="my graph") >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges >>> G = nx.Graph(e)
Arbitrary graph attribute pairs (key=value) may be assigned
>>> G = nx.Graph(e, day="Friday") >>> G.graph {'day': 'Friday'}
""" self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes self._node = self.node_dict_factory() # dictionary for node attr # We store two adjacency lists: # the predecessors of node n are stored in the dict self._pred # the successors of node n are stored in the dict self._succ=self._adj self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict successor self._pred = self.adjlist_outer_dict_factory() # predecessor # Note: self._succ = self._adj # successor
self.__networkx_cache__ = {} # attempt to load graph with data if incoming_graph_data is not None: convert.to_networkx_graph(incoming_graph_data, create_using=self) # load graph attributes (must be after convert) attr.pop("backend", None) # Ignore explicit `backend="networkx"` self.graph.update(attr)
@cached_property def adj(self): """Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets the color of the edge `(3, 2)` to `"blue"`.
Iterating over G.adj behaves like a dict. Useful idioms include `for nbr, datadict in G.adj[n].items():`.
The neighbor information is also provided by subscripting the graph. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
For directed graphs, `G.adj` holds outgoing (successor) info. """ return AdjacencyView(self._succ)
@cached_property def succ(self): """Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So `G.succ[3][2]['color'] = 'blue'` sets the color of the edge `(3, 2)` to `"blue"`.
Iterating over G.succ behaves like a dict. Useful idioms include `for nbr, datadict in G.succ[n].items():`. A data-view not provided by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):` and a default can be set via a `default` argument to the `data` method.
The neighbor information is also provided by subscripting the graph. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
For directed graphs, `G.adj` is identical to `G.succ`. """ return AdjacencyView(self._succ)
@cached_property def pred(self): """Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets the color of the edge `(3, 2)` to `"blue"`.
Iterating over G.pred behaves like a dict. Useful idioms include `for nbr, datadict in G.pred[n].items():`. A data-view not provided by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):` A default can be set via a `default` argument to the `data` method. """ return AdjacencyView(self._pred)
def add_node(self, node_for_adding, **attr): """Add a single node `node_for_adding` and update node attributes.
Parameters ---------- node_for_adding : node A node can be any hashable Python object except None. attr : keyword arguments, optional Set or change node attributes using key=value.
See Also -------- add_nodes_from
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_node(1) >>> G.add_node("Hello") >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_node(K3) >>> G.number_of_nodes() 3
Use keywords set/change node attributes:
>>> G.add_node(1, size=10) >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
Notes ----- A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be careful that the hash doesn't change on mutables. """ if node_for_adding not in self._succ: if node_for_adding is None: raise ValueError("None cannot be a node") self._succ[node_for_adding] = self.adjlist_inner_dict_factory() self._pred[node_for_adding] = self.adjlist_inner_dict_factory() attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory() attr_dict.update(attr) else: # update attr even if node already exists self._node[node_for_adding].update(attr) nx._clear_cache(self)
def add_nodes_from(self, nodes_for_adding, **attr): """Add multiple nodes.
Parameters ---------- nodes_for_adding : iterable container A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict. attr : keyword arguments, optional (default= no attributes) Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments.
See Also -------- add_node
Notes ----- When adding nodes from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_nodes)`, and pass this object to `G.add_nodes_from`.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_nodes_from("Hello") >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_nodes_from(K3) >>> sorted(G.nodes(), key=str) [0, 1, 2, 'H', 'e', 'l', 'o']
Use keywords to update specific node attributes for every node.
>>> G.add_nodes_from([1, 2], size=10) >>> G.add_nodes_from([3, 4], weight=0.4)
Use (node, attrdict) tuples to update attributes for specific nodes.
>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})]) >>> G.nodes[1]["size"] 11 >>> H = nx.Graph() >>> H.add_nodes_from(G.nodes(data=True)) >>> H.nodes[1]["size"] 11
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)]) >>> # wrong way - will raise RuntimeError >>> # G.add_nodes_from(n + 1 for n in G.nodes) >>> # correct way >>> G.add_nodes_from(list(n + 1 for n in G.nodes)) """ for n in nodes_for_adding: try: newnode = n not in self._node newdict = attr except TypeError: n, ndict = n newnode = n not in self._node newdict = attr.copy() newdict.update(ndict) if newnode: if n is None: raise ValueError("None cannot be a node") self._succ[n] = self.adjlist_inner_dict_factory() self._pred[n] = self.adjlist_inner_dict_factory() self._node[n] = self.node_attr_dict_factory() self._node[n].update(newdict) nx._clear_cache(self)
def remove_node(self, n): """Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a nonexistent node will raise an exception.
Parameters ---------- n : node A node in the graph
Raises ------ NetworkXError If n is not in the graph.
See Also -------- remove_nodes_from
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> list(G.edges) [(0, 1), (1, 2)] >>> G.remove_node(1) >>> list(G.edges) []
""" try: nbrs = self._succ[n] del self._node[n] except KeyError as err: # NetworkXError if n not in self raise NetworkXError(f"The node {n} is not in the digraph.") from err for u in nbrs: del self._pred[u][n] # remove all edges n-u in digraph del self._succ[n] # remove node from succ for u in self._pred[n]: del self._succ[u][n] # remove all edges n-u in digraph del self._pred[n] # remove node from pred nx._clear_cache(self)
def remove_nodes_from(self, nodes): """Remove multiple nodes.
Parameters ---------- nodes : iterable container A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.
See Also -------- remove_node
Notes ----- When removing nodes from an iterator over the graph you are changing, a `RuntimeError` will be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_nodes)`, and pass this object to `G.remove_nodes_from`.
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)]) >>> # this command will fail, as the graph's dict is modified during iteration >>> # G.remove_nodes_from(n for n in G.nodes if n < 2) >>> # this command will work, since the dictionary underlying graph is not modified >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2)) """ for n in nodes: try: succs = self._succ[n] del self._node[n] for u in succs: del self._pred[u][n] # remove all edges n-u in digraph del self._succ[n] # now remove node for u in self._pred[n]: del self._succ[u][n] # remove all edges n-u in digraph del self._pred[n] # now remove node except KeyError: pass # silent failure on remove nx._clear_cache(self)
def add_edge(self, u_of_edge, v_of_edge, **attr): """Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge's attribute dictionary. See examples below.
Parameters ---------- u_of_edge, v_of_edge : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects. attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
See Also -------- add_edges_from : add a collection of edges
Notes ----- Adding an edge that already exists updates the edge data.
Many NetworkX algorithms designed for weighted graphs use an edge attribute (by default `weight`) to hold a numerical value.
Examples -------- The following all add the edge e=(1, 2) to graph G:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = (1, 2) >>> G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
Associate data to edges using keywords:
>>> G.add_edge(1, 2, weight=3) >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
For non-string attribute keys, use subscript notation.
>>> G.add_edge(1, 2) >>> G[1][2].update({0: 5}) >>> G.edges[1, 2].update({0: 5}) """ u, v = u_of_edge, v_of_edge # add nodes if u not in self._succ: if u is None: raise ValueError("None cannot be a node") self._succ[u] = self.adjlist_inner_dict_factory() self._pred[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._succ: if v is None: raise ValueError("None cannot be a node") self._succ[v] = self.adjlist_inner_dict_factory() self._pred[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() # add the edge datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) self._succ[u][v] = datadict self._pred[v][u] = datadict nx._clear_cache(self)
def add_edges_from(self, ebunch_to_add, **attr): """Add all the edges in ebunch_to_add.
Parameters ---------- ebunch_to_add : container of edges Each edge given in the container will be added to the graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary containing edge data. attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
See Also -------- add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Notes ----- Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
When adding edges from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_edges)`, and pass this object to `G.add_edges_from`.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)]) >>> # Grow graph by one new node, adding edges to all existing nodes. >>> # wrong way - will raise RuntimeError >>> # G.add_edges_from(((5, n) for n in G.nodes)) >>> # right way - note that there will be no self-edge for node 5 >>> G.add_edges_from(list((5, n) for n in G.nodes)) """ for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == 2: u, v = e dd = {} else: raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.") if u not in self._succ: if u is None: raise ValueError("None cannot be a node") self._succ[u] = self.adjlist_inner_dict_factory() self._pred[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._succ: if v is None: raise ValueError("None cannot be a node") self._succ[v] = self.adjlist_inner_dict_factory() self._pred[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) datadict.update(dd) self._succ[u][v] = datadict self._pred[v][u] = datadict nx._clear_cache(self)
def remove_edge(self, u, v): """Remove the edge between u and v.
Parameters ---------- u, v : nodes Remove the edge between nodes u and v.
Raises ------ NetworkXError If there is not an edge between u and v.
See Also -------- remove_edges_from : remove a collection of edges
Examples -------- >>> G = nx.Graph() # or DiGraph, etc >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.remove_edge(0, 1) >>> e = (1, 2) >>> G.remove_edge(*e) # unpacks e from an edge tuple >>> e = (2, 3, {"weight": 7}) # an edge with attribute data >>> G.remove_edge(*e[:2]) # select first part of edge tuple """ try: del self._succ[u][v] del self._pred[v][u] except KeyError as err: raise NetworkXError(f"The edge {u}-{v} not in graph.") from err nx._clear_cache(self)
def remove_edges_from(self, ebunch): """Remove all edges specified in ebunch.
Parameters ---------- ebunch: list or container of edge tuples Each edge given in the list or container will be removed from the graph. The edges can be:
- 2-tuples (u, v) edge between u and v. - 3-tuples (u, v, k) where k is ignored.
See Also -------- remove_edge : remove a single edge
Notes ----- Will fail silently if an edge in ebunch is not in the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch = [(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch) """ for e in ebunch: u, v = e[:2] # ignore edge data if u in self._succ and v in self._succ[u]: del self._succ[u][v] del self._pred[v][u] nx._clear_cache(self)
def has_successor(self, u, v): """Returns True if node u has successor v.
This is true if graph has the edge u->v. """ return u in self._succ and v in self._succ[u]
def has_predecessor(self, u, v): """Returns True if node u has predecessor v.
This is true if graph has the edge u<-v. """ return u in self._pred and v in self._pred[u]
def successors(self, n): """Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters ---------- n : node A node in the graph
Raises ------ NetworkXError If n is not in the graph.
See Also -------- predecessors
Notes ----- neighbors() and successors() are the same. """ try: return iter(self._succ[n]) except KeyError as err: raise NetworkXError(f"The node {n} is not in the digraph.") from err
# digraph definitions neighbors = successors
def predecessors(self, n): """Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters ---------- n : node A node in the graph
Raises ------ NetworkXError If n is not in the graph.
See Also -------- successors """ try: return iter(self._pred[n]) except KeyError as err: raise NetworkXError(f"The node {n} is not in the digraph.") from err
@cached_property def edges(self): """An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, `G.edges[u, v]['color']` provides the value of the color attribute for edge `(u, v)` while `for (u, v, c) in G.edges.data('color', default='red'):` iterates through all the edges yielding the color attribute with default `'red'` if no color attribute exists.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges from these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- edges : OutEdgeView A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as `edges[u, v]['foo']`.
See Also -------- in_edges, out_edges
Notes ----- Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples -------- >>> G = nx.DiGraph() # or MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2]) >>> G.add_edge(2, 3, weight=5) >>> [e for e in G.edges] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data("weight", default=1) OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges([0, 2]) # only edges originating from these nodes OutEdgeDataView([(0, 1), (2, 3)]) >>> G.edges(0) # only edges from node 0 OutEdgeDataView([(0, 1)])
""" return OutEdgeView(self)
# alias out_edges to edges @cached_property def out_edges(self): return OutEdgeView(self)
out_edges.__doc__ = edges.__doc__
@cached_property def in_edges(self): """A view of the in edges of the graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, default=None):
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- in_edges : InEdgeView or InEdgeDataView A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as `edges[u, v]['foo']`.
Examples -------- >>> G = nx.DiGraph() >>> G.add_edge(1, 2, color="blue") >>> G.in_edges() InEdgeView([(1, 2)]) >>> G.in_edges(nbunch=2) InEdgeDataView([(1, 2)])
See Also -------- edges """ return InEdgeView(self)
@cached_property def degree(self): """A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- DiDegreeView or int If multiple nodes are requested (the default), returns a `DiDegreeView` mapping nodes to their degree. If a single node is requested, returns the degree of the node as an integer.
See Also -------- in_degree, out_degree
Examples -------- >>> G = nx.DiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1, 2])) [(0, 1), (1, 2), (2, 2)]
""" return DiDegreeView(self)
@cached_property def in_degree(self): """An InDegreeView for (node, in_degree) or in_degree for single node.
The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- If a single node is requested deg : int In-degree of the node
OR if multiple nodes are requested nd_iter : iterator The iterator returns two-tuples of (node, in-degree).
See Also -------- degree, out_degree
Examples -------- >>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.in_degree(0) # node 0 with degree 0 0 >>> list(G.in_degree([0, 1, 2])) [(0, 0), (1, 1), (2, 1)]
""" return InDegreeView(self)
@cached_property def out_degree(self): """An OutDegreeView for (node, out_degree)
The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- If a single node is requested deg : int Out-degree of the node
OR if multiple nodes are requested nd_iter : iterator The iterator returns two-tuples of (node, out-degree).
See Also -------- degree, in_degree
Examples -------- >>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.out_degree(0) # node 0 with degree 1 1 >>> list(G.out_degree([0, 1, 2])) [(0, 1), (1, 1), (2, 1)]
""" return OutDegreeView(self)
def clear(self): """Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear() >>> list(G.nodes) [] >>> list(G.edges) []
""" self._succ.clear() self._pred.clear() self._node.clear() self.graph.clear() nx._clear_cache(self)
def clear_edges(self): """Remove all edges from the graph without altering nodes.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear_edges() >>> list(G.nodes) [0, 1, 2, 3] >>> list(G.edges) []
""" for predecessor_dict in self._pred.values(): predecessor_dict.clear() for successor_dict in self._succ.values(): successor_dict.clear() nx._clear_cache(self)
def is_multigraph(self): """Returns True if graph is a multigraph, False otherwise.""" return False
def is_directed(self): """Returns True if graph is directed, False otherwise.""" return True
def to_undirected(self, reciprocal=False, as_view=False): """Returns an undirected representation of the digraph.
Parameters ---------- reciprocal : bool (optional) If True only keep edges that appear in both directions in the original digraph. as_view : bool (optional, default=False) If True return an undirected view of the original directed graph.
Returns ------- G : Graph An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is different, only one edge is created with an arbitrary choice of which edge data to use. You must check and correct for this manually if desired.
See Also -------- Graph, copy, add_edge, add_edges_from
Notes ----- If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not transfer to the Graph created by this method.
Examples -------- >>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)] """ graph_class = self.to_undirected_class() if as_view is True: return nx.graphviews.generic_graph_view(self, graph_class) # deepcopy when not a view G = graph_class() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) if reciprocal is True: G.add_edges_from( (u, v, deepcopy(d)) for u, nbrs in self._adj.items() for v, d in nbrs.items() if v in self._pred[u] ) else: G.add_edges_from( (u, v, deepcopy(d)) for u, nbrs in self._adj.items() for v, d in nbrs.items() ) return G
def reverse(self, copy=True): """Returns the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters ---------- copy : bool optional (default=True) If True, return a new DiGraph holding the reversed edges. If False, the reverse graph is created using a view of the original graph. """ if copy: H = self.__class__() H.graph.update(deepcopy(self.graph)) H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items()) H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True)) return H return nx.reverse_view(self)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Filter factories to hide or show sets of nodes and edges.
These filters return the function used when creating `SubGraph`."""
__all__ = [ "no_filter", "hide_nodes", "hide_edges", "hide_multiedges", "hide_diedges", "hide_multidiedges", "show_nodes", "show_edges", "show_multiedges", "show_diedges", "show_multidiedges",]
def no_filter(*items): """Returns a filter function that always evaluates to True.""" return True
def hide_nodes(nodes): """Returns a filter function that hides specific nodes.""" nodes = set(nodes) return lambda node: node not in nodes
def hide_diedges(edges): """Returns a filter function that hides specific directed edges.""" edges = {(u, v) for u, v in edges} return lambda u, v: (u, v) not in edges
def hide_edges(edges): """Returns a filter function that hides specific undirected edges.""" alledges = set(edges) | {(v, u) for (u, v) in edges} return lambda u, v: (u, v) not in alledges
def hide_multidiedges(edges): """Returns a filter function that hides specific multi-directed edges.""" edges = {(u, v, k) for u, v, k in edges} return lambda u, v, k: (u, v, k) not in edges
def hide_multiedges(edges): """Returns a filter function that hides specific multi-undirected edges.""" alledges = set(edges) | {(v, u, k) for (u, v, k) in edges} return lambda u, v, k: (u, v, k) not in alledges
# write show_nodes as a class to make SubGraph pickleableclass show_nodes: """Filter class to show specific nodes.
Attach the set of nodes as an attribute to speed up this commonly used filter
Note that another allowed attribute for filters is to store the number of nodes on the filter as attribute `length` (used in `__len__`). It is a user responsibility to ensure this attribute is accurate if present. """
def __init__(self, nodes): self.nodes = set(nodes)
def __call__(self, node): return node in self.nodes
def show_diedges(edges): """Returns a filter function that shows specific directed edges.""" edges = {(u, v) for u, v in edges} return lambda u, v: (u, v) in edges
def show_edges(edges): """Returns a filter function that shows specific undirected edges.""" alledges = set(edges) | {(v, u) for (u, v) in edges} return lambda u, v: (u, v) in alledges
def show_multidiedges(edges): """Returns a filter function that shows specific multi-directed edges.""" edges = {(u, v, k) for u, v, k in edges} return lambda u, v, k: (u, v, k) in edges
def show_multiedges(edges): """Returns a filter function that shows specific multi-undirected edges.""" alledges = set(edges) | {(v, u, k) for (u, v, k) in edges} return lambda u, v, k: (u, v, k) in alledges1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549"""Functional interface to graph methods and assorted utilities."""
from collections import Counterfrom itertools import chain
import networkx as nxfrom networkx.utils import not_implemented_for, pairwise
__all__ = [ "nodes", "edges", "degree", "degree_histogram", "neighbors", "number_of_nodes", "number_of_edges", "density", "is_directed", "freeze", "is_frozen", "subgraph", "induced_subgraph", "edge_subgraph", "restricted_view", "to_directed", "to_undirected", "add_star", "add_path", "add_cycle", "create_empty_copy", "set_node_attributes", "get_node_attributes", "remove_node_attributes", "set_edge_attributes", "get_edge_attributes", "remove_edge_attributes", "all_neighbors", "non_neighbors", "non_edges", "common_neighbors", "is_weighted", "is_negatively_weighted", "is_empty", "selfloop_edges", "nodes_with_selfloops", "number_of_selfloops", "path_weight", "is_path", "describe",]
def nodes(G): """Returns a NodeView over the graph nodes.
This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property. """ return G.nodes()
def edges(G, nbunch=None): """Returns an edge view of edges incident to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
This function wraps the :func:`G.edges <networkx.Graph.edges>` property. """ return G.edges(nbunch)
def degree(G, nbunch=None, weight=None): """Returns a degree view of single node or of nbunch of nodes. If nbunch is omitted, then return degrees of *all* nodes.
This function wraps the :func:`G.degree <networkx.Graph.degree>` property. """ return G.degree(nbunch, weight)
def neighbors(G, n): """Returns an iterator over all neighbors of node n.
This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function. """ return G.neighbors(n)
def number_of_nodes(G): """Returns the number of nodes in the graph.
This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function. """ return G.number_of_nodes()
def number_of_edges(G): """Returns the number of edges in the graph.
This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function. """ return G.number_of_edges()
def density(G): r"""Returns the density of a graph.
The density for undirected graphs is
.. math::
d = \frac{2m}{n(n-1)},
and for directed graphs is
.. math::
d = \frac{m}{n(n-1)},
where `n` is the number of nodes and `m` is the number of edges in `G`.
Notes ----- The density is 0 for a graph without edges and 1 for a complete graph. The density of multigraphs can be higher than 1.
Self loops are counted in the total number of edges so graphs with self loops can have density higher than 1. """ n = number_of_nodes(G) m = number_of_edges(G) if m == 0 or n <= 1: return 0 d = m / (n * (n - 1)) if not G.is_directed(): d *= 2 return d
def degree_histogram(G): """Returns a list of the frequency of each degree value.
Parameters ---------- G : Networkx graph A graph
Returns ------- hist : list A list of frequencies of degrees. The degree values are the index in the list.
Notes ----- Note: the bins are width one, hence len(list) can be large (Order(number_of_edges)) """ counts = Counter(d for n, d in G.degree()) return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
def is_directed(G): """Return True if graph is directed.""" return G.is_directed()
def frozen(*args, **kwargs): """Dummy method for raising errors when trying to modify frozen graphs""" raise nx.NetworkXError("Frozen graph can't be modified")
def freeze(G): """Modify graph to prevent further change by adding or removing nodes or edges.
Node and edge data can still be modified.
Parameters ---------- G : graph A NetworkX graph
Examples -------- >>> G = nx.path_graph(4) >>> G = nx.freeze(G) >>> try: ... G.add_edge(4, 5) ... except nx.NetworkXError as err: ... print(str(err)) Frozen graph can't be modified
Notes ----- To "unfreeze" a graph you must make a copy by creating a new graph object:
>>> graph = nx.path_graph(4) >>> frozen_graph = nx.freeze(graph) >>> unfrozen_graph = nx.Graph(frozen_graph) >>> nx.is_frozen(unfrozen_graph) False
See Also -------- is_frozen """ G.add_node = frozen G.add_nodes_from = frozen G.remove_node = frozen G.remove_nodes_from = frozen G.add_edge = frozen G.add_edges_from = frozen G.add_weighted_edges_from = frozen G.remove_edge = frozen G.remove_edges_from = frozen G.clear = frozen G.clear_edges = frozen G.frozen = True return G
def is_frozen(G): """Returns True if graph is frozen.
Parameters ---------- G : graph A NetworkX graph
See Also -------- freeze """ try: return G.frozen except AttributeError: return False
def add_star(G_to_add_to, nodes_for_star, **attr): """Add a star to Graph G_to_add_to.
The first node in `nodes_for_star` is the middle of the star. It is connected to all other nodes.
Parameters ---------- G_to_add_to : graph A NetworkX graph nodes_for_star : iterable container A container of nodes. attr : keyword arguments, optional (default= no attributes) Attributes to add to every edge in star.
See Also -------- add_path, add_cycle
Examples -------- >>> G = nx.Graph() >>> nx.add_star(G, [0, 1, 2, 3]) >>> nx.add_star(G, [10, 11, 12], weight=2) """ nlist = iter(nodes_for_star) try: v = next(nlist) except StopIteration: return G_to_add_to.add_node(v) edges = ((v, n) for n in nlist) G_to_add_to.add_edges_from(edges, **attr)
def add_path(G_to_add_to, nodes_for_path, **attr): """Add a path to the Graph G_to_add_to.
Parameters ---------- G_to_add_to : graph A NetworkX graph nodes_for_path : iterable container A container of nodes. A path will be constructed from the nodes (in order) and added to the graph. attr : keyword arguments, optional (default= no attributes) Attributes to add to every edge in path.
See Also -------- add_star, add_cycle
Examples -------- >>> G = nx.Graph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> nx.add_path(G, [10, 11, 12], weight=7) """ nlist = iter(nodes_for_path) try: first_node = next(nlist) except StopIteration: return G_to_add_to.add_node(first_node) G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
def add_cycle(G_to_add_to, nodes_for_cycle, **attr): """Add a cycle to the Graph G_to_add_to.
Parameters ---------- G_to_add_to : graph A NetworkX graph nodes_for_cycle: iterable container A container of nodes. A cycle will be constructed from the nodes (in order) and added to the graph. attr : keyword arguments, optional (default= no attributes) Attributes to add to every edge in cycle.
See Also -------- add_path, add_star
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> nx.add_cycle(G, [0, 1, 2, 3]) >>> nx.add_cycle(G, [10, 11, 12], weight=7) """ nlist = iter(nodes_for_cycle) try: first_node = next(nlist) except StopIteration: return G_to_add_to.add_node(first_node) G_to_add_to.add_edges_from( pairwise(chain((first_node,), nlist), cyclic=True), **attr )
def subgraph(G, nbunch): """Returns the subgraph induced on nodes in nbunch.
Parameters ---------- G : graph A NetworkX graph
nbunch : list, iterable A container of nodes that will be iterated through once (thus it should be an iterator or be iterable). Each element of the container should be a valid node type: any hashable type except None. If nbunch is None, return all edges data in the graph. Nodes in nbunch that are not in the graph will be (quietly) ignored.
Notes ----- subgraph(G) calls G.subgraph() """ return G.subgraph(nbunch)
def induced_subgraph(G, nbunch): """Returns a SubGraph view of `G` showing only nodes in nbunch.
The induced subgraph of a graph on a set of nodes N is the graph with nodes N and edges from G which have both ends in N.
Parameters ---------- G : NetworkX Graph nbunch : node, container of nodes or None (for all nodes)
Returns ------- subgraph : SubGraph View A read-only view of the subgraph in `G` induced by the nodes. Changes to the graph `G` will be reflected in the view.
Notes ----- To create a mutable subgraph with its own copies of nodes edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
For an inplace reduction of a graph to a subgraph you can remove nodes: `G.remove_nodes_from(n in G if n not in set(nbunch))`
If you are going to compute subgraphs of your subgraphs you could end up with a chain of views that can be very slow once the chain has about 15 views in it. If they are all induced subgraphs, you can short-cut the chain by making them all subgraphs of the original graph. The graph class method `G.subgraph` does this when `G` is a subgraph. In contrast, this function allows you to choose to build chains or not, as you wish. The returned subgraph is a view on `G`.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = nx.induced_subgraph(G, [0, 1, 3]) >>> list(H.edges) [(0, 1)] >>> list(H.nodes) [0, 1, 3] """ induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch)) return nx.subgraph_view(G, filter_node=induced_nodes)
def edge_subgraph(G, edges): """Returns a view of the subgraph induced by the specified edges.
The induced subgraph contains each edge in `edges` and each node incident to any of those edges.
Parameters ---------- G : NetworkX Graph edges : iterable An iterable of edges. Edges not present in `G` are ignored.
Returns ------- subgraph : SubGraph View A read-only edge-induced subgraph of `G`. Changes to `G` are reflected in the view.
Notes ----- To create a mutable subgraph with its own copies of nodes edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
If you create a subgraph of a subgraph recursively you can end up with a chain of subgraphs that becomes very slow with about 15 nested subgraph views. Luckily the edge_subgraph filter nests nicely so you can use the original graph as G in this function to avoid chains. We do not rule out chains programmatically so that odd cases like an `edge_subgraph` of a `restricted_view` can be created.
Examples -------- >>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)] """ nxf = nx.filters edges = set(edges) nodes = set() for e in edges: nodes.update(e[:2]) induced_nodes = nxf.show_nodes(nodes) if G.is_multigraph(): if G.is_directed(): induced_edges = nxf.show_multidiedges(edges) else: induced_edges = nxf.show_multiedges(edges) else: if G.is_directed(): induced_edges = nxf.show_diedges(edges) else: induced_edges = nxf.show_edges(edges) return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
def restricted_view(G, nodes, edges): """Returns a view of `G` with hidden nodes and edges.
The resulting subgraph filters out node `nodes` and edges `edges`. Filtered out nodes also filter out any of their edges.
Parameters ---------- G : NetworkX Graph nodes : iterable An iterable of nodes. Nodes not present in `G` are ignored. edges : iterable An iterable of edges. Edges not present in `G` are ignored.
Returns ------- subgraph : SubGraph View A read-only restricted view of `G` filtering out nodes and edges. Changes to `G` are reflected in the view.
Notes ----- To create a mutable subgraph with its own copies of nodes edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
If you create a subgraph of a subgraph recursively you may end up with a chain of subgraph views. Such chains can get quite slow for lengths near 15. To avoid long chains, try to make your subgraph based on the original graph. We do not rule out chains programmatically so that odd cases like an `edge_subgraph` of a `restricted_view` can be created.
Examples -------- >>> G = nx.path_graph(5) >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)]) >>> list(H.nodes) [1, 2, 3, 4] >>> list(H.edges) [(2, 3)] """ nxf = nx.filters hide_nodes = nxf.hide_nodes(nodes) if G.is_multigraph(): if G.is_directed(): hide_edges = nxf.hide_multidiedges(edges) else: hide_edges = nxf.hide_multiedges(edges) else: if G.is_directed(): hide_edges = nxf.hide_diedges(edges) else: hide_edges = nxf.hide_edges(edges) return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
def to_directed(graph): """Returns a directed view of the graph `graph`.
Identical to graph.to_directed(as_view=True) Note that graph.to_directed defaults to `as_view=False` while this function always provides a view. """ return graph.to_directed(as_view=True)
def to_undirected(graph): """Returns an undirected view of the graph `graph`.
Identical to graph.to_undirected(as_view=True) Note that graph.to_undirected defaults to `as_view=False` while this function always provides a view. """ return graph.to_undirected(as_view=True)
def create_empty_copy(G, with_data=True): """Returns a copy of the graph G with all of the edges removed.
Parameters ---------- G : graph A NetworkX graph
with_data : bool (default=True) Propagate Graph and Nodes data to the new graph.
See Also -------- empty_graph
""" H = G.__class__() H.add_nodes_from(G.nodes(data=with_data)) if with_data: H.graph.update(G.graph) return H
@nx._dispatchable(preserve_node_attrs=True, mutates_input=True)def set_node_attributes(G, values, name=None): """Sets node attributes from a given value or dictionary of values.
.. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x.
Parameters ---------- G : NetworkX Graph
values : scalar value, dict-like What the node attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every node in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the node attribute for every node. The attribute name will be `name`.
If `values` is a dict or a dict of dict, it should be keyed by node to either an attribute value or a dict of attribute key/value pairs used to update the node's attributes.
name : string (optional, default=None) Name of the node attribute to set if values is a scalar.
Examples -------- After computing some property of the nodes of a graph, you may want to assign a node attribute to store the value of that property for each node::
>>> G = nx.path_graph(3) >>> bb = nx.betweenness_centrality(G) >>> isinstance(bb, dict) True >>> nx.set_node_attributes(G, bb, "betweenness") >>> G.nodes[1]["betweenness"] 1.0
If you provide a list as the second argument, updates to the list will be reflected in the node attribute for each node::
>>> G = nx.path_graph(3) >>> labels = [] >>> nx.set_node_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.nodes[0]["labels"] ['foo'] >>> G.nodes[1]["labels"] ['foo'] >>> G.nodes[2]["labels"] ['foo']
If you provide a dictionary of dictionaries as the second argument, the outer dictionary is assumed to be keyed by node to an inner dictionary of node attributes for that node::
>>> G = nx.path_graph(3) >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}} >>> nx.set_node_attributes(G, attrs) >>> G.nodes[0]["attr1"] 20 >>> G.nodes[0]["attr2"] 'nothing' >>> G.nodes[1]["attr2"] 3 >>> G.nodes[2] {}
Note that if the dictionary contains nodes that are not in `G`, the values are silently ignored::
>>> G = nx.Graph() >>> G.add_node(0) >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color") >>> G.nodes[0]["color"] 'red' >>> 1 in G.nodes False
""" # Set node attributes based on type of `values` if name is not None: # `values` must not be a dict of dict try: # `values` is a dict for n, v in values.items(): try: G.nodes[n][name] = values[n] except KeyError: pass except AttributeError: # `values` is a constant for n in G: G.nodes[n][name] = values else: # `values` must be dict of dict for n, d in values.items(): try: G.nodes[n].update(d) except KeyError: pass nx._clear_cache(G)
@nx._dispatchable(node_attrs={"name": "default"})def get_node_attributes(G, name, default=None): """Get node attributes from graph
Parameters ---------- G : NetworkX Graph
name : string Attribute name
default: object (default=None) Default value of the node attribute if there is no value set for that node in graph. If `None` then nodes without this attribute are not included in the returned dict.
Returns ------- Dictionary of attributes keyed by node.
Examples -------- >>> G = nx.Graph() >>> G.add_nodes_from([1, 2, 3], color="red") >>> color = nx.get_node_attributes(G, "color") >>> color[1] 'red' >>> G.add_node(4) >>> color = nx.get_node_attributes(G, "color", default="yellow") >>> color[4] 'yellow' """ if default is not None: return {n: d.get(name, default) for n, d in G.nodes.items()} return {n: d[name] for n, d in G.nodes.items() if name in d}
@nx._dispatchable(preserve_node_attrs=True, mutates_input=True)def remove_node_attributes(G, *attr_names, nbunch=None): """Remove node attributes from all nodes in the graph.
Parameters ---------- G : NetworkX Graph
*attr_names : List of Strings The attribute names to remove from the graph.
nbunch : List of Nodes Remove the node attributes only from the nodes in this list.
Examples -------- >>> G = nx.Graph() >>> G.add_nodes_from([1, 2, 3], color="blue") >>> nx.get_node_attributes(G, "color") {1: 'blue', 2: 'blue', 3: 'blue'} >>> nx.remove_node_attributes(G, "color") >>> nx.get_node_attributes(G, "color") {} """
if nbunch is None: nbunch = G.nodes()
for attr in attr_names: for n, d in G.nodes(data=True): if n in nbunch: try: del d[attr] except KeyError: pass
@nx._dispatchable(preserve_edge_attrs=True, mutates_input=True)def set_edge_attributes(G, values, name=None): """Sets edge attributes from a given value or dictionary of values.
.. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x.
Parameters ---------- G : NetworkX Graph
values : scalar value, dict-like What the edge attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every edge in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the edge attribute for each edge. The attribute name will be `name`.
If `values` is a dict or a dict of dict, it should be keyed by edge tuple to either an attribute value or a dict of attribute key/value pairs used to update the edge's attributes. For multigraphs, the edge tuples must be of the form ``(u, v, key)``, where `u` and `v` are nodes and `key` is the edge key. For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
name : string (optional, default=None) Name of the edge attribute to set if values is a scalar.
Examples -------- After computing some property of the edges of a graph, you may want to assign a edge attribute to store the value of that property for each edge::
>>> G = nx.path_graph(3) >>> bb = nx.edge_betweenness_centrality(G, normalized=False) >>> nx.set_edge_attributes(G, bb, "betweenness") >>> G.edges[1, 2]["betweenness"] 2.0
If you provide a list as the second argument, updates to the list will be reflected in the edge attribute for each edge::
>>> labels = [] >>> nx.set_edge_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.edges[0, 1]["labels"] ['foo'] >>> G.edges[1, 2]["labels"] ['foo']
If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update edge attributes::
>>> G = nx.path_graph(3) >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}} >>> nx.set_edge_attributes(G, attrs) >>> G[0][1]["attr1"] 20 >>> G[0][1]["attr2"] 'nothing' >>> G[1][2]["attr2"] 3
The attributes of one Graph can be used to set those of another.
>>> H = nx.path_graph(3) >>> nx.set_edge_attributes(H, G.edges)
Note that if the dict contains edges that are not in `G`, they are silently ignored::
>>> G = nx.Graph([(0, 1)]) >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}}) >>> (1, 2) in G.edges() False
For multigraphs, the `values` dict is expected to be keyed by 3-tuples including the edge key::
>>> MG = nx.MultiGraph() >>> edges = [(0, 1), (0, 1)] >>> MG.add_edges_from(edges) # Returns list of edge keys [0, 1] >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}} >>> nx.set_edge_attributes(MG, attributes) >>> MG[0][1][0]["cost"] 21 >>> MG[0][1][1]["cost"] 7
If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple multiedge to a 2-tuple edge and the last multiedge's attribute value will overwrite the previous values. Continuing from the previous case we get::
>>> H = nx.path_graph([0, 1, 2]) >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()}) >>> nx.get_edge_attributes(H, "cost") {(0, 1): 7}
""" if name is not None: # `values` does not contain attribute names try: # if `values` is a dict using `.items()` => {edge: value} if G.is_multigraph(): for (u, v, key), value in values.items(): try: G._adj[u][v][key][name] = value except KeyError: pass else: for (u, v), value in values.items(): try: G._adj[u][v][name] = value except KeyError: pass except AttributeError: # treat `values` as a constant for u, v, data in G.edges(data=True): data[name] = values else: # `values` consists of doct-of-dict {edge: {attr: value}} shape if G.is_multigraph(): for (u, v, key), d in values.items(): try: G._adj[u][v][key].update(d) except KeyError: pass else: for (u, v), d in values.items(): try: G._adj[u][v].update(d) except KeyError: pass nx._clear_cache(G)
@nx._dispatchable(edge_attrs={"name": "default"})def get_edge_attributes(G, name, default=None): """Get edge attributes from graph
Parameters ---------- G : NetworkX Graph
name : string Attribute name
default: object (default=None) Default value of the edge attribute if there is no value set for that edge in graph. If `None` then edges without this attribute are not included in the returned dict.
Returns ------- Dictionary of attributes keyed by edge. For (di)graphs, the keys are 2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of the form: (u, v, key).
Examples -------- >>> G = nx.Graph() >>> nx.add_path(G, [1, 2, 3], color="red") >>> color = nx.get_edge_attributes(G, "color") >>> color[(1, 2)] 'red' >>> G.add_edge(3, 4) >>> color = nx.get_edge_attributes(G, "color", default="yellow") >>> color[(3, 4)] 'yellow' """ if G.is_multigraph(): edges = G.edges(keys=True, data=True) else: edges = G.edges(data=True) if default is not None: return {x[:-1]: x[-1].get(name, default) for x in edges} return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
@nx._dispatchable(preserve_edge_attrs=True, mutates_input=True)def remove_edge_attributes(G, *attr_names, ebunch=None): """Remove edge attributes from all edges in the graph.
Parameters ---------- G : NetworkX Graph
*attr_names : List of Strings The attribute names to remove from the graph.
Examples -------- >>> G = nx.path_graph(3) >>> nx.set_edge_attributes(G, {(u, v): u + v for u, v in G.edges()}, name="weight") >>> nx.get_edge_attributes(G, "weight") {(0, 1): 1, (1, 2): 3} >>> remove_edge_attributes(G, "weight") >>> nx.get_edge_attributes(G, "weight") {} """ if ebunch is None: ebunch = G.edges(keys=True) if G.is_multigraph() else G.edges()
for attr in attr_names: edges = ( G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True) ) for *e, d in edges: if tuple(e) in ebunch: try: del d[attr] except KeyError: pass
def all_neighbors(graph, node): """Returns all of the neighbors of a node in the graph.
If the graph is directed returns predecessors as well as successors.
Parameters ---------- graph : NetworkX graph Graph to find neighbors. node : node The node whose neighbors will be returned.
Returns ------- neighbors : iterator Iterator of neighbors
Raises ------ NetworkXError If `node` is not in the graph.
Examples -------- For undirected graphs, this function is equivalent to ``G.neighbors(node)``.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> list(nx.all_neighbors(G, 1)) [0, 2]
For directed graphs, this function returns both predecessors and successors, which may include duplicates if a node is both a predecessor and successor (e.g., in bidirectional edges or self-loops).
>>> DG = nx.DiGraph([(0, 1), (1, 2), (2, 1)]) >>> list(nx.all_neighbors(DG, 1)) [0, 2, 2]
Notes ----- This function iterates over all neighbors (both predecessors and successors).
See Also -------- Graph.neighbors : Returns successors for both Graph and DiGraph DiGraph.predecessors : Returns predecessors for directed graphs only DiGraph.successors : Returns successors for directed graphs only """ if graph.is_directed(): values = chain(graph.predecessors(node), graph.successors(node)) else: values = graph.neighbors(node) return values
def non_neighbors(graph, node): """Returns the non-neighbors of the node in the graph.
Parameters ---------- graph : NetworkX graph Graph to find neighbors.
node : node The node whose neighbors will be returned.
Returns ------- non_neighbors : set Set of nodes in the graph that are not neighbors of the node. """ return graph._adj.keys() - graph._adj[node].keys() - {node}
def non_edges(graph): """Returns the nonexistent edges in the graph.
Parameters ---------- graph : NetworkX graph. Graph to find nonexistent edges.
Returns ------- non_edges : iterator Iterator of edges that are not in the graph. """ if graph.is_directed(): for u in graph: for v in non_neighbors(graph, u): yield (u, v) else: nodes = set(graph) while nodes: u = nodes.pop() for v in nodes - set(graph[u]): yield (u, v)
@not_implemented_for("directed")def common_neighbors(G, u, v): """Returns the common neighbors of two nodes in a graph.
Parameters ---------- G : graph A NetworkX undirected graph.
u, v : nodes Nodes in the graph.
Returns ------- cnbors : set Set of common neighbors of u and v in the graph.
Raises ------ NetworkXError If u or v is not a node in the graph.
Examples -------- >>> G = nx.complete_graph(5) >>> sorted(nx.common_neighbors(G, 0, 1)) [2, 3, 4] """ if u not in G: raise nx.NetworkXError("u is not in the graph.") if v not in G: raise nx.NetworkXError("v is not in the graph.")
return G._adj[u].keys() & G._adj[v].keys() - {u, v}
@nx._dispatchable(preserve_edge_attrs=True)def is_weighted(G, edge=None, weight="weight"): """Returns True if `G` has weighted edges.
Parameters ---------- G : graph A NetworkX graph.
edge : tuple, optional A 2-tuple specifying the only edge in `G` that will be tested. If None, then every edge in `G` is tested.
weight: string, optional The attribute name used to query for edge weights.
Returns ------- bool A boolean signifying if `G`, or the specified edge, is weighted.
Raises ------ NetworkXError If the specified edge does not exist.
Examples -------- >>> G = nx.path_graph(4) >>> nx.is_weighted(G) False >>> nx.is_weighted(G, (2, 3)) False
>>> G = nx.DiGraph() >>> G.add_edge(1, 2, weight=1) >>> nx.is_weighted(G) True
""" if edge is not None: data = G.get_edge_data(*edge) if data is None: msg = f"Edge {edge!r} does not exist." raise nx.NetworkXError(msg) return weight in data
if is_empty(G): # Special handling required since: all([]) == True return False
return all(weight in data for u, v, data in G.edges(data=True))
@nx._dispatchable(edge_attrs="weight")def is_negatively_weighted(G, edge=None, weight="weight"): """Returns True if `G` has negatively weighted edges.
Parameters ---------- G : graph A NetworkX graph.
edge : tuple, optional A 2-tuple specifying the only edge in `G` that will be tested. If None, then every edge in `G` is tested.
weight: string, optional The attribute name used to query for edge weights.
Returns ------- bool A boolean signifying if `G`, or the specified edge, is negatively weighted.
Raises ------ NetworkXError If the specified edge does not exist.
Examples -------- >>> G = nx.Graph() >>> G.add_edges_from([(1, 3), (2, 4), (2, 6)]) >>> G.add_edge(1, 2, weight=4) >>> nx.is_negatively_weighted(G, (1, 2)) False >>> G[2][4]["weight"] = -2 >>> nx.is_negatively_weighted(G) True >>> G = nx.DiGraph() >>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)] >>> G.add_weighted_edges_from(edges) >>> nx.is_negatively_weighted(G) True
""" if edge is not None: data = G.get_edge_data(*edge) if data is None: msg = f"Edge {edge!r} does not exist." raise nx.NetworkXError(msg) return weight in data and data[weight] < 0
return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
@nx._dispatchabledef is_empty(G): """Returns True if `G` has no edges.
Parameters ---------- G : graph A NetworkX graph.
Returns ------- bool True if `G` has no edges, and False otherwise.
Notes ----- An empty graph can have nodes but not edges. The empty graph with zero nodes is known as the null graph. This is an $O(n)$ operation where n is the number of nodes in the graph.
""" return not any(G._adj.values())
def nodes_with_selfloops(G): """Returns an iterator over nodes with self loops.
A node with a self loop has an edge with both ends adjacent to that node.
Returns ------- nodelist : iterator A iterator over nodes with self loops.
See Also -------- selfloop_edges, number_of_selfloops
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge(1, 1) >>> G.add_edge(1, 2) >>> list(nx.nodes_with_selfloops(G)) [1]
""" return (n for n, nbrs in G._adj.items() if n in nbrs)
def selfloop_edges(G, data=False, keys=False, default=None): """Returns an iterator over selfloop edges.
A selfloop edge has the same node at both ends.
Parameters ---------- G : graph A NetworkX graph. data : string or bool, optional (default=False) Return selfloop edges as two tuples (u, v) (data=False) or three-tuples (u, v, datadict) (data=True) or three-tuples (u, v, datavalue) (data='attrname') keys : bool, optional (default=False) If True, return edge keys with each edge. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- edgeiter : iterator over edge tuples An iterator over all selfloop edges.
See Also -------- nodes_with_selfloops, number_of_selfloops
Examples -------- >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc >>> ekey = G.add_edge(1, 1) >>> ekey = G.add_edge(1, 2) >>> list(nx.selfloop_edges(G)) [(1, 1)] >>> list(nx.selfloop_edges(G, data=True)) [(1, 1, {})] >>> list(nx.selfloop_edges(G, keys=True)) [(1, 1, 0)] >>> list(nx.selfloop_edges(G, keys=True, data=True)) [(1, 1, 0, {})] """ if data is True: if G.is_multigraph(): if keys is True: return ( (n, n, k, d) for n, nbrs in G._adj.items() if n in nbrs for k, d in nbrs[n].items() ) else: return ( (n, n, d) for n, nbrs in G._adj.items() if n in nbrs for d in nbrs[n].values() ) else: return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs) elif data is not False: if G.is_multigraph(): if keys is True: return ( (n, n, k, d.get(data, default)) for n, nbrs in G._adj.items() if n in nbrs for k, d in nbrs[n].items() ) else: return ( (n, n, d.get(data, default)) for n, nbrs in G._adj.items() if n in nbrs for d in nbrs[n].values() ) else: return ( (n, n, nbrs[n].get(data, default)) for n, nbrs in G._adj.items() if n in nbrs ) else: if G.is_multigraph(): if keys is True: return ( (n, n, k) for n, nbrs in G._adj.items() if n in nbrs for k in nbrs[n] ) else: return ( (n, n) for n, nbrs in G._adj.items() if n in nbrs for i in range(len(nbrs[n])) # for easy edge removal (#4068) ) else: return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
@nx._dispatchabledef number_of_selfloops(G): """Returns the number of selfloop edges.
A selfloop edge has the same node at both ends.
Returns ------- nloops : int The number of selfloops.
See Also -------- nodes_with_selfloops, selfloop_edges
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge(1, 1) >>> G.add_edge(1, 2) >>> nx.number_of_selfloops(G) 1 """ return sum(1 for _ in nx.selfloop_edges(G))
def is_path(G, path): """Returns whether or not the specified path exists.
For it to return True, every node on the path must exist and each consecutive pair must be connected via one or more edges.
Parameters ---------- G : graph A NetworkX graph.
path : list A list of nodes which defines the path to traverse
Returns ------- bool True if `path` is a valid path in `G`
""" try: return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path)) except (KeyError, TypeError): return False
def path_weight(G, path, weight): """Returns total cost associated with specified path and weight
Parameters ---------- G : graph A NetworkX graph.
path: list A list of node labels which defines the path to traverse
weight: string A string indicating which edge attribute to use for path cost
Returns ------- cost: int or float An integer or a float representing the total cost with respect to the specified weight of the specified path
Raises ------ NetworkXNoPath If the specified edge does not exist. """ multigraph = G.is_multigraph() cost = 0
if not nx.is_path(G, path): raise nx.NetworkXNoPath("path does not exist") for node, nbr in nx.utils.pairwise(path): if multigraph: cost += min(v[weight] for v in G._adj[node][nbr].values()) else: cost += G._adj[node][nbr][weight] return cost
def describe(G, describe_hook=None): """Prints a description of the graph G.
By default, the description includes some basic properties of the graph. You can also provide additional functions to compute and include more properties in the description.
Parameters ---------- G : graph A NetworkX graph.
describe_hook: callable, optional (default=None) A function that takes a graph as input and returns a dictionary of additional properties to include in the description. The keys of the dictionary are the property names, and the values are the corresponding property values.
Examples -------- >>> G = nx.path_graph(5) >>> nx.describe(G) Number of nodes : 5 Number of edges : 4 Directed : False Multigraph : False Tree : True Bipartite : True Average degree (min, max) : 1.60 (1, 2) Number of connected components : 1
>>> def augment_description(G): ... return {"Average Shortest Path Length": nx.average_shortest_path_length(G)} >>> nx.describe(G, describe_hook=augment_description) Number of nodes : 5 Number of edges : 4 Directed : False Multigraph : False Tree : True Bipartite : True Average degree (min, max) : 1.60 (1, 2) Number of connected components : 1 Average Shortest Path Length : 2.0
>>> G.name = "Path Graph of 5 nodes" >>> nx.describe(G) Name of Graph : Path Graph of 5 nodes Number of nodes : 5 Number of edges : 4 Directed : False Multigraph : False Tree : True Bipartite : True Average degree (min, max) : 1.60 (1, 2) Number of connected components : 1
""" info_dict = _create_describe_info_dict(G)
if describe_hook is not None: additional_info = describe_hook(G) info_dict.update(additional_info)
max_key_len = max(len(k) for k in info_dict) for key, val in info_dict.items(): print(f"{key:<{max_key_len}} : {val}")
def _create_describe_info_dict(G): info = {} if G.name != "": info["Name of Graph"] = G.name info.update( { "Number of nodes": len(G), "Number of edges": G.number_of_edges(), "Directed": G.is_directed(), "Multigraph": G.is_multigraph(), "Tree": nx.is_tree(G), "Bipartite": nx.is_bipartite(G), } ) if len(G) == 0: return info
degree_values = dict(nx.degree(G)).values() avg_degree = sum(degree_values) / len(G) max_degree, min_degree = max(degree_values), min(degree_values) info["Average degree (min, max)"] = f"{avg_degree:.2f} ({min_degree}, {max_degree})"
if G.is_directed(): info["Number of strongly connected components"] = ( nx.number_strongly_connected_components(G) ) info["Number of weakly connected components"] = ( nx.number_weakly_connected_components(G) ) else: info["Number of connected components"] = nx.number_connected_components(G) return info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082"""Base class for undirected graphs.
The Graph class allows any hashable object as a nodeand can associate key/value attribute pairs with each undirected edge.
Self-loops are allowed but multiple edges are not (see MultiGraph).
For directed graphs see DiGraph and MultiDiGraph."""
from copy import deepcopyfrom functools import cached_property
import networkx as nxfrom networkx import convertfrom networkx.classes.coreviews import AdjacencyViewfrom networkx.classes.reportviews import DegreeView, EdgeView, NodeViewfrom networkx.exception import NetworkXError
__all__ = ["Graph"]
class _CachedPropertyResetterAdj: """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
This assumes that the ``cached_property`` ``G.adj`` should be reset whenever ``G._adj`` is set to a new value.
This object sits on a class and ensures that any instance of that class clears its cached property "adj" whenever the underlying instance attribute "_adj" is set to a new object. It only affects the set process of the obj._adj attribute. All get/del operations act as they normally would.
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html """
def __set__(self, obj, value): od = obj.__dict__ od["_adj"] = value # reset cached properties props = ["adj", "edges", "degree"] for prop in props: if prop in od: del od[prop]
class _CachedPropertyResetterNode: """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
This assumes that the ``cached_property`` ``G.node`` should be reset whenever ``G._node`` is set to a new value.
This object sits on a class and ensures that any instance of that class clears its cached property "nodes" whenever the underlying instance attribute "_node" is set to a new object. It only affects the set process of the obj._adj attribute. All get/del operations act as they normally would.
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html """
def __set__(self, obj, value): od = obj.__dict__ od["_node"] = value # reset cached properties if "nodes" in od: del od["nodes"]
class Graph: """ Base class for undirected graphs.
A Graph stores nodes and edges with optional data, or attributes.
Graphs hold undirected edges. Self loops are allowed but multiple (parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes, except that `None` is not allowed as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters ---------- incoming_graph_data : input graph (optional, default: None) Data to initialize graph. If None (default) an empty graph is created. The data can be any format that is supported by the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy sparse matrix, or PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- DiGraph MultiGraph MultiDiGraph
Examples -------- Create an empty graph structure (a "null graph") with no nodes and no edges.
>>> G = nx.Graph()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2, 3]) >>> G.add_nodes_from(range(100, 110)) >>> H = nx.path_graph(10) >>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a customized node object, or even another Graph.
>>> G.add_node(H)
**Edges:**
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1, 2), (1, 3)])
or a collection of edges,
>>> G.add_edges_from(H.edges)
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when adding nodes or edges that already exist.
**Attributes:**
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.Graph(day="Friday") >>> G.graph {'day': 'Friday'}
Add node attributes using add_node(), add_nodes_from() or G.nodes
>>> G.add_node(1, time="5pm") >>> G.add_nodes_from([3], time="2pm") >>> G.nodes[1] {'time': '5pm'} >>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes >>> del G.nodes[1]["room"] # remove attribute >>> list(G.nodes(data=True)) [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edges.
>>> G.add_edge(1, 2, weight=4.7) >>> G.add_edges_from([(3, 4), (4, 5)], color="red") >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})]) >>> G[1][2]["weight"] = 4.7 >>> G.edges[1, 2]["weight"] = 4
Warning: we protect the graph data structure by making `G.edges` a read-only dict-like structure. However, you can assign to attributes in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change data attributes: `G.edges[1, 2]['weight'] = 4` (For multigraphs: `MG.edges[u, v, key][name] = value`).
**Shortcuts:**
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph True >>> [n for n in G if n < 3] # iterate through nodes [1, 2] >>> len(G) # number of nodes in graph 5
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
>>> for n, nbrsdict in G.adjacency(): ... for nbr, eattr in nbrsdict.items(): ... if "weight" in eattr: ... # Do something useful with the edges ... pass
But the edges() method is often more convenient:
>>> for u, v, weight in G.edges.data("weight"): ... if weight is not None: ... # Do something useful with the edges ... pass
**Reporting:**
Simple graph information is obtained using object-attributes and methods. Reporting typically provides views instead of containers to reduce memory usage. The views update as the graph is updated similarly to dict-views. The objects `nodes`, `edges` and `adj` provide access to data attributes via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration (e.g. `nodes.items()`, `nodes.data('color')`, `nodes.data('color', default='blue')` and similarly for `edges`) Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
For details on these and other miscellaneous methods, see below.
**Subclasses (Advanced):**
The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these three dicts can be replaced in a subclass by a user defined dict-like object. In general, the dict-like features should be maintained but extra features can be added. To replace one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-like structure.
node_dict_factory : function, (default: dict) Factory function to be used to create the dict containing node attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object
adjlist_outer_dict_factory : function, (default: dict) Factory function to be used to create the outer-most dict in the data structure that holds adjacency info keyed by node. It should require no arguments and return a dict-like object.
adjlist_inner_dict_factory : function, (default: dict) Factory function to be used to create the adjacency list dict which holds edge data keyed by neighbor. It should require no arguments and return a dict-like object
edge_attr_dict_factory : function, (default: dict) Factory function to be used to create the edge attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
graph_attr_dict_factory : function, (default: dict) Factory function to be used to create the graph attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
Typically, if your extension doesn't impact the data structure all methods will inherit without issue except: `to_directed/to_undirected`. By default these methods create a DiGraph/Graph class and you probably want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you can set in your subclass.
to_directed_class : callable, (default: DiGraph or MultiDiGraph) Class to create a new graph structure in the `to_directed` method. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class : callable, (default: Graph or MultiGraph) Class to create a new graph structure in the `to_undirected` method. If `None`, a NetworkX class (Graph or MultiGraph) is used.
**Subclassing Example**
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all edges. This reduces the memory used, but you lose edge attributes.
>>> class ThinGraph(nx.Graph): ... all_edge_dict = {"weight": 1} ... ... def single_edge_dict(self): ... return self.all_edge_dict ... ... edge_attr_dict_factory = single_edge_dict >>> G = ThinGraph() >>> G.add_edge(2, 1) >>> G[2][1] {'weight': 1} >>> G.add_edge(2, 2) >>> G[2][1] is G[2][2] True """
__networkx_backend__ = "networkx"
_adj = _CachedPropertyResetterAdj() _node = _CachedPropertyResetterNode()
node_dict_factory = dict node_attr_dict_factory = dict adjlist_outer_dict_factory = dict adjlist_inner_dict_factory = dict edge_attr_dict_factory = dict graph_attr_dict_factory = dict
def to_directed_class(self): """Returns the class to use for empty directed copies.
If you subclass the base classes, use this to designate what directed class to use for `to_directed()` copies. """ return nx.DiGraph
def to_undirected_class(self): """Returns the class to use for empty undirected copies.
If you subclass the base classes, use this to designate what directed class to use for `to_directed()` copies. """ return Graph
# This __new__ method just does what Python itself does automatically. # We include it here as part of the dispatchable/backend interface. # If your goal is to understand how the graph classes work, you can ignore # this method, even when subclassing the base classes. If you are subclassing # in order to provide a backend that allows class instantiation, this method # can be overridden to return your own backend graph class. @nx._dispatchable(name="graph__new__", graphs=None, returns_graph=True) def __new__(cls, *args, **kwargs): return object.__new__(cls)
def __init__(self, incoming_graph_data=None, **attr): """Initialize a graph with edges, name, or graph attributes.
Parameters ---------- incoming_graph_data : input graph (optional, default: None) Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a 2D NumPy array, a SciPy sparse array, or a PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- convert
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G = nx.Graph(name="my graph") >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges >>> G = nx.Graph(e)
Arbitrary graph attribute pairs (key=value) may be assigned
>>> G = nx.Graph(e, day="Friday") >>> G.graph {'day': 'Friday'}
""" self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes self._node = self.node_dict_factory() # empty node attribute dict self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict self.__networkx_cache__ = {} # attempt to load graph with data if incoming_graph_data is not None: convert.to_networkx_graph(incoming_graph_data, create_using=self) # load graph attributes (must be after convert) attr.pop("backend", None) # Ignore explicit `backend="networkx"` self.graph.update(attr)
@cached_property def adj(self): """Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets the color of the edge `(3, 2)` to `"blue"`.
Iterating over G.adj behaves like a dict. Useful idioms include `for nbr, datadict in G.adj[n].items():`.
The neighbor information is also provided by subscripting the graph. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
For directed graphs, `G.adj` holds outgoing (successor) info. """ return AdjacencyView(self._adj)
@property def name(self): """String identifier of the graph.
This graph attribute appears in the attribute dict G.graph keyed by the string `"name"`. as well as an attribute (technically a property) `G.name`. This is entirely user controlled. """ return self.graph.get("name", "")
@name.setter def name(self, s): self.graph["name"] = s nx._clear_cache(self)
def __str__(self): """Returns a short summary of the graph.
Returns ------- info : string Graph information including the graph name (if any), graph type, and the number of nodes and edges.
Examples -------- >>> G = nx.Graph(name="foo") >>> str(G) "Graph named 'foo' with 0 nodes and 0 edges"
>>> G = nx.path_graph(3) >>> str(G) 'Graph with 3 nodes and 2 edges'
""" return "".join( [ type(self).__name__, f" named {self.name!r}" if self.name else "", f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges", ] )
def __iter__(self): """Iterate over the nodes. Use: 'for n in G'.
Returns ------- niter : iterator An iterator over all nodes in the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [n for n in G] [0, 1, 2, 3] >>> list(G) [0, 1, 2, 3] """ return iter(self._node)
def __contains__(self, n): """Returns True if n is a node, False otherwise. Use: 'n in G'.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> 1 in G True """ try: return n in self._node except TypeError: return False
def __len__(self): """Returns the number of nodes in the graph. Use: 'len(G)'.
Returns ------- nnodes : int The number of nodes in the graph.
See Also -------- number_of_nodes: identical method order: identical method
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> len(G) 4
""" return len(self._node)
def __getitem__(self, n): """Returns a dict of neighbors of node n. Use: 'G[n]'.
Parameters ---------- n : node A node in the graph.
Returns ------- adj_dict : dictionary The adjacency dictionary for nodes connected to n.
Notes ----- G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G[0] AtlasView({1: {}}) """ return self.adj[n]
def add_node(self, node_for_adding, **attr): """Add a single node `node_for_adding` and update node attributes.
Parameters ---------- node_for_adding : node A node can be any hashable Python object except None. attr : keyword arguments, optional Set or change node attributes using key=value.
See Also -------- add_nodes_from
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_node(1) >>> G.add_node("Hello") >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_node(K3) >>> G.number_of_nodes() 3
Use keywords set/change node attributes:
>>> G.add_node(1, size=10) >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
Notes ----- A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be careful that the hash doesn't change on mutables. """ if node_for_adding not in self._node: if node_for_adding is None: raise ValueError("None cannot be a node") self._adj[node_for_adding] = self.adjlist_inner_dict_factory() attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory() attr_dict.update(attr) else: # update attr even if node already exists self._node[node_for_adding].update(attr) nx._clear_cache(self)
def add_nodes_from(self, nodes_for_adding, **attr): """Add multiple nodes.
Parameters ---------- nodes_for_adding : iterable container A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict. attr : keyword arguments, optional (default= no attributes) Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments.
See Also -------- add_node
Notes ----- When adding nodes from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_nodes)`, and pass this object to `G.add_nodes_from`.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_nodes_from("Hello") >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_nodes_from(K3) >>> sorted(G.nodes(), key=str) [0, 1, 2, 'H', 'e', 'l', 'o']
Use keywords to update specific node attributes for every node.
>>> G.add_nodes_from([1, 2], size=10) >>> G.add_nodes_from([3, 4], weight=0.4)
Use (node, attrdict) tuples to update attributes for specific nodes.
>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})]) >>> G.nodes[1]["size"] 11 >>> H = nx.Graph() >>> H.add_nodes_from(G.nodes(data=True)) >>> H.nodes[1]["size"] 11
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.Graph([(0, 1), (1, 2), (3, 4)]) >>> # wrong way - will raise RuntimeError >>> # G.add_nodes_from(n + 1 for n in G.nodes) >>> # correct way >>> G.add_nodes_from(list(n + 1 for n in G.nodes)) """ for n in nodes_for_adding: try: newnode = n not in self._node newdict = attr except TypeError: n, ndict = n newnode = n not in self._node newdict = attr.copy() newdict.update(ndict) if newnode: if n is None: raise ValueError("None cannot be a node") self._adj[n] = self.adjlist_inner_dict_factory() self._node[n] = self.node_attr_dict_factory() self._node[n].update(newdict) nx._clear_cache(self)
def remove_node(self, n): """Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a nonexistent node will raise an exception.
Parameters ---------- n : node A node in the graph
Raises ------ NetworkXError If n is not in the graph.
See Also -------- remove_nodes_from
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> list(G.edges) [(0, 1), (1, 2)] >>> G.remove_node(1) >>> list(G.edges) []
""" adj = self._adj try: nbrs = list(adj[n]) # list handles self-loops (allows mutation) del self._node[n] except KeyError as err: # NetworkXError if n not in self raise NetworkXError(f"The node {n} is not in the graph.") from err for u in nbrs: del adj[u][n] # remove all edges n-u in graph del adj[n] # now remove node nx._clear_cache(self)
def remove_nodes_from(self, nodes): """Remove multiple nodes.
Parameters ---------- nodes : iterable container A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.
See Also -------- remove_node
Notes ----- When removing nodes from an iterator over the graph you are changing, a `RuntimeError` will be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_nodes)`, and pass this object to `G.remove_nodes_from`.
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.Graph([(0, 1), (1, 2), (3, 4)]) >>> # this command will fail, as the graph's dict is modified during iteration >>> # G.remove_nodes_from(n for n in G.nodes if n < 2) >>> # this command will work, since the dictionary underlying graph is not modified >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2)) """ adj = self._adj for n in nodes: try: del self._node[n] for u in list(adj[n]): # list handles self-loops del adj[u][n] # (allows mutation of dict in loop) del adj[n] except KeyError: pass nx._clear_cache(self)
@cached_property def nodes(self): """A NodeView of the Graph as G.nodes or G.nodes().
Can be used as `G.nodes` for data lookup and for set-like operations. Can also be used as `G.nodes(data='color', default=None)` to return a NodeDataView which reports specific node data but no set operations. It presents a dict-like interface as well with `G.nodes.items()` iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']` providing the value of the `foo` attribute for node `3`. In addition, a view `G.nodes.data('foo')` provides a dict-like interface to the `foo` attribute of each node. `G.nodes.data('foo', default=1)` provides a default for nodes that do not have attribute `foo`.
Parameters ---------- data : string or bool, optional (default=False) The node attribute returned in 2-tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
default : value, optional (default=None) Value used for nodes that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- NodeView Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over `(n, data)` and has no set operations. A NodeView iterates over `n` and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in `data`. If data is True then the attribute becomes the entire data dictionary.
Notes ----- If your node data is not needed, it is simpler and equivalent to use the expression ``for n in G``, or ``list(G)``.
Examples -------- There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time="5pm") >>> G.nodes[0]["foo"] = "bar" >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data="foo")) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data("foo")) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data="time")) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data("time")) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data="time", default="Not Available")) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data("time", default="Not Available")) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the `default` keyword argument to guarantee the value is never None::
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data="weight", default=1)) {0: 1, 1: 2, 2: 3}
""" return NodeView(self)
def number_of_nodes(self): """Returns the number of nodes in the graph.
Returns ------- nnodes : int The number of nodes in the graph.
See Also -------- order: identical method __len__: identical method
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.number_of_nodes() 3 """ return len(self._node)
def order(self): """Returns the number of nodes in the graph.
Returns ------- nnodes : int The number of nodes in the graph.
See Also -------- number_of_nodes: identical method __len__: identical method
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.order() 3 """ return len(self._node)
def has_node(self, n): """Returns True if the graph contains the node n.
Identical to `n in G`
Parameters ---------- n : node
Examples -------- >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_node(0) True
It is more readable and simpler to use
>>> 0 in G True
""" try: return n in self._node except TypeError: return False
def add_edge(self, u_of_edge, v_of_edge, **attr): """Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge's attribute dictionary. See examples below.
Parameters ---------- u_of_edge, v_of_edge : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects. attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
See Also -------- add_edges_from : add a collection of edges
Notes ----- Adding an edge that already exists updates the edge data.
Many NetworkX algorithms designed for weighted graphs use an edge attribute (by default `weight`) to hold a numerical value.
Examples -------- The following all add the edge e=(1, 2) to graph G:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = (1, 2) >>> G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
Associate data to edges using keywords:
>>> G.add_edge(1, 2, weight=3) >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
For non-string attribute keys, use subscript notation.
>>> G.add_edge(1, 2) >>> G[1][2].update({0: 5}) >>> G.edges[1, 2].update({0: 5}) """ u, v = u_of_edge, v_of_edge # add nodes if u not in self._node: if u is None: raise ValueError("None cannot be a node") self._adj[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._node: if v is None: raise ValueError("None cannot be a node") self._adj[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() # add the edge datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) self._adj[u][v] = datadict self._adj[v][u] = datadict nx._clear_cache(self)
def add_edges_from(self, ebunch_to_add, **attr): """Add all the edges in ebunch_to_add.
Parameters ---------- ebunch_to_add : container of edges Each edge given in the container will be added to the graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary containing edge data. attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
See Also -------- add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Notes ----- Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
When adding edges from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_edges)`, and pass this object to `G.add_edges_from`.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)]) >>> # Grow graph by one new node, adding edges to all existing nodes. >>> # wrong way - will raise RuntimeError >>> # G.add_edges_from(((5, n) for n in G.nodes)) >>> # correct way - note that there will be no self-edge for node 5 >>> G.add_edges_from(list((5, n) for n in G.nodes)) """ for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == 2: u, v = e dd = {} # doesn't need edge_attr_dict_factory else: raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.") if u not in self._node: if u is None: raise ValueError("None cannot be a node") self._adj[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._node: if v is None: raise ValueError("None cannot be a node") self._adj[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(attr) datadict.update(dd) self._adj[u][v] = datadict self._adj[v][u] = datadict nx._clear_cache(self)
def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr): """Add weighted edges in `ebunch_to_add` with specified weight attr
Parameters ---------- ebunch_to_add : container of edges Each edge given in the list or container will be added to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number. weight : string, optional (default= 'weight') The attribute name for the edge weights to be added. attr : keyword arguments, optional (default= no attributes) Edge attributes to add/update for all edges.
See Also -------- add_edge : add a single edge add_edges_from : add multiple edges
Notes ----- Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph, duplicate edges are stored.
When adding edges from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_edges)`, and pass this object to `G.add_weighted_edges_from`.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
Evaluate an iterator over edges before passing it
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)]) >>> weight = 0.1 >>> # Grow graph by one new node, adding edges to all existing nodes. >>> # wrong way - will raise RuntimeError >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes)) >>> # correct way - note that there will be no self-edge for node 5 >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes)) """ self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr) nx._clear_cache(self)
def remove_edge(self, u, v): """Remove the edge between u and v.
Parameters ---------- u, v : nodes Remove the edge between nodes u and v.
Raises ------ NetworkXError If there is not an edge between u and v.
See Also -------- remove_edges_from : remove a collection of edges
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, etc >>> G.remove_edge(0, 1) >>> e = (1, 2) >>> G.remove_edge(*e) # unpacks e from an edge tuple >>> e = (2, 3, {"weight": 7}) # an edge with attribute data >>> G.remove_edge(*e[:2]) # select first part of edge tuple """ try: del self._adj[u][v] if u != v: # self-loop needs only one entry removed del self._adj[v][u] except KeyError as err: raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err nx._clear_cache(self)
def remove_edges_from(self, ebunch): """Remove all edges specified in ebunch.
Parameters ---------- ebunch: list or container of edge tuples Each edge given in the list or container will be removed from the graph. The edges can be:
- 2-tuples (u, v) edge between u and v. - 3-tuples (u, v, k) where k is ignored.
See Also -------- remove_edge : remove a single edge
Notes ----- Will fail silently if an edge in ebunch is not in the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch = [(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch) """ adj = self._adj for e in ebunch: u, v = e[:2] # ignore edge data if present if u in adj and v in adj[u]: del adj[u][v] if u != v: # self loop needs only one entry removed del adj[v][u] nx._clear_cache(self)
def update(self, edges=None, nodes=None): """Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph's nodes and edges to this graph. It can also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword `nodes` must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods. When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters ---------- edges : Graph object, collection of edges, or None The first parameter can be a graph or some edges. If it has attributes `nodes` and `edges`, then it is taken to be a Graph-like object and those attributes are used as collections of nodes and edges to be added to the graph. If the first parameter does not have those attributes, it is treated as a collection of edges and added to the graph. If the first argument is None, no edges are added. nodes : collection of nodes, or None The second parameter is treated as a collection of nodes to be added to the graph unless it is None. If `edges is None` and `nodes is None` an exception is raised. If the first parameter is a Graph, then `nodes` is ignored.
Examples -------- >>> G = nx.path_graph(5) >>> G.update(nx.complete_graph(range(4, 10))) >>> from itertools import combinations >>> edges = ( ... (u, v, {"power": u * v}) ... for u, v in combinations(range(10, 20), 2) ... if u * v < 225 ... ) >>> nodes = [1000] # for singleton, use a container >>> G.update(edges, nodes)
Notes ----- It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from adjacency. The following examples provide common cases, your adjacency may be slightly different and require tweaks of these examples::
>>> # dict-of-set/list/tuple >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}} >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs] >>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph() >>> # dict-of-dict-of-attribute >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}} >>> e = [ ... (u, v, {"weight": d}) ... for u, nbrs in adj.items() ... for v, d in nbrs.items() ... ] >>> DG.update(edges=e, nodes=adj)
>>> # dict-of-dict-of-dict >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}} >>> e = [ ... (u, v, {"weight": d}) ... for u, nbrs in adj.items() ... for v, d in nbrs.items() ... ] >>> DG.update(edges=e, nodes=adj)
>>> # predecessor adjacency (dict-of-set) >>> pred = {1: {2, 3}, 2: {3}, 3: {3}} >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
>>> # MultiGraph dict-of-dict-of-dict-of-attribute >>> MDG = nx.MultiDiGraph() >>> adj = { ... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}}, ... 3: {2: {0: {"weight": 0.7}}}, ... } >>> e = [ ... (u, v, ekey, d) ... for u, nbrs in adj.items() ... for v, keydict in nbrs.items() ... for ekey, d in keydict.items() ... ] >>> MDG.update(edges=e)
See Also -------- add_edges_from: add multiple edges to a graph add_nodes_from: add multiple nodes to a graph """ if edges is not None: if nodes is not None: self.add_nodes_from(nodes) self.add_edges_from(edges) else: # check if edges is a Graph object try: graph_nodes = edges.nodes graph_edges = edges.edges except AttributeError: # edge not Graph-like self.add_edges_from(edges) else: # edges is Graph-like self.add_nodes_from(graph_nodes.data()) self.add_edges_from(graph_edges.data()) self.graph.update(edges.graph) elif nodes is not None: self.add_nodes_from(nodes) else: raise NetworkXError("update needs nodes or edges input")
def has_edge(self, u, v): """Returns True if the edge (u, v) is in the graph.
This is the same as `v in G[u]` without KeyError exceptions.
Parameters ---------- u, v : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
Returns ------- edge_ind : bool True if edge is in the graph, False otherwise.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2-tuple (u, v) True >>> e = (0, 1, {"weight": 7}) >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary) True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives KeyError if 0 not in G True
""" try: return v in self._adj[u] except KeyError: return False
def neighbors(self, n): """Returns an iterator over all neighbors of node n.
This is identical to `iter(G[n])`
Parameters ---------- n : node A node in the graph
Returns ------- neighbors : iterator An iterator over all neighbors of node n
Raises ------ NetworkXError If the node n is not in the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [n for n in G.neighbors(0)] [1]
Notes ----- Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge("a", "b", weight=7) >>> G["a"] AtlasView({'b': {'weight': 7}}) >>> G = nx.path_graph(4) >>> [n for n in G[0]] [1] """ try: return iter(self._adj[n]) except KeyError as err: raise NetworkXError(f"The node {n} is not in the graph.") from err
@cached_property def edges(self): """An EdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, `G.edges[u, v]['color']` provides the value of the color attribute for edge `(u, v)` while `for (u, v, c) in G.edges.data('color', default='red'):` iterates through all the edges yielding the color attribute with default `'red'` if no color attribute exists.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges from these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- edges : EdgeView A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as `edges[u, v]['foo']`.
Notes ----- Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples -------- >>> G = nx.path_graph(3) # or MultiGraph, etc >>> G.add_edge(2, 3, weight=5) >>> [e for e in G.edges] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data("weight", default=1) EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges([0, 3]) # only edges from these nodes EdgeDataView([(0, 1), (3, 2)]) >>> G.edges(0) # only edges from node 0 EdgeDataView([(0, 1)]) """ return EdgeView(self)
def get_edge_data(self, u, v, default=None): """Returns the attribute dictionary associated with edge (u, v).
This is identical to `G[u][v]` except the default is returned instead of an exception if the edge doesn't exist.
Parameters ---------- u, v : nodes default: any Python object (default=None) Value to return if the edge (u, v) is not found.
Returns ------- edge_dict : dictionary The edge attribute dictionary.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G[0][1] {}
Warning: Assigning to `G[u][v]` is not permitted. But it is safe to assign attributes `G[u][v]['foo']`
>>> G[0][1]["weight"] = 7 >>> G[0][1]["weight"] 7 >>> G[1][0]["weight"] 7
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.get_edge_data(0, 1) # default edge data is {} {} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {} >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0 0 """ try: return self._adj[u][v] except KeyError: return default
def adjacency(self): """Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns ------- adj_iter : iterator An iterator over (node, adjacency dictionary) for all nodes in the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [(n, nbrdict) for n, nbrdict in G.adjacency()] [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
""" return iter(self._adj.items())
@cached_property def degree(self): """A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- DegreeView or int If multiple nodes are requested (the default), returns a `DegreeView` mapping nodes to their degree. If a single node is requested, returns the degree of the node as an integer.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.degree[0] # node 0 has degree 1 1 >>> list(G.degree([0, 1, 2])) [(0, 1), (1, 2), (2, 2)] """ return DegreeView(self)
def clear(self): """Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear() >>> list(G.nodes) [] >>> list(G.edges) []
""" self._adj.clear() self._node.clear() self.graph.clear() nx._clear_cache(self)
def clear_edges(self): """Remove all edges from the graph without altering nodes.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear_edges() >>> list(G.nodes) [0, 1, 2, 3] >>> list(G.edges) [] """ for nbr_dict in self._adj.values(): nbr_dict.clear() nx._clear_cache(self)
def is_multigraph(self): """Returns True if graph is a multigraph, False otherwise.""" return False
def is_directed(self): """Returns True if graph is directed, False otherwise.""" return False
def copy(self, as_view=False): """Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python's `copy.deepcopy` for new containers.
If `as_view` is True then a view is returned instead of a copy.
Notes ----- All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.
Deepcopy -- A "deepcopy" copies the graph structure as well as all data attributes and any objects they might contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python's copy.deepcopy)
Data Reference (Shallow) -- For a shallow copy the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this level of shallow copy.
Independent Shallow -- This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what `dict.copy()` provides. You can obtain this style copy using:
>>> G = nx.path_graph(5) >>> H = G.copy() >>> H = G.copy(as_view=False) >>> H = nx.Graph(G) >>> H = G.__class__(G)
Fresh Data -- For fresh data, the graph structure is copied while new empty data attribute dicts are created. The resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not enabled. Instead use:
>>> H = G.__class__() >>> H.add_nodes_from(G) >>> H.add_edges_from(G.edges)
View -- Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Parameters ---------- as_view : bool, optional (default=False) If True, the returned graph-view provides a read-only view of the original graph without actually copying any data.
Returns ------- G : Graph A copy of the graph.
See Also -------- to_directed: return a directed copy of the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.copy()
""" if as_view is True: return nx.graphviews.generic_graph_view(self) G = self.__class__() G.graph.update(self.graph) G.add_nodes_from((n, d.copy()) for n, d in self._node.items()) G.add_edges_from( (u, v, datadict.copy()) for u, nbrs in self._adj.items() for v, datadict in nbrs.items() ) return G
def to_directed(self, as_view=False): """Returns a directed representation of the graph.
Returns ------- G : DiGraph A directed graph with the same name, same nodes, and with each edge (u, v, data) replaced by two directed edges (u, v, data) and (v, u, data).
Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not transfer to the DiGraph created by this method.
Examples -------- >>> G = nx.Graph() # or MultiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)] """ graph_class = self.to_directed_class() if as_view is True: return nx.graphviews.generic_graph_view(self, graph_class) # deepcopy when not a view G = graph_class() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) G.add_edges_from( (u, v, deepcopy(data)) for u, nbrs in self._adj.items() for v, data in nbrs.items() ) return G
def to_undirected(self, as_view=False): """Returns an undirected copy of the graph.
Parameters ---------- as_view : bool (optional, default=False) If True return a view of the original undirected graph.
Returns ------- G : Graph/MultiGraph A deepcopy of the graph.
See Also -------- Graph, copy, add_edge, add_edges_from
Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar `G = nx.DiGraph(D)` which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not transfer to the Graph created by this method.
Examples -------- >>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)] """ graph_class = self.to_undirected_class() if as_view is True: return nx.graphviews.generic_graph_view(self, graph_class) # deepcopy when not a view G = graph_class() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) G.add_edges_from( (u, v, deepcopy(d)) for u, nbrs in self._adj.items() for v, d in nbrs.items() ) return G
def subgraph(self, nodes): """Returns a SubGraph view of the subgraph induced on `nodes`.
The induced subgraph of the graph contains the nodes in `nodes` and the edges between those nodes.
Parameters ---------- nodes : list, iterable A container of nodes which will be iterated through once.
Returns ------- G : SubGraph View A subgraph view of the graph. The graph structure cannot be changed but node/edge attributes can and are shared with the original graph.
Notes ----- The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
::
# Create a subgraph SG based on a (possibly multigraph) G SG = G.__class__() SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc) if SG.is_multigraph(): SG.add_edges_from( (n, nbr, key, d) for n, nbrs in G.adj.items() if n in largest_wcc for nbr, keydict in nbrs.items() if nbr in largest_wcc for key, d in keydict.items() ) else: SG.add_edges_from( (n, nbr, d) for n, nbrs in G.adj.items() if n in largest_wcc for nbr, d in nbrs.items() if nbr in largest_wcc ) SG.graph.update(G.graph)
Subgraphs are not guaranteed to preserve the order of nodes or edges as they appear in the original graph. For example:
>>> G = nx.Graph() >>> G.add_nodes_from(reversed(range(10))) >>> list(G) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> list(G.subgraph([1, 3, 2])) [1, 2, 3]
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.subgraph([0, 1, 2]) >>> list(H.edges) [(0, 1), (1, 2)] """ induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes)) # if already a subgraph, don't make a chain subgraph = nx.subgraph_view if hasattr(self, "_NODE_OK"): return subgraph( self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK ) return subgraph(self, filter_node=induced_nodes)
def edge_subgraph(self, edges): """Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in `edges` and each node incident to any one of those edges.
Parameters ---------- edges : iterable An iterable of edges in this graph.
Returns ------- G : Graph An edge-induced subgraph of this graph with the same edge attributes.
Notes ----- The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use::
G.edge_subgraph(edges).copy()
Examples -------- >>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)]
""" return nx.edge_subgraph(self, edges)
def size(self, weight=None): """Returns the number of edges or total of all edge weights.
Parameters ---------- weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
Returns ------- size : numeric The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are more general).
See Also -------- number_of_edges
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.size() 3
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge("a", "b", weight=2) >>> G.add_edge("b", "c", weight=4) >>> G.size() 2 >>> G.size(weight="weight") 6.0 """ s = sum(d for v, d in self.degree(weight=weight)) # If `weight` is None, the sum of the degrees is guaranteed to be # even, so we can perform integer division and hence return an # integer. Otherwise, the sum of the weighted degrees is not # guaranteed to be an integer, so we perform "real" division. return s // 2 if weight is None else s / 2
def number_of_edges(self, u=None, v=None): """Returns the number of edges between two nodes.
Parameters ---------- u, v : nodes, optional (default=all edges) If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.
Returns ------- nedges : int The number of edges in the graph. If nodes `u` and `v` are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from `u` to `v`.
See Also -------- size
Examples -------- For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4) >>> G.number_of_edges() 3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1) 1
For directed graphs, this method can count the total number of directed edges from `u` to `v`:
>>> G = nx.DiGraph() >>> G.add_edge(0, 1) >>> G.add_edge(1, 0) >>> G.number_of_edges(0, 1) 1
""" if u is None: return int(self.size()) if v in self._adj[u]: return 1 return 0
def nbunch_iter(self, nbunch=None): """Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in an iterable nbunch are checked for membership in the graph and if not are silently ignored.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
Returns ------- niter : iterator An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate over all nodes in the graph.
Raises ------ NetworkXError If nbunch is not a node or sequence of nodes. If a node in nbunch is not hashable.
See Also -------- Graph.__iter__
Notes ----- When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when nbunch is exhausted.
To test whether nbunch is a single node, one can use "if nbunch in self:", even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a :exc:`NetworkXError` is raised. Also, if any object in nbunch is not hashable, a :exc:`NetworkXError` is raised. """ if nbunch is None: # include all nodes via iterator bunch = iter(self._adj) elif nbunch in self: # if nbunch is a single node bunch = iter([nbunch]) else: # if nbunch is a sequence of nodes
def bunch_iter(nlist, adj): try: for n in nlist: if n in adj: yield n except TypeError as err: exc, message = err, err.args[0] # capture error for non-sequence/iterator nbunch. if "iter" in message: exc = NetworkXError( "nbunch is not a node or a sequence of nodes." ) # capture single nodes that are not in the graph. if "object is not iterable" in message: exc = NetworkXError(f"Node {nbunch} is not in the graph.") # capture error for unhashable node. if "hashable" in message: exc = NetworkXError( f"Node {n} in sequence nbunch is not a valid node." ) raise exc
bunch = bunch_iter(nbunch, self._adj) return bunch123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269"""View of Graphs as SubGraph, Reverse, Directed, Undirected.
In some algorithms it is convenient to temporarily morpha graph to exclude some nodes or edges. It should be betterto do that via a view than to remove and then re-add.In other algorithms it is convenient to temporarily morpha graph to reverse directed edges, or treat a directed graphas undirected, etc. This module provides those graph views.
The resulting views are essentially read-only graphs thatreport data from the original graph object. We provide anattribute G._graph which points to the underlying graph object.
Note: Since graphviews look like graphs, one can end up withview-of-view-of-view chains. Be careful with chains becausethey become very slow with about 15 nested views.For the common simple case of node induced subgraphs createdfrom the graph class, we short-cut the chain by returning asubgraph of the original graph directly rather than a subgraphof a subgraph. We are careful not to disrupt any edge filter inthe middle subgraph. In general, determining how to short-cutthe chain is tricky and much harder with restricted_views thanwith induced subgraphs.Often it is easiest to use .copy() to avoid chains."""
import networkx as nxfrom networkx.classes.coreviews import ( FilterAdjacency, FilterAtlas, FilterMultiAdjacency, UnionAdjacency, UnionMultiAdjacency,)from networkx.classes.filters import no_filterfrom networkx.exception import NetworkXErrorfrom networkx.utils import not_implemented_for
__all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
def generic_graph_view(G, create_using=None): """Returns a read-only view of `G`.
The graph `G` and its attributes are not copied but viewed through the new graph object of the same class as `G` (or of the class specified in `create_using`).
Parameters ---------- G : graph A directed/undirected graph/multigraph.
create_using : NetworkX graph constructor, optional (default=None) Graph type to create. If graph instance, then cleared before populated. If `None`, then the appropriate Graph type is inferred from `G`.
Returns ------- newG : graph A view of the input graph `G` and its attributes as viewed through the `create_using` class.
Raises ------ NetworkXError If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
Notes ----- The returned graph view is read-only (cannot modify the graph). Yet the view reflects any changes in `G`. The intent is to mimic dict views.
Examples -------- >>> G = nx.Graph() >>> G.add_edge(1, 2, weight=0.3) >>> G.add_edge(2, 3, weight=0.5) >>> G.edges(data=True) EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
The view exposes the attributes from the original graph.
>>> viewG = nx.graphviews.generic_graph_view(G) >>> viewG.edges(data=True) EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
Changes to `G` are reflected in `viewG`.
>>> G.remove_edge(2, 3) >>> G.edges(data=True) EdgeDataView([(1, 2, {'weight': 0.3})])
>>> viewG.edges(data=True) EdgeDataView([(1, 2, {'weight': 0.3})])
We can change the graph type with the `create_using` parameter.
>>> type(G) <class 'networkx.classes.graph.Graph'> >>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph) >>> type(viewDG) <class 'networkx.classes.digraph.DiGraph'> """ if create_using is None: newG = G.__class__() else: newG = nx.empty_graph(0, create_using) if G.is_multigraph() != newG.is_multigraph(): raise NetworkXError("Multigraph for G must agree with create_using") newG = nx.freeze(newG)
# create view by assigning attributes from G newG._graph = G newG.graph = G.graph
newG._node = G._node if newG.is_directed(): if G.is_directed(): newG._succ = G._succ newG._pred = G._pred # newG._adj is synced with _succ else: newG._succ = G._adj newG._pred = G._adj # newG._adj is synced with _succ elif G.is_directed(): if G.is_multigraph(): newG._adj = UnionMultiAdjacency(G._succ, G._pred) else: newG._adj = UnionAdjacency(G._succ, G._pred) else: newG._adj = G._adj return newG
def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter): """View of `G` applying a filter on nodes and edges.
`subgraph_view` provides a read-only view of the input graph that excludes nodes and edges based on the outcome of two filter functions `filter_node` and `filter_edge`.
The `filter_node` function takes one argument --- the node --- and returns `True` if the node should be included in the subgraph, and `False` if it should not be included.
The `filter_edge` function takes two (or three arguments if `G` is a multi-graph) --- the nodes describing an edge, plus the edge-key if parallel edges are possible --- and returns `True` if the edge should be included in the subgraph, and `False` if it should not be included.
Both node and edge filter functions are called on graph elements as they are queried, meaning there is no up-front cost to creating the view.
Parameters ---------- G : networkx.Graph A directed/undirected graph/multigraph
filter_node : callable, optional A function taking a node as input, which returns `True` if the node should appear in the view.
filter_edge : callable, optional A function taking as input the two nodes describing an edge (plus the edge-key if `G` is a multi-graph), which returns `True` if the edge should appear in the view.
Returns ------- graph : networkx.Graph A read-only graph view of the input graph.
Examples -------- >>> G = nx.path_graph(6)
Filter functions operate on the node, and return `True` if the node should appear in the view:
>>> def filter_node(n1): ... return n1 != 5 >>> view = nx.subgraph_view(G, filter_node=filter_node) >>> view.nodes() NodeView((0, 1, 2, 3, 4))
We can use a closure pattern to filter graph elements based on additional data --- for example, filtering on edge data attached to the graph:
>>> G[3][4]["cross_me"] = False >>> def filter_edge(n1, n2): ... return G[n1][n2].get("cross_me", True) >>> view = nx.subgraph_view(G, filter_edge=filter_edge) >>> view.edges() EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
>>> view = nx.subgraph_view( ... G, ... filter_node=filter_node, ... filter_edge=filter_edge, ... ) >>> view.nodes() NodeView((0, 1, 2, 3, 4)) >>> view.edges() EdgeView([(0, 1), (1, 2), (2, 3)]) """ newG = nx.freeze(G.__class__()) newG._NODE_OK = filter_node newG._EDGE_OK = filter_edge
# create view by assigning attributes from G newG._graph = G newG.graph = G.graph
newG._node = FilterAtlas(G._node, filter_node) if G.is_multigraph(): Adj = FilterMultiAdjacency
def reverse_edge(u, v, k=None): return filter_edge(v, u, k)
else: Adj = FilterAdjacency
def reverse_edge(u, v, k=None): return filter_edge(v, u)
if G.is_directed(): newG._succ = Adj(G._succ, filter_node, filter_edge) newG._pred = Adj(G._pred, filter_node, reverse_edge) # newG._adj is synced with _succ else: newG._adj = Adj(G._adj, filter_node, filter_edge) return newG
@not_implemented_for("undirected")def reverse_view(G): """View of `G` with edge directions reversed
`reverse_view` returns a read-only view of the input graph where edge directions are reversed.
Identical to digraph.reverse(copy=False)
Parameters ---------- G : networkx.DiGraph
Returns ------- graph : networkx.DiGraph
Examples -------- >>> G = nx.DiGraph() >>> G.add_edge(1, 2) >>> G.add_edge(2, 3) >>> G.edges() OutEdgeView([(1, 2), (2, 3)])
>>> view = nx.reverse_view(G) >>> view.edges() OutEdgeView([(2, 1), (3, 2)]) """ newG = generic_graph_view(G) newG._succ, newG._pred = G._pred, G._succ # newG._adj is synced with _succ return newG123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977"""Base class for MultiDiGraph."""
from copy import deepcopyfrom functools import cached_property
import networkx as nxfrom networkx import convertfrom networkx.classes.coreviews import MultiAdjacencyViewfrom networkx.classes.digraph import DiGraphfrom networkx.classes.multigraph import MultiGraphfrom networkx.classes.reportviews import ( DiMultiDegreeView, InMultiDegreeView, InMultiEdgeView, OutMultiDegreeView, OutMultiEdgeView,)from networkx.exception import NetworkXError
__all__ = ["MultiDiGraph"]
class MultiDiGraph(MultiGraph, DiGraph): """A directed graph class that can store multiedges.
Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.
A MultiDiGraph holds directed edges. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention `None` is not used as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters ---------- incoming_graph_data : input graph (optional, default: None) Data to initialize graph. If None (default) an empty graph is created. The data can be any format that is supported by the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy sparse matrix, or PyGraphviz graph.
multigraph_input : bool or None (default None) Note: Only used when `incoming_graph_data` is a dict. If True, `incoming_graph_data` is assumed to be a dict-of-dict-of-dict-of-dict structure keyed by node to neighbor to edge keys to edge data for multi-edges. A NetworkXError is raised if this is not the case. If False, :func:`to_networkx_graph` is used to try to determine the dict's graph data structure as either a dict-of-dict-of-dict keyed by node to neighbor to edge data, or a dict-of-iterable keyed by node to neighbors. If None, the treatment for True is tried, but if it fails, the treatment for False is tried.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- Graph DiGraph MultiGraph
Examples -------- Create an empty graph structure (a "null graph") with no nodes and no edges.
>>> G = nx.MultiDiGraph()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2, 3]) >>> G.add_nodes_from(range(100, 110)) >>> H = nx.path_graph(10) >>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a customized node object, or even another Graph.
>>> G.add_node(H)
**Edges:**
G can also be grown by adding edges.
Add one edge,
>>> key = G.add_edge(1, 2)
a list of edges,
>>> keys = G.add_edges_from([(1, 2), (1, 3)])
or a collection of edges,
>>> keys = G.add_edges_from(H.edges)
If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists, an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused integer.
>>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))]) >>> G[4] AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
**Attributes:**
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.MultiDiGraph(day="Friday") >>> G.graph {'day': 'Friday'}
Add node attributes using add_node(), add_nodes_from() or G.nodes
>>> G.add_node(1, time="5pm") >>> G.add_nodes_from([3], time="2pm") >>> G.nodes[1] {'time': '5pm'} >>> G.nodes[1]["room"] = 714 >>> del G.nodes[1]["room"] # remove attribute >>> list(G.nodes(data=True)) [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edges.
>>> key = G.add_edge(1, 2, weight=4.7) >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red") >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})]) >>> G[1][2][0]["weight"] = 4.7 >>> G.edges[1, 2, 0]["weight"] = 4
Warning: we protect the graph data structure by making `G.edges[1, 2, 0]` a read-only dict-like structure. However, you can assign to attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4` (for multigraphs the edge key is required: `MG.edges[u, v, key][name] = value`).
**Shortcuts:**
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph True >>> [n for n in G if n < 3] # iterate through nodes [1, 2] >>> len(G) # number of nodes in graph 5 >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are available as an adjacency-view `G.adj` object or via the method `G.adjacency()`.
>>> for n, nbrsdict in G.adjacency(): ... for nbr, keydict in nbrsdict.items(): ... for key, eattr in keydict.items(): ... if "weight" in eattr: ... # Do something useful with the edges ... pass
But the edges() method is often more convenient:
>>> for u, v, keys, weight in G.edges(data="weight", keys=True): ... if weight is not None: ... # Do something useful with the edges ... pass
**Reporting:**
Simple graph information is obtained using methods and object-attributes. Reporting usually provides views instead of containers to reduce memory usage. The views update as the graph is updated similarly to dict-views. The objects `nodes`, `edges` and `adj` provide access to data attributes via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration (e.g. `nodes.items()`, `nodes.data('color')`, `nodes.data('color', default='blue')` and similarly for `edges`) Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
For details on these and other miscellaneous methods, see below.
**Subclasses (Advanced):**
The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure. The outer dict (node_dict) holds adjacency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge_key dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like object. In general, the dict-like features should be maintained but extra features can be added. To replace one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory : function, (default: dict) Factory function to be used to create the dict containing node attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object
adjlist_outer_dict_factory : function, (default: dict) Factory function to be used to create the outer-most dict in the data structure that holds adjacency info keyed by node. It should require no arguments and return a dict-like object.
adjlist_inner_dict_factory : function, (default: dict) Factory function to be used to create the adjacency list dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a dict-like object.
edge_key_dict_factory : function, (default: dict) Factory function to be used to create the edge key dict which holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory : function, (default: dict) Factory function to be used to create the edge attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
graph_attr_dict_factory : function, (default: dict) Factory function to be used to create the graph attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
Typically, if your extension doesn't impact the data structure all methods will inherited without issue except: `to_directed/to_undirected`. By default these methods create a DiGraph/Graph class and you probably want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you can set in your subclass.
to_directed_class : callable, (default: DiGraph or MultiDiGraph) Class to create a new graph structure in the `to_directed` method. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class : callable, (default: Graph or MultiGraph) Class to create a new graph structure in the `to_undirected` method. If `None`, a NetworkX class (Graph or MultiGraph) is used.
**Subclassing Example**
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all edges. This reduces the memory used, but you lose edge attributes.
>>> class ThinGraph(nx.Graph): ... all_edge_dict = {"weight": 1} ... ... def single_edge_dict(self): ... return self.all_edge_dict ... ... edge_attr_dict_factory = single_edge_dict >>> G = ThinGraph() >>> G.add_edge(2, 1) >>> G[2][1] {'weight': 1} >>> G.add_edge(2, 2) >>> G[2][1] is G[2][2] True """
# node_dict_factory = dict # already assigned in Graph # adjlist_outer_dict_factory = dict # adjlist_inner_dict_factory = dict edge_key_dict_factory = dict # edge_attr_dict_factory = dict
# This __new__ method just does what Python itself does automatically. # We include it here as part of the dispatchable/backend interface. # If your goal is to understand how the graph classes work, you can ignore # this method, even when subclassing the base classes. If you are subclassing # in order to provide a backend that allows class instantiation, this method # can be overridden to return your own backend graph class. @nx._dispatchable(name="multidigraph__new__", graphs=None, returns_graph=True) def __new__(cls, *args, **kwargs): return object.__new__(cls)
def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr): """Initialize a graph with edges, name, or graph attributes.
Parameters ---------- incoming_graph_data : input graph Data to initialize graph. If incoming_graph_data=None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a 2D NumPy array, a SciPy sparse array, or a PyGraphviz graph.
multigraph_input : bool or None (default None) Note: Only used when `incoming_graph_data` is a dict. If True, `incoming_graph_data` is assumed to be a dict-of-dict-of-dict-of-dict structure keyed by node to neighbor to edge keys to edge data for multi-edges. A NetworkXError is raised if this is not the case. If False, :func:`to_networkx_graph` is used to try to determine the dict's graph data structure as either a dict-of-dict-of-dict keyed by node to neighbor to edge data, or a dict-of-iterable keyed by node to neighbors. If None, the treatment for True is tried, but if it fails, the treatment for False is tried.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- convert
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G = nx.Graph(name="my graph") >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges >>> G = nx.Graph(e)
Arbitrary graph attribute pairs (key=value) may be assigned
>>> G = nx.Graph(e, day="Friday") >>> G.graph {'day': 'Friday'}
""" attr.pop("backend", None) # Ignore explicit `backend="networkx"` # multigraph_input can be None/True/False. So check "is not False" if isinstance(incoming_graph_data, dict) and multigraph_input is not False: DiGraph.__init__(self) try: convert.from_dict_of_dicts( incoming_graph_data, create_using=self, multigraph_input=True ) self.graph.update(attr) except Exception as err: if multigraph_input is True: raise nx.NetworkXError( f"converting multigraph_input raised:\n{type(err)}: {err}" ) DiGraph.__init__(self, incoming_graph_data, **attr) else: DiGraph.__init__(self, incoming_graph_data, **attr)
@cached_property def adj(self): """Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets the color of the edge `(3, 2, 0)` to `"blue"`.
Iterating over G.adj behaves like a dict. Useful idioms include `for nbr, datadict in G.adj[n].items():`.
The neighbor information is also provided by subscripting the graph. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
For directed graphs, `G.adj` holds outgoing (successor) info. """ return MultiAdjacencyView(self._succ)
@cached_property def succ(self): """Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets the color of the edge `(3, 2, 0)` to `"blue"`.
Iterating over G.adj behaves like a dict. Useful idioms include `for nbr, datadict in G.adj[n].items():`.
The neighbor information is also provided by subscripting the graph. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
For directed graphs, `G.succ` is identical to `G.adj`. """ return MultiAdjacencyView(self._succ)
@cached_property def pred(self): """Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets the color of the edge `(3, 2, 0)` to `"blue"`.
Iterating over G.adj behaves like a dict. Useful idioms include `for nbr, datadict in G.adj[n].items():`. """ return MultiAdjacencyView(self._pred)
def add_edge(self, u_for_edge, v_for_edge, key=None, **attr): """Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge's attribute dictionary. See examples below.
Parameters ---------- u_for_edge, v_for_edge : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects. key : hashable identifier, optional (default=lowest unused integer) Used to distinguish multiedges between a pair of nodes. attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
Returns ------- The edge key assigned to the edge.
See Also -------- add_edges_from : add a collection of edges
Notes ----- To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear how to handle multiedge weights. Convert to Graph using edge attribute 'weight' to enable weighted graph algorithms.
Default keys are generated using the method `new_edge_key()`. This method can be overridden by subclassing the base class and providing a custom `new_edge_key()` method.
Examples -------- The following all add the edge e=(1, 2) to graph G:
>>> G = nx.MultiDiGraph() >>> e = (1, 2) >>> key = G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes 1 >>> G.add_edges_from([(1, 2)]) # add edges from iterable container [2]
Associate data to edges using keywords:
>>> key = G.add_edge(1, 2, weight=3) >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0 >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
For non-string attribute keys, use subscript notation.
>>> ekey = G.add_edge(1, 2) >>> G[1][2][0].update({0: 5}) >>> G.edges[1, 2, 0].update({0: 5}) """ u, v = u_for_edge, v_for_edge # add nodes if u not in self._succ: if u is None: raise ValueError("None cannot be a node") self._succ[u] = self.adjlist_inner_dict_factory() self._pred[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._succ: if v is None: raise ValueError("None cannot be a node") self._succ[v] = self.adjlist_inner_dict_factory() self._pred[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() if key is None: key = self.new_edge_key(u, v) if v in self._succ[u]: keydict = self._adj[u][v] datadict = keydict.get(key, self.edge_attr_dict_factory()) datadict.update(attr) keydict[key] = datadict else: # selfloops work this way without special treatment datadict = self.edge_attr_dict_factory() datadict.update(attr) keydict = self.edge_key_dict_factory() keydict[key] = datadict self._succ[u][v] = keydict self._pred[v][u] = keydict nx._clear_cache(self) return key
def remove_edge(self, u, v, key=None): """Remove an edge between u and v.
Parameters ---------- u, v : nodes Remove an edge between nodes u and v. key : hashable identifier, optional (default=None) Used to distinguish multiple edges between a pair of nodes. If None, remove a single edge between u and v. If there are multiple edges, removes the last edge added in terms of insertion order.
Raises ------ NetworkXError If there is not an edge between u and v, or if there is no edge with the specified key.
See Also -------- remove_edges_from : remove a collection of edges
Examples -------- >>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.remove_edge(0, 1) >>> e = (1, 2) >>> G.remove_edge(*e) # unpacks e from an edge tuple
For multiple edges
>>> G = nx.MultiDiGraph() >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned [0, 1, 2]
When ``key=None`` (the default), edges are removed in the opposite order that they were added:
>>> G.remove_edge(1, 2) >>> G.edges(keys=True) OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
For edges with keys
>>> G = nx.MultiDiGraph() >>> G.add_edge(1, 2, key="first") 'first' >>> G.add_edge(1, 2, key="second") 'second' >>> G.remove_edge(1, 2, key="first") >>> G.edges(keys=True) OutMultiEdgeView([(1, 2, 'second')])
""" try: d = self._adj[u][v] except KeyError as err: raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err # remove the edge with specified data if key is None: d.popitem() else: try: del d[key] except KeyError as err: msg = f"The edge {u}-{v} with key {key} is not in the graph." raise NetworkXError(msg) from err if len(d) == 0: # remove the key entries if last edge del self._succ[u][v] del self._pred[v][u] nx._clear_cache(self)
@cached_property def edges(self): """An OutMultiEdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, ``G.edges[u, v, k]['color']`` provides the value of the color attribute for the edge from ``u`` to ``v`` with key ``k`` while ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):`` iterates through all the edges yielding the color attribute with default `'red'` if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data). If ``keys=True`` is not provided, the tuples will just be (node, neighbor, data), but multiple tuples with the same node and neighbor will be generated when multiple edges between two nodes exist.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges from these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). keys : bool, optional (default=False) If True, return edge keys with each edge, creating (u, v, k, d) tuples when data is also requested (the default) and (u, v, k) tuples when data is not requested. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- edges : OutMultiEdgeView A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as ``edges[u, v, k]['foo']``.
Notes ----- Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples -------- >>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2]) >>> key = G.add_edge(2, 3, weight=5) >>> key2 = G.add_edge(1, 2) # second edge between these nodes >>> [e for e in G.edges()] [(0, 1), (1, 2), (1, 2), (2, 3)] >>> list(G.edges(data=True)) # default data is {} (empty dict) [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})] >>> list(G.edges(data="weight", default=1)) [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)] >>> list(G.edges(keys=True)) # default keys are integers [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)] >>> list(G.edges(data=True, keys=True)) [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})] >>> list(G.edges(data="weight", default=1, keys=True)) [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)] >>> list(G.edges([0, 2])) [(0, 1), (2, 3)] >>> list(G.edges(0)) [(0, 1)] >>> list(G.edges(1)) [(1, 2), (1, 2)]
See Also -------- in_edges, out_edges """ return OutMultiEdgeView(self)
# alias out_edges to edges @cached_property def out_edges(self): return OutMultiEdgeView(self)
out_edges.__doc__ = edges.__doc__
@cached_property def in_edges(self): """A view of the in edges of the graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, keys=False, default=None)
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). keys : bool, optional (default=False) If True, return edge keys with each edge, creating 3-tuples (u, v, k) or with data, 4-tuples (u, v, k, d). default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- in_edges : InMultiEdgeView or InMultiEdgeDataView A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as `edges[u, v, k]['foo']`.
See Also -------- edges """ return InMultiEdgeView(self)
@cached_property def degree(self): """A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- DiMultiDegreeView or int If multiple nodes are requested (the default), returns a `DiMultiDegreeView` mapping nodes to their degree. If a single node is requested, returns the degree of the node as an integer.
See Also -------- out_degree, in_degree
Examples -------- >>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1, 2])) [(0, 1), (1, 2), (2, 2)] >>> G.add_edge(0, 1) # parallel edge 1 >>> list(G.degree([0, 1, 2])) # parallel edges are counted [(0, 2), (1, 3), (2, 2)]
""" return DiMultiDegreeView(self)
@cached_property def in_degree(self): """A DegreeView for (node, in_degree) or in_degree for single node.
The node in-degree is the number of edges pointing into the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- If a single node is requested deg : int Degree of the node
OR if multiple nodes are requested nd_iter : iterator The iterator returns two-tuples of (node, in-degree).
See Also -------- degree, out_degree
Examples -------- >>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.in_degree(0) # node 0 with degree 0 0 >>> list(G.in_degree([0, 1, 2])) [(0, 0), (1, 1), (2, 1)] >>> G.add_edge(0, 1) # parallel edge 1 >>> list(G.in_degree([0, 1, 2])) # parallel edges counted [(0, 0), (1, 2), (2, 1)]
""" return InMultiDegreeView(self)
@cached_property def out_degree(self): """Returns an iterator for (node, out-degree) or out-degree for single node.
out_degree(self, nbunch=None, weight=None)
The node out-degree is the number of edges pointing out of the node. This function returns the out-degree for a single node or an iterator for a bunch of nodes or if nothing is passed as argument.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights.
Returns ------- If a single node is requested deg : int Degree of the node
OR if multiple nodes are requested nd_iter : iterator The iterator returns two-tuples of (node, out-degree).
See Also -------- degree, in_degree
Examples -------- >>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.out_degree(0) # node 0 with degree 1 1 >>> list(G.out_degree([0, 1, 2])) [(0, 1), (1, 1), (2, 1)] >>> G.add_edge(0, 1) # parallel edge 1 >>> list(G.out_degree([0, 1, 2])) # counts parallel edges [(0, 2), (1, 1), (2, 1)]
""" return OutMultiDegreeView(self)
def is_multigraph(self): """Returns True if graph is a multigraph, False otherwise.""" return True
def is_directed(self): """Returns True if graph is directed, False otherwise.""" return True
def to_undirected(self, reciprocal=False, as_view=False): """Returns an undirected representation of the digraph.
Parameters ---------- reciprocal : bool (optional) If True only keep edges that appear in both directions in the original digraph. as_view : bool (optional, default=False) If True return an undirected view of the original directed graph.
Returns ------- G : MultiGraph An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is different, only one edge is created with an arbitrary choice of which edge data to use. You must check and correct for this manually if desired.
See Also -------- MultiGraph, copy, add_edge, add_edges_from
Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=MultiDiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Warning: If you have subclassed MultiDiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiGraph created by this method.
Examples -------- >>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)] """ graph_class = self.to_undirected_class() if as_view is True: return nx.graphviews.generic_graph_view(self, graph_class) # deepcopy when not a view G = graph_class() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) if reciprocal is True: G.add_edges_from( (u, v, key, deepcopy(data)) for u, nbrs in self._adj.items() for v, keydict in nbrs.items() for key, data in keydict.items() if v in self._pred[u] and key in self._pred[u][v] ) else: G.add_edges_from( (u, v, key, deepcopy(data)) for u, nbrs in self._adj.items() for v, keydict in nbrs.items() for key, data in keydict.items() ) return G
def reverse(self, copy=True): """Returns the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters ---------- copy : bool optional (default=True) If True, return a new DiGraph holding the reversed edges. If False, the reverse graph is created using a view of the original graph. """ if copy: H = self.__class__() H.graph.update(deepcopy(self.graph)) H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) H.add_edges_from( (v, u, k, deepcopy(d)) for u, v, k, d in self.edges(keys=True, data=True) ) return H return nx.reverse_view(self)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294"""Base class for MultiGraph."""
from copy import deepcopyfrom functools import cached_property
import networkx as nxfrom networkx import NetworkXError, convertfrom networkx.classes.coreviews import MultiAdjacencyViewfrom networkx.classes.graph import Graphfrom networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
__all__ = ["MultiGraph"]
class MultiGraph(Graph): """ An undirected graph class that can store multiedges.
Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.
A MultiGraph holds undirected edges. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention `None` is not used as a node.
Edges are represented as links between nodes with optional key/value attributes, in a MultiGraph each edge has a key to distinguish between multiple edges that have the same source and destination nodes.
Parameters ---------- incoming_graph_data : input graph (optional, default: None) Data to initialize graph. If None (default) an empty graph is created. The data can be any format that is supported by the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy sparse array, or PyGraphviz graph.
multigraph_input : bool or None (default None) Note: Only used when `incoming_graph_data` is a dict. If True, `incoming_graph_data` is assumed to be a dict-of-dict-of-dict-of-dict structure keyed by node to neighbor to edge keys to edge data for multi-edges. A NetworkXError is raised if this is not the case. If False, :func:`to_networkx_graph` is used to try to determine the dict's graph data structure as either a dict-of-dict-of-dict keyed by node to neighbor to edge data, or a dict-of-iterable keyed by node to neighbors. If None, the treatment for True is tried, but if it fails, the treatment for False is tried.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- Graph DiGraph MultiDiGraph
Examples -------- Create an empty graph structure (a "null graph") with no nodes and no edges.
>>> G = nx.MultiGraph()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2, 3]) >>> G.add_nodes_from(range(100, 110)) >>> H = nx.path_graph(10) >>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a customized node object, or even another Graph.
>>> G.add_node(H)
**Edges:**
G can also be grown by adding edges.
Add one edge,
>>> key = G.add_edge(1, 2)
a list of edges,
>>> keys = G.add_edges_from([(1, 2), (1, 3)])
or a collection of edges,
>>> keys = G.add_edges_from(H.edges)
If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists, an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused integer.
>>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})]) >>> G[4] AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
**Attributes:**
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.MultiGraph(day="Friday") >>> G.graph {'day': 'Friday'}
Add node attributes using add_node(), add_nodes_from() or G.nodes
>>> G.add_node(1, time="5pm") >>> G.add_nodes_from([3], time="2pm") >>> G.nodes[1] {'time': '5pm'} >>> G.nodes[1]["room"] = 714 >>> del G.nodes[1]["room"] # remove attribute >>> list(G.nodes(data=True)) [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edges.
>>> key = G.add_edge(1, 2, weight=4.7) >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red") >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})]) >>> G[1][2][0]["weight"] = 4.7 >>> G.edges[1, 2, 0]["weight"] = 4
Warning: we protect the graph data structure by making `G.edges[1, 2, 0]` a read-only dict-like structure. However, you can assign to attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
**Shortcuts:**
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph True >>> [n for n in G if n < 3] # iterate through nodes [1, 2] >>> len(G) # number of nodes in graph 5 >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
>>> for n, nbrsdict in G.adjacency(): ... for nbr, keydict in nbrsdict.items(): ... for key, eattr in keydict.items(): ... if "weight" in eattr: ... # Do something useful with the edges ... pass
But the edges() method is often more convenient:
>>> for u, v, keys, weight in G.edges(data="weight", keys=True): ... if weight is not None: ... # Do something useful with the edges ... pass
**Reporting:**
Simple graph information is obtained using methods and object-attributes. Reporting usually provides views instead of containers to reduce memory usage. The views update as the graph is updated similarly to dict-views. The objects `nodes`, `edges` and `adj` provide access to data attributes via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration (e.g. `nodes.items()`, `nodes.data('color')`, `nodes.data('color', default='blue')` and similarly for `edges`) Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
For details on these and other miscellaneous methods, see below.
**Subclasses (Advanced):**
The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge_key dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like object. In general, the dict-like features should be maintained but extra features can be added. To replace one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory : function, (default: dict) Factory function to be used to create the dict containing node attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object
adjlist_outer_dict_factory : function, (default: dict) Factory function to be used to create the outer-most dict in the data structure that holds adjacency info keyed by node. It should require no arguments and return a dict-like object.
adjlist_inner_dict_factory : function, (default: dict) Factory function to be used to create the adjacency list dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a dict-like object.
edge_key_dict_factory : function, (default: dict) Factory function to be used to create the edge key dict which holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory : function, (default: dict) Factory function to be used to create the edge attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
graph_attr_dict_factory : function, (default: dict) Factory function to be used to create the graph attribute dict which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like object.
Typically, if your extension doesn't impact the data structure all methods will inherited without issue except: `to_directed/to_undirected`. By default these methods create a DiGraph/Graph class and you probably want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you can set in your subclass.
to_directed_class : callable, (default: DiGraph or MultiDiGraph) Class to create a new graph structure in the `to_directed` method. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class : callable, (default: Graph or MultiGraph) Class to create a new graph structure in the `to_undirected` method. If `None`, a NetworkX class (Graph or MultiGraph) is used.
**Subclassing Example**
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all edges. This reduces the memory used, but you lose edge attributes.
>>> class ThinGraph(nx.Graph): ... all_edge_dict = {"weight": 1} ... ... def single_edge_dict(self): ... return self.all_edge_dict ... ... edge_attr_dict_factory = single_edge_dict >>> G = ThinGraph() >>> G.add_edge(2, 1) >>> G[2][1] {'weight': 1} >>> G.add_edge(2, 2) >>> G[2][1] is G[2][2] True """
# node_dict_factory = dict # already assigned in Graph # adjlist_outer_dict_factory = dict # adjlist_inner_dict_factory = dict edge_key_dict_factory = dict # edge_attr_dict_factory = dict
def to_directed_class(self): """Returns the class to use for empty directed copies.
If you subclass the base classes, use this to designate what directed class to use for `to_directed()` copies. """ return nx.MultiDiGraph
def to_undirected_class(self): """Returns the class to use for empty undirected copies.
If you subclass the base classes, use this to designate what directed class to use for `to_directed()` copies. """ return MultiGraph
# This __new__ method just does what Python itself does automatically. # We include it here as part of the dispatchable/backend interface. # If your goal is to understand how the graph classes work, you can ignore # this method, even when subclassing the base classes. If you are subclassing # in order to provide a backend that allows class instantiation, this method # can be overridden to return your own backend graph class. @nx._dispatchable(name="multigraph__new__", graphs=None, returns_graph=True) def __new__(cls, *args, **kwargs): return object.__new__(cls)
def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr): """Initialize a graph with edges, name, or graph attributes.
Parameters ---------- incoming_graph_data : input graph Data to initialize graph. If incoming_graph_data=None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a 2D NumPy array, a SciPy sparse array, or a PyGraphviz graph.
multigraph_input : bool or None (default None) Note: Only used when `incoming_graph_data` is a dict. If True, `incoming_graph_data` is assumed to be a dict-of-dict-of-dict-of-dict structure keyed by node to neighbor to edge keys to edge data for multi-edges. A NetworkXError is raised if this is not the case. If False, :func:`to_networkx_graph` is used to try to determine the dict's graph data structure as either a dict-of-dict-of-dict keyed by node to neighbor to edge data, or a dict-of-iterable keyed by node to neighbors. If None, the treatment for True is tried, but if it fails, the treatment for False is tried.
attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.
See Also -------- convert
Examples -------- >>> G = nx.MultiGraph() >>> G = nx.MultiGraph(name="my graph") >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges >>> G = nx.MultiGraph(e)
Arbitrary graph attribute pairs (key=value) may be assigned
>>> G = nx.MultiGraph(e, day="Friday") >>> G.graph {'day': 'Friday'}
""" attr.pop("backend", None) # Ignore explicit `backend="networkx"` # multigraph_input can be None/True/False. So check "is not False" if isinstance(incoming_graph_data, dict) and multigraph_input is not False: Graph.__init__(self) try: convert.from_dict_of_dicts( incoming_graph_data, create_using=self, multigraph_input=True ) self.graph.update(attr) except Exception as err: if multigraph_input is True: raise nx.NetworkXError( f"converting multigraph_input raised:\n{type(err)}: {err}" ) Graph.__init__(self, incoming_graph_data, **attr) else: Graph.__init__(self, incoming_graph_data, **attr)
@cached_property def adj(self): """Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets the color of the edge `(3, 2, 0)` to `"blue"`.
Iterating over G.adj behaves like a dict. Useful idioms include `for nbr, edgesdict in G.adj[n].items():`.
The neighbor information is also provided by subscripting the graph.
Examples -------- >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges >>> G = nx.MultiGraph(e) >>> G.edges[1, 2, 0]["weight"] = 3 >>> result = set() >>> for edgekey, data in G[1][2].items(): ... result.add(data.get("weight", 1)) >>> result {1, 3}
For directed graphs, `G.adj` holds outgoing (successor) info. """ return MultiAdjacencyView(self._adj)
def new_edge_key(self, u, v): """Returns an unused key for edges between nodes `u` and `v`.
The nodes `u` and `v` do not need to be already in the graph.
Notes ----- In the standard MultiGraph class the new key is the number of existing edges between `u` and `v` (increased if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further new_edge_keys may not be in this order.
Parameters ---------- u, v : nodes
Returns ------- key : int """ try: keydict = self._adj[u][v] except KeyError: return 0 key = len(keydict) while key in keydict: key += 1 return key
def add_edge(self, u_for_edge, v_for_edge, key=None, **attr): """Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge's attribute dictionary. See examples below.
Parameters ---------- u_for_edge, v_for_edge : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects. key : hashable identifier, optional (default=lowest unused integer) Used to distinguish multiedges between a pair of nodes. attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
Returns ------- The edge key assigned to the edge.
See Also -------- add_edges_from : add a collection of edges
Notes ----- To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear how to handle multiedge weights. Convert to Graph using edge attribute 'weight' to enable weighted graph algorithms.
Default keys are generated using the method `new_edge_key()`. This method can be overridden by subclassing the base class and providing a custom `new_edge_key()` method.
Examples -------- The following each add an additional edge e=(1, 2) to graph G:
>>> G = nx.MultiGraph() >>> e = (1, 2) >>> ekey = G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes 1 >>> G.add_edges_from([(1, 2)]) # add edges from iterable container [2]
Associate data to edges using keywords:
>>> ekey = G.add_edge(1, 2, weight=3) >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0 >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
For non-string attribute keys, use subscript notation.
>>> ekey = G.add_edge(1, 2) >>> G[1][2][0].update({0: 5}) >>> G.edges[1, 2, 0].update({0: 5}) """ u, v = u_for_edge, v_for_edge # add nodes if u not in self._adj: if u is None: raise ValueError("None cannot be a node") self._adj[u] = self.adjlist_inner_dict_factory() self._node[u] = self.node_attr_dict_factory() if v not in self._adj: if v is None: raise ValueError("None cannot be a node") self._adj[v] = self.adjlist_inner_dict_factory() self._node[v] = self.node_attr_dict_factory() if key is None: key = self.new_edge_key(u, v) if v in self._adj[u]: keydict = self._adj[u][v] datadict = keydict.get(key, self.edge_attr_dict_factory()) datadict.update(attr) keydict[key] = datadict else: # selfloops work this way without special treatment datadict = self.edge_attr_dict_factory() datadict.update(attr) keydict = self.edge_key_dict_factory() keydict[key] = datadict self._adj[u][v] = keydict self._adj[v][u] = keydict nx._clear_cache(self) return key
def add_edges_from(self, ebunch_to_add, **attr): """Add all the edges in ebunch_to_add.
Parameters ---------- ebunch_to_add : container of edges Each edge given in the container will be added to the graph. The edges can be:
- 2-tuples (u, v) or - 3-tuples (u, v, d) for an edge data dict d, or - 3-tuples (u, v, k) for not iterable key k, or - 4-tuples (u, v, k, d) for an edge with data and key k
attr : keyword arguments, optional Edge data (or labels or objects) can be assigned using keyword arguments.
Returns ------- A list of edge keys assigned to the edges in `ebunch`.
See Also -------- add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Notes ----- Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method ``new_edge_key()``. This method can be overridden by subclassing the base class and providing a custom ``new_edge_key()`` method.
When adding edges from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_edges)`, and pass this object to `G.add_edges_from`.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
Evaluate an iterator over a graph if using it to modify the same graph
>>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)]) >>> # Grow graph by one new node, adding edges to all existing nodes. >>> # wrong way - will raise RuntimeError >>> # G.add_edges_from(((5, n) for n in G.nodes)) >>> # right way - note that there will be no self-edge for node 5 >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes)) """ keylist = [] for e in ebunch_to_add: ne = len(e) if ne == 4: u, v, key, dd = e elif ne == 3: u, v, dd = e key = None elif ne == 2: u, v = e dd = {} key = None else: msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple." raise NetworkXError(msg) ddd = {} ddd.update(attr) try: ddd.update(dd) except (TypeError, ValueError): if ne != 3: raise key = dd # ne == 3 with 3rd value not dict, must be a key key = self.add_edge(u, v, key) self[u][v][key].update(ddd) keylist.append(key) nx._clear_cache(self) return keylist
def remove_edge(self, u, v, key=None): """Remove an edge between u and v.
Parameters ---------- u, v : nodes Remove an edge between nodes u and v. key : hashable identifier, optional (default=None) Used to distinguish multiple edges between a pair of nodes. If None, remove a single edge between u and v. If there are multiple edges, removes the last edge added in terms of insertion order.
Raises ------ NetworkXError If there is not an edge between u and v, or if there is no edge with the specified key.
See Also -------- remove_edges_from : remove a collection of edges
Examples -------- >>> G = nx.MultiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.remove_edge(0, 1) >>> e = (1, 2) >>> G.remove_edge(*e) # unpacks e from an edge tuple
For multiple edges
>>> G = nx.MultiGraph() # or MultiDiGraph, etc >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned [0, 1, 2]
When ``key=None`` (the default), edges are removed in the opposite order that they were added:
>>> G.remove_edge(1, 2) >>> G.edges(keys=True) MultiEdgeView([(1, 2, 0), (1, 2, 1)]) >>> G.remove_edge(2, 1) # edges are not directed >>> G.edges(keys=True) MultiEdgeView([(1, 2, 0)])
For edges with keys
>>> G = nx.MultiGraph() >>> G.add_edge(1, 2, key="first") 'first' >>> G.add_edge(1, 2, key="second") 'second' >>> G.remove_edge(1, 2, key="first") >>> G.edges(keys=True) MultiEdgeView([(1, 2, 'second')])
""" try: d = self._adj[u][v] except KeyError as err: raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err # remove the edge with specified data if key is None: d.popitem() else: try: del d[key] except KeyError as err: msg = f"The edge {u}-{v} with key {key} is not in the graph." raise NetworkXError(msg) from err if len(d) == 0: # remove the key entries if last edge del self._adj[u][v] if u != v: # check for selfloop del self._adj[v][u] nx._clear_cache(self)
def remove_edges_from(self, ebunch): """Remove all edges specified in ebunch.
Parameters ---------- ebunch: list or container of edge tuples Each edge given in the list or container will be removed from the graph. The edges can be:
- 2-tuples (u, v) A single edge between u and v is removed. - 3-tuples (u, v, key) The edge identified by key is removed. - 4-tuples (u, v, key, data) where data is ignored.
See Also -------- remove_edge : remove a single edge
Notes ----- Will fail silently if an edge in ebunch is not in the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch = [(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch)
Removing multiple copies of edges
>>> G = nx.MultiGraph() >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)]) >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed >>> list(G.edges()) [(1, 2)] >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy >>> list(G.edges) # now empty graph []
When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between u and v in the graph, the most recent edge (in terms of insertion order) is removed.
>>> G = nx.MultiGraph() >>> for key in ("x", "y", "a"): ... k = G.add_edge(0, 1, key=key) >>> G.edges(keys=True) MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')]) >>> G.remove_edges_from([(0, 1)]) >>> G.edges(keys=True) MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
""" for e in ebunch: try: self.remove_edge(*e[:3]) except NetworkXError: pass nx._clear_cache(self)
def has_edge(self, u, v, key=None): """Returns True if the graph has an edge between nodes u and v.
This is the same as `v in G[u] or key in G[u][v]` without KeyError exceptions.
Parameters ---------- u, v : nodes Nodes can be, for example, strings or numbers.
key : hashable identifier, optional (default=None) If specified return True only if the edge with key is found.
Returns ------- edge_ind : bool True if edge is in the graph, False otherwise.
Examples -------- Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2-tuple (u, v) True >>> G.add_edge(0, 1, key="a") 'a' >>> G.has_edge(0, 1, key="a") # specify key True >>> G.has_edge(1, 0, key="a") # edges aren't directed True >>> e = (0, 1, "a") >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a') True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G True >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G True
""" try: if key is None: return v in self._adj[u] else: return key in self._adj[u][v] except KeyError: return False
@cached_property def edges(self): """Returns an iterator over the edges.
edges(self, nbunch=None, data=False, keys=False, default=None)
The MultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, ``G.edges[u, v, k]['color']`` provides the value of the color attribute for the edge from ``u`` to ``v`` with key ``k`` while ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):`` iterates through all the edges yielding the color attribute with default `'red'` if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data). If ``keys=True`` is not provided, the tuples will just be (node, neighbor, data), but multiple tuples with the same node and neighbor will be generated when multiple edges exist between two nodes.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges from these nodes. data : string or bool, optional (default=False) The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v). keys : bool, optional (default=False) If True, return edge keys with each edge, creating (u, v, k) tuples or (u, v, k, d) tuples if data is also requested. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False.
Returns ------- edges : MultiEdgeView A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as ``edges[u, v, k]['foo']``.
Notes ----- Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples -------- >>> G = nx.MultiGraph() >>> nx.add_path(G, [0, 1, 2]) >>> key = G.add_edge(2, 3, weight=5) >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge >>> [e for e in G.edges()] [(0, 1), (1, 2), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})]) >>> G.edges.data("weight", default=1) MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)]) >>> G.edges(keys=True) # default keys are integers MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]) >>> G.edges.data(keys=True) MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})]) >>> G.edges.data("weight", default=1, keys=True) MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)]) >>> G.edges([0, 3]) # Note ordering of tuples from listed sources MultiEdgeDataView([(0, 1), (3, 2)]) >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)]) >>> G.edges(0) MultiEdgeDataView([(0, 1)]) """ return MultiEdgeView(self)
def get_edge_data(self, u, v, key=None, default=None): """Returns the attribute dictionary associated with edge (u, v, key).
If a key is not provided, returns a dictionary mapping edge keys to attribute dictionaries for each edge between u and v.
This is identical to `G[u][v][key]` except the default is returned instead of an exception is the edge doesn't exist.
Parameters ---------- u, v : nodes
default : any Python object (default=None) Value to return if the specific edge (u, v, key) is not found, OR if there are no edges between u and v and no key is specified.
key : hashable identifier, optional (default=None) Return data only for the edge with specified key, as an attribute dictionary (rather than a dictionary mapping keys to attribute dictionaries).
Returns ------- edge_dict : dictionary The edge attribute dictionary, OR a dictionary mapping edge keys to attribute dictionaries for each of those edges if no specific key is provided (even if there's only one edge between u and v).
Examples -------- >>> G = nx.MultiGraph() # or MultiDiGraph >>> key = G.add_edge(0, 1, key="a", weight=7) >>> G[0][1]["a"] # key='a' {'weight': 7} >>> G.edges[0, 1, "a"] # key='a' {'weight': 7}
Warning: we protect the graph data structure by making `G.edges` and `G[1][2]` read-only dict-like structures. However, you can assign values to attributes in e.g. `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an edge.
>>> G[0][1]["a"]["weight"] = 10 >>> G.edges[0, 1, "a"]["weight"] = 10 >>> G[0][1]["a"]["weight"] 10 >>> G.edges[1, 0, "a"]["weight"] 10
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.edges[0, 1, 0]["weight"] = 5 >>> G.get_edge_data(0, 1) {0: {'weight': 5}} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {0: {'weight': 5}} >>> G.get_edge_data(3, 0) # edge not in graph, returns None >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default 0 >>> G.get_edge_data(1, 0, 0) # specific key gives back {'weight': 5} """ try: if key is None: return self._adj[u][v] else: return self._adj[u][v][key] except KeyError: return default
@cached_property def degree(self): """A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters ---------- nbunch : single node, container, or all nodes (default= all nodes) The view will only report edges incident to these nodes.
weight : string or None, optional (default=None) The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- MultiDegreeView or int If multiple nodes are requested (the default), returns a `MultiDegreeView` mapping nodes to their degree. If a single node is requested, returns the degree of the node as an integer.
Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1])) [(0, 1), (1, 2)]
""" return MultiDegreeView(self)
def is_multigraph(self): """Returns True if graph is a multigraph, False otherwise.""" return True
def is_directed(self): """Returns True if graph is directed, False otherwise.""" return False
def copy(self, as_view=False): """Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python's `copy.deepcopy` for new containers.
If `as_view` is True then a view is returned instead of a copy.
Notes ----- All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.
Deepcopy -- A "deepcopy" copies the graph structure as well as all data attributes and any objects they might contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python's copy.deepcopy)
Data Reference (Shallow) -- For a shallow copy the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this level of shallow copy.
Independent Shallow -- This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what `dict.copy()` provides. You can obtain this style copy using:
>>> G = nx.path_graph(5) >>> H = G.copy() >>> H = G.copy(as_view=False) >>> H = nx.Graph(G) >>> H = G.__class__(G)
Fresh Data -- For fresh data, the graph structure is copied while new empty data attribute dicts are created. The resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not enabled. Instead use:
>>> H = G.__class__() >>> H.add_nodes_from(G) >>> H.add_edges_from(G.edges)
View -- Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Parameters ---------- as_view : bool, optional (default=False) If True, the returned graph-view provides a read-only view of the original graph without actually copying any data.
Returns ------- G : Graph A copy of the graph.
See Also -------- to_directed: return a directed copy of the graph.
Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.copy()
""" if as_view is True: return nx.graphviews.generic_graph_view(self) G = self.__class__() G.graph.update(self.graph) G.add_nodes_from((n, d.copy()) for n, d in self._node.items()) G.add_edges_from( (u, v, key, datadict.copy()) for u, nbrs in self._adj.items() for v, keydict in nbrs.items() for key, datadict in keydict.items() ) return G
def to_directed(self, as_view=False): """Returns a directed representation of the graph.
Returns ------- G : MultiDiGraph A directed graph with the same name, same nodes, and with each edge (u, v, k, data) replaced by two directed edges (u, v, k, data) and (v, u, k, data).
Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=MultiDiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiDiGraph created by this method.
Examples -------- >>> G = nx.MultiGraph() >>> G.add_edge(0, 1) 0 >>> G.add_edge(0, 1) 1 >>> H = G.to_directed() >>> list(H.edges) [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
If already directed, return a (deep) copy
>>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1) 0 >>> H = G.to_directed() >>> list(H.edges) [(0, 1, 0)] """ graph_class = self.to_directed_class() if as_view is True: return nx.graphviews.generic_graph_view(self, graph_class) # deepcopy when not a view G = graph_class() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) G.add_edges_from( (u, v, key, deepcopy(datadict)) for u, nbrs in self.adj.items() for v, keydict in nbrs.items() for key, datadict in keydict.items() ) return G
def to_undirected(self, as_view=False): """Returns an undirected copy of the graph.
Returns ------- G : Graph/MultiGraph A deepcopy of the graph.
See Also -------- copy, add_edge, add_edges_from
Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar `G = nx.MultiGraph(D)` which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiGraph created by this method.
Examples -------- >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)]) >>> H = G.to_directed() >>> list(H.edges) [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1, 0), (0, 1, 1), (1, 2, 0)] """ graph_class = self.to_undirected_class() if as_view is True: return nx.graphviews.generic_graph_view(self, graph_class) # deepcopy when not a view G = graph_class() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) G.add_edges_from( (u, v, key, deepcopy(datadict)) for u, nbrs in self._adj.items() for v, keydict in nbrs.items() for key, datadict in keydict.items() ) return G
def number_of_edges(self, u=None, v=None): """Returns the number of edges between two nodes.
Parameters ---------- u, v : nodes, optional (Default=all edges) If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.
Returns ------- nedges : int The number of edges in the graph. If nodes `u` and `v` are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from `u` to `v`.
See Also -------- size
Examples -------- For undirected multigraphs, this method counts the total number of edges in the graph::
>>> G = nx.MultiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)]) [0, 1, 0] >>> G.number_of_edges() 3
If you specify two nodes, this counts the total number of edges joining the two nodes::
>>> G.number_of_edges(0, 1) 2
For directed multigraphs, this method can count the total number of directed edges from `u` to `v`::
>>> G = nx.MultiDiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)]) [0, 1, 0] >>> G.number_of_edges(0, 1) 2 >>> G.number_of_edges(1, 0) 1
""" if u is None: return self.size() try: edgedata = self._adj[u][v] except KeyError: return 0 # no such edge return len(edgedata)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447"""View Classes provide node, edge and degree "views" of a graph.
Views for nodes, edges and degree are provided for all base graph classes.A view means a read-only object that is quick to create, automaticallyupdated when the graph changes, and provides basic access like `n in V`,`for n in V`, `V[n]` and sometimes set operations.
The views are read-only iterable containers that are updated as thegraph is updated. As with dicts, the graph should not be updatedwhile iterating through the view. Views can be iterated multiple times.
Edge and Node views also allow data attribute lookup.The resulting attribute dict is writable as `G.edges[3, 4]['color']='red'`Degree views allow lookup of degree values for single nodes.Weighted degree is supported with the `weight` argument.
NodeView========
`V = G.nodes` (or `V = G.nodes()`) allows `len(V)`, `n in V`, set operations e.g. "G.nodes & H.nodes", and `dd = G.nodes[n]`, where `dd` is the node data dict. Iteration is over the nodes by default.
NodeDataView============
To iterate over (node, data) pairs, use arguments to `G.nodes()` to create a DataView e.g. `DV = G.nodes(data='color', default='red')`. The DataView iterates as `for n, color in DV` and allows `(n, 'red') in DV`. Using `DV = G.nodes(data=True)`, the DataViews use the full datadict in writeable form also allowing contain testing as `(n, {'color': 'red'}) in VD`. DataViews allow set operations when data attributes are hashable.
DegreeView==========
`V = G.degree` allows iteration over (node, degree) pairs as well as lookup: `deg=V[n]`. There are many flavors of DegreeView for In/Out/Directed/Multi. For Directed Graphs, `G.degree` counts both in and out going edges. `G.out_degree` and `G.in_degree` count only specific directions. Weighted degree using edge data attributes is provide via `V = G.degree(weight='attr_name')` where any string with the attribute name can be used. `weight=None` is the default. No set operations are implemented for degrees, use NodeView.
The argument `nbunch` restricts iteration to nodes in nbunch. The DegreeView can still lookup any node even if nbunch is specified.
EdgeView========
`V = G.edges` or `V = G.edges()` allows iteration over edges as well as `e in V`, set operations and edge data lookup `dd = G.edges[2, 3]`. Iteration is over 2-tuples `(u, v)` for Graph/DiGraph. For multigraphs edges 3-tuples `(u, v, key)` are the default but 2-tuples can be obtained via `V = G.edges(keys=False)`.
Set operations for directed graphs treat the edges as a set of 2-tuples. For undirected graphs, 2-tuples are not a unique representation of edges. So long as the set being compared to contains unique representations of its edges, the set operations will act as expected. If the other set contains both `(0, 1)` and `(1, 0)` however, the result of set operations may contain both representations of the same edge.
EdgeDataView============
Edge data can be reported using an EdgeDataView typically created by calling an EdgeView: `DV = G.edges(data='weight', default=1)`. The EdgeDataView allows iteration over edge tuples, membership checking but no set operations.
Iteration depends on `data` and `default` and for multigraph `keys` If `data is False` (the default) then iterate over 2-tuples `(u, v)`. If `data is True` iterate over 3-tuples `(u, v, datadict)`. Otherwise iterate over `(u, v, datadict.get(data, default))`. For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` to create 3-tuples and 4-tuples.
The argument `nbunch` restricts edges to those incident to nodes in nbunch."""
from abc import ABCfrom collections.abc import Mapping, Set
import networkx as nx
__all__ = [ "NodeView", "NodeDataView", "EdgeView", "OutEdgeView", "InEdgeView", "EdgeDataView", "OutEdgeDataView", "InEdgeDataView", "MultiEdgeView", "OutMultiEdgeView", "InMultiEdgeView", "MultiEdgeDataView", "OutMultiEdgeDataView", "InMultiEdgeDataView", "DegreeView", "DiDegreeView", "InDegreeView", "OutDegreeView", "MultiDegreeView", "DiMultiDegreeView", "InMultiDegreeView", "OutMultiDegreeView",]
# NodeViewsclass NodeView(Mapping, Set): """A NodeView class to act as G.nodes for a NetworkX Graph
Set operations act on the nodes without considering data. Iteration is over nodes. Node data can be looked up like a dict. Use NodeDataView to iterate over node data or to specify a data attribute for lookup. NodeDataView is created by calling the NodeView.
Parameters ---------- graph : NetworkX graph-like class
Examples -------- >>> G = nx.path_graph(3) >>> NV = G.nodes() >>> 2 in NV True >>> for n in NV: ... print(n) 0 1 2 >>> assert NV & {1, 2, 3} == {1, 2}
>>> G.add_node(2, color="blue") >>> NV[2] {'color': 'blue'} >>> G.add_node(8, color="red") >>> NDV = G.nodes(data=True) >>> (2, NV[2]) in NDV True >>> for n, dd in NDV: ... print((n, dd.get("color", "aqua"))) (0, 'aqua') (1, 'aqua') (2, 'blue') (8, 'red') >>> NDV[2] == NV[2] True
>>> NVdata = G.nodes(data="color", default="aqua") >>> (2, NVdata[2]) in NVdata True >>> for n, dd in NVdata: ... print((n, dd)) (0, 'aqua') (1, 'aqua') (2, 'blue') (8, 'red') >>> NVdata[2] == NV[2] # NVdata gets 'color', NV gets datadict False """
__slots__ = ("_nodes",)
def __getstate__(self): return {"_nodes": self._nodes}
def __setstate__(self, state): self._nodes = state["_nodes"]
def __init__(self, graph): self._nodes = graph._node
# Mapping methods def __len__(self): return len(self._nodes)
def __iter__(self): return iter(self._nodes)
def __getitem__(self, n): if isinstance(n, slice): raise nx.NetworkXError( f"{type(self).__name__} does not support slicing, " f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]" ) return self._nodes[n]
# Set methods def __contains__(self, n): return n in self._nodes
@classmethod def _from_iterable(cls, it): return set(it)
# DataView method def __call__(self, data=False, default=None): if data is False: return self return NodeDataView(self._nodes, data, default)
def data(self, data=True, default=None): """ Return a read-only view of node data.
Parameters ---------- data : bool or node data key, default=True If ``data=True`` (the default), return a `NodeDataView` object that maps each node to *all* of its attributes. `data` may also be an arbitrary key, in which case the `NodeDataView` maps each node to the value for the keyed attribute. In this case, if a node does not have the `data` attribute, the `default` value is used. default : object, default=None The value used when a node does not have a specific attribute.
Returns ------- NodeDataView The layout of the returned NodeDataView depends on the value of the `data` parameter.
Notes ----- If ``data=False``, returns a `NodeView` object without data.
See Also -------- NodeDataView
Examples -------- >>> G = nx.Graph() >>> G.add_nodes_from( ... [ ... (0, {"color": "red", "weight": 10}), ... (1, {"color": "blue"}), ... (2, {"color": "yellow", "weight": 2}), ... ] ... )
Accessing node data with ``data=True`` (the default) returns a NodeDataView mapping each node to all of its attributes:
>>> G.nodes.data() NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}})
If `data` represents a key in the node attribute dict, a NodeDataView mapping the nodes to the value for that specific key is returned:
>>> G.nodes.data("color") NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color')
If a specific key is not found in an attribute dict, the value specified by `default` is returned:
>>> G.nodes.data("weight", default=-999) NodeDataView({0: 10, 1: -999, 2: 2}, data='weight')
Note that there is no check that the `data` key is in any of the node attribute dictionaries:
>>> G.nodes.data("height") NodeDataView({0: None, 1: None, 2: None}, data='height') """ if data is False: return self return NodeDataView(self._nodes, data, default)
def __str__(self): return str(list(self))
def __repr__(self): return f"{self.__class__.__name__}({tuple(self)})"
class NodeDataView(Set): """A DataView class for nodes of a NetworkX Graph
The main use for this class is to iterate through node-data pairs. The data can be the entire data-dictionary for each node, or it can be a specific attribute (with default) for each node. Set operations are enabled with NodeDataView, but don't work in cases where the data is not hashable. Use with caution. Typically, set operations on nodes use NodeView, not NodeDataView. That is, they use `G.nodes` instead of `G.nodes(data='foo')`.
Parameters ========== graph : NetworkX graph-like class data : bool or string (default=False) default : object (default=None) """
__slots__ = ("_nodes", "_data", "_default")
def __getstate__(self): return {"_nodes": self._nodes, "_data": self._data, "_default": self._default}
def __setstate__(self, state): self._nodes = state["_nodes"] self._data = state["_data"] self._default = state["_default"]
def __init__(self, nodedict, data=False, default=None): self._nodes = nodedict self._data = data self._default = default
@classmethod def _from_iterable(cls, it): try: return set(it) except TypeError as err: if "unhashable" in str(err): msg = " : Could be b/c data=True or your values are unhashable" raise TypeError(str(err) + msg) from err raise
def __len__(self): return len(self._nodes)
def __iter__(self): data = self._data if data is False: return iter(self._nodes) if data is True: return iter(self._nodes.items()) return ( (n, dd[data] if data in dd else self._default) for n, dd in self._nodes.items() )
def __contains__(self, n): try: node_in = n in self._nodes except TypeError: n, d = n return n in self._nodes and self[n] == d if node_in is True: return node_in try: n, d = n except (TypeError, ValueError): return False return n in self._nodes and self[n] == d
def __getitem__(self, n): if isinstance(n, slice): raise nx.NetworkXError( f"{type(self).__name__} does not support slicing, " f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]" ) ddict = self._nodes[n] data = self._data if data is False or data is True: return ddict return ddict[data] if data in ddict else self._default
def __str__(self): return str(list(self))
def __repr__(self): name = self.__class__.__name__ if self._data is False: return f"{name}({tuple(self)})" if self._data is True: return f"{name}({dict(self)})" return f"{name}({dict(self)}, data={self._data!r})"
# DegreeViewsclass DiDegreeView: """A View class for degree of nodes in a NetworkX Graph
The functionality is like dict.items() with (node, degree) pairs. Additional functionality includes read-only lookup of node degree, and calling with optional features nbunch (for only a subset of nodes) and weight (use edge weights to compute degree).
Parameters ========== graph : NetworkX graph-like class nbunch : node, container of nodes, or None meaning all nodes (default=None) weight : bool or string (default=None)
Notes ----- DegreeView can still lookup any node even if nbunch is specified.
Examples -------- >>> G = nx.path_graph(3) >>> DV = G.degree() >>> assert DV[2] == 1 >>> assert sum(deg for n, deg in DV) == 4
>>> DVweight = G.degree(weight="span") >>> G.add_edge(1, 2, span=34) >>> DVweight[2] 34 >>> DVweight[0] # default edge weight is 1 1 >>> sum(span for n, span in DVweight) # sum weighted degrees 70
>>> DVnbunch = G.degree(nbunch=(1, 2)) >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only """
def __init__(self, G, nbunch=None, weight=None): self._graph = G self._succ = G._succ if hasattr(G, "_succ") else G._adj self._pred = G._pred if hasattr(G, "_pred") else G._adj self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch)) self._weight = weight
def __call__(self, nbunch=None, weight=None): if nbunch is None: if weight == self._weight: return self return self.__class__(self._graph, None, weight) try: if nbunch in self._nodes: if weight == self._weight: return self[nbunch] return self.__class__(self._graph, None, weight)[nbunch] except TypeError: pass return self.__class__(self._graph, nbunch, weight)
def __getitem__(self, n): weight = self._weight succs = self._succ[n] preds = self._pred[n] if weight is None: return len(succs) + len(preds) return sum(dd.get(weight, 1) for dd in succs.values()) + sum( dd.get(weight, 1) for dd in preds.values() )
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: succs = self._succ[n] preds = self._pred[n] yield (n, len(succs) + len(preds)) else: for n in self._nodes: succs = self._succ[n] preds = self._pred[n] deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum( dd.get(weight, 1) for dd in preds.values() ) yield (n, deg)
def __len__(self): return len(self._nodes)
def __str__(self): return str(list(self))
def __repr__(self): return f"{self.__class__.__name__}({dict(self)})"
class DegreeView(DiDegreeView): """A DegreeView class to act as G.degree for a NetworkX Graph
Typical usage focuses on iteration over `(node, degree)` pairs. The degree is by default the number of edges incident to the node. Optional argument `weight` enables weighted degree using the edge attribute named in the `weight` argument. Reporting and iteration can also be restricted to a subset of nodes using `nbunch`.
Additional functionality include node lookup so that `G.degree[n]` reported the (possibly weighted) degree of node `n`. Calling the view creates a view with different arguments `nbunch` or `weight`.
Parameters ========== graph : NetworkX graph-like class nbunch : node, container of nodes, or None meaning all nodes (default=None) weight : string or None (default=None)
Notes ----- DegreeView can still lookup any node even if nbunch is specified.
Examples -------- >>> G = nx.path_graph(3) >>> DV = G.degree() >>> assert DV[2] == 1 >>> assert G.degree[2] == 1 >>> assert sum(deg for n, deg in DV) == 4
>>> DVweight = G.degree(weight="span") >>> G.add_edge(1, 2, span=34) >>> DVweight[2] 34 >>> DVweight[0] # default edge weight is 1 1 >>> sum(span for n, span in DVweight) # sum weighted degrees 70
>>> DVnbunch = G.degree(nbunch=(1, 2)) >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only """
def __getitem__(self, n): weight = self._weight nbrs = self._succ[n] if weight is None: return len(nbrs) + (n in nbrs) return sum(dd.get(weight, 1) for dd in nbrs.values()) + ( n in nbrs and nbrs[n].get(weight, 1) )
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: nbrs = self._succ[n] yield (n, len(nbrs) + (n in nbrs)) else: for n in self._nodes: nbrs = self._succ[n] deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + ( n in nbrs and nbrs[n].get(weight, 1) ) yield (n, deg)
class OutDegreeView(DiDegreeView): """A DegreeView class to report out_degree for a DiGraph; See DegreeView"""
def __getitem__(self, n): weight = self._weight nbrs = self._succ[n] if self._weight is None: return len(nbrs) return sum(dd.get(self._weight, 1) for dd in nbrs.values())
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: succs = self._succ[n] yield (n, len(succs)) else: for n in self._nodes: succs = self._succ[n] deg = sum(dd.get(weight, 1) for dd in succs.values()) yield (n, deg)
class InDegreeView(DiDegreeView): """A DegreeView class to report in_degree for a DiGraph; See DegreeView"""
def __getitem__(self, n): weight = self._weight nbrs = self._pred[n] if weight is None: return len(nbrs) return sum(dd.get(weight, 1) for dd in nbrs.values())
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: preds = self._pred[n] yield (n, len(preds)) else: for n in self._nodes: preds = self._pred[n] deg = sum(dd.get(weight, 1) for dd in preds.values()) yield (n, deg)
class MultiDegreeView(DiDegreeView): """A DegreeView class for undirected multigraphs; See DegreeView"""
def __getitem__(self, n): weight = self._weight nbrs = self._succ[n] if weight is None: return sum(len(keys) for keys in nbrs.values()) + ( n in nbrs and len(nbrs[n]) ) # edge weighted graph - degree is sum of nbr edge weights deg = sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() ) if n in nbrs: deg += sum(d.get(weight, 1) for d in nbrs[n].values()) return deg
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: nbrs = self._succ[n] deg = sum(len(keys) for keys in nbrs.values()) + ( n in nbrs and len(nbrs[n]) ) yield (n, deg) else: for n in self._nodes: nbrs = self._succ[n] deg = sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() ) if n in nbrs: deg += sum(d.get(weight, 1) for d in nbrs[n].values()) yield (n, deg)
class DiMultiDegreeView(DiDegreeView): """A DegreeView class for MultiDiGraph; See DegreeView"""
def __getitem__(self, n): weight = self._weight succs = self._succ[n] preds = self._pred[n] if weight is None: return sum(len(keys) for keys in succs.values()) + sum( len(keys) for keys in preds.values() ) # edge weighted graph - degree is sum of nbr edge weights deg = sum( d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values() ) + sum( d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values() ) return deg
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: succs = self._succ[n] preds = self._pred[n] deg = sum(len(keys) for keys in succs.values()) + sum( len(keys) for keys in preds.values() ) yield (n, deg) else: for n in self._nodes: succs = self._succ[n] preds = self._pred[n] deg = sum( d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values() ) + sum( d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values() ) yield (n, deg)
class InMultiDegreeView(DiDegreeView): """A DegreeView class for inward degree of MultiDiGraph; See DegreeView"""
def __getitem__(self, n): weight = self._weight nbrs = self._pred[n] if weight is None: return sum(len(data) for data in nbrs.values()) # edge weighted graph - degree is sum of nbr edge weights return sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() )
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: nbrs = self._pred[n] deg = sum(len(data) for data in nbrs.values()) yield (n, deg) else: for n in self._nodes: nbrs = self._pred[n] deg = sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() ) yield (n, deg)
class OutMultiDegreeView(DiDegreeView): """A DegreeView class for outward degree of MultiDiGraph; See DegreeView"""
def __getitem__(self, n): weight = self._weight nbrs = self._succ[n] if weight is None: return sum(len(data) for data in nbrs.values()) # edge weighted graph - degree is sum of nbr edge weights return sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() )
def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: nbrs = self._succ[n] deg = sum(len(data) for data in nbrs.values()) yield (n, deg) else: for n in self._nodes: nbrs = self._succ[n] deg = sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() ) yield (n, deg)
# A base class for all edge views. Ensures all edge view and edge data view# objects/classes are captured by `isinstance(obj, EdgeViewABC)` and# `issubclass(cls, EdgeViewABC)` respectivelyclass EdgeViewABC(ABC): pass
# EdgeDataViewsclass OutEdgeDataView(EdgeViewABC): """EdgeDataView for outward edges of DiGraph; See EdgeDataView"""
__slots__ = ( "_viewer", "_nbunch", "_data", "_default", "_adjdict", "_nodes_nbrs", "_report", )
def __getstate__(self): return { "viewer": self._viewer, "nbunch": self._nbunch, "data": self._data, "default": self._default, }
def __setstate__(self, state): self.__init__(**state)
def __init__(self, viewer, nbunch=None, data=False, *, default=None): self._viewer = viewer adjdict = self._adjdict = viewer._adjdict if nbunch is None: self._nodes_nbrs = adjdict.items else: # dict retains order of nodes but acts like a set nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch)) self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch] self._nbunch = nbunch self._data = data self._default = default # Set _report based on data and default if data is True: self._report = lambda n, nbr, dd: (n, nbr, dd) elif data is False: self._report = lambda n, nbr, dd: (n, nbr) else: # data is attribute name self._report = ( lambda n, nbr, dd: (n, nbr, dd[data]) if data in dd else (n, nbr, default) )
def __len__(self): return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
def __iter__(self): return ( self._report(n, nbr, dd) for n, nbrs in self._nodes_nbrs() for nbr, dd in nbrs.items() )
def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and u not in self._nbunch: return False # this edge doesn't start in nbunch try: ddict = self._adjdict[u][v] except KeyError: return False return e == self._report(u, v, ddict)
def __str__(self): return str(list(self))
def __repr__(self): return f"{self.__class__.__name__}({list(self)})"
class EdgeDataView(OutEdgeDataView): """A EdgeDataView class for edges of Graph
This view is primarily used to iterate over the edges reporting edges as node-tuples with edge data optionally reported. The argument `nbunch` allows restriction to edges incident to nodes in that container/singleton. The default (nbunch=None) reports all edges. The arguments `data` and `default` control what edge data is reported. The default `data is False` reports only node-tuples for each edge. If `data is True` the entire edge data dict is returned. Otherwise `data` is assumed to hold the name of the edge attribute to report with default `default` if that edge attribute is not present.
Parameters ---------- nbunch : container of nodes, node or None (default None) data : False, True or string (default False) default : default value (default None)
Examples -------- >>> G = nx.path_graph(3) >>> G.add_edge(1, 2, foo="bar") >>> list(G.edges(data="foo", default="biz")) [(0, 1, 'biz'), (1, 2, 'bar')] >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz") """
__slots__ = ()
def __len__(self): return sum(1 for e in self)
def __iter__(self): seen = {} for n, nbrs in self._nodes_nbrs(): for nbr, dd in nbrs.items(): if nbr not in seen: yield self._report(n, nbr, dd) seen[n] = 1 del seen
def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch: return False # this edge doesn't start and it doesn't end in nbunch try: ddict = self._adjdict[u][v] except KeyError: return False return e == self._report(u, v, ddict)
class InEdgeDataView(OutEdgeDataView): """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView"""
__slots__ = ()
def __iter__(self): return ( self._report(nbr, n, dd) for n, nbrs in self._nodes_nbrs() for nbr, dd in nbrs.items() )
def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and v not in self._nbunch: return False # this edge doesn't end in nbunch try: ddict = self._adjdict[v][u] except KeyError: return False return e == self._report(u, v, ddict)
class OutMultiEdgeDataView(OutEdgeDataView): """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
__slots__ = ("keys",)
def __getstate__(self): return { "viewer": self._viewer, "nbunch": self._nbunch, "keys": self.keys, "data": self._data, "default": self._default, }
def __setstate__(self, state): self.__init__(**state)
def __init__(self, viewer, nbunch=None, data=False, *, default=None, keys=False): self._viewer = viewer adjdict = self._adjdict = viewer._adjdict self.keys = keys if nbunch is None: self._nodes_nbrs = adjdict.items else: # dict retains order of nodes but acts like a set nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch)) self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch] self._nbunch = nbunch self._data = data self._default = default # Set _report based on data and default if data is True: if keys is True: self._report = lambda n, nbr, k, dd: (n, nbr, k, dd) else: self._report = lambda n, nbr, k, dd: (n, nbr, dd) elif data is False: if keys is True: self._report = lambda n, nbr, k, dd: (n, nbr, k) else: self._report = lambda n, nbr, k, dd: (n, nbr) else: # data is attribute name if keys is True: self._report = ( lambda n, nbr, k, dd: (n, nbr, k, dd[data]) if data in dd else (n, nbr, k, default) ) else: self._report = ( lambda n, nbr, k, dd: (n, nbr, dd[data]) if data in dd else (n, nbr, default) )
def __len__(self): return sum(1 for e in self)
def __iter__(self): return ( self._report(n, nbr, k, dd) for n, nbrs in self._nodes_nbrs() for nbr, kd in nbrs.items() for k, dd in kd.items() )
def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and u not in self._nbunch: return False # this edge doesn't start in nbunch try: kdict = self._adjdict[u][v] except KeyError: return False if self.keys is True: k = e[2] try: dd = kdict[k] except KeyError: return False return e == self._report(u, v, k, dd) return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
class MultiEdgeDataView(OutMultiEdgeDataView): """An EdgeDataView class for edges of MultiGraph; See EdgeDataView"""
__slots__ = ()
def __iter__(self): seen = {} for n, nbrs in self._nodes_nbrs(): for nbr, kd in nbrs.items(): if nbr not in seen: for k, dd in kd.items(): yield self._report(n, nbr, k, dd) seen[n] = 1 del seen
def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch: return False # this edge doesn't start and doesn't end in nbunch try: kdict = self._adjdict[u][v] except KeyError: try: kdict = self._adjdict[v][u] except KeyError: return False if self.keys is True: k = e[2] try: dd = kdict[k] except KeyError: return False return e == self._report(u, v, k, dd) return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
class InMultiEdgeDataView(OutMultiEdgeDataView): """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView"""
__slots__ = ()
def __iter__(self): return ( self._report(nbr, n, k, dd) for n, nbrs in self._nodes_nbrs() for nbr, kd in nbrs.items() for k, dd in kd.items() )
def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and v not in self._nbunch: return False # this edge doesn't end in nbunch try: kdict = self._adjdict[v][u] except KeyError: return False if self.keys is True: k = e[2] dd = kdict[k] return e == self._report(u, v, k, dd) return any(e == self._report(u, v, k, dd) for k, dd in kdict.items())
# EdgeViews have set operations and no data reportedclass OutEdgeView(Set, Mapping, EdgeViewABC): """A EdgeView class for outward edges of a DiGraph"""
__slots__ = ("_adjdict", "_graph", "_nodes_nbrs")
def __getstate__(self): return {"_graph": self._graph, "_adjdict": self._adjdict}
def __setstate__(self, state): self._graph = state["_graph"] self._adjdict = state["_adjdict"] self._nodes_nbrs = self._adjdict.items
@classmethod def _from_iterable(cls, it): return set(it)
dataview = OutEdgeDataView
def __init__(self, G): self._graph = G self._adjdict = G._succ if hasattr(G, "succ") else G._adj self._nodes_nbrs = self._adjdict.items
# Set methods def __len__(self): return sum(len(nbrs) for n, nbrs in self._nodes_nbrs())
def __iter__(self): for n, nbrs in self._nodes_nbrs(): for nbr in nbrs: yield (n, nbr)
def __contains__(self, e): try: u, v = e return v in self._adjdict[u] except KeyError: return False
# Mapping Methods def __getitem__(self, e): if isinstance(e, slice): raise nx.NetworkXError( f"{type(self).__name__} does not support slicing, " f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]" ) u, v = e try: return self._adjdict[u][v] except KeyError as ex: # Customize msg to indicate exception origin raise KeyError(f"The edge {e} is not in the graph.")
# EdgeDataView methods def __call__(self, nbunch=None, data=False, *, default=None): if nbunch is None and data is False: return self return self.dataview(self, nbunch, data, default=default)
def data(self, data=True, default=None, nbunch=None): """ Return a read-only view of edge data.
Parameters ---------- data : bool or edge attribute key If ``data=True``, then the data view maps each edge to a dictionary containing all of its attributes. If `data` is a key in the edge dictionary, then the data view maps each edge to its value for the keyed attribute. In this case, if the edge doesn't have the attribute, the `default` value is returned. default : object, default=None The value used when an edge does not have a specific attribute nbunch : container of nodes, optional (default=None) Allows restriction to edges only involving certain nodes. All edges are considered by default.
Returns ------- dataview Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView` for DiGraphs, `MultiEdgeDataView` for MultiGraphs and `OutMultiEdgeDataView` for MultiDiGraphs.
Notes ----- If ``data=False``, returns an `EdgeView` without any edge data.
See Also -------- EdgeDataView OutEdgeDataView MultiEdgeDataView OutMultiEdgeDataView
Examples -------- >>> G = nx.Graph() >>> G.add_edges_from( ... [ ... (0, 1, {"dist": 3, "capacity": 20}), ... (1, 2, {"dist": 4}), ... (2, 0, {"dist": 5}), ... ] ... )
Accessing edge data with ``data=True`` (the default) returns an edge data view object listing each edge with all of its attributes:
>>> G.edges.data() EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})])
If `data` represents a key in the edge attribute dict, a dataview listing each edge with its value for that specific key is returned:
>>> G.edges.data("dist") EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)])
`nbunch` can be used to limit the edges:
>>> G.edges.data("dist", nbunch=[0]) EdgeDataView([(0, 1, 3), (0, 2, 5)])
If a specific key is not found in an edge attribute dict, the value specified by `default` is used:
>>> G.edges.data("capacity") EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)])
Note that there is no check that the `data` key is present in any of the edge attribute dictionaries:
>>> G.edges.data("speed") EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)]) """ if nbunch is None and data is False: return self return self.dataview(self, nbunch, data, default=default)
# String Methods def __str__(self): return str(list(self))
def __repr__(self): return f"{self.__class__.__name__}({list(self)})"
class EdgeView(OutEdgeView): """A EdgeView class for edges of a Graph
This densely packed View allows iteration over edges, data lookup like a dict and set operations on edges represented by node-tuples. In addition, edge data can be controlled by calling this object possibly creating an EdgeDataView. Typically edges are iterated over and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples for multigraphs. Those edge representations can also be using to lookup the data dict for any edge. Set operations also are available where those tuples are the elements of the set. Calling this object with optional arguments `data`, `default` and `keys` controls the form of the tuple (see EdgeDataView). Optional argument `nbunch` allows restriction to edges only involving certain nodes.
If `data is False` (the default) then iterate over 2-tuples `(u, v)`. If `data is True` iterate over 3-tuples `(u, v, datadict)`. Otherwise iterate over `(u, v, datadict.get(data, default))`. For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above.
Parameters ========== graph : NetworkX graph-like class nbunch : (default= all nodes in graph) only report edges with these nodes keys : (only for MultiGraph. default=False) report edge key in tuple data : bool or string (default=False) see above default : object (default=None)
Examples ======== >>> G = nx.path_graph(4) >>> EV = G.edges() >>> (2, 3) in EV True >>> for u, v in EV: ... print((u, v)) (0, 1) (1, 2) (2, 3) >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)}
>>> EVdata = G.edges(data="color", default="aqua") >>> G.add_edge(2, 3, color="blue") >>> assert (2, 3, "blue") in EVdata >>> for u, v, c in EVdata: ... print(f"({u}, {v}) has color: {c}") (0, 1) has color: aqua (1, 2) has color: aqua (2, 3) has color: blue
>>> EVnbunch = G.edges(nbunch=2) >>> assert (2, 3) in EVnbunch >>> assert (0, 1) not in EVnbunch >>> for u, v in EVnbunch: ... assert u == 2 or v == 2
>>> MG = nx.path_graph(4, create_using=nx.MultiGraph) >>> EVmulti = MG.edges(keys=True) >>> (2, 3, 0) in EVmulti True >>> (2, 3) in EVmulti # 2-tuples work even when keys is True True >>> key = MG.add_edge(2, 3) >>> for u, v, k in EVmulti: ... print((u, v, k)) (0, 1, 0) (1, 2, 0) (2, 3, 0) (2, 3, 1) """
__slots__ = ()
dataview = EdgeDataView
def __len__(self): num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs()) return sum(num_nbrs) // 2
def __iter__(self): seen = {} for n, nbrs in self._nodes_nbrs(): for nbr in list(nbrs): if nbr not in seen: yield (n, nbr) seen[n] = 1 del seen
def __contains__(self, e): try: u, v = e[:2] return v in self._adjdict[u] or u in self._adjdict[v] except (KeyError, ValueError): return False
class InEdgeView(OutEdgeView): """A EdgeView class for inward edges of a DiGraph"""
__slots__ = ()
def __setstate__(self, state): self._graph = state["_graph"] self._adjdict = state["_adjdict"] self._nodes_nbrs = self._adjdict.items
dataview = InEdgeDataView
def __init__(self, G): self._graph = G self._adjdict = G._pred if hasattr(G, "pred") else G._adj self._nodes_nbrs = self._adjdict.items
def __iter__(self): for n, nbrs in self._nodes_nbrs(): for nbr in nbrs: yield (nbr, n)
def __contains__(self, e): try: u, v = e return u in self._adjdict[v] except KeyError: return False
def __getitem__(self, e): if isinstance(e, slice): raise nx.NetworkXError( f"{type(self).__name__} does not support slicing, " f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]" ) u, v = e return self._adjdict[v][u]
class OutMultiEdgeView(OutEdgeView): """A EdgeView class for outward edges of a MultiDiGraph"""
__slots__ = ()
dataview = OutMultiEdgeDataView
def __len__(self): return sum( len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items() )
def __iter__(self): for n, nbrs in self._nodes_nbrs(): for nbr, kdict in nbrs.items(): for key in kdict: yield (n, nbr, key)
def __contains__(self, e): N = len(e) if N == 3: u, v, k = e elif N == 2: u, v = e k = 0 else: raise ValueError("MultiEdge must have length 2 or 3") try: return k in self._adjdict[u][v] except KeyError: return False
def __getitem__(self, e): if isinstance(e, slice): raise nx.NetworkXError( f"{type(self).__name__} does not support slicing, " f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]" ) u, v, k = e return self._adjdict[u][v][k]
def __call__(self, nbunch=None, data=False, *, default=None, keys=False): if nbunch is None and data is False and keys is True: return self return self.dataview(self, nbunch, data, default=default, keys=keys)
def data(self, data=True, default=None, nbunch=None, keys=False): if nbunch is None and data is False and keys is True: return self return self.dataview(self, nbunch, data, default=default, keys=keys)
class MultiEdgeView(OutMultiEdgeView): """A EdgeView class for edges of a MultiGraph"""
__slots__ = ()
dataview = MultiEdgeDataView
def __len__(self): return sum(1 for e in self)
def __iter__(self): seen = {} for n, nbrs in self._nodes_nbrs(): for nbr, kd in nbrs.items(): if nbr not in seen: for k, dd in kd.items(): yield (n, nbr, k) seen[n] = 1 del seen
class InMultiEdgeView(OutMultiEdgeView): """A EdgeView class for inward edges of a MultiDiGraph"""
__slots__ = ()
def __setstate__(self, state): self._graph = state["_graph"] self._adjdict = state["_adjdict"] self._nodes_nbrs = self._adjdict.items
dataview = InMultiEdgeDataView
def __init__(self, G): self._graph = G self._adjdict = G._pred if hasattr(G, "pred") else G._adj self._nodes_nbrs = self._adjdict.items
def __iter__(self): for n, nbrs in self._nodes_nbrs(): for nbr, kdict in nbrs.items(): for key in kdict: yield (nbr, n, key)
def __contains__(self, e): N = len(e) if N == 3: u, v, k = e elif N == 2: u, v = e k = 0 else: raise ValueError("MultiEdge must have length 2 or 3") try: return k in self._adjdict[v][u] except KeyError: return False
def __getitem__(self, e): if isinstance(e, slice): raise nx.NetworkXError( f"{type(self).__name__} does not support slicing, " f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]" ) u, v, k = e return self._adjdict[v][u][k]lib/python3.12/site-packages/blinker-1.9.0.dist-info/INSTALLERAdded+1
lib/python3.12/site-packages/blinker-1.9.0.dist-info/LICENSE.txtAdded+20
lib/python3.12/site-packages/blinker-1.9.0.dist-info/METADATAAdded+60
lib/python3.12/site-packages/blinker-1.9.0.dist-info/RECORDAdded+12
lib/python3.12/site-packages/blinker-1.9.0.dist-info/WHEELAdded+4
lib/python3.12/site-packages/executing-2.2.1.dist-info/INSTALLERAdded+1
lib/python3.12/site-packages/executing-2.2.1.dist-info/LICENSE.txtAdded+21
lib/python3.12/site-packages/executing-2.2.1.dist-info/METADATAAdded+171
lib/python3.12/site-packages/executing-2.2.1.dist-info/RECORDAdded+21
lib/python3.12/site-packages/executing-2.2.1.dist-info/WHEELAdded+6
lib/python3.12/site-packages/executing-2.2.1.dist-info/top_level.txtAdded+1
lib/python3.12/site-packages/networkx/__init__.pyAdded+62
lib/python3.12/site-packages/networkx/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/__pycache__/conftest.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/__pycache__/convert.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/__pycache__/convert_matrix.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/__pycache__/exception.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/__pycache__/lazy_imports.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/__pycache__/relabel.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__init__.pyAdded+13
lib/python3.12/site-packages/networkx/classes/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/coreviews.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/digraph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/filters.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/function.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/graph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/graphviews.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/multidigraph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/multigraph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/__pycache__/reportviews.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/coreviews.pyAdded+435
lib/python3.12/site-packages/networkx/classes/digraph.pyAdded+1363
lib/python3.12/site-packages/networkx/classes/filters.pyAdded+95
lib/python3.12/site-packages/networkx/classes/function.pyAdded+1549
lib/python3.12/site-packages/networkx/classes/graph.pyAdded+2082
lib/python3.12/site-packages/networkx/classes/graphviews.pyAdded+269
lib/python3.12/site-packages/networkx/classes/multidigraph.pyAdded+977
lib/python3.12/site-packages/networkx/classes/multigraph.pyAdded+1294
lib/python3.12/site-packages/networkx/classes/reportviews.pyAdded+1447
lib/python3.12/site-packages/networkx/classes/tests/__init__.pyAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_coreviews.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_digraph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_digraph_historical.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_function.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_graph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/classes/tests/__pycache__/test_graph_historical.cpython-312.pycAdded