Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/10.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/16.attention.dense.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/16.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/17.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/26.attention.query_key_value.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/26.attention.query_key_value.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/INSTALLER +1 -0
- venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/LICENSE +20 -0
- venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/METADATA +66 -0
- venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/RECORD +14 -0
- venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/WHEEL +5 -0
- venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/top_level.txt +1 -0
- venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/INSTALLER +1 -0
- venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/LICENSE +201 -0
- venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/METADATA +420 -0
- venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/RECORD +12 -0
- venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/WHEEL +8 -0
- venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/top_level.txt +1 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/INSTALLER +1 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/LICENSE.md +21 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/METADATA +558 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/RECORD +14 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/REQUESTED +0 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/WHEEL +5 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/direct_url.json +1 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/entry_points.txt +3 -0
- venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/top_level.txt +1 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/INSTALLER +1 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/LICENSE.txt +29 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/LICENSES.txt +29 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/METADATA +89 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/RECORD +201 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/WHEEL +5 -0
- venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/top_level.txt +1 -0
- venv/lib/python3.10/site-packages/networkx/__init__.py +49 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/conftest.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/convert.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/convert_matrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/exception.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/lazy_imports.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/__pycache__/relabel.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/classes/__init__.py +13 -0
- venv/lib/python3.10/site-packages/networkx/classes/digraph.py +1334 -0
- venv/lib/python3.10/site-packages/networkx/classes/filters.py +87 -0
- venv/lib/python3.10/site-packages/networkx/classes/function.py +1335 -0
- venv/lib/python3.10/site-packages/networkx/classes/graph.py +2043 -0
- venv/lib/python3.10/site-packages/networkx/classes/graphviews.py +269 -0
- venv/lib/python3.10/site-packages/networkx/classes/multidigraph.py +965 -0
- venv/lib/python3.10/site-packages/networkx/classes/multigraph.py +1282 -0
ckpts/universal/global_step80/zero/10.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5e9c54dfffb3aba9d6db77729f80bd8bceb3689fbf2e9fe0b4f3f916a4ce271c
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/16.attention.dense.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1df0180bdc2af17b8deb1d44cdb55e8ff1ea09da825eb6975bcf350d36b806a3
|
3 |
+
size 16778411
|
ckpts/universal/global_step80/zero/16.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0c986afa78b200cbb3b3e10b26c581d09a2cf74ad70535a3b34b48194699aa35
|
3 |
+
size 16778317
|
ckpts/universal/global_step80/zero/17.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d48e7e421352cc1b4cef5f5f8162403f6f876faffe6abc909aa72f5294577f08
|
3 |
+
size 16778317
|
ckpts/universal/global_step80/zero/26.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ed58a358765b9003fb648cc20a3e709a31725fd6fd79c03e317b810d08908ebd
|
3 |
+
size 50332828
|
ckpts/universal/global_step80/zero/26.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e4dad34a3ad11f967f14743e8d1378c3216a69f6eaeafb14727bf6b1488130c3
|
3 |
+
size 50332749
|
venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
This package contains a modified version of ca-bundle.crt:
|
2 |
+
|
3 |
+
ca-bundle.crt -- Bundle of CA Root Certificates
|
4 |
+
|
5 |
+
This is a bundle of X.509 certificates of public Certificate Authorities
|
6 |
+
(CA). These were automatically extracted from Mozilla's root certificates
|
7 |
+
file (certdata.txt). This file can be found in the mozilla source tree:
|
8 |
+
https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt
|
9 |
+
It contains the certificates in PEM format and therefore
|
10 |
+
can be directly used with curl / libcurl / php_curl, or with
|
11 |
+
an Apache+mod_ssl webserver for SSL client authentication.
|
12 |
+
Just configure this file as the SSLCACertificateFile.#
|
13 |
+
|
14 |
+
***** BEGIN LICENSE BLOCK *****
|
15 |
+
This Source Code Form is subject to the terms of the Mozilla Public License,
|
16 |
+
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
|
17 |
+
one at http://mozilla.org/MPL/2.0/.
|
18 |
+
|
19 |
+
***** END LICENSE BLOCK *****
|
20 |
+
@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $
|
venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/METADATA
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: certifi
|
3 |
+
Version: 2024.2.2
|
4 |
+
Summary: Python package for providing Mozilla's CA Bundle.
|
5 |
+
Home-page: https://github.com/certifi/python-certifi
|
6 |
+
Author: Kenneth Reitz
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: MPL-2.0
|
9 |
+
Project-URL: Source, https://github.com/certifi/python-certifi
|
10 |
+
Classifier: Development Status :: 5 - Production/Stable
|
11 |
+
Classifier: Intended Audience :: Developers
|
12 |
+
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
|
13 |
+
Classifier: Natural Language :: English
|
14 |
+
Classifier: Programming Language :: Python
|
15 |
+
Classifier: Programming Language :: Python :: 3
|
16 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
17 |
+
Classifier: Programming Language :: Python :: 3.6
|
18 |
+
Classifier: Programming Language :: Python :: 3.7
|
19 |
+
Classifier: Programming Language :: Python :: 3.8
|
20 |
+
Classifier: Programming Language :: Python :: 3.9
|
21 |
+
Classifier: Programming Language :: Python :: 3.10
|
22 |
+
Classifier: Programming Language :: Python :: 3.11
|
23 |
+
Requires-Python: >=3.6
|
24 |
+
License-File: LICENSE
|
25 |
+
|
26 |
+
Certifi: Python SSL Certificates
|
27 |
+
================================
|
28 |
+
|
29 |
+
Certifi provides Mozilla's carefully curated collection of Root Certificates for
|
30 |
+
validating the trustworthiness of SSL certificates while verifying the identity
|
31 |
+
of TLS hosts. It has been extracted from the `Requests`_ project.
|
32 |
+
|
33 |
+
Installation
|
34 |
+
------------
|
35 |
+
|
36 |
+
``certifi`` is available on PyPI. Simply install it with ``pip``::
|
37 |
+
|
38 |
+
$ pip install certifi
|
39 |
+
|
40 |
+
Usage
|
41 |
+
-----
|
42 |
+
|
43 |
+
To reference the installed certificate authority (CA) bundle, you can use the
|
44 |
+
built-in function::
|
45 |
+
|
46 |
+
>>> import certifi
|
47 |
+
|
48 |
+
>>> certifi.where()
|
49 |
+
'/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
|
50 |
+
|
51 |
+
Or from the command line::
|
52 |
+
|
53 |
+
$ python -m certifi
|
54 |
+
/usr/local/lib/python3.7/site-packages/certifi/cacert.pem
|
55 |
+
|
56 |
+
Enjoy!
|
57 |
+
|
58 |
+
.. _`Requests`: https://requests.readthedocs.io/en/master/
|
59 |
+
|
60 |
+
Addition/Removal of Certificates
|
61 |
+
--------------------------------
|
62 |
+
|
63 |
+
Certifi does not support any addition/removal or other modification of the
|
64 |
+
CA trust store content. This project is intended to provide a reliable and
|
65 |
+
highly portable root of trust to python deployments. Look to upstream projects
|
66 |
+
for methods to use alternate trust.
|
venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/RECORD
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
certifi-2024.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
certifi-2024.2.2.dist-info/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
|
3 |
+
certifi-2024.2.2.dist-info/METADATA,sha256=1noreLRChpOgeSj0uJT1mehiBl8ngh33Guc7KdvzYYM,2170
|
4 |
+
certifi-2024.2.2.dist-info/RECORD,,
|
5 |
+
certifi-2024.2.2.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
|
6 |
+
certifi-2024.2.2.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
|
7 |
+
certifi/__init__.py,sha256=ljtEx-EmmPpTe2SOd5Kzsujm_lUD0fKJVnE9gzce320,94
|
8 |
+
certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
|
9 |
+
certifi/__pycache__/__init__.cpython-310.pyc,,
|
10 |
+
certifi/__pycache__/__main__.cpython-310.pyc,,
|
11 |
+
certifi/__pycache__/core.cpython-310.pyc,,
|
12 |
+
certifi/cacert.pem,sha256=ejR8qP724p-CtuR4U1WmY1wX-nVeCUD2XxWqj8e9f5I,292541
|
13 |
+
certifi/core.py,sha256=qRDDFyXVJwTB_EmoGppaXU_R9qCZvhl-EzxPMuV3nTA,4426
|
14 |
+
certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.42.0)
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
5 |
+
|
venv/lib/python3.10/site-packages/certifi-2024.2.2.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
certifi
|
venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright 2013-2019 Nikolay Kim and Andrew Svetlov
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/METADATA
ADDED
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: frozenlist
|
3 |
+
Version: 1.4.1
|
4 |
+
Summary: A list-like structure which implements collections.abc.MutableSequence
|
5 |
+
Home-page: https://github.com/aio-libs/frozenlist
|
6 |
+
Maintainer: aiohttp team <[email protected]>
|
7 |
+
Maintainer-email: [email protected]
|
8 |
+
License: Apache 2
|
9 |
+
Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org
|
10 |
+
Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org
|
11 |
+
Project-URL: CI: Github Actions, https://github.com/aio-libs/frozenlist/actions
|
12 |
+
Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md
|
13 |
+
Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/frozenlist
|
14 |
+
Project-URL: Docs: Changelog, https://github.com/aio-libs/frozenlist/blob/master/CHANGES.rst#changelog
|
15 |
+
Project-URL: Docs: RTD, https://frozenlist.aio-libs.org
|
16 |
+
Project-URL: GitHub: issues, https://github.com/aio-libs/frozenlist/issues
|
17 |
+
Project-URL: GitHub: repo, https://github.com/aio-libs/frozenlist
|
18 |
+
Classifier: Development Status :: 5 - Production/Stable
|
19 |
+
Classifier: Intended Audience :: Developers
|
20 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
21 |
+
Classifier: Operating System :: POSIX
|
22 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
23 |
+
Classifier: Operating System :: Microsoft :: Windows
|
24 |
+
Classifier: Programming Language :: Cython
|
25 |
+
Classifier: Programming Language :: Python
|
26 |
+
Classifier: Programming Language :: Python :: 3
|
27 |
+
Classifier: Programming Language :: Python :: 3.8
|
28 |
+
Classifier: Programming Language :: Python :: 3.9
|
29 |
+
Classifier: Programming Language :: Python :: 3.10
|
30 |
+
Classifier: Programming Language :: Python :: 3.11
|
31 |
+
Classifier: Programming Language :: Python :: 3.12
|
32 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
33 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
34 |
+
Requires-Python: >=3.8
|
35 |
+
Description-Content-Type: text/x-rst
|
36 |
+
License-File: LICENSE
|
37 |
+
|
38 |
+
frozenlist
|
39 |
+
==========
|
40 |
+
|
41 |
+
.. image:: https://github.com/aio-libs/frozenlist/workflows/CI/badge.svg
|
42 |
+
:target: https://github.com/aio-libs/frozenlist/actions
|
43 |
+
:alt: GitHub status for master branch
|
44 |
+
|
45 |
+
.. image:: https://codecov.io/gh/aio-libs/frozenlist/branch/master/graph/badge.svg
|
46 |
+
:target: https://codecov.io/gh/aio-libs/frozenlist
|
47 |
+
:alt: codecov.io status for master branch
|
48 |
+
|
49 |
+
.. image:: https://img.shields.io/pypi/v/frozenlist.svg?logo=Python&logoColor=white
|
50 |
+
:target: https://pypi.org/project/frozenlist
|
51 |
+
:alt: frozenlist @ PyPI
|
52 |
+
|
53 |
+
.. image:: https://readthedocs.org/projects/frozenlist/badge/?version=latest
|
54 |
+
:target: https://frozenlist.aio-libs.org
|
55 |
+
:alt: Read The Docs build status badge
|
56 |
+
|
57 |
+
.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
|
58 |
+
:target: https://matrix.to/#/%23aio-libs:matrix.org
|
59 |
+
:alt: Matrix Room — #aio-libs:matrix.org
|
60 |
+
|
61 |
+
.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
|
62 |
+
:target: https://matrix.to/#/%23aio-libs-space:matrix.org
|
63 |
+
:alt: Matrix Space — #aio-libs-space:matrix.org
|
64 |
+
|
65 |
+
Introduction
|
66 |
+
------------
|
67 |
+
|
68 |
+
``frozenlist.FrozenList`` is a list-like structure which implements
|
69 |
+
``collections.abc.MutableSequence``. The list is *mutable* until ``FrozenList.freeze``
|
70 |
+
is called, after which list modifications raise ``RuntimeError``:
|
71 |
+
|
72 |
+
|
73 |
+
>>> from frozenlist import FrozenList
|
74 |
+
>>> fl = FrozenList([17, 42])
|
75 |
+
>>> fl.append('spam')
|
76 |
+
>>> fl.append('Vikings')
|
77 |
+
>>> fl
|
78 |
+
<FrozenList(frozen=False, [17, 42, 'spam', 'Vikings'])>
|
79 |
+
>>> fl.freeze()
|
80 |
+
>>> fl
|
81 |
+
<FrozenList(frozen=True, [17, 42, 'spam', 'Vikings'])>
|
82 |
+
>>> fl.frozen
|
83 |
+
True
|
84 |
+
>>> fl.append("Monty")
|
85 |
+
Traceback (most recent call last):
|
86 |
+
File "<stdin>", line 1, in <module>
|
87 |
+
File "frozenlist/_frozenlist.pyx", line 97, in frozenlist._frozenlist.FrozenList.append
|
88 |
+
self._check_frozen()
|
89 |
+
File "frozenlist/_frozenlist.pyx", line 19, in frozenlist._frozenlist.FrozenList._check_frozen
|
90 |
+
raise RuntimeError("Cannot modify frozen list.")
|
91 |
+
RuntimeError: Cannot modify frozen list.
|
92 |
+
|
93 |
+
|
94 |
+
FrozenList is also hashable, but only when frozen. Otherwise it also throws a RuntimeError:
|
95 |
+
|
96 |
+
|
97 |
+
>>> fl = FrozenList([17, 42, 'spam'])
|
98 |
+
>>> hash(fl)
|
99 |
+
Traceback (most recent call last):
|
100 |
+
File "<stdin>", line 1, in <module>
|
101 |
+
File "frozenlist/_frozenlist.pyx", line 111, in frozenlist._frozenlist.FrozenList.__hash__
|
102 |
+
raise RuntimeError("Cannot hash unfrozen list.")
|
103 |
+
RuntimeError: Cannot hash unfrozen list.
|
104 |
+
>>> fl.freeze()
|
105 |
+
>>> hash(fl)
|
106 |
+
3713081631934410656
|
107 |
+
>>> dictionary = {fl: 'Vikings'} # frozen fl can be a dict key
|
108 |
+
>>> dictionary
|
109 |
+
{<FrozenList(frozen=True, [1, 2])>: 'Vikings'}
|
110 |
+
|
111 |
+
|
112 |
+
Installation
|
113 |
+
------------
|
114 |
+
|
115 |
+
::
|
116 |
+
|
117 |
+
$ pip install frozenlist
|
118 |
+
|
119 |
+
The library requires Python 3.8 or newer.
|
120 |
+
|
121 |
+
|
122 |
+
Documentation
|
123 |
+
-------------
|
124 |
+
|
125 |
+
https://frozenlist.aio-libs.org
|
126 |
+
|
127 |
+
Communication channels
|
128 |
+
----------------------
|
129 |
+
|
130 |
+
We have a *Matrix Space* `#aio-libs-space:matrix.org
|
131 |
+
<https://matrix.to/#/%23aio-libs-space:matrix.org>`_ which is
|
132 |
+
also accessible via Gitter.
|
133 |
+
|
134 |
+
Requirements
|
135 |
+
------------
|
136 |
+
|
137 |
+
- Python >= 3.8
|
138 |
+
|
139 |
+
License
|
140 |
+
-------
|
141 |
+
|
142 |
+
``frozenlist`` is offered under the Apache 2 license.
|
143 |
+
|
144 |
+
Source code
|
145 |
+
-----------
|
146 |
+
|
147 |
+
The project is hosted on GitHub_
|
148 |
+
|
149 |
+
Please file an issue in the `bug tracker
|
150 |
+
<https://github.com/aio-libs/frozenlist/issues>`_ if you have found a bug
|
151 |
+
or have some suggestions to improve the library.
|
152 |
+
|
153 |
+
.. _GitHub: https://github.com/aio-libs/frozenlist
|
154 |
+
|
155 |
+
=========
|
156 |
+
Changelog
|
157 |
+
=========
|
158 |
+
|
159 |
+
..
|
160 |
+
You should *NOT* be adding new change log entries to this file, this
|
161 |
+
file is managed by towncrier. You *may* edit previous change logs to
|
162 |
+
fix problems like typo corrections or such.
|
163 |
+
To add a new change log entry, please see
|
164 |
+
https://pip.pypa.io/en/latest/development/contributing/#news-entries
|
165 |
+
we named the news folder "changes".
|
166 |
+
|
167 |
+
WARNING: Don't drop the next directive!
|
168 |
+
|
169 |
+
.. towncrier release notes start
|
170 |
+
|
171 |
+
1.4.1 (2023-12-15)
|
172 |
+
==================
|
173 |
+
|
174 |
+
Packaging updates and notes for downstreams
|
175 |
+
-------------------------------------------
|
176 |
+
|
177 |
+
- Declared Python 3.12 and PyPy 3.8-3.10 supported officially
|
178 |
+
in the distribution package metadata.
|
179 |
+
|
180 |
+
|
181 |
+
*Related issues and pull requests on GitHub:*
|
182 |
+
`#553 <https://github.com/aio-libs/yarl/issues/553>`__.
|
183 |
+
|
184 |
+
- Replaced the packaging is replaced from an old-fashioned ``setup.py`` to an
|
185 |
+
in-tree `PEP 517 <https://peps.python.org/pep-517>`__ build backend -- by `@webknjaz <https://github.com/sponsors/webknjaz>`__.
|
186 |
+
|
187 |
+
Whenever the end-users or downstream packagers need to build ``frozenlist``
|
188 |
+
from source (a Git checkout or an sdist), they may pass a ``config_settings``
|
189 |
+
flag ``pure-python``. If this flag is not set, a C-extension will be built
|
190 |
+
and included into the distribution.
|
191 |
+
|
192 |
+
Here is how this can be done with ``pip``:
|
193 |
+
|
194 |
+
.. code-block:: console
|
195 |
+
|
196 |
+
$ python3 -m pip install . --config-settings=pure-python=
|
197 |
+
|
198 |
+
This will also work with ``-e | --editable``.
|
199 |
+
|
200 |
+
The same can be achieved via ``pypa/build``:
|
201 |
+
|
202 |
+
.. code-block:: console
|
203 |
+
|
204 |
+
$ python3 -m build --config-setting=pure-python=
|
205 |
+
|
206 |
+
Adding ``-w | --wheel`` can force ``pypa/build`` produce a wheel from source
|
207 |
+
directly, as opposed to building an ``sdist`` and then building from it.
|
208 |
+
|
209 |
+
|
210 |
+
*Related issues and pull requests on GitHub:*
|
211 |
+
`#560 <https://github.com/aio-libs/yarl/issues/560>`__.
|
212 |
+
|
213 |
+
|
214 |
+
Contributor-facing changes
|
215 |
+
--------------------------
|
216 |
+
|
217 |
+
- It is now possible to request line tracing in Cython builds using the
|
218 |
+
``with-cython-tracing`` `PEP 517 <https://peps.python.org/pep-517>`__ config setting
|
219 |
+
-- `@webknjaz <https://github.com/sponsors/webknjaz>`__.
|
220 |
+
|
221 |
+
This can be used in CI and development environment to measure coverage
|
222 |
+
on Cython modules, but is not normally useful to the end-users or
|
223 |
+
downstream packagers.
|
224 |
+
|
225 |
+
Here's a usage example:
|
226 |
+
|
227 |
+
.. code-block:: console
|
228 |
+
|
229 |
+
$ python3 -Im pip install . --config-settings=with-cython-tracing=true
|
230 |
+
|
231 |
+
For editable installs, this setting is on by default. Otherwise, it's
|
232 |
+
off unless requested explicitly.
|
233 |
+
|
234 |
+
The following produces C-files required for the Cython coverage
|
235 |
+
plugin to map the measurements back to the PYX-files:
|
236 |
+
|
237 |
+
.. code-block:: console
|
238 |
+
|
239 |
+
$ python -Im pip install -e .
|
240 |
+
|
241 |
+
Alternatively, the ``FROZENLIST_CYTHON_TRACING=1`` environment variable
|
242 |
+
can be set to do the same as the `PEP 517 <https://peps.python.org/pep-517>`__ config setting.
|
243 |
+
|
244 |
+
|
245 |
+
*Related issues and pull requests on GitHub:*
|
246 |
+
`#560 <https://github.com/aio-libs/yarl/issues/560>`__.
|
247 |
+
|
248 |
+
- Coverage collection has been implemented for the Cython modules
|
249 |
+
-- by `@webknjaz <https://github.com/sponsors/webknjaz>`__.
|
250 |
+
|
251 |
+
It will also be reported to Codecov from any non-release CI jobs.
|
252 |
+
|
253 |
+
|
254 |
+
*Related issues and pull requests on GitHub:*
|
255 |
+
`#561 <https://github.com/aio-libs/yarl/issues/561>`__.
|
256 |
+
|
257 |
+
- A step-by-step ``Release Guide`` guide has
|
258 |
+
been added, describing how to release *frozenlist* -- by `@webknjaz <https://github.com/sponsors/webknjaz>`__.
|
259 |
+
|
260 |
+
This is primarily targeting the maintainers.
|
261 |
+
|
262 |
+
|
263 |
+
*Related issues and pull requests on GitHub:*
|
264 |
+
`#563 <https://github.com/aio-libs/yarl/issues/563>`__.
|
265 |
+
|
266 |
+
- Detailed ``Contributing Guidelines`` on
|
267 |
+
authoring the changelog fragments have been published in the
|
268 |
+
documentation -- by `@webknjaz <https://github.com/sponsors/webknjaz>`__.
|
269 |
+
|
270 |
+
|
271 |
+
*Related issues and pull requests on GitHub:*
|
272 |
+
`#564 <https://github.com/aio-libs/yarl/issues/564>`__.
|
273 |
+
|
274 |
+
|
275 |
+
----
|
276 |
+
|
277 |
+
|
278 |
+
1.4.0 (2023-07-12)
|
279 |
+
==================
|
280 |
+
|
281 |
+
The published source distribution package became buildable
|
282 |
+
under Python 3.12.
|
283 |
+
|
284 |
+
|
285 |
+
----
|
286 |
+
|
287 |
+
|
288 |
+
Bugfixes
|
289 |
+
--------
|
290 |
+
|
291 |
+
- Removed an unused ``typing.Tuple`` import
|
292 |
+
`#411 <https://github.com/aio-libs/frozenlist/issues/411>`_
|
293 |
+
|
294 |
+
|
295 |
+
Deprecations and Removals
|
296 |
+
-------------------------
|
297 |
+
|
298 |
+
- Dropped Python 3.7 support.
|
299 |
+
`#413 <https://github.com/aio-libs/frozenlist/issues/413>`_
|
300 |
+
|
301 |
+
|
302 |
+
Misc
|
303 |
+
----
|
304 |
+
|
305 |
+
- `#410 <https://github.com/aio-libs/frozenlist/issues/410>`_, `#433 <https://github.com/aio-libs/frozenlist/issues/433>`_
|
306 |
+
|
307 |
+
|
308 |
+
----
|
309 |
+
|
310 |
+
|
311 |
+
1.3.3 (2022-11-08)
|
312 |
+
==================
|
313 |
+
|
314 |
+
- Fixed CI runs when creating a new release, where new towncrier versions
|
315 |
+
fail when the current version section is already present.
|
316 |
+
|
317 |
+
|
318 |
+
----
|
319 |
+
|
320 |
+
|
321 |
+
1.3.2 (2022-11-08)
|
322 |
+
==================
|
323 |
+
|
324 |
+
Misc
|
325 |
+
----
|
326 |
+
|
327 |
+
- Updated the CI runs to better check for test results and to avoid deprecated syntax. `#327 <https://github.com/aio-libs/frozenlist/issues/327>`_
|
328 |
+
|
329 |
+
|
330 |
+
----
|
331 |
+
|
332 |
+
|
333 |
+
1.3.1 (2022-08-02)
|
334 |
+
==================
|
335 |
+
|
336 |
+
The published source distribution package became buildable
|
337 |
+
under Python 3.11.
|
338 |
+
|
339 |
+
|
340 |
+
----
|
341 |
+
|
342 |
+
|
343 |
+
1.3.0 (2022-01-18)
|
344 |
+
==================
|
345 |
+
|
346 |
+
Bugfixes
|
347 |
+
--------
|
348 |
+
|
349 |
+
- Do not install C sources with binary distributions.
|
350 |
+
`#250 <https://github.com/aio-libs/frozenlist/issues/250>`_
|
351 |
+
|
352 |
+
|
353 |
+
Deprecations and Removals
|
354 |
+
-------------------------
|
355 |
+
|
356 |
+
- Dropped Python 3.6 support
|
357 |
+
`#274 <https://github.com/aio-libs/frozenlist/issues/274>`_
|
358 |
+
|
359 |
+
|
360 |
+
----
|
361 |
+
|
362 |
+
|
363 |
+
1.2.0 (2021-10-16)
|
364 |
+
==================
|
365 |
+
|
366 |
+
Features
|
367 |
+
--------
|
368 |
+
|
369 |
+
- ``FrozenList`` now supports being used as a generic type as per PEP 585, e.g. ``frozen_int_list: FrozenList[int]`` (requires Python 3.9 or newer).
|
370 |
+
`#172 <https://github.com/aio-libs/frozenlist/issues/172>`_
|
371 |
+
- Added support for Python 3.10.
|
372 |
+
`#227 <https://github.com/aio-libs/frozenlist/issues/227>`_
|
373 |
+
- Started shipping platform-specific wheels with the ``musl`` tag targeting typical Alpine Linux runtimes.
|
374 |
+
`#227 <https://github.com/aio-libs/frozenlist/issues/227>`_
|
375 |
+
- Started shipping platform-specific arm64 wheels for Apple Silicon.
|
376 |
+
`#227 <https://github.com/aio-libs/frozenlist/issues/227>`_
|
377 |
+
|
378 |
+
|
379 |
+
----
|
380 |
+
|
381 |
+
|
382 |
+
1.1.1 (2020-11-14)
|
383 |
+
==================
|
384 |
+
|
385 |
+
Bugfixes
|
386 |
+
--------
|
387 |
+
|
388 |
+
- Provide x86 Windows wheels.
|
389 |
+
`#169 <https://github.com/aio-libs/frozenlist/issues/169>`_
|
390 |
+
|
391 |
+
|
392 |
+
----
|
393 |
+
|
394 |
+
|
395 |
+
1.1.0 (2020-10-13)
|
396 |
+
==================
|
397 |
+
|
398 |
+
Features
|
399 |
+
--------
|
400 |
+
|
401 |
+
- Add support for hashing of a frozen list.
|
402 |
+
`#136 <https://github.com/aio-libs/frozenlist/issues/136>`_
|
403 |
+
|
404 |
+
- Support Python 3.8 and 3.9.
|
405 |
+
|
406 |
+
- Provide wheels for ``aarch64``, ``i686``, ``ppc64le``, ``s390x`` architectures on
|
407 |
+
Linux as well as ``x86_64``.
|
408 |
+
|
409 |
+
|
410 |
+
----
|
411 |
+
|
412 |
+
|
413 |
+
1.0.0 (2019-11-09)
|
414 |
+
==================
|
415 |
+
|
416 |
+
Deprecations and Removals
|
417 |
+
-------------------------
|
418 |
+
|
419 |
+
- Dropped support for Python 3.5; only 3.6, 3.7 and 3.8 are supported going forward.
|
420 |
+
`#24 <https://github.com/aio-libs/frozenlist/issues/24>`_
|
venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/RECORD
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
frozenlist-1.4.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
frozenlist-1.4.1.dist-info/LICENSE,sha256=b9UkPpLdf5jsacesN3co50kFcJ_1J6W_mNbQJjwE9bY,11332
|
3 |
+
frozenlist-1.4.1.dist-info/METADATA,sha256=i-BTxwxpJrHm-I8DMpFRvXVXJiqXwUcsPiUR47NY6eg,12136
|
4 |
+
frozenlist-1.4.1.dist-info/RECORD,,
|
5 |
+
frozenlist-1.4.1.dist-info/WHEEL,sha256=vV-3gZY0A60KvZ7BiFVUnyR1ohNO_OSjBIJIoRfk_rE,225
|
6 |
+
frozenlist-1.4.1.dist-info/top_level.txt,sha256=jivtxsPXA3nK3WBWW2LW5Mtu_GHt8UZA13NeCs2cKuA,11
|
7 |
+
frozenlist/__init__.py,sha256=hrSQhfujMaz1BWlHfwuVFrPD02-pCK7jG4e9FaCZCmM,2316
|
8 |
+
frozenlist/__init__.pyi,sha256=vMEoES1xGegPtVXoCi9XydEeHsyuIq-KdeXwP5PdsaA,1470
|
9 |
+
frozenlist/__pycache__/__init__.cpython-310.pyc,,
|
10 |
+
frozenlist/_frozenlist.cpython-310-x86_64-linux-gnu.so,sha256=NlvcEP-slIw1H6qbBejxVzEOxKG33BnttUAdSoP1wA4,766040
|
11 |
+
frozenlist/_frozenlist.pyx,sha256=9V4Z1En6TZwgFD26d-sjxyhUzUm338H1Qiz4-i5ukv0,2983
|
12 |
+
frozenlist/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
|
venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/WHEEL
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.42.0)
|
3 |
+
Root-Is-Purelib: false
|
4 |
+
Tag: cp310-cp310-manylinux_2_5_x86_64
|
5 |
+
Tag: cp310-cp310-manylinux1_x86_64
|
6 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
7 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
8 |
+
|
venv/lib/python3.10/site-packages/frozenlist-1.4.1.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
frozenlist
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/LICENSE.md
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2020 EleutherAI
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/METADATA
ADDED
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: lm_eval
|
3 |
+
Version: 0.4.2
|
4 |
+
Summary: A framework for evaluating language models
|
5 |
+
Author-email: EleutherAI <[email protected]>
|
6 |
+
License: MIT
|
7 |
+
Project-URL: Homepage, https://github.com/EleutherAI/lm-evaluation-harness
|
8 |
+
Project-URL: Repository, https://github.com/EleutherAI/lm-evaluation-harness
|
9 |
+
Classifier: Development Status :: 3 - Alpha
|
10 |
+
Classifier: Programming Language :: Python :: 3
|
11 |
+
Classifier: License :: OSI Approved :: MIT License
|
12 |
+
Classifier: Operating System :: OS Independent
|
13 |
+
Requires-Python: >=3.8
|
14 |
+
Description-Content-Type: text/markdown
|
15 |
+
License-File: LICENSE.md
|
16 |
+
Requires-Dist: accelerate >=0.21.0
|
17 |
+
Requires-Dist: evaluate
|
18 |
+
Requires-Dist: datasets >=2.16.0
|
19 |
+
Requires-Dist: evaluate >=0.4.0
|
20 |
+
Requires-Dist: jsonlines
|
21 |
+
Requires-Dist: numexpr
|
22 |
+
Requires-Dist: peft >=0.2.0
|
23 |
+
Requires-Dist: pybind11 >=2.6.2
|
24 |
+
Requires-Dist: pytablewriter
|
25 |
+
Requires-Dist: rouge-score >=0.0.4
|
26 |
+
Requires-Dist: sacrebleu >=1.5.0
|
27 |
+
Requires-Dist: scikit-learn >=0.24.1
|
28 |
+
Requires-Dist: sqlitedict
|
29 |
+
Requires-Dist: torch >=1.8
|
30 |
+
Requires-Dist: tqdm-multiprocess
|
31 |
+
Requires-Dist: transformers >=4.1
|
32 |
+
Requires-Dist: zstandard
|
33 |
+
Requires-Dist: dill
|
34 |
+
Requires-Dist: word2number
|
35 |
+
Requires-Dist: more-itertools
|
36 |
+
Provides-Extra: all
|
37 |
+
Requires-Dist: lm-eval[anthropic] ; extra == 'all'
|
38 |
+
Requires-Dist: lm-eval[dev] ; extra == 'all'
|
39 |
+
Requires-Dist: lm-eval[deepsparse] ; extra == 'all'
|
40 |
+
Requires-Dist: lm-eval[gptq] ; extra == 'all'
|
41 |
+
Requires-Dist: lm-eval[hf_transfer] ; extra == 'all'
|
42 |
+
Requires-Dist: lm-eval[ifeval] ; extra == 'all'
|
43 |
+
Requires-Dist: lm-eval[mamba] ; extra == 'all'
|
44 |
+
Requires-Dist: lm-eval[math] ; extra == 'all'
|
45 |
+
Requires-Dist: lm-eval[multilingual] ; extra == 'all'
|
46 |
+
Requires-Dist: lm-eval[openai] ; extra == 'all'
|
47 |
+
Requires-Dist: lm-eval[promptsource] ; extra == 'all'
|
48 |
+
Requires-Dist: lm-eval[sentencepiece] ; extra == 'all'
|
49 |
+
Requires-Dist: lm-eval[sparseml] ; extra == 'all'
|
50 |
+
Requires-Dist: lm-eval[testing] ; extra == 'all'
|
51 |
+
Requires-Dist: lm-eval[vllm] ; extra == 'all'
|
52 |
+
Requires-Dist: lm-eval[zeno] ; extra == 'all'
|
53 |
+
Requires-Dist: lm-eval[wandb] ; extra == 'all'
|
54 |
+
Provides-Extra: anthropic
|
55 |
+
Requires-Dist: anthropic ; extra == 'anthropic'
|
56 |
+
Provides-Extra: deepsparse
|
57 |
+
Requires-Dist: deepsparse-nightly[llm] >=1.8.0.20240404 ; extra == 'deepsparse'
|
58 |
+
Provides-Extra: dev
|
59 |
+
Requires-Dist: pytest ; extra == 'dev'
|
60 |
+
Requires-Dist: pytest-cov ; extra == 'dev'
|
61 |
+
Requires-Dist: pytest-xdist ; extra == 'dev'
|
62 |
+
Requires-Dist: pre-commit ; extra == 'dev'
|
63 |
+
Requires-Dist: mypy ; extra == 'dev'
|
64 |
+
Provides-Extra: gptq
|
65 |
+
Requires-Dist: auto-gptq[triton] >=0.6.0 ; extra == 'gptq'
|
66 |
+
Provides-Extra: hf_transfer
|
67 |
+
Requires-Dist: hf-transfer ; extra == 'hf_transfer'
|
68 |
+
Provides-Extra: ifeval
|
69 |
+
Requires-Dist: langdetect ; extra == 'ifeval'
|
70 |
+
Requires-Dist: immutabledict ; extra == 'ifeval'
|
71 |
+
Provides-Extra: mamba
|
72 |
+
Requires-Dist: mamba-ssm ; extra == 'mamba'
|
73 |
+
Requires-Dist: causal-conv1d ==1.0.2 ; extra == 'mamba'
|
74 |
+
Provides-Extra: math
|
75 |
+
Requires-Dist: sympy >=1.12 ; extra == 'math'
|
76 |
+
Requires-Dist: antlr4-python3-runtime ==4.11 ; extra == 'math'
|
77 |
+
Provides-Extra: multilingual
|
78 |
+
Requires-Dist: nagisa >=0.2.7 ; extra == 'multilingual'
|
79 |
+
Requires-Dist: jieba >=0.42.1 ; extra == 'multilingual'
|
80 |
+
Requires-Dist: pycountry ; extra == 'multilingual'
|
81 |
+
Provides-Extra: neuronx
|
82 |
+
Requires-Dist: optimum[neuronx] ; extra == 'neuronx'
|
83 |
+
Provides-Extra: openai
|
84 |
+
Requires-Dist: openai ==1.3.9 ; extra == 'openai'
|
85 |
+
Requires-Dist: tiktoken ; extra == 'openai'
|
86 |
+
Provides-Extra: optimum
|
87 |
+
Requires-Dist: optimum[openvino] ; extra == 'optimum'
|
88 |
+
Provides-Extra: promptsource
|
89 |
+
Requires-Dist: promptsource >=0.2.3 ; extra == 'promptsource'
|
90 |
+
Provides-Extra: sentencepiece
|
91 |
+
Requires-Dist: sentencepiece >=0.1.98 ; extra == 'sentencepiece'
|
92 |
+
Provides-Extra: sparseml
|
93 |
+
Requires-Dist: sparseml-nightly[llm] >=1.8.0.20240404 ; extra == 'sparseml'
|
94 |
+
Provides-Extra: testing
|
95 |
+
Requires-Dist: pytest ; extra == 'testing'
|
96 |
+
Requires-Dist: pytest-cov ; extra == 'testing'
|
97 |
+
Requires-Dist: pytest-xdist ; extra == 'testing'
|
98 |
+
Provides-Extra: vllm
|
99 |
+
Requires-Dist: vllm ==0.3.2 ; extra == 'vllm'
|
100 |
+
Provides-Extra: wandb
|
101 |
+
Requires-Dist: wandb >=0.16.3 ; extra == 'wandb'
|
102 |
+
Requires-Dist: pandas ; extra == 'wandb'
|
103 |
+
Requires-Dist: numpy ; extra == 'wandb'
|
104 |
+
Provides-Extra: zeno
|
105 |
+
Requires-Dist: pandas ; extra == 'zeno'
|
106 |
+
Requires-Dist: zeno-client ; extra == 'zeno'
|
107 |
+
|
108 |
+
# Language Model Evaluation Harness
|
109 |
+
|
110 |
+
[](https://doi.org/10.5281/zenodo.10256836)
|
111 |
+
|
112 |
+
## Announcement
|
113 |
+
**A new v0.4.0 release of lm-evaluation-harness is available** !
|
114 |
+
|
115 |
+
New updates and features include:
|
116 |
+
|
117 |
+
- Internal refactoring
|
118 |
+
- Config-based task creation and configuration
|
119 |
+
- Easier import and sharing of externally-defined task config YAMLs
|
120 |
+
- Support for Jinja2 prompt design, easy modification of prompts + prompt imports from Promptsource
|
121 |
+
- More advanced configuration options, including output post-processing, answer extraction, and multiple LM generations per document, configurable fewshot settings, and more
|
122 |
+
- Speedups and new modeling libraries supported, including: faster data-parallel HF model usage, vLLM support, MPS support with HuggingFace, and more
|
123 |
+
- Logging and usability changes
|
124 |
+
- New tasks including CoT BIG-Bench-Hard, Belebele, user-defined task groupings, and more
|
125 |
+
|
126 |
+
Please see our updated documentation pages in `docs/` for more details.
|
127 |
+
|
128 |
+
Development will be continuing on the `main` branch, and we encourage you to give us feedback on what features are desired and how to improve the library further, or ask questions, either in issues or PRs on GitHub, or in the [EleutherAI discord](https://discord.gg/eleutherai)!
|
129 |
+
|
130 |
+
## Overview
|
131 |
+
|
132 |
+
This project provides a unified framework to test generative language models on a large number of different evaluation tasks.
|
133 |
+
|
134 |
+
**Features:**
|
135 |
+
- Over 60 standard academic benchmarks for LLMs, with hundreds of subtasks and variants implemented.
|
136 |
+
- Support for models loaded via [transformers](https://github.com/huggingface/transformers/) (including quantization via [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)), [GPT-NeoX](https://github.com/EleutherAI/gpt-neox), and [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/), with a flexible tokenization-agnostic interface.
|
137 |
+
- Support for fast and memory-efficient inference with [vLLM](https://github.com/vllm-project/vllm).
|
138 |
+
- Support for commercial APIs including [OpenAI](https://openai.com), and [TextSynth](https://textsynth.com/).
|
139 |
+
- Support for evaluation on adapters (e.g. LoRA) supported in [HuggingFace's PEFT library](https://github.com/huggingface/peft).
|
140 |
+
- Support for local models and benchmarks.
|
141 |
+
- Evaluation with publicly available prompts ensures reproducibility and comparability between papers.
|
142 |
+
- Easy support for custom prompts and evaluation metrics.
|
143 |
+
|
144 |
+
The Language Model Evaluation Harness is the backend for 🤗 Hugging Face's popular [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), has been used in [hundreds of papers](https://scholar.google.com/scholar?oi=bibs&hl=en&authuser=2&cites=15052937328817631261,4097184744846514103,1520777361382155671,17476825572045927382,18443729326628441434,14801318227356878622,7890865700763267262,12854182577605049984,15641002901115500560,5104500764547628290), and is used internally by dozens of organizations including NVIDIA, Cohere, BigScience, BigCode, Nous Research, and Mosaic ML.
|
145 |
+
|
146 |
+
## Install
|
147 |
+
|
148 |
+
To install the `lm-eval` package from the github repository, run:
|
149 |
+
|
150 |
+
```bash
|
151 |
+
git clone https://github.com/EleutherAI/lm-evaluation-harness
|
152 |
+
cd lm-evaluation-harness
|
153 |
+
pip install -e .
|
154 |
+
```
|
155 |
+
|
156 |
+
We also provide a number of optional dependencies for extended functionality. A detailed table is available at the end of this document.
|
157 |
+
|
158 |
+
## Basic Usage
|
159 |
+
|
160 |
+
### Hugging Face `transformers`
|
161 |
+
|
162 |
+
To evaluate a model hosted on the [HuggingFace Hub](https://huggingface.co/models) (e.g. GPT-J-6B) on `hellaswag` you can use the following command (this assumes you are using a CUDA-compatible GPU):
|
163 |
+
|
164 |
+
```bash
|
165 |
+
lm_eval --model hf \
|
166 |
+
--model_args pretrained=EleutherAI/gpt-j-6B \
|
167 |
+
--tasks hellaswag \
|
168 |
+
--device cuda:0 \
|
169 |
+
--batch_size 8
|
170 |
+
```
|
171 |
+
|
172 |
+
Additional arguments can be provided to the model constructor using the `--model_args` flag. Most notably, this supports the common practice of using the `revisions` feature on the Hub to store partially trained checkpoints, or to specify the datatype for running a model:
|
173 |
+
|
174 |
+
```bash
|
175 |
+
lm_eval --model hf \
|
176 |
+
--model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \
|
177 |
+
--tasks lambada_openai,hellaswag \
|
178 |
+
--device cuda:0 \
|
179 |
+
--batch_size 8
|
180 |
+
```
|
181 |
+
|
182 |
+
Models that are loaded via both `transformers.AutoModelForCausalLM` (autoregressive, decoder-only GPT style models) and `transformers.AutoModelForSeq2SeqLM` (such as encoder-decoder models like T5) in Huggingface are supported.
|
183 |
+
|
184 |
+
Batch size selection can be automated by setting the ```--batch_size``` flag to ```auto```. This will perform automatic detection of the largest batch size that will fit on your device. On tasks where there is a large difference between the longest and shortest example, it can be helpful to periodically recompute the largest batch size, to gain a further speedup. To do this, append ```:N``` to above flag to automatically recompute the largest batch size ```N``` times. For example, to recompute the batch size 4 times, the command would be:
|
185 |
+
|
186 |
+
```bash
|
187 |
+
lm_eval --model hf \
|
188 |
+
--model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \
|
189 |
+
--tasks lambada_openai,hellaswag \
|
190 |
+
--device cuda:0 \
|
191 |
+
--batch_size auto:4
|
192 |
+
```
|
193 |
+
|
194 |
+
The full list of supported arguments are provided [here](./docs/interface.md), and on the terminal by calling `lm_eval -h`. Alternatively, you can use `lm-eval` instead of `lm_eval`. A list of supported tasks can be viewed with `lm-eval --tasks list`.
|
195 |
+
|
196 |
+
> [!Note]
|
197 |
+
> Just like you can provide a local path to `transformers.AutoModel`, you can also provide a local path to `lm_eval` via `--model_args pretrained=/path/to/model`
|
198 |
+
|
199 |
+
#### Multi-GPU Evaluation with Hugging Face `accelerate`
|
200 |
+
|
201 |
+
We support two main ways of using Hugging Face's [accelerate 🚀](https://github.com/huggingface/accelerate) library for multi-GPU evaluation.
|
202 |
+
|
203 |
+
To perform *data-parallel evaluation* (where each GPU loads a **separate full copy** of the model), we leverage the `accelerate` launcher as follows:
|
204 |
+
|
205 |
+
```
|
206 |
+
accelerate launch -m lm_eval --model hf \
|
207 |
+
--tasks lambada_openai,arc_easy \
|
208 |
+
--batch_size 16
|
209 |
+
```
|
210 |
+
(or via `accelerate launch --no-python lm_eval`).
|
211 |
+
|
212 |
+
For cases where your model can fit on a single GPU, this allows you to evaluate on K GPUs K times faster than on one.
|
213 |
+
|
214 |
+
**WARNING**: This setup does not work with FSDP model sharding, so in `accelerate config` FSDP must be disabled, or the NO_SHARD FSDP option must be used.
|
215 |
+
|
216 |
+
The second way of using `accelerate` for multi-GPU evaluation is when your model is *too large to fit on a single GPU.*
|
217 |
+
|
218 |
+
In this setting, run the library *outside of the `accelerate` launcher*, but passing `parallelize=True` to `--model_args` as follows:
|
219 |
+
|
220 |
+
```
|
221 |
+
lm_eval --model hf \
|
222 |
+
--tasks lambada_openai,arc_easy \
|
223 |
+
--model_args parallelize=True \
|
224 |
+
--batch_size 16
|
225 |
+
```
|
226 |
+
|
227 |
+
This means that your model's weights will be split across all available GPUs.
|
228 |
+
|
229 |
+
For more advanced users or even larger models, we allow for the following arguments when `parallelize=True` as well:
|
230 |
+
- `device_map_option`: How to split model weights across available GPUs. defaults to "auto".
|
231 |
+
- `max_memory_per_gpu`: the max GPU memory to use per GPU in loading the model.
|
232 |
+
- `max_cpu_memory`: the max amount of CPU memory to use when offloading the model weights to RAM.
|
233 |
+
- `offload_folder`: a folder where model weights will be offloaded to disk if needed.
|
234 |
+
|
235 |
+
These two options (`accelerate launch` and `parallelize=True`) are mutually exclusive.
|
236 |
+
|
237 |
+
**Note: we do not currently support multi-node evaluations natively, and advise using either an externally hosted server to run inference requests against, or creating a custom integration with your distributed framework [as is done for the GPT-NeoX library](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py).**
|
238 |
+
|
239 |
+
### NVIDIA `nemo` models
|
240 |
+
|
241 |
+
[NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo) is a generative AI framework built for researchers and pytorch developers working on language models.
|
242 |
+
|
243 |
+
To evaluate a `nemo` model, start by installing NeMo following [the documentation](https://github.com/NVIDIA/NeMo?tab=readme-ov-file#installation). We highly recommended to use the NVIDIA PyTorch or NeMo container, especially if having issues installing Apex or any other dependencies (see [latest released containers](https://github.com/NVIDIA/NeMo/releases)). Please also install the lm evaluation harness library following the instructions in [the Install section](https://github.com/EleutherAI/lm-evaluation-harness/tree/main?tab=readme-ov-file#install).
|
244 |
+
|
245 |
+
NeMo models can be obtained through [NVIDIA NGC Catalog](https://catalog.ngc.nvidia.com/models) or in [NVIDIA's Hugging Face page](https://huggingface.co/nvidia). In [NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo/tree/main/scripts/nlp_language_modeling) there are conversion scripts to convert the `hf` checkpoints of popular models like llama, falcon, mixtral or mpt to `nemo`.
|
246 |
+
|
247 |
+
Run a `nemo` model on one GPU:
|
248 |
+
```bash
|
249 |
+
lm_eval --model nemo_lm \
|
250 |
+
--model_args path=<path_to_nemo_model> \
|
251 |
+
--tasks hellaswag \
|
252 |
+
--batch_size 32
|
253 |
+
```
|
254 |
+
|
255 |
+
It is recommended to unpack the `nemo` model to avoid the unpacking inside the docker container - it may overflow disk space. For that you can run:
|
256 |
+
|
257 |
+
```
|
258 |
+
mkdir MY_MODEL
|
259 |
+
tar -xvf MY_MODEL.nemo -c MY_MODEL
|
260 |
+
```
|
261 |
+
|
262 |
+
#### Multi-GPU evaluation with NVIDIA `nemo` models
|
263 |
+
|
264 |
+
By default, only one GPU is used. But we do support either data replication or tensor/pipeline parallelism during evaluation, on one node.
|
265 |
+
|
266 |
+
1) To enable data replication, set the `model_args` of `devices` to the number of data replicas to run. For example, the command to run 8 data replicas over 8 GPUs is:
|
267 |
+
```bash
|
268 |
+
torchrun --nproc-per-node=8 --no-python lm_eval \
|
269 |
+
--model nemo_lm \
|
270 |
+
--model_args path=<path_to_nemo_model>,devices=8 \
|
271 |
+
--tasks hellaswag \
|
272 |
+
--batch_size 32
|
273 |
+
```
|
274 |
+
|
275 |
+
2) To enable tensor and/or pipeline parallelism, set the `model_args` of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. In addition, you also have to set up `devices` to be equal to the product of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. For example, the command to use one node of 4 GPUs with tensor parallelism of 2 and pipeline parallelism of 2 is:
|
276 |
+
```bash
|
277 |
+
torchrun --nproc-per-node=4 --no-python lm_eval \
|
278 |
+
--model nemo_lm \
|
279 |
+
--model_args path=<path_to_nemo_model>,devices=4,tensor_model_parallel_size=2,pipeline_model_parallel_size=2 \
|
280 |
+
--tasks hellaswag \
|
281 |
+
--batch_size 32
|
282 |
+
```
|
283 |
+
Note that it is recommended to substitute the `python` command by `torchrun --nproc-per-node=<number of devices> --no-python` to facilitate loading the model into the GPUs. This is especially important for large checkpoints loaded into multiple GPUs.
|
284 |
+
|
285 |
+
Not supported yet: multi-node evaluation and combinations of data replication with tensor or pipeline parallelism.
|
286 |
+
|
287 |
+
### Tensor + Data Parallel and Optimized Inference with `vLLM`
|
288 |
+
|
289 |
+
We also support vLLM for faster inference on [supported model types](https://docs.vllm.ai/en/latest/models/supported_models.html), especially faster when splitting a model across multiple GPUs. For single-GPU or multi-GPU — tensor parallel, data parallel, or a combination of both — inference, for example:
|
290 |
+
|
291 |
+
```bash
|
292 |
+
lm_eval --model vllm \
|
293 |
+
--model_args pretrained={model_name},tensor_parallel_size={GPUs_per_model},dtype=auto,gpu_memory_utilization=0.8,data_parallel_size={model_replicas} \
|
294 |
+
--tasks lambada_openai \
|
295 |
+
--batch_size auto
|
296 |
+
```
|
297 |
+
To use vllm, do `pip install lm_eval[vllm]`. For a full list of supported vLLM configurations, please reference our [vLLM integration](https://github.com/EleutherAI/lm-evaluation-harness/blob/e74ec966556253fbe3d8ecba9de675c77c075bce/lm_eval/models/vllm_causallms.py) and the vLLM documentation.
|
298 |
+
|
299 |
+
vLLM occasionally differs in output from Huggingface. We treat Huggingface as the reference implementation, and provide a [script](./scripts/model_comparator.py) for checking the validity of vllm results against HF.
|
300 |
+
|
301 |
+
> [!Tip]
|
302 |
+
> For fastest performance, we recommend using `--batch_size auto` for vLLM whenever possible, to leverage its continuous batching functionality!
|
303 |
+
|
304 |
+
> [!Tip]
|
305 |
+
> Passing `max_model_len=4096` or some other reasonable default to vLLM through model args may cause speedups or prevent out-of-memory errors when trying to use auto batch size, such as for Mistral-7B-v0.1 which defaults to a maximum length of 32k.
|
306 |
+
|
307 |
+
### Model APIs and Inference Servers
|
308 |
+
|
309 |
+
Our library also supports the evaluation of models served via several commercial APIs, and we hope to implement support for the most commonly used performant local/self-hosted inference servers.
|
310 |
+
|
311 |
+
To call a hosted model, use:
|
312 |
+
|
313 |
+
```bash
|
314 |
+
export OPENAI_API_KEY=YOUR_KEY_HERE
|
315 |
+
lm_eval --model openai-completions \
|
316 |
+
--model_args model=davinci \
|
317 |
+
--tasks lambada_openai,hellaswag
|
318 |
+
```
|
319 |
+
|
320 |
+
We also support using your own local inference server with servers that mirror the OpenAI Completions and ChatCompletions APIs.
|
321 |
+
|
322 |
+
```bash
|
323 |
+
lm_eval --model local-chat-completions --tasks gsm8k --model_args model=facebook/opt-125m,base_url=http://{yourip}:8000/v1
|
324 |
+
```
|
325 |
+
Note that for externally hosted models, configs such as `--device` and `--batch_size` should not be used and do not function. Just like you can use `--model_args` to pass arbitrary arguments to the model constructor for local models, you can use it to pass arbitrary arguments to the model API for hosted models. See the documentation of the hosting service for information on what arguments they support.
|
326 |
+
|
327 |
+
| API or Inference Server | Implemented? | `--model <xxx>` name | Models supported: | Request Types: |
|
328 |
+
|---------------------------------------------------------------------------------------------------------------------------|---------------------------------|---------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|------------------------------------------------------------|
|
329 |
+
| OpenAI Completions | :heavy_check_mark: | `openai-completions`, `local-completions` | All OpenAI Completions API models | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
|
330 |
+
| OpenAI ChatCompletions | :heavy_check_mark: | `openai-chat-completions`, `local-chat-completions` | [All ChatCompletions API models](https://platform.openai.com/docs/guides/gpt) | `generate_until` (no logprobs) |
|
331 |
+
| Anthropic | :heavy_check_mark: | `anthropic` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/reference/selecting-a-model) | `generate_until` (no logprobs) |
|
332 |
+
| Anthropic Chat | :heavy_check_mark: | `anthropic-chat`, `anthropic-chat-completions` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/docs/models-overview) | `generate_until` (no logprobs) |
|
333 |
+
| Textsynth | :heavy_check_mark: | `textsynth` | [All supported engines](https://textsynth.com/documentation.html#engines) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
|
334 |
+
| Cohere | [:hourglass: - blocked on Cohere API bug](https://github.com/EleutherAI/lm-evaluation-harness/pull/395) | N/A | [All `cohere.generate()` engines](https://docs.cohere.com/docs/models) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
|
335 |
+
| [Llama.cpp](https://github.com/ggerganov/llama.cpp) (via [llama-cpp-python](https://github.com/abetlen/llama-cpp-python)) | :heavy_check_mark: | `gguf`, `ggml` | [All models supported by llama.cpp](https://github.com/ggerganov/llama.cpp) | `generate_until`, `loglikelihood`, (perplexity evaluation not yet implemented) |
|
336 |
+
| vLLM | :heavy_check_mark: | `vllm` | [Most HF Causal Language Models](https://docs.vllm.ai/en/latest/models/supported_models.html) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
|
337 |
+
| Mamba | :heavy_check_mark: | `mamba_ssm` | [Mamba architecture Language Models via the `mamba_ssm` package](https://huggingface.co/state-spaces) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
|
338 |
+
| Huggingface Optimum (Causal LMs) | ✔️ | `openvino` | Any decoder-only AutoModelForCausalLM converted with Huggingface Optimum into OpenVINO™ Intermediate Representation (IR) format | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... |
|
339 |
+
| Neuron via AWS Inf2 (Causal LMs) | ✔️ | `neuronx` | Any decoder-only AutoModelForCausalLM supported to run on [huggingface-ami image for inferentia2](https://aws.amazon.com/marketplace/pp/prodview-gr3e6yiscria2) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... |
|
340 |
+
| [Neural Magic DeepSparse](https://github.com/neuralmagic/deepsparse) | ✔️ | `deepsparse` | Any LM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub with the "deepsparse" tag](https://huggingface.co/models?other=deepsparse) | `generate_until`, `loglikelihood` | ... |
|
341 |
+
| [Neural Magic SparseML](https://github.com/neuralmagic/sparseml) | ✔️ | `sparseml` | Any decoder-only AutoModelForCausalLM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub](https://huggingface.co/neuralmagic). Especially useful for models with quantization like [`zoo:llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized`](https://sparsezoo.neuralmagic.com/models/llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` | ... |
|
342 |
+
| Your local inference server! | :heavy_check_mark: | `local-completions` or `local-chat-completions` (using `openai-chat-completions` model type) | Any server address that accepts GET requests using HF models and mirror's OpenAI's Completions or ChatCompletions interface | `generate_until` | | ... |
|
343 |
+
|
344 |
+
Models which do not supply logits or logprobs can be used with tasks of type `generate_until` only, while local models, or APIs that supply logprobs/logits of their prompts, can be run on all task types: `generate_until`, `loglikelihood`, `loglikelihood_rolling`, and `multiple_choice`.
|
345 |
+
|
346 |
+
For more information on the different task `output_types` and model request types, see [our documentation](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/model_guide.md#interface).
|
347 |
+
|
348 |
+
> [!Note]
|
349 |
+
> For best performance with closed chat model APIs such as Anthropic Claude 3 and GPT-4, we recommend carefully looking at a few sample outputs using `--limit 10` first to confirm answer extraction and scoring on generative tasks is performing as expected. providing `system="<some system prompt here>"` within `--model_args` for anthropic-chat-completions, to instruct the model what format to respond in, may be useful.
|
350 |
+
|
351 |
+
|
352 |
+
### Other Frameworks
|
353 |
+
|
354 |
+
A number of other libraries contain scripts for calling the eval harness through their library. These include [GPT-NeoX](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py), [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/blob/main/examples/MoE/readme_evalharness.md), and [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/blob/master/eval_harness.py).
|
355 |
+
|
356 |
+
To create your own custom integration you can follow instructions from [this tutorial](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md#external-library-usage).
|
357 |
+
|
358 |
+
### Additional Features
|
359 |
+
> [!Note]
|
360 |
+
> For tasks unsuitable for direct evaluation — either due risks associated with executing untrusted code or complexities in the evaluation process — the `--predict_only` flag is available to obtain decoded generations for post-hoc evaluation.
|
361 |
+
|
362 |
+
If you have a Metal compatible Mac, you can run the eval harness using the MPS back-end by replacing `--device cuda:0` with `--device mps` (requires PyTorch version 2.1 or higher). **Note that the PyTorch MPS backend is still in early stages of development, so correctness issues or unsupported operations may exist. If you observe oddities in model performance on the MPS back-end, we recommend first checking that a forward pass of your model on `--device cpu` and `--device mps` match.**
|
363 |
+
|
364 |
+
> [!Note]
|
365 |
+
> You can inspect what the LM inputs look like by running the following command:
|
366 |
+
> ```bash
|
367 |
+
> python write_out.py \
|
368 |
+
> --tasks <task1,task2,...> \
|
369 |
+
> --num_fewshot 5 \
|
370 |
+
> --num_examples 10 \
|
371 |
+
> --output_base_path /path/to/output/folder
|
372 |
+
> ```
|
373 |
+
> This will write out one text file for each task.
|
374 |
+
|
375 |
+
To verify the data integrity of the tasks you're performing in addition to running the tasks themselves, you can use the `--check_integrity` flag:
|
376 |
+
|
377 |
+
```bash
|
378 |
+
lm_eval --model openai \
|
379 |
+
--model_args engine=davinci \
|
380 |
+
--tasks lambada_openai,hellaswag \
|
381 |
+
--check_integrity
|
382 |
+
```
|
383 |
+
|
384 |
+
## Advanced Usage Tips
|
385 |
+
|
386 |
+
For models loaded with the HuggingFace `transformers` library, any arguments provided via `--model_args` get passed to the relevant constructor directly. This means that anything you can do with `AutoModel` can be done with our library. For example, you can pass a local path via `pretrained=` or use models finetuned with [PEFT](https://github.com/huggingface/peft) by taking the call you would run to evaluate the base model and add `,peft=PATH` to the `model_args` argument:
|
387 |
+
```bash
|
388 |
+
lm_eval --model hf \
|
389 |
+
--model_args pretrained=EleutherAI/gpt-j-6b,parallelize=True,load_in_4bit=True,peft=nomic-ai/gpt4all-j-lora \
|
390 |
+
--tasks openbookqa,arc_easy,winogrande,hellaswag,arc_challenge,piqa,boolq \
|
391 |
+
--device cuda:0
|
392 |
+
```
|
393 |
+
|
394 |
+
Models provided as delta weights can be easily loaded using the Hugging Face transformers library. Within --model_args, set the delta argument to specify the delta weights, and use the pretrained argument to designate the relative base model to which they will be applied:
|
395 |
+
```bash
|
396 |
+
lm_eval --model hf \
|
397 |
+
--model_args pretrained=Ejafa/llama_7B,delta=lmsys/vicuna-7b-delta-v1.1 \
|
398 |
+
--tasks hellaswag
|
399 |
+
```
|
400 |
+
|
401 |
+
[GPTQ](https://github.com/PanQiWei/AutoGPTQ) quantized models can be loaded by specifying their file names in `,autogptq=NAME` (or `,autogptq=True` for default names) in the `model_args` argument:
|
402 |
+
|
403 |
+
```bash
|
404 |
+
lm_eval --model hf \
|
405 |
+
--model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \
|
406 |
+
--tasks hellaswag
|
407 |
+
```
|
408 |
+
|
409 |
+
We support wildcards in task names, for example you can run all of the machine-translated lambada tasks via `--task lambada_openai_mt_*`.
|
410 |
+
|
411 |
+
To save evaluation results provide an `--output_path`. We also support logging model responses with the `--log_samples` flag for post-hoc analysis.
|
412 |
+
|
413 |
+
Additionally, one can provide a directory with `--use_cache` to cache the results of prior runs. This allows you to avoid repeated execution of the same (model, task) pairs for re-scoring.
|
414 |
+
|
415 |
+
For a full list of supported arguments, check out the [interface](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md) guide in our documentation!
|
416 |
+
|
417 |
+
## Visualizing Results
|
418 |
+
|
419 |
+
You can seamlessly visualize and analyze the results of your evaluation harness runs using both Weights & Biases (W&B) and Zeno.
|
420 |
+
|
421 |
+
### Zeno
|
422 |
+
|
423 |
+
You can use [Zeno](https://zenoml.com) to visualize the results of your eval harness runs.
|
424 |
+
|
425 |
+
First, head to [hub.zenoml.com](https://hub.zenoml.com) to create an account and get an API key [on your account page](https://hub.zenoml.com/account).
|
426 |
+
Add this key as an environment variable:
|
427 |
+
|
428 |
+
```bash
|
429 |
+
export ZENO_API_KEY=[your api key]
|
430 |
+
```
|
431 |
+
|
432 |
+
You'll also need to install the `lm_eval[zeno]` package extra.
|
433 |
+
|
434 |
+
To visualize the results, run the eval harness with the `log_samples` and `output_path` flags.
|
435 |
+
We expect `output_path` to contain multiple folders that represent individual model names.
|
436 |
+
You can thus run your evaluation on any number of tasks and models and upload all of the results as projects on Zeno.
|
437 |
+
|
438 |
+
```bash
|
439 |
+
lm_eval \
|
440 |
+
--model hf \
|
441 |
+
--model_args pretrained=EleutherAI/gpt-j-6B \
|
442 |
+
--tasks hellaswag \
|
443 |
+
--device cuda:0 \
|
444 |
+
--batch_size 8 \
|
445 |
+
--log_samples \
|
446 |
+
--output_path output/gpt-j-6B
|
447 |
+
```
|
448 |
+
|
449 |
+
Then, you can upload the resulting data using the `zeno_visualize` script:
|
450 |
+
|
451 |
+
```bash
|
452 |
+
python scripts/zeno_visualize.py \
|
453 |
+
--data_path output \
|
454 |
+
--project_name "Eleuther Project"
|
455 |
+
```
|
456 |
+
|
457 |
+
This will use all subfolders in `data_path` as different models and upload all tasks within these model folders to Zeno.
|
458 |
+
If you run the eval harness on multiple tasks, the `project_name` will be used as a prefix and one project will be created per task.
|
459 |
+
|
460 |
+
You can find an example of this workflow in [examples/visualize-zeno.ipynb](examples/visualize-zeno.ipynb).
|
461 |
+
|
462 |
+
### Weights and Biases
|
463 |
+
|
464 |
+
With the [Weights and Biases](https://wandb.ai/site) integration, you can now spend more time extracting deeper insights into your evaluation results. The integration is designed to streamline the process of logging and visualizing experiment results using the Weights & Biases (W&B) platform.
|
465 |
+
|
466 |
+
The integration provide functionalities
|
467 |
+
|
468 |
+
- to automatically log the evaluation results,
|
469 |
+
- log the samples as W&B Tables for easy visualization,
|
470 |
+
- log the `results.json` file as an artifact for version control,
|
471 |
+
- log the `<task_name>_eval_samples.json` file if the samples are logged,
|
472 |
+
- generate a comprehensive report for analysis and visualization with all the important metric,
|
473 |
+
- log task and cli specific configs,
|
474 |
+
- and more out of the box like the command used to run the evaluation, GPU/CPU counts, timestamp, etc.
|
475 |
+
|
476 |
+
First you'll need to install the lm_eval[wandb] package extra. Do `pip install lm_eval[wandb]`.
|
477 |
+
|
478 |
+
Authenticate your machine with an your unique W&B token. Visit https://wandb.ai/authorize to get one. Do `wandb login` in your command line terminal.
|
479 |
+
|
480 |
+
Run eval harness as usual with a `wandb_args` flag. Use this flag to provide arguments for initializing a wandb run ([wandb.init](https://docs.wandb.ai/ref/python/init)) as comma separated string arguments.
|
481 |
+
|
482 |
+
```bash
|
483 |
+
lm_eval \
|
484 |
+
--model hf \
|
485 |
+
--model_args pretrained=microsoft/phi-2,trust_remote_code=True \
|
486 |
+
--tasks hellaswag,mmlu_abstract_algebra \
|
487 |
+
--device cuda:0 \
|
488 |
+
--batch_size 8 \
|
489 |
+
--output_path output/phi-2 \
|
490 |
+
--limit 10 \
|
491 |
+
--wandb_args project=lm-eval-harness-integration \
|
492 |
+
--log_samples
|
493 |
+
```
|
494 |
+
|
495 |
+
In the stdout, you will find the link to the W&B run page as well as link to the generated report. You can find an example of this workflow in [examples/visualize-wandb.ipynb](examples/visualize-wandb.ipynb), and an example of how to integrate it beyond the CLI.
|
496 |
+
|
497 |
+
## How to Contribute or Learn More?
|
498 |
+
|
499 |
+
For more information on the library and how everything fits together, check out all of our [documentation pages](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs)! We plan to post a larger roadmap of desired + planned library improvements soon, with more information on how contributors can help.
|
500 |
+
|
501 |
+
### Implementing new tasks
|
502 |
+
|
503 |
+
To implement a new task in the eval harness, see [this guide](./docs/new_task_guide.md).
|
504 |
+
|
505 |
+
In general, we follow this priority list for addressing concerns about prompting and other eval details:
|
506 |
+
1. If there is widespread agreement among people who train LLMs, use the agreed upon procedure.
|
507 |
+
2. If there is a clear and unambiguous official implementation, use that procedure.
|
508 |
+
3. If there is widespread agreement among people who evaluate LLMs, use the agreed upon procedure.
|
509 |
+
4. If there are multiple common implementations but not universal or widespread agreement, use our preferred option among the common implementations. As before, prioritize choosing from among the implementations found in LLM training papers.
|
510 |
+
|
511 |
+
These are guidelines and not rules, and can be overruled in special circumstances.
|
512 |
+
|
513 |
+
We try to prioritize agreement with the procedures used by other groups to decrease the harm when people inevitably compare runs across different papers despite our discouragement of the practice. Historically, we also prioritized the implementation from [Language Models are Few Shot Learners](https://arxiv.org/abs/2005.14165) as our original goal was specifically to compare results with that paper.
|
514 |
+
|
515 |
+
### Support
|
516 |
+
|
517 |
+
The best way to get support is to open an issue on this repo or join the [EleutherAI Discord server](https://discord.gg/eleutherai). The `#lm-thunderdome` channel is dedicated to developing this project and the `#release-discussion` channel is for receiving support for our releases. If you've used the library and have had a positive (or negative) experience, we'd love to hear from you!
|
518 |
+
|
519 |
+
## Optional Extras
|
520 |
+
Extras dependencies can be installed via `pip install -e ".[NAME]"`
|
521 |
+
|
522 |
+
| Name | Use |
|
523 |
+
|---------------|---------------------------------------|
|
524 |
+
| anthropic | For using Anthropic's models |
|
525 |
+
| deepsparse | For running NM's DeepSparse models |
|
526 |
+
| dev | For linting PRs and contributions |
|
527 |
+
| gptq | For loading models with GPTQ |
|
528 |
+
| hf_transfer | For speeding up HF Hub file downloads |
|
529 |
+
| ifeval | For running the IFEval task |
|
530 |
+
| neuronx | For running on AWS inf2 instances |
|
531 |
+
| mamba | For loading Mamba SSM models |
|
532 |
+
| math | For running math task answer checking |
|
533 |
+
| multilingual | For multilingual tokenizers |
|
534 |
+
| openai | For using OpenAI's models |
|
535 |
+
| optimum | For running Intel OpenVINO models |
|
536 |
+
| promptsource | For using PromptSource prompts |
|
537 |
+
| sentencepiece | For using the sentencepiece tokenizer |
|
538 |
+
| sparseml | For using NM's SparseML models |
|
539 |
+
| testing | For running library test suite |
|
540 |
+
| vllm | For loading models with vLLM |
|
541 |
+
| zeno | For visualizing results with Zeno |
|
542 |
+
|---------------|---------------------------------------|
|
543 |
+
| all | Loads all extras (not recommended) |
|
544 |
+
|
545 |
+
## Cite as
|
546 |
+
|
547 |
+
```
|
548 |
+
@misc{eval-harness,
|
549 |
+
author = {Gao, Leo and Tow, Jonathan and Abbasi, Baber and Biderman, Stella and Black, Sid and DiPofi, Anthony and Foster, Charles and Golding, Laurence and Hsu, Jeffrey and Le Noac'h, Alain and Li, Haonan and McDonell, Kyle and Muennighoff, Niklas and Ociepa, Chris and Phang, Jason and Reynolds, Laria and Schoelkopf, Hailey and Skowron, Aviya and Sutawika, Lintang and Tang, Eric and Thite, Anish and Wang, Ben and Wang, Kevin and Zou, Andy},
|
550 |
+
title = {A framework for few-shot language model evaluation},
|
551 |
+
month = 12,
|
552 |
+
year = 2023,
|
553 |
+
publisher = {Zenodo},
|
554 |
+
version = {v0.4.0},
|
555 |
+
doi = {10.5281/zenodo.10256836},
|
556 |
+
url = {https://zenodo.org/records/10256836}
|
557 |
+
}
|
558 |
+
```
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/RECORD
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
../../../bin/lm-eval,sha256=sg8FOSPWPtuzyAIlQfYls6iiB34TAdSNPYhBxqKk3wE,260
|
2 |
+
../../../bin/lm_eval,sha256=sg8FOSPWPtuzyAIlQfYls6iiB34TAdSNPYhBxqKk3wE,260
|
3 |
+
__editable__.lm_eval-0.4.2.pth,sha256=C4fSS19B6d-idgvdOOiL7g2yPVs0ZZ0_9S0BPtrZ1ew,85
|
4 |
+
__editable___lm_eval_0_4_2_finder.py,sha256=p6QUJyTCjRyjzYrqRmNQchPEO6nZQ7aeF_W852hh7y8,18846
|
5 |
+
__pycache__/__editable___lm_eval_0_4_2_finder.cpython-310.pyc,,
|
6 |
+
lm_eval-0.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
7 |
+
lm_eval-0.4.2.dist-info/LICENSE.md,sha256=qAbkJUdiDf-8LsAzMyLIs1I7SvEeBZvhTvgapbGuAh8,1067
|
8 |
+
lm_eval-0.4.2.dist-info/METADATA,sha256=3K8XmbaY59La0a0nzIZbdncEhgrVsb0wHv8XFXFYNm4,37274
|
9 |
+
lm_eval-0.4.2.dist-info/RECORD,,
|
10 |
+
lm_eval-0.4.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
11 |
+
lm_eval-0.4.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
12 |
+
lm_eval-0.4.2.dist-info/direct_url.json,sha256=GwLGB_cV_2rgPWCNM0YUp_eFefNglQlueiT3vyDp90E,100
|
13 |
+
lm_eval-0.4.2.dist-info/entry_points.txt,sha256=mMr4hFXQwSHYb924AKGzP6dbbBAWcXiyBO-AfXrV72E,98
|
14 |
+
lm_eval-0.4.2.dist-info/top_level.txt,sha256=risQwf3pU3EoXaYL_bKYFzW6EtBOvJxJotKdDz605Dk,8
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/REQUESTED
ADDED
File without changes
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.43.0)
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
5 |
+
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/direct_url.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"dir_info": {"editable": true}, "url": "file:///mnt/weka/peacock/cronscript/lm-evaluation-harness"}
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/entry_points.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[console_scripts]
|
2 |
+
lm-eval = lm_eval.__main__:cli_evaluate
|
3 |
+
lm_eval = lm_eval.__main__:cli_evaluate
|
venv/lib/python3.10/site-packages/lm_eval-0.4.2.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
lm_eval
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/LICENSE.txt
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2004 Infrae. All rights reserved.
|
2 |
+
|
3 |
+
Redistribution and use in source and binary forms, with or without
|
4 |
+
modification, are permitted provided that the following conditions are
|
5 |
+
met:
|
6 |
+
|
7 |
+
1. Redistributions of source code must retain the above copyright
|
8 |
+
notice, this list of conditions and the following disclaimer.
|
9 |
+
|
10 |
+
2. Redistributions in binary form must reproduce the above copyright
|
11 |
+
notice, this list of conditions and the following disclaimer in
|
12 |
+
the documentation and/or other materials provided with the
|
13 |
+
distribution.
|
14 |
+
|
15 |
+
3. Neither the name of Infrae nor the names of its contributors may
|
16 |
+
be used to endorse or promote products derived from this software
|
17 |
+
without specific prior written permission.
|
18 |
+
|
19 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
20 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
21 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
22 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INFRAE OR
|
23 |
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
24 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
25 |
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
26 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
27 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
28 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
29 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/LICENSES.txt
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
lxml is copyright Infrae and distributed under the BSD license (see
|
2 |
+
doc/licenses/BSD.txt), with the following exceptions:
|
3 |
+
|
4 |
+
Some code, such a selftest.py, selftest2.py and
|
5 |
+
src/lxml/_elementpath.py are derived from ElementTree and
|
6 |
+
cElementTree. See doc/licenses/elementtree.txt for the license text.
|
7 |
+
|
8 |
+
lxml.cssselect and lxml.html are copyright Ian Bicking and distributed
|
9 |
+
under the BSD license (see doc/licenses/BSD.txt).
|
10 |
+
|
11 |
+
test.py, the test-runner script, is GPL and copyright Shuttleworth
|
12 |
+
Foundation. See doc/licenses/GPL.txt. It is believed the unchanged
|
13 |
+
inclusion of test.py to run the unit test suite falls under the
|
14 |
+
"aggregation" clause of the GPL and thus does not affect the license
|
15 |
+
of the rest of the package.
|
16 |
+
|
17 |
+
The isoschematron implementation uses several XSL and RelaxNG resources:
|
18 |
+
* The (XML syntax) RelaxNG schema for schematron, copyright International
|
19 |
+
Organization for Standardization (see
|
20 |
+
src/lxml/isoschematron/resources/rng/iso-schematron.rng for the license
|
21 |
+
text)
|
22 |
+
* The skeleton iso-schematron-xlt1 pure-xslt schematron implementation
|
23 |
+
xsl stylesheets, copyright Rick Jelliffe and Academia Sinica Computing
|
24 |
+
Center, Taiwan (see the xsl files here for the license text:
|
25 |
+
src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/)
|
26 |
+
* The xsd/rng schema schematron extraction xsl transformations are unlicensed
|
27 |
+
and copyright the respective authors as noted (see
|
28 |
+
src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl and
|
29 |
+
src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl)
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/METADATA
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: lxml
|
3 |
+
Version: 5.2.1
|
4 |
+
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
|
5 |
+
Home-page: https://lxml.de/
|
6 |
+
Author: lxml dev team
|
7 |
+
Author-email: [email protected]
|
8 |
+
Maintainer: lxml dev team
|
9 |
+
Maintainer-email: [email protected]
|
10 |
+
License: BSD-3-Clause
|
11 |
+
Project-URL: Source, https://github.com/lxml/lxml
|
12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
13 |
+
Classifier: Intended Audience :: Developers
|
14 |
+
Classifier: Intended Audience :: Information Technology
|
15 |
+
Classifier: License :: OSI Approved :: BSD License
|
16 |
+
Classifier: Programming Language :: Cython
|
17 |
+
Classifier: Programming Language :: Python :: 3
|
18 |
+
Classifier: Programming Language :: Python :: 3.6
|
19 |
+
Classifier: Programming Language :: Python :: 3.7
|
20 |
+
Classifier: Programming Language :: Python :: 3.8
|
21 |
+
Classifier: Programming Language :: Python :: 3.9
|
22 |
+
Classifier: Programming Language :: Python :: 3.10
|
23 |
+
Classifier: Programming Language :: Python :: 3.11
|
24 |
+
Classifier: Programming Language :: Python :: 3.12
|
25 |
+
Classifier: Programming Language :: C
|
26 |
+
Classifier: Operating System :: OS Independent
|
27 |
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
28 |
+
Classifier: Topic :: Text Processing :: Markup :: XML
|
29 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
30 |
+
Requires-Python: >=3.6
|
31 |
+
License-File: LICENSE.txt
|
32 |
+
License-File: LICENSES.txt
|
33 |
+
Provides-Extra: cssselect
|
34 |
+
Requires-Dist: cssselect >=0.7 ; extra == 'cssselect'
|
35 |
+
Provides-Extra: html5
|
36 |
+
Requires-Dist: html5lib ; extra == 'html5'
|
37 |
+
Provides-Extra: html_clean
|
38 |
+
Requires-Dist: lxml-html-clean ; extra == 'html_clean'
|
39 |
+
Provides-Extra: htmlsoup
|
40 |
+
Requires-Dist: BeautifulSoup4 ; extra == 'htmlsoup'
|
41 |
+
Provides-Extra: source
|
42 |
+
Requires-Dist: Cython >=3.0.10 ; extra == 'source'
|
43 |
+
|
44 |
+
lxml is a Pythonic, mature binding for the libxml2 and libxslt libraries. It
|
45 |
+
provides safe and convenient access to these libraries using the ElementTree
|
46 |
+
API.
|
47 |
+
|
48 |
+
It extends the ElementTree API significantly to offer support for XPath,
|
49 |
+
RelaxNG, XML Schema, XSLT, C14N and much more.
|
50 |
+
|
51 |
+
To contact the project, go to the `project home page
|
52 |
+
<https://lxml.de/>`_ or see our bug tracker at
|
53 |
+
https://launchpad.net/lxml
|
54 |
+
|
55 |
+
In case you want to use the current in-development version of lxml,
|
56 |
+
you can get it from the github repository at
|
57 |
+
https://github.com/lxml/lxml . Note that this requires Cython to
|
58 |
+
build the sources, see the build instructions on the project home
|
59 |
+
page. To the same end, running ``easy_install lxml==dev`` will
|
60 |
+
install lxml from
|
61 |
+
https://github.com/lxml/lxml/tarball/master#egg=lxml-dev if you have
|
62 |
+
an appropriate version of Cython installed.
|
63 |
+
|
64 |
+
|
65 |
+
After an official release of a new stable series, bug fixes may become
|
66 |
+
available at
|
67 |
+
https://github.com/lxml/lxml/tree/lxml-5.2 .
|
68 |
+
Running ``easy_install lxml==5.2bugfix`` will install
|
69 |
+
the unreleased branch state from
|
70 |
+
https://github.com/lxml/lxml/tarball/lxml-5.2#egg=lxml-5.2bugfix
|
71 |
+
as soon as a maintenance branch has been established. Note that this
|
72 |
+
requires Cython to be installed at an appropriate version for the build.
|
73 |
+
|
74 |
+
5.2.1 (2024-04-02)
|
75 |
+
==================
|
76 |
+
|
77 |
+
Bugs fixed
|
78 |
+
----------
|
79 |
+
|
80 |
+
* LP#2059910: The minimum CPU architecture for the Linux x86 binary wheels was set back to
|
81 |
+
"core2", but with SSE 4.2 enabled.
|
82 |
+
|
83 |
+
* LP#2059977: ``Element.iterfind("//absolute_path")`` failed with a ``SyntaxError``
|
84 |
+
where it should have issued a warning.
|
85 |
+
|
86 |
+
* GH#416: The documentation build was using the non-standard ``which`` command.
|
87 |
+
Patch by Michał Górny.
|
88 |
+
|
89 |
+
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/RECORD
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
lxml-5.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
lxml-5.2.1.dist-info/LICENSE.txt,sha256=ae20RcEzWoMS1MCScYR-mVbYTw2fck0SU0DMP612eyo,1488
|
3 |
+
lxml-5.2.1.dist-info/LICENSES.txt,sha256=QdSd1AaqDhVIptXyGjDWv2OLPNlutyid00jYPtLkA5I,1514
|
4 |
+
lxml-5.2.1.dist-info/METADATA,sha256=gOuJgh--uI1YuhrzK8UoTG-oBMJJB1tljdEWH-Y9_Aw,3444
|
5 |
+
lxml-5.2.1.dist-info/RECORD,,
|
6 |
+
lxml-5.2.1.dist-info/WHEEL,sha256=DRFGfbmk00iwRfDF9fpLQAJbF-b4Wp23htOC54ltOsw,114
|
7 |
+
lxml-5.2.1.dist-info/top_level.txt,sha256=NjD988wqaKq512nshNdLt-uDxsjkp4Bh51m6N-dhUrk,5
|
8 |
+
lxml/ElementInclude.py,sha256=PSLeZFvCa76WHJulPLxcZXJtCI2-4dK2CtqPRiYOAQg,8560
|
9 |
+
lxml/__init__.py,sha256=muWa7ZIKDJW7z7hAmmliO3nRMLRFeGHBjo7qnnf2mIk,574
|
10 |
+
lxml/__pycache__/ElementInclude.cpython-310.pyc,,
|
11 |
+
lxml/__pycache__/__init__.cpython-310.pyc,,
|
12 |
+
lxml/__pycache__/_elementpath.cpython-310.pyc,,
|
13 |
+
lxml/__pycache__/builder.cpython-310.pyc,,
|
14 |
+
lxml/__pycache__/cssselect.cpython-310.pyc,,
|
15 |
+
lxml/__pycache__/doctestcompare.cpython-310.pyc,,
|
16 |
+
lxml/__pycache__/pyclasslookup.cpython-310.pyc,,
|
17 |
+
lxml/__pycache__/sax.cpython-310.pyc,,
|
18 |
+
lxml/__pycache__/usedoctest.cpython-310.pyc,,
|
19 |
+
lxml/_elementpath.cpython-310-x86_64-linux-gnu.so,sha256=QQNpkJSHYkyZj1jb70g4bZzZHAJFRc7xxjzQtBV10B4,209088
|
20 |
+
lxml/_elementpath.py,sha256=5-PzX8ZIxPIvESKDGVL829sejYkvx991FSQyM-J0LqE,10888
|
21 |
+
lxml/apihelpers.pxi,sha256=zipCUecXzy5INij_qdEEqZoLp9LYB3CJQUzIzFVH1Ow,63610
|
22 |
+
lxml/builder.cpython-310-x86_64-linux-gnu.so,sha256=g2l9-5NdQVyGLKlvk8VRM-CmOrBPEacGym59vnUozGs,112416
|
23 |
+
lxml/builder.py,sha256=XD0DQc_G-D950Ym2NwDqxF2v9frtldxdfmvYhxhpP64,8100
|
24 |
+
lxml/classlookup.pxi,sha256=Tax8Vhbm5C6UCjgmRFsYjW0pFHxIuTthH1MOgASDLgc,22435
|
25 |
+
lxml/cleanup.pxi,sha256=ZNEpbv7qx_ICPzsxhCaMUHCOfiznOoZ_u3jlYXHAuh4,8454
|
26 |
+
lxml/cssselect.py,sha256=_wZdX-B9p5MeIYABmENIYRWEkwXwX-7jO8Dkf-1rUZU,3306
|
27 |
+
lxml/debug.pxi,sha256=zhxiMeNnKtkjn_FWboHk1T-Vtcg_vEGV8jfYK0XyXHM,3282
|
28 |
+
lxml/docloader.pxi,sha256=bYSZAxxbBEfVzfLXTUWFRfOyUTfV23L7i9hR2dgtSNY,5772
|
29 |
+
lxml/doctestcompare.py,sha256=40EDnkwpcvW86qNa86990OXF42xdHaosSZoiBsEjkzU,17731
|
30 |
+
lxml/dtd.pxi,sha256=y2i_PVKnlWCe9VGchgM6t8lIljtVfbWSXuWC-rEbzeE,15228
|
31 |
+
lxml/etree.cpython-310-x86_64-linux-gnu.so,sha256=zZ00g74Zo8BV9ZvKDxe17KREzm8UHydWXR-e4DG-_6g,5341640
|
32 |
+
lxml/etree.h,sha256=NPhL2CztGkHk3YgMx2j7pkimDavjx_8CTmCRrdMxslM,9912
|
33 |
+
lxml/etree.pyx,sha256=dHJaEezpj2bZrsiUZgh5ypC79L3FPxMXRiHnGlBkOx8,133885
|
34 |
+
lxml/etree_api.h,sha256=XDHi7lgGoIcyoS8hB27di8OAb0RC6ubGs3ETzd3KDSE,17063
|
35 |
+
lxml/extensions.pxi,sha256=58O6mBbDeWnkiIsRd9T7mLodylo7typz2dbjpJryAyY,32088
|
36 |
+
lxml/html/ElementSoup.py,sha256=s_dLobLMuKn2DhexR-iDXdZrMFg1RjLy1feHsIeZMpw,320
|
37 |
+
lxml/html/__init__.py,sha256=ap2X3ZzRaufsJppVEVa7ctw1bYtBfs7FSRBCUIKPyDk,64302
|
38 |
+
lxml/html/__pycache__/ElementSoup.cpython-310.pyc,,
|
39 |
+
lxml/html/__pycache__/__init__.cpython-310.pyc,,
|
40 |
+
lxml/html/__pycache__/_diffcommand.cpython-310.pyc,,
|
41 |
+
lxml/html/__pycache__/_html5builder.cpython-310.pyc,,
|
42 |
+
lxml/html/__pycache__/_setmixin.cpython-310.pyc,,
|
43 |
+
lxml/html/__pycache__/builder.cpython-310.pyc,,
|
44 |
+
lxml/html/__pycache__/clean.cpython-310.pyc,,
|
45 |
+
lxml/html/__pycache__/defs.cpython-310.pyc,,
|
46 |
+
lxml/html/__pycache__/diff.cpython-310.pyc,,
|
47 |
+
lxml/html/__pycache__/formfill.cpython-310.pyc,,
|
48 |
+
lxml/html/__pycache__/html5parser.cpython-310.pyc,,
|
49 |
+
lxml/html/__pycache__/soupparser.cpython-310.pyc,,
|
50 |
+
lxml/html/__pycache__/usedoctest.cpython-310.pyc,,
|
51 |
+
lxml/html/_diffcommand.py,sha256=kz_7EP9PmYWuczlZcGiw74_rG0eTKvQ2lrO0rkiwlYE,2081
|
52 |
+
lxml/html/_html5builder.py,sha256=NLaT-Ev-aBgJpeQl-6ZbJChLZK5GV-znDkHOJD5VQC4,3230
|
53 |
+
lxml/html/_setmixin.py,sha256=8IFIOLmVz0G-XzsD2tCEkSFWO-dgPBHgvHufC8ni67s,1188
|
54 |
+
lxml/html/builder.py,sha256=aRgS-Ea9bli-muGX0iUQGKAe9D93P8BspQ2WPuiWJcU,4492
|
55 |
+
lxml/html/clean.py,sha256=FghSJy4jt2RaBy6dgusowkU18hxpZ4XLE5ceCK9qxyA,503
|
56 |
+
lxml/html/defs.py,sha256=ZzOp2TmY9f_ein9GIcDPyN8-f5HVptzSj56umimWub4,4236
|
57 |
+
lxml/html/diff.cpython-310-x86_64-linux-gnu.so,sha256=K3PSxK2JraOQ4OwSlTCKZJJ-_K_etEyIt5_6nMDhIUI,372864
|
58 |
+
lxml/html/diff.py,sha256=n2jMJW8D2OYfG-SKbdmpSjZ3Lwk516WwJfMn6yvQiuM,30393
|
59 |
+
lxml/html/formfill.py,sha256=umgk0BbkAI1W6q9musFbL-cDnI_aap2NsLBJqk0UmVI,9681
|
60 |
+
lxml/html/html5parser.py,sha256=dnyC4cqHxywjZSzk0mu2L7THTZjxhg4yF4pncjusa_w,8634
|
61 |
+
lxml/html/soupparser.py,sha256=xo8VvNeOEb-SChuXLKCRECh8J7HBiJLE9sAbEskoUUQ,10197
|
62 |
+
lxml/html/usedoctest.py,sha256=tPlmVz4KK1GRKV5DJLrdVECeqsT9PlDzSqqTodVi5s0,249
|
63 |
+
lxml/includes/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
64 |
+
lxml/includes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
65 |
+
lxml/includes/__pycache__/__init__.cpython-310.pyc,,
|
66 |
+
lxml/includes/c14n.pxd,sha256=DBQcOJ0c_YS245ohMb8fmuEC1kFyv1LrNY_8Mf-syZg,1110
|
67 |
+
lxml/includes/config.pxd,sha256=H6Mrl8It21hzRI2hzMId9W48QqkYYkoLT4dniLNmdTw,96
|
68 |
+
lxml/includes/dtdvalid.pxd,sha256=Nv0OykjYehv2lO-Zj--q6jS3TAC_dvQVPSgPMuse1NM,689
|
69 |
+
lxml/includes/etree_defs.h,sha256=wWC0nsE3NCLBABsKjo_UMBtUJr7yPL7-e8OLc-tGI5o,14245
|
70 |
+
lxml/includes/etreepublic.pxd,sha256=Bn4d3JkWPqXputXqI-eJ0xmPrwNFPTfDCa7axgjB7FM,10184
|
71 |
+
lxml/includes/extlibs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
72 |
+
lxml/includes/extlibs/__pycache__/__init__.cpython-310.pyc,,
|
73 |
+
lxml/includes/extlibs/libcharset.h,sha256=GA0FumrbNI4VDGlzq3lf5CLaCwXgn4unw2l0btGQFwI,1510
|
74 |
+
lxml/includes/extlibs/localcharset.h,sha256=Z_AagaQeq0aDE7NPsVOqEf4nO4KcUp46ggo4d0ONIOQ,6338
|
75 |
+
lxml/includes/extlibs/zconf.h,sha256=ROVD_0UUx6mgHWSAGcLJqB0RBcv6PHfx-vbNhur6ir0,16464
|
76 |
+
lxml/includes/extlibs/zlib.h,sha256=ilV5r3LqT0J_8ApBUPDMs_xcHkN59ybhARM7Grn8YAw,96829
|
77 |
+
lxml/includes/htmlparser.pxd,sha256=9uASkP5dU7OE2lCOLT-z2e01qSbFlp4ehgwdostF_qk,2802
|
78 |
+
lxml/includes/libexslt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
79 |
+
lxml/includes/libexslt/__pycache__/__init__.cpython-310.pyc,,
|
80 |
+
lxml/includes/libexslt/exslt.h,sha256=eSW5tMJAewSUANLqk7AGEiU8b2BbCNRyauHnez7nKSU,3114
|
81 |
+
lxml/includes/libexslt/exsltconfig.h,sha256=I0m5Qut1Equ7peyWaseRI4jtPC5ENlOp4UthyUYI3QM,1172
|
82 |
+
lxml/includes/libexslt/exsltexports.h,sha256=1Jm9KTXm2FUUJIZ6V6-Uw55yG0BMULX3_goyxDd2LL8,1077
|
83 |
+
lxml/includes/libxml/HTMLparser.h,sha256=ySe0Ebz_SqcymDMfwbuuXrWFjzk36u87-gEel_Nuctg,10008
|
84 |
+
lxml/includes/libxml/HTMLtree.h,sha256=xQMeETDtY8XZnkV9rGkI4UgUIp71I4z2O3R_P1AEwc4,3502
|
85 |
+
lxml/includes/libxml/SAX.h,sha256=TG2pkIInEA1vLbMfhB02mZhYSoTKxX-m0RaUGmYyzCo,4418
|
86 |
+
lxml/includes/libxml/SAX2.h,sha256=5fiNvrQmkgIzgZJk-38P1txfs-jIvAcL-_hDAE2pQFs,4430
|
87 |
+
lxml/includes/libxml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
88 |
+
lxml/includes/libxml/__pycache__/__init__.cpython-310.pyc,,
|
89 |
+
lxml/includes/libxml/c14n.h,sha256=vG_CjBvBDaMDVLD8qTQNqT-fj7rmkvD8O8Q7OCv9p3M,3021
|
90 |
+
lxml/includes/libxml/catalog.h,sha256=_aTvqPlvW9WSwGr0UsUr50H3xvLK3KjIT7NEaE8L4Ww,4618
|
91 |
+
lxml/includes/libxml/chvalid.h,sha256=TZcceNp6Cw0QlYwIqK9GxyYqL5UiAjpQyjt_yrZGTQE,5087
|
92 |
+
lxml/includes/libxml/debugXML.h,sha256=W0JxFbxqZKEDwyTffBNeVPyHjFQL4wj3Vr9PCl63YA4,4928
|
93 |
+
lxml/includes/libxml/dict.h,sha256=SweaPGMtTTf4je6dNTIoEzcfEvpsAT9_PhR7FC0K-rQ,1770
|
94 |
+
lxml/includes/libxml/encoding.h,sha256=10GEJ6jAieaRXNHDqoHy4s5FSDTfPBm-_Y8V5eSQdqU,8109
|
95 |
+
lxml/includes/libxml/entities.h,sha256=QDLCNfqDBiza2N4T5nBqecGLcvmCqdPbbXBpoqd1ZgY,4659
|
96 |
+
lxml/includes/libxml/globals.h,sha256=GCp5Iy7IOre0MC1FbFTdpidiSeVFT4fA2t0Facbiw0Q,890
|
97 |
+
lxml/includes/libxml/hash.h,sha256=NiQ7FIrpb5_fqLbqB_wuakO2hcbEjkjrLMkWsJ4u7z0,6310
|
98 |
+
lxml/includes/libxml/list.h,sha256=kwMDctdAgRtCGInjdXuaBAlNDrn5Vc87rdUNjHgUNH4,3140
|
99 |
+
lxml/includes/libxml/nanoftp.h,sha256=q-OGmv3ltTTTbB_n6ehpGFJpS6wwME-pNTkxcYhHKvo,4013
|
100 |
+
lxml/includes/libxml/nanohttp.h,sha256=jca5Z9jzu_Lb6ey7B90q6gjZHGlO82LUx0OsTulCl8E,1869
|
101 |
+
lxml/includes/libxml/parser.h,sha256=payh3SrRC3q1IBC6OT_RSTZK8Wp1KUoEcca43p-2pds,44410
|
102 |
+
lxml/includes/libxml/parserInternals.h,sha256=ZVSsuLs_K-Ldj0ryU1OPP8lnIe3yKN4QL_CgfhmeiZM,16604
|
103 |
+
lxml/includes/libxml/relaxng.h,sha256=miygBGaAxpxiG16kzGWbah9Pl84TunzqKIQf9GcTkhE,5830
|
104 |
+
lxml/includes/libxml/schemasInternals.h,sha256=V8M4In3zf24EX55Yt4dcfxwp7NpHGYViKnLKwtyrPJ4,26233
|
105 |
+
lxml/includes/libxml/schematron.h,sha256=8EhPDhvtlMxl9e0C5rSbEruOvzJS5BC_OOFbq9RXZnY,4255
|
106 |
+
lxml/includes/libxml/threads.h,sha256=vWXv_Nvf7a1iJVZO22J7nCUZkTwM1plW6lL_v9Wckd0,1730
|
107 |
+
lxml/includes/libxml/tree.h,sha256=qVYizJJHQqrFJPmK_ZbdeWGDTwv2m1MzeZ51xfeVong,38353
|
108 |
+
lxml/includes/libxml/uri.h,sha256=A7nSyNLbCGWRVvpVbg8bbo-cw3s-Eu0rs45ILWhzfDk,2568
|
109 |
+
lxml/includes/libxml/valid.h,sha256=N0iyv98q1qPwS1lzzuF9U5o_ZSXfPNqsbnq2qjofeU4,12834
|
110 |
+
lxml/includes/libxml/xinclude.h,sha256=2M5D4Koe4Q4zX1qYaiKmp0Fq5joC5UpY4fcV6FG80Xw,2887
|
111 |
+
lxml/includes/libxml/xlink.h,sha256=UwJVQvFAax69tdMkePYiAlfkpzTTGZM7hWMyGzEDdwk,5002
|
112 |
+
lxml/includes/libxml/xmlIO.h,sha256=SSvJNj3eA4zw87n4-tTrsZBGqHnw7_Rt_6jJon_stDk,12253
|
113 |
+
lxml/includes/libxml/xmlautomata.h,sha256=6V_99Ozmfjy1EywHByHLBrgvBsItuYoV34qifJDdXDc,3787
|
114 |
+
lxml/includes/libxml/xmlerror.h,sha256=mPPTbEDEM3UodTTwMMPhMG0zWsEBMA6w2xUOUELWisM,37295
|
115 |
+
lxml/includes/libxml/xmlexports.h,sha256=GZ1O2qLq9NHTeUddup2ac90MdoImLuH81HvA59oYFyY,992
|
116 |
+
lxml/includes/libxml/xmlmemory.h,sha256=N1C_93dytOuKccDvGWzRoT5yrA9YZS9A57vb34DwtuY,6116
|
117 |
+
lxml/includes/libxml/xmlmodule.h,sha256=y8AmygZrR3wf5UEfyhu6Sf6sn7TTO47g0FUfwdtexA8,1138
|
118 |
+
lxml/includes/libxml/xmlreader.h,sha256=iSQmsBM7175FC9D0yPzASIrEVzXktaibRMzmYJPJBxE,12114
|
119 |
+
lxml/includes/libxml/xmlregexp.h,sha256=AK69btlcPhG_i_6wVB-VABljotbg241WFsL34STKxmg,5149
|
120 |
+
lxml/includes/libxml/xmlsave.h,sha256=A6_a6TtPnAT8vLcSW-CU4ntcs8GCc1igRyjz2eVlpv4,2469
|
121 |
+
lxml/includes/libxml/xmlschemas.h,sha256=lXHsYTgPFpvSZF8LSFmHlF6EycX1PkzzW7zejosOn34,6902
|
122 |
+
lxml/includes/libxml/xmlschemastypes.h,sha256=MYwlGmoKAo3lHRaaKgnCXiLmPT9KRjdxyCJ7TEyZ6jM,4583
|
123 |
+
lxml/includes/libxml/xmlstring.h,sha256=d5PpqxP1I1sfmCUHvVJtjoC9h7hLHcAAQ5ok_Rtf50I,5271
|
124 |
+
lxml/includes/libxml/xmlunicode.h,sha256=xqhfmchk-GELwmZWZ2Ha0IgosCy9csZswVDnbmvzRjI,8665
|
125 |
+
lxml/includes/libxml/xmlversion.h,sha256=Qa_a27aFYEAc2U7xl_whMtgB8BTe36VfBgUxGjIF2XI,9205
|
126 |
+
lxml/includes/libxml/xmlwriter.h,sha256=7tXNqXynH7tbeeMrxcbpI_TI_ZSjxmcR43wXxVg9X9o,20625
|
127 |
+
lxml/includes/libxml/xpath.h,sha256=v7fb_GTuugqevysPRNLBocL0YleyEGMyH_SaDpescek,16442
|
128 |
+
lxml/includes/libxml/xpathInternals.h,sha256=y3F0P7awBk9qhRQmmEgtSDEHoSvbLN_Q2vIifflypSI,18419
|
129 |
+
lxml/includes/libxml/xpointer.h,sha256=9MKw7uRowx53od3plREL_szioEudglZS6H2EUetBToQ,3647
|
130 |
+
lxml/includes/libxslt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
131 |
+
lxml/includes/libxslt/__pycache__/__init__.cpython-310.pyc,,
|
132 |
+
lxml/includes/libxslt/attributes.h,sha256=qKwzfGf7r89esLC65s96iYJWRA-s-Ezss2_V6Mmo1hk,957
|
133 |
+
lxml/includes/libxslt/documents.h,sha256=kBihgH5pqRvFalhm_fOFHtJTFhTpBcm681yT5dxgwfw,2704
|
134 |
+
lxml/includes/libxslt/extensions.h,sha256=W5UMyJqUP_1zt6sXZ0mgc0gAIwDJrZ8gjByhyrWqvd8,6899
|
135 |
+
lxml/includes/libxslt/extra.h,sha256=6X3Wu3NdPtrlqz-Koo7dB-rccnnszi6j3zg599gTByg,1640
|
136 |
+
lxml/includes/libxslt/functions.h,sha256=fc4CZj-9KeBHzO9-WWU_bNqmaEZAz3n7NNwClIBXk14,1972
|
137 |
+
lxml/includes/libxslt/imports.h,sha256=18kIjoGqdFXR63Ce3ZtzxsTiYV3XGKpchYakMUPDuUI,1840
|
138 |
+
lxml/includes/libxslt/keys.h,sha256=16v25VEluS7jYhgg6gYFwVxgGMn-1ctnlhhWWT4RcBY,1155
|
139 |
+
lxml/includes/libxslt/namespaces.h,sha256=VofSn2Kkn-a5JyRKCmY3jPp7amQy3n09vzy0KUQt4q0,1666
|
140 |
+
lxml/includes/libxslt/numbersInternals.h,sha256=Eg5gYZ5p3h0_e5wyI61S-0E6_ArVJzv0yr63j6BU2fc,2019
|
141 |
+
lxml/includes/libxslt/pattern.h,sha256=tJ-BPfs9UYgiZMMoQZbhij3g7xVppYq7TrrOu25eR7Q,2110
|
142 |
+
lxml/includes/libxslt/preproc.h,sha256=D_LjEdHhsdyBnEAvflnwFgoR4hGUb72kgEhXkkmPRsw,896
|
143 |
+
lxml/includes/libxslt/security.h,sha256=fUD1cy_WxFCTvTNAF0WOQIU4p5CNWn1LHFyZJd-Fx5U,2652
|
144 |
+
lxml/includes/libxslt/templates.h,sha256=bnt6Jqui6KU5pNUdMNPbQZkZ5d-VTWqC0TMGkOlVoIo,2268
|
145 |
+
lxml/includes/libxslt/transform.h,sha256=ICT7meUV0OTAx27WaKVrKj-aUmR9LSpTNaOAJd2UStg,6311
|
146 |
+
lxml/includes/libxslt/variables.h,sha256=cQAgPe4QCcK2uKbWg7Iz-9peM9xWGm7m3M6jQm0sjIA,3143
|
147 |
+
lxml/includes/libxslt/xslt.h,sha256=wmFx2Q31Pd8Iq2phAQpY9J3QQatb8lWg3gABtqKFgEw,1964
|
148 |
+
lxml/includes/libxslt/xsltInternals.h,sha256=VKpvlPx4gUMYYdnaTFgyzcwamcGR0oOUou0iQi8-I9Q,57894
|
149 |
+
lxml/includes/libxslt/xsltconfig.h,sha256=W_FQN0zWOn-tbHapROrD5BgHkeykaG1khzrxl4H6eNc,3682
|
150 |
+
lxml/includes/libxslt/xsltexports.h,sha256=1-luH-0bCIgBAlKAXhV-dqHBfwOAQNDamiYbxIlTf0k,1124
|
151 |
+
lxml/includes/libxslt/xsltlocale.h,sha256=ppxGEmJfZIJgwRQzCM0_77p9WNekEWq1NrdYZrQl4IE,942
|
152 |
+
lxml/includes/libxslt/xsltutils.h,sha256=1eguYgR9-jeNOVlBUktHboaq-VLX6JXraO80TfbARKM,9085
|
153 |
+
lxml/includes/lxml-version.h,sha256=2fN0JTHAnzy65wnMxsss7l72xTYbVKZiJMDuIOQaai0,71
|
154 |
+
lxml/includes/relaxng.pxd,sha256=HzHlQ6mCcf_tj_JZ9NAVJTVAv8ScCkE8Ifq15y3bS0c,2615
|
155 |
+
lxml/includes/schematron.pxd,sha256=Hob7xh-K-MKqp7WiG8thMagf5EkQzmgfi4ds0EF91JA,1604
|
156 |
+
lxml/includes/tree.pxd,sha256=Z5mHkABQPlnwu81WTTq7R4fz17rJAkamOvXf_Jp-nxg,20391
|
157 |
+
lxml/includes/uri.pxd,sha256=3vOXw6AbSPxAM9uo71T1qnfx-wd9ezXLDQtWsb2zX0I,145
|
158 |
+
lxml/includes/xinclude.pxd,sha256=CuO_XZNB6E2JK1qXXWn11APrjFQV5kA6SMyb77WZn0A,804
|
159 |
+
lxml/includes/xmlerror.pxd,sha256=pNP5juL4hRHdVdXUWzMspbdtgPqJdHLDu4jns3ItvrI,58016
|
160 |
+
lxml/includes/xmlparser.pxd,sha256=d79Wmyof6BX_rjBkKYyDXhBBC3O-yCfyhx8PrI0wm5E,11434
|
161 |
+
lxml/includes/xmlschema.pxd,sha256=OLZPd2WDJyopiXJJyo-dAyyYHaeSYFiMAI4tqIiv-Ik,1702
|
162 |
+
lxml/includes/xpath.pxd,sha256=e8-ZYUbRG7N1mHETAlknJ_QqAteOosrYLRgpH-OsTkg,5603
|
163 |
+
lxml/includes/xslt.pxd,sha256=4yl3pOu7pAvsx5Tc-W4IWCoB8wgtSSR62HI1jqu6jko,8241
|
164 |
+
lxml/isoschematron/__init__.py,sha256=D9LF5IXdj08t7QXajHFT3LtIW3-DCbXZw1ZjJZlpn-4,13270
|
165 |
+
lxml/isoschematron/__pycache__/__init__.cpython-310.pyc,,
|
166 |
+
lxml/isoschematron/resources/rng/iso-schematron.rng,sha256=VsWxPyi3iViJDDbjJJw0wWkEHkLrz9zoCA8zJLor9N4,18337
|
167 |
+
lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl,sha256=ObebsB8Wt-d3uIA_U5NU85TpnQ3PxPX38TdOAqosMac,3172
|
168 |
+
lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl,sha256=QweRrIIM-zFcgg98GXA2CaWfIbgVE0XKEeYSfvv67A0,4563
|
169 |
+
lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl,sha256=xSZ_Ekq_I-62ZpiE5AqYYHwFW_qh855zt9V4_s7rbkY,11703
|
170 |
+
lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl,sha256=x42QJ-dxQ1waPzydsCoQnp2Xj15y53nW43O7BuoDRHk,39957
|
171 |
+
lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl,sha256=Tr9BnO6pzjVWwhqJfm10UlvAy95EgfSCz2iMlrVGT6Q,2015
|
172 |
+
lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl,sha256=ue8q_88X4e_jsJizo31GRNBxNhdxkEE9fY20oq0Iqwk,71764
|
173 |
+
lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl,sha256=BBAdsVSi5zAzeGepuN6gS1saQINDqITXKplmmj4dTWg,20382
|
174 |
+
lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt,sha256=OGLiFswuLJEW5EPYKOeoauuCJFEtVa6jyzBE1OcJI98,3310
|
175 |
+
lxml/iterparse.pxi,sha256=HcHYTLU6cs1R7GOik62rEkTebgsz1fYttk00iKfOtcw,16527
|
176 |
+
lxml/lxml.etree.h,sha256=NPhL2CztGkHk3YgMx2j7pkimDavjx_8CTmCRrdMxslM,9912
|
177 |
+
lxml/lxml.etree_api.h,sha256=10b-ePscCH-tL0k-Ve4JD109sxsFJQnNcLXet_7U8wc,17068
|
178 |
+
lxml/nsclasses.pxi,sha256=5pzNBhBtlqObPdThL9QIGRs1Dxj1qnr0PyXuTCURqTg,9129
|
179 |
+
lxml/objectify.cpython-310-x86_64-linux-gnu.so,sha256=yF0ZRQPngWsI5PypQASvFY4-ewc3ugZHowHKy9bpKIY,3057096
|
180 |
+
lxml/objectify.pyx,sha256=pvaZmS21G-qlNjPuVaB_dgGgi0alxNALo7gFOV8Ispc,75735
|
181 |
+
lxml/objectpath.pxi,sha256=s5TNG2-EbaWWKLFAiX303B95zK_Ui8ausB__3QvFFGw,11450
|
182 |
+
lxml/parser.pxi,sha256=9R2rdzq1f8LOaKSAzAnFghB3rAspy4vcMTB6q8u0RSA,81866
|
183 |
+
lxml/parsertarget.pxi,sha256=v1PidxRaG5giwXcTDkpBI7PDFmsZuOcK0y9LdkQaY8M,6326
|
184 |
+
lxml/proxy.pxi,sha256=TPfavn4-ufhVlr-GKciz2qXCTUFtvGdxO-F-h30yIws,23697
|
185 |
+
lxml/public-api.pxi,sha256=XoP6_cJOEoQIItvE1RiYCKYD1ry4AobaOr4XLo0KSE4,6666
|
186 |
+
lxml/pyclasslookup.py,sha256=gLD1HM2HtITYYiGzjEOewSwbB7XkVx_NZv_quCt79Oc,92
|
187 |
+
lxml/readonlytree.pxi,sha256=ddRYczhHieJ4XUvWvTPW9N9oQ8vuKtv7lC1mtE1qvH8,18976
|
188 |
+
lxml/relaxng.pxi,sha256=3OQ-fZMzP-KF5vM6HTozT_9ee3J0DJnpj9RcHC8LoMw,6339
|
189 |
+
lxml/sax.cpython-310-x86_64-linux-gnu.so,sha256=LqPdMCg8pC_R5MfcqdSdeoEXy4AQ71SSDLqXCgQFZKU,186008
|
190 |
+
lxml/sax.py,sha256=8e9Ef4Cfbwr7AHMGCBBZcotBkOehQtdaCxsVCgWM5_c,9303
|
191 |
+
lxml/saxparser.pxi,sha256=9nJEnVFFFx7vueUJ3fSeDjxG4gLgrXsDBWVkD_f8U1Q,33322
|
192 |
+
lxml/schematron.pxi,sha256=hFn1p4egpvvz-Tkk2AH7cbVOavTC-A7mzHABHrGh7g4,5908
|
193 |
+
lxml/serializer.pxi,sha256=3wqS0zC0Pgh5ev-8Mn3YB6sVeJVH_j7wjpzSEDVTdvM,67951
|
194 |
+
lxml/usedoctest.py,sha256=qRgZKQVcAZcl-zN0AIXVJnOsETUXz2nPXkxuzs1lGgk,230
|
195 |
+
lxml/xinclude.pxi,sha256=7eBrI_OK47mmrHQ0ixbixRI8pKqQ1nwkMV-OmKUVlD4,2456
|
196 |
+
lxml/xmlerror.pxi,sha256=K7YIB21sLWdf_2GxyUymRZ5vDr3O4OJ5vGjrklBGa6o,49854
|
197 |
+
lxml/xmlid.pxi,sha256=5zf9oR6bsCtavGiOmilNyHqYwgG_bnrIabSd2SURtm0,6073
|
198 |
+
lxml/xmlschema.pxi,sha256=mumNoHni5S3BQPtcmOHRd61KRaVWu4eOie2wQeB0e6E,8490
|
199 |
+
lxml/xpath.pxi,sha256=aqW24V817dUxps4Gnc8h7Tm3QVlITKvxU5_9WgJUIFg,19132
|
200 |
+
lxml/xslt.pxi,sha256=R2fpAf0P7GA1Dhjg0-fGVUbxCk8bBAshuoAs4ODwqlc,36023
|
201 |
+
lxml/xsltext.pxi,sha256=TImDiAPlAezC07P7RY1N9YChA7AuKFH-G53hXdel9yc,11088
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.43.0)
|
3 |
+
Root-Is-Purelib: false
|
4 |
+
Tag: cp310-cp310-manylinux_2_28_x86_64
|
5 |
+
|
venv/lib/python3.10/site-packages/lxml-5.2.1.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
lxml
|
venv/lib/python3.10/site-packages/networkx/__init__.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
NetworkX
|
3 |
+
========
|
4 |
+
|
5 |
+
NetworkX is a Python package for the creation, manipulation, and study of the
|
6 |
+
structure, dynamics, and functions of complex networks.
|
7 |
+
|
8 |
+
See https://networkx.org for complete documentation.
|
9 |
+
"""
|
10 |
+
|
11 |
+
__version__ = "3.3"
|
12 |
+
|
13 |
+
|
14 |
+
# These are imported in order as listed
|
15 |
+
from networkx.lazy_imports import _lazy_import
|
16 |
+
|
17 |
+
from networkx.exception import *
|
18 |
+
|
19 |
+
from networkx import utils
|
20 |
+
from networkx.utils import _clear_cache, _dispatchable, config
|
21 |
+
|
22 |
+
from networkx import classes
|
23 |
+
from networkx.classes import filters
|
24 |
+
from networkx.classes import *
|
25 |
+
|
26 |
+
from networkx import convert
|
27 |
+
from networkx.convert import *
|
28 |
+
|
29 |
+
from networkx import convert_matrix
|
30 |
+
from networkx.convert_matrix import *
|
31 |
+
|
32 |
+
from networkx import relabel
|
33 |
+
from networkx.relabel import *
|
34 |
+
|
35 |
+
from networkx import generators
|
36 |
+
from networkx.generators import *
|
37 |
+
|
38 |
+
from networkx import readwrite
|
39 |
+
from networkx.readwrite import *
|
40 |
+
|
41 |
+
# Need to test with SciPy, when available
|
42 |
+
from networkx import algorithms
|
43 |
+
from networkx.algorithms import *
|
44 |
+
|
45 |
+
from networkx import linalg
|
46 |
+
from networkx.linalg import *
|
47 |
+
|
48 |
+
from networkx import drawing
|
49 |
+
from networkx.drawing import *
|
venv/lib/python3.10/site-packages/networkx/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.23 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/__pycache__/conftest.cpython-310.pyc
ADDED
Binary file (6.11 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/__pycache__/convert.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/__pycache__/convert_matrix.cpython-310.pyc
ADDED
Binary file (37.6 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/__pycache__/exception.cpython-310.pyc
ADDED
Binary file (4.52 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/__pycache__/lazy_imports.cpython-310.pyc
ADDED
Binary file (5.86 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/__pycache__/relabel.cpython-310.pyc
ADDED
Binary file (10.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/classes/__init__.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .graph import Graph
|
2 |
+
from .digraph import DiGraph
|
3 |
+
from .multigraph import MultiGraph
|
4 |
+
from .multidigraph import MultiDiGraph
|
5 |
+
|
6 |
+
from .function import *
|
7 |
+
from .graphviews import subgraph_view, reverse_view
|
8 |
+
|
9 |
+
from networkx.classes import filters
|
10 |
+
|
11 |
+
from networkx.classes import coreviews
|
12 |
+
from networkx.classes import graphviews
|
13 |
+
from networkx.classes import reportviews
|
venv/lib/python3.10/site-packages/networkx/classes/digraph.py
ADDED
@@ -0,0 +1,1334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for directed graphs."""
|
2 |
+
from copy import deepcopy
|
3 |
+
from functools import cached_property
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx import convert
|
7 |
+
from networkx.classes.coreviews import AdjacencyView
|
8 |
+
from networkx.classes.graph import Graph
|
9 |
+
from networkx.classes.reportviews import (
|
10 |
+
DiDegreeView,
|
11 |
+
InDegreeView,
|
12 |
+
InEdgeView,
|
13 |
+
OutDegreeView,
|
14 |
+
OutEdgeView,
|
15 |
+
)
|
16 |
+
from networkx.exception import NetworkXError
|
17 |
+
|
18 |
+
__all__ = ["DiGraph"]
|
19 |
+
|
20 |
+
|
21 |
+
class _CachedPropertyResetterAdjAndSucc:
|
22 |
+
"""Data Descriptor class that syncs and resets cached properties adj and succ
|
23 |
+
|
24 |
+
The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ`
|
25 |
+
are set to new objects. In addition, the attributes `_succ` and `_adj`
|
26 |
+
are synced so these two names point to the same object.
|
27 |
+
|
28 |
+
This object sits on a class and ensures that any instance of that
|
29 |
+
class clears its cached properties "succ" and "adj" whenever the
|
30 |
+
underlying instance attributes "_succ" or "_adj" are set to a new object.
|
31 |
+
It only affects the set process of the obj._adj and obj._succ attribute.
|
32 |
+
All get/del operations act as they normally would.
|
33 |
+
|
34 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __set__(self, obj, value):
|
38 |
+
od = obj.__dict__
|
39 |
+
od["_adj"] = value
|
40 |
+
od["_succ"] = value
|
41 |
+
# reset cached properties
|
42 |
+
if "adj" in od:
|
43 |
+
del od["adj"]
|
44 |
+
if "succ" in od:
|
45 |
+
del od["succ"]
|
46 |
+
|
47 |
+
|
48 |
+
class _CachedPropertyResetterPred:
|
49 |
+
"""Data Descriptor class for _pred that resets ``pred`` cached_property when needed
|
50 |
+
|
51 |
+
This assumes that the ``cached_property`` ``G.pred`` should be reset whenever
|
52 |
+
``G._pred`` is set to a new value.
|
53 |
+
|
54 |
+
This object sits on a class and ensures that any instance of that
|
55 |
+
class clears its cached property "pred" whenever the underlying
|
56 |
+
instance attribute "_pred" is set to a new object. It only affects
|
57 |
+
the set process of the obj._pred attribute. All get/del operations
|
58 |
+
act as they normally would.
|
59 |
+
|
60 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
61 |
+
"""
|
62 |
+
|
63 |
+
def __set__(self, obj, value):
|
64 |
+
od = obj.__dict__
|
65 |
+
od["_pred"] = value
|
66 |
+
if "pred" in od:
|
67 |
+
del od["pred"]
|
68 |
+
|
69 |
+
|
70 |
+
class DiGraph(Graph):
|
71 |
+
"""
|
72 |
+
Base class for directed graphs.
|
73 |
+
|
74 |
+
A DiGraph stores nodes and edges with optional data, or attributes.
|
75 |
+
|
76 |
+
DiGraphs hold directed edges. Self loops are allowed but multiple
|
77 |
+
(parallel) edges are not.
|
78 |
+
|
79 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
80 |
+
key/value attributes. By convention `None` is not used as a node.
|
81 |
+
|
82 |
+
Edges are represented as links between nodes with optional
|
83 |
+
key/value attributes.
|
84 |
+
|
85 |
+
Parameters
|
86 |
+
----------
|
87 |
+
incoming_graph_data : input graph (optional, default: None)
|
88 |
+
Data to initialize graph. If None (default) an empty
|
89 |
+
graph is created. The data can be any format that is supported
|
90 |
+
by the to_networkx_graph() function, currently including edge list,
|
91 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
|
92 |
+
sparse matrix, or PyGraphviz graph.
|
93 |
+
|
94 |
+
attr : keyword arguments, optional (default= no attributes)
|
95 |
+
Attributes to add to graph as key=value pairs.
|
96 |
+
|
97 |
+
See Also
|
98 |
+
--------
|
99 |
+
Graph
|
100 |
+
MultiGraph
|
101 |
+
MultiDiGraph
|
102 |
+
|
103 |
+
Examples
|
104 |
+
--------
|
105 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
106 |
+
no edges.
|
107 |
+
|
108 |
+
>>> G = nx.DiGraph()
|
109 |
+
|
110 |
+
G can be grown in several ways.
|
111 |
+
|
112 |
+
**Nodes:**
|
113 |
+
|
114 |
+
Add one node at a time:
|
115 |
+
|
116 |
+
>>> G.add_node(1)
|
117 |
+
|
118 |
+
Add the nodes from any container (a list, dict, set or
|
119 |
+
even the lines from a file or the nodes from another graph).
|
120 |
+
|
121 |
+
>>> G.add_nodes_from([2, 3])
|
122 |
+
>>> G.add_nodes_from(range(100, 110))
|
123 |
+
>>> H = nx.path_graph(10)
|
124 |
+
>>> G.add_nodes_from(H)
|
125 |
+
|
126 |
+
In addition to strings and integers any hashable Python object
|
127 |
+
(except None) can represent a node, e.g. a customized node object,
|
128 |
+
or even another Graph.
|
129 |
+
|
130 |
+
>>> G.add_node(H)
|
131 |
+
|
132 |
+
**Edges:**
|
133 |
+
|
134 |
+
G can also be grown by adding edges.
|
135 |
+
|
136 |
+
Add one edge,
|
137 |
+
|
138 |
+
>>> G.add_edge(1, 2)
|
139 |
+
|
140 |
+
a list of edges,
|
141 |
+
|
142 |
+
>>> G.add_edges_from([(1, 2), (1, 3)])
|
143 |
+
|
144 |
+
or a collection of edges,
|
145 |
+
|
146 |
+
>>> G.add_edges_from(H.edges)
|
147 |
+
|
148 |
+
If some edges connect nodes not yet in the graph, the nodes
|
149 |
+
are added automatically. There are no errors when adding
|
150 |
+
nodes or edges that already exist.
|
151 |
+
|
152 |
+
**Attributes:**
|
153 |
+
|
154 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
155 |
+
in an associated attribute dictionary (the keys must be hashable).
|
156 |
+
By default these are empty, but can be added or changed using
|
157 |
+
add_edge, add_node or direct manipulation of the attribute
|
158 |
+
dictionaries named graph, node and edge respectively.
|
159 |
+
|
160 |
+
>>> G = nx.DiGraph(day="Friday")
|
161 |
+
>>> G.graph
|
162 |
+
{'day': 'Friday'}
|
163 |
+
|
164 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
165 |
+
|
166 |
+
>>> G.add_node(1, time="5pm")
|
167 |
+
>>> G.add_nodes_from([3], time="2pm")
|
168 |
+
>>> G.nodes[1]
|
169 |
+
{'time': '5pm'}
|
170 |
+
>>> G.nodes[1]["room"] = 714
|
171 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
172 |
+
>>> list(G.nodes(data=True))
|
173 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
174 |
+
|
175 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
176 |
+
notation, or G.edges.
|
177 |
+
|
178 |
+
>>> G.add_edge(1, 2, weight=4.7)
|
179 |
+
>>> G.add_edges_from([(3, 4), (4, 5)], color="red")
|
180 |
+
>>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
181 |
+
>>> G[1][2]["weight"] = 4.7
|
182 |
+
>>> G.edges[1, 2]["weight"] = 4
|
183 |
+
|
184 |
+
Warning: we protect the graph data structure by making `G.edges[1, 2]` a
|
185 |
+
read-only dict-like structure. However, you can assign to attributes
|
186 |
+
in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
|
187 |
+
data attributes: `G.edges[1, 2]['weight'] = 4`
|
188 |
+
(For multigraphs: `MG.edges[u, v, key][name] = value`).
|
189 |
+
|
190 |
+
**Shortcuts:**
|
191 |
+
|
192 |
+
Many common graph features allow python syntax to speed reporting.
|
193 |
+
|
194 |
+
>>> 1 in G # check if node in graph
|
195 |
+
True
|
196 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
197 |
+
[1, 2]
|
198 |
+
>>> len(G) # number of nodes in graph
|
199 |
+
5
|
200 |
+
|
201 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
202 |
+
The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
|
203 |
+
|
204 |
+
>>> for n, nbrsdict in G.adjacency():
|
205 |
+
... for nbr, eattr in nbrsdict.items():
|
206 |
+
... if "weight" in eattr:
|
207 |
+
... # Do something useful with the edges
|
208 |
+
... pass
|
209 |
+
|
210 |
+
But the edges reporting object is often more convenient:
|
211 |
+
|
212 |
+
>>> for u, v, weight in G.edges(data="weight"):
|
213 |
+
... if weight is not None:
|
214 |
+
... # Do something useful with the edges
|
215 |
+
... pass
|
216 |
+
|
217 |
+
**Reporting:**
|
218 |
+
|
219 |
+
Simple graph information is obtained using object-attributes and methods.
|
220 |
+
Reporting usually provides views instead of containers to reduce memory
|
221 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
222 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
223 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
|
224 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
225 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
226 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
227 |
+
|
228 |
+
For details on these and other miscellaneous methods, see below.
|
229 |
+
|
230 |
+
**Subclasses (Advanced):**
|
231 |
+
|
232 |
+
The Graph class uses a dict-of-dict-of-dict data structure.
|
233 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
234 |
+
The next dict (adjlist_dict) represents the adjacency information and holds
|
235 |
+
edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
|
236 |
+
the edge data and holds edge attribute values keyed by attribute names.
|
237 |
+
|
238 |
+
Each of these three dicts can be replaced in a subclass by a user defined
|
239 |
+
dict-like object. In general, the dict-like features should be
|
240 |
+
maintained but extra features can be added. To replace one of the
|
241 |
+
dicts create a new graph class by changing the class(!) variable
|
242 |
+
holding the factory for that dict-like structure. The variable names are
|
243 |
+
node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
|
244 |
+
adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
|
245 |
+
|
246 |
+
node_dict_factory : function, (default: dict)
|
247 |
+
Factory function to be used to create the dict containing node
|
248 |
+
attributes, keyed by node id.
|
249 |
+
It should require no arguments and return a dict-like object
|
250 |
+
|
251 |
+
node_attr_dict_factory: function, (default: dict)
|
252 |
+
Factory function to be used to create the node attribute
|
253 |
+
dict which holds attribute values keyed by attribute name.
|
254 |
+
It should require no arguments and return a dict-like object
|
255 |
+
|
256 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
257 |
+
Factory function to be used to create the outer-most dict
|
258 |
+
in the data structure that holds adjacency info keyed by node.
|
259 |
+
It should require no arguments and return a dict-like object.
|
260 |
+
|
261 |
+
adjlist_inner_dict_factory : function, optional (default: dict)
|
262 |
+
Factory function to be used to create the adjacency list
|
263 |
+
dict which holds edge data keyed by neighbor.
|
264 |
+
It should require no arguments and return a dict-like object
|
265 |
+
|
266 |
+
edge_attr_dict_factory : function, optional (default: dict)
|
267 |
+
Factory function to be used to create the edge attribute
|
268 |
+
dict which holds attribute values keyed by attribute name.
|
269 |
+
It should require no arguments and return a dict-like object.
|
270 |
+
|
271 |
+
graph_attr_dict_factory : function, (default: dict)
|
272 |
+
Factory function to be used to create the graph attribute
|
273 |
+
dict which holds attribute values keyed by attribute name.
|
274 |
+
It should require no arguments and return a dict-like object.
|
275 |
+
|
276 |
+
Typically, if your extension doesn't impact the data structure all
|
277 |
+
methods will inherited without issue except: `to_directed/to_undirected`.
|
278 |
+
By default these methods create a DiGraph/Graph class and you probably
|
279 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
280 |
+
this we define two class variables that you can set in your subclass.
|
281 |
+
|
282 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
283 |
+
Class to create a new graph structure in the `to_directed` method.
|
284 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
285 |
+
|
286 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
287 |
+
Class to create a new graph structure in the `to_undirected` method.
|
288 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
289 |
+
|
290 |
+
**Subclassing Example**
|
291 |
+
|
292 |
+
Create a low memory graph class that effectively disallows edge
|
293 |
+
attributes by using a single attribute dict for all edges.
|
294 |
+
This reduces the memory used, but you lose edge attributes.
|
295 |
+
|
296 |
+
>>> class ThinGraph(nx.Graph):
|
297 |
+
... all_edge_dict = {"weight": 1}
|
298 |
+
...
|
299 |
+
... def single_edge_dict(self):
|
300 |
+
... return self.all_edge_dict
|
301 |
+
...
|
302 |
+
... edge_attr_dict_factory = single_edge_dict
|
303 |
+
>>> G = ThinGraph()
|
304 |
+
>>> G.add_edge(2, 1)
|
305 |
+
>>> G[2][1]
|
306 |
+
{'weight': 1}
|
307 |
+
>>> G.add_edge(2, 2)
|
308 |
+
>>> G[2][1] is G[2][2]
|
309 |
+
True
|
310 |
+
"""
|
311 |
+
|
312 |
+
_adj = _CachedPropertyResetterAdjAndSucc() # type: ignore[assignment]
|
313 |
+
_succ = _adj # type: ignore[has-type]
|
314 |
+
_pred = _CachedPropertyResetterPred()
|
315 |
+
|
316 |
+
def __init__(self, incoming_graph_data=None, **attr):
|
317 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
318 |
+
|
319 |
+
Parameters
|
320 |
+
----------
|
321 |
+
incoming_graph_data : input graph (optional, default: None)
|
322 |
+
Data to initialize graph. If None (default) an empty
|
323 |
+
graph is created. The data can be an edge list, or any
|
324 |
+
NetworkX graph object. If the corresponding optional Python
|
325 |
+
packages are installed the data can also be a 2D NumPy array, a
|
326 |
+
SciPy sparse array, or a PyGraphviz graph.
|
327 |
+
|
328 |
+
attr : keyword arguments, optional (default= no attributes)
|
329 |
+
Attributes to add to graph as key=value pairs.
|
330 |
+
|
331 |
+
See Also
|
332 |
+
--------
|
333 |
+
convert
|
334 |
+
|
335 |
+
Examples
|
336 |
+
--------
|
337 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
338 |
+
>>> G = nx.Graph(name="my graph")
|
339 |
+
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
|
340 |
+
>>> G = nx.Graph(e)
|
341 |
+
|
342 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
343 |
+
|
344 |
+
>>> G = nx.Graph(e, day="Friday")
|
345 |
+
>>> G.graph
|
346 |
+
{'day': 'Friday'}
|
347 |
+
|
348 |
+
"""
|
349 |
+
self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
|
350 |
+
self._node = self.node_dict_factory() # dictionary for node attr
|
351 |
+
# We store two adjacency lists:
|
352 |
+
# the predecessors of node n are stored in the dict self._pred
|
353 |
+
# the successors of node n are stored in the dict self._succ=self._adj
|
354 |
+
self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict successor
|
355 |
+
self._pred = self.adjlist_outer_dict_factory() # predecessor
|
356 |
+
# Note: self._succ = self._adj # successor
|
357 |
+
|
358 |
+
self.__networkx_cache__ = {}
|
359 |
+
# attempt to load graph with data
|
360 |
+
if incoming_graph_data is not None:
|
361 |
+
convert.to_networkx_graph(incoming_graph_data, create_using=self)
|
362 |
+
# load graph attributes (must be after convert)
|
363 |
+
self.graph.update(attr)
|
364 |
+
|
365 |
+
@cached_property
|
366 |
+
def adj(self):
|
367 |
+
"""Graph adjacency object holding the neighbors of each node.
|
368 |
+
|
369 |
+
This object is a read-only dict-like structure with node keys
|
370 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
371 |
+
to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
|
372 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
373 |
+
|
374 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
375 |
+
`for nbr, datadict in G.adj[n].items():`.
|
376 |
+
|
377 |
+
The neighbor information is also provided by subscripting the graph.
|
378 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
379 |
+
|
380 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
381 |
+
"""
|
382 |
+
return AdjacencyView(self._succ)
|
383 |
+
|
384 |
+
@cached_property
|
385 |
+
def succ(self):
|
386 |
+
"""Graph adjacency object holding the successors of each node.
|
387 |
+
|
388 |
+
This object is a read-only dict-like structure with node keys
|
389 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
390 |
+
to the edge-data-dict. So `G.succ[3][2]['color'] = 'blue'` sets
|
391 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
392 |
+
|
393 |
+
Iterating over G.succ behaves like a dict. Useful idioms include
|
394 |
+
`for nbr, datadict in G.succ[n].items():`. A data-view not provided
|
395 |
+
by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`
|
396 |
+
and a default can be set via a `default` argument to the `data` method.
|
397 |
+
|
398 |
+
The neighbor information is also provided by subscripting the graph.
|
399 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
400 |
+
|
401 |
+
For directed graphs, `G.adj` is identical to `G.succ`.
|
402 |
+
"""
|
403 |
+
return AdjacencyView(self._succ)
|
404 |
+
|
405 |
+
@cached_property
|
406 |
+
def pred(self):
|
407 |
+
"""Graph adjacency object holding the predecessors of each node.
|
408 |
+
|
409 |
+
This object is a read-only dict-like structure with node keys
|
410 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
411 |
+
to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
|
412 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
413 |
+
|
414 |
+
Iterating over G.pred behaves like a dict. Useful idioms include
|
415 |
+
`for nbr, datadict in G.pred[n].items():`. A data-view not provided
|
416 |
+
by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
|
417 |
+
A default can be set via a `default` argument to the `data` method.
|
418 |
+
"""
|
419 |
+
return AdjacencyView(self._pred)
|
420 |
+
|
421 |
+
def add_node(self, node_for_adding, **attr):
|
422 |
+
"""Add a single node `node_for_adding` and update node attributes.
|
423 |
+
|
424 |
+
Parameters
|
425 |
+
----------
|
426 |
+
node_for_adding : node
|
427 |
+
A node can be any hashable Python object except None.
|
428 |
+
attr : keyword arguments, optional
|
429 |
+
Set or change node attributes using key=value.
|
430 |
+
|
431 |
+
See Also
|
432 |
+
--------
|
433 |
+
add_nodes_from
|
434 |
+
|
435 |
+
Examples
|
436 |
+
--------
|
437 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
438 |
+
>>> G.add_node(1)
|
439 |
+
>>> G.add_node("Hello")
|
440 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
441 |
+
>>> G.add_node(K3)
|
442 |
+
>>> G.number_of_nodes()
|
443 |
+
3
|
444 |
+
|
445 |
+
Use keywords set/change node attributes:
|
446 |
+
|
447 |
+
>>> G.add_node(1, size=10)
|
448 |
+
>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
|
449 |
+
|
450 |
+
Notes
|
451 |
+
-----
|
452 |
+
A hashable object is one that can be used as a key in a Python
|
453 |
+
dictionary. This includes strings, numbers, tuples of strings
|
454 |
+
and numbers, etc.
|
455 |
+
|
456 |
+
On many platforms hashable items also include mutables such as
|
457 |
+
NetworkX Graphs, though one should be careful that the hash
|
458 |
+
doesn't change on mutables.
|
459 |
+
"""
|
460 |
+
if node_for_adding not in self._succ:
|
461 |
+
if node_for_adding is None:
|
462 |
+
raise ValueError("None cannot be a node")
|
463 |
+
self._succ[node_for_adding] = self.adjlist_inner_dict_factory()
|
464 |
+
self._pred[node_for_adding] = self.adjlist_inner_dict_factory()
|
465 |
+
attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
|
466 |
+
attr_dict.update(attr)
|
467 |
+
else: # update attr even if node already exists
|
468 |
+
self._node[node_for_adding].update(attr)
|
469 |
+
nx._clear_cache(self)
|
470 |
+
|
471 |
+
def add_nodes_from(self, nodes_for_adding, **attr):
|
472 |
+
"""Add multiple nodes.
|
473 |
+
|
474 |
+
Parameters
|
475 |
+
----------
|
476 |
+
nodes_for_adding : iterable container
|
477 |
+
A container of nodes (list, dict, set, etc.).
|
478 |
+
OR
|
479 |
+
A container of (node, attribute dict) tuples.
|
480 |
+
Node attributes are updated using the attribute dict.
|
481 |
+
attr : keyword arguments, optional (default= no attributes)
|
482 |
+
Update attributes for all nodes in nodes.
|
483 |
+
Node attributes specified in nodes as a tuple take
|
484 |
+
precedence over attributes specified via keyword arguments.
|
485 |
+
|
486 |
+
See Also
|
487 |
+
--------
|
488 |
+
add_node
|
489 |
+
|
490 |
+
Notes
|
491 |
+
-----
|
492 |
+
When adding nodes from an iterator over the graph you are changing,
|
493 |
+
a `RuntimeError` can be raised with message:
|
494 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
495 |
+
happens when the graph's underlying dictionary is modified during
|
496 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
497 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
498 |
+
object to `G.add_nodes_from`.
|
499 |
+
|
500 |
+
Examples
|
501 |
+
--------
|
502 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
503 |
+
>>> G.add_nodes_from("Hello")
|
504 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
505 |
+
>>> G.add_nodes_from(K3)
|
506 |
+
>>> sorted(G.nodes(), key=str)
|
507 |
+
[0, 1, 2, 'H', 'e', 'l', 'o']
|
508 |
+
|
509 |
+
Use keywords to update specific node attributes for every node.
|
510 |
+
|
511 |
+
>>> G.add_nodes_from([1, 2], size=10)
|
512 |
+
>>> G.add_nodes_from([3, 4], weight=0.4)
|
513 |
+
|
514 |
+
Use (node, attrdict) tuples to update attributes for specific nodes.
|
515 |
+
|
516 |
+
>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
|
517 |
+
>>> G.nodes[1]["size"]
|
518 |
+
11
|
519 |
+
>>> H = nx.Graph()
|
520 |
+
>>> H.add_nodes_from(G.nodes(data=True))
|
521 |
+
>>> H.nodes[1]["size"]
|
522 |
+
11
|
523 |
+
|
524 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
525 |
+
|
526 |
+
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
|
527 |
+
>>> # wrong way - will raise RuntimeError
|
528 |
+
>>> # G.add_nodes_from(n + 1 for n in G.nodes)
|
529 |
+
>>> # correct way
|
530 |
+
>>> G.add_nodes_from(list(n + 1 for n in G.nodes))
|
531 |
+
"""
|
532 |
+
for n in nodes_for_adding:
|
533 |
+
try:
|
534 |
+
newnode = n not in self._node
|
535 |
+
newdict = attr
|
536 |
+
except TypeError:
|
537 |
+
n, ndict = n
|
538 |
+
newnode = n not in self._node
|
539 |
+
newdict = attr.copy()
|
540 |
+
newdict.update(ndict)
|
541 |
+
if newnode:
|
542 |
+
if n is None:
|
543 |
+
raise ValueError("None cannot be a node")
|
544 |
+
self._succ[n] = self.adjlist_inner_dict_factory()
|
545 |
+
self._pred[n] = self.adjlist_inner_dict_factory()
|
546 |
+
self._node[n] = self.node_attr_dict_factory()
|
547 |
+
self._node[n].update(newdict)
|
548 |
+
nx._clear_cache(self)
|
549 |
+
|
550 |
+
def remove_node(self, n):
|
551 |
+
"""Remove node n.
|
552 |
+
|
553 |
+
Removes the node n and all adjacent edges.
|
554 |
+
Attempting to remove a nonexistent node will raise an exception.
|
555 |
+
|
556 |
+
Parameters
|
557 |
+
----------
|
558 |
+
n : node
|
559 |
+
A node in the graph
|
560 |
+
|
561 |
+
Raises
|
562 |
+
------
|
563 |
+
NetworkXError
|
564 |
+
If n is not in the graph.
|
565 |
+
|
566 |
+
See Also
|
567 |
+
--------
|
568 |
+
remove_nodes_from
|
569 |
+
|
570 |
+
Examples
|
571 |
+
--------
|
572 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
573 |
+
>>> list(G.edges)
|
574 |
+
[(0, 1), (1, 2)]
|
575 |
+
>>> G.remove_node(1)
|
576 |
+
>>> list(G.edges)
|
577 |
+
[]
|
578 |
+
|
579 |
+
"""
|
580 |
+
try:
|
581 |
+
nbrs = self._succ[n]
|
582 |
+
del self._node[n]
|
583 |
+
except KeyError as err: # NetworkXError if n not in self
|
584 |
+
raise NetworkXError(f"The node {n} is not in the digraph.") from err
|
585 |
+
for u in nbrs:
|
586 |
+
del self._pred[u][n] # remove all edges n-u in digraph
|
587 |
+
del self._succ[n] # remove node from succ
|
588 |
+
for u in self._pred[n]:
|
589 |
+
del self._succ[u][n] # remove all edges n-u in digraph
|
590 |
+
del self._pred[n] # remove node from pred
|
591 |
+
nx._clear_cache(self)
|
592 |
+
|
593 |
+
def remove_nodes_from(self, nodes):
|
594 |
+
"""Remove multiple nodes.
|
595 |
+
|
596 |
+
Parameters
|
597 |
+
----------
|
598 |
+
nodes : iterable container
|
599 |
+
A container of nodes (list, dict, set, etc.). If a node
|
600 |
+
in the container is not in the graph it is silently ignored.
|
601 |
+
|
602 |
+
See Also
|
603 |
+
--------
|
604 |
+
remove_node
|
605 |
+
|
606 |
+
Notes
|
607 |
+
-----
|
608 |
+
When removing nodes from an iterator over the graph you are changing,
|
609 |
+
a `RuntimeError` will be raised with message:
|
610 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
611 |
+
happens when the graph's underlying dictionary is modified during
|
612 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
613 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
614 |
+
object to `G.remove_nodes_from`.
|
615 |
+
|
616 |
+
Examples
|
617 |
+
--------
|
618 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
619 |
+
>>> e = list(G.nodes)
|
620 |
+
>>> e
|
621 |
+
[0, 1, 2]
|
622 |
+
>>> G.remove_nodes_from(e)
|
623 |
+
>>> list(G.nodes)
|
624 |
+
[]
|
625 |
+
|
626 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
627 |
+
|
628 |
+
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
|
629 |
+
>>> # this command will fail, as the graph's dict is modified during iteration
|
630 |
+
>>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
|
631 |
+
>>> # this command will work, since the dictionary underlying graph is not modified
|
632 |
+
>>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
|
633 |
+
"""
|
634 |
+
for n in nodes:
|
635 |
+
try:
|
636 |
+
succs = self._succ[n]
|
637 |
+
del self._node[n]
|
638 |
+
for u in succs:
|
639 |
+
del self._pred[u][n] # remove all edges n-u in digraph
|
640 |
+
del self._succ[n] # now remove node
|
641 |
+
for u in self._pred[n]:
|
642 |
+
del self._succ[u][n] # remove all edges n-u in digraph
|
643 |
+
del self._pred[n] # now remove node
|
644 |
+
except KeyError:
|
645 |
+
pass # silent failure on remove
|
646 |
+
nx._clear_cache(self)
|
647 |
+
|
648 |
+
def add_edge(self, u_of_edge, v_of_edge, **attr):
|
649 |
+
"""Add an edge between u and v.
|
650 |
+
|
651 |
+
The nodes u and v will be automatically added if they are
|
652 |
+
not already in the graph.
|
653 |
+
|
654 |
+
Edge attributes can be specified with keywords or by directly
|
655 |
+
accessing the edge's attribute dictionary. See examples below.
|
656 |
+
|
657 |
+
Parameters
|
658 |
+
----------
|
659 |
+
u_of_edge, v_of_edge : nodes
|
660 |
+
Nodes can be, for example, strings or numbers.
|
661 |
+
Nodes must be hashable (and not None) Python objects.
|
662 |
+
attr : keyword arguments, optional
|
663 |
+
Edge data (or labels or objects) can be assigned using
|
664 |
+
keyword arguments.
|
665 |
+
|
666 |
+
See Also
|
667 |
+
--------
|
668 |
+
add_edges_from : add a collection of edges
|
669 |
+
|
670 |
+
Notes
|
671 |
+
-----
|
672 |
+
Adding an edge that already exists updates the edge data.
|
673 |
+
|
674 |
+
Many NetworkX algorithms designed for weighted graphs use
|
675 |
+
an edge attribute (by default `weight`) to hold a numerical value.
|
676 |
+
|
677 |
+
Examples
|
678 |
+
--------
|
679 |
+
The following all add the edge e=(1, 2) to graph G:
|
680 |
+
|
681 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
682 |
+
>>> e = (1, 2)
|
683 |
+
>>> G.add_edge(1, 2) # explicit two-node form
|
684 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
685 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
686 |
+
|
687 |
+
Associate data to edges using keywords:
|
688 |
+
|
689 |
+
>>> G.add_edge(1, 2, weight=3)
|
690 |
+
>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
691 |
+
|
692 |
+
For non-string attribute keys, use subscript notation.
|
693 |
+
|
694 |
+
>>> G.add_edge(1, 2)
|
695 |
+
>>> G[1][2].update({0: 5})
|
696 |
+
>>> G.edges[1, 2].update({0: 5})
|
697 |
+
"""
|
698 |
+
u, v = u_of_edge, v_of_edge
|
699 |
+
# add nodes
|
700 |
+
if u not in self._succ:
|
701 |
+
if u is None:
|
702 |
+
raise ValueError("None cannot be a node")
|
703 |
+
self._succ[u] = self.adjlist_inner_dict_factory()
|
704 |
+
self._pred[u] = self.adjlist_inner_dict_factory()
|
705 |
+
self._node[u] = self.node_attr_dict_factory()
|
706 |
+
if v not in self._succ:
|
707 |
+
if v is None:
|
708 |
+
raise ValueError("None cannot be a node")
|
709 |
+
self._succ[v] = self.adjlist_inner_dict_factory()
|
710 |
+
self._pred[v] = self.adjlist_inner_dict_factory()
|
711 |
+
self._node[v] = self.node_attr_dict_factory()
|
712 |
+
# add the edge
|
713 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
714 |
+
datadict.update(attr)
|
715 |
+
self._succ[u][v] = datadict
|
716 |
+
self._pred[v][u] = datadict
|
717 |
+
nx._clear_cache(self)
|
718 |
+
|
719 |
+
def add_edges_from(self, ebunch_to_add, **attr):
|
720 |
+
"""Add all the edges in ebunch_to_add.
|
721 |
+
|
722 |
+
Parameters
|
723 |
+
----------
|
724 |
+
ebunch_to_add : container of edges
|
725 |
+
Each edge given in the container will be added to the
|
726 |
+
graph. The edges must be given as 2-tuples (u, v) or
|
727 |
+
3-tuples (u, v, d) where d is a dictionary containing edge data.
|
728 |
+
attr : keyword arguments, optional
|
729 |
+
Edge data (or labels or objects) can be assigned using
|
730 |
+
keyword arguments.
|
731 |
+
|
732 |
+
See Also
|
733 |
+
--------
|
734 |
+
add_edge : add a single edge
|
735 |
+
add_weighted_edges_from : convenient way to add weighted edges
|
736 |
+
|
737 |
+
Notes
|
738 |
+
-----
|
739 |
+
Adding the same edge twice has no effect but any edge data
|
740 |
+
will be updated when each duplicate edge is added.
|
741 |
+
|
742 |
+
Edge attributes specified in an ebunch take precedence over
|
743 |
+
attributes specified via keyword arguments.
|
744 |
+
|
745 |
+
When adding edges from an iterator over the graph you are changing,
|
746 |
+
a `RuntimeError` can be raised with message:
|
747 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
748 |
+
happens when the graph's underlying dictionary is modified during
|
749 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
750 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
751 |
+
object to `G.add_edges_from`.
|
752 |
+
|
753 |
+
Examples
|
754 |
+
--------
|
755 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
756 |
+
>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
|
757 |
+
>>> e = zip(range(0, 3), range(1, 4))
|
758 |
+
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3
|
759 |
+
|
760 |
+
Associate data to edges
|
761 |
+
|
762 |
+
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
|
763 |
+
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
|
764 |
+
|
765 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
766 |
+
|
767 |
+
>>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
|
768 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
769 |
+
>>> # wrong way - will raise RuntimeError
|
770 |
+
>>> # G.add_edges_from(((5, n) for n in G.nodes))
|
771 |
+
>>> # right way - note that there will be no self-edge for node 5
|
772 |
+
>>> G.add_edges_from(list((5, n) for n in G.nodes))
|
773 |
+
"""
|
774 |
+
for e in ebunch_to_add:
|
775 |
+
ne = len(e)
|
776 |
+
if ne == 3:
|
777 |
+
u, v, dd = e
|
778 |
+
elif ne == 2:
|
779 |
+
u, v = e
|
780 |
+
dd = {}
|
781 |
+
else:
|
782 |
+
raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
|
783 |
+
if u not in self._succ:
|
784 |
+
if u is None:
|
785 |
+
raise ValueError("None cannot be a node")
|
786 |
+
self._succ[u] = self.adjlist_inner_dict_factory()
|
787 |
+
self._pred[u] = self.adjlist_inner_dict_factory()
|
788 |
+
self._node[u] = self.node_attr_dict_factory()
|
789 |
+
if v not in self._succ:
|
790 |
+
if v is None:
|
791 |
+
raise ValueError("None cannot be a node")
|
792 |
+
self._succ[v] = self.adjlist_inner_dict_factory()
|
793 |
+
self._pred[v] = self.adjlist_inner_dict_factory()
|
794 |
+
self._node[v] = self.node_attr_dict_factory()
|
795 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
796 |
+
datadict.update(attr)
|
797 |
+
datadict.update(dd)
|
798 |
+
self._succ[u][v] = datadict
|
799 |
+
self._pred[v][u] = datadict
|
800 |
+
nx._clear_cache(self)
|
801 |
+
|
802 |
+
def remove_edge(self, u, v):
|
803 |
+
"""Remove the edge between u and v.
|
804 |
+
|
805 |
+
Parameters
|
806 |
+
----------
|
807 |
+
u, v : nodes
|
808 |
+
Remove the edge between nodes u and v.
|
809 |
+
|
810 |
+
Raises
|
811 |
+
------
|
812 |
+
NetworkXError
|
813 |
+
If there is not an edge between u and v.
|
814 |
+
|
815 |
+
See Also
|
816 |
+
--------
|
817 |
+
remove_edges_from : remove a collection of edges
|
818 |
+
|
819 |
+
Examples
|
820 |
+
--------
|
821 |
+
>>> G = nx.Graph() # or DiGraph, etc
|
822 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
823 |
+
>>> G.remove_edge(0, 1)
|
824 |
+
>>> e = (1, 2)
|
825 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
826 |
+
>>> e = (2, 3, {"weight": 7}) # an edge with attribute data
|
827 |
+
>>> G.remove_edge(*e[:2]) # select first part of edge tuple
|
828 |
+
"""
|
829 |
+
try:
|
830 |
+
del self._succ[u][v]
|
831 |
+
del self._pred[v][u]
|
832 |
+
except KeyError as err:
|
833 |
+
raise NetworkXError(f"The edge {u}-{v} not in graph.") from err
|
834 |
+
nx._clear_cache(self)
|
835 |
+
|
836 |
+
def remove_edges_from(self, ebunch):
|
837 |
+
"""Remove all edges specified in ebunch.
|
838 |
+
|
839 |
+
Parameters
|
840 |
+
----------
|
841 |
+
ebunch: list or container of edge tuples
|
842 |
+
Each edge given in the list or container will be removed
|
843 |
+
from the graph. The edges can be:
|
844 |
+
|
845 |
+
- 2-tuples (u, v) edge between u and v.
|
846 |
+
- 3-tuples (u, v, k) where k is ignored.
|
847 |
+
|
848 |
+
See Also
|
849 |
+
--------
|
850 |
+
remove_edge : remove a single edge
|
851 |
+
|
852 |
+
Notes
|
853 |
+
-----
|
854 |
+
Will fail silently if an edge in ebunch is not in the graph.
|
855 |
+
|
856 |
+
Examples
|
857 |
+
--------
|
858 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
859 |
+
>>> ebunch = [(1, 2), (2, 3)]
|
860 |
+
>>> G.remove_edges_from(ebunch)
|
861 |
+
"""
|
862 |
+
for e in ebunch:
|
863 |
+
u, v = e[:2] # ignore edge data
|
864 |
+
if u in self._succ and v in self._succ[u]:
|
865 |
+
del self._succ[u][v]
|
866 |
+
del self._pred[v][u]
|
867 |
+
nx._clear_cache(self)
|
868 |
+
|
869 |
+
def has_successor(self, u, v):
|
870 |
+
"""Returns True if node u has successor v.
|
871 |
+
|
872 |
+
This is true if graph has the edge u->v.
|
873 |
+
"""
|
874 |
+
return u in self._succ and v in self._succ[u]
|
875 |
+
|
876 |
+
def has_predecessor(self, u, v):
|
877 |
+
"""Returns True if node u has predecessor v.
|
878 |
+
|
879 |
+
This is true if graph has the edge u<-v.
|
880 |
+
"""
|
881 |
+
return u in self._pred and v in self._pred[u]
|
882 |
+
|
883 |
+
def successors(self, n):
|
884 |
+
"""Returns an iterator over successor nodes of n.
|
885 |
+
|
886 |
+
A successor of n is a node m such that there exists a directed
|
887 |
+
edge from n to m.
|
888 |
+
|
889 |
+
Parameters
|
890 |
+
----------
|
891 |
+
n : node
|
892 |
+
A node in the graph
|
893 |
+
|
894 |
+
Raises
|
895 |
+
------
|
896 |
+
NetworkXError
|
897 |
+
If n is not in the graph.
|
898 |
+
|
899 |
+
See Also
|
900 |
+
--------
|
901 |
+
predecessors
|
902 |
+
|
903 |
+
Notes
|
904 |
+
-----
|
905 |
+
neighbors() and successors() are the same.
|
906 |
+
"""
|
907 |
+
try:
|
908 |
+
return iter(self._succ[n])
|
909 |
+
except KeyError as err:
|
910 |
+
raise NetworkXError(f"The node {n} is not in the digraph.") from err
|
911 |
+
|
912 |
+
# digraph definitions
|
913 |
+
neighbors = successors
|
914 |
+
|
915 |
+
def predecessors(self, n):
|
916 |
+
"""Returns an iterator over predecessor nodes of n.
|
917 |
+
|
918 |
+
A predecessor of n is a node m such that there exists a directed
|
919 |
+
edge from m to n.
|
920 |
+
|
921 |
+
Parameters
|
922 |
+
----------
|
923 |
+
n : node
|
924 |
+
A node in the graph
|
925 |
+
|
926 |
+
Raises
|
927 |
+
------
|
928 |
+
NetworkXError
|
929 |
+
If n is not in the graph.
|
930 |
+
|
931 |
+
See Also
|
932 |
+
--------
|
933 |
+
successors
|
934 |
+
"""
|
935 |
+
try:
|
936 |
+
return iter(self._pred[n])
|
937 |
+
except KeyError as err:
|
938 |
+
raise NetworkXError(f"The node {n} is not in the digraph.") from err
|
939 |
+
|
940 |
+
@cached_property
|
941 |
+
def edges(self):
|
942 |
+
"""An OutEdgeView of the DiGraph as G.edges or G.edges().
|
943 |
+
|
944 |
+
edges(self, nbunch=None, data=False, default=None)
|
945 |
+
|
946 |
+
The OutEdgeView provides set-like operations on the edge-tuples
|
947 |
+
as well as edge attribute lookup. When called, it also provides
|
948 |
+
an EdgeDataView object which allows control of access to edge
|
949 |
+
attributes (but does not provide set-like operations).
|
950 |
+
Hence, `G.edges[u, v]['color']` provides the value of the color
|
951 |
+
attribute for edge `(u, v)` while
|
952 |
+
`for (u, v, c) in G.edges.data('color', default='red'):`
|
953 |
+
iterates through all the edges yielding the color attribute
|
954 |
+
with default `'red'` if no color attribute exists.
|
955 |
+
|
956 |
+
Parameters
|
957 |
+
----------
|
958 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
959 |
+
The view will only report edges from these nodes.
|
960 |
+
data : string or bool, optional (default=False)
|
961 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
962 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
963 |
+
If False, return 2-tuple (u, v).
|
964 |
+
default : value, optional (default=None)
|
965 |
+
Value used for edges that don't have the requested attribute.
|
966 |
+
Only relevant if data is not True or False.
|
967 |
+
|
968 |
+
Returns
|
969 |
+
-------
|
970 |
+
edges : OutEdgeView
|
971 |
+
A view of edge attributes, usually it iterates over (u, v)
|
972 |
+
or (u, v, d) tuples of edges, but can also be used for
|
973 |
+
attribute lookup as `edges[u, v]['foo']`.
|
974 |
+
|
975 |
+
See Also
|
976 |
+
--------
|
977 |
+
in_edges, out_edges
|
978 |
+
|
979 |
+
Notes
|
980 |
+
-----
|
981 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
982 |
+
For directed graphs this returns the out-edges.
|
983 |
+
|
984 |
+
Examples
|
985 |
+
--------
|
986 |
+
>>> G = nx.DiGraph() # or MultiDiGraph, etc
|
987 |
+
>>> nx.add_path(G, [0, 1, 2])
|
988 |
+
>>> G.add_edge(2, 3, weight=5)
|
989 |
+
>>> [e for e in G.edges]
|
990 |
+
[(0, 1), (1, 2), (2, 3)]
|
991 |
+
>>> G.edges.data() # default data is {} (empty dict)
|
992 |
+
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
|
993 |
+
>>> G.edges.data("weight", default=1)
|
994 |
+
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
|
995 |
+
>>> G.edges([0, 2]) # only edges originating from these nodes
|
996 |
+
OutEdgeDataView([(0, 1), (2, 3)])
|
997 |
+
>>> G.edges(0) # only edges from node 0
|
998 |
+
OutEdgeDataView([(0, 1)])
|
999 |
+
|
1000 |
+
"""
|
1001 |
+
return OutEdgeView(self)
|
1002 |
+
|
1003 |
+
# alias out_edges to edges
|
1004 |
+
@cached_property
|
1005 |
+
def out_edges(self):
|
1006 |
+
return OutEdgeView(self)
|
1007 |
+
|
1008 |
+
out_edges.__doc__ = edges.__doc__
|
1009 |
+
|
1010 |
+
@cached_property
|
1011 |
+
def in_edges(self):
|
1012 |
+
"""A view of the in edges of the graph as G.in_edges or G.in_edges().
|
1013 |
+
|
1014 |
+
in_edges(self, nbunch=None, data=False, default=None):
|
1015 |
+
|
1016 |
+
Parameters
|
1017 |
+
----------
|
1018 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1019 |
+
The view will only report edges incident to these nodes.
|
1020 |
+
data : string or bool, optional (default=False)
|
1021 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
1022 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
1023 |
+
If False, return 2-tuple (u, v).
|
1024 |
+
default : value, optional (default=None)
|
1025 |
+
Value used for edges that don't have the requested attribute.
|
1026 |
+
Only relevant if data is not True or False.
|
1027 |
+
|
1028 |
+
Returns
|
1029 |
+
-------
|
1030 |
+
in_edges : InEdgeView or InEdgeDataView
|
1031 |
+
A view of edge attributes, usually it iterates over (u, v)
|
1032 |
+
or (u, v, d) tuples of edges, but can also be used for
|
1033 |
+
attribute lookup as `edges[u, v]['foo']`.
|
1034 |
+
|
1035 |
+
Examples
|
1036 |
+
--------
|
1037 |
+
>>> G = nx.DiGraph()
|
1038 |
+
>>> G.add_edge(1, 2, color="blue")
|
1039 |
+
>>> G.in_edges()
|
1040 |
+
InEdgeView([(1, 2)])
|
1041 |
+
>>> G.in_edges(nbunch=2)
|
1042 |
+
InEdgeDataView([(1, 2)])
|
1043 |
+
|
1044 |
+
See Also
|
1045 |
+
--------
|
1046 |
+
edges
|
1047 |
+
"""
|
1048 |
+
return InEdgeView(self)
|
1049 |
+
|
1050 |
+
@cached_property
|
1051 |
+
def degree(self):
|
1052 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
1053 |
+
|
1054 |
+
The node degree is the number of edges adjacent to the node.
|
1055 |
+
The weighted node degree is the sum of the edge weights for
|
1056 |
+
edges incident to that node.
|
1057 |
+
|
1058 |
+
This object provides an iterator for (node, degree) as well as
|
1059 |
+
lookup for the degree for a single node.
|
1060 |
+
|
1061 |
+
Parameters
|
1062 |
+
----------
|
1063 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1064 |
+
The view will only report edges incident to these nodes.
|
1065 |
+
|
1066 |
+
weight : string or None, optional (default=None)
|
1067 |
+
The name of an edge attribute that holds the numerical value used
|
1068 |
+
as a weight. If None, then each edge has weight 1.
|
1069 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1070 |
+
|
1071 |
+
Returns
|
1072 |
+
-------
|
1073 |
+
DiDegreeView or int
|
1074 |
+
If multiple nodes are requested (the default), returns a `DiDegreeView`
|
1075 |
+
mapping nodes to their degree.
|
1076 |
+
If a single node is requested, returns the degree of the node as an integer.
|
1077 |
+
|
1078 |
+
See Also
|
1079 |
+
--------
|
1080 |
+
in_degree, out_degree
|
1081 |
+
|
1082 |
+
Examples
|
1083 |
+
--------
|
1084 |
+
>>> G = nx.DiGraph() # or MultiDiGraph
|
1085 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1086 |
+
>>> G.degree(0) # node 0 with degree 1
|
1087 |
+
1
|
1088 |
+
>>> list(G.degree([0, 1, 2]))
|
1089 |
+
[(0, 1), (1, 2), (2, 2)]
|
1090 |
+
|
1091 |
+
"""
|
1092 |
+
return DiDegreeView(self)
|
1093 |
+
|
1094 |
+
@cached_property
|
1095 |
+
def in_degree(self):
|
1096 |
+
"""An InDegreeView for (node, in_degree) or in_degree for single node.
|
1097 |
+
|
1098 |
+
The node in_degree is the number of edges pointing to the node.
|
1099 |
+
The weighted node degree is the sum of the edge weights for
|
1100 |
+
edges incident to that node.
|
1101 |
+
|
1102 |
+
This object provides an iteration over (node, in_degree) as well as
|
1103 |
+
lookup for the degree for a single node.
|
1104 |
+
|
1105 |
+
Parameters
|
1106 |
+
----------
|
1107 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1108 |
+
The view will only report edges incident to these nodes.
|
1109 |
+
|
1110 |
+
weight : string or None, optional (default=None)
|
1111 |
+
The name of an edge attribute that holds the numerical value used
|
1112 |
+
as a weight. If None, then each edge has weight 1.
|
1113 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1114 |
+
|
1115 |
+
Returns
|
1116 |
+
-------
|
1117 |
+
If a single node is requested
|
1118 |
+
deg : int
|
1119 |
+
In-degree of the node
|
1120 |
+
|
1121 |
+
OR if multiple nodes are requested
|
1122 |
+
nd_iter : iterator
|
1123 |
+
The iterator returns two-tuples of (node, in-degree).
|
1124 |
+
|
1125 |
+
See Also
|
1126 |
+
--------
|
1127 |
+
degree, out_degree
|
1128 |
+
|
1129 |
+
Examples
|
1130 |
+
--------
|
1131 |
+
>>> G = nx.DiGraph()
|
1132 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1133 |
+
>>> G.in_degree(0) # node 0 with degree 0
|
1134 |
+
0
|
1135 |
+
>>> list(G.in_degree([0, 1, 2]))
|
1136 |
+
[(0, 0), (1, 1), (2, 1)]
|
1137 |
+
|
1138 |
+
"""
|
1139 |
+
return InDegreeView(self)
|
1140 |
+
|
1141 |
+
@cached_property
|
1142 |
+
def out_degree(self):
|
1143 |
+
"""An OutDegreeView for (node, out_degree)
|
1144 |
+
|
1145 |
+
The node out_degree is the number of edges pointing out of the node.
|
1146 |
+
The weighted node degree is the sum of the edge weights for
|
1147 |
+
edges incident to that node.
|
1148 |
+
|
1149 |
+
This object provides an iterator over (node, out_degree) as well as
|
1150 |
+
lookup for the degree for a single node.
|
1151 |
+
|
1152 |
+
Parameters
|
1153 |
+
----------
|
1154 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1155 |
+
The view will only report edges incident to these nodes.
|
1156 |
+
|
1157 |
+
weight : string or None, optional (default=None)
|
1158 |
+
The name of an edge attribute that holds the numerical value used
|
1159 |
+
as a weight. If None, then each edge has weight 1.
|
1160 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1161 |
+
|
1162 |
+
Returns
|
1163 |
+
-------
|
1164 |
+
If a single node is requested
|
1165 |
+
deg : int
|
1166 |
+
Out-degree of the node
|
1167 |
+
|
1168 |
+
OR if multiple nodes are requested
|
1169 |
+
nd_iter : iterator
|
1170 |
+
The iterator returns two-tuples of (node, out-degree).
|
1171 |
+
|
1172 |
+
See Also
|
1173 |
+
--------
|
1174 |
+
degree, in_degree
|
1175 |
+
|
1176 |
+
Examples
|
1177 |
+
--------
|
1178 |
+
>>> G = nx.DiGraph()
|
1179 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1180 |
+
>>> G.out_degree(0) # node 0 with degree 1
|
1181 |
+
1
|
1182 |
+
>>> list(G.out_degree([0, 1, 2]))
|
1183 |
+
[(0, 1), (1, 1), (2, 1)]
|
1184 |
+
|
1185 |
+
"""
|
1186 |
+
return OutDegreeView(self)
|
1187 |
+
|
1188 |
+
def clear(self):
|
1189 |
+
"""Remove all nodes and edges from the graph.
|
1190 |
+
|
1191 |
+
This also removes the name, and all graph, node, and edge attributes.
|
1192 |
+
|
1193 |
+
Examples
|
1194 |
+
--------
|
1195 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1196 |
+
>>> G.clear()
|
1197 |
+
>>> list(G.nodes)
|
1198 |
+
[]
|
1199 |
+
>>> list(G.edges)
|
1200 |
+
[]
|
1201 |
+
|
1202 |
+
"""
|
1203 |
+
self._succ.clear()
|
1204 |
+
self._pred.clear()
|
1205 |
+
self._node.clear()
|
1206 |
+
self.graph.clear()
|
1207 |
+
nx._clear_cache(self)
|
1208 |
+
|
1209 |
+
def clear_edges(self):
|
1210 |
+
"""Remove all edges from the graph without altering nodes.
|
1211 |
+
|
1212 |
+
Examples
|
1213 |
+
--------
|
1214 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1215 |
+
>>> G.clear_edges()
|
1216 |
+
>>> list(G.nodes)
|
1217 |
+
[0, 1, 2, 3]
|
1218 |
+
>>> list(G.edges)
|
1219 |
+
[]
|
1220 |
+
|
1221 |
+
"""
|
1222 |
+
for predecessor_dict in self._pred.values():
|
1223 |
+
predecessor_dict.clear()
|
1224 |
+
for successor_dict in self._succ.values():
|
1225 |
+
successor_dict.clear()
|
1226 |
+
nx._clear_cache(self)
|
1227 |
+
|
1228 |
+
def is_multigraph(self):
|
1229 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
1230 |
+
return False
|
1231 |
+
|
1232 |
+
def is_directed(self):
|
1233 |
+
"""Returns True if graph is directed, False otherwise."""
|
1234 |
+
return True
|
1235 |
+
|
1236 |
+
def to_undirected(self, reciprocal=False, as_view=False):
|
1237 |
+
"""Returns an undirected representation of the digraph.
|
1238 |
+
|
1239 |
+
Parameters
|
1240 |
+
----------
|
1241 |
+
reciprocal : bool (optional)
|
1242 |
+
If True only keep edges that appear in both directions
|
1243 |
+
in the original digraph.
|
1244 |
+
as_view : bool (optional, default=False)
|
1245 |
+
If True return an undirected view of the original directed graph.
|
1246 |
+
|
1247 |
+
Returns
|
1248 |
+
-------
|
1249 |
+
G : Graph
|
1250 |
+
An undirected graph with the same name and nodes and
|
1251 |
+
with edge (u, v, data) if either (u, v, data) or (v, u, data)
|
1252 |
+
is in the digraph. If both edges exist in digraph and
|
1253 |
+
their edge data is different, only one edge is created
|
1254 |
+
with an arbitrary choice of which edge data to use.
|
1255 |
+
You must check and correct for this manually if desired.
|
1256 |
+
|
1257 |
+
See Also
|
1258 |
+
--------
|
1259 |
+
Graph, copy, add_edge, add_edges_from
|
1260 |
+
|
1261 |
+
Notes
|
1262 |
+
-----
|
1263 |
+
If edges in both directions (u, v) and (v, u) exist in the
|
1264 |
+
graph, attributes for the new undirected edge will be a combination of
|
1265 |
+
the attributes of the directed edges. The edge data is updated
|
1266 |
+
in the (arbitrary) order that the edges are encountered. For
|
1267 |
+
more customized control of the edge attributes use add_edge().
|
1268 |
+
|
1269 |
+
This returns a "deepcopy" of the edge, node, and
|
1270 |
+
graph attributes which attempts to completely copy
|
1271 |
+
all of the data and references.
|
1272 |
+
|
1273 |
+
This is in contrast to the similar G=DiGraph(D) which returns a
|
1274 |
+
shallow copy of the data.
|
1275 |
+
|
1276 |
+
See the Python copy module for more information on shallow
|
1277 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1278 |
+
|
1279 |
+
Warning: If you have subclassed DiGraph to use dict-like objects
|
1280 |
+
in the data structure, those changes do not transfer to the
|
1281 |
+
Graph created by this method.
|
1282 |
+
|
1283 |
+
Examples
|
1284 |
+
--------
|
1285 |
+
>>> G = nx.path_graph(2) # or MultiGraph, etc
|
1286 |
+
>>> H = G.to_directed()
|
1287 |
+
>>> list(H.edges)
|
1288 |
+
[(0, 1), (1, 0)]
|
1289 |
+
>>> G2 = H.to_undirected()
|
1290 |
+
>>> list(G2.edges)
|
1291 |
+
[(0, 1)]
|
1292 |
+
"""
|
1293 |
+
graph_class = self.to_undirected_class()
|
1294 |
+
if as_view is True:
|
1295 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1296 |
+
# deepcopy when not a view
|
1297 |
+
G = graph_class()
|
1298 |
+
G.graph.update(deepcopy(self.graph))
|
1299 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1300 |
+
if reciprocal is True:
|
1301 |
+
G.add_edges_from(
|
1302 |
+
(u, v, deepcopy(d))
|
1303 |
+
for u, nbrs in self._adj.items()
|
1304 |
+
for v, d in nbrs.items()
|
1305 |
+
if v in self._pred[u]
|
1306 |
+
)
|
1307 |
+
else:
|
1308 |
+
G.add_edges_from(
|
1309 |
+
(u, v, deepcopy(d))
|
1310 |
+
for u, nbrs in self._adj.items()
|
1311 |
+
for v, d in nbrs.items()
|
1312 |
+
)
|
1313 |
+
return G
|
1314 |
+
|
1315 |
+
def reverse(self, copy=True):
|
1316 |
+
"""Returns the reverse of the graph.
|
1317 |
+
|
1318 |
+
The reverse is a graph with the same nodes and edges
|
1319 |
+
but with the directions of the edges reversed.
|
1320 |
+
|
1321 |
+
Parameters
|
1322 |
+
----------
|
1323 |
+
copy : bool optional (default=True)
|
1324 |
+
If True, return a new DiGraph holding the reversed edges.
|
1325 |
+
If False, the reverse graph is created using a view of
|
1326 |
+
the original graph.
|
1327 |
+
"""
|
1328 |
+
if copy:
|
1329 |
+
H = self.__class__()
|
1330 |
+
H.graph.update(deepcopy(self.graph))
|
1331 |
+
H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items())
|
1332 |
+
H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True))
|
1333 |
+
return H
|
1334 |
+
return nx.reverse_view(self)
|
venv/lib/python3.10/site-packages/networkx/classes/filters.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Filter factories to hide or show sets of nodes and edges.
|
2 |
+
|
3 |
+
These filters return the function used when creating `SubGraph`.
|
4 |
+
"""
|
5 |
+
__all__ = [
|
6 |
+
"no_filter",
|
7 |
+
"hide_nodes",
|
8 |
+
"hide_edges",
|
9 |
+
"hide_multiedges",
|
10 |
+
"hide_diedges",
|
11 |
+
"hide_multidiedges",
|
12 |
+
"show_nodes",
|
13 |
+
"show_edges",
|
14 |
+
"show_multiedges",
|
15 |
+
"show_diedges",
|
16 |
+
"show_multidiedges",
|
17 |
+
]
|
18 |
+
|
19 |
+
|
20 |
+
def no_filter(*items):
|
21 |
+
"""Returns a filter function that always evaluates to True."""
|
22 |
+
return True
|
23 |
+
|
24 |
+
|
25 |
+
def hide_nodes(nodes):
|
26 |
+
"""Returns a filter function that hides specific nodes."""
|
27 |
+
nodes = set(nodes)
|
28 |
+
return lambda node: node not in nodes
|
29 |
+
|
30 |
+
|
31 |
+
def hide_diedges(edges):
|
32 |
+
"""Returns a filter function that hides specific directed edges."""
|
33 |
+
edges = {(u, v) for u, v in edges}
|
34 |
+
return lambda u, v: (u, v) not in edges
|
35 |
+
|
36 |
+
|
37 |
+
def hide_edges(edges):
|
38 |
+
"""Returns a filter function that hides specific undirected edges."""
|
39 |
+
alledges = set(edges) | {(v, u) for (u, v) in edges}
|
40 |
+
return lambda u, v: (u, v) not in alledges
|
41 |
+
|
42 |
+
|
43 |
+
def hide_multidiedges(edges):
|
44 |
+
"""Returns a filter function that hides specific multi-directed edges."""
|
45 |
+
edges = {(u, v, k) for u, v, k in edges}
|
46 |
+
return lambda u, v, k: (u, v, k) not in edges
|
47 |
+
|
48 |
+
|
49 |
+
def hide_multiedges(edges):
|
50 |
+
"""Returns a filter function that hides specific multi-undirected edges."""
|
51 |
+
alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
|
52 |
+
return lambda u, v, k: (u, v, k) not in alledges
|
53 |
+
|
54 |
+
|
55 |
+
# write show_nodes as a class to make SubGraph pickleable
|
56 |
+
class show_nodes:
|
57 |
+
"""Filter class to show specific nodes."""
|
58 |
+
|
59 |
+
def __init__(self, nodes):
|
60 |
+
self.nodes = set(nodes)
|
61 |
+
|
62 |
+
def __call__(self, node):
|
63 |
+
return node in self.nodes
|
64 |
+
|
65 |
+
|
66 |
+
def show_diedges(edges):
|
67 |
+
"""Returns a filter function that shows specific directed edges."""
|
68 |
+
edges = {(u, v) for u, v in edges}
|
69 |
+
return lambda u, v: (u, v) in edges
|
70 |
+
|
71 |
+
|
72 |
+
def show_edges(edges):
|
73 |
+
"""Returns a filter function that shows specific undirected edges."""
|
74 |
+
alledges = set(edges) | {(v, u) for (u, v) in edges}
|
75 |
+
return lambda u, v: (u, v) in alledges
|
76 |
+
|
77 |
+
|
78 |
+
def show_multidiedges(edges):
|
79 |
+
"""Returns a filter function that shows specific multi-directed edges."""
|
80 |
+
edges = {(u, v, k) for u, v, k in edges}
|
81 |
+
return lambda u, v, k: (u, v, k) in edges
|
82 |
+
|
83 |
+
|
84 |
+
def show_multiedges(edges):
|
85 |
+
"""Returns a filter function that shows specific multi-undirected edges."""
|
86 |
+
alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
|
87 |
+
return lambda u, v, k: (u, v, k) in alledges
|
venv/lib/python3.10/site-packages/networkx/classes/function.py
ADDED
@@ -0,0 +1,1335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Functional interface to graph methods and assorted utilities.
|
2 |
+
"""
|
3 |
+
|
4 |
+
from collections import Counter
|
5 |
+
from itertools import chain
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
from networkx.utils import not_implemented_for, pairwise
|
9 |
+
|
10 |
+
__all__ = [
|
11 |
+
"nodes",
|
12 |
+
"edges",
|
13 |
+
"degree",
|
14 |
+
"degree_histogram",
|
15 |
+
"neighbors",
|
16 |
+
"number_of_nodes",
|
17 |
+
"number_of_edges",
|
18 |
+
"density",
|
19 |
+
"is_directed",
|
20 |
+
"freeze",
|
21 |
+
"is_frozen",
|
22 |
+
"subgraph",
|
23 |
+
"induced_subgraph",
|
24 |
+
"edge_subgraph",
|
25 |
+
"restricted_view",
|
26 |
+
"to_directed",
|
27 |
+
"to_undirected",
|
28 |
+
"add_star",
|
29 |
+
"add_path",
|
30 |
+
"add_cycle",
|
31 |
+
"create_empty_copy",
|
32 |
+
"set_node_attributes",
|
33 |
+
"get_node_attributes",
|
34 |
+
"set_edge_attributes",
|
35 |
+
"get_edge_attributes",
|
36 |
+
"all_neighbors",
|
37 |
+
"non_neighbors",
|
38 |
+
"non_edges",
|
39 |
+
"common_neighbors",
|
40 |
+
"is_weighted",
|
41 |
+
"is_negatively_weighted",
|
42 |
+
"is_empty",
|
43 |
+
"selfloop_edges",
|
44 |
+
"nodes_with_selfloops",
|
45 |
+
"number_of_selfloops",
|
46 |
+
"path_weight",
|
47 |
+
"is_path",
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
def nodes(G):
|
52 |
+
"""Returns a NodeView over the graph nodes.
|
53 |
+
|
54 |
+
This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
|
55 |
+
"""
|
56 |
+
return G.nodes()
|
57 |
+
|
58 |
+
|
59 |
+
def edges(G, nbunch=None):
|
60 |
+
"""Returns an edge view of edges incident to nodes in nbunch.
|
61 |
+
|
62 |
+
Return all edges if nbunch is unspecified or nbunch=None.
|
63 |
+
|
64 |
+
For digraphs, edges=out_edges
|
65 |
+
|
66 |
+
This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
|
67 |
+
"""
|
68 |
+
return G.edges(nbunch)
|
69 |
+
|
70 |
+
|
71 |
+
def degree(G, nbunch=None, weight=None):
|
72 |
+
"""Returns a degree view of single node or of nbunch of nodes.
|
73 |
+
If nbunch is omitted, then return degrees of *all* nodes.
|
74 |
+
|
75 |
+
This function wraps the :func:`G.degree <networkx.Graph.degree>` property.
|
76 |
+
"""
|
77 |
+
return G.degree(nbunch, weight)
|
78 |
+
|
79 |
+
|
80 |
+
def neighbors(G, n):
|
81 |
+
"""Returns an iterator over all neighbors of node n.
|
82 |
+
|
83 |
+
This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
|
84 |
+
"""
|
85 |
+
return G.neighbors(n)
|
86 |
+
|
87 |
+
|
88 |
+
def number_of_nodes(G):
|
89 |
+
"""Returns the number of nodes in the graph.
|
90 |
+
|
91 |
+
This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
|
92 |
+
"""
|
93 |
+
return G.number_of_nodes()
|
94 |
+
|
95 |
+
|
96 |
+
def number_of_edges(G):
|
97 |
+
"""Returns the number of edges in the graph.
|
98 |
+
|
99 |
+
This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
|
100 |
+
"""
|
101 |
+
return G.number_of_edges()
|
102 |
+
|
103 |
+
|
104 |
+
def density(G):
|
105 |
+
r"""Returns the density of a graph.
|
106 |
+
|
107 |
+
The density for undirected graphs is
|
108 |
+
|
109 |
+
.. math::
|
110 |
+
|
111 |
+
d = \frac{2m}{n(n-1)},
|
112 |
+
|
113 |
+
and for directed graphs is
|
114 |
+
|
115 |
+
.. math::
|
116 |
+
|
117 |
+
d = \frac{m}{n(n-1)},
|
118 |
+
|
119 |
+
where `n` is the number of nodes and `m` is the number of edges in `G`.
|
120 |
+
|
121 |
+
Notes
|
122 |
+
-----
|
123 |
+
The density is 0 for a graph without edges and 1 for a complete graph.
|
124 |
+
The density of multigraphs can be higher than 1.
|
125 |
+
|
126 |
+
Self loops are counted in the total number of edges so graphs with self
|
127 |
+
loops can have density higher than 1.
|
128 |
+
"""
|
129 |
+
n = number_of_nodes(G)
|
130 |
+
m = number_of_edges(G)
|
131 |
+
if m == 0 or n <= 1:
|
132 |
+
return 0
|
133 |
+
d = m / (n * (n - 1))
|
134 |
+
if not G.is_directed():
|
135 |
+
d *= 2
|
136 |
+
return d
|
137 |
+
|
138 |
+
|
139 |
+
def degree_histogram(G):
|
140 |
+
"""Returns a list of the frequency of each degree value.
|
141 |
+
|
142 |
+
Parameters
|
143 |
+
----------
|
144 |
+
G : Networkx graph
|
145 |
+
A graph
|
146 |
+
|
147 |
+
Returns
|
148 |
+
-------
|
149 |
+
hist : list
|
150 |
+
A list of frequencies of degrees.
|
151 |
+
The degree values are the index in the list.
|
152 |
+
|
153 |
+
Notes
|
154 |
+
-----
|
155 |
+
Note: the bins are width one, hence len(list) can be large
|
156 |
+
(Order(number_of_edges))
|
157 |
+
"""
|
158 |
+
counts = Counter(d for n, d in G.degree())
|
159 |
+
return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
|
160 |
+
|
161 |
+
|
162 |
+
def is_directed(G):
|
163 |
+
"""Return True if graph is directed."""
|
164 |
+
return G.is_directed()
|
165 |
+
|
166 |
+
|
167 |
+
def frozen(*args, **kwargs):
|
168 |
+
"""Dummy method for raising errors when trying to modify frozen graphs"""
|
169 |
+
raise nx.NetworkXError("Frozen graph can't be modified")
|
170 |
+
|
171 |
+
|
172 |
+
def freeze(G):
|
173 |
+
"""Modify graph to prevent further change by adding or removing
|
174 |
+
nodes or edges.
|
175 |
+
|
176 |
+
Node and edge data can still be modified.
|
177 |
+
|
178 |
+
Parameters
|
179 |
+
----------
|
180 |
+
G : graph
|
181 |
+
A NetworkX graph
|
182 |
+
|
183 |
+
Examples
|
184 |
+
--------
|
185 |
+
>>> G = nx.path_graph(4)
|
186 |
+
>>> G = nx.freeze(G)
|
187 |
+
>>> try:
|
188 |
+
... G.add_edge(4, 5)
|
189 |
+
... except nx.NetworkXError as err:
|
190 |
+
... print(str(err))
|
191 |
+
Frozen graph can't be modified
|
192 |
+
|
193 |
+
Notes
|
194 |
+
-----
|
195 |
+
To "unfreeze" a graph you must make a copy by creating a new graph object:
|
196 |
+
|
197 |
+
>>> graph = nx.path_graph(4)
|
198 |
+
>>> frozen_graph = nx.freeze(graph)
|
199 |
+
>>> unfrozen_graph = nx.Graph(frozen_graph)
|
200 |
+
>>> nx.is_frozen(unfrozen_graph)
|
201 |
+
False
|
202 |
+
|
203 |
+
See Also
|
204 |
+
--------
|
205 |
+
is_frozen
|
206 |
+
"""
|
207 |
+
G.add_node = frozen
|
208 |
+
G.add_nodes_from = frozen
|
209 |
+
G.remove_node = frozen
|
210 |
+
G.remove_nodes_from = frozen
|
211 |
+
G.add_edge = frozen
|
212 |
+
G.add_edges_from = frozen
|
213 |
+
G.add_weighted_edges_from = frozen
|
214 |
+
G.remove_edge = frozen
|
215 |
+
G.remove_edges_from = frozen
|
216 |
+
G.clear = frozen
|
217 |
+
G.clear_edges = frozen
|
218 |
+
G.frozen = True
|
219 |
+
return G
|
220 |
+
|
221 |
+
|
222 |
+
def is_frozen(G):
|
223 |
+
"""Returns True if graph is frozen.
|
224 |
+
|
225 |
+
Parameters
|
226 |
+
----------
|
227 |
+
G : graph
|
228 |
+
A NetworkX graph
|
229 |
+
|
230 |
+
See Also
|
231 |
+
--------
|
232 |
+
freeze
|
233 |
+
"""
|
234 |
+
try:
|
235 |
+
return G.frozen
|
236 |
+
except AttributeError:
|
237 |
+
return False
|
238 |
+
|
239 |
+
|
240 |
+
def add_star(G_to_add_to, nodes_for_star, **attr):
|
241 |
+
"""Add a star to Graph G_to_add_to.
|
242 |
+
|
243 |
+
The first node in `nodes_for_star` is the middle of the star.
|
244 |
+
It is connected to all other nodes.
|
245 |
+
|
246 |
+
Parameters
|
247 |
+
----------
|
248 |
+
G_to_add_to : graph
|
249 |
+
A NetworkX graph
|
250 |
+
nodes_for_star : iterable container
|
251 |
+
A container of nodes.
|
252 |
+
attr : keyword arguments, optional (default= no attributes)
|
253 |
+
Attributes to add to every edge in star.
|
254 |
+
|
255 |
+
See Also
|
256 |
+
--------
|
257 |
+
add_path, add_cycle
|
258 |
+
|
259 |
+
Examples
|
260 |
+
--------
|
261 |
+
>>> G = nx.Graph()
|
262 |
+
>>> nx.add_star(G, [0, 1, 2, 3])
|
263 |
+
>>> nx.add_star(G, [10, 11, 12], weight=2)
|
264 |
+
"""
|
265 |
+
nlist = iter(nodes_for_star)
|
266 |
+
try:
|
267 |
+
v = next(nlist)
|
268 |
+
except StopIteration:
|
269 |
+
return
|
270 |
+
G_to_add_to.add_node(v)
|
271 |
+
edges = ((v, n) for n in nlist)
|
272 |
+
G_to_add_to.add_edges_from(edges, **attr)
|
273 |
+
|
274 |
+
|
275 |
+
def add_path(G_to_add_to, nodes_for_path, **attr):
|
276 |
+
"""Add a path to the Graph G_to_add_to.
|
277 |
+
|
278 |
+
Parameters
|
279 |
+
----------
|
280 |
+
G_to_add_to : graph
|
281 |
+
A NetworkX graph
|
282 |
+
nodes_for_path : iterable container
|
283 |
+
A container of nodes. A path will be constructed from
|
284 |
+
the nodes (in order) and added to the graph.
|
285 |
+
attr : keyword arguments, optional (default= no attributes)
|
286 |
+
Attributes to add to every edge in path.
|
287 |
+
|
288 |
+
See Also
|
289 |
+
--------
|
290 |
+
add_star, add_cycle
|
291 |
+
|
292 |
+
Examples
|
293 |
+
--------
|
294 |
+
>>> G = nx.Graph()
|
295 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
296 |
+
>>> nx.add_path(G, [10, 11, 12], weight=7)
|
297 |
+
"""
|
298 |
+
nlist = iter(nodes_for_path)
|
299 |
+
try:
|
300 |
+
first_node = next(nlist)
|
301 |
+
except StopIteration:
|
302 |
+
return
|
303 |
+
G_to_add_to.add_node(first_node)
|
304 |
+
G_to_add_to.add_edges_from(pairwise(chain((first_node,), nlist)), **attr)
|
305 |
+
|
306 |
+
|
307 |
+
def add_cycle(G_to_add_to, nodes_for_cycle, **attr):
|
308 |
+
"""Add a cycle to the Graph G_to_add_to.
|
309 |
+
|
310 |
+
Parameters
|
311 |
+
----------
|
312 |
+
G_to_add_to : graph
|
313 |
+
A NetworkX graph
|
314 |
+
nodes_for_cycle: iterable container
|
315 |
+
A container of nodes. A cycle will be constructed from
|
316 |
+
the nodes (in order) and added to the graph.
|
317 |
+
attr : keyword arguments, optional (default= no attributes)
|
318 |
+
Attributes to add to every edge in cycle.
|
319 |
+
|
320 |
+
See Also
|
321 |
+
--------
|
322 |
+
add_path, add_star
|
323 |
+
|
324 |
+
Examples
|
325 |
+
--------
|
326 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
327 |
+
>>> nx.add_cycle(G, [0, 1, 2, 3])
|
328 |
+
>>> nx.add_cycle(G, [10, 11, 12], weight=7)
|
329 |
+
"""
|
330 |
+
nlist = iter(nodes_for_cycle)
|
331 |
+
try:
|
332 |
+
first_node = next(nlist)
|
333 |
+
except StopIteration:
|
334 |
+
return
|
335 |
+
G_to_add_to.add_node(first_node)
|
336 |
+
G_to_add_to.add_edges_from(
|
337 |
+
pairwise(chain((first_node,), nlist), cyclic=True), **attr
|
338 |
+
)
|
339 |
+
|
340 |
+
|
341 |
+
def subgraph(G, nbunch):
|
342 |
+
"""Returns the subgraph induced on nodes in nbunch.
|
343 |
+
|
344 |
+
Parameters
|
345 |
+
----------
|
346 |
+
G : graph
|
347 |
+
A NetworkX graph
|
348 |
+
|
349 |
+
nbunch : list, iterable
|
350 |
+
A container of nodes that will be iterated through once (thus
|
351 |
+
it should be an iterator or be iterable). Each element of the
|
352 |
+
container should be a valid node type: any hashable type except
|
353 |
+
None. If nbunch is None, return all edges data in the graph.
|
354 |
+
Nodes in nbunch that are not in the graph will be (quietly)
|
355 |
+
ignored.
|
356 |
+
|
357 |
+
Notes
|
358 |
+
-----
|
359 |
+
subgraph(G) calls G.subgraph()
|
360 |
+
"""
|
361 |
+
return G.subgraph(nbunch)
|
362 |
+
|
363 |
+
|
364 |
+
def induced_subgraph(G, nbunch):
|
365 |
+
"""Returns a SubGraph view of `G` showing only nodes in nbunch.
|
366 |
+
|
367 |
+
The induced subgraph of a graph on a set of nodes N is the
|
368 |
+
graph with nodes N and edges from G which have both ends in N.
|
369 |
+
|
370 |
+
Parameters
|
371 |
+
----------
|
372 |
+
G : NetworkX Graph
|
373 |
+
nbunch : node, container of nodes or None (for all nodes)
|
374 |
+
|
375 |
+
Returns
|
376 |
+
-------
|
377 |
+
subgraph : SubGraph View
|
378 |
+
A read-only view of the subgraph in `G` induced by the nodes.
|
379 |
+
Changes to the graph `G` will be reflected in the view.
|
380 |
+
|
381 |
+
Notes
|
382 |
+
-----
|
383 |
+
To create a mutable subgraph with its own copies of nodes
|
384 |
+
edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
|
385 |
+
|
386 |
+
For an inplace reduction of a graph to a subgraph you can remove nodes:
|
387 |
+
`G.remove_nodes_from(n in G if n not in set(nbunch))`
|
388 |
+
|
389 |
+
If you are going to compute subgraphs of your subgraphs you could
|
390 |
+
end up with a chain of views that can be very slow once the chain
|
391 |
+
has about 15 views in it. If they are all induced subgraphs, you
|
392 |
+
can short-cut the chain by making them all subgraphs of the original
|
393 |
+
graph. The graph class method `G.subgraph` does this when `G` is
|
394 |
+
a subgraph. In contrast, this function allows you to choose to build
|
395 |
+
chains or not, as you wish. The returned subgraph is a view on `G`.
|
396 |
+
|
397 |
+
Examples
|
398 |
+
--------
|
399 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
400 |
+
>>> H = nx.induced_subgraph(G, [0, 1, 3])
|
401 |
+
>>> list(H.edges)
|
402 |
+
[(0, 1)]
|
403 |
+
>>> list(H.nodes)
|
404 |
+
[0, 1, 3]
|
405 |
+
"""
|
406 |
+
induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
|
407 |
+
return nx.subgraph_view(G, filter_node=induced_nodes)
|
408 |
+
|
409 |
+
|
410 |
+
def edge_subgraph(G, edges):
|
411 |
+
"""Returns a view of the subgraph induced by the specified edges.
|
412 |
+
|
413 |
+
The induced subgraph contains each edge in `edges` and each
|
414 |
+
node incident to any of those edges.
|
415 |
+
|
416 |
+
Parameters
|
417 |
+
----------
|
418 |
+
G : NetworkX Graph
|
419 |
+
edges : iterable
|
420 |
+
An iterable of edges. Edges not present in `G` are ignored.
|
421 |
+
|
422 |
+
Returns
|
423 |
+
-------
|
424 |
+
subgraph : SubGraph View
|
425 |
+
A read-only edge-induced subgraph of `G`.
|
426 |
+
Changes to `G` are reflected in the view.
|
427 |
+
|
428 |
+
Notes
|
429 |
+
-----
|
430 |
+
To create a mutable subgraph with its own copies of nodes
|
431 |
+
edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
|
432 |
+
|
433 |
+
If you create a subgraph of a subgraph recursively you can end up
|
434 |
+
with a chain of subgraphs that becomes very slow with about 15
|
435 |
+
nested subgraph views. Luckily the edge_subgraph filter nests
|
436 |
+
nicely so you can use the original graph as G in this function
|
437 |
+
to avoid chains. We do not rule out chains programmatically so
|
438 |
+
that odd cases like an `edge_subgraph` of a `restricted_view`
|
439 |
+
can be created.
|
440 |
+
|
441 |
+
Examples
|
442 |
+
--------
|
443 |
+
>>> G = nx.path_graph(5)
|
444 |
+
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
|
445 |
+
>>> list(H.nodes)
|
446 |
+
[0, 1, 3, 4]
|
447 |
+
>>> list(H.edges)
|
448 |
+
[(0, 1), (3, 4)]
|
449 |
+
"""
|
450 |
+
nxf = nx.filters
|
451 |
+
edges = set(edges)
|
452 |
+
nodes = set()
|
453 |
+
for e in edges:
|
454 |
+
nodes.update(e[:2])
|
455 |
+
induced_nodes = nxf.show_nodes(nodes)
|
456 |
+
if G.is_multigraph():
|
457 |
+
if G.is_directed():
|
458 |
+
induced_edges = nxf.show_multidiedges(edges)
|
459 |
+
else:
|
460 |
+
induced_edges = nxf.show_multiedges(edges)
|
461 |
+
else:
|
462 |
+
if G.is_directed():
|
463 |
+
induced_edges = nxf.show_diedges(edges)
|
464 |
+
else:
|
465 |
+
induced_edges = nxf.show_edges(edges)
|
466 |
+
return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
|
467 |
+
|
468 |
+
|
469 |
+
def restricted_view(G, nodes, edges):
|
470 |
+
"""Returns a view of `G` with hidden nodes and edges.
|
471 |
+
|
472 |
+
The resulting subgraph filters out node `nodes` and edges `edges`.
|
473 |
+
Filtered out nodes also filter out any of their edges.
|
474 |
+
|
475 |
+
Parameters
|
476 |
+
----------
|
477 |
+
G : NetworkX Graph
|
478 |
+
nodes : iterable
|
479 |
+
An iterable of nodes. Nodes not present in `G` are ignored.
|
480 |
+
edges : iterable
|
481 |
+
An iterable of edges. Edges not present in `G` are ignored.
|
482 |
+
|
483 |
+
Returns
|
484 |
+
-------
|
485 |
+
subgraph : SubGraph View
|
486 |
+
A read-only restricted view of `G` filtering out nodes and edges.
|
487 |
+
Changes to `G` are reflected in the view.
|
488 |
+
|
489 |
+
Notes
|
490 |
+
-----
|
491 |
+
To create a mutable subgraph with its own copies of nodes
|
492 |
+
edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
|
493 |
+
|
494 |
+
If you create a subgraph of a subgraph recursively you may end up
|
495 |
+
with a chain of subgraph views. Such chains can get quite slow
|
496 |
+
for lengths near 15. To avoid long chains, try to make your subgraph
|
497 |
+
based on the original graph. We do not rule out chains programmatically
|
498 |
+
so that odd cases like an `edge_subgraph` of a `restricted_view`
|
499 |
+
can be created.
|
500 |
+
|
501 |
+
Examples
|
502 |
+
--------
|
503 |
+
>>> G = nx.path_graph(5)
|
504 |
+
>>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)])
|
505 |
+
>>> list(H.nodes)
|
506 |
+
[1, 2, 3, 4]
|
507 |
+
>>> list(H.edges)
|
508 |
+
[(2, 3)]
|
509 |
+
"""
|
510 |
+
nxf = nx.filters
|
511 |
+
hide_nodes = nxf.hide_nodes(nodes)
|
512 |
+
if G.is_multigraph():
|
513 |
+
if G.is_directed():
|
514 |
+
hide_edges = nxf.hide_multidiedges(edges)
|
515 |
+
else:
|
516 |
+
hide_edges = nxf.hide_multiedges(edges)
|
517 |
+
else:
|
518 |
+
if G.is_directed():
|
519 |
+
hide_edges = nxf.hide_diedges(edges)
|
520 |
+
else:
|
521 |
+
hide_edges = nxf.hide_edges(edges)
|
522 |
+
return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
|
523 |
+
|
524 |
+
|
525 |
+
def to_directed(graph):
|
526 |
+
"""Returns a directed view of the graph `graph`.
|
527 |
+
|
528 |
+
Identical to graph.to_directed(as_view=True)
|
529 |
+
Note that graph.to_directed defaults to `as_view=False`
|
530 |
+
while this function always provides a view.
|
531 |
+
"""
|
532 |
+
return graph.to_directed(as_view=True)
|
533 |
+
|
534 |
+
|
535 |
+
def to_undirected(graph):
|
536 |
+
"""Returns an undirected view of the graph `graph`.
|
537 |
+
|
538 |
+
Identical to graph.to_undirected(as_view=True)
|
539 |
+
Note that graph.to_undirected defaults to `as_view=False`
|
540 |
+
while this function always provides a view.
|
541 |
+
"""
|
542 |
+
return graph.to_undirected(as_view=True)
|
543 |
+
|
544 |
+
|
545 |
+
def create_empty_copy(G, with_data=True):
|
546 |
+
"""Returns a copy of the graph G with all of the edges removed.
|
547 |
+
|
548 |
+
Parameters
|
549 |
+
----------
|
550 |
+
G : graph
|
551 |
+
A NetworkX graph
|
552 |
+
|
553 |
+
with_data : bool (default=True)
|
554 |
+
Propagate Graph and Nodes data to the new graph.
|
555 |
+
|
556 |
+
See Also
|
557 |
+
--------
|
558 |
+
empty_graph
|
559 |
+
|
560 |
+
"""
|
561 |
+
H = G.__class__()
|
562 |
+
H.add_nodes_from(G.nodes(data=with_data))
|
563 |
+
if with_data:
|
564 |
+
H.graph.update(G.graph)
|
565 |
+
return H
|
566 |
+
|
567 |
+
|
568 |
+
def set_node_attributes(G, values, name=None):
|
569 |
+
"""Sets node attributes from a given value or dictionary of values.
|
570 |
+
|
571 |
+
.. Warning:: The call order of arguments `values` and `name`
|
572 |
+
switched between v1.x & v2.x.
|
573 |
+
|
574 |
+
Parameters
|
575 |
+
----------
|
576 |
+
G : NetworkX Graph
|
577 |
+
|
578 |
+
values : scalar value, dict-like
|
579 |
+
What the node attribute should be set to. If `values` is
|
580 |
+
not a dictionary, then it is treated as a single attribute value
|
581 |
+
that is then applied to every node in `G`. This means that if
|
582 |
+
you provide a mutable object, like a list, updates to that object
|
583 |
+
will be reflected in the node attribute for every node.
|
584 |
+
The attribute name will be `name`.
|
585 |
+
|
586 |
+
If `values` is a dict or a dict of dict, it should be keyed
|
587 |
+
by node to either an attribute value or a dict of attribute key/value
|
588 |
+
pairs used to update the node's attributes.
|
589 |
+
|
590 |
+
name : string (optional, default=None)
|
591 |
+
Name of the node attribute to set if values is a scalar.
|
592 |
+
|
593 |
+
Examples
|
594 |
+
--------
|
595 |
+
After computing some property of the nodes of a graph, you may want
|
596 |
+
to assign a node attribute to store the value of that property for
|
597 |
+
each node::
|
598 |
+
|
599 |
+
>>> G = nx.path_graph(3)
|
600 |
+
>>> bb = nx.betweenness_centrality(G)
|
601 |
+
>>> isinstance(bb, dict)
|
602 |
+
True
|
603 |
+
>>> nx.set_node_attributes(G, bb, "betweenness")
|
604 |
+
>>> G.nodes[1]["betweenness"]
|
605 |
+
1.0
|
606 |
+
|
607 |
+
If you provide a list as the second argument, updates to the list
|
608 |
+
will be reflected in the node attribute for each node::
|
609 |
+
|
610 |
+
>>> G = nx.path_graph(3)
|
611 |
+
>>> labels = []
|
612 |
+
>>> nx.set_node_attributes(G, labels, "labels")
|
613 |
+
>>> labels.append("foo")
|
614 |
+
>>> G.nodes[0]["labels"]
|
615 |
+
['foo']
|
616 |
+
>>> G.nodes[1]["labels"]
|
617 |
+
['foo']
|
618 |
+
>>> G.nodes[2]["labels"]
|
619 |
+
['foo']
|
620 |
+
|
621 |
+
If you provide a dictionary of dictionaries as the second argument,
|
622 |
+
the outer dictionary is assumed to be keyed by node to an inner
|
623 |
+
dictionary of node attributes for that node::
|
624 |
+
|
625 |
+
>>> G = nx.path_graph(3)
|
626 |
+
>>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}}
|
627 |
+
>>> nx.set_node_attributes(G, attrs)
|
628 |
+
>>> G.nodes[0]["attr1"]
|
629 |
+
20
|
630 |
+
>>> G.nodes[0]["attr2"]
|
631 |
+
'nothing'
|
632 |
+
>>> G.nodes[1]["attr2"]
|
633 |
+
3
|
634 |
+
>>> G.nodes[2]
|
635 |
+
{}
|
636 |
+
|
637 |
+
Note that if the dictionary contains nodes that are not in `G`, the
|
638 |
+
values are silently ignored::
|
639 |
+
|
640 |
+
>>> G = nx.Graph()
|
641 |
+
>>> G.add_node(0)
|
642 |
+
>>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color")
|
643 |
+
>>> G.nodes[0]["color"]
|
644 |
+
'red'
|
645 |
+
>>> 1 in G.nodes
|
646 |
+
False
|
647 |
+
|
648 |
+
"""
|
649 |
+
# Set node attributes based on type of `values`
|
650 |
+
if name is not None: # `values` must not be a dict of dict
|
651 |
+
try: # `values` is a dict
|
652 |
+
for n, v in values.items():
|
653 |
+
try:
|
654 |
+
G.nodes[n][name] = values[n]
|
655 |
+
except KeyError:
|
656 |
+
pass
|
657 |
+
except AttributeError: # `values` is a constant
|
658 |
+
for n in G:
|
659 |
+
G.nodes[n][name] = values
|
660 |
+
else: # `values` must be dict of dict
|
661 |
+
for n, d in values.items():
|
662 |
+
try:
|
663 |
+
G.nodes[n].update(d)
|
664 |
+
except KeyError:
|
665 |
+
pass
|
666 |
+
nx._clear_cache(G)
|
667 |
+
|
668 |
+
|
669 |
+
def get_node_attributes(G, name, default=None):
|
670 |
+
"""Get node attributes from graph
|
671 |
+
|
672 |
+
Parameters
|
673 |
+
----------
|
674 |
+
G : NetworkX Graph
|
675 |
+
|
676 |
+
name : string
|
677 |
+
Attribute name
|
678 |
+
|
679 |
+
default: object (default=None)
|
680 |
+
Default value of the node attribute if there is no value set for that
|
681 |
+
node in graph. If `None` then nodes without this attribute are not
|
682 |
+
included in the returned dict.
|
683 |
+
|
684 |
+
Returns
|
685 |
+
-------
|
686 |
+
Dictionary of attributes keyed by node.
|
687 |
+
|
688 |
+
Examples
|
689 |
+
--------
|
690 |
+
>>> G = nx.Graph()
|
691 |
+
>>> G.add_nodes_from([1, 2, 3], color="red")
|
692 |
+
>>> color = nx.get_node_attributes(G, "color")
|
693 |
+
>>> color[1]
|
694 |
+
'red'
|
695 |
+
>>> G.add_node(4)
|
696 |
+
>>> color = nx.get_node_attributes(G, "color", default="yellow")
|
697 |
+
>>> color[4]
|
698 |
+
'yellow'
|
699 |
+
"""
|
700 |
+
if default is not None:
|
701 |
+
return {n: d.get(name, default) for n, d in G.nodes.items()}
|
702 |
+
return {n: d[name] for n, d in G.nodes.items() if name in d}
|
703 |
+
|
704 |
+
|
705 |
+
def set_edge_attributes(G, values, name=None):
|
706 |
+
"""Sets edge attributes from a given value or dictionary of values.
|
707 |
+
|
708 |
+
.. Warning:: The call order of arguments `values` and `name`
|
709 |
+
switched between v1.x & v2.x.
|
710 |
+
|
711 |
+
Parameters
|
712 |
+
----------
|
713 |
+
G : NetworkX Graph
|
714 |
+
|
715 |
+
values : scalar value, dict-like
|
716 |
+
What the edge attribute should be set to. If `values` is
|
717 |
+
not a dictionary, then it is treated as a single attribute value
|
718 |
+
that is then applied to every edge in `G`. This means that if
|
719 |
+
you provide a mutable object, like a list, updates to that object
|
720 |
+
will be reflected in the edge attribute for each edge. The attribute
|
721 |
+
name will be `name`.
|
722 |
+
|
723 |
+
If `values` is a dict or a dict of dict, it should be keyed
|
724 |
+
by edge tuple to either an attribute value or a dict of attribute
|
725 |
+
key/value pairs used to update the edge's attributes.
|
726 |
+
For multigraphs, the edge tuples must be of the form ``(u, v, key)``,
|
727 |
+
where `u` and `v` are nodes and `key` is the edge key.
|
728 |
+
For non-multigraphs, the keys must be tuples of the form ``(u, v)``.
|
729 |
+
|
730 |
+
name : string (optional, default=None)
|
731 |
+
Name of the edge attribute to set if values is a scalar.
|
732 |
+
|
733 |
+
Examples
|
734 |
+
--------
|
735 |
+
After computing some property of the edges of a graph, you may want
|
736 |
+
to assign a edge attribute to store the value of that property for
|
737 |
+
each edge::
|
738 |
+
|
739 |
+
>>> G = nx.path_graph(3)
|
740 |
+
>>> bb = nx.edge_betweenness_centrality(G, normalized=False)
|
741 |
+
>>> nx.set_edge_attributes(G, bb, "betweenness")
|
742 |
+
>>> G.edges[1, 2]["betweenness"]
|
743 |
+
2.0
|
744 |
+
|
745 |
+
If you provide a list as the second argument, updates to the list
|
746 |
+
will be reflected in the edge attribute for each edge::
|
747 |
+
|
748 |
+
>>> labels = []
|
749 |
+
>>> nx.set_edge_attributes(G, labels, "labels")
|
750 |
+
>>> labels.append("foo")
|
751 |
+
>>> G.edges[0, 1]["labels"]
|
752 |
+
['foo']
|
753 |
+
>>> G.edges[1, 2]["labels"]
|
754 |
+
['foo']
|
755 |
+
|
756 |
+
If you provide a dictionary of dictionaries as the second argument,
|
757 |
+
the entire dictionary will be used to update edge attributes::
|
758 |
+
|
759 |
+
>>> G = nx.path_graph(3)
|
760 |
+
>>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}}
|
761 |
+
>>> nx.set_edge_attributes(G, attrs)
|
762 |
+
>>> G[0][1]["attr1"]
|
763 |
+
20
|
764 |
+
>>> G[0][1]["attr2"]
|
765 |
+
'nothing'
|
766 |
+
>>> G[1][2]["attr2"]
|
767 |
+
3
|
768 |
+
|
769 |
+
The attributes of one Graph can be used to set those of another.
|
770 |
+
|
771 |
+
>>> H = nx.path_graph(3)
|
772 |
+
>>> nx.set_edge_attributes(H, G.edges)
|
773 |
+
|
774 |
+
Note that if the dict contains edges that are not in `G`, they are
|
775 |
+
silently ignored::
|
776 |
+
|
777 |
+
>>> G = nx.Graph([(0, 1)])
|
778 |
+
>>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}})
|
779 |
+
>>> (1, 2) in G.edges()
|
780 |
+
False
|
781 |
+
|
782 |
+
For multigraphs, the `values` dict is expected to be keyed by 3-tuples
|
783 |
+
including the edge key::
|
784 |
+
|
785 |
+
>>> MG = nx.MultiGraph()
|
786 |
+
>>> edges = [(0, 1), (0, 1)]
|
787 |
+
>>> MG.add_edges_from(edges) # Returns list of edge keys
|
788 |
+
[0, 1]
|
789 |
+
>>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
|
790 |
+
>>> nx.set_edge_attributes(MG, attributes)
|
791 |
+
>>> MG[0][1][0]["cost"]
|
792 |
+
21
|
793 |
+
>>> MG[0][1][1]["cost"]
|
794 |
+
7
|
795 |
+
|
796 |
+
If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
|
797 |
+
multiedge to a 2-tuple edge and the last multiedge's attribute value will
|
798 |
+
overwrite the previous values. Continuing from the previous case we get::
|
799 |
+
|
800 |
+
>>> H = nx.path_graph([0, 1, 2])
|
801 |
+
>>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
|
802 |
+
>>> nx.get_edge_attributes(H, "cost")
|
803 |
+
{(0, 1): 7}
|
804 |
+
|
805 |
+
"""
|
806 |
+
if name is not None:
|
807 |
+
# `values` does not contain attribute names
|
808 |
+
try:
|
809 |
+
# if `values` is a dict using `.items()` => {edge: value}
|
810 |
+
if G.is_multigraph():
|
811 |
+
for (u, v, key), value in values.items():
|
812 |
+
try:
|
813 |
+
G._adj[u][v][key][name] = value
|
814 |
+
except KeyError:
|
815 |
+
pass
|
816 |
+
else:
|
817 |
+
for (u, v), value in values.items():
|
818 |
+
try:
|
819 |
+
G._adj[u][v][name] = value
|
820 |
+
except KeyError:
|
821 |
+
pass
|
822 |
+
except AttributeError:
|
823 |
+
# treat `values` as a constant
|
824 |
+
for u, v, data in G.edges(data=True):
|
825 |
+
data[name] = values
|
826 |
+
else:
|
827 |
+
# `values` consists of doct-of-dict {edge: {attr: value}} shape
|
828 |
+
if G.is_multigraph():
|
829 |
+
for (u, v, key), d in values.items():
|
830 |
+
try:
|
831 |
+
G._adj[u][v][key].update(d)
|
832 |
+
except KeyError:
|
833 |
+
pass
|
834 |
+
else:
|
835 |
+
for (u, v), d in values.items():
|
836 |
+
try:
|
837 |
+
G._adj[u][v].update(d)
|
838 |
+
except KeyError:
|
839 |
+
pass
|
840 |
+
nx._clear_cache(G)
|
841 |
+
|
842 |
+
|
843 |
+
def get_edge_attributes(G, name, default=None):
|
844 |
+
"""Get edge attributes from graph
|
845 |
+
|
846 |
+
Parameters
|
847 |
+
----------
|
848 |
+
G : NetworkX Graph
|
849 |
+
|
850 |
+
name : string
|
851 |
+
Attribute name
|
852 |
+
|
853 |
+
default: object (default=None)
|
854 |
+
Default value of the edge attribute if there is no value set for that
|
855 |
+
edge in graph. If `None` then edges without this attribute are not
|
856 |
+
included in the returned dict.
|
857 |
+
|
858 |
+
Returns
|
859 |
+
-------
|
860 |
+
Dictionary of attributes keyed by edge. For (di)graphs, the keys are
|
861 |
+
2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
|
862 |
+
the form: (u, v, key).
|
863 |
+
|
864 |
+
Examples
|
865 |
+
--------
|
866 |
+
>>> G = nx.Graph()
|
867 |
+
>>> nx.add_path(G, [1, 2, 3], color="red")
|
868 |
+
>>> color = nx.get_edge_attributes(G, "color")
|
869 |
+
>>> color[(1, 2)]
|
870 |
+
'red'
|
871 |
+
>>> G.add_edge(3, 4)
|
872 |
+
>>> color = nx.get_edge_attributes(G, "color", default="yellow")
|
873 |
+
>>> color[(3, 4)]
|
874 |
+
'yellow'
|
875 |
+
"""
|
876 |
+
if G.is_multigraph():
|
877 |
+
edges = G.edges(keys=True, data=True)
|
878 |
+
else:
|
879 |
+
edges = G.edges(data=True)
|
880 |
+
if default is not None:
|
881 |
+
return {x[:-1]: x[-1].get(name, default) for x in edges}
|
882 |
+
return {x[:-1]: x[-1][name] for x in edges if name in x[-1]}
|
883 |
+
|
884 |
+
|
885 |
+
def all_neighbors(graph, node):
|
886 |
+
"""Returns all of the neighbors of a node in the graph.
|
887 |
+
|
888 |
+
If the graph is directed returns predecessors as well as successors.
|
889 |
+
|
890 |
+
Parameters
|
891 |
+
----------
|
892 |
+
graph : NetworkX graph
|
893 |
+
Graph to find neighbors.
|
894 |
+
|
895 |
+
node : node
|
896 |
+
The node whose neighbors will be returned.
|
897 |
+
|
898 |
+
Returns
|
899 |
+
-------
|
900 |
+
neighbors : iterator
|
901 |
+
Iterator of neighbors
|
902 |
+
"""
|
903 |
+
if graph.is_directed():
|
904 |
+
values = chain(graph.predecessors(node), graph.successors(node))
|
905 |
+
else:
|
906 |
+
values = graph.neighbors(node)
|
907 |
+
return values
|
908 |
+
|
909 |
+
|
910 |
+
def non_neighbors(graph, node):
|
911 |
+
"""Returns the non-neighbors of the node in the graph.
|
912 |
+
|
913 |
+
Parameters
|
914 |
+
----------
|
915 |
+
graph : NetworkX graph
|
916 |
+
Graph to find neighbors.
|
917 |
+
|
918 |
+
node : node
|
919 |
+
The node whose neighbors will be returned.
|
920 |
+
|
921 |
+
Returns
|
922 |
+
-------
|
923 |
+
non_neighbors : set
|
924 |
+
Set of nodes in the graph that are not neighbors of the node.
|
925 |
+
"""
|
926 |
+
return graph._adj.keys() - graph._adj[node].keys() - {node}
|
927 |
+
|
928 |
+
|
929 |
+
def non_edges(graph):
|
930 |
+
"""Returns the nonexistent edges in the graph.
|
931 |
+
|
932 |
+
Parameters
|
933 |
+
----------
|
934 |
+
graph : NetworkX graph.
|
935 |
+
Graph to find nonexistent edges.
|
936 |
+
|
937 |
+
Returns
|
938 |
+
-------
|
939 |
+
non_edges : iterator
|
940 |
+
Iterator of edges that are not in the graph.
|
941 |
+
"""
|
942 |
+
if graph.is_directed():
|
943 |
+
for u in graph:
|
944 |
+
for v in non_neighbors(graph, u):
|
945 |
+
yield (u, v)
|
946 |
+
else:
|
947 |
+
nodes = set(graph)
|
948 |
+
while nodes:
|
949 |
+
u = nodes.pop()
|
950 |
+
for v in nodes - set(graph[u]):
|
951 |
+
yield (u, v)
|
952 |
+
|
953 |
+
|
954 |
+
@not_implemented_for("directed")
|
955 |
+
def common_neighbors(G, u, v):
|
956 |
+
"""Returns the common neighbors of two nodes in a graph.
|
957 |
+
|
958 |
+
Parameters
|
959 |
+
----------
|
960 |
+
G : graph
|
961 |
+
A NetworkX undirected graph.
|
962 |
+
|
963 |
+
u, v : nodes
|
964 |
+
Nodes in the graph.
|
965 |
+
|
966 |
+
Returns
|
967 |
+
-------
|
968 |
+
cnbors : set
|
969 |
+
Set of common neighbors of u and v in the graph.
|
970 |
+
|
971 |
+
Raises
|
972 |
+
------
|
973 |
+
NetworkXError
|
974 |
+
If u or v is not a node in the graph.
|
975 |
+
|
976 |
+
Examples
|
977 |
+
--------
|
978 |
+
>>> G = nx.complete_graph(5)
|
979 |
+
>>> sorted(nx.common_neighbors(G, 0, 1))
|
980 |
+
[2, 3, 4]
|
981 |
+
"""
|
982 |
+
if u not in G:
|
983 |
+
raise nx.NetworkXError("u is not in the graph.")
|
984 |
+
if v not in G:
|
985 |
+
raise nx.NetworkXError("v is not in the graph.")
|
986 |
+
|
987 |
+
return G._adj[u].keys() & G._adj[v].keys() - {u, v}
|
988 |
+
|
989 |
+
|
990 |
+
def is_weighted(G, edge=None, weight="weight"):
|
991 |
+
"""Returns True if `G` has weighted edges.
|
992 |
+
|
993 |
+
Parameters
|
994 |
+
----------
|
995 |
+
G : graph
|
996 |
+
A NetworkX graph.
|
997 |
+
|
998 |
+
edge : tuple, optional
|
999 |
+
A 2-tuple specifying the only edge in `G` that will be tested. If
|
1000 |
+
None, then every edge in `G` is tested.
|
1001 |
+
|
1002 |
+
weight: string, optional
|
1003 |
+
The attribute name used to query for edge weights.
|
1004 |
+
|
1005 |
+
Returns
|
1006 |
+
-------
|
1007 |
+
bool
|
1008 |
+
A boolean signifying if `G`, or the specified edge, is weighted.
|
1009 |
+
|
1010 |
+
Raises
|
1011 |
+
------
|
1012 |
+
NetworkXError
|
1013 |
+
If the specified edge does not exist.
|
1014 |
+
|
1015 |
+
Examples
|
1016 |
+
--------
|
1017 |
+
>>> G = nx.path_graph(4)
|
1018 |
+
>>> nx.is_weighted(G)
|
1019 |
+
False
|
1020 |
+
>>> nx.is_weighted(G, (2, 3))
|
1021 |
+
False
|
1022 |
+
|
1023 |
+
>>> G = nx.DiGraph()
|
1024 |
+
>>> G.add_edge(1, 2, weight=1)
|
1025 |
+
>>> nx.is_weighted(G)
|
1026 |
+
True
|
1027 |
+
|
1028 |
+
"""
|
1029 |
+
if edge is not None:
|
1030 |
+
data = G.get_edge_data(*edge)
|
1031 |
+
if data is None:
|
1032 |
+
msg = f"Edge {edge!r} does not exist."
|
1033 |
+
raise nx.NetworkXError(msg)
|
1034 |
+
return weight in data
|
1035 |
+
|
1036 |
+
if is_empty(G):
|
1037 |
+
# Special handling required since: all([]) == True
|
1038 |
+
return False
|
1039 |
+
|
1040 |
+
return all(weight in data for u, v, data in G.edges(data=True))
|
1041 |
+
|
1042 |
+
|
1043 |
+
@nx._dispatchable(edge_attrs="weight")
|
1044 |
+
def is_negatively_weighted(G, edge=None, weight="weight"):
|
1045 |
+
"""Returns True if `G` has negatively weighted edges.
|
1046 |
+
|
1047 |
+
Parameters
|
1048 |
+
----------
|
1049 |
+
G : graph
|
1050 |
+
A NetworkX graph.
|
1051 |
+
|
1052 |
+
edge : tuple, optional
|
1053 |
+
A 2-tuple specifying the only edge in `G` that will be tested. If
|
1054 |
+
None, then every edge in `G` is tested.
|
1055 |
+
|
1056 |
+
weight: string, optional
|
1057 |
+
The attribute name used to query for edge weights.
|
1058 |
+
|
1059 |
+
Returns
|
1060 |
+
-------
|
1061 |
+
bool
|
1062 |
+
A boolean signifying if `G`, or the specified edge, is negatively
|
1063 |
+
weighted.
|
1064 |
+
|
1065 |
+
Raises
|
1066 |
+
------
|
1067 |
+
NetworkXError
|
1068 |
+
If the specified edge does not exist.
|
1069 |
+
|
1070 |
+
Examples
|
1071 |
+
--------
|
1072 |
+
>>> G = nx.Graph()
|
1073 |
+
>>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
|
1074 |
+
>>> G.add_edge(1, 2, weight=4)
|
1075 |
+
>>> nx.is_negatively_weighted(G, (1, 2))
|
1076 |
+
False
|
1077 |
+
>>> G[2][4]["weight"] = -2
|
1078 |
+
>>> nx.is_negatively_weighted(G)
|
1079 |
+
True
|
1080 |
+
>>> G = nx.DiGraph()
|
1081 |
+
>>> edges = [("0", "3", 3), ("0", "1", -5), ("1", "0", -2)]
|
1082 |
+
>>> G.add_weighted_edges_from(edges)
|
1083 |
+
>>> nx.is_negatively_weighted(G)
|
1084 |
+
True
|
1085 |
+
|
1086 |
+
"""
|
1087 |
+
if edge is not None:
|
1088 |
+
data = G.get_edge_data(*edge)
|
1089 |
+
if data is None:
|
1090 |
+
msg = f"Edge {edge!r} does not exist."
|
1091 |
+
raise nx.NetworkXError(msg)
|
1092 |
+
return weight in data and data[weight] < 0
|
1093 |
+
|
1094 |
+
return any(weight in data and data[weight] < 0 for u, v, data in G.edges(data=True))
|
1095 |
+
|
1096 |
+
|
1097 |
+
def is_empty(G):
|
1098 |
+
"""Returns True if `G` has no edges.
|
1099 |
+
|
1100 |
+
Parameters
|
1101 |
+
----------
|
1102 |
+
G : graph
|
1103 |
+
A NetworkX graph.
|
1104 |
+
|
1105 |
+
Returns
|
1106 |
+
-------
|
1107 |
+
bool
|
1108 |
+
True if `G` has no edges, and False otherwise.
|
1109 |
+
|
1110 |
+
Notes
|
1111 |
+
-----
|
1112 |
+
An empty graph can have nodes but not edges. The empty graph with zero
|
1113 |
+
nodes is known as the null graph. This is an $O(n)$ operation where n
|
1114 |
+
is the number of nodes in the graph.
|
1115 |
+
|
1116 |
+
"""
|
1117 |
+
return not any(G._adj.values())
|
1118 |
+
|
1119 |
+
|
1120 |
+
def nodes_with_selfloops(G):
|
1121 |
+
"""Returns an iterator over nodes with self loops.
|
1122 |
+
|
1123 |
+
A node with a self loop has an edge with both ends adjacent
|
1124 |
+
to that node.
|
1125 |
+
|
1126 |
+
Returns
|
1127 |
+
-------
|
1128 |
+
nodelist : iterator
|
1129 |
+
A iterator over nodes with self loops.
|
1130 |
+
|
1131 |
+
See Also
|
1132 |
+
--------
|
1133 |
+
selfloop_edges, number_of_selfloops
|
1134 |
+
|
1135 |
+
Examples
|
1136 |
+
--------
|
1137 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1138 |
+
>>> G.add_edge(1, 1)
|
1139 |
+
>>> G.add_edge(1, 2)
|
1140 |
+
>>> list(nx.nodes_with_selfloops(G))
|
1141 |
+
[1]
|
1142 |
+
|
1143 |
+
"""
|
1144 |
+
return (n for n, nbrs in G._adj.items() if n in nbrs)
|
1145 |
+
|
1146 |
+
|
1147 |
+
def selfloop_edges(G, data=False, keys=False, default=None):
|
1148 |
+
"""Returns an iterator over selfloop edges.
|
1149 |
+
|
1150 |
+
A selfloop edge has the same node at both ends.
|
1151 |
+
|
1152 |
+
Parameters
|
1153 |
+
----------
|
1154 |
+
G : graph
|
1155 |
+
A NetworkX graph.
|
1156 |
+
data : string or bool, optional (default=False)
|
1157 |
+
Return selfloop edges as two tuples (u, v) (data=False)
|
1158 |
+
or three-tuples (u, v, datadict) (data=True)
|
1159 |
+
or three-tuples (u, v, datavalue) (data='attrname')
|
1160 |
+
keys : bool, optional (default=False)
|
1161 |
+
If True, return edge keys with each edge.
|
1162 |
+
default : value, optional (default=None)
|
1163 |
+
Value used for edges that don't have the requested attribute.
|
1164 |
+
Only relevant if data is not True or False.
|
1165 |
+
|
1166 |
+
Returns
|
1167 |
+
-------
|
1168 |
+
edgeiter : iterator over edge tuples
|
1169 |
+
An iterator over all selfloop edges.
|
1170 |
+
|
1171 |
+
See Also
|
1172 |
+
--------
|
1173 |
+
nodes_with_selfloops, number_of_selfloops
|
1174 |
+
|
1175 |
+
Examples
|
1176 |
+
--------
|
1177 |
+
>>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc
|
1178 |
+
>>> ekey = G.add_edge(1, 1)
|
1179 |
+
>>> ekey = G.add_edge(1, 2)
|
1180 |
+
>>> list(nx.selfloop_edges(G))
|
1181 |
+
[(1, 1)]
|
1182 |
+
>>> list(nx.selfloop_edges(G, data=True))
|
1183 |
+
[(1, 1, {})]
|
1184 |
+
>>> list(nx.selfloop_edges(G, keys=True))
|
1185 |
+
[(1, 1, 0)]
|
1186 |
+
>>> list(nx.selfloop_edges(G, keys=True, data=True))
|
1187 |
+
[(1, 1, 0, {})]
|
1188 |
+
"""
|
1189 |
+
if data is True:
|
1190 |
+
if G.is_multigraph():
|
1191 |
+
if keys is True:
|
1192 |
+
return (
|
1193 |
+
(n, n, k, d)
|
1194 |
+
for n, nbrs in G._adj.items()
|
1195 |
+
if n in nbrs
|
1196 |
+
for k, d in nbrs[n].items()
|
1197 |
+
)
|
1198 |
+
else:
|
1199 |
+
return (
|
1200 |
+
(n, n, d)
|
1201 |
+
for n, nbrs in G._adj.items()
|
1202 |
+
if n in nbrs
|
1203 |
+
for d in nbrs[n].values()
|
1204 |
+
)
|
1205 |
+
else:
|
1206 |
+
return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs)
|
1207 |
+
elif data is not False:
|
1208 |
+
if G.is_multigraph():
|
1209 |
+
if keys is True:
|
1210 |
+
return (
|
1211 |
+
(n, n, k, d.get(data, default))
|
1212 |
+
for n, nbrs in G._adj.items()
|
1213 |
+
if n in nbrs
|
1214 |
+
for k, d in nbrs[n].items()
|
1215 |
+
)
|
1216 |
+
else:
|
1217 |
+
return (
|
1218 |
+
(n, n, d.get(data, default))
|
1219 |
+
for n, nbrs in G._adj.items()
|
1220 |
+
if n in nbrs
|
1221 |
+
for d in nbrs[n].values()
|
1222 |
+
)
|
1223 |
+
else:
|
1224 |
+
return (
|
1225 |
+
(n, n, nbrs[n].get(data, default))
|
1226 |
+
for n, nbrs in G._adj.items()
|
1227 |
+
if n in nbrs
|
1228 |
+
)
|
1229 |
+
else:
|
1230 |
+
if G.is_multigraph():
|
1231 |
+
if keys is True:
|
1232 |
+
return (
|
1233 |
+
(n, n, k)
|
1234 |
+
for n, nbrs in G._adj.items()
|
1235 |
+
if n in nbrs
|
1236 |
+
for k in nbrs[n]
|
1237 |
+
)
|
1238 |
+
else:
|
1239 |
+
return (
|
1240 |
+
(n, n)
|
1241 |
+
for n, nbrs in G._adj.items()
|
1242 |
+
if n in nbrs
|
1243 |
+
for i in range(len(nbrs[n])) # for easy edge removal (#4068)
|
1244 |
+
)
|
1245 |
+
else:
|
1246 |
+
return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
|
1247 |
+
|
1248 |
+
|
1249 |
+
def number_of_selfloops(G):
|
1250 |
+
"""Returns the number of selfloop edges.
|
1251 |
+
|
1252 |
+
A selfloop edge has the same node at both ends.
|
1253 |
+
|
1254 |
+
Returns
|
1255 |
+
-------
|
1256 |
+
nloops : int
|
1257 |
+
The number of selfloops.
|
1258 |
+
|
1259 |
+
See Also
|
1260 |
+
--------
|
1261 |
+
nodes_with_selfloops, selfloop_edges
|
1262 |
+
|
1263 |
+
Examples
|
1264 |
+
--------
|
1265 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1266 |
+
>>> G.add_edge(1, 1)
|
1267 |
+
>>> G.add_edge(1, 2)
|
1268 |
+
>>> nx.number_of_selfloops(G)
|
1269 |
+
1
|
1270 |
+
"""
|
1271 |
+
return sum(1 for _ in nx.selfloop_edges(G))
|
1272 |
+
|
1273 |
+
|
1274 |
+
def is_path(G, path):
|
1275 |
+
"""Returns whether or not the specified path exists.
|
1276 |
+
|
1277 |
+
For it to return True, every node on the path must exist and
|
1278 |
+
each consecutive pair must be connected via one or more edges.
|
1279 |
+
|
1280 |
+
Parameters
|
1281 |
+
----------
|
1282 |
+
G : graph
|
1283 |
+
A NetworkX graph.
|
1284 |
+
|
1285 |
+
path : list
|
1286 |
+
A list of nodes which defines the path to traverse
|
1287 |
+
|
1288 |
+
Returns
|
1289 |
+
-------
|
1290 |
+
bool
|
1291 |
+
True if `path` is a valid path in `G`
|
1292 |
+
|
1293 |
+
"""
|
1294 |
+
try:
|
1295 |
+
return all(nbr in G._adj[node] for node, nbr in nx.utils.pairwise(path))
|
1296 |
+
except (KeyError, TypeError):
|
1297 |
+
return False
|
1298 |
+
|
1299 |
+
|
1300 |
+
def path_weight(G, path, weight):
|
1301 |
+
"""Returns total cost associated with specified path and weight
|
1302 |
+
|
1303 |
+
Parameters
|
1304 |
+
----------
|
1305 |
+
G : graph
|
1306 |
+
A NetworkX graph.
|
1307 |
+
|
1308 |
+
path: list
|
1309 |
+
A list of node labels which defines the path to traverse
|
1310 |
+
|
1311 |
+
weight: string
|
1312 |
+
A string indicating which edge attribute to use for path cost
|
1313 |
+
|
1314 |
+
Returns
|
1315 |
+
-------
|
1316 |
+
cost: int or float
|
1317 |
+
An integer or a float representing the total cost with respect to the
|
1318 |
+
specified weight of the specified path
|
1319 |
+
|
1320 |
+
Raises
|
1321 |
+
------
|
1322 |
+
NetworkXNoPath
|
1323 |
+
If the specified edge does not exist.
|
1324 |
+
"""
|
1325 |
+
multigraph = G.is_multigraph()
|
1326 |
+
cost = 0
|
1327 |
+
|
1328 |
+
if not nx.is_path(G, path):
|
1329 |
+
raise nx.NetworkXNoPath("path does not exist")
|
1330 |
+
for node, nbr in nx.utils.pairwise(path):
|
1331 |
+
if multigraph:
|
1332 |
+
cost += min(v[weight] for v in G._adj[node][nbr].values())
|
1333 |
+
else:
|
1334 |
+
cost += G._adj[node][nbr][weight]
|
1335 |
+
return cost
|
venv/lib/python3.10/site-packages/networkx/classes/graph.py
ADDED
@@ -0,0 +1,2043 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for undirected graphs.
|
2 |
+
|
3 |
+
The Graph class allows any hashable object as a node
|
4 |
+
and can associate key/value attribute pairs with each undirected edge.
|
5 |
+
|
6 |
+
Self-loops are allowed but multiple edges are not (see MultiGraph).
|
7 |
+
|
8 |
+
For directed graphs see DiGraph and MultiDiGraph.
|
9 |
+
"""
|
10 |
+
from copy import deepcopy
|
11 |
+
from functools import cached_property
|
12 |
+
|
13 |
+
import networkx as nx
|
14 |
+
from networkx import convert
|
15 |
+
from networkx.classes.coreviews import AdjacencyView
|
16 |
+
from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
|
17 |
+
from networkx.exception import NetworkXError
|
18 |
+
|
19 |
+
__all__ = ["Graph"]
|
20 |
+
|
21 |
+
|
22 |
+
class _CachedPropertyResetterAdj:
|
23 |
+
"""Data Descriptor class for _adj that resets ``adj`` cached_property when needed
|
24 |
+
|
25 |
+
This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
|
26 |
+
``G._adj`` is set to a new value.
|
27 |
+
|
28 |
+
This object sits on a class and ensures that any instance of that
|
29 |
+
class clears its cached property "adj" whenever the underlying
|
30 |
+
instance attribute "_adj" is set to a new object. It only affects
|
31 |
+
the set process of the obj._adj attribute. All get/del operations
|
32 |
+
act as they normally would.
|
33 |
+
|
34 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __set__(self, obj, value):
|
38 |
+
od = obj.__dict__
|
39 |
+
od["_adj"] = value
|
40 |
+
if "adj" in od:
|
41 |
+
del od["adj"]
|
42 |
+
|
43 |
+
|
44 |
+
class _CachedPropertyResetterNode:
|
45 |
+
"""Data Descriptor class for _node that resets ``nodes`` cached_property when needed
|
46 |
+
|
47 |
+
This assumes that the ``cached_property`` ``G.node`` should be reset whenever
|
48 |
+
``G._node`` is set to a new value.
|
49 |
+
|
50 |
+
This object sits on a class and ensures that any instance of that
|
51 |
+
class clears its cached property "nodes" whenever the underlying
|
52 |
+
instance attribute "_node" is set to a new object. It only affects
|
53 |
+
the set process of the obj._adj attribute. All get/del operations
|
54 |
+
act as they normally would.
|
55 |
+
|
56 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
57 |
+
"""
|
58 |
+
|
59 |
+
def __set__(self, obj, value):
|
60 |
+
od = obj.__dict__
|
61 |
+
od["_node"] = value
|
62 |
+
if "nodes" in od:
|
63 |
+
del od["nodes"]
|
64 |
+
|
65 |
+
|
66 |
+
class Graph:
|
67 |
+
"""
|
68 |
+
Base class for undirected graphs.
|
69 |
+
|
70 |
+
A Graph stores nodes and edges with optional data, or attributes.
|
71 |
+
|
72 |
+
Graphs hold undirected edges. Self loops are allowed but multiple
|
73 |
+
(parallel) edges are not.
|
74 |
+
|
75 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
76 |
+
key/value attributes, except that `None` is not allowed as a node.
|
77 |
+
|
78 |
+
Edges are represented as links between nodes with optional
|
79 |
+
key/value attributes.
|
80 |
+
|
81 |
+
Parameters
|
82 |
+
----------
|
83 |
+
incoming_graph_data : input graph (optional, default: None)
|
84 |
+
Data to initialize graph. If None (default) an empty
|
85 |
+
graph is created. The data can be any format that is supported
|
86 |
+
by the to_networkx_graph() function, currently including edge list,
|
87 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
|
88 |
+
sparse matrix, or PyGraphviz graph.
|
89 |
+
|
90 |
+
attr : keyword arguments, optional (default= no attributes)
|
91 |
+
Attributes to add to graph as key=value pairs.
|
92 |
+
|
93 |
+
See Also
|
94 |
+
--------
|
95 |
+
DiGraph
|
96 |
+
MultiGraph
|
97 |
+
MultiDiGraph
|
98 |
+
|
99 |
+
Examples
|
100 |
+
--------
|
101 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
102 |
+
no edges.
|
103 |
+
|
104 |
+
>>> G = nx.Graph()
|
105 |
+
|
106 |
+
G can be grown in several ways.
|
107 |
+
|
108 |
+
**Nodes:**
|
109 |
+
|
110 |
+
Add one node at a time:
|
111 |
+
|
112 |
+
>>> G.add_node(1)
|
113 |
+
|
114 |
+
Add the nodes from any container (a list, dict, set or
|
115 |
+
even the lines from a file or the nodes from another graph).
|
116 |
+
|
117 |
+
>>> G.add_nodes_from([2, 3])
|
118 |
+
>>> G.add_nodes_from(range(100, 110))
|
119 |
+
>>> H = nx.path_graph(10)
|
120 |
+
>>> G.add_nodes_from(H)
|
121 |
+
|
122 |
+
In addition to strings and integers any hashable Python object
|
123 |
+
(except None) can represent a node, e.g. a customized node object,
|
124 |
+
or even another Graph.
|
125 |
+
|
126 |
+
>>> G.add_node(H)
|
127 |
+
|
128 |
+
**Edges:**
|
129 |
+
|
130 |
+
G can also be grown by adding edges.
|
131 |
+
|
132 |
+
Add one edge,
|
133 |
+
|
134 |
+
>>> G.add_edge(1, 2)
|
135 |
+
|
136 |
+
a list of edges,
|
137 |
+
|
138 |
+
>>> G.add_edges_from([(1, 2), (1, 3)])
|
139 |
+
|
140 |
+
or a collection of edges,
|
141 |
+
|
142 |
+
>>> G.add_edges_from(H.edges)
|
143 |
+
|
144 |
+
If some edges connect nodes not yet in the graph, the nodes
|
145 |
+
are added automatically. There are no errors when adding
|
146 |
+
nodes or edges that already exist.
|
147 |
+
|
148 |
+
**Attributes:**
|
149 |
+
|
150 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
151 |
+
in an associated attribute dictionary (the keys must be hashable).
|
152 |
+
By default these are empty, but can be added or changed using
|
153 |
+
add_edge, add_node or direct manipulation of the attribute
|
154 |
+
dictionaries named graph, node and edge respectively.
|
155 |
+
|
156 |
+
>>> G = nx.Graph(day="Friday")
|
157 |
+
>>> G.graph
|
158 |
+
{'day': 'Friday'}
|
159 |
+
|
160 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
161 |
+
|
162 |
+
>>> G.add_node(1, time="5pm")
|
163 |
+
>>> G.add_nodes_from([3], time="2pm")
|
164 |
+
>>> G.nodes[1]
|
165 |
+
{'time': '5pm'}
|
166 |
+
>>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes
|
167 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
168 |
+
>>> list(G.nodes(data=True))
|
169 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
170 |
+
|
171 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
172 |
+
notation, or G.edges.
|
173 |
+
|
174 |
+
>>> G.add_edge(1, 2, weight=4.7)
|
175 |
+
>>> G.add_edges_from([(3, 4), (4, 5)], color="red")
|
176 |
+
>>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
177 |
+
>>> G[1][2]["weight"] = 4.7
|
178 |
+
>>> G.edges[1, 2]["weight"] = 4
|
179 |
+
|
180 |
+
Warning: we protect the graph data structure by making `G.edges` a
|
181 |
+
read-only dict-like structure. However, you can assign to attributes
|
182 |
+
in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
|
183 |
+
data attributes: `G.edges[1, 2]['weight'] = 4`
|
184 |
+
(For multigraphs: `MG.edges[u, v, key][name] = value`).
|
185 |
+
|
186 |
+
**Shortcuts:**
|
187 |
+
|
188 |
+
Many common graph features allow python syntax to speed reporting.
|
189 |
+
|
190 |
+
>>> 1 in G # check if node in graph
|
191 |
+
True
|
192 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
193 |
+
[1, 2]
|
194 |
+
>>> len(G) # number of nodes in graph
|
195 |
+
5
|
196 |
+
|
197 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
198 |
+
The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
|
199 |
+
|
200 |
+
>>> for n, nbrsdict in G.adjacency():
|
201 |
+
... for nbr, eattr in nbrsdict.items():
|
202 |
+
... if "weight" in eattr:
|
203 |
+
... # Do something useful with the edges
|
204 |
+
... pass
|
205 |
+
|
206 |
+
But the edges() method is often more convenient:
|
207 |
+
|
208 |
+
>>> for u, v, weight in G.edges.data("weight"):
|
209 |
+
... if weight is not None:
|
210 |
+
... # Do something useful with the edges
|
211 |
+
... pass
|
212 |
+
|
213 |
+
**Reporting:**
|
214 |
+
|
215 |
+
Simple graph information is obtained using object-attributes and methods.
|
216 |
+
Reporting typically provides views instead of containers to reduce memory
|
217 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
218 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
219 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
|
220 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
221 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
222 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
223 |
+
|
224 |
+
For details on these and other miscellaneous methods, see below.
|
225 |
+
|
226 |
+
**Subclasses (Advanced):**
|
227 |
+
|
228 |
+
The Graph class uses a dict-of-dict-of-dict data structure.
|
229 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
230 |
+
The next dict (adjlist_dict) represents the adjacency information and holds
|
231 |
+
edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
|
232 |
+
the edge data and holds edge attribute values keyed by attribute names.
|
233 |
+
|
234 |
+
Each of these three dicts can be replaced in a subclass by a user defined
|
235 |
+
dict-like object. In general, the dict-like features should be
|
236 |
+
maintained but extra features can be added. To replace one of the
|
237 |
+
dicts create a new graph class by changing the class(!) variable
|
238 |
+
holding the factory for that dict-like structure.
|
239 |
+
|
240 |
+
node_dict_factory : function, (default: dict)
|
241 |
+
Factory function to be used to create the dict containing node
|
242 |
+
attributes, keyed by node id.
|
243 |
+
It should require no arguments and return a dict-like object
|
244 |
+
|
245 |
+
node_attr_dict_factory: function, (default: dict)
|
246 |
+
Factory function to be used to create the node attribute
|
247 |
+
dict which holds attribute values keyed by attribute name.
|
248 |
+
It should require no arguments and return a dict-like object
|
249 |
+
|
250 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
251 |
+
Factory function to be used to create the outer-most dict
|
252 |
+
in the data structure that holds adjacency info keyed by node.
|
253 |
+
It should require no arguments and return a dict-like object.
|
254 |
+
|
255 |
+
adjlist_inner_dict_factory : function, (default: dict)
|
256 |
+
Factory function to be used to create the adjacency list
|
257 |
+
dict which holds edge data keyed by neighbor.
|
258 |
+
It should require no arguments and return a dict-like object
|
259 |
+
|
260 |
+
edge_attr_dict_factory : function, (default: dict)
|
261 |
+
Factory function to be used to create the edge attribute
|
262 |
+
dict which holds attribute values keyed by attribute name.
|
263 |
+
It should require no arguments and return a dict-like object.
|
264 |
+
|
265 |
+
graph_attr_dict_factory : function, (default: dict)
|
266 |
+
Factory function to be used to create the graph attribute
|
267 |
+
dict which holds attribute values keyed by attribute name.
|
268 |
+
It should require no arguments and return a dict-like object.
|
269 |
+
|
270 |
+
Typically, if your extension doesn't impact the data structure all
|
271 |
+
methods will inherit without issue except: `to_directed/to_undirected`.
|
272 |
+
By default these methods create a DiGraph/Graph class and you probably
|
273 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
274 |
+
this we define two class variables that you can set in your subclass.
|
275 |
+
|
276 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
277 |
+
Class to create a new graph structure in the `to_directed` method.
|
278 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
279 |
+
|
280 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
281 |
+
Class to create a new graph structure in the `to_undirected` method.
|
282 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
283 |
+
|
284 |
+
**Subclassing Example**
|
285 |
+
|
286 |
+
Create a low memory graph class that effectively disallows edge
|
287 |
+
attributes by using a single attribute dict for all edges.
|
288 |
+
This reduces the memory used, but you lose edge attributes.
|
289 |
+
|
290 |
+
>>> class ThinGraph(nx.Graph):
|
291 |
+
... all_edge_dict = {"weight": 1}
|
292 |
+
...
|
293 |
+
... def single_edge_dict(self):
|
294 |
+
... return self.all_edge_dict
|
295 |
+
...
|
296 |
+
... edge_attr_dict_factory = single_edge_dict
|
297 |
+
>>> G = ThinGraph()
|
298 |
+
>>> G.add_edge(2, 1)
|
299 |
+
>>> G[2][1]
|
300 |
+
{'weight': 1}
|
301 |
+
>>> G.add_edge(2, 2)
|
302 |
+
>>> G[2][1] is G[2][2]
|
303 |
+
True
|
304 |
+
"""
|
305 |
+
|
306 |
+
_adj = _CachedPropertyResetterAdj()
|
307 |
+
_node = _CachedPropertyResetterNode()
|
308 |
+
|
309 |
+
node_dict_factory = dict
|
310 |
+
node_attr_dict_factory = dict
|
311 |
+
adjlist_outer_dict_factory = dict
|
312 |
+
adjlist_inner_dict_factory = dict
|
313 |
+
edge_attr_dict_factory = dict
|
314 |
+
graph_attr_dict_factory = dict
|
315 |
+
|
316 |
+
def to_directed_class(self):
|
317 |
+
"""Returns the class to use for empty directed copies.
|
318 |
+
|
319 |
+
If you subclass the base classes, use this to designate
|
320 |
+
what directed class to use for `to_directed()` copies.
|
321 |
+
"""
|
322 |
+
return nx.DiGraph
|
323 |
+
|
324 |
+
def to_undirected_class(self):
|
325 |
+
"""Returns the class to use for empty undirected copies.
|
326 |
+
|
327 |
+
If you subclass the base classes, use this to designate
|
328 |
+
what directed class to use for `to_directed()` copies.
|
329 |
+
"""
|
330 |
+
return Graph
|
331 |
+
|
332 |
+
def __init__(self, incoming_graph_data=None, **attr):
|
333 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
334 |
+
|
335 |
+
Parameters
|
336 |
+
----------
|
337 |
+
incoming_graph_data : input graph (optional, default: None)
|
338 |
+
Data to initialize graph. If None (default) an empty
|
339 |
+
graph is created. The data can be an edge list, or any
|
340 |
+
NetworkX graph object. If the corresponding optional Python
|
341 |
+
packages are installed the data can also be a 2D NumPy array, a
|
342 |
+
SciPy sparse array, or a PyGraphviz graph.
|
343 |
+
|
344 |
+
attr : keyword arguments, optional (default= no attributes)
|
345 |
+
Attributes to add to graph as key=value pairs.
|
346 |
+
|
347 |
+
See Also
|
348 |
+
--------
|
349 |
+
convert
|
350 |
+
|
351 |
+
Examples
|
352 |
+
--------
|
353 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
354 |
+
>>> G = nx.Graph(name="my graph")
|
355 |
+
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
|
356 |
+
>>> G = nx.Graph(e)
|
357 |
+
|
358 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
359 |
+
|
360 |
+
>>> G = nx.Graph(e, day="Friday")
|
361 |
+
>>> G.graph
|
362 |
+
{'day': 'Friday'}
|
363 |
+
|
364 |
+
"""
|
365 |
+
self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
|
366 |
+
self._node = self.node_dict_factory() # empty node attribute dict
|
367 |
+
self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict
|
368 |
+
self.__networkx_cache__ = {}
|
369 |
+
# attempt to load graph with data
|
370 |
+
if incoming_graph_data is not None:
|
371 |
+
convert.to_networkx_graph(incoming_graph_data, create_using=self)
|
372 |
+
# load graph attributes (must be after convert)
|
373 |
+
self.graph.update(attr)
|
374 |
+
|
375 |
+
@cached_property
|
376 |
+
def adj(self):
|
377 |
+
"""Graph adjacency object holding the neighbors of each node.
|
378 |
+
|
379 |
+
This object is a read-only dict-like structure with node keys
|
380 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
381 |
+
to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
|
382 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
383 |
+
|
384 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
385 |
+
`for nbr, datadict in G.adj[n].items():`.
|
386 |
+
|
387 |
+
The neighbor information is also provided by subscripting the graph.
|
388 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
389 |
+
|
390 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
391 |
+
"""
|
392 |
+
return AdjacencyView(self._adj)
|
393 |
+
|
394 |
+
@property
|
395 |
+
def name(self):
|
396 |
+
"""String identifier of the graph.
|
397 |
+
|
398 |
+
This graph attribute appears in the attribute dict G.graph
|
399 |
+
keyed by the string `"name"`. as well as an attribute (technically
|
400 |
+
a property) `G.name`. This is entirely user controlled.
|
401 |
+
"""
|
402 |
+
return self.graph.get("name", "")
|
403 |
+
|
404 |
+
@name.setter
|
405 |
+
def name(self, s):
|
406 |
+
self.graph["name"] = s
|
407 |
+
nx._clear_cache(self)
|
408 |
+
|
409 |
+
def __str__(self):
|
410 |
+
"""Returns a short summary of the graph.
|
411 |
+
|
412 |
+
Returns
|
413 |
+
-------
|
414 |
+
info : string
|
415 |
+
Graph information including the graph name (if any), graph type, and the
|
416 |
+
number of nodes and edges.
|
417 |
+
|
418 |
+
Examples
|
419 |
+
--------
|
420 |
+
>>> G = nx.Graph(name="foo")
|
421 |
+
>>> str(G)
|
422 |
+
"Graph named 'foo' with 0 nodes and 0 edges"
|
423 |
+
|
424 |
+
>>> G = nx.path_graph(3)
|
425 |
+
>>> str(G)
|
426 |
+
'Graph with 3 nodes and 2 edges'
|
427 |
+
|
428 |
+
"""
|
429 |
+
return "".join(
|
430 |
+
[
|
431 |
+
type(self).__name__,
|
432 |
+
f" named {self.name!r}" if self.name else "",
|
433 |
+
f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
|
434 |
+
]
|
435 |
+
)
|
436 |
+
|
437 |
+
def __iter__(self):
|
438 |
+
"""Iterate over the nodes. Use: 'for n in G'.
|
439 |
+
|
440 |
+
Returns
|
441 |
+
-------
|
442 |
+
niter : iterator
|
443 |
+
An iterator over all nodes in the graph.
|
444 |
+
|
445 |
+
Examples
|
446 |
+
--------
|
447 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
448 |
+
>>> [n for n in G]
|
449 |
+
[0, 1, 2, 3]
|
450 |
+
>>> list(G)
|
451 |
+
[0, 1, 2, 3]
|
452 |
+
"""
|
453 |
+
return iter(self._node)
|
454 |
+
|
455 |
+
def __contains__(self, n):
|
456 |
+
"""Returns True if n is a node, False otherwise. Use: 'n in G'.
|
457 |
+
|
458 |
+
Examples
|
459 |
+
--------
|
460 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
461 |
+
>>> 1 in G
|
462 |
+
True
|
463 |
+
"""
|
464 |
+
try:
|
465 |
+
return n in self._node
|
466 |
+
except TypeError:
|
467 |
+
return False
|
468 |
+
|
469 |
+
def __len__(self):
|
470 |
+
"""Returns the number of nodes in the graph. Use: 'len(G)'.
|
471 |
+
|
472 |
+
Returns
|
473 |
+
-------
|
474 |
+
nnodes : int
|
475 |
+
The number of nodes in the graph.
|
476 |
+
|
477 |
+
See Also
|
478 |
+
--------
|
479 |
+
number_of_nodes: identical method
|
480 |
+
order: identical method
|
481 |
+
|
482 |
+
Examples
|
483 |
+
--------
|
484 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
485 |
+
>>> len(G)
|
486 |
+
4
|
487 |
+
|
488 |
+
"""
|
489 |
+
return len(self._node)
|
490 |
+
|
491 |
+
def __getitem__(self, n):
|
492 |
+
"""Returns a dict of neighbors of node n. Use: 'G[n]'.
|
493 |
+
|
494 |
+
Parameters
|
495 |
+
----------
|
496 |
+
n : node
|
497 |
+
A node in the graph.
|
498 |
+
|
499 |
+
Returns
|
500 |
+
-------
|
501 |
+
adj_dict : dictionary
|
502 |
+
The adjacency dictionary for nodes connected to n.
|
503 |
+
|
504 |
+
Notes
|
505 |
+
-----
|
506 |
+
G[n] is the same as G.adj[n] and similar to G.neighbors(n)
|
507 |
+
(which is an iterator over G.adj[n])
|
508 |
+
|
509 |
+
Examples
|
510 |
+
--------
|
511 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
512 |
+
>>> G[0]
|
513 |
+
AtlasView({1: {}})
|
514 |
+
"""
|
515 |
+
return self.adj[n]
|
516 |
+
|
517 |
+
def add_node(self, node_for_adding, **attr):
|
518 |
+
"""Add a single node `node_for_adding` and update node attributes.
|
519 |
+
|
520 |
+
Parameters
|
521 |
+
----------
|
522 |
+
node_for_adding : node
|
523 |
+
A node can be any hashable Python object except None.
|
524 |
+
attr : keyword arguments, optional
|
525 |
+
Set or change node attributes using key=value.
|
526 |
+
|
527 |
+
See Also
|
528 |
+
--------
|
529 |
+
add_nodes_from
|
530 |
+
|
531 |
+
Examples
|
532 |
+
--------
|
533 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
534 |
+
>>> G.add_node(1)
|
535 |
+
>>> G.add_node("Hello")
|
536 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
537 |
+
>>> G.add_node(K3)
|
538 |
+
>>> G.number_of_nodes()
|
539 |
+
3
|
540 |
+
|
541 |
+
Use keywords set/change node attributes:
|
542 |
+
|
543 |
+
>>> G.add_node(1, size=10)
|
544 |
+
>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
|
545 |
+
|
546 |
+
Notes
|
547 |
+
-----
|
548 |
+
A hashable object is one that can be used as a key in a Python
|
549 |
+
dictionary. This includes strings, numbers, tuples of strings
|
550 |
+
and numbers, etc.
|
551 |
+
|
552 |
+
On many platforms hashable items also include mutables such as
|
553 |
+
NetworkX Graphs, though one should be careful that the hash
|
554 |
+
doesn't change on mutables.
|
555 |
+
"""
|
556 |
+
if node_for_adding not in self._node:
|
557 |
+
if node_for_adding is None:
|
558 |
+
raise ValueError("None cannot be a node")
|
559 |
+
self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
|
560 |
+
attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
|
561 |
+
attr_dict.update(attr)
|
562 |
+
else: # update attr even if node already exists
|
563 |
+
self._node[node_for_adding].update(attr)
|
564 |
+
nx._clear_cache(self)
|
565 |
+
|
566 |
+
def add_nodes_from(self, nodes_for_adding, **attr):
|
567 |
+
"""Add multiple nodes.
|
568 |
+
|
569 |
+
Parameters
|
570 |
+
----------
|
571 |
+
nodes_for_adding : iterable container
|
572 |
+
A container of nodes (list, dict, set, etc.).
|
573 |
+
OR
|
574 |
+
A container of (node, attribute dict) tuples.
|
575 |
+
Node attributes are updated using the attribute dict.
|
576 |
+
attr : keyword arguments, optional (default= no attributes)
|
577 |
+
Update attributes for all nodes in nodes.
|
578 |
+
Node attributes specified in nodes as a tuple take
|
579 |
+
precedence over attributes specified via keyword arguments.
|
580 |
+
|
581 |
+
See Also
|
582 |
+
--------
|
583 |
+
add_node
|
584 |
+
|
585 |
+
Notes
|
586 |
+
-----
|
587 |
+
When adding nodes from an iterator over the graph you are changing,
|
588 |
+
a `RuntimeError` can be raised with message:
|
589 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
590 |
+
happens when the graph's underlying dictionary is modified during
|
591 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
592 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
593 |
+
object to `G.add_nodes_from`.
|
594 |
+
|
595 |
+
Examples
|
596 |
+
--------
|
597 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
598 |
+
>>> G.add_nodes_from("Hello")
|
599 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
600 |
+
>>> G.add_nodes_from(K3)
|
601 |
+
>>> sorted(G.nodes(), key=str)
|
602 |
+
[0, 1, 2, 'H', 'e', 'l', 'o']
|
603 |
+
|
604 |
+
Use keywords to update specific node attributes for every node.
|
605 |
+
|
606 |
+
>>> G.add_nodes_from([1, 2], size=10)
|
607 |
+
>>> G.add_nodes_from([3, 4], weight=0.4)
|
608 |
+
|
609 |
+
Use (node, attrdict) tuples to update attributes for specific nodes.
|
610 |
+
|
611 |
+
>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
|
612 |
+
>>> G.nodes[1]["size"]
|
613 |
+
11
|
614 |
+
>>> H = nx.Graph()
|
615 |
+
>>> H.add_nodes_from(G.nodes(data=True))
|
616 |
+
>>> H.nodes[1]["size"]
|
617 |
+
11
|
618 |
+
|
619 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
620 |
+
|
621 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
|
622 |
+
>>> # wrong way - will raise RuntimeError
|
623 |
+
>>> # G.add_nodes_from(n + 1 for n in G.nodes)
|
624 |
+
>>> # correct way
|
625 |
+
>>> G.add_nodes_from(list(n + 1 for n in G.nodes))
|
626 |
+
"""
|
627 |
+
for n in nodes_for_adding:
|
628 |
+
try:
|
629 |
+
newnode = n not in self._node
|
630 |
+
newdict = attr
|
631 |
+
except TypeError:
|
632 |
+
n, ndict = n
|
633 |
+
newnode = n not in self._node
|
634 |
+
newdict = attr.copy()
|
635 |
+
newdict.update(ndict)
|
636 |
+
if newnode:
|
637 |
+
if n is None:
|
638 |
+
raise ValueError("None cannot be a node")
|
639 |
+
self._adj[n] = self.adjlist_inner_dict_factory()
|
640 |
+
self._node[n] = self.node_attr_dict_factory()
|
641 |
+
self._node[n].update(newdict)
|
642 |
+
nx._clear_cache(self)
|
643 |
+
|
644 |
+
def remove_node(self, n):
|
645 |
+
"""Remove node n.
|
646 |
+
|
647 |
+
Removes the node n and all adjacent edges.
|
648 |
+
Attempting to remove a nonexistent node will raise an exception.
|
649 |
+
|
650 |
+
Parameters
|
651 |
+
----------
|
652 |
+
n : node
|
653 |
+
A node in the graph
|
654 |
+
|
655 |
+
Raises
|
656 |
+
------
|
657 |
+
NetworkXError
|
658 |
+
If n is not in the graph.
|
659 |
+
|
660 |
+
See Also
|
661 |
+
--------
|
662 |
+
remove_nodes_from
|
663 |
+
|
664 |
+
Examples
|
665 |
+
--------
|
666 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
667 |
+
>>> list(G.edges)
|
668 |
+
[(0, 1), (1, 2)]
|
669 |
+
>>> G.remove_node(1)
|
670 |
+
>>> list(G.edges)
|
671 |
+
[]
|
672 |
+
|
673 |
+
"""
|
674 |
+
adj = self._adj
|
675 |
+
try:
|
676 |
+
nbrs = list(adj[n]) # list handles self-loops (allows mutation)
|
677 |
+
del self._node[n]
|
678 |
+
except KeyError as err: # NetworkXError if n not in self
|
679 |
+
raise NetworkXError(f"The node {n} is not in the graph.") from err
|
680 |
+
for u in nbrs:
|
681 |
+
del adj[u][n] # remove all edges n-u in graph
|
682 |
+
del adj[n] # now remove node
|
683 |
+
nx._clear_cache(self)
|
684 |
+
|
685 |
+
def remove_nodes_from(self, nodes):
|
686 |
+
"""Remove multiple nodes.
|
687 |
+
|
688 |
+
Parameters
|
689 |
+
----------
|
690 |
+
nodes : iterable container
|
691 |
+
A container of nodes (list, dict, set, etc.). If a node
|
692 |
+
in the container is not in the graph it is silently
|
693 |
+
ignored.
|
694 |
+
|
695 |
+
See Also
|
696 |
+
--------
|
697 |
+
remove_node
|
698 |
+
|
699 |
+
Notes
|
700 |
+
-----
|
701 |
+
When removing nodes from an iterator over the graph you are changing,
|
702 |
+
a `RuntimeError` will be raised with message:
|
703 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
704 |
+
happens when the graph's underlying dictionary is modified during
|
705 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
706 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
707 |
+
object to `G.remove_nodes_from`.
|
708 |
+
|
709 |
+
Examples
|
710 |
+
--------
|
711 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
712 |
+
>>> e = list(G.nodes)
|
713 |
+
>>> e
|
714 |
+
[0, 1, 2]
|
715 |
+
>>> G.remove_nodes_from(e)
|
716 |
+
>>> list(G.nodes)
|
717 |
+
[]
|
718 |
+
|
719 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
720 |
+
|
721 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
|
722 |
+
>>> # this command will fail, as the graph's dict is modified during iteration
|
723 |
+
>>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
|
724 |
+
>>> # this command will work, since the dictionary underlying graph is not modified
|
725 |
+
>>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
|
726 |
+
"""
|
727 |
+
adj = self._adj
|
728 |
+
for n in nodes:
|
729 |
+
try:
|
730 |
+
del self._node[n]
|
731 |
+
for u in list(adj[n]): # list handles self-loops
|
732 |
+
del adj[u][n] # (allows mutation of dict in loop)
|
733 |
+
del adj[n]
|
734 |
+
except KeyError:
|
735 |
+
pass
|
736 |
+
nx._clear_cache(self)
|
737 |
+
|
738 |
+
@cached_property
|
739 |
+
def nodes(self):
|
740 |
+
"""A NodeView of the Graph as G.nodes or G.nodes().
|
741 |
+
|
742 |
+
Can be used as `G.nodes` for data lookup and for set-like operations.
|
743 |
+
Can also be used as `G.nodes(data='color', default=None)` to return a
|
744 |
+
NodeDataView which reports specific node data but no set operations.
|
745 |
+
It presents a dict-like interface as well with `G.nodes.items()`
|
746 |
+
iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
|
747 |
+
providing the value of the `foo` attribute for node `3`. In addition,
|
748 |
+
a view `G.nodes.data('foo')` provides a dict-like interface to the
|
749 |
+
`foo` attribute of each node. `G.nodes.data('foo', default=1)`
|
750 |
+
provides a default for nodes that do not have attribute `foo`.
|
751 |
+
|
752 |
+
Parameters
|
753 |
+
----------
|
754 |
+
data : string or bool, optional (default=False)
|
755 |
+
The node attribute returned in 2-tuple (n, ddict[data]).
|
756 |
+
If True, return entire node attribute dict as (n, ddict).
|
757 |
+
If False, return just the nodes n.
|
758 |
+
|
759 |
+
default : value, optional (default=None)
|
760 |
+
Value used for nodes that don't have the requested attribute.
|
761 |
+
Only relevant if data is not True or False.
|
762 |
+
|
763 |
+
Returns
|
764 |
+
-------
|
765 |
+
NodeView
|
766 |
+
Allows set-like operations over the nodes as well as node
|
767 |
+
attribute dict lookup and calling to get a NodeDataView.
|
768 |
+
A NodeDataView iterates over `(n, data)` and has no set operations.
|
769 |
+
A NodeView iterates over `n` and includes set operations.
|
770 |
+
|
771 |
+
When called, if data is False, an iterator over nodes.
|
772 |
+
Otherwise an iterator of 2-tuples (node, attribute value)
|
773 |
+
where the attribute is specified in `data`.
|
774 |
+
If data is True then the attribute becomes the
|
775 |
+
entire data dictionary.
|
776 |
+
|
777 |
+
Notes
|
778 |
+
-----
|
779 |
+
If your node data is not needed, it is simpler and equivalent
|
780 |
+
to use the expression ``for n in G``, or ``list(G)``.
|
781 |
+
|
782 |
+
Examples
|
783 |
+
--------
|
784 |
+
There are two simple ways of getting a list of all nodes in the graph:
|
785 |
+
|
786 |
+
>>> G = nx.path_graph(3)
|
787 |
+
>>> list(G.nodes)
|
788 |
+
[0, 1, 2]
|
789 |
+
>>> list(G)
|
790 |
+
[0, 1, 2]
|
791 |
+
|
792 |
+
To get the node data along with the nodes:
|
793 |
+
|
794 |
+
>>> G.add_node(1, time="5pm")
|
795 |
+
>>> G.nodes[0]["foo"] = "bar"
|
796 |
+
>>> list(G.nodes(data=True))
|
797 |
+
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
|
798 |
+
>>> list(G.nodes.data())
|
799 |
+
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
|
800 |
+
|
801 |
+
>>> list(G.nodes(data="foo"))
|
802 |
+
[(0, 'bar'), (1, None), (2, None)]
|
803 |
+
>>> list(G.nodes.data("foo"))
|
804 |
+
[(0, 'bar'), (1, None), (2, None)]
|
805 |
+
|
806 |
+
>>> list(G.nodes(data="time"))
|
807 |
+
[(0, None), (1, '5pm'), (2, None)]
|
808 |
+
>>> list(G.nodes.data("time"))
|
809 |
+
[(0, None), (1, '5pm'), (2, None)]
|
810 |
+
|
811 |
+
>>> list(G.nodes(data="time", default="Not Available"))
|
812 |
+
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
|
813 |
+
>>> list(G.nodes.data("time", default="Not Available"))
|
814 |
+
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
|
815 |
+
|
816 |
+
If some of your nodes have an attribute and the rest are assumed
|
817 |
+
to have a default attribute value you can create a dictionary
|
818 |
+
from node/attribute pairs using the `default` keyword argument
|
819 |
+
to guarantee the value is never None::
|
820 |
+
|
821 |
+
>>> G = nx.Graph()
|
822 |
+
>>> G.add_node(0)
|
823 |
+
>>> G.add_node(1, weight=2)
|
824 |
+
>>> G.add_node(2, weight=3)
|
825 |
+
>>> dict(G.nodes(data="weight", default=1))
|
826 |
+
{0: 1, 1: 2, 2: 3}
|
827 |
+
|
828 |
+
"""
|
829 |
+
return NodeView(self)
|
830 |
+
|
831 |
+
def number_of_nodes(self):
|
832 |
+
"""Returns the number of nodes in the graph.
|
833 |
+
|
834 |
+
Returns
|
835 |
+
-------
|
836 |
+
nnodes : int
|
837 |
+
The number of nodes in the graph.
|
838 |
+
|
839 |
+
See Also
|
840 |
+
--------
|
841 |
+
order: identical method
|
842 |
+
__len__: identical method
|
843 |
+
|
844 |
+
Examples
|
845 |
+
--------
|
846 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
847 |
+
>>> G.number_of_nodes()
|
848 |
+
3
|
849 |
+
"""
|
850 |
+
return len(self._node)
|
851 |
+
|
852 |
+
def order(self):
|
853 |
+
"""Returns the number of nodes in the graph.
|
854 |
+
|
855 |
+
Returns
|
856 |
+
-------
|
857 |
+
nnodes : int
|
858 |
+
The number of nodes in the graph.
|
859 |
+
|
860 |
+
See Also
|
861 |
+
--------
|
862 |
+
number_of_nodes: identical method
|
863 |
+
__len__: identical method
|
864 |
+
|
865 |
+
Examples
|
866 |
+
--------
|
867 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
868 |
+
>>> G.order()
|
869 |
+
3
|
870 |
+
"""
|
871 |
+
return len(self._node)
|
872 |
+
|
873 |
+
def has_node(self, n):
|
874 |
+
"""Returns True if the graph contains the node n.
|
875 |
+
|
876 |
+
Identical to `n in G`
|
877 |
+
|
878 |
+
Parameters
|
879 |
+
----------
|
880 |
+
n : node
|
881 |
+
|
882 |
+
Examples
|
883 |
+
--------
|
884 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
885 |
+
>>> G.has_node(0)
|
886 |
+
True
|
887 |
+
|
888 |
+
It is more readable and simpler to use
|
889 |
+
|
890 |
+
>>> 0 in G
|
891 |
+
True
|
892 |
+
|
893 |
+
"""
|
894 |
+
try:
|
895 |
+
return n in self._node
|
896 |
+
except TypeError:
|
897 |
+
return False
|
898 |
+
|
899 |
+
def add_edge(self, u_of_edge, v_of_edge, **attr):
|
900 |
+
"""Add an edge between u and v.
|
901 |
+
|
902 |
+
The nodes u and v will be automatically added if they are
|
903 |
+
not already in the graph.
|
904 |
+
|
905 |
+
Edge attributes can be specified with keywords or by directly
|
906 |
+
accessing the edge's attribute dictionary. See examples below.
|
907 |
+
|
908 |
+
Parameters
|
909 |
+
----------
|
910 |
+
u_of_edge, v_of_edge : nodes
|
911 |
+
Nodes can be, for example, strings or numbers.
|
912 |
+
Nodes must be hashable (and not None) Python objects.
|
913 |
+
attr : keyword arguments, optional
|
914 |
+
Edge data (or labels or objects) can be assigned using
|
915 |
+
keyword arguments.
|
916 |
+
|
917 |
+
See Also
|
918 |
+
--------
|
919 |
+
add_edges_from : add a collection of edges
|
920 |
+
|
921 |
+
Notes
|
922 |
+
-----
|
923 |
+
Adding an edge that already exists updates the edge data.
|
924 |
+
|
925 |
+
Many NetworkX algorithms designed for weighted graphs use
|
926 |
+
an edge attribute (by default `weight`) to hold a numerical value.
|
927 |
+
|
928 |
+
Examples
|
929 |
+
--------
|
930 |
+
The following all add the edge e=(1, 2) to graph G:
|
931 |
+
|
932 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
933 |
+
>>> e = (1, 2)
|
934 |
+
>>> G.add_edge(1, 2) # explicit two-node form
|
935 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
936 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
937 |
+
|
938 |
+
Associate data to edges using keywords:
|
939 |
+
|
940 |
+
>>> G.add_edge(1, 2, weight=3)
|
941 |
+
>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
942 |
+
|
943 |
+
For non-string attribute keys, use subscript notation.
|
944 |
+
|
945 |
+
>>> G.add_edge(1, 2)
|
946 |
+
>>> G[1][2].update({0: 5})
|
947 |
+
>>> G.edges[1, 2].update({0: 5})
|
948 |
+
"""
|
949 |
+
u, v = u_of_edge, v_of_edge
|
950 |
+
# add nodes
|
951 |
+
if u not in self._node:
|
952 |
+
if u is None:
|
953 |
+
raise ValueError("None cannot be a node")
|
954 |
+
self._adj[u] = self.adjlist_inner_dict_factory()
|
955 |
+
self._node[u] = self.node_attr_dict_factory()
|
956 |
+
if v not in self._node:
|
957 |
+
if v is None:
|
958 |
+
raise ValueError("None cannot be a node")
|
959 |
+
self._adj[v] = self.adjlist_inner_dict_factory()
|
960 |
+
self._node[v] = self.node_attr_dict_factory()
|
961 |
+
# add the edge
|
962 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
963 |
+
datadict.update(attr)
|
964 |
+
self._adj[u][v] = datadict
|
965 |
+
self._adj[v][u] = datadict
|
966 |
+
nx._clear_cache(self)
|
967 |
+
|
968 |
+
def add_edges_from(self, ebunch_to_add, **attr):
|
969 |
+
"""Add all the edges in ebunch_to_add.
|
970 |
+
|
971 |
+
Parameters
|
972 |
+
----------
|
973 |
+
ebunch_to_add : container of edges
|
974 |
+
Each edge given in the container will be added to the
|
975 |
+
graph. The edges must be given as 2-tuples (u, v) or
|
976 |
+
3-tuples (u, v, d) where d is a dictionary containing edge data.
|
977 |
+
attr : keyword arguments, optional
|
978 |
+
Edge data (or labels or objects) can be assigned using
|
979 |
+
keyword arguments.
|
980 |
+
|
981 |
+
See Also
|
982 |
+
--------
|
983 |
+
add_edge : add a single edge
|
984 |
+
add_weighted_edges_from : convenient way to add weighted edges
|
985 |
+
|
986 |
+
Notes
|
987 |
+
-----
|
988 |
+
Adding the same edge twice has no effect but any edge data
|
989 |
+
will be updated when each duplicate edge is added.
|
990 |
+
|
991 |
+
Edge attributes specified in an ebunch take precedence over
|
992 |
+
attributes specified via keyword arguments.
|
993 |
+
|
994 |
+
When adding edges from an iterator over the graph you are changing,
|
995 |
+
a `RuntimeError` can be raised with message:
|
996 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
997 |
+
happens when the graph's underlying dictionary is modified during
|
998 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
999 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
1000 |
+
object to `G.add_edges_from`.
|
1001 |
+
|
1002 |
+
Examples
|
1003 |
+
--------
|
1004 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1005 |
+
>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
|
1006 |
+
>>> e = zip(range(0, 3), range(1, 4))
|
1007 |
+
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3
|
1008 |
+
|
1009 |
+
Associate data to edges
|
1010 |
+
|
1011 |
+
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
|
1012 |
+
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
|
1013 |
+
|
1014 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
1015 |
+
|
1016 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
|
1017 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
1018 |
+
>>> # wrong way - will raise RuntimeError
|
1019 |
+
>>> # G.add_edges_from(((5, n) for n in G.nodes))
|
1020 |
+
>>> # correct way - note that there will be no self-edge for node 5
|
1021 |
+
>>> G.add_edges_from(list((5, n) for n in G.nodes))
|
1022 |
+
"""
|
1023 |
+
for e in ebunch_to_add:
|
1024 |
+
ne = len(e)
|
1025 |
+
if ne == 3:
|
1026 |
+
u, v, dd = e
|
1027 |
+
elif ne == 2:
|
1028 |
+
u, v = e
|
1029 |
+
dd = {} # doesn't need edge_attr_dict_factory
|
1030 |
+
else:
|
1031 |
+
raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
|
1032 |
+
if u not in self._node:
|
1033 |
+
if u is None:
|
1034 |
+
raise ValueError("None cannot be a node")
|
1035 |
+
self._adj[u] = self.adjlist_inner_dict_factory()
|
1036 |
+
self._node[u] = self.node_attr_dict_factory()
|
1037 |
+
if v not in self._node:
|
1038 |
+
if v is None:
|
1039 |
+
raise ValueError("None cannot be a node")
|
1040 |
+
self._adj[v] = self.adjlist_inner_dict_factory()
|
1041 |
+
self._node[v] = self.node_attr_dict_factory()
|
1042 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
1043 |
+
datadict.update(attr)
|
1044 |
+
datadict.update(dd)
|
1045 |
+
self._adj[u][v] = datadict
|
1046 |
+
self._adj[v][u] = datadict
|
1047 |
+
nx._clear_cache(self)
|
1048 |
+
|
1049 |
+
def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
|
1050 |
+
"""Add weighted edges in `ebunch_to_add` with specified weight attr
|
1051 |
+
|
1052 |
+
Parameters
|
1053 |
+
----------
|
1054 |
+
ebunch_to_add : container of edges
|
1055 |
+
Each edge given in the list or container will be added
|
1056 |
+
to the graph. The edges must be given as 3-tuples (u, v, w)
|
1057 |
+
where w is a number.
|
1058 |
+
weight : string, optional (default= 'weight')
|
1059 |
+
The attribute name for the edge weights to be added.
|
1060 |
+
attr : keyword arguments, optional (default= no attributes)
|
1061 |
+
Edge attributes to add/update for all edges.
|
1062 |
+
|
1063 |
+
See Also
|
1064 |
+
--------
|
1065 |
+
add_edge : add a single edge
|
1066 |
+
add_edges_from : add multiple edges
|
1067 |
+
|
1068 |
+
Notes
|
1069 |
+
-----
|
1070 |
+
Adding the same edge twice for Graph/DiGraph simply updates
|
1071 |
+
the edge data. For MultiGraph/MultiDiGraph, duplicate edges
|
1072 |
+
are stored.
|
1073 |
+
|
1074 |
+
When adding edges from an iterator over the graph you are changing,
|
1075 |
+
a `RuntimeError` can be raised with message:
|
1076 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
1077 |
+
happens when the graph's underlying dictionary is modified during
|
1078 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
1079 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
1080 |
+
object to `G.add_weighted_edges_from`.
|
1081 |
+
|
1082 |
+
Examples
|
1083 |
+
--------
|
1084 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1085 |
+
>>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
|
1086 |
+
|
1087 |
+
Evaluate an iterator over edges before passing it
|
1088 |
+
|
1089 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
|
1090 |
+
>>> weight = 0.1
|
1091 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
1092 |
+
>>> # wrong way - will raise RuntimeError
|
1093 |
+
>>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
|
1094 |
+
>>> # correct way - note that there will be no self-edge for node 5
|
1095 |
+
>>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
|
1096 |
+
"""
|
1097 |
+
self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
|
1098 |
+
nx._clear_cache(self)
|
1099 |
+
|
1100 |
+
def remove_edge(self, u, v):
|
1101 |
+
"""Remove the edge between u and v.
|
1102 |
+
|
1103 |
+
Parameters
|
1104 |
+
----------
|
1105 |
+
u, v : nodes
|
1106 |
+
Remove the edge between nodes u and v.
|
1107 |
+
|
1108 |
+
Raises
|
1109 |
+
------
|
1110 |
+
NetworkXError
|
1111 |
+
If there is not an edge between u and v.
|
1112 |
+
|
1113 |
+
See Also
|
1114 |
+
--------
|
1115 |
+
remove_edges_from : remove a collection of edges
|
1116 |
+
|
1117 |
+
Examples
|
1118 |
+
--------
|
1119 |
+
>>> G = nx.path_graph(4) # or DiGraph, etc
|
1120 |
+
>>> G.remove_edge(0, 1)
|
1121 |
+
>>> e = (1, 2)
|
1122 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
1123 |
+
>>> e = (2, 3, {"weight": 7}) # an edge with attribute data
|
1124 |
+
>>> G.remove_edge(*e[:2]) # select first part of edge tuple
|
1125 |
+
"""
|
1126 |
+
try:
|
1127 |
+
del self._adj[u][v]
|
1128 |
+
if u != v: # self-loop needs only one entry removed
|
1129 |
+
del self._adj[v][u]
|
1130 |
+
except KeyError as err:
|
1131 |
+
raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
|
1132 |
+
nx._clear_cache(self)
|
1133 |
+
|
1134 |
+
def remove_edges_from(self, ebunch):
|
1135 |
+
"""Remove all edges specified in ebunch.
|
1136 |
+
|
1137 |
+
Parameters
|
1138 |
+
----------
|
1139 |
+
ebunch: list or container of edge tuples
|
1140 |
+
Each edge given in the list or container will be removed
|
1141 |
+
from the graph. The edges can be:
|
1142 |
+
|
1143 |
+
- 2-tuples (u, v) edge between u and v.
|
1144 |
+
- 3-tuples (u, v, k) where k is ignored.
|
1145 |
+
|
1146 |
+
See Also
|
1147 |
+
--------
|
1148 |
+
remove_edge : remove a single edge
|
1149 |
+
|
1150 |
+
Notes
|
1151 |
+
-----
|
1152 |
+
Will fail silently if an edge in ebunch is not in the graph.
|
1153 |
+
|
1154 |
+
Examples
|
1155 |
+
--------
|
1156 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1157 |
+
>>> ebunch = [(1, 2), (2, 3)]
|
1158 |
+
>>> G.remove_edges_from(ebunch)
|
1159 |
+
"""
|
1160 |
+
adj = self._adj
|
1161 |
+
for e in ebunch:
|
1162 |
+
u, v = e[:2] # ignore edge data if present
|
1163 |
+
if u in adj and v in adj[u]:
|
1164 |
+
del adj[u][v]
|
1165 |
+
if u != v: # self loop needs only one entry removed
|
1166 |
+
del adj[v][u]
|
1167 |
+
nx._clear_cache(self)
|
1168 |
+
|
1169 |
+
def update(self, edges=None, nodes=None):
|
1170 |
+
"""Update the graph using nodes/edges/graphs as input.
|
1171 |
+
|
1172 |
+
Like dict.update, this method takes a graph as input, adding the
|
1173 |
+
graph's nodes and edges to this graph. It can also take two inputs:
|
1174 |
+
edges and nodes. Finally it can take either edges or nodes.
|
1175 |
+
To specify only nodes the keyword `nodes` must be used.
|
1176 |
+
|
1177 |
+
The collections of edges and nodes are treated similarly to
|
1178 |
+
the add_edges_from/add_nodes_from methods. When iterated, they
|
1179 |
+
should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
|
1180 |
+
|
1181 |
+
Parameters
|
1182 |
+
----------
|
1183 |
+
edges : Graph object, collection of edges, or None
|
1184 |
+
The first parameter can be a graph or some edges. If it has
|
1185 |
+
attributes `nodes` and `edges`, then it is taken to be a
|
1186 |
+
Graph-like object and those attributes are used as collections
|
1187 |
+
of nodes and edges to be added to the graph.
|
1188 |
+
If the first parameter does not have those attributes, it is
|
1189 |
+
treated as a collection of edges and added to the graph.
|
1190 |
+
If the first argument is None, no edges are added.
|
1191 |
+
nodes : collection of nodes, or None
|
1192 |
+
The second parameter is treated as a collection of nodes
|
1193 |
+
to be added to the graph unless it is None.
|
1194 |
+
If `edges is None` and `nodes is None` an exception is raised.
|
1195 |
+
If the first parameter is a Graph, then `nodes` is ignored.
|
1196 |
+
|
1197 |
+
Examples
|
1198 |
+
--------
|
1199 |
+
>>> G = nx.path_graph(5)
|
1200 |
+
>>> G.update(nx.complete_graph(range(4, 10)))
|
1201 |
+
>>> from itertools import combinations
|
1202 |
+
>>> edges = (
|
1203 |
+
... (u, v, {"power": u * v})
|
1204 |
+
... for u, v in combinations(range(10, 20), 2)
|
1205 |
+
... if u * v < 225
|
1206 |
+
... )
|
1207 |
+
>>> nodes = [1000] # for singleton, use a container
|
1208 |
+
>>> G.update(edges, nodes)
|
1209 |
+
|
1210 |
+
Notes
|
1211 |
+
-----
|
1212 |
+
It you want to update the graph using an adjacency structure
|
1213 |
+
it is straightforward to obtain the edges/nodes from adjacency.
|
1214 |
+
The following examples provide common cases, your adjacency may
|
1215 |
+
be slightly different and require tweaks of these examples::
|
1216 |
+
|
1217 |
+
>>> # dict-of-set/list/tuple
|
1218 |
+
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
|
1219 |
+
>>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
|
1220 |
+
>>> G.update(edges=e, nodes=adj)
|
1221 |
+
|
1222 |
+
>>> DG = nx.DiGraph()
|
1223 |
+
>>> # dict-of-dict-of-attribute
|
1224 |
+
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
|
1225 |
+
>>> e = [(u, v, {"weight": d}) for u, nbrs in adj.items() for v, d in nbrs.items()]
|
1226 |
+
>>> DG.update(edges=e, nodes=adj)
|
1227 |
+
|
1228 |
+
>>> # dict-of-dict-of-dict
|
1229 |
+
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
|
1230 |
+
>>> e = [(u, v, {"weight": d}) for u, nbrs in adj.items() for v, d in nbrs.items()]
|
1231 |
+
>>> DG.update(edges=e, nodes=adj)
|
1232 |
+
|
1233 |
+
>>> # predecessor adjacency (dict-of-set)
|
1234 |
+
>>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
|
1235 |
+
>>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
|
1236 |
+
|
1237 |
+
>>> # MultiGraph dict-of-dict-of-dict-of-attribute
|
1238 |
+
>>> MDG = nx.MultiDiGraph()
|
1239 |
+
>>> adj = {
|
1240 |
+
... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
|
1241 |
+
... 3: {2: {0: {"weight": 0.7}}},
|
1242 |
+
... }
|
1243 |
+
>>> e = [
|
1244 |
+
... (u, v, ekey, d)
|
1245 |
+
... for u, nbrs in adj.items()
|
1246 |
+
... for v, keydict in nbrs.items()
|
1247 |
+
... for ekey, d in keydict.items()
|
1248 |
+
... ]
|
1249 |
+
>>> MDG.update(edges=e)
|
1250 |
+
|
1251 |
+
See Also
|
1252 |
+
--------
|
1253 |
+
add_edges_from: add multiple edges to a graph
|
1254 |
+
add_nodes_from: add multiple nodes to a graph
|
1255 |
+
"""
|
1256 |
+
if edges is not None:
|
1257 |
+
if nodes is not None:
|
1258 |
+
self.add_nodes_from(nodes)
|
1259 |
+
self.add_edges_from(edges)
|
1260 |
+
else:
|
1261 |
+
# check if edges is a Graph object
|
1262 |
+
try:
|
1263 |
+
graph_nodes = edges.nodes
|
1264 |
+
graph_edges = edges.edges
|
1265 |
+
except AttributeError:
|
1266 |
+
# edge not Graph-like
|
1267 |
+
self.add_edges_from(edges)
|
1268 |
+
else: # edges is Graph-like
|
1269 |
+
self.add_nodes_from(graph_nodes.data())
|
1270 |
+
self.add_edges_from(graph_edges.data())
|
1271 |
+
self.graph.update(edges.graph)
|
1272 |
+
elif nodes is not None:
|
1273 |
+
self.add_nodes_from(nodes)
|
1274 |
+
else:
|
1275 |
+
raise NetworkXError("update needs nodes or edges input")
|
1276 |
+
|
1277 |
+
def has_edge(self, u, v):
|
1278 |
+
"""Returns True if the edge (u, v) is in the graph.
|
1279 |
+
|
1280 |
+
This is the same as `v in G[u]` without KeyError exceptions.
|
1281 |
+
|
1282 |
+
Parameters
|
1283 |
+
----------
|
1284 |
+
u, v : nodes
|
1285 |
+
Nodes can be, for example, strings or numbers.
|
1286 |
+
Nodes must be hashable (and not None) Python objects.
|
1287 |
+
|
1288 |
+
Returns
|
1289 |
+
-------
|
1290 |
+
edge_ind : bool
|
1291 |
+
True if edge is in the graph, False otherwise.
|
1292 |
+
|
1293 |
+
Examples
|
1294 |
+
--------
|
1295 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1296 |
+
>>> G.has_edge(0, 1) # using two nodes
|
1297 |
+
True
|
1298 |
+
>>> e = (0, 1)
|
1299 |
+
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
|
1300 |
+
True
|
1301 |
+
>>> e = (0, 1, {"weight": 7})
|
1302 |
+
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
|
1303 |
+
True
|
1304 |
+
|
1305 |
+
The following syntax are equivalent:
|
1306 |
+
|
1307 |
+
>>> G.has_edge(0, 1)
|
1308 |
+
True
|
1309 |
+
>>> 1 in G[0] # though this gives KeyError if 0 not in G
|
1310 |
+
True
|
1311 |
+
|
1312 |
+
"""
|
1313 |
+
try:
|
1314 |
+
return v in self._adj[u]
|
1315 |
+
except KeyError:
|
1316 |
+
return False
|
1317 |
+
|
1318 |
+
def neighbors(self, n):
|
1319 |
+
"""Returns an iterator over all neighbors of node n.
|
1320 |
+
|
1321 |
+
This is identical to `iter(G[n])`
|
1322 |
+
|
1323 |
+
Parameters
|
1324 |
+
----------
|
1325 |
+
n : node
|
1326 |
+
A node in the graph
|
1327 |
+
|
1328 |
+
Returns
|
1329 |
+
-------
|
1330 |
+
neighbors : iterator
|
1331 |
+
An iterator over all neighbors of node n
|
1332 |
+
|
1333 |
+
Raises
|
1334 |
+
------
|
1335 |
+
NetworkXError
|
1336 |
+
If the node n is not in the graph.
|
1337 |
+
|
1338 |
+
Examples
|
1339 |
+
--------
|
1340 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1341 |
+
>>> [n for n in G.neighbors(0)]
|
1342 |
+
[1]
|
1343 |
+
|
1344 |
+
Notes
|
1345 |
+
-----
|
1346 |
+
Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
|
1347 |
+
|
1348 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1349 |
+
>>> G.add_edge("a", "b", weight=7)
|
1350 |
+
>>> G["a"]
|
1351 |
+
AtlasView({'b': {'weight': 7}})
|
1352 |
+
>>> G = nx.path_graph(4)
|
1353 |
+
>>> [n for n in G[0]]
|
1354 |
+
[1]
|
1355 |
+
"""
|
1356 |
+
try:
|
1357 |
+
return iter(self._adj[n])
|
1358 |
+
except KeyError as err:
|
1359 |
+
raise NetworkXError(f"The node {n} is not in the graph.") from err
|
1360 |
+
|
1361 |
+
@cached_property
|
1362 |
+
def edges(self):
|
1363 |
+
"""An EdgeView of the Graph as G.edges or G.edges().
|
1364 |
+
|
1365 |
+
edges(self, nbunch=None, data=False, default=None)
|
1366 |
+
|
1367 |
+
The EdgeView provides set-like operations on the edge-tuples
|
1368 |
+
as well as edge attribute lookup. When called, it also provides
|
1369 |
+
an EdgeDataView object which allows control of access to edge
|
1370 |
+
attributes (but does not provide set-like operations).
|
1371 |
+
Hence, `G.edges[u, v]['color']` provides the value of the color
|
1372 |
+
attribute for edge `(u, v)` while
|
1373 |
+
`for (u, v, c) in G.edges.data('color', default='red'):`
|
1374 |
+
iterates through all the edges yielding the color attribute
|
1375 |
+
with default `'red'` if no color attribute exists.
|
1376 |
+
|
1377 |
+
Parameters
|
1378 |
+
----------
|
1379 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1380 |
+
The view will only report edges from these nodes.
|
1381 |
+
data : string or bool, optional (default=False)
|
1382 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
1383 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
1384 |
+
If False, return 2-tuple (u, v).
|
1385 |
+
default : value, optional (default=None)
|
1386 |
+
Value used for edges that don't have the requested attribute.
|
1387 |
+
Only relevant if data is not True or False.
|
1388 |
+
|
1389 |
+
Returns
|
1390 |
+
-------
|
1391 |
+
edges : EdgeView
|
1392 |
+
A view of edge attributes, usually it iterates over (u, v)
|
1393 |
+
or (u, v, d) tuples of edges, but can also be used for
|
1394 |
+
attribute lookup as `edges[u, v]['foo']`.
|
1395 |
+
|
1396 |
+
Notes
|
1397 |
+
-----
|
1398 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
1399 |
+
For directed graphs this returns the out-edges.
|
1400 |
+
|
1401 |
+
Examples
|
1402 |
+
--------
|
1403 |
+
>>> G = nx.path_graph(3) # or MultiGraph, etc
|
1404 |
+
>>> G.add_edge(2, 3, weight=5)
|
1405 |
+
>>> [e for e in G.edges]
|
1406 |
+
[(0, 1), (1, 2), (2, 3)]
|
1407 |
+
>>> G.edges.data() # default data is {} (empty dict)
|
1408 |
+
EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
|
1409 |
+
>>> G.edges.data("weight", default=1)
|
1410 |
+
EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
|
1411 |
+
>>> G.edges([0, 3]) # only edges from these nodes
|
1412 |
+
EdgeDataView([(0, 1), (3, 2)])
|
1413 |
+
>>> G.edges(0) # only edges from node 0
|
1414 |
+
EdgeDataView([(0, 1)])
|
1415 |
+
"""
|
1416 |
+
return EdgeView(self)
|
1417 |
+
|
1418 |
+
def get_edge_data(self, u, v, default=None):
|
1419 |
+
"""Returns the attribute dictionary associated with edge (u, v).
|
1420 |
+
|
1421 |
+
This is identical to `G[u][v]` except the default is returned
|
1422 |
+
instead of an exception if the edge doesn't exist.
|
1423 |
+
|
1424 |
+
Parameters
|
1425 |
+
----------
|
1426 |
+
u, v : nodes
|
1427 |
+
default: any Python object (default=None)
|
1428 |
+
Value to return if the edge (u, v) is not found.
|
1429 |
+
|
1430 |
+
Returns
|
1431 |
+
-------
|
1432 |
+
edge_dict : dictionary
|
1433 |
+
The edge attribute dictionary.
|
1434 |
+
|
1435 |
+
Examples
|
1436 |
+
--------
|
1437 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1438 |
+
>>> G[0][1]
|
1439 |
+
{}
|
1440 |
+
|
1441 |
+
Warning: Assigning to `G[u][v]` is not permitted.
|
1442 |
+
But it is safe to assign attributes `G[u][v]['foo']`
|
1443 |
+
|
1444 |
+
>>> G[0][1]["weight"] = 7
|
1445 |
+
>>> G[0][1]["weight"]
|
1446 |
+
7
|
1447 |
+
>>> G[1][0]["weight"]
|
1448 |
+
7
|
1449 |
+
|
1450 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1451 |
+
>>> G.get_edge_data(0, 1) # default edge data is {}
|
1452 |
+
{}
|
1453 |
+
>>> e = (0, 1)
|
1454 |
+
>>> G.get_edge_data(*e) # tuple form
|
1455 |
+
{}
|
1456 |
+
>>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
|
1457 |
+
0
|
1458 |
+
"""
|
1459 |
+
try:
|
1460 |
+
return self._adj[u][v]
|
1461 |
+
except KeyError:
|
1462 |
+
return default
|
1463 |
+
|
1464 |
+
def adjacency(self):
|
1465 |
+
"""Returns an iterator over (node, adjacency dict) tuples for all nodes.
|
1466 |
+
|
1467 |
+
For directed graphs, only outgoing neighbors/adjacencies are included.
|
1468 |
+
|
1469 |
+
Returns
|
1470 |
+
-------
|
1471 |
+
adj_iter : iterator
|
1472 |
+
An iterator over (node, adjacency dictionary) for all nodes in
|
1473 |
+
the graph.
|
1474 |
+
|
1475 |
+
Examples
|
1476 |
+
--------
|
1477 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1478 |
+
>>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
|
1479 |
+
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
|
1480 |
+
|
1481 |
+
"""
|
1482 |
+
return iter(self._adj.items())
|
1483 |
+
|
1484 |
+
@cached_property
|
1485 |
+
def degree(self):
|
1486 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
1487 |
+
|
1488 |
+
The node degree is the number of edges adjacent to the node.
|
1489 |
+
The weighted node degree is the sum of the edge weights for
|
1490 |
+
edges incident to that node.
|
1491 |
+
|
1492 |
+
This object provides an iterator for (node, degree) as well as
|
1493 |
+
lookup for the degree for a single node.
|
1494 |
+
|
1495 |
+
Parameters
|
1496 |
+
----------
|
1497 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1498 |
+
The view will only report edges incident to these nodes.
|
1499 |
+
|
1500 |
+
weight : string or None, optional (default=None)
|
1501 |
+
The name of an edge attribute that holds the numerical value used
|
1502 |
+
as a weight. If None, then each edge has weight 1.
|
1503 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1504 |
+
|
1505 |
+
Returns
|
1506 |
+
-------
|
1507 |
+
DegreeView or int
|
1508 |
+
If multiple nodes are requested (the default), returns a `DegreeView`
|
1509 |
+
mapping nodes to their degree.
|
1510 |
+
If a single node is requested, returns the degree of the node as an integer.
|
1511 |
+
|
1512 |
+
Examples
|
1513 |
+
--------
|
1514 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1515 |
+
>>> G.degree[0] # node 0 has degree 1
|
1516 |
+
1
|
1517 |
+
>>> list(G.degree([0, 1, 2]))
|
1518 |
+
[(0, 1), (1, 2), (2, 2)]
|
1519 |
+
"""
|
1520 |
+
return DegreeView(self)
|
1521 |
+
|
1522 |
+
def clear(self):
|
1523 |
+
"""Remove all nodes and edges from the graph.
|
1524 |
+
|
1525 |
+
This also removes the name, and all graph, node, and edge attributes.
|
1526 |
+
|
1527 |
+
Examples
|
1528 |
+
--------
|
1529 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1530 |
+
>>> G.clear()
|
1531 |
+
>>> list(G.nodes)
|
1532 |
+
[]
|
1533 |
+
>>> list(G.edges)
|
1534 |
+
[]
|
1535 |
+
|
1536 |
+
"""
|
1537 |
+
self._adj.clear()
|
1538 |
+
self._node.clear()
|
1539 |
+
self.graph.clear()
|
1540 |
+
nx._clear_cache(self)
|
1541 |
+
|
1542 |
+
def clear_edges(self):
|
1543 |
+
"""Remove all edges from the graph without altering nodes.
|
1544 |
+
|
1545 |
+
Examples
|
1546 |
+
--------
|
1547 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1548 |
+
>>> G.clear_edges()
|
1549 |
+
>>> list(G.nodes)
|
1550 |
+
[0, 1, 2, 3]
|
1551 |
+
>>> list(G.edges)
|
1552 |
+
[]
|
1553 |
+
"""
|
1554 |
+
for nbr_dict in self._adj.values():
|
1555 |
+
nbr_dict.clear()
|
1556 |
+
nx._clear_cache(self)
|
1557 |
+
|
1558 |
+
def is_multigraph(self):
|
1559 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
1560 |
+
return False
|
1561 |
+
|
1562 |
+
def is_directed(self):
|
1563 |
+
"""Returns True if graph is directed, False otherwise."""
|
1564 |
+
return False
|
1565 |
+
|
1566 |
+
def copy(self, as_view=False):
|
1567 |
+
"""Returns a copy of the graph.
|
1568 |
+
|
1569 |
+
The copy method by default returns an independent shallow copy
|
1570 |
+
of the graph and attributes. That is, if an attribute is a
|
1571 |
+
container, that container is shared by the original an the copy.
|
1572 |
+
Use Python's `copy.deepcopy` for new containers.
|
1573 |
+
|
1574 |
+
If `as_view` is True then a view is returned instead of a copy.
|
1575 |
+
|
1576 |
+
Notes
|
1577 |
+
-----
|
1578 |
+
All copies reproduce the graph structure, but data attributes
|
1579 |
+
may be handled in different ways. There are four types of copies
|
1580 |
+
of a graph that people might want.
|
1581 |
+
|
1582 |
+
Deepcopy -- A "deepcopy" copies the graph structure as well as
|
1583 |
+
all data attributes and any objects they might contain.
|
1584 |
+
The entire graph object is new so that changes in the copy
|
1585 |
+
do not affect the original object. (see Python's copy.deepcopy)
|
1586 |
+
|
1587 |
+
Data Reference (Shallow) -- For a shallow copy the graph structure
|
1588 |
+
is copied but the edge, node and graph attribute dicts are
|
1589 |
+
references to those in the original graph. This saves
|
1590 |
+
time and memory but could cause confusion if you change an attribute
|
1591 |
+
in one graph and it changes the attribute in the other.
|
1592 |
+
NetworkX does not provide this level of shallow copy.
|
1593 |
+
|
1594 |
+
Independent Shallow -- This copy creates new independent attribute
|
1595 |
+
dicts and then does a shallow copy of the attributes. That is, any
|
1596 |
+
attributes that are containers are shared between the new graph
|
1597 |
+
and the original. This is exactly what `dict.copy()` provides.
|
1598 |
+
You can obtain this style copy using:
|
1599 |
+
|
1600 |
+
>>> G = nx.path_graph(5)
|
1601 |
+
>>> H = G.copy()
|
1602 |
+
>>> H = G.copy(as_view=False)
|
1603 |
+
>>> H = nx.Graph(G)
|
1604 |
+
>>> H = G.__class__(G)
|
1605 |
+
|
1606 |
+
Fresh Data -- For fresh data, the graph structure is copied while
|
1607 |
+
new empty data attribute dicts are created. The resulting graph
|
1608 |
+
is independent of the original and it has no edge, node or graph
|
1609 |
+
attributes. Fresh copies are not enabled. Instead use:
|
1610 |
+
|
1611 |
+
>>> H = G.__class__()
|
1612 |
+
>>> H.add_nodes_from(G)
|
1613 |
+
>>> H.add_edges_from(G.edges)
|
1614 |
+
|
1615 |
+
View -- Inspired by dict-views, graph-views act like read-only
|
1616 |
+
versions of the original graph, providing a copy of the original
|
1617 |
+
structure without requiring any memory for copying the information.
|
1618 |
+
|
1619 |
+
See the Python copy module for more information on shallow
|
1620 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1621 |
+
|
1622 |
+
Parameters
|
1623 |
+
----------
|
1624 |
+
as_view : bool, optional (default=False)
|
1625 |
+
If True, the returned graph-view provides a read-only view
|
1626 |
+
of the original graph without actually copying any data.
|
1627 |
+
|
1628 |
+
Returns
|
1629 |
+
-------
|
1630 |
+
G : Graph
|
1631 |
+
A copy of the graph.
|
1632 |
+
|
1633 |
+
See Also
|
1634 |
+
--------
|
1635 |
+
to_directed: return a directed copy of the graph.
|
1636 |
+
|
1637 |
+
Examples
|
1638 |
+
--------
|
1639 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1640 |
+
>>> H = G.copy()
|
1641 |
+
|
1642 |
+
"""
|
1643 |
+
if as_view is True:
|
1644 |
+
return nx.graphviews.generic_graph_view(self)
|
1645 |
+
G = self.__class__()
|
1646 |
+
G.graph.update(self.graph)
|
1647 |
+
G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
|
1648 |
+
G.add_edges_from(
|
1649 |
+
(u, v, datadict.copy())
|
1650 |
+
for u, nbrs in self._adj.items()
|
1651 |
+
for v, datadict in nbrs.items()
|
1652 |
+
)
|
1653 |
+
return G
|
1654 |
+
|
1655 |
+
def to_directed(self, as_view=False):
|
1656 |
+
"""Returns a directed representation of the graph.
|
1657 |
+
|
1658 |
+
Returns
|
1659 |
+
-------
|
1660 |
+
G : DiGraph
|
1661 |
+
A directed graph with the same name, same nodes, and with
|
1662 |
+
each edge (u, v, data) replaced by two directed edges
|
1663 |
+
(u, v, data) and (v, u, data).
|
1664 |
+
|
1665 |
+
Notes
|
1666 |
+
-----
|
1667 |
+
This returns a "deepcopy" of the edge, node, and
|
1668 |
+
graph attributes which attempts to completely copy
|
1669 |
+
all of the data and references.
|
1670 |
+
|
1671 |
+
This is in contrast to the similar D=DiGraph(G) which returns a
|
1672 |
+
shallow copy of the data.
|
1673 |
+
|
1674 |
+
See the Python copy module for more information on shallow
|
1675 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1676 |
+
|
1677 |
+
Warning: If you have subclassed Graph to use dict-like objects
|
1678 |
+
in the data structure, those changes do not transfer to the
|
1679 |
+
DiGraph created by this method.
|
1680 |
+
|
1681 |
+
Examples
|
1682 |
+
--------
|
1683 |
+
>>> G = nx.Graph() # or MultiGraph, etc
|
1684 |
+
>>> G.add_edge(0, 1)
|
1685 |
+
>>> H = G.to_directed()
|
1686 |
+
>>> list(H.edges)
|
1687 |
+
[(0, 1), (1, 0)]
|
1688 |
+
|
1689 |
+
If already directed, return a (deep) copy
|
1690 |
+
|
1691 |
+
>>> G = nx.DiGraph() # or MultiDiGraph, etc
|
1692 |
+
>>> G.add_edge(0, 1)
|
1693 |
+
>>> H = G.to_directed()
|
1694 |
+
>>> list(H.edges)
|
1695 |
+
[(0, 1)]
|
1696 |
+
"""
|
1697 |
+
graph_class = self.to_directed_class()
|
1698 |
+
if as_view is True:
|
1699 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1700 |
+
# deepcopy when not a view
|
1701 |
+
G = graph_class()
|
1702 |
+
G.graph.update(deepcopy(self.graph))
|
1703 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1704 |
+
G.add_edges_from(
|
1705 |
+
(u, v, deepcopy(data))
|
1706 |
+
for u, nbrs in self._adj.items()
|
1707 |
+
for v, data in nbrs.items()
|
1708 |
+
)
|
1709 |
+
return G
|
1710 |
+
|
1711 |
+
def to_undirected(self, as_view=False):
|
1712 |
+
"""Returns an undirected copy of the graph.
|
1713 |
+
|
1714 |
+
Parameters
|
1715 |
+
----------
|
1716 |
+
as_view : bool (optional, default=False)
|
1717 |
+
If True return a view of the original undirected graph.
|
1718 |
+
|
1719 |
+
Returns
|
1720 |
+
-------
|
1721 |
+
G : Graph/MultiGraph
|
1722 |
+
A deepcopy of the graph.
|
1723 |
+
|
1724 |
+
See Also
|
1725 |
+
--------
|
1726 |
+
Graph, copy, add_edge, add_edges_from
|
1727 |
+
|
1728 |
+
Notes
|
1729 |
+
-----
|
1730 |
+
This returns a "deepcopy" of the edge, node, and
|
1731 |
+
graph attributes which attempts to completely copy
|
1732 |
+
all of the data and references.
|
1733 |
+
|
1734 |
+
This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
|
1735 |
+
shallow copy of the data.
|
1736 |
+
|
1737 |
+
See the Python copy module for more information on shallow
|
1738 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1739 |
+
|
1740 |
+
Warning: If you have subclassed DiGraph to use dict-like objects
|
1741 |
+
in the data structure, those changes do not transfer to the
|
1742 |
+
Graph created by this method.
|
1743 |
+
|
1744 |
+
Examples
|
1745 |
+
--------
|
1746 |
+
>>> G = nx.path_graph(2) # or MultiGraph, etc
|
1747 |
+
>>> H = G.to_directed()
|
1748 |
+
>>> list(H.edges)
|
1749 |
+
[(0, 1), (1, 0)]
|
1750 |
+
>>> G2 = H.to_undirected()
|
1751 |
+
>>> list(G2.edges)
|
1752 |
+
[(0, 1)]
|
1753 |
+
"""
|
1754 |
+
graph_class = self.to_undirected_class()
|
1755 |
+
if as_view is True:
|
1756 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1757 |
+
# deepcopy when not a view
|
1758 |
+
G = graph_class()
|
1759 |
+
G.graph.update(deepcopy(self.graph))
|
1760 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1761 |
+
G.add_edges_from(
|
1762 |
+
(u, v, deepcopy(d))
|
1763 |
+
for u, nbrs in self._adj.items()
|
1764 |
+
for v, d in nbrs.items()
|
1765 |
+
)
|
1766 |
+
return G
|
1767 |
+
|
1768 |
+
def subgraph(self, nodes):
|
1769 |
+
"""Returns a SubGraph view of the subgraph induced on `nodes`.
|
1770 |
+
|
1771 |
+
The induced subgraph of the graph contains the nodes in `nodes`
|
1772 |
+
and the edges between those nodes.
|
1773 |
+
|
1774 |
+
Parameters
|
1775 |
+
----------
|
1776 |
+
nodes : list, iterable
|
1777 |
+
A container of nodes which will be iterated through once.
|
1778 |
+
|
1779 |
+
Returns
|
1780 |
+
-------
|
1781 |
+
G : SubGraph View
|
1782 |
+
A subgraph view of the graph. The graph structure cannot be
|
1783 |
+
changed but node/edge attributes can and are shared with the
|
1784 |
+
original graph.
|
1785 |
+
|
1786 |
+
Notes
|
1787 |
+
-----
|
1788 |
+
The graph, edge and node attributes are shared with the original graph.
|
1789 |
+
Changes to the graph structure is ruled out by the view, but changes
|
1790 |
+
to attributes are reflected in the original graph.
|
1791 |
+
|
1792 |
+
To create a subgraph with its own copy of the edge/node attributes use:
|
1793 |
+
G.subgraph(nodes).copy()
|
1794 |
+
|
1795 |
+
For an inplace reduction of a graph to a subgraph you can remove nodes:
|
1796 |
+
G.remove_nodes_from([n for n in G if n not in set(nodes)])
|
1797 |
+
|
1798 |
+
Subgraph views are sometimes NOT what you want. In most cases where
|
1799 |
+
you want to do more than simply look at the induced edges, it makes
|
1800 |
+
more sense to just create the subgraph as its own graph with code like:
|
1801 |
+
|
1802 |
+
::
|
1803 |
+
|
1804 |
+
# Create a subgraph SG based on a (possibly multigraph) G
|
1805 |
+
SG = G.__class__()
|
1806 |
+
SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
|
1807 |
+
if SG.is_multigraph():
|
1808 |
+
SG.add_edges_from(
|
1809 |
+
(n, nbr, key, d)
|
1810 |
+
for n, nbrs in G.adj.items()
|
1811 |
+
if n in largest_wcc
|
1812 |
+
for nbr, keydict in nbrs.items()
|
1813 |
+
if nbr in largest_wcc
|
1814 |
+
for key, d in keydict.items()
|
1815 |
+
)
|
1816 |
+
else:
|
1817 |
+
SG.add_edges_from(
|
1818 |
+
(n, nbr, d)
|
1819 |
+
for n, nbrs in G.adj.items()
|
1820 |
+
if n in largest_wcc
|
1821 |
+
for nbr, d in nbrs.items()
|
1822 |
+
if nbr in largest_wcc
|
1823 |
+
)
|
1824 |
+
SG.graph.update(G.graph)
|
1825 |
+
|
1826 |
+
Examples
|
1827 |
+
--------
|
1828 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1829 |
+
>>> H = G.subgraph([0, 1, 2])
|
1830 |
+
>>> list(H.edges)
|
1831 |
+
[(0, 1), (1, 2)]
|
1832 |
+
"""
|
1833 |
+
induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
|
1834 |
+
# if already a subgraph, don't make a chain
|
1835 |
+
subgraph = nx.subgraph_view
|
1836 |
+
if hasattr(self, "_NODE_OK"):
|
1837 |
+
return subgraph(
|
1838 |
+
self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
|
1839 |
+
)
|
1840 |
+
return subgraph(self, filter_node=induced_nodes)
|
1841 |
+
|
1842 |
+
def edge_subgraph(self, edges):
|
1843 |
+
"""Returns the subgraph induced by the specified edges.
|
1844 |
+
|
1845 |
+
The induced subgraph contains each edge in `edges` and each
|
1846 |
+
node incident to any one of those edges.
|
1847 |
+
|
1848 |
+
Parameters
|
1849 |
+
----------
|
1850 |
+
edges : iterable
|
1851 |
+
An iterable of edges in this graph.
|
1852 |
+
|
1853 |
+
Returns
|
1854 |
+
-------
|
1855 |
+
G : Graph
|
1856 |
+
An edge-induced subgraph of this graph with the same edge
|
1857 |
+
attributes.
|
1858 |
+
|
1859 |
+
Notes
|
1860 |
+
-----
|
1861 |
+
The graph, edge, and node attributes in the returned subgraph
|
1862 |
+
view are references to the corresponding attributes in the original
|
1863 |
+
graph. The view is read-only.
|
1864 |
+
|
1865 |
+
To create a full graph version of the subgraph with its own copy
|
1866 |
+
of the edge or node attributes, use::
|
1867 |
+
|
1868 |
+
G.edge_subgraph(edges).copy()
|
1869 |
+
|
1870 |
+
Examples
|
1871 |
+
--------
|
1872 |
+
>>> G = nx.path_graph(5)
|
1873 |
+
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
|
1874 |
+
>>> list(H.nodes)
|
1875 |
+
[0, 1, 3, 4]
|
1876 |
+
>>> list(H.edges)
|
1877 |
+
[(0, 1), (3, 4)]
|
1878 |
+
|
1879 |
+
"""
|
1880 |
+
return nx.edge_subgraph(self, edges)
|
1881 |
+
|
1882 |
+
def size(self, weight=None):
|
1883 |
+
"""Returns the number of edges or total of all edge weights.
|
1884 |
+
|
1885 |
+
Parameters
|
1886 |
+
----------
|
1887 |
+
weight : string or None, optional (default=None)
|
1888 |
+
The edge attribute that holds the numerical value used
|
1889 |
+
as a weight. If None, then each edge has weight 1.
|
1890 |
+
|
1891 |
+
Returns
|
1892 |
+
-------
|
1893 |
+
size : numeric
|
1894 |
+
The number of edges or
|
1895 |
+
(if weight keyword is provided) the total weight sum.
|
1896 |
+
|
1897 |
+
If weight is None, returns an int. Otherwise a float
|
1898 |
+
(or more general numeric if the weights are more general).
|
1899 |
+
|
1900 |
+
See Also
|
1901 |
+
--------
|
1902 |
+
number_of_edges
|
1903 |
+
|
1904 |
+
Examples
|
1905 |
+
--------
|
1906 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1907 |
+
>>> G.size()
|
1908 |
+
3
|
1909 |
+
|
1910 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1911 |
+
>>> G.add_edge("a", "b", weight=2)
|
1912 |
+
>>> G.add_edge("b", "c", weight=4)
|
1913 |
+
>>> G.size()
|
1914 |
+
2
|
1915 |
+
>>> G.size(weight="weight")
|
1916 |
+
6.0
|
1917 |
+
"""
|
1918 |
+
s = sum(d for v, d in self.degree(weight=weight))
|
1919 |
+
# If `weight` is None, the sum of the degrees is guaranteed to be
|
1920 |
+
# even, so we can perform integer division and hence return an
|
1921 |
+
# integer. Otherwise, the sum of the weighted degrees is not
|
1922 |
+
# guaranteed to be an integer, so we perform "real" division.
|
1923 |
+
return s // 2 if weight is None else s / 2
|
1924 |
+
|
1925 |
+
def number_of_edges(self, u=None, v=None):
|
1926 |
+
"""Returns the number of edges between two nodes.
|
1927 |
+
|
1928 |
+
Parameters
|
1929 |
+
----------
|
1930 |
+
u, v : nodes, optional (default=all edges)
|
1931 |
+
If u and v are specified, return the number of edges between
|
1932 |
+
u and v. Otherwise return the total number of all edges.
|
1933 |
+
|
1934 |
+
Returns
|
1935 |
+
-------
|
1936 |
+
nedges : int
|
1937 |
+
The number of edges in the graph. If nodes `u` and `v` are
|
1938 |
+
specified return the number of edges between those nodes. If
|
1939 |
+
the graph is directed, this only returns the number of edges
|
1940 |
+
from `u` to `v`.
|
1941 |
+
|
1942 |
+
See Also
|
1943 |
+
--------
|
1944 |
+
size
|
1945 |
+
|
1946 |
+
Examples
|
1947 |
+
--------
|
1948 |
+
For undirected graphs, this method counts the total number of
|
1949 |
+
edges in the graph:
|
1950 |
+
|
1951 |
+
>>> G = nx.path_graph(4)
|
1952 |
+
>>> G.number_of_edges()
|
1953 |
+
3
|
1954 |
+
|
1955 |
+
If you specify two nodes, this counts the total number of edges
|
1956 |
+
joining the two nodes:
|
1957 |
+
|
1958 |
+
>>> G.number_of_edges(0, 1)
|
1959 |
+
1
|
1960 |
+
|
1961 |
+
For directed graphs, this method can count the total number of
|
1962 |
+
directed edges from `u` to `v`:
|
1963 |
+
|
1964 |
+
>>> G = nx.DiGraph()
|
1965 |
+
>>> G.add_edge(0, 1)
|
1966 |
+
>>> G.add_edge(1, 0)
|
1967 |
+
>>> G.number_of_edges(0, 1)
|
1968 |
+
1
|
1969 |
+
|
1970 |
+
"""
|
1971 |
+
if u is None:
|
1972 |
+
return int(self.size())
|
1973 |
+
if v in self._adj[u]:
|
1974 |
+
return 1
|
1975 |
+
return 0
|
1976 |
+
|
1977 |
+
def nbunch_iter(self, nbunch=None):
|
1978 |
+
"""Returns an iterator over nodes contained in nbunch that are
|
1979 |
+
also in the graph.
|
1980 |
+
|
1981 |
+
The nodes in nbunch are checked for membership in the graph
|
1982 |
+
and if not are silently ignored.
|
1983 |
+
|
1984 |
+
Parameters
|
1985 |
+
----------
|
1986 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1987 |
+
The view will only report edges incident to these nodes.
|
1988 |
+
|
1989 |
+
Returns
|
1990 |
+
-------
|
1991 |
+
niter : iterator
|
1992 |
+
An iterator over nodes in nbunch that are also in the graph.
|
1993 |
+
If nbunch is None, iterate over all nodes in the graph.
|
1994 |
+
|
1995 |
+
Raises
|
1996 |
+
------
|
1997 |
+
NetworkXError
|
1998 |
+
If nbunch is not a node or sequence of nodes.
|
1999 |
+
If a node in nbunch is not hashable.
|
2000 |
+
|
2001 |
+
See Also
|
2002 |
+
--------
|
2003 |
+
Graph.__iter__
|
2004 |
+
|
2005 |
+
Notes
|
2006 |
+
-----
|
2007 |
+
When nbunch is an iterator, the returned iterator yields values
|
2008 |
+
directly from nbunch, becoming exhausted when nbunch is exhausted.
|
2009 |
+
|
2010 |
+
To test whether nbunch is a single node, one can use
|
2011 |
+
"if nbunch in self:", even after processing with this routine.
|
2012 |
+
|
2013 |
+
If nbunch is not a node or a (possibly empty) sequence/iterator
|
2014 |
+
or None, a :exc:`NetworkXError` is raised. Also, if any object in
|
2015 |
+
nbunch is not hashable, a :exc:`NetworkXError` is raised.
|
2016 |
+
"""
|
2017 |
+
if nbunch is None: # include all nodes via iterator
|
2018 |
+
bunch = iter(self._adj)
|
2019 |
+
elif nbunch in self: # if nbunch is a single node
|
2020 |
+
bunch = iter([nbunch])
|
2021 |
+
else: # if nbunch is a sequence of nodes
|
2022 |
+
|
2023 |
+
def bunch_iter(nlist, adj):
|
2024 |
+
try:
|
2025 |
+
for n in nlist:
|
2026 |
+
if n in adj:
|
2027 |
+
yield n
|
2028 |
+
except TypeError as err:
|
2029 |
+
exc, message = err, err.args[0]
|
2030 |
+
# capture error for non-sequence/iterator nbunch.
|
2031 |
+
if "iter" in message:
|
2032 |
+
exc = NetworkXError(
|
2033 |
+
"nbunch is not a node or a sequence of nodes."
|
2034 |
+
)
|
2035 |
+
# capture error for unhashable node.
|
2036 |
+
if "hashable" in message:
|
2037 |
+
exc = NetworkXError(
|
2038 |
+
f"Node {n} in sequence nbunch is not a valid node."
|
2039 |
+
)
|
2040 |
+
raise exc
|
2041 |
+
|
2042 |
+
bunch = bunch_iter(nbunch, self._adj)
|
2043 |
+
return bunch
|
venv/lib/python3.10/site-packages/networkx/classes/graphviews.py
ADDED
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""View of Graphs as SubGraph, Reverse, Directed, Undirected.
|
2 |
+
|
3 |
+
In some algorithms it is convenient to temporarily morph
|
4 |
+
a graph to exclude some nodes or edges. It should be better
|
5 |
+
to do that via a view than to remove and then re-add.
|
6 |
+
In other algorithms it is convenient to temporarily morph
|
7 |
+
a graph to reverse directed edges, or treat a directed graph
|
8 |
+
as undirected, etc. This module provides those graph views.
|
9 |
+
|
10 |
+
The resulting views are essentially read-only graphs that
|
11 |
+
report data from the original graph object. We provide an
|
12 |
+
attribute G._graph which points to the underlying graph object.
|
13 |
+
|
14 |
+
Note: Since graphviews look like graphs, one can end up with
|
15 |
+
view-of-view-of-view chains. Be careful with chains because
|
16 |
+
they become very slow with about 15 nested views.
|
17 |
+
For the common simple case of node induced subgraphs created
|
18 |
+
from the graph class, we short-cut the chain by returning a
|
19 |
+
subgraph of the original graph directly rather than a subgraph
|
20 |
+
of a subgraph. We are careful not to disrupt any edge filter in
|
21 |
+
the middle subgraph. In general, determining how to short-cut
|
22 |
+
the chain is tricky and much harder with restricted_views than
|
23 |
+
with induced subgraphs.
|
24 |
+
Often it is easiest to use .copy() to avoid chains.
|
25 |
+
"""
|
26 |
+
import networkx as nx
|
27 |
+
from networkx.classes.coreviews import (
|
28 |
+
FilterAdjacency,
|
29 |
+
FilterAtlas,
|
30 |
+
FilterMultiAdjacency,
|
31 |
+
UnionAdjacency,
|
32 |
+
UnionMultiAdjacency,
|
33 |
+
)
|
34 |
+
from networkx.classes.filters import no_filter
|
35 |
+
from networkx.exception import NetworkXError
|
36 |
+
from networkx.utils import deprecate_positional_args, not_implemented_for
|
37 |
+
|
38 |
+
__all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
|
39 |
+
|
40 |
+
|
41 |
+
def generic_graph_view(G, create_using=None):
|
42 |
+
"""Returns a read-only view of `G`.
|
43 |
+
|
44 |
+
The graph `G` and its attributes are not copied but viewed through the new graph object
|
45 |
+
of the same class as `G` (or of the class specified in `create_using`).
|
46 |
+
|
47 |
+
Parameters
|
48 |
+
----------
|
49 |
+
G : graph
|
50 |
+
A directed/undirected graph/multigraph.
|
51 |
+
|
52 |
+
create_using : NetworkX graph constructor, optional (default=None)
|
53 |
+
Graph type to create. If graph instance, then cleared before populated.
|
54 |
+
If `None`, then the appropriate Graph type is inferred from `G`.
|
55 |
+
|
56 |
+
Returns
|
57 |
+
-------
|
58 |
+
newG : graph
|
59 |
+
A view of the input graph `G` and its attributes as viewed through
|
60 |
+
the `create_using` class.
|
61 |
+
|
62 |
+
Raises
|
63 |
+
------
|
64 |
+
NetworkXError
|
65 |
+
If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
|
66 |
+
|
67 |
+
Notes
|
68 |
+
-----
|
69 |
+
The returned graph view is read-only (cannot modify the graph).
|
70 |
+
Yet the view reflects any changes in `G`. The intent is to mimic dict views.
|
71 |
+
|
72 |
+
Examples
|
73 |
+
--------
|
74 |
+
>>> G = nx.Graph()
|
75 |
+
>>> G.add_edge(1, 2, weight=0.3)
|
76 |
+
>>> G.add_edge(2, 3, weight=0.5)
|
77 |
+
>>> G.edges(data=True)
|
78 |
+
EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
|
79 |
+
|
80 |
+
The view exposes the attributes from the original graph.
|
81 |
+
|
82 |
+
>>> viewG = nx.graphviews.generic_graph_view(G)
|
83 |
+
>>> viewG.edges(data=True)
|
84 |
+
EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
|
85 |
+
|
86 |
+
Changes to `G` are reflected in `viewG`.
|
87 |
+
|
88 |
+
>>> G.remove_edge(2, 3)
|
89 |
+
>>> G.edges(data=True)
|
90 |
+
EdgeDataView([(1, 2, {'weight': 0.3})])
|
91 |
+
|
92 |
+
>>> viewG.edges(data=True)
|
93 |
+
EdgeDataView([(1, 2, {'weight': 0.3})])
|
94 |
+
|
95 |
+
We can change the graph type with the `create_using` parameter.
|
96 |
+
|
97 |
+
>>> type(G)
|
98 |
+
<class 'networkx.classes.graph.Graph'>
|
99 |
+
>>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph)
|
100 |
+
>>> type(viewDG)
|
101 |
+
<class 'networkx.classes.digraph.DiGraph'>
|
102 |
+
"""
|
103 |
+
if create_using is None:
|
104 |
+
newG = G.__class__()
|
105 |
+
else:
|
106 |
+
newG = nx.empty_graph(0, create_using)
|
107 |
+
if G.is_multigraph() != newG.is_multigraph():
|
108 |
+
raise NetworkXError("Multigraph for G must agree with create_using")
|
109 |
+
newG = nx.freeze(newG)
|
110 |
+
|
111 |
+
# create view by assigning attributes from G
|
112 |
+
newG._graph = G
|
113 |
+
newG.graph = G.graph
|
114 |
+
|
115 |
+
newG._node = G._node
|
116 |
+
if newG.is_directed():
|
117 |
+
if G.is_directed():
|
118 |
+
newG._succ = G._succ
|
119 |
+
newG._pred = G._pred
|
120 |
+
# newG._adj is synced with _succ
|
121 |
+
else:
|
122 |
+
newG._succ = G._adj
|
123 |
+
newG._pred = G._adj
|
124 |
+
# newG._adj is synced with _succ
|
125 |
+
elif G.is_directed():
|
126 |
+
if G.is_multigraph():
|
127 |
+
newG._adj = UnionMultiAdjacency(G._succ, G._pred)
|
128 |
+
else:
|
129 |
+
newG._adj = UnionAdjacency(G._succ, G._pred)
|
130 |
+
else:
|
131 |
+
newG._adj = G._adj
|
132 |
+
return newG
|
133 |
+
|
134 |
+
|
135 |
+
@deprecate_positional_args(version="3.4")
|
136 |
+
def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter):
|
137 |
+
"""View of `G` applying a filter on nodes and edges.
|
138 |
+
|
139 |
+
`subgraph_view` provides a read-only view of the input graph that excludes
|
140 |
+
nodes and edges based on the outcome of two filter functions `filter_node`
|
141 |
+
and `filter_edge`.
|
142 |
+
|
143 |
+
The `filter_node` function takes one argument --- the node --- and returns
|
144 |
+
`True` if the node should be included in the subgraph, and `False` if it
|
145 |
+
should not be included.
|
146 |
+
|
147 |
+
The `filter_edge` function takes two (or three arguments if `G` is a
|
148 |
+
multi-graph) --- the nodes describing an edge, plus the edge-key if
|
149 |
+
parallel edges are possible --- and returns `True` if the edge should be
|
150 |
+
included in the subgraph, and `False` if it should not be included.
|
151 |
+
|
152 |
+
Both node and edge filter functions are called on graph elements as they
|
153 |
+
are queried, meaning there is no up-front cost to creating the view.
|
154 |
+
|
155 |
+
Parameters
|
156 |
+
----------
|
157 |
+
G : networkx.Graph
|
158 |
+
A directed/undirected graph/multigraph
|
159 |
+
|
160 |
+
filter_node : callable, optional
|
161 |
+
A function taking a node as input, which returns `True` if the node
|
162 |
+
should appear in the view.
|
163 |
+
|
164 |
+
filter_edge : callable, optional
|
165 |
+
A function taking as input the two nodes describing an edge (plus the
|
166 |
+
edge-key if `G` is a multi-graph), which returns `True` if the edge
|
167 |
+
should appear in the view.
|
168 |
+
|
169 |
+
Returns
|
170 |
+
-------
|
171 |
+
graph : networkx.Graph
|
172 |
+
A read-only graph view of the input graph.
|
173 |
+
|
174 |
+
Examples
|
175 |
+
--------
|
176 |
+
>>> G = nx.path_graph(6)
|
177 |
+
|
178 |
+
Filter functions operate on the node, and return `True` if the node should
|
179 |
+
appear in the view:
|
180 |
+
|
181 |
+
>>> def filter_node(n1):
|
182 |
+
... return n1 != 5
|
183 |
+
>>> view = nx.subgraph_view(G, filter_node=filter_node)
|
184 |
+
>>> view.nodes()
|
185 |
+
NodeView((0, 1, 2, 3, 4))
|
186 |
+
|
187 |
+
We can use a closure pattern to filter graph elements based on additional
|
188 |
+
data --- for example, filtering on edge data attached to the graph:
|
189 |
+
|
190 |
+
>>> G[3][4]["cross_me"] = False
|
191 |
+
>>> def filter_edge(n1, n2):
|
192 |
+
... return G[n1][n2].get("cross_me", True)
|
193 |
+
>>> view = nx.subgraph_view(G, filter_edge=filter_edge)
|
194 |
+
>>> view.edges()
|
195 |
+
EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
|
196 |
+
|
197 |
+
>>> view = nx.subgraph_view(
|
198 |
+
... G,
|
199 |
+
... filter_node=filter_node,
|
200 |
+
... filter_edge=filter_edge,
|
201 |
+
... )
|
202 |
+
>>> view.nodes()
|
203 |
+
NodeView((0, 1, 2, 3, 4))
|
204 |
+
>>> view.edges()
|
205 |
+
EdgeView([(0, 1), (1, 2), (2, 3)])
|
206 |
+
"""
|
207 |
+
newG = nx.freeze(G.__class__())
|
208 |
+
newG._NODE_OK = filter_node
|
209 |
+
newG._EDGE_OK = filter_edge
|
210 |
+
|
211 |
+
# create view by assigning attributes from G
|
212 |
+
newG._graph = G
|
213 |
+
newG.graph = G.graph
|
214 |
+
|
215 |
+
newG._node = FilterAtlas(G._node, filter_node)
|
216 |
+
if G.is_multigraph():
|
217 |
+
Adj = FilterMultiAdjacency
|
218 |
+
|
219 |
+
def reverse_edge(u, v, k=None):
|
220 |
+
return filter_edge(v, u, k)
|
221 |
+
|
222 |
+
else:
|
223 |
+
Adj = FilterAdjacency
|
224 |
+
|
225 |
+
def reverse_edge(u, v, k=None):
|
226 |
+
return filter_edge(v, u)
|
227 |
+
|
228 |
+
if G.is_directed():
|
229 |
+
newG._succ = Adj(G._succ, filter_node, filter_edge)
|
230 |
+
newG._pred = Adj(G._pred, filter_node, reverse_edge)
|
231 |
+
# newG._adj is synced with _succ
|
232 |
+
else:
|
233 |
+
newG._adj = Adj(G._adj, filter_node, filter_edge)
|
234 |
+
return newG
|
235 |
+
|
236 |
+
|
237 |
+
@not_implemented_for("undirected")
|
238 |
+
def reverse_view(G):
|
239 |
+
"""View of `G` with edge directions reversed
|
240 |
+
|
241 |
+
`reverse_view` returns a read-only view of the input graph where
|
242 |
+
edge directions are reversed.
|
243 |
+
|
244 |
+
Identical to digraph.reverse(copy=False)
|
245 |
+
|
246 |
+
Parameters
|
247 |
+
----------
|
248 |
+
G : networkx.DiGraph
|
249 |
+
|
250 |
+
Returns
|
251 |
+
-------
|
252 |
+
graph : networkx.DiGraph
|
253 |
+
|
254 |
+
Examples
|
255 |
+
--------
|
256 |
+
>>> G = nx.DiGraph()
|
257 |
+
>>> G.add_edge(1, 2)
|
258 |
+
>>> G.add_edge(2, 3)
|
259 |
+
>>> G.edges()
|
260 |
+
OutEdgeView([(1, 2), (2, 3)])
|
261 |
+
|
262 |
+
>>> view = nx.reverse_view(G)
|
263 |
+
>>> view.edges()
|
264 |
+
OutEdgeView([(2, 1), (3, 2)])
|
265 |
+
"""
|
266 |
+
newG = generic_graph_view(G)
|
267 |
+
newG._succ, newG._pred = G._pred, G._succ
|
268 |
+
# newG._adj is synced with _succ
|
269 |
+
return newG
|
venv/lib/python3.10/site-packages/networkx/classes/multidigraph.py
ADDED
@@ -0,0 +1,965 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for MultiDiGraph."""
|
2 |
+
from copy import deepcopy
|
3 |
+
from functools import cached_property
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx import convert
|
7 |
+
from networkx.classes.coreviews import MultiAdjacencyView
|
8 |
+
from networkx.classes.digraph import DiGraph
|
9 |
+
from networkx.classes.multigraph import MultiGraph
|
10 |
+
from networkx.classes.reportviews import (
|
11 |
+
DiMultiDegreeView,
|
12 |
+
InMultiDegreeView,
|
13 |
+
InMultiEdgeView,
|
14 |
+
OutMultiDegreeView,
|
15 |
+
OutMultiEdgeView,
|
16 |
+
)
|
17 |
+
from networkx.exception import NetworkXError
|
18 |
+
|
19 |
+
__all__ = ["MultiDiGraph"]
|
20 |
+
|
21 |
+
|
22 |
+
class MultiDiGraph(MultiGraph, DiGraph):
|
23 |
+
"""A directed graph class that can store multiedges.
|
24 |
+
|
25 |
+
Multiedges are multiple edges between two nodes. Each edge
|
26 |
+
can hold optional data or attributes.
|
27 |
+
|
28 |
+
A MultiDiGraph holds directed edges. Self loops are allowed.
|
29 |
+
|
30 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
31 |
+
key/value attributes. By convention `None` is not used as a node.
|
32 |
+
|
33 |
+
Edges are represented as links between nodes with optional
|
34 |
+
key/value attributes.
|
35 |
+
|
36 |
+
Parameters
|
37 |
+
----------
|
38 |
+
incoming_graph_data : input graph (optional, default: None)
|
39 |
+
Data to initialize graph. If None (default) an empty
|
40 |
+
graph is created. The data can be any format that is supported
|
41 |
+
by the to_networkx_graph() function, currently including edge list,
|
42 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
|
43 |
+
sparse matrix, or PyGraphviz graph.
|
44 |
+
|
45 |
+
multigraph_input : bool or None (default None)
|
46 |
+
Note: Only used when `incoming_graph_data` is a dict.
|
47 |
+
If True, `incoming_graph_data` is assumed to be a
|
48 |
+
dict-of-dict-of-dict-of-dict structure keyed by
|
49 |
+
node to neighbor to edge keys to edge data for multi-edges.
|
50 |
+
A NetworkXError is raised if this is not the case.
|
51 |
+
If False, :func:`to_networkx_graph` is used to try to determine
|
52 |
+
the dict's graph data structure as either a dict-of-dict-of-dict
|
53 |
+
keyed by node to neighbor to edge data, or a dict-of-iterable
|
54 |
+
keyed by node to neighbors.
|
55 |
+
If None, the treatment for True is tried, but if it fails,
|
56 |
+
the treatment for False is tried.
|
57 |
+
|
58 |
+
attr : keyword arguments, optional (default= no attributes)
|
59 |
+
Attributes to add to graph as key=value pairs.
|
60 |
+
|
61 |
+
See Also
|
62 |
+
--------
|
63 |
+
Graph
|
64 |
+
DiGraph
|
65 |
+
MultiGraph
|
66 |
+
|
67 |
+
Examples
|
68 |
+
--------
|
69 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
70 |
+
no edges.
|
71 |
+
|
72 |
+
>>> G = nx.MultiDiGraph()
|
73 |
+
|
74 |
+
G can be grown in several ways.
|
75 |
+
|
76 |
+
**Nodes:**
|
77 |
+
|
78 |
+
Add one node at a time:
|
79 |
+
|
80 |
+
>>> G.add_node(1)
|
81 |
+
|
82 |
+
Add the nodes from any container (a list, dict, set or
|
83 |
+
even the lines from a file or the nodes from another graph).
|
84 |
+
|
85 |
+
>>> G.add_nodes_from([2, 3])
|
86 |
+
>>> G.add_nodes_from(range(100, 110))
|
87 |
+
>>> H = nx.path_graph(10)
|
88 |
+
>>> G.add_nodes_from(H)
|
89 |
+
|
90 |
+
In addition to strings and integers any hashable Python object
|
91 |
+
(except None) can represent a node, e.g. a customized node object,
|
92 |
+
or even another Graph.
|
93 |
+
|
94 |
+
>>> G.add_node(H)
|
95 |
+
|
96 |
+
**Edges:**
|
97 |
+
|
98 |
+
G can also be grown by adding edges.
|
99 |
+
|
100 |
+
Add one edge,
|
101 |
+
|
102 |
+
>>> key = G.add_edge(1, 2)
|
103 |
+
|
104 |
+
a list of edges,
|
105 |
+
|
106 |
+
>>> keys = G.add_edges_from([(1, 2), (1, 3)])
|
107 |
+
|
108 |
+
or a collection of edges,
|
109 |
+
|
110 |
+
>>> keys = G.add_edges_from(H.edges)
|
111 |
+
|
112 |
+
If some edges connect nodes not yet in the graph, the nodes
|
113 |
+
are added automatically. If an edge already exists, an additional
|
114 |
+
edge is created and stored using a key to identify the edge.
|
115 |
+
By default the key is the lowest unused integer.
|
116 |
+
|
117 |
+
>>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
|
118 |
+
>>> G[4]
|
119 |
+
AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
|
120 |
+
|
121 |
+
**Attributes:**
|
122 |
+
|
123 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
124 |
+
in an associated attribute dictionary (the keys must be hashable).
|
125 |
+
By default these are empty, but can be added or changed using
|
126 |
+
add_edge, add_node or direct manipulation of the attribute
|
127 |
+
dictionaries named graph, node and edge respectively.
|
128 |
+
|
129 |
+
>>> G = nx.MultiDiGraph(day="Friday")
|
130 |
+
>>> G.graph
|
131 |
+
{'day': 'Friday'}
|
132 |
+
|
133 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
134 |
+
|
135 |
+
>>> G.add_node(1, time="5pm")
|
136 |
+
>>> G.add_nodes_from([3], time="2pm")
|
137 |
+
>>> G.nodes[1]
|
138 |
+
{'time': '5pm'}
|
139 |
+
>>> G.nodes[1]["room"] = 714
|
140 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
141 |
+
>>> list(G.nodes(data=True))
|
142 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
143 |
+
|
144 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
145 |
+
notation, or G.edges.
|
146 |
+
|
147 |
+
>>> key = G.add_edge(1, 2, weight=4.7)
|
148 |
+
>>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
|
149 |
+
>>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
150 |
+
>>> G[1][2][0]["weight"] = 4.7
|
151 |
+
>>> G.edges[1, 2, 0]["weight"] = 4
|
152 |
+
|
153 |
+
Warning: we protect the graph data structure by making `G.edges[1,
|
154 |
+
2, 0]` a read-only dict-like structure. However, you can assign to
|
155 |
+
attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
|
156 |
+
to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
|
157 |
+
(for multigraphs the edge key is required: `MG.edges[u, v,
|
158 |
+
key][name] = value`).
|
159 |
+
|
160 |
+
**Shortcuts:**
|
161 |
+
|
162 |
+
Many common graph features allow python syntax to speed reporting.
|
163 |
+
|
164 |
+
>>> 1 in G # check if node in graph
|
165 |
+
True
|
166 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
167 |
+
[1, 2]
|
168 |
+
>>> len(G) # number of nodes in graph
|
169 |
+
5
|
170 |
+
>>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
|
171 |
+
AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
|
172 |
+
|
173 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
174 |
+
The neighbors are available as an adjacency-view `G.adj` object or via
|
175 |
+
the method `G.adjacency()`.
|
176 |
+
|
177 |
+
>>> for n, nbrsdict in G.adjacency():
|
178 |
+
... for nbr, keydict in nbrsdict.items():
|
179 |
+
... for key, eattr in keydict.items():
|
180 |
+
... if "weight" in eattr:
|
181 |
+
... # Do something useful with the edges
|
182 |
+
... pass
|
183 |
+
|
184 |
+
But the edges() method is often more convenient:
|
185 |
+
|
186 |
+
>>> for u, v, keys, weight in G.edges(data="weight", keys=True):
|
187 |
+
... if weight is not None:
|
188 |
+
... # Do something useful with the edges
|
189 |
+
... pass
|
190 |
+
|
191 |
+
**Reporting:**
|
192 |
+
|
193 |
+
Simple graph information is obtained using methods and object-attributes.
|
194 |
+
Reporting usually provides views instead of containers to reduce memory
|
195 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
196 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
197 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
|
198 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
199 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
200 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
201 |
+
|
202 |
+
For details on these and other miscellaneous methods, see below.
|
203 |
+
|
204 |
+
**Subclasses (Advanced):**
|
205 |
+
|
206 |
+
The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
|
207 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
208 |
+
The next dict (adjlist_dict) represents the adjacency information
|
209 |
+
and holds edge_key dicts keyed by neighbor. The edge_key dict holds
|
210 |
+
each edge_attr dict keyed by edge key. The inner dict
|
211 |
+
(edge_attr_dict) represents the edge data and holds edge attribute
|
212 |
+
values keyed by attribute names.
|
213 |
+
|
214 |
+
Each of these four dicts in the dict-of-dict-of-dict-of-dict
|
215 |
+
structure can be replaced by a user defined dict-like object.
|
216 |
+
In general, the dict-like features should be maintained but
|
217 |
+
extra features can be added. To replace one of the dicts create
|
218 |
+
a new graph class by changing the class(!) variable holding the
|
219 |
+
factory for that dict-like structure. The variable names are
|
220 |
+
node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
|
221 |
+
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
|
222 |
+
and graph_attr_dict_factory.
|
223 |
+
|
224 |
+
node_dict_factory : function, (default: dict)
|
225 |
+
Factory function to be used to create the dict containing node
|
226 |
+
attributes, keyed by node id.
|
227 |
+
It should require no arguments and return a dict-like object
|
228 |
+
|
229 |
+
node_attr_dict_factory: function, (default: dict)
|
230 |
+
Factory function to be used to create the node attribute
|
231 |
+
dict which holds attribute values keyed by attribute name.
|
232 |
+
It should require no arguments and return a dict-like object
|
233 |
+
|
234 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
235 |
+
Factory function to be used to create the outer-most dict
|
236 |
+
in the data structure that holds adjacency info keyed by node.
|
237 |
+
It should require no arguments and return a dict-like object.
|
238 |
+
|
239 |
+
adjlist_inner_dict_factory : function, (default: dict)
|
240 |
+
Factory function to be used to create the adjacency list
|
241 |
+
dict which holds multiedge key dicts keyed by neighbor.
|
242 |
+
It should require no arguments and return a dict-like object.
|
243 |
+
|
244 |
+
edge_key_dict_factory : function, (default: dict)
|
245 |
+
Factory function to be used to create the edge key dict
|
246 |
+
which holds edge data keyed by edge key.
|
247 |
+
It should require no arguments and return a dict-like object.
|
248 |
+
|
249 |
+
edge_attr_dict_factory : function, (default: dict)
|
250 |
+
Factory function to be used to create the edge attribute
|
251 |
+
dict which holds attribute values keyed by attribute name.
|
252 |
+
It should require no arguments and return a dict-like object.
|
253 |
+
|
254 |
+
graph_attr_dict_factory : function, (default: dict)
|
255 |
+
Factory function to be used to create the graph attribute
|
256 |
+
dict which holds attribute values keyed by attribute name.
|
257 |
+
It should require no arguments and return a dict-like object.
|
258 |
+
|
259 |
+
Typically, if your extension doesn't impact the data structure all
|
260 |
+
methods will inherited without issue except: `to_directed/to_undirected`.
|
261 |
+
By default these methods create a DiGraph/Graph class and you probably
|
262 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
263 |
+
this we define two class variables that you can set in your subclass.
|
264 |
+
|
265 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
266 |
+
Class to create a new graph structure in the `to_directed` method.
|
267 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
268 |
+
|
269 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
270 |
+
Class to create a new graph structure in the `to_undirected` method.
|
271 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
272 |
+
|
273 |
+
**Subclassing Example**
|
274 |
+
|
275 |
+
Create a low memory graph class that effectively disallows edge
|
276 |
+
attributes by using a single attribute dict for all edges.
|
277 |
+
This reduces the memory used, but you lose edge attributes.
|
278 |
+
|
279 |
+
>>> class ThinGraph(nx.Graph):
|
280 |
+
... all_edge_dict = {"weight": 1}
|
281 |
+
...
|
282 |
+
... def single_edge_dict(self):
|
283 |
+
... return self.all_edge_dict
|
284 |
+
...
|
285 |
+
... edge_attr_dict_factory = single_edge_dict
|
286 |
+
>>> G = ThinGraph()
|
287 |
+
>>> G.add_edge(2, 1)
|
288 |
+
>>> G[2][1]
|
289 |
+
{'weight': 1}
|
290 |
+
>>> G.add_edge(2, 2)
|
291 |
+
>>> G[2][1] is G[2][2]
|
292 |
+
True
|
293 |
+
"""
|
294 |
+
|
295 |
+
# node_dict_factory = dict # already assigned in Graph
|
296 |
+
# adjlist_outer_dict_factory = dict
|
297 |
+
# adjlist_inner_dict_factory = dict
|
298 |
+
edge_key_dict_factory = dict
|
299 |
+
# edge_attr_dict_factory = dict
|
300 |
+
|
301 |
+
def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
|
302 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
303 |
+
|
304 |
+
Parameters
|
305 |
+
----------
|
306 |
+
incoming_graph_data : input graph
|
307 |
+
Data to initialize graph. If incoming_graph_data=None (default)
|
308 |
+
an empty graph is created. The data can be an edge list, or any
|
309 |
+
NetworkX graph object. If the corresponding optional Python
|
310 |
+
packages are installed the data can also be a 2D NumPy array, a
|
311 |
+
SciPy sparse array, or a PyGraphviz graph.
|
312 |
+
|
313 |
+
multigraph_input : bool or None (default None)
|
314 |
+
Note: Only used when `incoming_graph_data` is a dict.
|
315 |
+
If True, `incoming_graph_data` is assumed to be a
|
316 |
+
dict-of-dict-of-dict-of-dict structure keyed by
|
317 |
+
node to neighbor to edge keys to edge data for multi-edges.
|
318 |
+
A NetworkXError is raised if this is not the case.
|
319 |
+
If False, :func:`to_networkx_graph` is used to try to determine
|
320 |
+
the dict's graph data structure as either a dict-of-dict-of-dict
|
321 |
+
keyed by node to neighbor to edge data, or a dict-of-iterable
|
322 |
+
keyed by node to neighbors.
|
323 |
+
If None, the treatment for True is tried, but if it fails,
|
324 |
+
the treatment for False is tried.
|
325 |
+
|
326 |
+
attr : keyword arguments, optional (default= no attributes)
|
327 |
+
Attributes to add to graph as key=value pairs.
|
328 |
+
|
329 |
+
See Also
|
330 |
+
--------
|
331 |
+
convert
|
332 |
+
|
333 |
+
Examples
|
334 |
+
--------
|
335 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
336 |
+
>>> G = nx.Graph(name="my graph")
|
337 |
+
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
|
338 |
+
>>> G = nx.Graph(e)
|
339 |
+
|
340 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
341 |
+
|
342 |
+
>>> G = nx.Graph(e, day="Friday")
|
343 |
+
>>> G.graph
|
344 |
+
{'day': 'Friday'}
|
345 |
+
|
346 |
+
"""
|
347 |
+
# multigraph_input can be None/True/False. So check "is not False"
|
348 |
+
if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
|
349 |
+
DiGraph.__init__(self)
|
350 |
+
try:
|
351 |
+
convert.from_dict_of_dicts(
|
352 |
+
incoming_graph_data, create_using=self, multigraph_input=True
|
353 |
+
)
|
354 |
+
self.graph.update(attr)
|
355 |
+
except Exception as err:
|
356 |
+
if multigraph_input is True:
|
357 |
+
raise nx.NetworkXError(
|
358 |
+
f"converting multigraph_input raised:\n{type(err)}: {err}"
|
359 |
+
)
|
360 |
+
DiGraph.__init__(self, incoming_graph_data, **attr)
|
361 |
+
else:
|
362 |
+
DiGraph.__init__(self, incoming_graph_data, **attr)
|
363 |
+
|
364 |
+
@cached_property
|
365 |
+
def adj(self):
|
366 |
+
"""Graph adjacency object holding the neighbors of each node.
|
367 |
+
|
368 |
+
This object is a read-only dict-like structure with node keys
|
369 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
370 |
+
to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
371 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
372 |
+
|
373 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
374 |
+
`for nbr, datadict in G.adj[n].items():`.
|
375 |
+
|
376 |
+
The neighbor information is also provided by subscripting the graph.
|
377 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
378 |
+
|
379 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
380 |
+
"""
|
381 |
+
return MultiAdjacencyView(self._succ)
|
382 |
+
|
383 |
+
@cached_property
|
384 |
+
def succ(self):
|
385 |
+
"""Graph adjacency object holding the successors of each node.
|
386 |
+
|
387 |
+
This object is a read-only dict-like structure with node keys
|
388 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
389 |
+
to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
390 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
391 |
+
|
392 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
393 |
+
`for nbr, datadict in G.adj[n].items():`.
|
394 |
+
|
395 |
+
The neighbor information is also provided by subscripting the graph.
|
396 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
397 |
+
|
398 |
+
For directed graphs, `G.succ` is identical to `G.adj`.
|
399 |
+
"""
|
400 |
+
return MultiAdjacencyView(self._succ)
|
401 |
+
|
402 |
+
@cached_property
|
403 |
+
def pred(self):
|
404 |
+
"""Graph adjacency object holding the predecessors of each node.
|
405 |
+
|
406 |
+
This object is a read-only dict-like structure with node keys
|
407 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
408 |
+
to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
409 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
410 |
+
|
411 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
412 |
+
`for nbr, datadict in G.adj[n].items():`.
|
413 |
+
"""
|
414 |
+
return MultiAdjacencyView(self._pred)
|
415 |
+
|
416 |
+
def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
|
417 |
+
"""Add an edge between u and v.
|
418 |
+
|
419 |
+
The nodes u and v will be automatically added if they are
|
420 |
+
not already in the graph.
|
421 |
+
|
422 |
+
Edge attributes can be specified with keywords or by directly
|
423 |
+
accessing the edge's attribute dictionary. See examples below.
|
424 |
+
|
425 |
+
Parameters
|
426 |
+
----------
|
427 |
+
u_for_edge, v_for_edge : nodes
|
428 |
+
Nodes can be, for example, strings or numbers.
|
429 |
+
Nodes must be hashable (and not None) Python objects.
|
430 |
+
key : hashable identifier, optional (default=lowest unused integer)
|
431 |
+
Used to distinguish multiedges between a pair of nodes.
|
432 |
+
attr : keyword arguments, optional
|
433 |
+
Edge data (or labels or objects) can be assigned using
|
434 |
+
keyword arguments.
|
435 |
+
|
436 |
+
Returns
|
437 |
+
-------
|
438 |
+
The edge key assigned to the edge.
|
439 |
+
|
440 |
+
See Also
|
441 |
+
--------
|
442 |
+
add_edges_from : add a collection of edges
|
443 |
+
|
444 |
+
Notes
|
445 |
+
-----
|
446 |
+
To replace/update edge data, use the optional key argument
|
447 |
+
to identify a unique edge. Otherwise a new edge will be created.
|
448 |
+
|
449 |
+
NetworkX algorithms designed for weighted graphs cannot use
|
450 |
+
multigraphs directly because it is not clear how to handle
|
451 |
+
multiedge weights. Convert to Graph using edge attribute
|
452 |
+
'weight' to enable weighted graph algorithms.
|
453 |
+
|
454 |
+
Default keys are generated using the method `new_edge_key()`.
|
455 |
+
This method can be overridden by subclassing the base class and
|
456 |
+
providing a custom `new_edge_key()` method.
|
457 |
+
|
458 |
+
Examples
|
459 |
+
--------
|
460 |
+
The following all add the edge e=(1, 2) to graph G:
|
461 |
+
|
462 |
+
>>> G = nx.MultiDiGraph()
|
463 |
+
>>> e = (1, 2)
|
464 |
+
>>> key = G.add_edge(1, 2) # explicit two-node form
|
465 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
466 |
+
1
|
467 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
468 |
+
[2]
|
469 |
+
|
470 |
+
Associate data to edges using keywords:
|
471 |
+
|
472 |
+
>>> key = G.add_edge(1, 2, weight=3)
|
473 |
+
>>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
|
474 |
+
>>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
475 |
+
|
476 |
+
For non-string attribute keys, use subscript notation.
|
477 |
+
|
478 |
+
>>> ekey = G.add_edge(1, 2)
|
479 |
+
>>> G[1][2][0].update({0: 5})
|
480 |
+
>>> G.edges[1, 2, 0].update({0: 5})
|
481 |
+
"""
|
482 |
+
u, v = u_for_edge, v_for_edge
|
483 |
+
# add nodes
|
484 |
+
if u not in self._succ:
|
485 |
+
if u is None:
|
486 |
+
raise ValueError("None cannot be a node")
|
487 |
+
self._succ[u] = self.adjlist_inner_dict_factory()
|
488 |
+
self._pred[u] = self.adjlist_inner_dict_factory()
|
489 |
+
self._node[u] = self.node_attr_dict_factory()
|
490 |
+
if v not in self._succ:
|
491 |
+
if v is None:
|
492 |
+
raise ValueError("None cannot be a node")
|
493 |
+
self._succ[v] = self.adjlist_inner_dict_factory()
|
494 |
+
self._pred[v] = self.adjlist_inner_dict_factory()
|
495 |
+
self._node[v] = self.node_attr_dict_factory()
|
496 |
+
if key is None:
|
497 |
+
key = self.new_edge_key(u, v)
|
498 |
+
if v in self._succ[u]:
|
499 |
+
keydict = self._adj[u][v]
|
500 |
+
datadict = keydict.get(key, self.edge_attr_dict_factory())
|
501 |
+
datadict.update(attr)
|
502 |
+
keydict[key] = datadict
|
503 |
+
else:
|
504 |
+
# selfloops work this way without special treatment
|
505 |
+
datadict = self.edge_attr_dict_factory()
|
506 |
+
datadict.update(attr)
|
507 |
+
keydict = self.edge_key_dict_factory()
|
508 |
+
keydict[key] = datadict
|
509 |
+
self._succ[u][v] = keydict
|
510 |
+
self._pred[v][u] = keydict
|
511 |
+
nx._clear_cache(self)
|
512 |
+
return key
|
513 |
+
|
514 |
+
def remove_edge(self, u, v, key=None):
|
515 |
+
"""Remove an edge between u and v.
|
516 |
+
|
517 |
+
Parameters
|
518 |
+
----------
|
519 |
+
u, v : nodes
|
520 |
+
Remove an edge between nodes u and v.
|
521 |
+
key : hashable identifier, optional (default=None)
|
522 |
+
Used to distinguish multiple edges between a pair of nodes.
|
523 |
+
If None, remove a single edge between u and v. If there are
|
524 |
+
multiple edges, removes the last edge added in terms of
|
525 |
+
insertion order.
|
526 |
+
|
527 |
+
Raises
|
528 |
+
------
|
529 |
+
NetworkXError
|
530 |
+
If there is not an edge between u and v, or
|
531 |
+
if there is no edge with the specified key.
|
532 |
+
|
533 |
+
See Also
|
534 |
+
--------
|
535 |
+
remove_edges_from : remove a collection of edges
|
536 |
+
|
537 |
+
Examples
|
538 |
+
--------
|
539 |
+
>>> G = nx.MultiDiGraph()
|
540 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
541 |
+
>>> G.remove_edge(0, 1)
|
542 |
+
>>> e = (1, 2)
|
543 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
544 |
+
|
545 |
+
For multiple edges
|
546 |
+
|
547 |
+
>>> G = nx.MultiDiGraph()
|
548 |
+
>>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
|
549 |
+
[0, 1, 2]
|
550 |
+
|
551 |
+
When ``key=None`` (the default), edges are removed in the opposite
|
552 |
+
order that they were added:
|
553 |
+
|
554 |
+
>>> G.remove_edge(1, 2)
|
555 |
+
>>> G.edges(keys=True)
|
556 |
+
OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
|
557 |
+
|
558 |
+
For edges with keys
|
559 |
+
|
560 |
+
>>> G = nx.MultiDiGraph()
|
561 |
+
>>> G.add_edge(1, 2, key="first")
|
562 |
+
'first'
|
563 |
+
>>> G.add_edge(1, 2, key="second")
|
564 |
+
'second'
|
565 |
+
>>> G.remove_edge(1, 2, key="first")
|
566 |
+
>>> G.edges(keys=True)
|
567 |
+
OutMultiEdgeView([(1, 2, 'second')])
|
568 |
+
|
569 |
+
"""
|
570 |
+
try:
|
571 |
+
d = self._adj[u][v]
|
572 |
+
except KeyError as err:
|
573 |
+
raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
|
574 |
+
# remove the edge with specified data
|
575 |
+
if key is None:
|
576 |
+
d.popitem()
|
577 |
+
else:
|
578 |
+
try:
|
579 |
+
del d[key]
|
580 |
+
except KeyError as err:
|
581 |
+
msg = f"The edge {u}-{v} with key {key} is not in the graph."
|
582 |
+
raise NetworkXError(msg) from err
|
583 |
+
if len(d) == 0:
|
584 |
+
# remove the key entries if last edge
|
585 |
+
del self._succ[u][v]
|
586 |
+
del self._pred[v][u]
|
587 |
+
nx._clear_cache(self)
|
588 |
+
|
589 |
+
@cached_property
|
590 |
+
def edges(self):
|
591 |
+
"""An OutMultiEdgeView of the Graph as G.edges or G.edges().
|
592 |
+
|
593 |
+
edges(self, nbunch=None, data=False, keys=False, default=None)
|
594 |
+
|
595 |
+
The OutMultiEdgeView provides set-like operations on the edge-tuples
|
596 |
+
as well as edge attribute lookup. When called, it also provides
|
597 |
+
an EdgeDataView object which allows control of access to edge
|
598 |
+
attributes (but does not provide set-like operations).
|
599 |
+
Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
|
600 |
+
attribute for the edge from ``u`` to ``v`` with key ``k`` while
|
601 |
+
``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
|
602 |
+
iterates through all the edges yielding the color attribute with
|
603 |
+
default `'red'` if no color attribute exists.
|
604 |
+
|
605 |
+
Edges are returned as tuples with optional data and keys
|
606 |
+
in the order (node, neighbor, key, data). If ``keys=True`` is not
|
607 |
+
provided, the tuples will just be (node, neighbor, data), but
|
608 |
+
multiple tuples with the same node and neighbor will be
|
609 |
+
generated when multiple edges between two nodes exist.
|
610 |
+
|
611 |
+
Parameters
|
612 |
+
----------
|
613 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
614 |
+
The view will only report edges from these nodes.
|
615 |
+
data : string or bool, optional (default=False)
|
616 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
617 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
618 |
+
If False, return 2-tuple (u, v).
|
619 |
+
keys : bool, optional (default=False)
|
620 |
+
If True, return edge keys with each edge, creating (u, v, k,
|
621 |
+
d) tuples when data is also requested (the default) and (u,
|
622 |
+
v, k) tuples when data is not requested.
|
623 |
+
default : value, optional (default=None)
|
624 |
+
Value used for edges that don't have the requested attribute.
|
625 |
+
Only relevant if data is not True or False.
|
626 |
+
|
627 |
+
Returns
|
628 |
+
-------
|
629 |
+
edges : OutMultiEdgeView
|
630 |
+
A view of edge attributes, usually it iterates over (u, v)
|
631 |
+
(u, v, k) or (u, v, k, d) tuples of edges, but can also be
|
632 |
+
used for attribute lookup as ``edges[u, v, k]['foo']``.
|
633 |
+
|
634 |
+
Notes
|
635 |
+
-----
|
636 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
637 |
+
For directed graphs this returns the out-edges.
|
638 |
+
|
639 |
+
Examples
|
640 |
+
--------
|
641 |
+
>>> G = nx.MultiDiGraph()
|
642 |
+
>>> nx.add_path(G, [0, 1, 2])
|
643 |
+
>>> key = G.add_edge(2, 3, weight=5)
|
644 |
+
>>> key2 = G.add_edge(1, 2) # second edge between these nodes
|
645 |
+
>>> [e for e in G.edges()]
|
646 |
+
[(0, 1), (1, 2), (1, 2), (2, 3)]
|
647 |
+
>>> list(G.edges(data=True)) # default data is {} (empty dict)
|
648 |
+
[(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
|
649 |
+
>>> list(G.edges(data="weight", default=1))
|
650 |
+
[(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
|
651 |
+
>>> list(G.edges(keys=True)) # default keys are integers
|
652 |
+
[(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
|
653 |
+
>>> list(G.edges(data=True, keys=True))
|
654 |
+
[(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
|
655 |
+
>>> list(G.edges(data="weight", default=1, keys=True))
|
656 |
+
[(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
|
657 |
+
>>> list(G.edges([0, 2]))
|
658 |
+
[(0, 1), (2, 3)]
|
659 |
+
>>> list(G.edges(0))
|
660 |
+
[(0, 1)]
|
661 |
+
>>> list(G.edges(1))
|
662 |
+
[(1, 2), (1, 2)]
|
663 |
+
|
664 |
+
See Also
|
665 |
+
--------
|
666 |
+
in_edges, out_edges
|
667 |
+
"""
|
668 |
+
return OutMultiEdgeView(self)
|
669 |
+
|
670 |
+
# alias out_edges to edges
|
671 |
+
@cached_property
|
672 |
+
def out_edges(self):
|
673 |
+
return OutMultiEdgeView(self)
|
674 |
+
|
675 |
+
out_edges.__doc__ = edges.__doc__
|
676 |
+
|
677 |
+
@cached_property
|
678 |
+
def in_edges(self):
|
679 |
+
"""A view of the in edges of the graph as G.in_edges or G.in_edges().
|
680 |
+
|
681 |
+
in_edges(self, nbunch=None, data=False, keys=False, default=None)
|
682 |
+
|
683 |
+
Parameters
|
684 |
+
----------
|
685 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
686 |
+
The view will only report edges incident to these nodes.
|
687 |
+
data : string or bool, optional (default=False)
|
688 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
689 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
690 |
+
If False, return 2-tuple (u, v).
|
691 |
+
keys : bool, optional (default=False)
|
692 |
+
If True, return edge keys with each edge, creating 3-tuples
|
693 |
+
(u, v, k) or with data, 4-tuples (u, v, k, d).
|
694 |
+
default : value, optional (default=None)
|
695 |
+
Value used for edges that don't have the requested attribute.
|
696 |
+
Only relevant if data is not True or False.
|
697 |
+
|
698 |
+
Returns
|
699 |
+
-------
|
700 |
+
in_edges : InMultiEdgeView or InMultiEdgeDataView
|
701 |
+
A view of edge attributes, usually it iterates over (u, v)
|
702 |
+
or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
|
703 |
+
used for attribute lookup as `edges[u, v, k]['foo']`.
|
704 |
+
|
705 |
+
See Also
|
706 |
+
--------
|
707 |
+
edges
|
708 |
+
"""
|
709 |
+
return InMultiEdgeView(self)
|
710 |
+
|
711 |
+
@cached_property
|
712 |
+
def degree(self):
|
713 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
714 |
+
|
715 |
+
The node degree is the number of edges adjacent to the node.
|
716 |
+
The weighted node degree is the sum of the edge weights for
|
717 |
+
edges incident to that node.
|
718 |
+
|
719 |
+
This object provides an iterator for (node, degree) as well as
|
720 |
+
lookup for the degree for a single node.
|
721 |
+
|
722 |
+
Parameters
|
723 |
+
----------
|
724 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
725 |
+
The view will only report edges incident to these nodes.
|
726 |
+
|
727 |
+
weight : string or None, optional (default=None)
|
728 |
+
The name of an edge attribute that holds the numerical value used
|
729 |
+
as a weight. If None, then each edge has weight 1.
|
730 |
+
The degree is the sum of the edge weights adjacent to the node.
|
731 |
+
|
732 |
+
Returns
|
733 |
+
-------
|
734 |
+
DiMultiDegreeView or int
|
735 |
+
If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
|
736 |
+
mapping nodes to their degree.
|
737 |
+
If a single node is requested, returns the degree of the node as an integer.
|
738 |
+
|
739 |
+
See Also
|
740 |
+
--------
|
741 |
+
out_degree, in_degree
|
742 |
+
|
743 |
+
Examples
|
744 |
+
--------
|
745 |
+
>>> G = nx.MultiDiGraph()
|
746 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
747 |
+
>>> G.degree(0) # node 0 with degree 1
|
748 |
+
1
|
749 |
+
>>> list(G.degree([0, 1, 2]))
|
750 |
+
[(0, 1), (1, 2), (2, 2)]
|
751 |
+
>>> G.add_edge(0, 1) # parallel edge
|
752 |
+
1
|
753 |
+
>>> list(G.degree([0, 1, 2])) # parallel edges are counted
|
754 |
+
[(0, 2), (1, 3), (2, 2)]
|
755 |
+
|
756 |
+
"""
|
757 |
+
return DiMultiDegreeView(self)
|
758 |
+
|
759 |
+
@cached_property
|
760 |
+
def in_degree(self):
|
761 |
+
"""A DegreeView for (node, in_degree) or in_degree for single node.
|
762 |
+
|
763 |
+
The node in-degree is the number of edges pointing into the node.
|
764 |
+
The weighted node degree is the sum of the edge weights for
|
765 |
+
edges incident to that node.
|
766 |
+
|
767 |
+
This object provides an iterator for (node, degree) as well as
|
768 |
+
lookup for the degree for a single node.
|
769 |
+
|
770 |
+
Parameters
|
771 |
+
----------
|
772 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
773 |
+
The view will only report edges incident to these nodes.
|
774 |
+
|
775 |
+
weight : string or None, optional (default=None)
|
776 |
+
The edge attribute that holds the numerical value used
|
777 |
+
as a weight. If None, then each edge has weight 1.
|
778 |
+
The degree is the sum of the edge weights adjacent to the node.
|
779 |
+
|
780 |
+
Returns
|
781 |
+
-------
|
782 |
+
If a single node is requested
|
783 |
+
deg : int
|
784 |
+
Degree of the node
|
785 |
+
|
786 |
+
OR if multiple nodes are requested
|
787 |
+
nd_iter : iterator
|
788 |
+
The iterator returns two-tuples of (node, in-degree).
|
789 |
+
|
790 |
+
See Also
|
791 |
+
--------
|
792 |
+
degree, out_degree
|
793 |
+
|
794 |
+
Examples
|
795 |
+
--------
|
796 |
+
>>> G = nx.MultiDiGraph()
|
797 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
798 |
+
>>> G.in_degree(0) # node 0 with degree 0
|
799 |
+
0
|
800 |
+
>>> list(G.in_degree([0, 1, 2]))
|
801 |
+
[(0, 0), (1, 1), (2, 1)]
|
802 |
+
>>> G.add_edge(0, 1) # parallel edge
|
803 |
+
1
|
804 |
+
>>> list(G.in_degree([0, 1, 2])) # parallel edges counted
|
805 |
+
[(0, 0), (1, 2), (2, 1)]
|
806 |
+
|
807 |
+
"""
|
808 |
+
return InMultiDegreeView(self)
|
809 |
+
|
810 |
+
@cached_property
|
811 |
+
def out_degree(self):
|
812 |
+
"""Returns an iterator for (node, out-degree) or out-degree for single node.
|
813 |
+
|
814 |
+
out_degree(self, nbunch=None, weight=None)
|
815 |
+
|
816 |
+
The node out-degree is the number of edges pointing out of the node.
|
817 |
+
This function returns the out-degree for a single node or an iterator
|
818 |
+
for a bunch of nodes or if nothing is passed as argument.
|
819 |
+
|
820 |
+
Parameters
|
821 |
+
----------
|
822 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
823 |
+
The view will only report edges incident to these nodes.
|
824 |
+
|
825 |
+
weight : string or None, optional (default=None)
|
826 |
+
The edge attribute that holds the numerical value used
|
827 |
+
as a weight. If None, then each edge has weight 1.
|
828 |
+
The degree is the sum of the edge weights.
|
829 |
+
|
830 |
+
Returns
|
831 |
+
-------
|
832 |
+
If a single node is requested
|
833 |
+
deg : int
|
834 |
+
Degree of the node
|
835 |
+
|
836 |
+
OR if multiple nodes are requested
|
837 |
+
nd_iter : iterator
|
838 |
+
The iterator returns two-tuples of (node, out-degree).
|
839 |
+
|
840 |
+
See Also
|
841 |
+
--------
|
842 |
+
degree, in_degree
|
843 |
+
|
844 |
+
Examples
|
845 |
+
--------
|
846 |
+
>>> G = nx.MultiDiGraph()
|
847 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
848 |
+
>>> G.out_degree(0) # node 0 with degree 1
|
849 |
+
1
|
850 |
+
>>> list(G.out_degree([0, 1, 2]))
|
851 |
+
[(0, 1), (1, 1), (2, 1)]
|
852 |
+
>>> G.add_edge(0, 1) # parallel edge
|
853 |
+
1
|
854 |
+
>>> list(G.out_degree([0, 1, 2])) # counts parallel edges
|
855 |
+
[(0, 2), (1, 1), (2, 1)]
|
856 |
+
|
857 |
+
"""
|
858 |
+
return OutMultiDegreeView(self)
|
859 |
+
|
860 |
+
def is_multigraph(self):
|
861 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
862 |
+
return True
|
863 |
+
|
864 |
+
def is_directed(self):
|
865 |
+
"""Returns True if graph is directed, False otherwise."""
|
866 |
+
return True
|
867 |
+
|
868 |
+
def to_undirected(self, reciprocal=False, as_view=False):
|
869 |
+
"""Returns an undirected representation of the digraph.
|
870 |
+
|
871 |
+
Parameters
|
872 |
+
----------
|
873 |
+
reciprocal : bool (optional)
|
874 |
+
If True only keep edges that appear in both directions
|
875 |
+
in the original digraph.
|
876 |
+
as_view : bool (optional, default=False)
|
877 |
+
If True return an undirected view of the original directed graph.
|
878 |
+
|
879 |
+
Returns
|
880 |
+
-------
|
881 |
+
G : MultiGraph
|
882 |
+
An undirected graph with the same name and nodes and
|
883 |
+
with edge (u, v, data) if either (u, v, data) or (v, u, data)
|
884 |
+
is in the digraph. If both edges exist in digraph and
|
885 |
+
their edge data is different, only one edge is created
|
886 |
+
with an arbitrary choice of which edge data to use.
|
887 |
+
You must check and correct for this manually if desired.
|
888 |
+
|
889 |
+
See Also
|
890 |
+
--------
|
891 |
+
MultiGraph, copy, add_edge, add_edges_from
|
892 |
+
|
893 |
+
Notes
|
894 |
+
-----
|
895 |
+
This returns a "deepcopy" of the edge, node, and
|
896 |
+
graph attributes which attempts to completely copy
|
897 |
+
all of the data and references.
|
898 |
+
|
899 |
+
This is in contrast to the similar D=MultiDiGraph(G) which
|
900 |
+
returns a shallow copy of the data.
|
901 |
+
|
902 |
+
See the Python copy module for more information on shallow
|
903 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
904 |
+
|
905 |
+
Warning: If you have subclassed MultiDiGraph to use dict-like
|
906 |
+
objects in the data structure, those changes do not transfer
|
907 |
+
to the MultiGraph created by this method.
|
908 |
+
|
909 |
+
Examples
|
910 |
+
--------
|
911 |
+
>>> G = nx.path_graph(2) # or MultiGraph, etc
|
912 |
+
>>> H = G.to_directed()
|
913 |
+
>>> list(H.edges)
|
914 |
+
[(0, 1), (1, 0)]
|
915 |
+
>>> G2 = H.to_undirected()
|
916 |
+
>>> list(G2.edges)
|
917 |
+
[(0, 1)]
|
918 |
+
"""
|
919 |
+
graph_class = self.to_undirected_class()
|
920 |
+
if as_view is True:
|
921 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
922 |
+
# deepcopy when not a view
|
923 |
+
G = graph_class()
|
924 |
+
G.graph.update(deepcopy(self.graph))
|
925 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
926 |
+
if reciprocal is True:
|
927 |
+
G.add_edges_from(
|
928 |
+
(u, v, key, deepcopy(data))
|
929 |
+
for u, nbrs in self._adj.items()
|
930 |
+
for v, keydict in nbrs.items()
|
931 |
+
for key, data in keydict.items()
|
932 |
+
if v in self._pred[u] and key in self._pred[u][v]
|
933 |
+
)
|
934 |
+
else:
|
935 |
+
G.add_edges_from(
|
936 |
+
(u, v, key, deepcopy(data))
|
937 |
+
for u, nbrs in self._adj.items()
|
938 |
+
for v, keydict in nbrs.items()
|
939 |
+
for key, data in keydict.items()
|
940 |
+
)
|
941 |
+
return G
|
942 |
+
|
943 |
+
def reverse(self, copy=True):
|
944 |
+
"""Returns the reverse of the graph.
|
945 |
+
|
946 |
+
The reverse is a graph with the same nodes and edges
|
947 |
+
but with the directions of the edges reversed.
|
948 |
+
|
949 |
+
Parameters
|
950 |
+
----------
|
951 |
+
copy : bool optional (default=True)
|
952 |
+
If True, return a new DiGraph holding the reversed edges.
|
953 |
+
If False, the reverse graph is created using a view of
|
954 |
+
the original graph.
|
955 |
+
"""
|
956 |
+
if copy:
|
957 |
+
H = self.__class__()
|
958 |
+
H.graph.update(deepcopy(self.graph))
|
959 |
+
H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
960 |
+
H.add_edges_from(
|
961 |
+
(v, u, k, deepcopy(d))
|
962 |
+
for u, v, k, d in self.edges(keys=True, data=True)
|
963 |
+
)
|
964 |
+
return H
|
965 |
+
return nx.reverse_view(self)
|
venv/lib/python3.10/site-packages/networkx/classes/multigraph.py
ADDED
@@ -0,0 +1,1282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for MultiGraph."""
|
2 |
+
from copy import deepcopy
|
3 |
+
from functools import cached_property
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx import NetworkXError, convert
|
7 |
+
from networkx.classes.coreviews import MultiAdjacencyView
|
8 |
+
from networkx.classes.graph import Graph
|
9 |
+
from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
|
10 |
+
|
11 |
+
__all__ = ["MultiGraph"]
|
12 |
+
|
13 |
+
|
14 |
+
class MultiGraph(Graph):
|
15 |
+
"""
|
16 |
+
An undirected graph class that can store multiedges.
|
17 |
+
|
18 |
+
Multiedges are multiple edges between two nodes. Each edge
|
19 |
+
can hold optional data or attributes.
|
20 |
+
|
21 |
+
A MultiGraph holds undirected edges. Self loops are allowed.
|
22 |
+
|
23 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
24 |
+
key/value attributes. By convention `None` is not used as a node.
|
25 |
+
|
26 |
+
Edges are represented as links between nodes with optional
|
27 |
+
key/value attributes, in a MultiGraph each edge has a key to
|
28 |
+
distinguish between multiple edges that have the same source and
|
29 |
+
destination nodes.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
----------
|
33 |
+
incoming_graph_data : input graph (optional, default: None)
|
34 |
+
Data to initialize graph. If None (default) an empty
|
35 |
+
graph is created. The data can be any format that is supported
|
36 |
+
by the to_networkx_graph() function, currently including edge list,
|
37 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
|
38 |
+
SciPy sparse array, or PyGraphviz graph.
|
39 |
+
|
40 |
+
multigraph_input : bool or None (default None)
|
41 |
+
Note: Only used when `incoming_graph_data` is a dict.
|
42 |
+
If True, `incoming_graph_data` is assumed to be a
|
43 |
+
dict-of-dict-of-dict-of-dict structure keyed by
|
44 |
+
node to neighbor to edge keys to edge data for multi-edges.
|
45 |
+
A NetworkXError is raised if this is not the case.
|
46 |
+
If False, :func:`to_networkx_graph` is used to try to determine
|
47 |
+
the dict's graph data structure as either a dict-of-dict-of-dict
|
48 |
+
keyed by node to neighbor to edge data, or a dict-of-iterable
|
49 |
+
keyed by node to neighbors.
|
50 |
+
If None, the treatment for True is tried, but if it fails,
|
51 |
+
the treatment for False is tried.
|
52 |
+
|
53 |
+
attr : keyword arguments, optional (default= no attributes)
|
54 |
+
Attributes to add to graph as key=value pairs.
|
55 |
+
|
56 |
+
See Also
|
57 |
+
--------
|
58 |
+
Graph
|
59 |
+
DiGraph
|
60 |
+
MultiDiGraph
|
61 |
+
|
62 |
+
Examples
|
63 |
+
--------
|
64 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
65 |
+
no edges.
|
66 |
+
|
67 |
+
>>> G = nx.MultiGraph()
|
68 |
+
|
69 |
+
G can be grown in several ways.
|
70 |
+
|
71 |
+
**Nodes:**
|
72 |
+
|
73 |
+
Add one node at a time:
|
74 |
+
|
75 |
+
>>> G.add_node(1)
|
76 |
+
|
77 |
+
Add the nodes from any container (a list, dict, set or
|
78 |
+
even the lines from a file or the nodes from another graph).
|
79 |
+
|
80 |
+
>>> G.add_nodes_from([2, 3])
|
81 |
+
>>> G.add_nodes_from(range(100, 110))
|
82 |
+
>>> H = nx.path_graph(10)
|
83 |
+
>>> G.add_nodes_from(H)
|
84 |
+
|
85 |
+
In addition to strings and integers any hashable Python object
|
86 |
+
(except None) can represent a node, e.g. a customized node object,
|
87 |
+
or even another Graph.
|
88 |
+
|
89 |
+
>>> G.add_node(H)
|
90 |
+
|
91 |
+
**Edges:**
|
92 |
+
|
93 |
+
G can also be grown by adding edges.
|
94 |
+
|
95 |
+
Add one edge,
|
96 |
+
|
97 |
+
>>> key = G.add_edge(1, 2)
|
98 |
+
|
99 |
+
a list of edges,
|
100 |
+
|
101 |
+
>>> keys = G.add_edges_from([(1, 2), (1, 3)])
|
102 |
+
|
103 |
+
or a collection of edges,
|
104 |
+
|
105 |
+
>>> keys = G.add_edges_from(H.edges)
|
106 |
+
|
107 |
+
If some edges connect nodes not yet in the graph, the nodes
|
108 |
+
are added automatically. If an edge already exists, an additional
|
109 |
+
edge is created and stored using a key to identify the edge.
|
110 |
+
By default the key is the lowest unused integer.
|
111 |
+
|
112 |
+
>>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
|
113 |
+
>>> G[4]
|
114 |
+
AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
|
115 |
+
|
116 |
+
**Attributes:**
|
117 |
+
|
118 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
119 |
+
in an associated attribute dictionary (the keys must be hashable).
|
120 |
+
By default these are empty, but can be added or changed using
|
121 |
+
add_edge, add_node or direct manipulation of the attribute
|
122 |
+
dictionaries named graph, node and edge respectively.
|
123 |
+
|
124 |
+
>>> G = nx.MultiGraph(day="Friday")
|
125 |
+
>>> G.graph
|
126 |
+
{'day': 'Friday'}
|
127 |
+
|
128 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
129 |
+
|
130 |
+
>>> G.add_node(1, time="5pm")
|
131 |
+
>>> G.add_nodes_from([3], time="2pm")
|
132 |
+
>>> G.nodes[1]
|
133 |
+
{'time': '5pm'}
|
134 |
+
>>> G.nodes[1]["room"] = 714
|
135 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
136 |
+
>>> list(G.nodes(data=True))
|
137 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
138 |
+
|
139 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
140 |
+
notation, or G.edges.
|
141 |
+
|
142 |
+
>>> key = G.add_edge(1, 2, weight=4.7)
|
143 |
+
>>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
|
144 |
+
>>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
145 |
+
>>> G[1][2][0]["weight"] = 4.7
|
146 |
+
>>> G.edges[1, 2, 0]["weight"] = 4
|
147 |
+
|
148 |
+
Warning: we protect the graph data structure by making `G.edges[1,
|
149 |
+
2, 0]` a read-only dict-like structure. However, you can assign to
|
150 |
+
attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
|
151 |
+
to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
|
152 |
+
|
153 |
+
**Shortcuts:**
|
154 |
+
|
155 |
+
Many common graph features allow python syntax to speed reporting.
|
156 |
+
|
157 |
+
>>> 1 in G # check if node in graph
|
158 |
+
True
|
159 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
160 |
+
[1, 2]
|
161 |
+
>>> len(G) # number of nodes in graph
|
162 |
+
5
|
163 |
+
>>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
|
164 |
+
AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
|
165 |
+
|
166 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
167 |
+
The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
|
168 |
+
|
169 |
+
>>> for n, nbrsdict in G.adjacency():
|
170 |
+
... for nbr, keydict in nbrsdict.items():
|
171 |
+
... for key, eattr in keydict.items():
|
172 |
+
... if "weight" in eattr:
|
173 |
+
... # Do something useful with the edges
|
174 |
+
... pass
|
175 |
+
|
176 |
+
But the edges() method is often more convenient:
|
177 |
+
|
178 |
+
>>> for u, v, keys, weight in G.edges(data="weight", keys=True):
|
179 |
+
... if weight is not None:
|
180 |
+
... # Do something useful with the edges
|
181 |
+
... pass
|
182 |
+
|
183 |
+
**Reporting:**
|
184 |
+
|
185 |
+
Simple graph information is obtained using methods and object-attributes.
|
186 |
+
Reporting usually provides views instead of containers to reduce memory
|
187 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
188 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
189 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
|
190 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
191 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
192 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
193 |
+
|
194 |
+
For details on these and other miscellaneous methods, see below.
|
195 |
+
|
196 |
+
**Subclasses (Advanced):**
|
197 |
+
|
198 |
+
The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
|
199 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
200 |
+
The next dict (adjlist_dict) represents the adjacency information
|
201 |
+
and holds edge_key dicts keyed by neighbor. The edge_key dict holds
|
202 |
+
each edge_attr dict keyed by edge key. The inner dict
|
203 |
+
(edge_attr_dict) represents the edge data and holds edge attribute
|
204 |
+
values keyed by attribute names.
|
205 |
+
|
206 |
+
Each of these four dicts in the dict-of-dict-of-dict-of-dict
|
207 |
+
structure can be replaced by a user defined dict-like object.
|
208 |
+
In general, the dict-like features should be maintained but
|
209 |
+
extra features can be added. To replace one of the dicts create
|
210 |
+
a new graph class by changing the class(!) variable holding the
|
211 |
+
factory for that dict-like structure. The variable names are
|
212 |
+
node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
|
213 |
+
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
|
214 |
+
and graph_attr_dict_factory.
|
215 |
+
|
216 |
+
node_dict_factory : function, (default: dict)
|
217 |
+
Factory function to be used to create the dict containing node
|
218 |
+
attributes, keyed by node id.
|
219 |
+
It should require no arguments and return a dict-like object
|
220 |
+
|
221 |
+
node_attr_dict_factory: function, (default: dict)
|
222 |
+
Factory function to be used to create the node attribute
|
223 |
+
dict which holds attribute values keyed by attribute name.
|
224 |
+
It should require no arguments and return a dict-like object
|
225 |
+
|
226 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
227 |
+
Factory function to be used to create the outer-most dict
|
228 |
+
in the data structure that holds adjacency info keyed by node.
|
229 |
+
It should require no arguments and return a dict-like object.
|
230 |
+
|
231 |
+
adjlist_inner_dict_factory : function, (default: dict)
|
232 |
+
Factory function to be used to create the adjacency list
|
233 |
+
dict which holds multiedge key dicts keyed by neighbor.
|
234 |
+
It should require no arguments and return a dict-like object.
|
235 |
+
|
236 |
+
edge_key_dict_factory : function, (default: dict)
|
237 |
+
Factory function to be used to create the edge key dict
|
238 |
+
which holds edge data keyed by edge key.
|
239 |
+
It should require no arguments and return a dict-like object.
|
240 |
+
|
241 |
+
edge_attr_dict_factory : function, (default: dict)
|
242 |
+
Factory function to be used to create the edge attribute
|
243 |
+
dict which holds attribute values keyed by attribute name.
|
244 |
+
It should require no arguments and return a dict-like object.
|
245 |
+
|
246 |
+
graph_attr_dict_factory : function, (default: dict)
|
247 |
+
Factory function to be used to create the graph attribute
|
248 |
+
dict which holds attribute values keyed by attribute name.
|
249 |
+
It should require no arguments and return a dict-like object.
|
250 |
+
|
251 |
+
Typically, if your extension doesn't impact the data structure all
|
252 |
+
methods will inherited without issue except: `to_directed/to_undirected`.
|
253 |
+
By default these methods create a DiGraph/Graph class and you probably
|
254 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
255 |
+
this we define two class variables that you can set in your subclass.
|
256 |
+
|
257 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
258 |
+
Class to create a new graph structure in the `to_directed` method.
|
259 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
260 |
+
|
261 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
262 |
+
Class to create a new graph structure in the `to_undirected` method.
|
263 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
264 |
+
|
265 |
+
**Subclassing Example**
|
266 |
+
|
267 |
+
Create a low memory graph class that effectively disallows edge
|
268 |
+
attributes by using a single attribute dict for all edges.
|
269 |
+
This reduces the memory used, but you lose edge attributes.
|
270 |
+
|
271 |
+
>>> class ThinGraph(nx.Graph):
|
272 |
+
... all_edge_dict = {"weight": 1}
|
273 |
+
...
|
274 |
+
... def single_edge_dict(self):
|
275 |
+
... return self.all_edge_dict
|
276 |
+
...
|
277 |
+
... edge_attr_dict_factory = single_edge_dict
|
278 |
+
>>> G = ThinGraph()
|
279 |
+
>>> G.add_edge(2, 1)
|
280 |
+
>>> G[2][1]
|
281 |
+
{'weight': 1}
|
282 |
+
>>> G.add_edge(2, 2)
|
283 |
+
>>> G[2][1] is G[2][2]
|
284 |
+
True
|
285 |
+
"""
|
286 |
+
|
287 |
+
# node_dict_factory = dict # already assigned in Graph
|
288 |
+
# adjlist_outer_dict_factory = dict
|
289 |
+
# adjlist_inner_dict_factory = dict
|
290 |
+
edge_key_dict_factory = dict
|
291 |
+
# edge_attr_dict_factory = dict
|
292 |
+
|
293 |
+
def to_directed_class(self):
|
294 |
+
"""Returns the class to use for empty directed copies.
|
295 |
+
|
296 |
+
If you subclass the base classes, use this to designate
|
297 |
+
what directed class to use for `to_directed()` copies.
|
298 |
+
"""
|
299 |
+
return nx.MultiDiGraph
|
300 |
+
|
301 |
+
def to_undirected_class(self):
|
302 |
+
"""Returns the class to use for empty undirected copies.
|
303 |
+
|
304 |
+
If you subclass the base classes, use this to designate
|
305 |
+
what directed class to use for `to_directed()` copies.
|
306 |
+
"""
|
307 |
+
return MultiGraph
|
308 |
+
|
309 |
+
def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
|
310 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
311 |
+
|
312 |
+
Parameters
|
313 |
+
----------
|
314 |
+
incoming_graph_data : input graph
|
315 |
+
Data to initialize graph. If incoming_graph_data=None (default)
|
316 |
+
an empty graph is created. The data can be an edge list, or any
|
317 |
+
NetworkX graph object. If the corresponding optional Python
|
318 |
+
packages are installed the data can also be a 2D NumPy array, a
|
319 |
+
SciPy sparse array, or a PyGraphviz graph.
|
320 |
+
|
321 |
+
multigraph_input : bool or None (default None)
|
322 |
+
Note: Only used when `incoming_graph_data` is a dict.
|
323 |
+
If True, `incoming_graph_data` is assumed to be a
|
324 |
+
dict-of-dict-of-dict-of-dict structure keyed by
|
325 |
+
node to neighbor to edge keys to edge data for multi-edges.
|
326 |
+
A NetworkXError is raised if this is not the case.
|
327 |
+
If False, :func:`to_networkx_graph` is used to try to determine
|
328 |
+
the dict's graph data structure as either a dict-of-dict-of-dict
|
329 |
+
keyed by node to neighbor to edge data, or a dict-of-iterable
|
330 |
+
keyed by node to neighbors.
|
331 |
+
If None, the treatment for True is tried, but if it fails,
|
332 |
+
the treatment for False is tried.
|
333 |
+
|
334 |
+
attr : keyword arguments, optional (default= no attributes)
|
335 |
+
Attributes to add to graph as key=value pairs.
|
336 |
+
|
337 |
+
See Also
|
338 |
+
--------
|
339 |
+
convert
|
340 |
+
|
341 |
+
Examples
|
342 |
+
--------
|
343 |
+
>>> G = nx.MultiGraph()
|
344 |
+
>>> G = nx.MultiGraph(name="my graph")
|
345 |
+
>>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
|
346 |
+
>>> G = nx.MultiGraph(e)
|
347 |
+
|
348 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
349 |
+
|
350 |
+
>>> G = nx.MultiGraph(e, day="Friday")
|
351 |
+
>>> G.graph
|
352 |
+
{'day': 'Friday'}
|
353 |
+
|
354 |
+
"""
|
355 |
+
# multigraph_input can be None/True/False. So check "is not False"
|
356 |
+
if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
|
357 |
+
Graph.__init__(self)
|
358 |
+
try:
|
359 |
+
convert.from_dict_of_dicts(
|
360 |
+
incoming_graph_data, create_using=self, multigraph_input=True
|
361 |
+
)
|
362 |
+
self.graph.update(attr)
|
363 |
+
except Exception as err:
|
364 |
+
if multigraph_input is True:
|
365 |
+
raise nx.NetworkXError(
|
366 |
+
f"converting multigraph_input raised:\n{type(err)}: {err}"
|
367 |
+
)
|
368 |
+
Graph.__init__(self, incoming_graph_data, **attr)
|
369 |
+
else:
|
370 |
+
Graph.__init__(self, incoming_graph_data, **attr)
|
371 |
+
|
372 |
+
@cached_property
|
373 |
+
def adj(self):
|
374 |
+
"""Graph adjacency object holding the neighbors of each node.
|
375 |
+
|
376 |
+
This object is a read-only dict-like structure with node keys
|
377 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
378 |
+
to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
379 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
380 |
+
|
381 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
382 |
+
`for nbr, edgesdict in G.adj[n].items():`.
|
383 |
+
|
384 |
+
The neighbor information is also provided by subscripting the graph.
|
385 |
+
|
386 |
+
Examples
|
387 |
+
--------
|
388 |
+
>>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
|
389 |
+
>>> G = nx.MultiGraph(e)
|
390 |
+
>>> G.edges[1, 2, 0]["weight"] = 3
|
391 |
+
>>> result = set()
|
392 |
+
>>> for edgekey, data in G[1][2].items():
|
393 |
+
... result.add(data.get("weight", 1))
|
394 |
+
>>> result
|
395 |
+
{1, 3}
|
396 |
+
|
397 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
398 |
+
"""
|
399 |
+
return MultiAdjacencyView(self._adj)
|
400 |
+
|
401 |
+
def new_edge_key(self, u, v):
|
402 |
+
"""Returns an unused key for edges between nodes `u` and `v`.
|
403 |
+
|
404 |
+
The nodes `u` and `v` do not need to be already in the graph.
|
405 |
+
|
406 |
+
Notes
|
407 |
+
-----
|
408 |
+
In the standard MultiGraph class the new key is the number of existing
|
409 |
+
edges between `u` and `v` (increased if necessary to ensure unused).
|
410 |
+
The first edge will have key 0, then 1, etc. If an edge is removed
|
411 |
+
further new_edge_keys may not be in this order.
|
412 |
+
|
413 |
+
Parameters
|
414 |
+
----------
|
415 |
+
u, v : nodes
|
416 |
+
|
417 |
+
Returns
|
418 |
+
-------
|
419 |
+
key : int
|
420 |
+
"""
|
421 |
+
try:
|
422 |
+
keydict = self._adj[u][v]
|
423 |
+
except KeyError:
|
424 |
+
return 0
|
425 |
+
key = len(keydict)
|
426 |
+
while key in keydict:
|
427 |
+
key += 1
|
428 |
+
return key
|
429 |
+
|
430 |
+
def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
|
431 |
+
"""Add an edge between u and v.
|
432 |
+
|
433 |
+
The nodes u and v will be automatically added if they are
|
434 |
+
not already in the graph.
|
435 |
+
|
436 |
+
Edge attributes can be specified with keywords or by directly
|
437 |
+
accessing the edge's attribute dictionary. See examples below.
|
438 |
+
|
439 |
+
Parameters
|
440 |
+
----------
|
441 |
+
u_for_edge, v_for_edge : nodes
|
442 |
+
Nodes can be, for example, strings or numbers.
|
443 |
+
Nodes must be hashable (and not None) Python objects.
|
444 |
+
key : hashable identifier, optional (default=lowest unused integer)
|
445 |
+
Used to distinguish multiedges between a pair of nodes.
|
446 |
+
attr : keyword arguments, optional
|
447 |
+
Edge data (or labels or objects) can be assigned using
|
448 |
+
keyword arguments.
|
449 |
+
|
450 |
+
Returns
|
451 |
+
-------
|
452 |
+
The edge key assigned to the edge.
|
453 |
+
|
454 |
+
See Also
|
455 |
+
--------
|
456 |
+
add_edges_from : add a collection of edges
|
457 |
+
|
458 |
+
Notes
|
459 |
+
-----
|
460 |
+
To replace/update edge data, use the optional key argument
|
461 |
+
to identify a unique edge. Otherwise a new edge will be created.
|
462 |
+
|
463 |
+
NetworkX algorithms designed for weighted graphs cannot use
|
464 |
+
multigraphs directly because it is not clear how to handle
|
465 |
+
multiedge weights. Convert to Graph using edge attribute
|
466 |
+
'weight' to enable weighted graph algorithms.
|
467 |
+
|
468 |
+
Default keys are generated using the method `new_edge_key()`.
|
469 |
+
This method can be overridden by subclassing the base class and
|
470 |
+
providing a custom `new_edge_key()` method.
|
471 |
+
|
472 |
+
Examples
|
473 |
+
--------
|
474 |
+
The following each add an additional edge e=(1, 2) to graph G:
|
475 |
+
|
476 |
+
>>> G = nx.MultiGraph()
|
477 |
+
>>> e = (1, 2)
|
478 |
+
>>> ekey = G.add_edge(1, 2) # explicit two-node form
|
479 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
480 |
+
1
|
481 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
482 |
+
[2]
|
483 |
+
|
484 |
+
Associate data to edges using keywords:
|
485 |
+
|
486 |
+
>>> ekey = G.add_edge(1, 2, weight=3)
|
487 |
+
>>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
|
488 |
+
>>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
489 |
+
|
490 |
+
For non-string attribute keys, use subscript notation.
|
491 |
+
|
492 |
+
>>> ekey = G.add_edge(1, 2)
|
493 |
+
>>> G[1][2][0].update({0: 5})
|
494 |
+
>>> G.edges[1, 2, 0].update({0: 5})
|
495 |
+
"""
|
496 |
+
u, v = u_for_edge, v_for_edge
|
497 |
+
# add nodes
|
498 |
+
if u not in self._adj:
|
499 |
+
if u is None:
|
500 |
+
raise ValueError("None cannot be a node")
|
501 |
+
self._adj[u] = self.adjlist_inner_dict_factory()
|
502 |
+
self._node[u] = self.node_attr_dict_factory()
|
503 |
+
if v not in self._adj:
|
504 |
+
if v is None:
|
505 |
+
raise ValueError("None cannot be a node")
|
506 |
+
self._adj[v] = self.adjlist_inner_dict_factory()
|
507 |
+
self._node[v] = self.node_attr_dict_factory()
|
508 |
+
if key is None:
|
509 |
+
key = self.new_edge_key(u, v)
|
510 |
+
if v in self._adj[u]:
|
511 |
+
keydict = self._adj[u][v]
|
512 |
+
datadict = keydict.get(key, self.edge_attr_dict_factory())
|
513 |
+
datadict.update(attr)
|
514 |
+
keydict[key] = datadict
|
515 |
+
else:
|
516 |
+
# selfloops work this way without special treatment
|
517 |
+
datadict = self.edge_attr_dict_factory()
|
518 |
+
datadict.update(attr)
|
519 |
+
keydict = self.edge_key_dict_factory()
|
520 |
+
keydict[key] = datadict
|
521 |
+
self._adj[u][v] = keydict
|
522 |
+
self._adj[v][u] = keydict
|
523 |
+
nx._clear_cache(self)
|
524 |
+
return key
|
525 |
+
|
526 |
+
def add_edges_from(self, ebunch_to_add, **attr):
|
527 |
+
"""Add all the edges in ebunch_to_add.
|
528 |
+
|
529 |
+
Parameters
|
530 |
+
----------
|
531 |
+
ebunch_to_add : container of edges
|
532 |
+
Each edge given in the container will be added to the
|
533 |
+
graph. The edges can be:
|
534 |
+
|
535 |
+
- 2-tuples (u, v) or
|
536 |
+
- 3-tuples (u, v, d) for an edge data dict d, or
|
537 |
+
- 3-tuples (u, v, k) for not iterable key k, or
|
538 |
+
- 4-tuples (u, v, k, d) for an edge with data and key k
|
539 |
+
|
540 |
+
attr : keyword arguments, optional
|
541 |
+
Edge data (or labels or objects) can be assigned using
|
542 |
+
keyword arguments.
|
543 |
+
|
544 |
+
Returns
|
545 |
+
-------
|
546 |
+
A list of edge keys assigned to the edges in `ebunch`.
|
547 |
+
|
548 |
+
See Also
|
549 |
+
--------
|
550 |
+
add_edge : add a single edge
|
551 |
+
add_weighted_edges_from : convenient way to add weighted edges
|
552 |
+
|
553 |
+
Notes
|
554 |
+
-----
|
555 |
+
Adding the same edge twice has no effect but any edge data
|
556 |
+
will be updated when each duplicate edge is added.
|
557 |
+
|
558 |
+
Edge attributes specified in an ebunch take precedence over
|
559 |
+
attributes specified via keyword arguments.
|
560 |
+
|
561 |
+
Default keys are generated using the method ``new_edge_key()``.
|
562 |
+
This method can be overridden by subclassing the base class and
|
563 |
+
providing a custom ``new_edge_key()`` method.
|
564 |
+
|
565 |
+
When adding edges from an iterator over the graph you are changing,
|
566 |
+
a `RuntimeError` can be raised with message:
|
567 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
568 |
+
happens when the graph's underlying dictionary is modified during
|
569 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
570 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
571 |
+
object to `G.add_edges_from`.
|
572 |
+
|
573 |
+
Examples
|
574 |
+
--------
|
575 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
576 |
+
>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
|
577 |
+
>>> e = zip(range(0, 3), range(1, 4))
|
578 |
+
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3
|
579 |
+
|
580 |
+
Associate data to edges
|
581 |
+
|
582 |
+
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
|
583 |
+
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
|
584 |
+
|
585 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
586 |
+
|
587 |
+
>>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
|
588 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
589 |
+
>>> # wrong way - will raise RuntimeError
|
590 |
+
>>> # G.add_edges_from(((5, n) for n in G.nodes))
|
591 |
+
>>> # right way - note that there will be no self-edge for node 5
|
592 |
+
>>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
|
593 |
+
"""
|
594 |
+
keylist = []
|
595 |
+
for e in ebunch_to_add:
|
596 |
+
ne = len(e)
|
597 |
+
if ne == 4:
|
598 |
+
u, v, key, dd = e
|
599 |
+
elif ne == 3:
|
600 |
+
u, v, dd = e
|
601 |
+
key = None
|
602 |
+
elif ne == 2:
|
603 |
+
u, v = e
|
604 |
+
dd = {}
|
605 |
+
key = None
|
606 |
+
else:
|
607 |
+
msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
|
608 |
+
raise NetworkXError(msg)
|
609 |
+
ddd = {}
|
610 |
+
ddd.update(attr)
|
611 |
+
try:
|
612 |
+
ddd.update(dd)
|
613 |
+
except (TypeError, ValueError):
|
614 |
+
if ne != 3:
|
615 |
+
raise
|
616 |
+
key = dd # ne == 3 with 3rd value not dict, must be a key
|
617 |
+
key = self.add_edge(u, v, key)
|
618 |
+
self[u][v][key].update(ddd)
|
619 |
+
keylist.append(key)
|
620 |
+
nx._clear_cache(self)
|
621 |
+
return keylist
|
622 |
+
|
623 |
+
def remove_edge(self, u, v, key=None):
|
624 |
+
"""Remove an edge between u and v.
|
625 |
+
|
626 |
+
Parameters
|
627 |
+
----------
|
628 |
+
u, v : nodes
|
629 |
+
Remove an edge between nodes u and v.
|
630 |
+
key : hashable identifier, optional (default=None)
|
631 |
+
Used to distinguish multiple edges between a pair of nodes.
|
632 |
+
If None, remove a single edge between u and v. If there are
|
633 |
+
multiple edges, removes the last edge added in terms of
|
634 |
+
insertion order.
|
635 |
+
|
636 |
+
Raises
|
637 |
+
------
|
638 |
+
NetworkXError
|
639 |
+
If there is not an edge between u and v, or
|
640 |
+
if there is no edge with the specified key.
|
641 |
+
|
642 |
+
See Also
|
643 |
+
--------
|
644 |
+
remove_edges_from : remove a collection of edges
|
645 |
+
|
646 |
+
Examples
|
647 |
+
--------
|
648 |
+
>>> G = nx.MultiGraph()
|
649 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
650 |
+
>>> G.remove_edge(0, 1)
|
651 |
+
>>> e = (1, 2)
|
652 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
653 |
+
|
654 |
+
For multiple edges
|
655 |
+
|
656 |
+
>>> G = nx.MultiGraph() # or MultiDiGraph, etc
|
657 |
+
>>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
|
658 |
+
[0, 1, 2]
|
659 |
+
|
660 |
+
When ``key=None`` (the default), edges are removed in the opposite
|
661 |
+
order that they were added:
|
662 |
+
|
663 |
+
>>> G.remove_edge(1, 2)
|
664 |
+
>>> G.edges(keys=True)
|
665 |
+
MultiEdgeView([(1, 2, 0), (1, 2, 1)])
|
666 |
+
>>> G.remove_edge(2, 1) # edges are not directed
|
667 |
+
>>> G.edges(keys=True)
|
668 |
+
MultiEdgeView([(1, 2, 0)])
|
669 |
+
|
670 |
+
For edges with keys
|
671 |
+
|
672 |
+
>>> G = nx.MultiGraph()
|
673 |
+
>>> G.add_edge(1, 2, key="first")
|
674 |
+
'first'
|
675 |
+
>>> G.add_edge(1, 2, key="second")
|
676 |
+
'second'
|
677 |
+
>>> G.remove_edge(1, 2, key="first")
|
678 |
+
>>> G.edges(keys=True)
|
679 |
+
MultiEdgeView([(1, 2, 'second')])
|
680 |
+
|
681 |
+
"""
|
682 |
+
try:
|
683 |
+
d = self._adj[u][v]
|
684 |
+
except KeyError as err:
|
685 |
+
raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
|
686 |
+
# remove the edge with specified data
|
687 |
+
if key is None:
|
688 |
+
d.popitem()
|
689 |
+
else:
|
690 |
+
try:
|
691 |
+
del d[key]
|
692 |
+
except KeyError as err:
|
693 |
+
msg = f"The edge {u}-{v} with key {key} is not in the graph."
|
694 |
+
raise NetworkXError(msg) from err
|
695 |
+
if len(d) == 0:
|
696 |
+
# remove the key entries if last edge
|
697 |
+
del self._adj[u][v]
|
698 |
+
if u != v: # check for selfloop
|
699 |
+
del self._adj[v][u]
|
700 |
+
nx._clear_cache(self)
|
701 |
+
|
702 |
+
def remove_edges_from(self, ebunch):
|
703 |
+
"""Remove all edges specified in ebunch.
|
704 |
+
|
705 |
+
Parameters
|
706 |
+
----------
|
707 |
+
ebunch: list or container of edge tuples
|
708 |
+
Each edge given in the list or container will be removed
|
709 |
+
from the graph. The edges can be:
|
710 |
+
|
711 |
+
- 2-tuples (u, v) A single edge between u and v is removed.
|
712 |
+
- 3-tuples (u, v, key) The edge identified by key is removed.
|
713 |
+
- 4-tuples (u, v, key, data) where data is ignored.
|
714 |
+
|
715 |
+
See Also
|
716 |
+
--------
|
717 |
+
remove_edge : remove a single edge
|
718 |
+
|
719 |
+
Notes
|
720 |
+
-----
|
721 |
+
Will fail silently if an edge in ebunch is not in the graph.
|
722 |
+
|
723 |
+
Examples
|
724 |
+
--------
|
725 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
726 |
+
>>> ebunch = [(1, 2), (2, 3)]
|
727 |
+
>>> G.remove_edges_from(ebunch)
|
728 |
+
|
729 |
+
Removing multiple copies of edges
|
730 |
+
|
731 |
+
>>> G = nx.MultiGraph()
|
732 |
+
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
|
733 |
+
>>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
|
734 |
+
>>> list(G.edges())
|
735 |
+
[(1, 2)]
|
736 |
+
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
|
737 |
+
>>> list(G.edges) # now empty graph
|
738 |
+
[]
|
739 |
+
|
740 |
+
When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
|
741 |
+
u and v in the graph, the most recent edge (in terms of insertion
|
742 |
+
order) is removed.
|
743 |
+
|
744 |
+
>>> G = nx.MultiGraph()
|
745 |
+
>>> for key in ("x", "y", "a"):
|
746 |
+
... k = G.add_edge(0, 1, key=key)
|
747 |
+
>>> G.edges(keys=True)
|
748 |
+
MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
|
749 |
+
>>> G.remove_edges_from([(0, 1)])
|
750 |
+
>>> G.edges(keys=True)
|
751 |
+
MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
|
752 |
+
|
753 |
+
"""
|
754 |
+
for e in ebunch:
|
755 |
+
try:
|
756 |
+
self.remove_edge(*e[:3])
|
757 |
+
except NetworkXError:
|
758 |
+
pass
|
759 |
+
nx._clear_cache(self)
|
760 |
+
|
761 |
+
def has_edge(self, u, v, key=None):
|
762 |
+
"""Returns True if the graph has an edge between nodes u and v.
|
763 |
+
|
764 |
+
This is the same as `v in G[u] or key in G[u][v]`
|
765 |
+
without KeyError exceptions.
|
766 |
+
|
767 |
+
Parameters
|
768 |
+
----------
|
769 |
+
u, v : nodes
|
770 |
+
Nodes can be, for example, strings or numbers.
|
771 |
+
|
772 |
+
key : hashable identifier, optional (default=None)
|
773 |
+
If specified return True only if the edge with
|
774 |
+
key is found.
|
775 |
+
|
776 |
+
Returns
|
777 |
+
-------
|
778 |
+
edge_ind : bool
|
779 |
+
True if edge is in the graph, False otherwise.
|
780 |
+
|
781 |
+
Examples
|
782 |
+
--------
|
783 |
+
Can be called either using two nodes u, v, an edge tuple (u, v),
|
784 |
+
or an edge tuple (u, v, key).
|
785 |
+
|
786 |
+
>>> G = nx.MultiGraph() # or MultiDiGraph
|
787 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
788 |
+
>>> G.has_edge(0, 1) # using two nodes
|
789 |
+
True
|
790 |
+
>>> e = (0, 1)
|
791 |
+
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
|
792 |
+
True
|
793 |
+
>>> G.add_edge(0, 1, key="a")
|
794 |
+
'a'
|
795 |
+
>>> G.has_edge(0, 1, key="a") # specify key
|
796 |
+
True
|
797 |
+
>>> G.has_edge(1, 0, key="a") # edges aren't directed
|
798 |
+
True
|
799 |
+
>>> e = (0, 1, "a")
|
800 |
+
>>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
|
801 |
+
True
|
802 |
+
|
803 |
+
The following syntax are equivalent:
|
804 |
+
|
805 |
+
>>> G.has_edge(0, 1)
|
806 |
+
True
|
807 |
+
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
|
808 |
+
True
|
809 |
+
>>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
|
810 |
+
True
|
811 |
+
|
812 |
+
"""
|
813 |
+
try:
|
814 |
+
if key is None:
|
815 |
+
return v in self._adj[u]
|
816 |
+
else:
|
817 |
+
return key in self._adj[u][v]
|
818 |
+
except KeyError:
|
819 |
+
return False
|
820 |
+
|
821 |
+
@cached_property
|
822 |
+
def edges(self):
|
823 |
+
"""Returns an iterator over the edges.
|
824 |
+
|
825 |
+
edges(self, nbunch=None, data=False, keys=False, default=None)
|
826 |
+
|
827 |
+
The MultiEdgeView provides set-like operations on the edge-tuples
|
828 |
+
as well as edge attribute lookup. When called, it also provides
|
829 |
+
an EdgeDataView object which allows control of access to edge
|
830 |
+
attributes (but does not provide set-like operations).
|
831 |
+
Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
|
832 |
+
attribute for the edge from ``u`` to ``v`` with key ``k`` while
|
833 |
+
``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
|
834 |
+
iterates through all the edges yielding the color attribute with
|
835 |
+
default `'red'` if no color attribute exists.
|
836 |
+
|
837 |
+
Edges are returned as tuples with optional data and keys
|
838 |
+
in the order (node, neighbor, key, data). If ``keys=True`` is not
|
839 |
+
provided, the tuples will just be (node, neighbor, data), but
|
840 |
+
multiple tuples with the same node and neighbor will be generated
|
841 |
+
when multiple edges exist between two nodes.
|
842 |
+
|
843 |
+
Parameters
|
844 |
+
----------
|
845 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
846 |
+
The view will only report edges from these nodes.
|
847 |
+
data : string or bool, optional (default=False)
|
848 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
849 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
850 |
+
If False, return 2-tuple (u, v).
|
851 |
+
keys : bool, optional (default=False)
|
852 |
+
If True, return edge keys with each edge, creating (u, v, k)
|
853 |
+
tuples or (u, v, k, d) tuples if data is also requested.
|
854 |
+
default : value, optional (default=None)
|
855 |
+
Value used for edges that don't have the requested attribute.
|
856 |
+
Only relevant if data is not True or False.
|
857 |
+
|
858 |
+
Returns
|
859 |
+
-------
|
860 |
+
edges : MultiEdgeView
|
861 |
+
A view of edge attributes, usually it iterates over (u, v)
|
862 |
+
(u, v, k) or (u, v, k, d) tuples of edges, but can also be
|
863 |
+
used for attribute lookup as ``edges[u, v, k]['foo']``.
|
864 |
+
|
865 |
+
Notes
|
866 |
+
-----
|
867 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
868 |
+
For directed graphs this returns the out-edges.
|
869 |
+
|
870 |
+
Examples
|
871 |
+
--------
|
872 |
+
>>> G = nx.MultiGraph()
|
873 |
+
>>> nx.add_path(G, [0, 1, 2])
|
874 |
+
>>> key = G.add_edge(2, 3, weight=5)
|
875 |
+
>>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
|
876 |
+
>>> [e for e in G.edges()]
|
877 |
+
[(0, 1), (1, 2), (1, 2), (2, 3)]
|
878 |
+
>>> G.edges.data() # default data is {} (empty dict)
|
879 |
+
MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
|
880 |
+
>>> G.edges.data("weight", default=1)
|
881 |
+
MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
|
882 |
+
>>> G.edges(keys=True) # default keys are integers
|
883 |
+
MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
|
884 |
+
>>> G.edges.data(keys=True)
|
885 |
+
MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
|
886 |
+
>>> G.edges.data("weight", default=1, keys=True)
|
887 |
+
MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
|
888 |
+
>>> G.edges([0, 3]) # Note ordering of tuples from listed sources
|
889 |
+
MultiEdgeDataView([(0, 1), (3, 2)])
|
890 |
+
>>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
|
891 |
+
MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
|
892 |
+
>>> G.edges(0)
|
893 |
+
MultiEdgeDataView([(0, 1)])
|
894 |
+
"""
|
895 |
+
return MultiEdgeView(self)
|
896 |
+
|
897 |
+
def get_edge_data(self, u, v, key=None, default=None):
|
898 |
+
"""Returns the attribute dictionary associated with edge (u, v,
|
899 |
+
key).
|
900 |
+
|
901 |
+
If a key is not provided, returns a dictionary mapping edge keys
|
902 |
+
to attribute dictionaries for each edge between u and v.
|
903 |
+
|
904 |
+
This is identical to `G[u][v][key]` except the default is returned
|
905 |
+
instead of an exception is the edge doesn't exist.
|
906 |
+
|
907 |
+
Parameters
|
908 |
+
----------
|
909 |
+
u, v : nodes
|
910 |
+
|
911 |
+
default : any Python object (default=None)
|
912 |
+
Value to return if the specific edge (u, v, key) is not
|
913 |
+
found, OR if there are no edges between u and v and no key
|
914 |
+
is specified.
|
915 |
+
|
916 |
+
key : hashable identifier, optional (default=None)
|
917 |
+
Return data only for the edge with specified key, as an
|
918 |
+
attribute dictionary (rather than a dictionary mapping keys
|
919 |
+
to attribute dictionaries).
|
920 |
+
|
921 |
+
Returns
|
922 |
+
-------
|
923 |
+
edge_dict : dictionary
|
924 |
+
The edge attribute dictionary, OR a dictionary mapping edge
|
925 |
+
keys to attribute dictionaries for each of those edges if no
|
926 |
+
specific key is provided (even if there's only one edge
|
927 |
+
between u and v).
|
928 |
+
|
929 |
+
Examples
|
930 |
+
--------
|
931 |
+
>>> G = nx.MultiGraph() # or MultiDiGraph
|
932 |
+
>>> key = G.add_edge(0, 1, key="a", weight=7)
|
933 |
+
>>> G[0][1]["a"] # key='a'
|
934 |
+
{'weight': 7}
|
935 |
+
>>> G.edges[0, 1, "a"] # key='a'
|
936 |
+
{'weight': 7}
|
937 |
+
|
938 |
+
Warning: we protect the graph data structure by making
|
939 |
+
`G.edges` and `G[1][2]` read-only dict-like structures.
|
940 |
+
However, you can assign values to attributes in e.g.
|
941 |
+
`G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
|
942 |
+
bracket as shown next. You need to specify all edge info
|
943 |
+
to assign to the edge data associated with an edge.
|
944 |
+
|
945 |
+
>>> G[0][1]["a"]["weight"] = 10
|
946 |
+
>>> G.edges[0, 1, "a"]["weight"] = 10
|
947 |
+
>>> G[0][1]["a"]["weight"]
|
948 |
+
10
|
949 |
+
>>> G.edges[1, 0, "a"]["weight"]
|
950 |
+
10
|
951 |
+
|
952 |
+
>>> G = nx.MultiGraph() # or MultiDiGraph
|
953 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
954 |
+
>>> G.edges[0, 1, 0]["weight"] = 5
|
955 |
+
>>> G.get_edge_data(0, 1)
|
956 |
+
{0: {'weight': 5}}
|
957 |
+
>>> e = (0, 1)
|
958 |
+
>>> G.get_edge_data(*e) # tuple form
|
959 |
+
{0: {'weight': 5}}
|
960 |
+
>>> G.get_edge_data(3, 0) # edge not in graph, returns None
|
961 |
+
>>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
|
962 |
+
0
|
963 |
+
>>> G.get_edge_data(1, 0, 0) # specific key gives back
|
964 |
+
{'weight': 5}
|
965 |
+
"""
|
966 |
+
try:
|
967 |
+
if key is None:
|
968 |
+
return self._adj[u][v]
|
969 |
+
else:
|
970 |
+
return self._adj[u][v][key]
|
971 |
+
except KeyError:
|
972 |
+
return default
|
973 |
+
|
974 |
+
@cached_property
|
975 |
+
def degree(self):
|
976 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
977 |
+
|
978 |
+
The node degree is the number of edges adjacent to the node.
|
979 |
+
The weighted node degree is the sum of the edge weights for
|
980 |
+
edges incident to that node.
|
981 |
+
|
982 |
+
This object provides an iterator for (node, degree) as well as
|
983 |
+
lookup for the degree for a single node.
|
984 |
+
|
985 |
+
Parameters
|
986 |
+
----------
|
987 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
988 |
+
The view will only report edges incident to these nodes.
|
989 |
+
|
990 |
+
weight : string or None, optional (default=None)
|
991 |
+
The name of an edge attribute that holds the numerical value used
|
992 |
+
as a weight. If None, then each edge has weight 1.
|
993 |
+
The degree is the sum of the edge weights adjacent to the node.
|
994 |
+
|
995 |
+
Returns
|
996 |
+
-------
|
997 |
+
MultiDegreeView or int
|
998 |
+
If multiple nodes are requested (the default), returns a `MultiDegreeView`
|
999 |
+
mapping nodes to their degree.
|
1000 |
+
If a single node is requested, returns the degree of the node as an integer.
|
1001 |
+
|
1002 |
+
Examples
|
1003 |
+
--------
|
1004 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1005 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1006 |
+
>>> G.degree(0) # node 0 with degree 1
|
1007 |
+
1
|
1008 |
+
>>> list(G.degree([0, 1]))
|
1009 |
+
[(0, 1), (1, 2)]
|
1010 |
+
|
1011 |
+
"""
|
1012 |
+
return MultiDegreeView(self)
|
1013 |
+
|
1014 |
+
def is_multigraph(self):
|
1015 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
1016 |
+
return True
|
1017 |
+
|
1018 |
+
def is_directed(self):
|
1019 |
+
"""Returns True if graph is directed, False otherwise."""
|
1020 |
+
return False
|
1021 |
+
|
1022 |
+
def copy(self, as_view=False):
|
1023 |
+
"""Returns a copy of the graph.
|
1024 |
+
|
1025 |
+
The copy method by default returns an independent shallow copy
|
1026 |
+
of the graph and attributes. That is, if an attribute is a
|
1027 |
+
container, that container is shared by the original an the copy.
|
1028 |
+
Use Python's `copy.deepcopy` for new containers.
|
1029 |
+
|
1030 |
+
If `as_view` is True then a view is returned instead of a copy.
|
1031 |
+
|
1032 |
+
Notes
|
1033 |
+
-----
|
1034 |
+
All copies reproduce the graph structure, but data attributes
|
1035 |
+
may be handled in different ways. There are four types of copies
|
1036 |
+
of a graph that people might want.
|
1037 |
+
|
1038 |
+
Deepcopy -- A "deepcopy" copies the graph structure as well as
|
1039 |
+
all data attributes and any objects they might contain.
|
1040 |
+
The entire graph object is new so that changes in the copy
|
1041 |
+
do not affect the original object. (see Python's copy.deepcopy)
|
1042 |
+
|
1043 |
+
Data Reference (Shallow) -- For a shallow copy the graph structure
|
1044 |
+
is copied but the edge, node and graph attribute dicts are
|
1045 |
+
references to those in the original graph. This saves
|
1046 |
+
time and memory but could cause confusion if you change an attribute
|
1047 |
+
in one graph and it changes the attribute in the other.
|
1048 |
+
NetworkX does not provide this level of shallow copy.
|
1049 |
+
|
1050 |
+
Independent Shallow -- This copy creates new independent attribute
|
1051 |
+
dicts and then does a shallow copy of the attributes. That is, any
|
1052 |
+
attributes that are containers are shared between the new graph
|
1053 |
+
and the original. This is exactly what `dict.copy()` provides.
|
1054 |
+
You can obtain this style copy using:
|
1055 |
+
|
1056 |
+
>>> G = nx.path_graph(5)
|
1057 |
+
>>> H = G.copy()
|
1058 |
+
>>> H = G.copy(as_view=False)
|
1059 |
+
>>> H = nx.Graph(G)
|
1060 |
+
>>> H = G.__class__(G)
|
1061 |
+
|
1062 |
+
Fresh Data -- For fresh data, the graph structure is copied while
|
1063 |
+
new empty data attribute dicts are created. The resulting graph
|
1064 |
+
is independent of the original and it has no edge, node or graph
|
1065 |
+
attributes. Fresh copies are not enabled. Instead use:
|
1066 |
+
|
1067 |
+
>>> H = G.__class__()
|
1068 |
+
>>> H.add_nodes_from(G)
|
1069 |
+
>>> H.add_edges_from(G.edges)
|
1070 |
+
|
1071 |
+
View -- Inspired by dict-views, graph-views act like read-only
|
1072 |
+
versions of the original graph, providing a copy of the original
|
1073 |
+
structure without requiring any memory for copying the information.
|
1074 |
+
|
1075 |
+
See the Python copy module for more information on shallow
|
1076 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1077 |
+
|
1078 |
+
Parameters
|
1079 |
+
----------
|
1080 |
+
as_view : bool, optional (default=False)
|
1081 |
+
If True, the returned graph-view provides a read-only view
|
1082 |
+
of the original graph without actually copying any data.
|
1083 |
+
|
1084 |
+
Returns
|
1085 |
+
-------
|
1086 |
+
G : Graph
|
1087 |
+
A copy of the graph.
|
1088 |
+
|
1089 |
+
See Also
|
1090 |
+
--------
|
1091 |
+
to_directed: return a directed copy of the graph.
|
1092 |
+
|
1093 |
+
Examples
|
1094 |
+
--------
|
1095 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1096 |
+
>>> H = G.copy()
|
1097 |
+
|
1098 |
+
"""
|
1099 |
+
if as_view is True:
|
1100 |
+
return nx.graphviews.generic_graph_view(self)
|
1101 |
+
G = self.__class__()
|
1102 |
+
G.graph.update(self.graph)
|
1103 |
+
G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
|
1104 |
+
G.add_edges_from(
|
1105 |
+
(u, v, key, datadict.copy())
|
1106 |
+
for u, nbrs in self._adj.items()
|
1107 |
+
for v, keydict in nbrs.items()
|
1108 |
+
for key, datadict in keydict.items()
|
1109 |
+
)
|
1110 |
+
return G
|
1111 |
+
|
1112 |
+
def to_directed(self, as_view=False):
|
1113 |
+
"""Returns a directed representation of the graph.
|
1114 |
+
|
1115 |
+
Returns
|
1116 |
+
-------
|
1117 |
+
G : MultiDiGraph
|
1118 |
+
A directed graph with the same name, same nodes, and with
|
1119 |
+
each edge (u, v, k, data) replaced by two directed edges
|
1120 |
+
(u, v, k, data) and (v, u, k, data).
|
1121 |
+
|
1122 |
+
Notes
|
1123 |
+
-----
|
1124 |
+
This returns a "deepcopy" of the edge, node, and
|
1125 |
+
graph attributes which attempts to completely copy
|
1126 |
+
all of the data and references.
|
1127 |
+
|
1128 |
+
This is in contrast to the similar D=MultiDiGraph(G) which
|
1129 |
+
returns a shallow copy of the data.
|
1130 |
+
|
1131 |
+
See the Python copy module for more information on shallow
|
1132 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1133 |
+
|
1134 |
+
Warning: If you have subclassed MultiGraph to use dict-like objects
|
1135 |
+
in the data structure, those changes do not transfer to the
|
1136 |
+
MultiDiGraph created by this method.
|
1137 |
+
|
1138 |
+
Examples
|
1139 |
+
--------
|
1140 |
+
>>> G = nx.MultiGraph()
|
1141 |
+
>>> G.add_edge(0, 1)
|
1142 |
+
0
|
1143 |
+
>>> G.add_edge(0, 1)
|
1144 |
+
1
|
1145 |
+
>>> H = G.to_directed()
|
1146 |
+
>>> list(H.edges)
|
1147 |
+
[(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
|
1148 |
+
|
1149 |
+
If already directed, return a (deep) copy
|
1150 |
+
|
1151 |
+
>>> G = nx.MultiDiGraph()
|
1152 |
+
>>> G.add_edge(0, 1)
|
1153 |
+
0
|
1154 |
+
>>> H = G.to_directed()
|
1155 |
+
>>> list(H.edges)
|
1156 |
+
[(0, 1, 0)]
|
1157 |
+
"""
|
1158 |
+
graph_class = self.to_directed_class()
|
1159 |
+
if as_view is True:
|
1160 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1161 |
+
# deepcopy when not a view
|
1162 |
+
G = graph_class()
|
1163 |
+
G.graph.update(deepcopy(self.graph))
|
1164 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1165 |
+
G.add_edges_from(
|
1166 |
+
(u, v, key, deepcopy(datadict))
|
1167 |
+
for u, nbrs in self.adj.items()
|
1168 |
+
for v, keydict in nbrs.items()
|
1169 |
+
for key, datadict in keydict.items()
|
1170 |
+
)
|
1171 |
+
return G
|
1172 |
+
|
1173 |
+
def to_undirected(self, as_view=False):
|
1174 |
+
"""Returns an undirected copy of the graph.
|
1175 |
+
|
1176 |
+
Returns
|
1177 |
+
-------
|
1178 |
+
G : Graph/MultiGraph
|
1179 |
+
A deepcopy of the graph.
|
1180 |
+
|
1181 |
+
See Also
|
1182 |
+
--------
|
1183 |
+
copy, add_edge, add_edges_from
|
1184 |
+
|
1185 |
+
Notes
|
1186 |
+
-----
|
1187 |
+
This returns a "deepcopy" of the edge, node, and
|
1188 |
+
graph attributes which attempts to completely copy
|
1189 |
+
all of the data and references.
|
1190 |
+
|
1191 |
+
This is in contrast to the similar `G = nx.MultiGraph(D)`
|
1192 |
+
which returns a shallow copy of the data.
|
1193 |
+
|
1194 |
+
See the Python copy module for more information on shallow
|
1195 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1196 |
+
|
1197 |
+
Warning: If you have subclassed MultiGraph to use dict-like
|
1198 |
+
objects in the data structure, those changes do not transfer
|
1199 |
+
to the MultiGraph created by this method.
|
1200 |
+
|
1201 |
+
Examples
|
1202 |
+
--------
|
1203 |
+
>>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
|
1204 |
+
>>> H = G.to_directed()
|
1205 |
+
>>> list(H.edges)
|
1206 |
+
[(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
|
1207 |
+
>>> G2 = H.to_undirected()
|
1208 |
+
>>> list(G2.edges)
|
1209 |
+
[(0, 1, 0), (0, 1, 1), (1, 2, 0)]
|
1210 |
+
"""
|
1211 |
+
graph_class = self.to_undirected_class()
|
1212 |
+
if as_view is True:
|
1213 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1214 |
+
# deepcopy when not a view
|
1215 |
+
G = graph_class()
|
1216 |
+
G.graph.update(deepcopy(self.graph))
|
1217 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1218 |
+
G.add_edges_from(
|
1219 |
+
(u, v, key, deepcopy(datadict))
|
1220 |
+
for u, nbrs in self._adj.items()
|
1221 |
+
for v, keydict in nbrs.items()
|
1222 |
+
for key, datadict in keydict.items()
|
1223 |
+
)
|
1224 |
+
return G
|
1225 |
+
|
1226 |
+
def number_of_edges(self, u=None, v=None):
|
1227 |
+
"""Returns the number of edges between two nodes.
|
1228 |
+
|
1229 |
+
Parameters
|
1230 |
+
----------
|
1231 |
+
u, v : nodes, optional (Default=all edges)
|
1232 |
+
If u and v are specified, return the number of edges between
|
1233 |
+
u and v. Otherwise return the total number of all edges.
|
1234 |
+
|
1235 |
+
Returns
|
1236 |
+
-------
|
1237 |
+
nedges : int
|
1238 |
+
The number of edges in the graph. If nodes `u` and `v` are
|
1239 |
+
specified return the number of edges between those nodes. If
|
1240 |
+
the graph is directed, this only returns the number of edges
|
1241 |
+
from `u` to `v`.
|
1242 |
+
|
1243 |
+
See Also
|
1244 |
+
--------
|
1245 |
+
size
|
1246 |
+
|
1247 |
+
Examples
|
1248 |
+
--------
|
1249 |
+
For undirected multigraphs, this method counts the total number
|
1250 |
+
of edges in the graph::
|
1251 |
+
|
1252 |
+
>>> G = nx.MultiGraph()
|
1253 |
+
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
|
1254 |
+
[0, 1, 0]
|
1255 |
+
>>> G.number_of_edges()
|
1256 |
+
3
|
1257 |
+
|
1258 |
+
If you specify two nodes, this counts the total number of edges
|
1259 |
+
joining the two nodes::
|
1260 |
+
|
1261 |
+
>>> G.number_of_edges(0, 1)
|
1262 |
+
2
|
1263 |
+
|
1264 |
+
For directed multigraphs, this method can count the total number
|
1265 |
+
of directed edges from `u` to `v`::
|
1266 |
+
|
1267 |
+
>>> G = nx.MultiDiGraph()
|
1268 |
+
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
|
1269 |
+
[0, 1, 0]
|
1270 |
+
>>> G.number_of_edges(0, 1)
|
1271 |
+
2
|
1272 |
+
>>> G.number_of_edges(1, 0)
|
1273 |
+
1
|
1274 |
+
|
1275 |
+
"""
|
1276 |
+
if u is None:
|
1277 |
+
return self.size()
|
1278 |
+
try:
|
1279 |
+
edgedata = self._adj[u][v]
|
1280 |
+
except KeyError:
|
1281 |
+
return 0 # no such edge
|
1282 |
+
return len(edgedata)
|