Upload folder using huggingface_hub (part 11)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +20 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/METADATA +177 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/RECORD +0 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/WHEEL +5 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/entry_points.txt +2 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt +37 -0
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/top_level.txt +1 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__init__.py +19 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/adjacency.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/cytoscape.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/node_link.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/tree.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/adjacency.py +156 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/cytoscape.py +190 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/node_link.py +261 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_adjacency.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_cytoscape.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_node_link.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_tree.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_adjacency.py +78 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_cytoscape.py +78 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_node_link.py +109 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_tree.py +48 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tree.py +137 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/leda.py +108 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/multiline_adjlist.py +393 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/p2g.py +113 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/pajek.py +286 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/sparse6.py +379 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_adjlist.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_edgelist.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_gexf.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_gml.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_graph6.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_graphml.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_leda.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_p2g.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_pajek.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_sparse6.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_text.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.py +354 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.py +318 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.py +612 -0
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gml.py +744 -0
.gitattributes
CHANGED
|
@@ -231,3 +231,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 231 |
.venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_fp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 232 |
.venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 233 |
.venv/lib/python3.12/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
.venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_fp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 232 |
.venv/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 233 |
.venv/lib/python3.12/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 234 |
+
.venv/lib/python3.12/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 235 |
+
.venv/lib/python3.12/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 236 |
+
.venv/lib/python3.12/site-packages/numpy/_core/_multiarray_tests.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 237 |
+
.venv/lib/python3.12/site-packages/numpy/_core/_multiarray_umath.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 238 |
+
.venv/lib/python3.12/site-packages/numpy/_core/_simd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 239 |
+
.venv/lib/python3.12/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 240 |
+
.venv/lib/python3.12/site-packages/numpy/fft/_pocketfft_umath.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 241 |
+
.venv/lib/python3.12/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 242 |
+
.venv/lib/python3.12/site-packages/numpy/linalg/__pycache__/_linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 243 |
+
.venv/lib/python3.12/site-packages/numpy/linalg/_umath_linalg.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 244 |
+
.venv/lib/python3.12/site-packages/numpy/ma/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 245 |
+
.venv/lib/python3.12/site-packages/numpy/random/_bounded_integers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 246 |
+
.venv/lib/python3.12/site-packages/numpy/random/_common.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 247 |
+
.venv/lib/python3.12/site-packages/numpy/random/_generator.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 248 |
+
.venv/lib/python3.12/site-packages/numpy/random/_mt19937.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 249 |
+
.venv/lib/python3.12/site-packages/numpy/random/_pcg64.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 250 |
+
.venv/lib/python3.12/site-packages/numpy/random/_philox.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 251 |
+
.venv/lib/python3.12/site-packages/numpy/random/bit_generator.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 252 |
+
.venv/lib/python3.12/site-packages/numpy/random/mtrand.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 253 |
+
.venv/lib/python3.12/site-packages/numpy/testing/_private/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: networkx
|
| 3 |
+
Version: 3.6.1
|
| 4 |
+
Summary: Python package for creating and manipulating graphs and networks
|
| 5 |
+
Author-email: Aric Hagberg <hagberg@lanl.gov>
|
| 6 |
+
Maintainer-email: NetworkX Developers <networkx-discuss@googlegroups.com>
|
| 7 |
+
License-Expression: BSD-3-Clause
|
| 8 |
+
Project-URL: Homepage, https://networkx.org/
|
| 9 |
+
Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues
|
| 10 |
+
Project-URL: Documentation, https://networkx.org/documentation/stable/
|
| 11 |
+
Project-URL: Source Code, https://github.com/networkx/networkx
|
| 12 |
+
Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math
|
| 13 |
+
Platform: Linux
|
| 14 |
+
Platform: Mac OSX
|
| 15 |
+
Platform: Windows
|
| 16 |
+
Platform: Unix
|
| 17 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 18 |
+
Classifier: Intended Audience :: Developers
|
| 19 |
+
Classifier: Intended Audience :: Science/Research
|
| 20 |
+
Classifier: Operating System :: OS Independent
|
| 21 |
+
Classifier: Programming Language :: Python :: 3
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 26 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
| 29 |
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
| 30 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 31 |
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
| 32 |
+
Requires-Python: !=3.14.1,>=3.11
|
| 33 |
+
Description-Content-Type: text/x-rst
|
| 34 |
+
License-File: LICENSE.txt
|
| 35 |
+
Provides-Extra: benchmarking
|
| 36 |
+
Requires-Dist: asv; extra == "benchmarking"
|
| 37 |
+
Requires-Dist: virtualenv; extra == "benchmarking"
|
| 38 |
+
Provides-Extra: default
|
| 39 |
+
Requires-Dist: numpy>=1.25; extra == "default"
|
| 40 |
+
Requires-Dist: scipy>=1.11.2; extra == "default"
|
| 41 |
+
Requires-Dist: matplotlib>=3.8; extra == "default"
|
| 42 |
+
Requires-Dist: pandas>=2.0; extra == "default"
|
| 43 |
+
Provides-Extra: developer
|
| 44 |
+
Requires-Dist: pre-commit>=4.1; extra == "developer"
|
| 45 |
+
Requires-Dist: mypy>=1.15; extra == "developer"
|
| 46 |
+
Provides-Extra: doc
|
| 47 |
+
Requires-Dist: sphinx>=8.0; extra == "doc"
|
| 48 |
+
Requires-Dist: pydata-sphinx-theme>=0.16; extra == "doc"
|
| 49 |
+
Requires-Dist: sphinx-gallery>=0.18; extra == "doc"
|
| 50 |
+
Requires-Dist: numpydoc>=1.8.0; extra == "doc"
|
| 51 |
+
Requires-Dist: pillow>=10; extra == "doc"
|
| 52 |
+
Requires-Dist: texext>=0.6.7; extra == "doc"
|
| 53 |
+
Requires-Dist: myst-nb>=1.1; extra == "doc"
|
| 54 |
+
Requires-Dist: intersphinx-registry; extra == "doc"
|
| 55 |
+
Provides-Extra: example
|
| 56 |
+
Requires-Dist: osmnx>=2.0.0; extra == "example"
|
| 57 |
+
Requires-Dist: momepy>=0.7.2; extra == "example"
|
| 58 |
+
Requires-Dist: contextily>=1.6; extra == "example"
|
| 59 |
+
Requires-Dist: seaborn>=0.13; extra == "example"
|
| 60 |
+
Requires-Dist: cairocffi>=1.7; extra == "example"
|
| 61 |
+
Requires-Dist: igraph>=0.11; extra == "example"
|
| 62 |
+
Requires-Dist: scikit-learn>=1.5; extra == "example"
|
| 63 |
+
Requires-Dist: iplotx>=0.9.0; extra == "example"
|
| 64 |
+
Provides-Extra: extra
|
| 65 |
+
Requires-Dist: lxml>=4.6; extra == "extra"
|
| 66 |
+
Requires-Dist: pygraphviz>=1.14; extra == "extra"
|
| 67 |
+
Requires-Dist: pydot>=3.0.1; extra == "extra"
|
| 68 |
+
Requires-Dist: sympy>=1.10; extra == "extra"
|
| 69 |
+
Provides-Extra: release
|
| 70 |
+
Requires-Dist: build>=0.10; extra == "release"
|
| 71 |
+
Requires-Dist: twine>=4.0; extra == "release"
|
| 72 |
+
Requires-Dist: wheel>=0.40; extra == "release"
|
| 73 |
+
Requires-Dist: changelist==0.5; extra == "release"
|
| 74 |
+
Provides-Extra: test
|
| 75 |
+
Requires-Dist: pytest>=7.2; extra == "test"
|
| 76 |
+
Requires-Dist: pytest-cov>=4.0; extra == "test"
|
| 77 |
+
Requires-Dist: pytest-xdist>=3.0; extra == "test"
|
| 78 |
+
Provides-Extra: test-extras
|
| 79 |
+
Requires-Dist: pytest-mpl; extra == "test-extras"
|
| 80 |
+
Requires-Dist: pytest-randomly; extra == "test-extras"
|
| 81 |
+
Dynamic: license-file
|
| 82 |
+
|
| 83 |
+
NetworkX
|
| 84 |
+
========
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
.. image::
|
| 88 |
+
https://github.com/networkx/networkx/actions/workflows/test.yml/badge.svg?branch=main
|
| 89 |
+
:target: https://github.com/networkx/networkx/actions/workflows/test.yml
|
| 90 |
+
|
| 91 |
+
.. image::
|
| 92 |
+
https://img.shields.io/pypi/v/networkx.svg?
|
| 93 |
+
:target: https://pypi.python.org/pypi/networkx
|
| 94 |
+
|
| 95 |
+
.. image::
|
| 96 |
+
https://img.shields.io/pypi/l/networkx.svg?
|
| 97 |
+
:target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
|
| 98 |
+
|
| 99 |
+
.. image::
|
| 100 |
+
https://img.shields.io/pypi/pyversions/networkx.svg?
|
| 101 |
+
:target: https://pypi.python.org/pypi/networkx
|
| 102 |
+
|
| 103 |
+
.. image::
|
| 104 |
+
https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute
|
| 105 |
+
:target: https://github.com/networkx/networkx/contribute
|
| 106 |
+
|
| 107 |
+
.. image::
|
| 108 |
+
https://insights.linuxfoundation.org/api/badge/health-score?project=networkx
|
| 109 |
+
:target: https://insights.linuxfoundation.org/project/networkx
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
NetworkX is a Python package for the creation, manipulation,
|
| 113 |
+
and study of the structure, dynamics, and functions
|
| 114 |
+
of complex networks.
|
| 115 |
+
|
| 116 |
+
- **Website (including documentation):** https://networkx.org
|
| 117 |
+
- **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
|
| 118 |
+
- **Source:** https://github.com/networkx/networkx
|
| 119 |
+
- **Bug reports:** https://github.com/networkx/networkx/issues
|
| 120 |
+
- **Report a security vulnerability:** https://tidelift.com/security
|
| 121 |
+
- **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
|
| 122 |
+
- **GitHub Discussions:** https://github.com/networkx/networkx/discussions
|
| 123 |
+
- **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz
|
| 124 |
+
- **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
|
| 125 |
+
|
| 126 |
+
Simple example
|
| 127 |
+
--------------
|
| 128 |
+
|
| 129 |
+
Find the shortest path between two nodes in an undirected graph:
|
| 130 |
+
|
| 131 |
+
.. code:: pycon
|
| 132 |
+
|
| 133 |
+
>>> import networkx as nx
|
| 134 |
+
>>> G = nx.Graph()
|
| 135 |
+
>>> G.add_edge("A", "B", weight=4)
|
| 136 |
+
>>> G.add_edge("B", "D", weight=2)
|
| 137 |
+
>>> G.add_edge("A", "C", weight=3)
|
| 138 |
+
>>> G.add_edge("C", "D", weight=4)
|
| 139 |
+
>>> nx.shortest_path(G, "A", "D", weight="weight")
|
| 140 |
+
['A', 'B', 'D']
|
| 141 |
+
|
| 142 |
+
Install
|
| 143 |
+
-------
|
| 144 |
+
|
| 145 |
+
Install the latest released version of NetworkX:
|
| 146 |
+
|
| 147 |
+
.. code:: shell
|
| 148 |
+
|
| 149 |
+
$ pip install networkx
|
| 150 |
+
|
| 151 |
+
Install with all optional dependencies:
|
| 152 |
+
|
| 153 |
+
.. code:: shell
|
| 154 |
+
|
| 155 |
+
$ pip install networkx[default]
|
| 156 |
+
|
| 157 |
+
For additional details,
|
| 158 |
+
please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
|
| 159 |
+
|
| 160 |
+
Bugs
|
| 161 |
+
----
|
| 162 |
+
|
| 163 |
+
Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
|
| 164 |
+
Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
|
| 165 |
+
and create a pull request (PR). We welcome all changes, big or small, and we
|
| 166 |
+
will help you make the PR if you are new to `git` (just ask on the issue and/or
|
| 167 |
+
see the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
|
| 168 |
+
|
| 169 |
+
License
|
| 170 |
+
-------
|
| 171 |
+
|
| 172 |
+
Released under the `3-clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
|
| 173 |
+
|
| 174 |
+
Copyright (c) 2004-2025, NetworkX Developers
|
| 175 |
+
Aric Hagberg <hagberg@lanl.gov>
|
| 176 |
+
Dan Schult <dschult@colgate.edu>
|
| 177 |
+
Pieter Swart <swart@lanl.gov>
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[networkx.backends]
|
| 2 |
+
nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NetworkX is distributed with the 3-clause BSD license.
|
| 2 |
+
|
| 3 |
+
::
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2004-2025, NetworkX Developers
|
| 6 |
+
Aric Hagberg <hagberg@lanl.gov>
|
| 7 |
+
Dan Schult <dschult@colgate.edu>
|
| 8 |
+
Pieter Swart <swart@lanl.gov>
|
| 9 |
+
All rights reserved.
|
| 10 |
+
|
| 11 |
+
Redistribution and use in source and binary forms, with or without
|
| 12 |
+
modification, are permitted provided that the following conditions are
|
| 13 |
+
met:
|
| 14 |
+
|
| 15 |
+
* Redistributions of source code must retain the above copyright
|
| 16 |
+
notice, this list of conditions and the following disclaimer.
|
| 17 |
+
|
| 18 |
+
* Redistributions in binary form must reproduce the above
|
| 19 |
+
copyright notice, this list of conditions and the following
|
| 20 |
+
disclaimer in the documentation and/or other materials provided
|
| 21 |
+
with the distribution.
|
| 22 |
+
|
| 23 |
+
* Neither the name of the NetworkX Developers nor the names of its
|
| 24 |
+
contributors may be used to endorse or promote products derived
|
| 25 |
+
from this software without specific prior written permission.
|
| 26 |
+
|
| 27 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 28 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 29 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 30 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 31 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 32 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 33 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 34 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 35 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 36 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 37 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
networkx
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
*********
|
| 3 |
+
JSON data
|
| 4 |
+
*********
|
| 5 |
+
Generate and parse JSON serializable data for NetworkX graphs.
|
| 6 |
+
|
| 7 |
+
These formats are suitable for use with the d3.js examples https://d3js.org/
|
| 8 |
+
|
| 9 |
+
The three formats that you can generate with NetworkX are:
|
| 10 |
+
|
| 11 |
+
- node-link like in the d3.js example https://bl.ocks.org/mbostock/4062045
|
| 12 |
+
- tree like in the d3.js example https://bl.ocks.org/mbostock/4063550
|
| 13 |
+
- adjacency like in the d3.js example https://bost.ocks.org/mike/miserables/
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from networkx.readwrite.json_graph.node_link import *
|
| 17 |
+
from networkx.readwrite.json_graph.adjacency import *
|
| 18 |
+
from networkx.readwrite.json_graph.tree import *
|
| 19 |
+
from networkx.readwrite.json_graph.cytoscape import *
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (905 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/adjacency.cpython-312.pyc
ADDED
|
Binary file (5.89 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/cytoscape.cpython-312.pyc
ADDED
|
Binary file (7.62 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/node_link.cpython-312.pyc
ADDED
|
Binary file (9.32 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__pycache__/tree.cpython-312.pyc
ADDED
|
Binary file (5.18 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/adjacency.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import networkx as nx
|
| 2 |
+
|
| 3 |
+
__all__ = ["adjacency_data", "adjacency_graph"]
|
| 4 |
+
|
| 5 |
+
_attrs = {"id": "id", "key": "key"}
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def adjacency_data(G, attrs=_attrs):
|
| 9 |
+
"""Returns data in adjacency format that is suitable for JSON serialization
|
| 10 |
+
and use in JavaScript documents.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
G : NetworkX graph
|
| 15 |
+
|
| 16 |
+
attrs : dict
|
| 17 |
+
A dictionary that contains two keys 'id' and 'key'. The corresponding
|
| 18 |
+
values provide the attribute names for storing NetworkX-internal graph
|
| 19 |
+
data. The values should be unique. Default value:
|
| 20 |
+
:samp:`dict(id='id', key='key')`.
|
| 21 |
+
|
| 22 |
+
If some user-defined graph data use these attribute names as data keys,
|
| 23 |
+
they may be silently dropped.
|
| 24 |
+
|
| 25 |
+
Returns
|
| 26 |
+
-------
|
| 27 |
+
data : dict
|
| 28 |
+
A dictionary with adjacency formatted data.
|
| 29 |
+
|
| 30 |
+
Raises
|
| 31 |
+
------
|
| 32 |
+
NetworkXError
|
| 33 |
+
If values in attrs are not unique.
|
| 34 |
+
|
| 35 |
+
Examples
|
| 36 |
+
--------
|
| 37 |
+
>>> from networkx.readwrite import json_graph
|
| 38 |
+
>>> G = nx.Graph([(1, 2)])
|
| 39 |
+
>>> data = json_graph.adjacency_data(G)
|
| 40 |
+
|
| 41 |
+
To serialize with json
|
| 42 |
+
|
| 43 |
+
>>> import json
|
| 44 |
+
>>> s = json.dumps(data)
|
| 45 |
+
|
| 46 |
+
Notes
|
| 47 |
+
-----
|
| 48 |
+
Graph, node, and link attributes will be written when using this format
|
| 49 |
+
but attribute keys must be strings if you want to serialize the resulting
|
| 50 |
+
data with JSON.
|
| 51 |
+
|
| 52 |
+
The default value of attrs will be changed in a future release of NetworkX.
|
| 53 |
+
|
| 54 |
+
See Also
|
| 55 |
+
--------
|
| 56 |
+
adjacency_graph, node_link_data, tree_data
|
| 57 |
+
"""
|
| 58 |
+
multigraph = G.is_multigraph()
|
| 59 |
+
id_ = attrs["id"]
|
| 60 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
| 61 |
+
key = None if not multigraph else attrs["key"]
|
| 62 |
+
if id_ == key:
|
| 63 |
+
raise nx.NetworkXError("Attribute names are not unique.")
|
| 64 |
+
data = {}
|
| 65 |
+
data["directed"] = G.is_directed()
|
| 66 |
+
data["multigraph"] = multigraph
|
| 67 |
+
data["graph"] = list(G.graph.items())
|
| 68 |
+
data["nodes"] = []
|
| 69 |
+
data["adjacency"] = []
|
| 70 |
+
for n, nbrdict in G.adjacency():
|
| 71 |
+
data["nodes"].append({**G.nodes[n], id_: n})
|
| 72 |
+
adj = []
|
| 73 |
+
if multigraph:
|
| 74 |
+
for nbr, keys in nbrdict.items():
|
| 75 |
+
for k, d in keys.items():
|
| 76 |
+
adj.append({**d, id_: nbr, key: k})
|
| 77 |
+
else:
|
| 78 |
+
for nbr, d in nbrdict.items():
|
| 79 |
+
adj.append({**d, id_: nbr})
|
| 80 |
+
data["adjacency"].append(adj)
|
| 81 |
+
return data
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 85 |
+
def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
|
| 86 |
+
"""Returns graph from adjacency data format.
|
| 87 |
+
|
| 88 |
+
Parameters
|
| 89 |
+
----------
|
| 90 |
+
data : dict
|
| 91 |
+
Adjacency list formatted graph data
|
| 92 |
+
|
| 93 |
+
directed : bool
|
| 94 |
+
If True, and direction not specified in data, return a directed graph.
|
| 95 |
+
|
| 96 |
+
multigraph : bool
|
| 97 |
+
If True, and multigraph not specified in data, return a multigraph.
|
| 98 |
+
|
| 99 |
+
attrs : dict
|
| 100 |
+
A dictionary that contains two keys 'id' and 'key'. The corresponding
|
| 101 |
+
values provide the attribute names for storing NetworkX-internal graph
|
| 102 |
+
data. The values should be unique. Default value:
|
| 103 |
+
:samp:`dict(id='id', key='key')`.
|
| 104 |
+
|
| 105 |
+
Returns
|
| 106 |
+
-------
|
| 107 |
+
G : NetworkX graph
|
| 108 |
+
A NetworkX graph object
|
| 109 |
+
|
| 110 |
+
Examples
|
| 111 |
+
--------
|
| 112 |
+
>>> from networkx.readwrite import json_graph
|
| 113 |
+
>>> G = nx.Graph([(1, 2)])
|
| 114 |
+
>>> data = json_graph.adjacency_data(G)
|
| 115 |
+
>>> H = json_graph.adjacency_graph(data)
|
| 116 |
+
|
| 117 |
+
Notes
|
| 118 |
+
-----
|
| 119 |
+
The default value of attrs will be changed in a future release of NetworkX.
|
| 120 |
+
|
| 121 |
+
See Also
|
| 122 |
+
--------
|
| 123 |
+
adjacency_graph, node_link_data, tree_data
|
| 124 |
+
"""
|
| 125 |
+
multigraph = data.get("multigraph", multigraph)
|
| 126 |
+
directed = data.get("directed", directed)
|
| 127 |
+
if multigraph:
|
| 128 |
+
graph = nx.MultiGraph()
|
| 129 |
+
else:
|
| 130 |
+
graph = nx.Graph()
|
| 131 |
+
if directed:
|
| 132 |
+
graph = graph.to_directed()
|
| 133 |
+
id_ = attrs["id"]
|
| 134 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
| 135 |
+
key = None if not multigraph else attrs["key"]
|
| 136 |
+
graph.graph = dict(data.get("graph", []))
|
| 137 |
+
mapping = []
|
| 138 |
+
for d in data["nodes"]:
|
| 139 |
+
node_data = d.copy()
|
| 140 |
+
node = node_data.pop(id_)
|
| 141 |
+
mapping.append(node)
|
| 142 |
+
graph.add_node(node)
|
| 143 |
+
graph.nodes[node].update(node_data)
|
| 144 |
+
for i, d in enumerate(data["adjacency"]):
|
| 145 |
+
source = mapping[i]
|
| 146 |
+
for tdata in d:
|
| 147 |
+
target_data = tdata.copy()
|
| 148 |
+
target = target_data.pop(id_)
|
| 149 |
+
if not multigraph:
|
| 150 |
+
graph.add_edge(source, target)
|
| 151 |
+
graph[source][target].update(target_data)
|
| 152 |
+
else:
|
| 153 |
+
ky = target_data.pop(key, None)
|
| 154 |
+
graph.add_edge(source, target, key=ky)
|
| 155 |
+
graph[source][target][ky].update(target_data)
|
| 156 |
+
return graph
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/cytoscape.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import networkx as nx
|
| 2 |
+
|
| 3 |
+
__all__ = ["cytoscape_data", "cytoscape_graph"]
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def cytoscape_data(G, name="name", ident="id"):
|
| 7 |
+
"""Returns data in Cytoscape JSON format (cyjs).
|
| 8 |
+
|
| 9 |
+
Parameters
|
| 10 |
+
----------
|
| 11 |
+
G : NetworkX Graph
|
| 12 |
+
The graph to convert to cytoscape format
|
| 13 |
+
name : string
|
| 14 |
+
A string which is mapped to the 'name' node element in cyjs format.
|
| 15 |
+
Must not have the same value as `ident`.
|
| 16 |
+
ident : string
|
| 17 |
+
A string which is mapped to the 'id' node element in cyjs format.
|
| 18 |
+
Must not have the same value as `name`.
|
| 19 |
+
|
| 20 |
+
Returns
|
| 21 |
+
-------
|
| 22 |
+
data: dict
|
| 23 |
+
A dictionary with cyjs formatted data.
|
| 24 |
+
|
| 25 |
+
Raises
|
| 26 |
+
------
|
| 27 |
+
NetworkXError
|
| 28 |
+
If the values for `name` and `ident` are identical.
|
| 29 |
+
|
| 30 |
+
See Also
|
| 31 |
+
--------
|
| 32 |
+
cytoscape_graph: convert a dictionary in cyjs format to a graph
|
| 33 |
+
|
| 34 |
+
References
|
| 35 |
+
----------
|
| 36 |
+
.. [1] Cytoscape user's manual:
|
| 37 |
+
http://manual.cytoscape.org/en/stable/index.html
|
| 38 |
+
|
| 39 |
+
Examples
|
| 40 |
+
--------
|
| 41 |
+
>>> from pprint import pprint
|
| 42 |
+
>>> G = nx.path_graph(2)
|
| 43 |
+
>>> cyto_data = nx.cytoscape_data(G)
|
| 44 |
+
>>> pprint(cyto_data, sort_dicts=False)
|
| 45 |
+
{'data': [],
|
| 46 |
+
'directed': False,
|
| 47 |
+
'multigraph': False,
|
| 48 |
+
'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
|
| 49 |
+
{'data': {'id': '1', 'value': 1, 'name': '1'}}],
|
| 50 |
+
'edges': [{'data': {'source': 0, 'target': 1}}]}}
|
| 51 |
+
|
| 52 |
+
The :mod:`json` package can be used to serialize the resulting data
|
| 53 |
+
|
| 54 |
+
>>> import io, json
|
| 55 |
+
>>> with io.StringIO() as fh: # replace io with `open(...)` to write to disk
|
| 56 |
+
... json.dump(cyto_data, fh)
|
| 57 |
+
... fh.seek(0) # doctest: +SKIP
|
| 58 |
+
... print(fh.getvalue()[:64]) # View the first 64 characters
|
| 59 |
+
{"data": [], "directed": false, "multigraph": false, "elements":
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
if name == ident:
|
| 63 |
+
raise nx.NetworkXError("name and ident must be different.")
|
| 64 |
+
|
| 65 |
+
jsondata = {"data": list(G.graph.items())}
|
| 66 |
+
jsondata["directed"] = G.is_directed()
|
| 67 |
+
jsondata["multigraph"] = G.is_multigraph()
|
| 68 |
+
jsondata["elements"] = {"nodes": [], "edges": []}
|
| 69 |
+
nodes = jsondata["elements"]["nodes"]
|
| 70 |
+
edges = jsondata["elements"]["edges"]
|
| 71 |
+
|
| 72 |
+
for i, j in G.nodes.items():
|
| 73 |
+
n = {"data": j.copy()}
|
| 74 |
+
n["data"]["id"] = j.get(ident) or str(i)
|
| 75 |
+
n["data"]["value"] = i
|
| 76 |
+
n["data"]["name"] = j.get(name) or str(i)
|
| 77 |
+
nodes.append(n)
|
| 78 |
+
|
| 79 |
+
if G.is_multigraph():
|
| 80 |
+
for e in G.edges(keys=True):
|
| 81 |
+
n = {"data": G.adj[e[0]][e[1]][e[2]].copy()}
|
| 82 |
+
n["data"]["source"] = e[0]
|
| 83 |
+
n["data"]["target"] = e[1]
|
| 84 |
+
n["data"]["key"] = e[2]
|
| 85 |
+
edges.append(n)
|
| 86 |
+
else:
|
| 87 |
+
for e in G.edges():
|
| 88 |
+
n = {"data": G.adj[e[0]][e[1]].copy()}
|
| 89 |
+
n["data"]["source"] = e[0]
|
| 90 |
+
n["data"]["target"] = e[1]
|
| 91 |
+
edges.append(n)
|
| 92 |
+
return jsondata
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 96 |
+
def cytoscape_graph(data, name="name", ident="id"):
|
| 97 |
+
"""
|
| 98 |
+
Create a NetworkX graph from a dictionary in cytoscape JSON format.
|
| 99 |
+
|
| 100 |
+
Parameters
|
| 101 |
+
----------
|
| 102 |
+
data : dict
|
| 103 |
+
A dictionary of data conforming to cytoscape JSON format.
|
| 104 |
+
name : string
|
| 105 |
+
A string which is mapped to the 'name' node element in cyjs format.
|
| 106 |
+
Must not have the same value as `ident`.
|
| 107 |
+
ident : string
|
| 108 |
+
A string which is mapped to the 'id' node element in cyjs format.
|
| 109 |
+
Must not have the same value as `name`.
|
| 110 |
+
|
| 111 |
+
Returns
|
| 112 |
+
-------
|
| 113 |
+
graph : a NetworkX graph instance
|
| 114 |
+
The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or
|
| 115 |
+
`MultiDiGraph` depending on the input data.
|
| 116 |
+
|
| 117 |
+
Raises
|
| 118 |
+
------
|
| 119 |
+
NetworkXError
|
| 120 |
+
If the `name` and `ident` attributes are identical.
|
| 121 |
+
|
| 122 |
+
See Also
|
| 123 |
+
--------
|
| 124 |
+
cytoscape_data: convert a NetworkX graph to a dict in cyjs format
|
| 125 |
+
|
| 126 |
+
References
|
| 127 |
+
----------
|
| 128 |
+
.. [1] Cytoscape user's manual:
|
| 129 |
+
http://manual.cytoscape.org/en/stable/index.html
|
| 130 |
+
|
| 131 |
+
Examples
|
| 132 |
+
--------
|
| 133 |
+
>>> data_dict = {
|
| 134 |
+
... "data": [],
|
| 135 |
+
... "directed": False,
|
| 136 |
+
... "multigraph": False,
|
| 137 |
+
... "elements": {
|
| 138 |
+
... "nodes": [
|
| 139 |
+
... {"data": {"id": "0", "value": 0, "name": "0"}},
|
| 140 |
+
... {"data": {"id": "1", "value": 1, "name": "1"}},
|
| 141 |
+
... ],
|
| 142 |
+
... "edges": [{"data": {"source": 0, "target": 1}}],
|
| 143 |
+
... },
|
| 144 |
+
... }
|
| 145 |
+
>>> G = nx.cytoscape_graph(data_dict)
|
| 146 |
+
>>> G.name
|
| 147 |
+
''
|
| 148 |
+
>>> G.nodes()
|
| 149 |
+
NodeView((0, 1))
|
| 150 |
+
>>> G.nodes(data=True)[0]
|
| 151 |
+
{'id': '0', 'value': 0, 'name': '0'}
|
| 152 |
+
>>> G.edges(data=True)
|
| 153 |
+
EdgeDataView([(0, 1, {'source': 0, 'target': 1})])
|
| 154 |
+
"""
|
| 155 |
+
if name == ident:
|
| 156 |
+
raise nx.NetworkXError("name and ident must be different.")
|
| 157 |
+
|
| 158 |
+
multigraph = data.get("multigraph")
|
| 159 |
+
directed = data.get("directed")
|
| 160 |
+
if multigraph:
|
| 161 |
+
graph = nx.MultiGraph()
|
| 162 |
+
else:
|
| 163 |
+
graph = nx.Graph()
|
| 164 |
+
if directed:
|
| 165 |
+
graph = graph.to_directed()
|
| 166 |
+
graph.graph = dict(data.get("data"))
|
| 167 |
+
for d in data["elements"]["nodes"]:
|
| 168 |
+
node_data = d["data"].copy()
|
| 169 |
+
node = d["data"]["value"]
|
| 170 |
+
|
| 171 |
+
if d["data"].get(name):
|
| 172 |
+
node_data[name] = d["data"].get(name)
|
| 173 |
+
if d["data"].get(ident):
|
| 174 |
+
node_data[ident] = d["data"].get(ident)
|
| 175 |
+
|
| 176 |
+
graph.add_node(node)
|
| 177 |
+
graph.nodes[node].update(node_data)
|
| 178 |
+
|
| 179 |
+
for d in data["elements"]["edges"]:
|
| 180 |
+
edge_data = d["data"].copy()
|
| 181 |
+
sour = d["data"]["source"]
|
| 182 |
+
targ = d["data"]["target"]
|
| 183 |
+
if multigraph:
|
| 184 |
+
key = d["data"].get("key", 0)
|
| 185 |
+
graph.add_edge(sour, targ, key=key)
|
| 186 |
+
graph.edges[sour, targ, key].update(edge_data)
|
| 187 |
+
else:
|
| 188 |
+
graph.add_edge(sour, targ)
|
| 189 |
+
graph.edges[sour, targ].update(edge_data)
|
| 190 |
+
return graph
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/node_link.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from itertools import count
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
__all__ = ["node_link_data", "node_link_graph"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _to_tuple(x):
|
| 10 |
+
"""Converts lists to tuples, including nested lists.
|
| 11 |
+
|
| 12 |
+
All other non-list inputs are passed through unmodified. This function is
|
| 13 |
+
intended to be used to convert potentially nested lists from json files
|
| 14 |
+
into valid nodes.
|
| 15 |
+
|
| 16 |
+
Examples
|
| 17 |
+
--------
|
| 18 |
+
>>> _to_tuple([1, 2, [3, 4]])
|
| 19 |
+
(1, 2, (3, 4))
|
| 20 |
+
"""
|
| 21 |
+
if not isinstance(x, tuple | list):
|
| 22 |
+
return x
|
| 23 |
+
return tuple(map(_to_tuple, x))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def node_link_data(
|
| 27 |
+
G,
|
| 28 |
+
*,
|
| 29 |
+
source="source",
|
| 30 |
+
target="target",
|
| 31 |
+
name="id",
|
| 32 |
+
key="key",
|
| 33 |
+
edges="edges",
|
| 34 |
+
nodes="nodes",
|
| 35 |
+
):
|
| 36 |
+
"""Returns data in node-link format that is suitable for JSON serialization
|
| 37 |
+
and use in JavaScript documents.
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
G : NetworkX graph
|
| 42 |
+
source : string
|
| 43 |
+
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
|
| 44 |
+
target : string
|
| 45 |
+
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
|
| 46 |
+
name : string
|
| 47 |
+
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
|
| 48 |
+
key : string
|
| 49 |
+
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
|
| 50 |
+
edges : string
|
| 51 |
+
A string that provides the 'edges' attribute name for storing NetworkX-internal graph data.
|
| 52 |
+
nodes : string
|
| 53 |
+
A string that provides the 'nodes' attribute name for storing NetworkX-internal graph data.
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
data : dict
|
| 58 |
+
A dictionary with node-link formatted data.
|
| 59 |
+
|
| 60 |
+
Raises
|
| 61 |
+
------
|
| 62 |
+
NetworkXError
|
| 63 |
+
If the values of 'source', 'target' and 'key' are not unique.
|
| 64 |
+
|
| 65 |
+
Examples
|
| 66 |
+
--------
|
| 67 |
+
>>> from pprint import pprint
|
| 68 |
+
>>> G = nx.Graph([("A", "B")])
|
| 69 |
+
>>> data1 = nx.node_link_data(G)
|
| 70 |
+
>>> pprint(data1)
|
| 71 |
+
{'directed': False,
|
| 72 |
+
'edges': [{'source': 'A', 'target': 'B'}],
|
| 73 |
+
'graph': {},
|
| 74 |
+
'multigraph': False,
|
| 75 |
+
'nodes': [{'id': 'A'}, {'id': 'B'}]}
|
| 76 |
+
|
| 77 |
+
To serialize with JSON
|
| 78 |
+
|
| 79 |
+
>>> import json
|
| 80 |
+
>>> s1 = json.dumps(data1)
|
| 81 |
+
>>> pprint(s1)
|
| 82 |
+
('{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, '
|
| 83 |
+
'{"id": "B"}], "edges": [{"source": "A", "target": "B"}]}')
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
A graph can also be serialized by passing `node_link_data` as an encoder function.
|
| 87 |
+
|
| 88 |
+
>>> s1 = json.dumps(G, default=nx.node_link_data)
|
| 89 |
+
>>> pprint(s1)
|
| 90 |
+
('{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, '
|
| 91 |
+
'{"id": "B"}], "edges": [{"source": "A", "target": "B"}]}')
|
| 92 |
+
|
| 93 |
+
The attribute names for storing NetworkX-internal graph data can
|
| 94 |
+
be specified as keyword options.
|
| 95 |
+
|
| 96 |
+
>>> H = nx.gn_graph(2)
|
| 97 |
+
>>> data2 = nx.node_link_data(
|
| 98 |
+
... H, edges="links", source="from", target="to", nodes="vertices"
|
| 99 |
+
... )
|
| 100 |
+
>>> pprint(data2)
|
| 101 |
+
{'directed': True,
|
| 102 |
+
'graph': {},
|
| 103 |
+
'links': [{'from': 1, 'to': 0}],
|
| 104 |
+
'multigraph': False,
|
| 105 |
+
'vertices': [{'id': 0}, {'id': 1}]}
|
| 106 |
+
|
| 107 |
+
Notes
|
| 108 |
+
-----
|
| 109 |
+
Graph, node, and edge attributes are stored in this format. Note that
|
| 110 |
+
attribute keys will be converted to strings in order to comply with JSON.
|
| 111 |
+
|
| 112 |
+
Attribute 'key' is only used for multigraphs.
|
| 113 |
+
|
| 114 |
+
To use `node_link_data` in conjunction with `node_link_graph`,
|
| 115 |
+
the keyword names for the attributes must match.
|
| 116 |
+
|
| 117 |
+
See Also
|
| 118 |
+
--------
|
| 119 |
+
node_link_graph, adjacency_data, tree_data
|
| 120 |
+
"""
|
| 121 |
+
multigraph = G.is_multigraph()
|
| 122 |
+
|
| 123 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
| 124 |
+
key = None if not multigraph else key
|
| 125 |
+
if len({source, target, key}) < 3:
|
| 126 |
+
raise nx.NetworkXError("Attribute names are not unique.")
|
| 127 |
+
data = {
|
| 128 |
+
"directed": G.is_directed(),
|
| 129 |
+
"multigraph": multigraph,
|
| 130 |
+
"graph": G.graph,
|
| 131 |
+
nodes: [{**G.nodes[n], name: n} for n in G],
|
| 132 |
+
}
|
| 133 |
+
if multigraph:
|
| 134 |
+
data[edges] = [
|
| 135 |
+
{**d, source: u, target: v, key: k}
|
| 136 |
+
for u, v, k, d in G.edges(keys=True, data=True)
|
| 137 |
+
]
|
| 138 |
+
else:
|
| 139 |
+
data[edges] = [{**d, source: u, target: v} for u, v, d in G.edges(data=True)]
|
| 140 |
+
return data
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 144 |
+
def node_link_graph(
|
| 145 |
+
data,
|
| 146 |
+
directed=False,
|
| 147 |
+
multigraph=True,
|
| 148 |
+
*,
|
| 149 |
+
source="source",
|
| 150 |
+
target="target",
|
| 151 |
+
name="id",
|
| 152 |
+
key="key",
|
| 153 |
+
edges="edges",
|
| 154 |
+
nodes="nodes",
|
| 155 |
+
):
|
| 156 |
+
"""Returns graph from node-link data format.
|
| 157 |
+
|
| 158 |
+
Useful for de-serialization from JSON.
|
| 159 |
+
|
| 160 |
+
Parameters
|
| 161 |
+
----------
|
| 162 |
+
data : dict
|
| 163 |
+
node-link formatted graph data
|
| 164 |
+
|
| 165 |
+
directed : bool
|
| 166 |
+
If True, and direction not specified in data, return a directed graph.
|
| 167 |
+
|
| 168 |
+
multigraph : bool
|
| 169 |
+
If True, and multigraph not specified in data, return a multigraph.
|
| 170 |
+
|
| 171 |
+
source : string
|
| 172 |
+
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
|
| 173 |
+
target : string
|
| 174 |
+
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
|
| 175 |
+
name : string
|
| 176 |
+
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
|
| 177 |
+
key : string
|
| 178 |
+
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
|
| 179 |
+
edges : string
|
| 180 |
+
A string that provides the 'edges' attribute name for storing NetworkX-internal graph data.
|
| 181 |
+
nodes : string
|
| 182 |
+
A string that provides the 'nodes' attribute name for storing NetworkX-internal graph data.
|
| 183 |
+
|
| 184 |
+
Returns
|
| 185 |
+
-------
|
| 186 |
+
G : NetworkX graph
|
| 187 |
+
A NetworkX graph object
|
| 188 |
+
|
| 189 |
+
Examples
|
| 190 |
+
--------
|
| 191 |
+
|
| 192 |
+
Create data in node-link format by converting a graph.
|
| 193 |
+
|
| 194 |
+
>>> from pprint import pprint
|
| 195 |
+
>>> G = nx.Graph([("A", "B")])
|
| 196 |
+
>>> data = nx.node_link_data(G)
|
| 197 |
+
>>> pprint(data)
|
| 198 |
+
{'directed': False,
|
| 199 |
+
'edges': [{'source': 'A', 'target': 'B'}],
|
| 200 |
+
'graph': {},
|
| 201 |
+
'multigraph': False,
|
| 202 |
+
'nodes': [{'id': 'A'}, {'id': 'B'}]}
|
| 203 |
+
|
| 204 |
+
Revert data in node-link format to a graph.
|
| 205 |
+
|
| 206 |
+
>>> H = nx.node_link_graph(data)
|
| 207 |
+
>>> print(H.edges)
|
| 208 |
+
[('A', 'B')]
|
| 209 |
+
|
| 210 |
+
To serialize and deserialize a graph with JSON,
|
| 211 |
+
|
| 212 |
+
>>> import json
|
| 213 |
+
>>> d = json.dumps(nx.node_link_data(G))
|
| 214 |
+
>>> H = nx.node_link_graph(json.loads(d))
|
| 215 |
+
>>> print(G.edges, H.edges)
|
| 216 |
+
[('A', 'B')] [('A', 'B')]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
Notes
|
| 220 |
+
-----
|
| 221 |
+
Attribute 'key' is only used for multigraphs.
|
| 222 |
+
|
| 223 |
+
To use `node_link_data` in conjunction with `node_link_graph`,
|
| 224 |
+
the keyword names for the attributes must match.
|
| 225 |
+
|
| 226 |
+
See Also
|
| 227 |
+
--------
|
| 228 |
+
node_link_data, adjacency_data, tree_data
|
| 229 |
+
"""
|
| 230 |
+
multigraph = data.get("multigraph", multigraph)
|
| 231 |
+
directed = data.get("directed", directed)
|
| 232 |
+
if multigraph:
|
| 233 |
+
graph = nx.MultiGraph()
|
| 234 |
+
else:
|
| 235 |
+
graph = nx.Graph()
|
| 236 |
+
if directed:
|
| 237 |
+
graph = graph.to_directed()
|
| 238 |
+
|
| 239 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
| 240 |
+
key = None if not multigraph else key
|
| 241 |
+
graph.graph = data.get("graph", {})
|
| 242 |
+
c = count()
|
| 243 |
+
for d in data[nodes]:
|
| 244 |
+
node = _to_tuple(d.get(name, next(c)))
|
| 245 |
+
nodedata = {str(k): v for k, v in d.items() if k != name}
|
| 246 |
+
graph.add_node(node, **nodedata)
|
| 247 |
+
for d in data[edges]:
|
| 248 |
+
src = tuple(d[source]) if isinstance(d[source], list) else d[source]
|
| 249 |
+
tgt = tuple(d[target]) if isinstance(d[target], list) else d[target]
|
| 250 |
+
if not multigraph:
|
| 251 |
+
edgedata = {str(k): v for k, v in d.items() if k != source and k != target}
|
| 252 |
+
graph.add_edge(src, tgt, **edgedata)
|
| 253 |
+
else:
|
| 254 |
+
ky = d.get(key, None)
|
| 255 |
+
edgedata = {
|
| 256 |
+
str(k): v
|
| 257 |
+
for k, v in d.items()
|
| 258 |
+
if k != source and k != target and k != key
|
| 259 |
+
}
|
| 260 |
+
graph.add_edge(src, tgt, ky, **edgedata)
|
| 261 |
+
return graph
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (210 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_adjacency.cpython-312.pyc
ADDED
|
Binary file (5.25 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_cytoscape.cpython-312.pyc
ADDED
|
Binary file (4.58 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_node_link.cpython-312.pyc
ADDED
|
Binary file (6.99 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__pycache__/test_tree.cpython-312.pyc
ADDED
|
Binary file (3.42 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_adjacency.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.readwrite.json_graph import adjacency_data, adjacency_graph
|
| 8 |
+
from networkx.utils import graphs_equal
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestAdjacency:
|
| 12 |
+
def test_graph(self):
|
| 13 |
+
G = nx.path_graph(4)
|
| 14 |
+
H = adjacency_graph(adjacency_data(G))
|
| 15 |
+
assert graphs_equal(G, H)
|
| 16 |
+
|
| 17 |
+
def test_graph_attributes(self):
|
| 18 |
+
G = nx.path_graph(4)
|
| 19 |
+
G.add_node(1, color="red")
|
| 20 |
+
G.add_edge(1, 2, width=7)
|
| 21 |
+
G.graph["foo"] = "bar"
|
| 22 |
+
G.graph[1] = "one"
|
| 23 |
+
|
| 24 |
+
H = adjacency_graph(adjacency_data(G))
|
| 25 |
+
assert graphs_equal(G, H)
|
| 26 |
+
assert H.graph["foo"] == "bar"
|
| 27 |
+
assert H.nodes[1]["color"] == "red"
|
| 28 |
+
assert H[1][2]["width"] == 7
|
| 29 |
+
|
| 30 |
+
d = json.dumps(adjacency_data(G))
|
| 31 |
+
H = adjacency_graph(json.loads(d))
|
| 32 |
+
assert graphs_equal(G, H)
|
| 33 |
+
assert H.graph["foo"] == "bar"
|
| 34 |
+
assert H.graph[1] == "one"
|
| 35 |
+
assert H.nodes[1]["color"] == "red"
|
| 36 |
+
assert H[1][2]["width"] == 7
|
| 37 |
+
|
| 38 |
+
def test_digraph(self):
|
| 39 |
+
G = nx.DiGraph()
|
| 40 |
+
nx.add_path(G, [1, 2, 3])
|
| 41 |
+
H = adjacency_graph(adjacency_data(G))
|
| 42 |
+
assert H.is_directed()
|
| 43 |
+
assert graphs_equal(G, H)
|
| 44 |
+
|
| 45 |
+
def test_multidigraph(self):
|
| 46 |
+
G = nx.MultiDiGraph()
|
| 47 |
+
nx.add_path(G, [1, 2, 3])
|
| 48 |
+
H = adjacency_graph(adjacency_data(G))
|
| 49 |
+
assert H.is_directed()
|
| 50 |
+
assert H.is_multigraph()
|
| 51 |
+
assert graphs_equal(G, H)
|
| 52 |
+
|
| 53 |
+
def test_multigraph(self):
|
| 54 |
+
G = nx.MultiGraph()
|
| 55 |
+
G.add_edge(1, 2, key="first")
|
| 56 |
+
G.add_edge(1, 2, key="second", color="blue")
|
| 57 |
+
H = adjacency_graph(adjacency_data(G))
|
| 58 |
+
assert graphs_equal(G, H)
|
| 59 |
+
assert H[1][2]["second"]["color"] == "blue"
|
| 60 |
+
|
| 61 |
+
def test_input_data_is_not_modified_when_building_graph(self):
|
| 62 |
+
G = nx.path_graph(4)
|
| 63 |
+
input_data = adjacency_data(G)
|
| 64 |
+
orig_data = copy.deepcopy(input_data)
|
| 65 |
+
# Ensure input is unmodified by deserialisation
|
| 66 |
+
assert graphs_equal(G, adjacency_graph(input_data))
|
| 67 |
+
assert input_data == orig_data
|
| 68 |
+
|
| 69 |
+
def test_adjacency_form_json_serialisable(self):
|
| 70 |
+
G = nx.path_graph(4)
|
| 71 |
+
H = adjacency_graph(json.loads(json.dumps(adjacency_data(G))))
|
| 72 |
+
assert graphs_equal(G, H)
|
| 73 |
+
|
| 74 |
+
def test_exception(self):
|
| 75 |
+
with pytest.raises(nx.NetworkXError):
|
| 76 |
+
G = nx.MultiDiGraph()
|
| 77 |
+
attrs = {"id": "node", "key": "node"}
|
| 78 |
+
adjacency_data(G, attrs)
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_cytoscape.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.readwrite.json_graph import cytoscape_data, cytoscape_graph
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_graph():
|
| 11 |
+
G = nx.path_graph(4)
|
| 12 |
+
H = cytoscape_graph(cytoscape_data(G))
|
| 13 |
+
assert nx.is_isomorphic(G, H)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_input_data_is_not_modified_when_building_graph():
|
| 17 |
+
G = nx.path_graph(4)
|
| 18 |
+
input_data = cytoscape_data(G)
|
| 19 |
+
orig_data = copy.deepcopy(input_data)
|
| 20 |
+
# Ensure input is unmodified by cytoscape_graph (gh-4173)
|
| 21 |
+
cytoscape_graph(input_data)
|
| 22 |
+
assert input_data == orig_data
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_graph_attributes():
|
| 26 |
+
G = nx.path_graph(4)
|
| 27 |
+
G.add_node(1, color="red")
|
| 28 |
+
G.add_edge(1, 2, width=7)
|
| 29 |
+
G.graph["foo"] = "bar"
|
| 30 |
+
G.graph[1] = "one"
|
| 31 |
+
G.add_node(3, name="node", id="123")
|
| 32 |
+
|
| 33 |
+
H = cytoscape_graph(cytoscape_data(G))
|
| 34 |
+
assert H.graph["foo"] == "bar"
|
| 35 |
+
assert H.nodes[1]["color"] == "red"
|
| 36 |
+
assert H[1][2]["width"] == 7
|
| 37 |
+
assert H.nodes[3]["name"] == "node"
|
| 38 |
+
assert H.nodes[3]["id"] == "123"
|
| 39 |
+
|
| 40 |
+
d = json.dumps(cytoscape_data(G))
|
| 41 |
+
H = cytoscape_graph(json.loads(d))
|
| 42 |
+
assert H.graph["foo"] == "bar"
|
| 43 |
+
assert H.graph[1] == "one"
|
| 44 |
+
assert H.nodes[1]["color"] == "red"
|
| 45 |
+
assert H[1][2]["width"] == 7
|
| 46 |
+
assert H.nodes[3]["name"] == "node"
|
| 47 |
+
assert H.nodes[3]["id"] == "123"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_digraph():
|
| 51 |
+
G = nx.DiGraph()
|
| 52 |
+
nx.add_path(G, [1, 2, 3])
|
| 53 |
+
H = cytoscape_graph(cytoscape_data(G))
|
| 54 |
+
assert H.is_directed()
|
| 55 |
+
assert nx.is_isomorphic(G, H)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_multidigraph():
|
| 59 |
+
G = nx.MultiDiGraph()
|
| 60 |
+
nx.add_path(G, [1, 2, 3])
|
| 61 |
+
H = cytoscape_graph(cytoscape_data(G))
|
| 62 |
+
assert H.is_directed()
|
| 63 |
+
assert H.is_multigraph()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_multigraph():
|
| 67 |
+
G = nx.MultiGraph()
|
| 68 |
+
G.add_edge(1, 2, key="first")
|
| 69 |
+
G.add_edge(1, 2, key="second", color="blue")
|
| 70 |
+
H = cytoscape_graph(cytoscape_data(G))
|
| 71 |
+
assert nx.is_isomorphic(G, H)
|
| 72 |
+
assert H[1][2]["second"]["color"] == "blue"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_exception():
|
| 76 |
+
with pytest.raises(nx.NetworkXError):
|
| 77 |
+
G = nx.MultiDiGraph()
|
| 78 |
+
cytoscape_data(G, name="foo", ident="foo")
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_node_link.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.readwrite.json_graph import node_link_data, node_link_graph
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestNodeLink:
|
| 10 |
+
def test_exception_dep(self):
|
| 11 |
+
G = nx.MultiDiGraph()
|
| 12 |
+
with pytest.raises(nx.NetworkXError):
|
| 13 |
+
node_link_data(G, name="node", source="node", target="node", key="node")
|
| 14 |
+
|
| 15 |
+
def test_graph(self):
|
| 16 |
+
G = nx.path_graph(4)
|
| 17 |
+
H = node_link_graph(node_link_data(G))
|
| 18 |
+
assert nx.is_isomorphic(G, H)
|
| 19 |
+
|
| 20 |
+
def test_graph_attributes(self):
|
| 21 |
+
G = nx.path_graph(4)
|
| 22 |
+
G.add_node(1, color="red")
|
| 23 |
+
G.add_edge(1, 2, width=7)
|
| 24 |
+
G.graph[1] = "one"
|
| 25 |
+
G.graph["foo"] = "bar"
|
| 26 |
+
|
| 27 |
+
H = node_link_graph(node_link_data(G))
|
| 28 |
+
assert H.graph["foo"] == "bar"
|
| 29 |
+
assert H.nodes[1]["color"] == "red"
|
| 30 |
+
assert H[1][2]["width"] == 7
|
| 31 |
+
|
| 32 |
+
d = json.dumps(node_link_data(G))
|
| 33 |
+
H = node_link_graph(json.loads(d))
|
| 34 |
+
assert H.graph["foo"] == "bar"
|
| 35 |
+
assert H.graph["1"] == "one"
|
| 36 |
+
assert H.nodes[1]["color"] == "red"
|
| 37 |
+
assert H[1][2]["width"] == 7
|
| 38 |
+
|
| 39 |
+
def test_digraph(self):
|
| 40 |
+
G = nx.DiGraph()
|
| 41 |
+
H = node_link_graph(node_link_data(G))
|
| 42 |
+
assert H.is_directed()
|
| 43 |
+
|
| 44 |
+
def test_multigraph(self):
|
| 45 |
+
G = nx.MultiGraph()
|
| 46 |
+
G.add_edge(1, 2, key="first")
|
| 47 |
+
G.add_edge(1, 2, key="second", color="blue")
|
| 48 |
+
H = node_link_graph(node_link_data(G))
|
| 49 |
+
assert nx.is_isomorphic(G, H)
|
| 50 |
+
assert H[1][2]["second"]["color"] == "blue"
|
| 51 |
+
|
| 52 |
+
def test_graph_with_tuple_nodes(self):
|
| 53 |
+
G = nx.Graph()
|
| 54 |
+
G.add_edge((0, 0), (1, 0), color=[255, 255, 0])
|
| 55 |
+
d = node_link_data(G)
|
| 56 |
+
dumped_d = json.dumps(d)
|
| 57 |
+
dd = json.loads(dumped_d)
|
| 58 |
+
H = node_link_graph(dd)
|
| 59 |
+
assert H.nodes[(0, 0)] == G.nodes[(0, 0)]
|
| 60 |
+
assert H[(0, 0)][(1, 0)]["color"] == [255, 255, 0]
|
| 61 |
+
|
| 62 |
+
def test_unicode_keys(self):
|
| 63 |
+
q = "qualité"
|
| 64 |
+
G = nx.Graph()
|
| 65 |
+
G.add_node(1, **{q: q})
|
| 66 |
+
s = node_link_data(G)
|
| 67 |
+
output = json.dumps(s, ensure_ascii=False)
|
| 68 |
+
data = json.loads(output)
|
| 69 |
+
H = node_link_graph(data)
|
| 70 |
+
assert H.nodes[1][q] == q
|
| 71 |
+
|
| 72 |
+
def test_exception(self):
|
| 73 |
+
G = nx.MultiDiGraph()
|
| 74 |
+
attrs = {"name": "node", "source": "node", "target": "node", "key": "node"}
|
| 75 |
+
with pytest.raises(nx.NetworkXError):
|
| 76 |
+
node_link_data(G, **attrs)
|
| 77 |
+
|
| 78 |
+
def test_string_ids(self):
|
| 79 |
+
q = "qualité"
|
| 80 |
+
G = nx.DiGraph()
|
| 81 |
+
G.add_node("A")
|
| 82 |
+
G.add_node(q)
|
| 83 |
+
G.add_edge("A", q)
|
| 84 |
+
data = node_link_data(G)
|
| 85 |
+
assert data["edges"][0]["source"] == "A"
|
| 86 |
+
assert data["edges"][0]["target"] == q
|
| 87 |
+
H = node_link_graph(data)
|
| 88 |
+
assert nx.is_isomorphic(G, H)
|
| 89 |
+
|
| 90 |
+
def test_custom_attrs(self):
|
| 91 |
+
G = nx.path_graph(4)
|
| 92 |
+
G.add_node(1, color="red")
|
| 93 |
+
G.add_edge(1, 2, width=7)
|
| 94 |
+
G.graph[1] = "one"
|
| 95 |
+
G.graph["foo"] = "bar"
|
| 96 |
+
|
| 97 |
+
attrs = {
|
| 98 |
+
"source": "c_source",
|
| 99 |
+
"target": "c_target",
|
| 100 |
+
"name": "c_id",
|
| 101 |
+
"key": "c_key",
|
| 102 |
+
"edges": "c_links",
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
H = node_link_graph(node_link_data(G, **attrs), multigraph=False, **attrs)
|
| 106 |
+
assert nx.is_isomorphic(G, H)
|
| 107 |
+
assert H.graph["foo"] == "bar"
|
| 108 |
+
assert H.nodes[1]["color"] == "red"
|
| 109 |
+
assert H[1][2]["width"] == 7
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_tree.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.readwrite.json_graph import tree_data, tree_graph
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_graph():
|
| 10 |
+
G = nx.DiGraph()
|
| 11 |
+
G.add_nodes_from([1, 2, 3], color="red")
|
| 12 |
+
G.add_edge(1, 2, foo=7)
|
| 13 |
+
G.add_edge(1, 3, foo=10)
|
| 14 |
+
G.add_edge(3, 4, foo=10)
|
| 15 |
+
H = tree_graph(tree_data(G, 1))
|
| 16 |
+
assert nx.is_isomorphic(G, H)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_graph_attributes():
|
| 20 |
+
G = nx.DiGraph()
|
| 21 |
+
G.add_nodes_from([1, 2, 3], color="red")
|
| 22 |
+
G.add_edge(1, 2, foo=7)
|
| 23 |
+
G.add_edge(1, 3, foo=10)
|
| 24 |
+
G.add_edge(3, 4, foo=10)
|
| 25 |
+
H = tree_graph(tree_data(G, 1))
|
| 26 |
+
assert H.nodes[1]["color"] == "red"
|
| 27 |
+
|
| 28 |
+
d = json.dumps(tree_data(G, 1))
|
| 29 |
+
H = tree_graph(json.loads(d))
|
| 30 |
+
assert H.nodes[1]["color"] == "red"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_exceptions():
|
| 34 |
+
with pytest.raises(TypeError, match="is not a tree."):
|
| 35 |
+
G = nx.complete_graph(3)
|
| 36 |
+
tree_data(G, 0)
|
| 37 |
+
with pytest.raises(TypeError, match="is not directed."):
|
| 38 |
+
G = nx.path_graph(3)
|
| 39 |
+
tree_data(G, 0)
|
| 40 |
+
with pytest.raises(TypeError, match="is not weakly connected."):
|
| 41 |
+
G = nx.path_graph(3, create_using=nx.DiGraph)
|
| 42 |
+
G.add_edge(2, 0)
|
| 43 |
+
G.add_node(3)
|
| 44 |
+
tree_data(G, 0)
|
| 45 |
+
with pytest.raises(nx.NetworkXError, match="must be different."):
|
| 46 |
+
G = nx.MultiDiGraph()
|
| 47 |
+
G.add_node(0)
|
| 48 |
+
tree_data(G, 0, ident="node", children="node")
|
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tree.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import chain
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["tree_data", "tree_graph"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def tree_data(G, root, ident="id", children="children"):
|
| 9 |
+
"""Returns data in tree format that is suitable for JSON serialization
|
| 10 |
+
and use in JavaScript documents.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
G : NetworkX graph
|
| 15 |
+
G must be an oriented tree
|
| 16 |
+
|
| 17 |
+
root : node
|
| 18 |
+
The root of the tree
|
| 19 |
+
|
| 20 |
+
ident : string
|
| 21 |
+
Attribute name for storing NetworkX-internal graph data. `ident` must
|
| 22 |
+
have a different value than `children`. The default is 'id'.
|
| 23 |
+
|
| 24 |
+
children : string
|
| 25 |
+
Attribute name for storing NetworkX-internal graph data. `children`
|
| 26 |
+
must have a different value than `ident`. The default is 'children'.
|
| 27 |
+
|
| 28 |
+
Returns
|
| 29 |
+
-------
|
| 30 |
+
data : dict
|
| 31 |
+
A dictionary with node-link formatted data.
|
| 32 |
+
|
| 33 |
+
Raises
|
| 34 |
+
------
|
| 35 |
+
NetworkXError
|
| 36 |
+
If `children` and `ident` attributes are identical.
|
| 37 |
+
|
| 38 |
+
Examples
|
| 39 |
+
--------
|
| 40 |
+
>>> from networkx.readwrite import json_graph
|
| 41 |
+
>>> G = nx.DiGraph([(1, 2)])
|
| 42 |
+
>>> data = json_graph.tree_data(G, root=1)
|
| 43 |
+
|
| 44 |
+
To serialize with json
|
| 45 |
+
|
| 46 |
+
>>> import json
|
| 47 |
+
>>> s = json.dumps(data)
|
| 48 |
+
|
| 49 |
+
Notes
|
| 50 |
+
-----
|
| 51 |
+
Node attributes are stored in this format but keys
|
| 52 |
+
for attributes must be strings if you want to serialize with JSON.
|
| 53 |
+
|
| 54 |
+
Graph and edge attributes are not stored.
|
| 55 |
+
|
| 56 |
+
See Also
|
| 57 |
+
--------
|
| 58 |
+
tree_graph, node_link_data, adjacency_data
|
| 59 |
+
"""
|
| 60 |
+
if G.number_of_nodes() != G.number_of_edges() + 1:
|
| 61 |
+
raise TypeError("G is not a tree.")
|
| 62 |
+
if not G.is_directed():
|
| 63 |
+
raise TypeError("G is not directed.")
|
| 64 |
+
if not nx.is_weakly_connected(G):
|
| 65 |
+
raise TypeError("G is not weakly connected.")
|
| 66 |
+
|
| 67 |
+
if ident == children:
|
| 68 |
+
raise nx.NetworkXError("The values for `id` and `children` must be different.")
|
| 69 |
+
|
| 70 |
+
def add_children(n, G):
|
| 71 |
+
nbrs = G[n]
|
| 72 |
+
if len(nbrs) == 0:
|
| 73 |
+
return []
|
| 74 |
+
children_ = []
|
| 75 |
+
for child in nbrs:
|
| 76 |
+
d = {**G.nodes[child], ident: child}
|
| 77 |
+
c = add_children(child, G)
|
| 78 |
+
if c:
|
| 79 |
+
d[children] = c
|
| 80 |
+
children_.append(d)
|
| 81 |
+
return children_
|
| 82 |
+
|
| 83 |
+
return {**G.nodes[root], ident: root, children: add_children(root, G)}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 87 |
+
def tree_graph(data, ident="id", children="children"):
|
| 88 |
+
"""Returns graph from tree data format.
|
| 89 |
+
|
| 90 |
+
Parameters
|
| 91 |
+
----------
|
| 92 |
+
data : dict
|
| 93 |
+
Tree formatted graph data
|
| 94 |
+
|
| 95 |
+
ident : string
|
| 96 |
+
Attribute name for storing NetworkX-internal graph data. `ident` must
|
| 97 |
+
have a different value than `children`. The default is 'id'.
|
| 98 |
+
|
| 99 |
+
children : string
|
| 100 |
+
Attribute name for storing NetworkX-internal graph data. `children`
|
| 101 |
+
must have a different value than `ident`. The default is 'children'.
|
| 102 |
+
|
| 103 |
+
Returns
|
| 104 |
+
-------
|
| 105 |
+
G : NetworkX DiGraph
|
| 106 |
+
|
| 107 |
+
Examples
|
| 108 |
+
--------
|
| 109 |
+
>>> from networkx.readwrite import json_graph
|
| 110 |
+
>>> G = nx.DiGraph([(1, 2)])
|
| 111 |
+
>>> data = json_graph.tree_data(G, root=1)
|
| 112 |
+
>>> H = json_graph.tree_graph(data)
|
| 113 |
+
|
| 114 |
+
See Also
|
| 115 |
+
--------
|
| 116 |
+
tree_data, node_link_data, adjacency_data
|
| 117 |
+
"""
|
| 118 |
+
graph = nx.DiGraph()
|
| 119 |
+
|
| 120 |
+
def add_children(parent, children_):
|
| 121 |
+
for data in children_:
|
| 122 |
+
child = data[ident]
|
| 123 |
+
graph.add_edge(parent, child)
|
| 124 |
+
grandchildren = data.get(children, [])
|
| 125 |
+
if grandchildren:
|
| 126 |
+
add_children(child, grandchildren)
|
| 127 |
+
nodedata = {
|
| 128 |
+
str(k): v for k, v in data.items() if k != ident and k != children
|
| 129 |
+
}
|
| 130 |
+
graph.add_node(child, **nodedata)
|
| 131 |
+
|
| 132 |
+
root = data[ident]
|
| 133 |
+
children_ = data.get(children, [])
|
| 134 |
+
nodedata = {str(k): v for k, v in data.items() if k != ident and k != children}
|
| 135 |
+
graph.add_node(root, **nodedata)
|
| 136 |
+
add_children(root, children_)
|
| 137 |
+
return graph
|
.venv/lib/python3.12/site-packages/networkx/readwrite/leda.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Read graphs in LEDA format.
|
| 3 |
+
|
| 4 |
+
LEDA is a C++ class library for efficient data types and algorithms.
|
| 5 |
+
|
| 6 |
+
Format
|
| 7 |
+
------
|
| 8 |
+
See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
# Original author: D. Eppstein, UC Irvine, August 12, 2003.
|
| 12 |
+
# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
|
| 13 |
+
|
| 14 |
+
__all__ = ["read_leda", "parse_leda"]
|
| 15 |
+
|
| 16 |
+
import networkx as nx
|
| 17 |
+
from networkx.exception import NetworkXError
|
| 18 |
+
from networkx.utils import open_file
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@open_file(0, mode="rb")
|
| 22 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 23 |
+
def read_leda(path, encoding="UTF-8"):
|
| 24 |
+
"""Read graph in LEDA format from path.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
path : file or string
|
| 29 |
+
Filename or file handle to read.
|
| 30 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
G : NetworkX graph
|
| 35 |
+
|
| 36 |
+
Examples
|
| 37 |
+
--------
|
| 38 |
+
>>> G = nx.read_leda("file.leda") # doctest: +SKIP
|
| 39 |
+
|
| 40 |
+
References
|
| 41 |
+
----------
|
| 42 |
+
.. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
|
| 43 |
+
"""
|
| 44 |
+
lines = (line.decode(encoding) for line in path)
|
| 45 |
+
G = parse_leda(lines)
|
| 46 |
+
return G
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 50 |
+
def parse_leda(lines):
|
| 51 |
+
"""Read graph in LEDA format from string or iterable.
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
lines : string or iterable
|
| 56 |
+
Data in LEDA format.
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
G : NetworkX graph
|
| 61 |
+
|
| 62 |
+
Examples
|
| 63 |
+
--------
|
| 64 |
+
>>> G = nx.parse_leda(string) # doctest: +SKIP
|
| 65 |
+
|
| 66 |
+
References
|
| 67 |
+
----------
|
| 68 |
+
.. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
|
| 69 |
+
"""
|
| 70 |
+
if isinstance(lines, str):
|
| 71 |
+
lines = iter(lines.split("\n"))
|
| 72 |
+
lines = iter(
|
| 73 |
+
[
|
| 74 |
+
line.rstrip("\n")
|
| 75 |
+
for line in lines
|
| 76 |
+
if not (line.startswith(("#", "\n")) or line == "")
|
| 77 |
+
]
|
| 78 |
+
)
|
| 79 |
+
for i in range(3):
|
| 80 |
+
next(lines)
|
| 81 |
+
# Graph
|
| 82 |
+
du = int(next(lines)) # -1=directed, -2=undirected
|
| 83 |
+
if du == -1:
|
| 84 |
+
G = nx.DiGraph()
|
| 85 |
+
else:
|
| 86 |
+
G = nx.Graph()
|
| 87 |
+
|
| 88 |
+
# Nodes
|
| 89 |
+
n = int(next(lines)) # number of nodes
|
| 90 |
+
node = {}
|
| 91 |
+
for i in range(1, n + 1): # LEDA counts from 1 to n
|
| 92 |
+
symbol = next(lines).rstrip().strip("|{}| ")
|
| 93 |
+
if symbol == "":
|
| 94 |
+
symbol = str(i) # use int if no label - could be trouble
|
| 95 |
+
node[i] = symbol
|
| 96 |
+
|
| 97 |
+
G.add_nodes_from([s for i, s in node.items()])
|
| 98 |
+
|
| 99 |
+
# Edges
|
| 100 |
+
m = int(next(lines)) # number of edges
|
| 101 |
+
for i in range(m):
|
| 102 |
+
try:
|
| 103 |
+
s, t, reversal, label = next(lines).split()
|
| 104 |
+
except BaseException as err:
|
| 105 |
+
raise NetworkXError(f"Too few fields in LEDA.GRAPH edge {i + 1}") from err
|
| 106 |
+
# BEWARE: no handling of reversal edges
|
| 107 |
+
G.add_edge(node[int(s)], node[int(t)], label=label[2:-2])
|
| 108 |
+
return G
|
.venv/lib/python3.12/site-packages/networkx/readwrite/multiline_adjlist.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
*************************
|
| 3 |
+
Multi-line Adjacency List
|
| 4 |
+
*************************
|
| 5 |
+
Read and write NetworkX graphs as multi-line adjacency lists.
|
| 6 |
+
|
| 7 |
+
The multi-line adjacency list format is useful for graphs with
|
| 8 |
+
nodes that can be meaningfully represented as strings. With this format
|
| 9 |
+
simple edge data can be stored but node or graph data is not.
|
| 10 |
+
|
| 11 |
+
Format
|
| 12 |
+
------
|
| 13 |
+
The first label in a line is the source node label followed by the node degree
|
| 14 |
+
d. The next d lines are target node labels and optional edge data.
|
| 15 |
+
That pattern repeats for all nodes in the graph.
|
| 16 |
+
|
| 17 |
+
The graph with edges a-b, a-c, d-e can be represented as the following
|
| 18 |
+
adjacency list (anything following the # in a line is a comment)::
|
| 19 |
+
|
| 20 |
+
# example.multiline-adjlist
|
| 21 |
+
a 2
|
| 22 |
+
b
|
| 23 |
+
c
|
| 24 |
+
d 1
|
| 25 |
+
e
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
__all__ = [
|
| 29 |
+
"generate_multiline_adjlist",
|
| 30 |
+
"write_multiline_adjlist",
|
| 31 |
+
"parse_multiline_adjlist",
|
| 32 |
+
"read_multiline_adjlist",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
import networkx as nx
|
| 36 |
+
from networkx.utils import open_file
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def generate_multiline_adjlist(G, delimiter=" "):
|
| 40 |
+
"""Generate a single line of the graph G in multiline adjacency list format.
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
G : NetworkX graph
|
| 45 |
+
|
| 46 |
+
delimiter : string, optional
|
| 47 |
+
Separator for node labels
|
| 48 |
+
|
| 49 |
+
Returns
|
| 50 |
+
-------
|
| 51 |
+
lines : string
|
| 52 |
+
Lines of data in multiline adjlist format.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
--------
|
| 56 |
+
>>> G = nx.lollipop_graph(4, 3)
|
| 57 |
+
>>> for line in nx.generate_multiline_adjlist(G):
|
| 58 |
+
... print(line)
|
| 59 |
+
0 3
|
| 60 |
+
1 {}
|
| 61 |
+
2 {}
|
| 62 |
+
3 {}
|
| 63 |
+
1 2
|
| 64 |
+
2 {}
|
| 65 |
+
3 {}
|
| 66 |
+
2 1
|
| 67 |
+
3 {}
|
| 68 |
+
3 1
|
| 69 |
+
4 {}
|
| 70 |
+
4 1
|
| 71 |
+
5 {}
|
| 72 |
+
5 1
|
| 73 |
+
6 {}
|
| 74 |
+
6 0
|
| 75 |
+
|
| 76 |
+
See Also
|
| 77 |
+
--------
|
| 78 |
+
write_multiline_adjlist, read_multiline_adjlist
|
| 79 |
+
"""
|
| 80 |
+
if G.is_directed():
|
| 81 |
+
if G.is_multigraph():
|
| 82 |
+
for s, nbrs in G.adjacency():
|
| 83 |
+
nbr_edges = [
|
| 84 |
+
(u, data)
|
| 85 |
+
for u, datadict in nbrs.items()
|
| 86 |
+
for key, data in datadict.items()
|
| 87 |
+
]
|
| 88 |
+
deg = len(nbr_edges)
|
| 89 |
+
yield str(s) + delimiter + str(deg)
|
| 90 |
+
for u, d in nbr_edges:
|
| 91 |
+
if d is None:
|
| 92 |
+
yield str(u)
|
| 93 |
+
else:
|
| 94 |
+
yield str(u) + delimiter + str(d)
|
| 95 |
+
else: # directed single edges
|
| 96 |
+
for s, nbrs in G.adjacency():
|
| 97 |
+
deg = len(nbrs)
|
| 98 |
+
yield str(s) + delimiter + str(deg)
|
| 99 |
+
for u, d in nbrs.items():
|
| 100 |
+
if d is None:
|
| 101 |
+
yield str(u)
|
| 102 |
+
else:
|
| 103 |
+
yield str(u) + delimiter + str(d)
|
| 104 |
+
else: # undirected
|
| 105 |
+
if G.is_multigraph():
|
| 106 |
+
seen = set() # helper dict used to avoid duplicate edges
|
| 107 |
+
for s, nbrs in G.adjacency():
|
| 108 |
+
nbr_edges = [
|
| 109 |
+
(u, data)
|
| 110 |
+
for u, datadict in nbrs.items()
|
| 111 |
+
if u not in seen
|
| 112 |
+
for key, data in datadict.items()
|
| 113 |
+
]
|
| 114 |
+
deg = len(nbr_edges)
|
| 115 |
+
yield str(s) + delimiter + str(deg)
|
| 116 |
+
for u, d in nbr_edges:
|
| 117 |
+
if d is None:
|
| 118 |
+
yield str(u)
|
| 119 |
+
else:
|
| 120 |
+
yield str(u) + delimiter + str(d)
|
| 121 |
+
seen.add(s)
|
| 122 |
+
else: # undirected single edges
|
| 123 |
+
seen = set() # helper dict used to avoid duplicate edges
|
| 124 |
+
for s, nbrs in G.adjacency():
|
| 125 |
+
nbr_edges = [(u, d) for u, d in nbrs.items() if u not in seen]
|
| 126 |
+
deg = len(nbr_edges)
|
| 127 |
+
yield str(s) + delimiter + str(deg)
|
| 128 |
+
for u, d in nbr_edges:
|
| 129 |
+
if d is None:
|
| 130 |
+
yield str(u)
|
| 131 |
+
else:
|
| 132 |
+
yield str(u) + delimiter + str(d)
|
| 133 |
+
seen.add(s)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@open_file(1, mode="wb")
|
| 137 |
+
def write_multiline_adjlist(G, path, delimiter=" ", comments="#", encoding="utf-8"):
|
| 138 |
+
"""Write the graph G in multiline adjacency list format to path
|
| 139 |
+
|
| 140 |
+
Parameters
|
| 141 |
+
----------
|
| 142 |
+
G : NetworkX graph
|
| 143 |
+
|
| 144 |
+
path : string or file
|
| 145 |
+
Filename or file handle to write to.
|
| 146 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 147 |
+
|
| 148 |
+
comments : string, optional
|
| 149 |
+
Marker for comment lines
|
| 150 |
+
|
| 151 |
+
delimiter : string, optional
|
| 152 |
+
Separator for node labels
|
| 153 |
+
|
| 154 |
+
encoding : string, optional
|
| 155 |
+
Text encoding.
|
| 156 |
+
|
| 157 |
+
Examples
|
| 158 |
+
--------
|
| 159 |
+
>>> G = nx.path_graph(4)
|
| 160 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlist")
|
| 161 |
+
|
| 162 |
+
The path can be a file handle or a string with the name of the file. If a
|
| 163 |
+
file handle is provided, it has to be opened in 'wb' mode.
|
| 164 |
+
|
| 165 |
+
>>> fh = open("test.multi_adjlist2", "wb")
|
| 166 |
+
>>> nx.write_multiline_adjlist(G, fh)
|
| 167 |
+
|
| 168 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 169 |
+
|
| 170 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlist.gz")
|
| 171 |
+
|
| 172 |
+
See Also
|
| 173 |
+
--------
|
| 174 |
+
read_multiline_adjlist
|
| 175 |
+
"""
|
| 176 |
+
import sys
|
| 177 |
+
import time
|
| 178 |
+
|
| 179 |
+
pargs = comments + " ".join(sys.argv)
|
| 180 |
+
header = (
|
| 181 |
+
f"{pargs}\n"
|
| 182 |
+
+ comments
|
| 183 |
+
+ f" GMT {time.asctime(time.gmtime())}\n"
|
| 184 |
+
+ comments
|
| 185 |
+
+ f" {G.name}\n"
|
| 186 |
+
)
|
| 187 |
+
path.write(header.encode(encoding))
|
| 188 |
+
|
| 189 |
+
for multiline in generate_multiline_adjlist(G, delimiter):
|
| 190 |
+
multiline += "\n"
|
| 191 |
+
path.write(multiline.encode(encoding))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 195 |
+
def parse_multiline_adjlist(
|
| 196 |
+
lines, comments="#", delimiter=None, create_using=None, nodetype=None, edgetype=None
|
| 197 |
+
):
|
| 198 |
+
"""Parse lines of a multiline adjacency list representation of a graph.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
lines : list or iterator of strings
|
| 203 |
+
Input data in multiline adjlist format
|
| 204 |
+
|
| 205 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 206 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 207 |
+
|
| 208 |
+
nodetype : Python type, optional
|
| 209 |
+
Convert nodes to this type.
|
| 210 |
+
|
| 211 |
+
edgetype : Python type, optional
|
| 212 |
+
Convert edges to this type.
|
| 213 |
+
|
| 214 |
+
comments : string, optional
|
| 215 |
+
Marker for comment lines
|
| 216 |
+
|
| 217 |
+
delimiter : string, optional
|
| 218 |
+
Separator for node labels. The default is whitespace.
|
| 219 |
+
|
| 220 |
+
Returns
|
| 221 |
+
-------
|
| 222 |
+
G: NetworkX graph
|
| 223 |
+
The graph corresponding to the lines in multiline adjacency list format.
|
| 224 |
+
|
| 225 |
+
Examples
|
| 226 |
+
--------
|
| 227 |
+
>>> lines = [
|
| 228 |
+
... "1 2",
|
| 229 |
+
... "2 {'weight':3, 'name': 'Frodo'}",
|
| 230 |
+
... "3 {}",
|
| 231 |
+
... "2 1",
|
| 232 |
+
... "5 {'weight':6, 'name': 'Saruman'}",
|
| 233 |
+
... ]
|
| 234 |
+
>>> G = nx.parse_multiline_adjlist(iter(lines), nodetype=int)
|
| 235 |
+
>>> list(G)
|
| 236 |
+
[1, 2, 3, 5]
|
| 237 |
+
|
| 238 |
+
"""
|
| 239 |
+
from ast import literal_eval
|
| 240 |
+
|
| 241 |
+
G = nx.empty_graph(0, create_using)
|
| 242 |
+
for line in lines:
|
| 243 |
+
p = line.find(comments)
|
| 244 |
+
if p >= 0:
|
| 245 |
+
line = line[:p]
|
| 246 |
+
if not line:
|
| 247 |
+
continue
|
| 248 |
+
try:
|
| 249 |
+
(u, deg) = line.rstrip("\n").split(delimiter)
|
| 250 |
+
deg = int(deg)
|
| 251 |
+
except BaseException as err:
|
| 252 |
+
raise TypeError(f"Failed to read node and degree on line ({line})") from err
|
| 253 |
+
if nodetype is not None:
|
| 254 |
+
try:
|
| 255 |
+
u = nodetype(u)
|
| 256 |
+
except BaseException as err:
|
| 257 |
+
raise TypeError(
|
| 258 |
+
f"Failed to convert node ({u}) to type {nodetype}"
|
| 259 |
+
) from err
|
| 260 |
+
G.add_node(u)
|
| 261 |
+
for i in range(deg):
|
| 262 |
+
while True:
|
| 263 |
+
try:
|
| 264 |
+
line = next(lines)
|
| 265 |
+
except StopIteration as err:
|
| 266 |
+
msg = f"Failed to find neighbor for node ({u})"
|
| 267 |
+
raise TypeError(msg) from err
|
| 268 |
+
p = line.find(comments)
|
| 269 |
+
if p >= 0:
|
| 270 |
+
line = line[:p]
|
| 271 |
+
if line:
|
| 272 |
+
break
|
| 273 |
+
vlist = line.rstrip("\n").split(delimiter)
|
| 274 |
+
numb = len(vlist)
|
| 275 |
+
if numb < 1:
|
| 276 |
+
continue # isolated node
|
| 277 |
+
v = vlist.pop(0)
|
| 278 |
+
data = "".join(vlist)
|
| 279 |
+
if nodetype is not None:
|
| 280 |
+
try:
|
| 281 |
+
v = nodetype(v)
|
| 282 |
+
except BaseException as err:
|
| 283 |
+
raise TypeError(
|
| 284 |
+
f"Failed to convert node ({v}) to type {nodetype}"
|
| 285 |
+
) from err
|
| 286 |
+
if edgetype is not None:
|
| 287 |
+
try:
|
| 288 |
+
edgedata = {"weight": edgetype(data)}
|
| 289 |
+
except BaseException as err:
|
| 290 |
+
raise TypeError(
|
| 291 |
+
f"Failed to convert edge data ({data}) to type {edgetype}"
|
| 292 |
+
) from err
|
| 293 |
+
else:
|
| 294 |
+
try: # try to evaluate
|
| 295 |
+
edgedata = literal_eval(data)
|
| 296 |
+
except:
|
| 297 |
+
edgedata = {}
|
| 298 |
+
G.add_edge(u, v, **edgedata)
|
| 299 |
+
|
| 300 |
+
return G
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@open_file(0, mode="rb")
|
| 304 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 305 |
+
def read_multiline_adjlist(
|
| 306 |
+
path,
|
| 307 |
+
comments="#",
|
| 308 |
+
delimiter=None,
|
| 309 |
+
create_using=None,
|
| 310 |
+
nodetype=None,
|
| 311 |
+
edgetype=None,
|
| 312 |
+
encoding="utf-8",
|
| 313 |
+
):
|
| 314 |
+
"""Read graph in multi-line adjacency list format from path.
|
| 315 |
+
|
| 316 |
+
Parameters
|
| 317 |
+
----------
|
| 318 |
+
path : string or file
|
| 319 |
+
Filename or file handle to read.
|
| 320 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 321 |
+
|
| 322 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 323 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 324 |
+
|
| 325 |
+
nodetype : Python type, optional
|
| 326 |
+
Convert nodes to this type.
|
| 327 |
+
|
| 328 |
+
edgetype : Python type, optional
|
| 329 |
+
Convert edge data to this type.
|
| 330 |
+
|
| 331 |
+
comments : string, optional
|
| 332 |
+
Marker for comment lines
|
| 333 |
+
|
| 334 |
+
delimiter : string, optional
|
| 335 |
+
Separator for node labels. The default is whitespace.
|
| 336 |
+
|
| 337 |
+
Returns
|
| 338 |
+
-------
|
| 339 |
+
G: NetworkX graph
|
| 340 |
+
|
| 341 |
+
Examples
|
| 342 |
+
--------
|
| 343 |
+
>>> G = nx.path_graph(4)
|
| 344 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4")
|
| 345 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
|
| 346 |
+
|
| 347 |
+
The path can be a file or a string with the name of the file. If a
|
| 348 |
+
file s provided, it has to be opened in 'rb' mode.
|
| 349 |
+
|
| 350 |
+
>>> fh = open("test.multi_adjlistP4", "rb")
|
| 351 |
+
>>> G = nx.read_multiline_adjlist(fh)
|
| 352 |
+
|
| 353 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 354 |
+
|
| 355 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4.gz")
|
| 356 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4.gz")
|
| 357 |
+
|
| 358 |
+
The optional nodetype is a function to convert node strings to nodetype.
|
| 359 |
+
|
| 360 |
+
For example
|
| 361 |
+
|
| 362 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", nodetype=int)
|
| 363 |
+
|
| 364 |
+
will attempt to convert all nodes to integer type.
|
| 365 |
+
|
| 366 |
+
The optional edgetype is a function to convert edge data strings to
|
| 367 |
+
edgetype.
|
| 368 |
+
|
| 369 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
|
| 370 |
+
|
| 371 |
+
The optional create_using parameter is a NetworkX graph container.
|
| 372 |
+
The default is Graph(), an undirected graph. To read the data as
|
| 373 |
+
a directed graph use
|
| 374 |
+
|
| 375 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", create_using=nx.DiGraph)
|
| 376 |
+
|
| 377 |
+
Notes
|
| 378 |
+
-----
|
| 379 |
+
This format does not store graph, node, or edge data.
|
| 380 |
+
|
| 381 |
+
See Also
|
| 382 |
+
--------
|
| 383 |
+
write_multiline_adjlist
|
| 384 |
+
"""
|
| 385 |
+
lines = (line.decode(encoding) for line in path)
|
| 386 |
+
return parse_multiline_adjlist(
|
| 387 |
+
lines,
|
| 388 |
+
comments=comments,
|
| 389 |
+
delimiter=delimiter,
|
| 390 |
+
create_using=create_using,
|
| 391 |
+
nodetype=nodetype,
|
| 392 |
+
edgetype=edgetype,
|
| 393 |
+
)
|
.venv/lib/python3.12/site-packages/networkx/readwrite/p2g.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides the following: read and write of p2g format
|
| 3 |
+
used in metabolic pathway studies.
|
| 4 |
+
|
| 5 |
+
See:
|
| 6 |
+
<https://web.archive.org/web/20080626113807/http://www.cs.purdue.edu/homes/koyuturk/pathway/>
|
| 7 |
+
for a description.
|
| 8 |
+
|
| 9 |
+
The summary is included here:
|
| 10 |
+
|
| 11 |
+
A file that describes a uniquely labeled graph (with extension ".gr")
|
| 12 |
+
format looks like the following:
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
name
|
| 16 |
+
3 4
|
| 17 |
+
a
|
| 18 |
+
1 2
|
| 19 |
+
b
|
| 20 |
+
|
| 21 |
+
c
|
| 22 |
+
0 2
|
| 23 |
+
|
| 24 |
+
"name" is simply a description of what the graph corresponds to. The
|
| 25 |
+
second line displays the number of nodes and number of edges,
|
| 26 |
+
respectively. This sample graph contains three nodes labeled "a", "b",
|
| 27 |
+
and "c". The rest of the graph contains two lines for each node. The
|
| 28 |
+
first line for a node contains the node label. After the declaration
|
| 29 |
+
of the node label, the out-edges of that node in the graph are
|
| 30 |
+
provided. For instance, "a" is linked to nodes 1 and 2, which are
|
| 31 |
+
labeled "b" and "c", while the node labeled "b" has no outgoing
|
| 32 |
+
edges. Observe that node labeled "c" has an outgoing edge to
|
| 33 |
+
itself. Indeed, self-loops are allowed. Node index starts from 0.
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
import networkx as nx
|
| 38 |
+
from networkx.utils import open_file
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@open_file(1, mode="w")
|
| 42 |
+
def write_p2g(G, path, encoding="utf-8"):
|
| 43 |
+
"""Write NetworkX graph in p2g format.
|
| 44 |
+
|
| 45 |
+
Notes
|
| 46 |
+
-----
|
| 47 |
+
This format is meant to be used with directed graphs with
|
| 48 |
+
possible self loops.
|
| 49 |
+
"""
|
| 50 |
+
path.write((f"{G.name}\n").encode(encoding))
|
| 51 |
+
path.write((f"{G.order()} {G.size()}\n").encode(encoding))
|
| 52 |
+
nodes = list(G)
|
| 53 |
+
# make dictionary mapping nodes to integers
|
| 54 |
+
nodenumber = dict(zip(nodes, range(len(nodes))))
|
| 55 |
+
for n in nodes:
|
| 56 |
+
path.write((f"{n}\n").encode(encoding))
|
| 57 |
+
for nbr in G.neighbors(n):
|
| 58 |
+
path.write((f"{nodenumber[nbr]} ").encode(encoding))
|
| 59 |
+
path.write("\n".encode(encoding))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@open_file(0, mode="r")
|
| 63 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 64 |
+
def read_p2g(path, encoding="utf-8"):
|
| 65 |
+
"""Read graph in p2g format from path.
|
| 66 |
+
|
| 67 |
+
Parameters
|
| 68 |
+
----------
|
| 69 |
+
path : string or file
|
| 70 |
+
Filename or file handle to read.
|
| 71 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 72 |
+
|
| 73 |
+
Returns
|
| 74 |
+
-------
|
| 75 |
+
MultiDiGraph
|
| 76 |
+
|
| 77 |
+
Notes
|
| 78 |
+
-----
|
| 79 |
+
If you want a DiGraph (with no self loops allowed and no edge data)
|
| 80 |
+
use D=nx.DiGraph(read_p2g(path))
|
| 81 |
+
"""
|
| 82 |
+
lines = (line.decode(encoding) for line in path)
|
| 83 |
+
G = parse_p2g(lines)
|
| 84 |
+
return G
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 88 |
+
def parse_p2g(lines):
|
| 89 |
+
"""Parse p2g format graph from string or iterable.
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
-------
|
| 93 |
+
MultiDiGraph
|
| 94 |
+
"""
|
| 95 |
+
description = next(lines).strip()
|
| 96 |
+
# are multiedges (parallel edges) allowed?
|
| 97 |
+
G = nx.MultiDiGraph(name=description, selfloops=True)
|
| 98 |
+
nnodes, nedges = map(int, next(lines).split())
|
| 99 |
+
nodelabel = {}
|
| 100 |
+
nbrs = {}
|
| 101 |
+
# loop over the nodes keeping track of node labels and out neighbors
|
| 102 |
+
# defer adding edges until all node labels are known
|
| 103 |
+
for i in range(nnodes):
|
| 104 |
+
n = next(lines).strip()
|
| 105 |
+
nodelabel[i] = n
|
| 106 |
+
G.add_node(n)
|
| 107 |
+
nbrs[n] = map(int, next(lines).split())
|
| 108 |
+
# now we know all of the node labels so we can add the edges
|
| 109 |
+
# with the correct labels
|
| 110 |
+
for n in G:
|
| 111 |
+
for nbr in nbrs[n]:
|
| 112 |
+
G.add_edge(n, nodelabel[nbr])
|
| 113 |
+
return G
|
.venv/lib/python3.12/site-packages/networkx/readwrite/pajek.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
*****
|
| 3 |
+
Pajek
|
| 4 |
+
*****
|
| 5 |
+
Read graphs in Pajek format.
|
| 6 |
+
|
| 7 |
+
This implementation handles directed and undirected graphs including
|
| 8 |
+
those with self loops and parallel edges.
|
| 9 |
+
|
| 10 |
+
Format
|
| 11 |
+
------
|
| 12 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
| 13 |
+
for format information.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
import networkx as nx
|
| 20 |
+
from networkx.utils import open_file
|
| 21 |
+
|
| 22 |
+
__all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def generate_pajek(G):
|
| 26 |
+
"""Generate lines in Pajek graph format.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
----------
|
| 30 |
+
G : graph
|
| 31 |
+
A Networkx graph
|
| 32 |
+
|
| 33 |
+
References
|
| 34 |
+
----------
|
| 35 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
| 36 |
+
for format information.
|
| 37 |
+
"""
|
| 38 |
+
if G.name == "":
|
| 39 |
+
name = "NetworkX"
|
| 40 |
+
else:
|
| 41 |
+
name = G.name
|
| 42 |
+
# Apparently many Pajek format readers can't process this line
|
| 43 |
+
# So we'll leave it out for now.
|
| 44 |
+
# yield '*network %s'%name
|
| 45 |
+
|
| 46 |
+
# write nodes with attributes
|
| 47 |
+
yield f"*vertices {G.order()}"
|
| 48 |
+
nodes = list(G)
|
| 49 |
+
# make dictionary mapping nodes to integers
|
| 50 |
+
nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
|
| 51 |
+
for n in nodes:
|
| 52 |
+
# copy node attributes and pop mandatory attributes
|
| 53 |
+
# to avoid duplication.
|
| 54 |
+
na = G.nodes.get(n, {}).copy()
|
| 55 |
+
x = na.pop("x", 0.0)
|
| 56 |
+
y = na.pop("y", 0.0)
|
| 57 |
+
try:
|
| 58 |
+
id = int(na.pop("id", nodenumber[n]))
|
| 59 |
+
except ValueError as err:
|
| 60 |
+
err.args += (
|
| 61 |
+
(
|
| 62 |
+
"Pajek format requires 'id' to be an int()."
|
| 63 |
+
" Refer to the 'Relabeling nodes' section."
|
| 64 |
+
),
|
| 65 |
+
)
|
| 66 |
+
raise
|
| 67 |
+
nodenumber[n] = id
|
| 68 |
+
shape = na.pop("shape", "ellipse")
|
| 69 |
+
s = " ".join(map(make_qstr, (id, n, x, y, shape)))
|
| 70 |
+
# only optional attributes are left in na.
|
| 71 |
+
for k, v in na.items():
|
| 72 |
+
if isinstance(v, str) and v.strip() != "":
|
| 73 |
+
s += f" {make_qstr(k)} {make_qstr(v)}"
|
| 74 |
+
else:
|
| 75 |
+
warnings.warn(
|
| 76 |
+
f"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
|
| 77 |
+
)
|
| 78 |
+
yield s
|
| 79 |
+
|
| 80 |
+
# write edges with attributes
|
| 81 |
+
if G.is_directed():
|
| 82 |
+
yield "*arcs"
|
| 83 |
+
else:
|
| 84 |
+
yield "*edges"
|
| 85 |
+
for u, v, edgedata in G.edges(data=True):
|
| 86 |
+
d = edgedata.copy()
|
| 87 |
+
value = d.pop("weight", 1.0) # use 1 as default edge value
|
| 88 |
+
s = " ".join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
|
| 89 |
+
for k, v in d.items():
|
| 90 |
+
if isinstance(v, str) and v.strip() != "":
|
| 91 |
+
s += f" {make_qstr(k)} {make_qstr(v)}"
|
| 92 |
+
else:
|
| 93 |
+
warnings.warn(
|
| 94 |
+
f"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
|
| 95 |
+
)
|
| 96 |
+
yield s
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@open_file(1, mode="wb")
|
| 100 |
+
def write_pajek(G, path, encoding="UTF-8"):
|
| 101 |
+
"""Write graph in Pajek format to path.
|
| 102 |
+
|
| 103 |
+
Parameters
|
| 104 |
+
----------
|
| 105 |
+
G : graph
|
| 106 |
+
A Networkx graph
|
| 107 |
+
path : file or string
|
| 108 |
+
File or filename to write.
|
| 109 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 110 |
+
|
| 111 |
+
Examples
|
| 112 |
+
--------
|
| 113 |
+
>>> G = nx.path_graph(4)
|
| 114 |
+
>>> nx.write_pajek(G, "test.netP4")
|
| 115 |
+
|
| 116 |
+
Warnings
|
| 117 |
+
--------
|
| 118 |
+
Optional node attributes and edge attributes must be non-empty strings.
|
| 119 |
+
Otherwise it will not be written into the file. You will need to
|
| 120 |
+
convert those attributes to strings if you want to keep them.
|
| 121 |
+
|
| 122 |
+
References
|
| 123 |
+
----------
|
| 124 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
| 125 |
+
for format information.
|
| 126 |
+
"""
|
| 127 |
+
for line in generate_pajek(G):
|
| 128 |
+
line += "\n"
|
| 129 |
+
path.write(line.encode(encoding))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@open_file(0, mode="rb")
|
| 133 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 134 |
+
def read_pajek(path, encoding="UTF-8"):
|
| 135 |
+
"""Read graph in Pajek format from path.
|
| 136 |
+
|
| 137 |
+
Parameters
|
| 138 |
+
----------
|
| 139 |
+
path : file or string
|
| 140 |
+
Filename or file handle to read.
|
| 141 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 142 |
+
|
| 143 |
+
Returns
|
| 144 |
+
-------
|
| 145 |
+
G : NetworkX MultiGraph or MultiDiGraph.
|
| 146 |
+
|
| 147 |
+
Examples
|
| 148 |
+
--------
|
| 149 |
+
>>> G = nx.path_graph(4)
|
| 150 |
+
>>> nx.write_pajek(G, "test.net")
|
| 151 |
+
>>> G = nx.read_pajek("test.net")
|
| 152 |
+
|
| 153 |
+
To create a Graph instead of a MultiGraph use
|
| 154 |
+
|
| 155 |
+
>>> G1 = nx.Graph(G)
|
| 156 |
+
|
| 157 |
+
References
|
| 158 |
+
----------
|
| 159 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
| 160 |
+
for format information.
|
| 161 |
+
"""
|
| 162 |
+
lines = (line.decode(encoding) for line in path)
|
| 163 |
+
return parse_pajek(lines)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 167 |
+
def parse_pajek(lines):
|
| 168 |
+
"""Parse Pajek format graph from string or iterable.
|
| 169 |
+
|
| 170 |
+
Parameters
|
| 171 |
+
----------
|
| 172 |
+
lines : string or iterable
|
| 173 |
+
Data in Pajek format.
|
| 174 |
+
|
| 175 |
+
Returns
|
| 176 |
+
-------
|
| 177 |
+
G : NetworkX graph
|
| 178 |
+
|
| 179 |
+
See Also
|
| 180 |
+
--------
|
| 181 |
+
read_pajek
|
| 182 |
+
|
| 183 |
+
"""
|
| 184 |
+
import shlex
|
| 185 |
+
|
| 186 |
+
# multigraph=False
|
| 187 |
+
if isinstance(lines, str):
|
| 188 |
+
lines = iter(lines.split("\n"))
|
| 189 |
+
lines = iter([line.rstrip("\n") for line in lines])
|
| 190 |
+
G = nx.MultiDiGraph() # are multiedges allowed in Pajek? assume yes
|
| 191 |
+
labels = [] # in the order of the file, needed for matrix
|
| 192 |
+
while lines:
|
| 193 |
+
try:
|
| 194 |
+
l = next(lines)
|
| 195 |
+
except: # EOF
|
| 196 |
+
break
|
| 197 |
+
if l.lower().startswith("*network"):
|
| 198 |
+
try:
|
| 199 |
+
label, name = l.split(None, 1)
|
| 200 |
+
except ValueError:
|
| 201 |
+
# Line was not of the form: *network NAME
|
| 202 |
+
pass
|
| 203 |
+
else:
|
| 204 |
+
G.graph["name"] = name
|
| 205 |
+
elif l.lower().startswith("*vertices"):
|
| 206 |
+
nodelabels = {}
|
| 207 |
+
l, nnodes = l.split()
|
| 208 |
+
for i in range(int(nnodes)):
|
| 209 |
+
l = next(lines)
|
| 210 |
+
try:
|
| 211 |
+
splitline = [
|
| 212 |
+
x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
|
| 213 |
+
]
|
| 214 |
+
except AttributeError:
|
| 215 |
+
splitline = shlex.split(str(l))
|
| 216 |
+
id, label = splitline[0:2]
|
| 217 |
+
labels.append(label)
|
| 218 |
+
G.add_node(label)
|
| 219 |
+
nodelabels[id] = label
|
| 220 |
+
G.nodes[label]["id"] = id
|
| 221 |
+
try:
|
| 222 |
+
x, y, shape = splitline[2:5]
|
| 223 |
+
G.nodes[label].update(
|
| 224 |
+
{"x": float(x), "y": float(y), "shape": shape}
|
| 225 |
+
)
|
| 226 |
+
except:
|
| 227 |
+
pass
|
| 228 |
+
extra_attr = zip(splitline[5::2], splitline[6::2])
|
| 229 |
+
G.nodes[label].update(extra_attr)
|
| 230 |
+
elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
|
| 231 |
+
if l.lower().startswith("*edge"):
|
| 232 |
+
# switch from multidigraph to multigraph
|
| 233 |
+
G = nx.MultiGraph(G)
|
| 234 |
+
if l.lower().startswith("*arcs"):
|
| 235 |
+
# switch to directed with multiple arcs for each existing edge
|
| 236 |
+
G = G.to_directed()
|
| 237 |
+
for l in lines:
|
| 238 |
+
try:
|
| 239 |
+
splitline = [
|
| 240 |
+
x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
|
| 241 |
+
]
|
| 242 |
+
except AttributeError:
|
| 243 |
+
splitline = shlex.split(str(l))
|
| 244 |
+
|
| 245 |
+
if len(splitline) < 2:
|
| 246 |
+
continue
|
| 247 |
+
ui, vi = splitline[0:2]
|
| 248 |
+
u = nodelabels.get(ui, ui)
|
| 249 |
+
v = nodelabels.get(vi, vi)
|
| 250 |
+
# parse the data attached to this edge and put in a dictionary
|
| 251 |
+
edge_data = {}
|
| 252 |
+
try:
|
| 253 |
+
# there should always be a single value on the edge?
|
| 254 |
+
w = splitline[2:3]
|
| 255 |
+
edge_data.update({"weight": float(w[0])})
|
| 256 |
+
except:
|
| 257 |
+
pass
|
| 258 |
+
# if there isn't, just assign a 1
|
| 259 |
+
# edge_data.update({'value':1})
|
| 260 |
+
extra_attr = zip(splitline[3::2], splitline[4::2])
|
| 261 |
+
edge_data.update(extra_attr)
|
| 262 |
+
# if G.has_edge(u,v):
|
| 263 |
+
# multigraph=True
|
| 264 |
+
G.add_edge(u, v, **edge_data)
|
| 265 |
+
elif l.lower().startswith("*matrix"):
|
| 266 |
+
G = nx.DiGraph(G)
|
| 267 |
+
adj_list = (
|
| 268 |
+
(labels[row], labels[col], {"weight": int(data)})
|
| 269 |
+
for (row, line) in enumerate(lines)
|
| 270 |
+
for (col, data) in enumerate(line.split())
|
| 271 |
+
if int(data) != 0
|
| 272 |
+
)
|
| 273 |
+
G.add_edges_from(adj_list)
|
| 274 |
+
|
| 275 |
+
return G
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def make_qstr(t):
|
| 279 |
+
"""Returns the string representation of t.
|
| 280 |
+
Add outer double-quotes if the string has a space.
|
| 281 |
+
"""
|
| 282 |
+
if not isinstance(t, str):
|
| 283 |
+
t = str(t)
|
| 284 |
+
if " " in t:
|
| 285 |
+
t = f'"{t}"'
|
| 286 |
+
return t
|
.venv/lib/python3.12/site-packages/networkx/readwrite/sparse6.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Original author: D. Eppstein, UC Irvine, August 12, 2003.
|
| 2 |
+
# The original code at https://www.ics.uci.edu/~eppstein/PADS/ is public domain.
|
| 3 |
+
"""Functions for reading and writing graphs in the *sparse6* format.
|
| 4 |
+
|
| 5 |
+
The *sparse6* file format is a space-efficient format for large sparse
|
| 6 |
+
graphs. For small graphs or large dense graphs, use the *graph6* file
|
| 7 |
+
format.
|
| 8 |
+
|
| 9 |
+
For more information, see the `sparse6`_ homepage.
|
| 10 |
+
|
| 11 |
+
.. _sparse6: https://users.cecs.anu.edu.au/~bdm/data/formats.html
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import networkx as nx
|
| 16 |
+
from networkx.exception import NetworkXError
|
| 17 |
+
from networkx.readwrite.graph6 import data_to_n, n_to_data
|
| 18 |
+
from networkx.utils import not_implemented_for, open_file
|
| 19 |
+
|
| 20 |
+
__all__ = ["from_sparse6_bytes", "read_sparse6", "to_sparse6_bytes", "write_sparse6"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _generate_sparse6_bytes(G, nodes, header):
|
| 24 |
+
"""Yield bytes in the sparse6 encoding of a graph.
|
| 25 |
+
|
| 26 |
+
`G` is an undirected simple graph. `nodes` is the list of nodes for
|
| 27 |
+
which the node-induced subgraph will be encoded; if `nodes` is the
|
| 28 |
+
list of all nodes in the graph, the entire graph will be
|
| 29 |
+
encoded. `header` is a Boolean that specifies whether to generate
|
| 30 |
+
the header ``b'>>sparse6<<'`` before the remaining data.
|
| 31 |
+
|
| 32 |
+
This function generates `bytes` objects in the following order:
|
| 33 |
+
|
| 34 |
+
1. the header (if requested),
|
| 35 |
+
2. the encoding of the number of nodes,
|
| 36 |
+
3. each character, one-at-a-time, in the encoding of the requested
|
| 37 |
+
node-induced subgraph,
|
| 38 |
+
4. a newline character.
|
| 39 |
+
|
| 40 |
+
This function raises :exc:`ValueError` if the graph is too large for
|
| 41 |
+
the graph6 format (that is, greater than ``2 ** 36`` nodes).
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
n = len(G)
|
| 45 |
+
if n >= 2**36:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
"sparse6 is only defined if number of nodes is less than 2 ** 36"
|
| 48 |
+
)
|
| 49 |
+
if header:
|
| 50 |
+
yield b">>sparse6<<"
|
| 51 |
+
yield b":"
|
| 52 |
+
for d in n_to_data(n):
|
| 53 |
+
yield str.encode(chr(d + 63))
|
| 54 |
+
|
| 55 |
+
k = 1
|
| 56 |
+
while 1 << k < n:
|
| 57 |
+
k += 1
|
| 58 |
+
|
| 59 |
+
def enc(x):
|
| 60 |
+
"""Big endian k-bit encoding of x"""
|
| 61 |
+
return [1 if (x & 1 << (k - 1 - i)) else 0 for i in range(k)]
|
| 62 |
+
|
| 63 |
+
edges = sorted((max(u, v), min(u, v)) for u, v in G.edges())
|
| 64 |
+
bits = []
|
| 65 |
+
curv = 0
|
| 66 |
+
for v, u in edges:
|
| 67 |
+
if v == curv: # current vertex edge
|
| 68 |
+
bits.append(0)
|
| 69 |
+
bits.extend(enc(u))
|
| 70 |
+
elif v == curv + 1: # next vertex edge
|
| 71 |
+
curv += 1
|
| 72 |
+
bits.append(1)
|
| 73 |
+
bits.extend(enc(u))
|
| 74 |
+
else: # skip to vertex v and then add edge to u
|
| 75 |
+
curv = v
|
| 76 |
+
bits.append(1)
|
| 77 |
+
bits.extend(enc(v))
|
| 78 |
+
bits.append(0)
|
| 79 |
+
bits.extend(enc(u))
|
| 80 |
+
if k < 6 and n == (1 << k) and ((-len(bits)) % 6) >= k and curv < (n - 1):
|
| 81 |
+
# Padding special case: small k, n=2^k,
|
| 82 |
+
# more than k bits of padding needed,
|
| 83 |
+
# current vertex is not (n-1) --
|
| 84 |
+
# appending 1111... would add a loop on (n-1)
|
| 85 |
+
bits.append(0)
|
| 86 |
+
bits.extend([1] * ((-len(bits)) % 6))
|
| 87 |
+
else:
|
| 88 |
+
bits.extend([1] * ((-len(bits)) % 6))
|
| 89 |
+
|
| 90 |
+
data = [
|
| 91 |
+
(bits[i + 0] << 5)
|
| 92 |
+
+ (bits[i + 1] << 4)
|
| 93 |
+
+ (bits[i + 2] << 3)
|
| 94 |
+
+ (bits[i + 3] << 2)
|
| 95 |
+
+ (bits[i + 4] << 1)
|
| 96 |
+
+ (bits[i + 5] << 0)
|
| 97 |
+
for i in range(0, len(bits), 6)
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
for d in data:
|
| 101 |
+
yield str.encode(chr(d + 63))
|
| 102 |
+
yield b"\n"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 106 |
+
def from_sparse6_bytes(string):
|
| 107 |
+
"""Read an undirected graph in sparse6 format from string.
|
| 108 |
+
|
| 109 |
+
Parameters
|
| 110 |
+
----------
|
| 111 |
+
string : string
|
| 112 |
+
Data in sparse6 format
|
| 113 |
+
|
| 114 |
+
Returns
|
| 115 |
+
-------
|
| 116 |
+
G : Graph
|
| 117 |
+
|
| 118 |
+
Raises
|
| 119 |
+
------
|
| 120 |
+
NetworkXError
|
| 121 |
+
If the string is unable to be parsed in sparse6 format
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
--------
|
| 125 |
+
>>> G = nx.from_sparse6_bytes(b":A_")
|
| 126 |
+
>>> sorted(G.edges())
|
| 127 |
+
[(0, 1), (0, 1), (0, 1)]
|
| 128 |
+
|
| 129 |
+
See Also
|
| 130 |
+
--------
|
| 131 |
+
read_sparse6, write_sparse6
|
| 132 |
+
|
| 133 |
+
References
|
| 134 |
+
----------
|
| 135 |
+
.. [1] Sparse6 specification
|
| 136 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
if string.startswith(b">>sparse6<<"):
|
| 140 |
+
string = string[11:]
|
| 141 |
+
if not string.startswith(b":"):
|
| 142 |
+
raise NetworkXError("Expected leading colon in sparse6")
|
| 143 |
+
|
| 144 |
+
chars = [c - 63 for c in string[1:]]
|
| 145 |
+
n, data = data_to_n(chars)
|
| 146 |
+
k = 1
|
| 147 |
+
while 1 << k < n:
|
| 148 |
+
k += 1
|
| 149 |
+
|
| 150 |
+
def parseData():
|
| 151 |
+
"""Returns stream of pairs b[i], x[i] for sparse6 format."""
|
| 152 |
+
chunks = iter(data)
|
| 153 |
+
d = None # partial data word
|
| 154 |
+
dLen = 0 # how many unparsed bits are left in d
|
| 155 |
+
|
| 156 |
+
while 1:
|
| 157 |
+
if dLen < 1:
|
| 158 |
+
try:
|
| 159 |
+
d = next(chunks)
|
| 160 |
+
except StopIteration:
|
| 161 |
+
return
|
| 162 |
+
dLen = 6
|
| 163 |
+
dLen -= 1
|
| 164 |
+
b = (d >> dLen) & 1 # grab top remaining bit
|
| 165 |
+
|
| 166 |
+
x = d & ((1 << dLen) - 1) # partially built up value of x
|
| 167 |
+
xLen = dLen # how many bits included so far in x
|
| 168 |
+
while xLen < k: # now grab full chunks until we have enough
|
| 169 |
+
try:
|
| 170 |
+
d = next(chunks)
|
| 171 |
+
except StopIteration:
|
| 172 |
+
return
|
| 173 |
+
dLen = 6
|
| 174 |
+
x = (x << 6) + d
|
| 175 |
+
xLen += 6
|
| 176 |
+
x = x >> (xLen - k) # shift back the extra bits
|
| 177 |
+
dLen = xLen - k
|
| 178 |
+
yield b, x
|
| 179 |
+
|
| 180 |
+
v = 0
|
| 181 |
+
|
| 182 |
+
G = nx.MultiGraph()
|
| 183 |
+
G.add_nodes_from(range(n))
|
| 184 |
+
|
| 185 |
+
multigraph = False
|
| 186 |
+
for b, x in parseData():
|
| 187 |
+
if b == 1:
|
| 188 |
+
v += 1
|
| 189 |
+
# padding with ones can cause overlarge number here
|
| 190 |
+
if x >= n or v >= n:
|
| 191 |
+
break
|
| 192 |
+
elif x > v:
|
| 193 |
+
v = x
|
| 194 |
+
else:
|
| 195 |
+
if G.has_edge(x, v):
|
| 196 |
+
multigraph = True
|
| 197 |
+
G.add_edge(x, v)
|
| 198 |
+
if not multigraph:
|
| 199 |
+
G = nx.Graph(G)
|
| 200 |
+
return G
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def to_sparse6_bytes(G, nodes=None, header=True):
|
| 204 |
+
"""Convert an undirected graph to bytes in sparse6 format.
|
| 205 |
+
|
| 206 |
+
Parameters
|
| 207 |
+
----------
|
| 208 |
+
G : Graph (undirected)
|
| 209 |
+
|
| 210 |
+
nodes: list or iterable
|
| 211 |
+
Nodes are labeled 0...n-1 in the order provided. If None the ordering
|
| 212 |
+
given by ``G.nodes()`` is used.
|
| 213 |
+
|
| 214 |
+
header: bool
|
| 215 |
+
If True add '>>sparse6<<' bytes to head of data.
|
| 216 |
+
|
| 217 |
+
Raises
|
| 218 |
+
------
|
| 219 |
+
NetworkXNotImplemented
|
| 220 |
+
If the graph is directed.
|
| 221 |
+
|
| 222 |
+
ValueError
|
| 223 |
+
If the graph has at least ``2 ** 36`` nodes; the sparse6 format
|
| 224 |
+
is only defined for graphs of order less than ``2 ** 36``.
|
| 225 |
+
|
| 226 |
+
Examples
|
| 227 |
+
--------
|
| 228 |
+
>>> nx.to_sparse6_bytes(nx.path_graph(2))
|
| 229 |
+
b'>>sparse6<<:An\\n'
|
| 230 |
+
|
| 231 |
+
See Also
|
| 232 |
+
--------
|
| 233 |
+
to_sparse6_bytes, read_sparse6, write_sparse6_bytes
|
| 234 |
+
|
| 235 |
+
Notes
|
| 236 |
+
-----
|
| 237 |
+
The returned bytes end with a newline character.
|
| 238 |
+
|
| 239 |
+
The format does not support edge or node labels.
|
| 240 |
+
|
| 241 |
+
References
|
| 242 |
+
----------
|
| 243 |
+
.. [1] Graph6 specification
|
| 244 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
| 245 |
+
|
| 246 |
+
"""
|
| 247 |
+
if nodes is not None:
|
| 248 |
+
G = G.subgraph(nodes)
|
| 249 |
+
G = nx.convert_node_labels_to_integers(G, ordering="sorted")
|
| 250 |
+
return b"".join(_generate_sparse6_bytes(G, nodes, header))
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@open_file(0, mode="rb")
|
| 254 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 255 |
+
def read_sparse6(path):
|
| 256 |
+
"""Read an undirected graph in sparse6 format from path.
|
| 257 |
+
|
| 258 |
+
Parameters
|
| 259 |
+
----------
|
| 260 |
+
path : file or string
|
| 261 |
+
Filename or file handle to read.
|
| 262 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 263 |
+
|
| 264 |
+
Returns
|
| 265 |
+
-------
|
| 266 |
+
G : Graph/Multigraph or list of Graphs/MultiGraphs
|
| 267 |
+
If the file contains multiple lines then a list of graphs is returned
|
| 268 |
+
|
| 269 |
+
Raises
|
| 270 |
+
------
|
| 271 |
+
NetworkXError
|
| 272 |
+
If the string is unable to be parsed in sparse6 format
|
| 273 |
+
|
| 274 |
+
Examples
|
| 275 |
+
--------
|
| 276 |
+
You can read a sparse6 file by giving the path to the file::
|
| 277 |
+
|
| 278 |
+
>>> import tempfile
|
| 279 |
+
>>> with tempfile.NamedTemporaryFile(delete=False) as f:
|
| 280 |
+
... _ = f.write(b">>sparse6<<:An\\n")
|
| 281 |
+
... _ = f.seek(0)
|
| 282 |
+
... G = nx.read_sparse6(f.name)
|
| 283 |
+
>>> list(G.edges())
|
| 284 |
+
[(0, 1)]
|
| 285 |
+
|
| 286 |
+
You can also read a sparse6 file by giving an open file-like object::
|
| 287 |
+
|
| 288 |
+
>>> import tempfile
|
| 289 |
+
>>> with tempfile.NamedTemporaryFile() as f:
|
| 290 |
+
... _ = f.write(b">>sparse6<<:An\\n")
|
| 291 |
+
... _ = f.seek(0)
|
| 292 |
+
... G = nx.read_sparse6(f)
|
| 293 |
+
>>> list(G.edges())
|
| 294 |
+
[(0, 1)]
|
| 295 |
+
|
| 296 |
+
See Also
|
| 297 |
+
--------
|
| 298 |
+
read_sparse6, from_sparse6_bytes
|
| 299 |
+
|
| 300 |
+
References
|
| 301 |
+
----------
|
| 302 |
+
.. [1] Sparse6 specification
|
| 303 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
| 304 |
+
|
| 305 |
+
"""
|
| 306 |
+
glist = []
|
| 307 |
+
for line in path:
|
| 308 |
+
line = line.strip()
|
| 309 |
+
if not len(line):
|
| 310 |
+
continue
|
| 311 |
+
glist.append(from_sparse6_bytes(line))
|
| 312 |
+
if len(glist) == 1:
|
| 313 |
+
return glist[0]
|
| 314 |
+
else:
|
| 315 |
+
return glist
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@not_implemented_for("directed")
|
| 319 |
+
@open_file(1, mode="wb")
|
| 320 |
+
def write_sparse6(G, path, nodes=None, header=True):
|
| 321 |
+
"""Write graph G to given path in sparse6 format.
|
| 322 |
+
|
| 323 |
+
Parameters
|
| 324 |
+
----------
|
| 325 |
+
G : Graph (undirected)
|
| 326 |
+
|
| 327 |
+
path : file or string
|
| 328 |
+
File or filename to write.
|
| 329 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 330 |
+
|
| 331 |
+
nodes: list or iterable
|
| 332 |
+
Nodes are labeled 0...n-1 in the order provided. If None the ordering
|
| 333 |
+
given by G.nodes() is used.
|
| 334 |
+
|
| 335 |
+
header: bool
|
| 336 |
+
If True add '>>sparse6<<' string to head of data
|
| 337 |
+
|
| 338 |
+
Raises
|
| 339 |
+
------
|
| 340 |
+
NetworkXError
|
| 341 |
+
If the graph is directed
|
| 342 |
+
|
| 343 |
+
Examples
|
| 344 |
+
--------
|
| 345 |
+
You can write a sparse6 file by giving the path to the file::
|
| 346 |
+
|
| 347 |
+
>>> import tempfile
|
| 348 |
+
>>> with tempfile.NamedTemporaryFile(delete=False) as f:
|
| 349 |
+
... nx.write_sparse6(nx.path_graph(2), f.name)
|
| 350 |
+
... print(f.read())
|
| 351 |
+
b'>>sparse6<<:An\\n'
|
| 352 |
+
|
| 353 |
+
You can also write a sparse6 file by giving an open file-like object::
|
| 354 |
+
|
| 355 |
+
>>> with tempfile.NamedTemporaryFile() as f:
|
| 356 |
+
... nx.write_sparse6(nx.path_graph(2), f)
|
| 357 |
+
... _ = f.seek(0)
|
| 358 |
+
... print(f.read())
|
| 359 |
+
b'>>sparse6<<:An\\n'
|
| 360 |
+
|
| 361 |
+
See Also
|
| 362 |
+
--------
|
| 363 |
+
read_sparse6, from_sparse6_bytes
|
| 364 |
+
|
| 365 |
+
Notes
|
| 366 |
+
-----
|
| 367 |
+
The format does not support edge or node labels.
|
| 368 |
+
|
| 369 |
+
References
|
| 370 |
+
----------
|
| 371 |
+
.. [1] Sparse6 specification
|
| 372 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
| 373 |
+
|
| 374 |
+
"""
|
| 375 |
+
if nodes is not None:
|
| 376 |
+
G = G.subgraph(nodes)
|
| 377 |
+
G = nx.convert_node_labels_to_integers(G, ordering="sorted")
|
| 378 |
+
for b in _generate_sparse6_bytes(G, nodes, header):
|
| 379 |
+
path.write(b)
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (199 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_adjlist.cpython-312.pyc
ADDED
|
Binary file (23 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_edgelist.cpython-312.pyc
ADDED
|
Binary file (18.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_gexf.cpython-312.pyc
ADDED
|
Binary file (36.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_gml.cpython-312.pyc
ADDED
|
Binary file (30.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_graph6.cpython-312.pyc
ADDED
|
Binary file (15.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_graphml.cpython-312.pyc
ADDED
|
Binary file (90.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_leda.cpython-312.pyc
ADDED
|
Binary file (2.27 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_p2g.cpython-312.pyc
ADDED
|
Binary file (2.98 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_pajek.cpython-312.pyc
ADDED
|
Binary file (7.96 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_sparse6.cpython-312.pyc
ADDED
|
Binary file (9.47 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__pycache__/test_text.cpython-312.pyc
ADDED
|
Binary file (67.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit tests for adjlist.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
import networkx as nx
|
| 10 |
+
from networkx.utils import edges_equal, graphs_equal, nodes_equal
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestGenerateAdjlist:
|
| 14 |
+
@pytest.mark.parametrize("graph_type", [nx.Graph, nx.MultiGraph])
|
| 15 |
+
def test_undirected(self, graph_type):
|
| 16 |
+
G = nx.complete_graph(5, create_using=graph_type)
|
| 17 |
+
lines = [
|
| 18 |
+
"0 1 2 3 4",
|
| 19 |
+
"1 2 3 4",
|
| 20 |
+
"2 3 4",
|
| 21 |
+
"3 4",
|
| 22 |
+
"4",
|
| 23 |
+
]
|
| 24 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 25 |
+
|
| 26 |
+
@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph])
|
| 27 |
+
def test_directed(self, graph_type):
|
| 28 |
+
G = nx.complete_graph(5, create_using=graph_type)
|
| 29 |
+
lines = [
|
| 30 |
+
"0 1 2 3 4",
|
| 31 |
+
"1 0 2 3 4",
|
| 32 |
+
"2 0 1 3 4",
|
| 33 |
+
"3 0 1 2 4",
|
| 34 |
+
"4 0 1 2 3",
|
| 35 |
+
]
|
| 36 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 37 |
+
|
| 38 |
+
G = nx.path_graph(5, create_using=graph_type)
|
| 39 |
+
G.add_edge(1, 0)
|
| 40 |
+
lines = [
|
| 41 |
+
"0 1",
|
| 42 |
+
"1 2 0",
|
| 43 |
+
"2 3",
|
| 44 |
+
"3 4",
|
| 45 |
+
"4",
|
| 46 |
+
]
|
| 47 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 48 |
+
|
| 49 |
+
@pytest.mark.parametrize("delimiter", [" ", ",", "\t"])
|
| 50 |
+
def test_delimiter(self, delimiter):
|
| 51 |
+
G = nx.complete_graph(3)
|
| 52 |
+
lines = [
|
| 53 |
+
f"0{delimiter}1{delimiter}2",
|
| 54 |
+
f"1{delimiter}2",
|
| 55 |
+
f"2",
|
| 56 |
+
]
|
| 57 |
+
assert list(nx.generate_adjlist(G, delimiter=delimiter)) == lines
|
| 58 |
+
|
| 59 |
+
def test_multiple_edges_undirected(self):
|
| 60 |
+
G = nx.complete_graph(3, create_using=nx.MultiGraph)
|
| 61 |
+
G.add_edge(0, 1)
|
| 62 |
+
lines = [
|
| 63 |
+
"0 1 1 2",
|
| 64 |
+
"1 2",
|
| 65 |
+
"2",
|
| 66 |
+
]
|
| 67 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 68 |
+
|
| 69 |
+
def test_multiple_edges_directed(self):
|
| 70 |
+
G = nx.complete_graph(3, create_using=nx.MultiDiGraph)
|
| 71 |
+
G.add_edge(0, 1)
|
| 72 |
+
lines = [
|
| 73 |
+
"0 1 1 2",
|
| 74 |
+
"1 0 2",
|
| 75 |
+
"2 0 1",
|
| 76 |
+
]
|
| 77 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 78 |
+
|
| 79 |
+
G.add_edge(1, 0)
|
| 80 |
+
lines[1] = "1 0 0 2"
|
| 81 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 82 |
+
|
| 83 |
+
def test_multiple_edges_with_data(self):
|
| 84 |
+
G = nx.complete_graph(3, create_using=nx.MultiGraph)
|
| 85 |
+
G.add_edge(0, 1, weight=1)
|
| 86 |
+
G.add_edge(0, 1, weight=2)
|
| 87 |
+
lines = [
|
| 88 |
+
"0 1 1 1 2",
|
| 89 |
+
"1 2",
|
| 90 |
+
"2",
|
| 91 |
+
]
|
| 92 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 93 |
+
|
| 94 |
+
def test_with_self_loop(self):
|
| 95 |
+
G = nx.complete_graph(3)
|
| 96 |
+
G.add_edge(0, 0)
|
| 97 |
+
lines = [
|
| 98 |
+
"0 1 2 0",
|
| 99 |
+
"1 2",
|
| 100 |
+
"2",
|
| 101 |
+
]
|
| 102 |
+
assert list(nx.generate_adjlist(G)) == lines
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class TestAdjlist:
|
| 106 |
+
@classmethod
|
| 107 |
+
def setup_class(cls):
|
| 108 |
+
cls.G = nx.Graph(name="test")
|
| 109 |
+
e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")]
|
| 110 |
+
cls.G.add_edges_from(e)
|
| 111 |
+
cls.G.add_node("g")
|
| 112 |
+
cls.DG = nx.DiGraph(cls.G)
|
| 113 |
+
cls.XG = nx.MultiGraph()
|
| 114 |
+
cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)])
|
| 115 |
+
cls.XDG = nx.MultiDiGraph(cls.XG)
|
| 116 |
+
|
| 117 |
+
def test_read_multiline_adjlist_1(self):
|
| 118 |
+
# Unit test for https://networkx.lanl.gov/trac/ticket/252
|
| 119 |
+
s = b"""# comment line
|
| 120 |
+
1 2
|
| 121 |
+
# comment line
|
| 122 |
+
2
|
| 123 |
+
3
|
| 124 |
+
"""
|
| 125 |
+
bytesIO = io.BytesIO(s)
|
| 126 |
+
G = nx.read_multiline_adjlist(bytesIO)
|
| 127 |
+
adj = {"1": {"3": {}, "2": {}}, "3": {"1": {}}, "2": {"1": {}}}
|
| 128 |
+
assert graphs_equal(G, nx.Graph(adj))
|
| 129 |
+
|
| 130 |
+
def test_unicode(self, tmp_path):
|
| 131 |
+
G = nx.Graph()
|
| 132 |
+
name1 = chr(2344) + chr(123) + chr(6543)
|
| 133 |
+
name2 = chr(5543) + chr(1543) + chr(324)
|
| 134 |
+
G.add_edge(name1, "Radiohead", **{name2: 3})
|
| 135 |
+
|
| 136 |
+
fname = tmp_path / "adjlist.txt"
|
| 137 |
+
nx.write_multiline_adjlist(G, fname)
|
| 138 |
+
H = nx.read_multiline_adjlist(fname)
|
| 139 |
+
assert graphs_equal(G, H)
|
| 140 |
+
|
| 141 |
+
def test_latin1_err(self, tmp_path):
|
| 142 |
+
G = nx.Graph()
|
| 143 |
+
name1 = chr(2344) + chr(123) + chr(6543)
|
| 144 |
+
name2 = chr(5543) + chr(1543) + chr(324)
|
| 145 |
+
G.add_edge(name1, "Radiohead", **{name2: 3})
|
| 146 |
+
fname = tmp_path / "adjlist.txt"
|
| 147 |
+
with pytest.raises(UnicodeEncodeError):
|
| 148 |
+
nx.write_multiline_adjlist(G, fname, encoding="latin-1")
|
| 149 |
+
|
| 150 |
+
def test_latin1(self, tmp_path):
|
| 151 |
+
G = nx.Graph()
|
| 152 |
+
name1 = "Bj" + chr(246) + "rk"
|
| 153 |
+
name2 = chr(220) + "ber"
|
| 154 |
+
G.add_edge(name1, "Radiohead", **{name2: 3})
|
| 155 |
+
fname = tmp_path / "adjlist.txt"
|
| 156 |
+
nx.write_multiline_adjlist(G, fname, encoding="latin-1")
|
| 157 |
+
H = nx.read_multiline_adjlist(fname, encoding="latin-1")
|
| 158 |
+
assert graphs_equal(G, H)
|
| 159 |
+
|
| 160 |
+
def test_parse_adjlist(self):
|
| 161 |
+
lines = ["1 2 5", "2 3 4", "3 5", "4", "5"]
|
| 162 |
+
nx.parse_adjlist(lines, nodetype=int) # smoke test
|
| 163 |
+
with pytest.raises(TypeError):
|
| 164 |
+
nx.parse_adjlist(lines, nodetype="int")
|
| 165 |
+
lines = ["1 2 5", "2 b", "c"]
|
| 166 |
+
with pytest.raises(TypeError):
|
| 167 |
+
nx.parse_adjlist(lines, nodetype=int)
|
| 168 |
+
|
| 169 |
+
def test_adjlist_graph(self, tmp_path):
|
| 170 |
+
G = self.G
|
| 171 |
+
fname = tmp_path / "adjlist.txt"
|
| 172 |
+
nx.write_adjlist(G, fname)
|
| 173 |
+
H = nx.read_adjlist(fname)
|
| 174 |
+
H2 = nx.read_adjlist(fname)
|
| 175 |
+
assert H is not H2 # they should be different graphs
|
| 176 |
+
assert nodes_equal(list(H), list(G))
|
| 177 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 178 |
+
|
| 179 |
+
def test_adjlist_digraph(self, tmp_path):
|
| 180 |
+
G = self.DG
|
| 181 |
+
fname = tmp_path / "adjlist.txt"
|
| 182 |
+
nx.write_adjlist(G, fname)
|
| 183 |
+
H = nx.read_adjlist(fname, create_using=nx.DiGraph())
|
| 184 |
+
H2 = nx.read_adjlist(fname, create_using=nx.DiGraph())
|
| 185 |
+
assert H is not H2 # they should be different graphs
|
| 186 |
+
assert nodes_equal(list(H), list(G))
|
| 187 |
+
assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
|
| 188 |
+
|
| 189 |
+
def test_adjlist_integers(self, tmp_path):
|
| 190 |
+
fname = tmp_path / "adjlist.txt"
|
| 191 |
+
G = nx.convert_node_labels_to_integers(self.G)
|
| 192 |
+
nx.write_adjlist(G, fname)
|
| 193 |
+
H = nx.read_adjlist(fname, nodetype=int)
|
| 194 |
+
H2 = nx.read_adjlist(fname, nodetype=int)
|
| 195 |
+
assert H is not H2 # they should be different graphs
|
| 196 |
+
assert nodes_equal(list(H), list(G))
|
| 197 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 198 |
+
|
| 199 |
+
def test_adjlist_multigraph(self, tmp_path):
|
| 200 |
+
G = self.XG
|
| 201 |
+
fname = tmp_path / "adjlist.txt"
|
| 202 |
+
nx.write_adjlist(G, fname)
|
| 203 |
+
H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph())
|
| 204 |
+
H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph())
|
| 205 |
+
assert H is not H2 # they should be different graphs
|
| 206 |
+
assert nodes_equal(list(H), list(G))
|
| 207 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 208 |
+
|
| 209 |
+
def test_adjlist_multidigraph(self, tmp_path):
|
| 210 |
+
G = self.XDG
|
| 211 |
+
fname = tmp_path / "adjlist.txt"
|
| 212 |
+
nx.write_adjlist(G, fname)
|
| 213 |
+
H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph())
|
| 214 |
+
H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph())
|
| 215 |
+
assert H is not H2 # they should be different graphs
|
| 216 |
+
assert nodes_equal(list(H), list(G))
|
| 217 |
+
assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
|
| 218 |
+
|
| 219 |
+
def test_adjlist_delimiter(self):
|
| 220 |
+
fh = io.BytesIO()
|
| 221 |
+
G = nx.path_graph(3)
|
| 222 |
+
nx.write_adjlist(G, fh, delimiter=":")
|
| 223 |
+
fh.seek(0)
|
| 224 |
+
H = nx.read_adjlist(fh, nodetype=int, delimiter=":")
|
| 225 |
+
assert nodes_equal(list(H), list(G))
|
| 226 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class TestMultilineAdjlist:
|
| 230 |
+
@classmethod
|
| 231 |
+
def setup_class(cls):
|
| 232 |
+
cls.G = nx.Graph(name="test")
|
| 233 |
+
e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")]
|
| 234 |
+
cls.G.add_edges_from(e)
|
| 235 |
+
cls.G.add_node("g")
|
| 236 |
+
cls.DG = nx.DiGraph(cls.G)
|
| 237 |
+
cls.DG.remove_edge("b", "a")
|
| 238 |
+
cls.DG.remove_edge("b", "c")
|
| 239 |
+
cls.XG = nx.MultiGraph()
|
| 240 |
+
cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)])
|
| 241 |
+
cls.XDG = nx.MultiDiGraph(cls.XG)
|
| 242 |
+
|
| 243 |
+
def test_parse_multiline_adjlist(self):
|
| 244 |
+
lines = [
|
| 245 |
+
"1 2",
|
| 246 |
+
"b {'weight':3, 'name': 'Frodo'}",
|
| 247 |
+
"c {}",
|
| 248 |
+
"d 1",
|
| 249 |
+
"e {'weight':6, 'name': 'Saruman'}",
|
| 250 |
+
]
|
| 251 |
+
nx.parse_multiline_adjlist(iter(lines)) # smoke test
|
| 252 |
+
with pytest.raises(TypeError):
|
| 253 |
+
nx.parse_multiline_adjlist(iter(lines), nodetype=int)
|
| 254 |
+
nx.parse_multiline_adjlist(iter(lines), edgetype=str) # smoke test
|
| 255 |
+
with pytest.raises(TypeError):
|
| 256 |
+
nx.parse_multiline_adjlist(iter(lines), nodetype=int)
|
| 257 |
+
lines = ["1 a"]
|
| 258 |
+
with pytest.raises(TypeError):
|
| 259 |
+
nx.parse_multiline_adjlist(iter(lines))
|
| 260 |
+
lines = ["a 2"]
|
| 261 |
+
with pytest.raises(TypeError):
|
| 262 |
+
nx.parse_multiline_adjlist(iter(lines), nodetype=int)
|
| 263 |
+
lines = ["1 2"]
|
| 264 |
+
with pytest.raises(TypeError):
|
| 265 |
+
nx.parse_multiline_adjlist(iter(lines))
|
| 266 |
+
lines = ["1 2", "2 {}"]
|
| 267 |
+
with pytest.raises(TypeError):
|
| 268 |
+
nx.parse_multiline_adjlist(iter(lines))
|
| 269 |
+
|
| 270 |
+
def test_multiline_adjlist_graph(self, tmp_path):
|
| 271 |
+
G = self.G
|
| 272 |
+
fname = tmp_path / "adjlist.txt"
|
| 273 |
+
nx.write_multiline_adjlist(G, fname)
|
| 274 |
+
H = nx.read_multiline_adjlist(fname)
|
| 275 |
+
H2 = nx.read_multiline_adjlist(fname)
|
| 276 |
+
assert H is not H2 # they should be different graphs
|
| 277 |
+
assert nodes_equal(list(H), list(G))
|
| 278 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 279 |
+
|
| 280 |
+
def test_multiline_adjlist_digraph(self, tmp_path):
|
| 281 |
+
G = self.DG
|
| 282 |
+
fname = tmp_path / "adjlist.txt"
|
| 283 |
+
nx.write_multiline_adjlist(G, fname)
|
| 284 |
+
H = nx.read_multiline_adjlist(fname, create_using=nx.DiGraph())
|
| 285 |
+
H2 = nx.read_multiline_adjlist(fname, create_using=nx.DiGraph())
|
| 286 |
+
assert H is not H2 # they should be different graphs
|
| 287 |
+
assert nodes_equal(list(H), list(G))
|
| 288 |
+
assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
|
| 289 |
+
|
| 290 |
+
def test_multiline_adjlist_integers(self, tmp_path):
|
| 291 |
+
fname = tmp_path / "adjlist.txt"
|
| 292 |
+
G = nx.convert_node_labels_to_integers(self.G)
|
| 293 |
+
nx.write_multiline_adjlist(G, fname)
|
| 294 |
+
H = nx.read_multiline_adjlist(fname, nodetype=int)
|
| 295 |
+
H2 = nx.read_multiline_adjlist(fname, nodetype=int)
|
| 296 |
+
assert H is not H2 # they should be different graphs
|
| 297 |
+
assert nodes_equal(list(H), list(G))
|
| 298 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 299 |
+
|
| 300 |
+
def test_multiline_adjlist_multigraph(self, tmp_path):
|
| 301 |
+
G = self.XG
|
| 302 |
+
fname = tmp_path / "adjlist.txt"
|
| 303 |
+
nx.write_multiline_adjlist(G, fname)
|
| 304 |
+
H = nx.read_multiline_adjlist(fname, nodetype=int, create_using=nx.MultiGraph())
|
| 305 |
+
H2 = nx.read_multiline_adjlist(
|
| 306 |
+
fname, nodetype=int, create_using=nx.MultiGraph()
|
| 307 |
+
)
|
| 308 |
+
assert H is not H2 # they should be different graphs
|
| 309 |
+
assert nodes_equal(list(H), list(G))
|
| 310 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 311 |
+
|
| 312 |
+
def test_multiline_adjlist_multidigraph(self, tmp_path):
|
| 313 |
+
G = self.XDG
|
| 314 |
+
fname = tmp_path / "adjlist.txt"
|
| 315 |
+
nx.write_multiline_adjlist(G, fname)
|
| 316 |
+
H = nx.read_multiline_adjlist(
|
| 317 |
+
fname, nodetype=int, create_using=nx.MultiDiGraph()
|
| 318 |
+
)
|
| 319 |
+
H2 = nx.read_multiline_adjlist(
|
| 320 |
+
fname, nodetype=int, create_using=nx.MultiDiGraph()
|
| 321 |
+
)
|
| 322 |
+
assert H is not H2 # they should be different graphs
|
| 323 |
+
assert nodes_equal(list(H), list(G))
|
| 324 |
+
assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
|
| 325 |
+
|
| 326 |
+
def test_multiline_adjlist_delimiter(self):
|
| 327 |
+
fh = io.BytesIO()
|
| 328 |
+
G = nx.path_graph(3)
|
| 329 |
+
nx.write_multiline_adjlist(G, fh, delimiter=":")
|
| 330 |
+
fh.seek(0)
|
| 331 |
+
H = nx.read_multiline_adjlist(fh, nodetype=int, delimiter=":")
|
| 332 |
+
assert nodes_equal(list(H), list(G))
|
| 333 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@pytest.mark.parametrize(
|
| 337 |
+
("lines", "delim"),
|
| 338 |
+
(
|
| 339 |
+
(["1 2 5", "2 3 4", "3 5", "4", "5"], None), # No extra whitespace
|
| 340 |
+
(["1\t2\t5", "2\t3\t4", "3\t5", "4", "5"], "\t"), # tab-delimited
|
| 341 |
+
(
|
| 342 |
+
["1\t2\t5", "2\t3\t4", "3\t5\t", "4\t", "5"],
|
| 343 |
+
"\t",
|
| 344 |
+
), # tab-delimited, extra delims
|
| 345 |
+
(
|
| 346 |
+
["1\t2\t5", "2\t3\t4", "3\t5\t\t\n", "4\t", "5"],
|
| 347 |
+
"\t",
|
| 348 |
+
), # extra delim+newlines
|
| 349 |
+
),
|
| 350 |
+
)
|
| 351 |
+
def test_adjlist_rstrip_parsing(lines, delim):
|
| 352 |
+
"""Regression test related to gh-7465"""
|
| 353 |
+
expected = nx.Graph([(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)])
|
| 354 |
+
nx.utils.graphs_equal(nx.parse_adjlist(lines, delimiter=delim), expected)
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit tests for edgelists.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
import textwrap
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import networkx as nx
|
| 11 |
+
from networkx.utils import edges_equal, graphs_equal, nodes_equal
|
| 12 |
+
|
| 13 |
+
edges_no_data = textwrap.dedent(
|
| 14 |
+
"""
|
| 15 |
+
# comment line
|
| 16 |
+
1 2
|
| 17 |
+
# comment line
|
| 18 |
+
2 3
|
| 19 |
+
"""
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
edges_with_values = textwrap.dedent(
|
| 24 |
+
"""
|
| 25 |
+
# comment line
|
| 26 |
+
1 2 2.0
|
| 27 |
+
# comment line
|
| 28 |
+
2 3 3.0
|
| 29 |
+
"""
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
edges_with_weight = textwrap.dedent(
|
| 34 |
+
"""
|
| 35 |
+
# comment line
|
| 36 |
+
1 2 {'weight':2.0}
|
| 37 |
+
# comment line
|
| 38 |
+
2 3 {'weight':3.0}
|
| 39 |
+
"""
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
edges_with_multiple_attrs = textwrap.dedent(
|
| 44 |
+
"""
|
| 45 |
+
# comment line
|
| 46 |
+
1 2 {'weight':2.0, 'color':'green'}
|
| 47 |
+
# comment line
|
| 48 |
+
2 3 {'weight':3.0, 'color':'red'}
|
| 49 |
+
"""
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
edges_with_multiple_attrs_csv = textwrap.dedent(
|
| 54 |
+
"""
|
| 55 |
+
# comment line
|
| 56 |
+
1, 2, {'weight':2.0, 'color':'green'}
|
| 57 |
+
# comment line
|
| 58 |
+
2, 3, {'weight':3.0, 'color':'red'}
|
| 59 |
+
"""
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_expected_edges_weights = [(1, 2, {"weight": 2.0}), (2, 3, {"weight": 3.0})]
|
| 64 |
+
_expected_edges_multiattr = [
|
| 65 |
+
(1, 2, {"weight": 2.0, "color": "green"}),
|
| 66 |
+
(2, 3, {"weight": 3.0, "color": "red"}),
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pytest.mark.parametrize(
|
| 71 |
+
("data", "extra_kwargs"),
|
| 72 |
+
(
|
| 73 |
+
(edges_no_data, {}),
|
| 74 |
+
(edges_with_values, {}),
|
| 75 |
+
(edges_with_weight, {}),
|
| 76 |
+
(edges_with_multiple_attrs, {}),
|
| 77 |
+
(edges_with_multiple_attrs_csv, {"delimiter": ","}),
|
| 78 |
+
),
|
| 79 |
+
)
|
| 80 |
+
def test_read_edgelist_no_data(data, extra_kwargs):
|
| 81 |
+
bytesIO = io.BytesIO(data.encode("utf-8"))
|
| 82 |
+
G = nx.read_edgelist(bytesIO, nodetype=int, data=False, **extra_kwargs)
|
| 83 |
+
assert edges_equal(G.edges(), [(1, 2), (2, 3)])
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_read_weighted_edgelist():
|
| 87 |
+
bytesIO = io.BytesIO(edges_with_values.encode("utf-8"))
|
| 88 |
+
G = nx.read_weighted_edgelist(bytesIO, nodetype=int)
|
| 89 |
+
assert edges_equal(G.edges(data=True), _expected_edges_weights)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@pytest.mark.parametrize(
|
| 93 |
+
("data", "extra_kwargs", "expected"),
|
| 94 |
+
(
|
| 95 |
+
(edges_with_weight, {}, _expected_edges_weights),
|
| 96 |
+
(edges_with_multiple_attrs, {}, _expected_edges_multiattr),
|
| 97 |
+
(
|
| 98 |
+
edges_with_multiple_attrs_csv,
|
| 99 |
+
{"delimiter": ","},
|
| 100 |
+
_expected_edges_multiattr,
|
| 101 |
+
),
|
| 102 |
+
),
|
| 103 |
+
)
|
| 104 |
+
def test_read_edgelist_with_data(data, extra_kwargs, expected):
|
| 105 |
+
bytesIO = io.BytesIO(data.encode("utf-8"))
|
| 106 |
+
G = nx.read_edgelist(bytesIO, nodetype=int, **extra_kwargs)
|
| 107 |
+
assert edges_equal(G.edges(data=True), expected)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@pytest.fixture
|
| 111 |
+
def example_graph():
|
| 112 |
+
G = nx.Graph()
|
| 113 |
+
G.add_weighted_edges_from([(1, 2, 3.0), (2, 3, 27.0), (3, 4, 3.0)])
|
| 114 |
+
return G
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_parse_edgelist_no_data(example_graph):
|
| 118 |
+
G = example_graph
|
| 119 |
+
H = nx.parse_edgelist(["1 2", "2 3", "3 4"], nodetype=int)
|
| 120 |
+
assert nodes_equal(G.nodes, H.nodes)
|
| 121 |
+
assert edges_equal(G.edges, H.edges)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_parse_edgelist_with_data_dict(example_graph):
|
| 125 |
+
G = example_graph
|
| 126 |
+
H = nx.parse_edgelist(
|
| 127 |
+
["1 2 {'weight': 3}", "2 3 {'weight': 27}", "3 4 {'weight': 3.0}"], nodetype=int
|
| 128 |
+
)
|
| 129 |
+
assert nodes_equal(G.nodes, H.nodes)
|
| 130 |
+
assert edges_equal(G.edges(data=True), H.edges(data=True))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_parse_edgelist_with_data_list(example_graph):
|
| 134 |
+
G = example_graph
|
| 135 |
+
H = nx.parse_edgelist(
|
| 136 |
+
["1 2 3", "2 3 27", "3 4 3.0"], nodetype=int, data=(("weight", float),)
|
| 137 |
+
)
|
| 138 |
+
assert nodes_equal(G.nodes, H.nodes)
|
| 139 |
+
assert edges_equal(G.edges(data=True), H.edges(data=True))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def test_parse_edgelist():
|
| 143 |
+
# ignore lines with less than 2 nodes
|
| 144 |
+
lines = ["1;2", "2 3", "3 4"]
|
| 145 |
+
G = nx.parse_edgelist(lines, nodetype=int)
|
| 146 |
+
assert list(G.edges()) == [(2, 3), (3, 4)]
|
| 147 |
+
# unknown nodetype
|
| 148 |
+
with pytest.raises(TypeError, match="Failed to convert nodes"):
|
| 149 |
+
lines = ["1 2", "2 3", "3 4"]
|
| 150 |
+
nx.parse_edgelist(lines, nodetype="nope")
|
| 151 |
+
# lines have invalid edge format
|
| 152 |
+
with pytest.raises(TypeError, match="Failed to convert edge data"):
|
| 153 |
+
lines = ["1 2 3", "2 3", "3 4"]
|
| 154 |
+
nx.parse_edgelist(lines, nodetype=int)
|
| 155 |
+
# edge data and data_keys not the same length
|
| 156 |
+
with pytest.raises(IndexError, match="not the same length"):
|
| 157 |
+
lines = ["1 2 3", "2 3 27", "3 4 3.0"]
|
| 158 |
+
nx.parse_edgelist(
|
| 159 |
+
lines, nodetype=int, data=(("weight", float), ("capacity", int))
|
| 160 |
+
)
|
| 161 |
+
# edge data can't be converted to edge type
|
| 162 |
+
with pytest.raises(TypeError, match="Failed to convert"):
|
| 163 |
+
lines = ["1 2 't1'", "2 3 't3'", "3 4 't3'"]
|
| 164 |
+
nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_comments_None():
|
| 168 |
+
edgelist = ["node#1 node#2", "node#2 node#3"]
|
| 169 |
+
# comments=None supported to ignore all comment characters
|
| 170 |
+
G = nx.parse_edgelist(edgelist, comments=None)
|
| 171 |
+
H = nx.Graph([e.split(" ") for e in edgelist])
|
| 172 |
+
assert edges_equal(G.edges, H.edges)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class TestEdgelist:
|
| 176 |
+
@classmethod
|
| 177 |
+
def setup_class(cls):
|
| 178 |
+
cls.G = nx.Graph(name="test")
|
| 179 |
+
e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")]
|
| 180 |
+
cls.G.add_edges_from(e)
|
| 181 |
+
cls.G.add_node("g")
|
| 182 |
+
cls.DG = nx.DiGraph(cls.G)
|
| 183 |
+
cls.XG = nx.MultiGraph()
|
| 184 |
+
cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)])
|
| 185 |
+
cls.XDG = nx.MultiDiGraph(cls.XG)
|
| 186 |
+
|
| 187 |
+
def test_write_edgelist_1(self):
|
| 188 |
+
fh = io.BytesIO()
|
| 189 |
+
G = nx.Graph()
|
| 190 |
+
G.add_edges_from([(1, 2), (2, 3)])
|
| 191 |
+
nx.write_edgelist(G, fh, data=False)
|
| 192 |
+
fh.seek(0)
|
| 193 |
+
assert fh.read() == b"1 2\n2 3\n"
|
| 194 |
+
|
| 195 |
+
def test_write_edgelist_2(self):
|
| 196 |
+
fh = io.BytesIO()
|
| 197 |
+
G = nx.Graph()
|
| 198 |
+
G.add_edges_from([(1, 2), (2, 3)])
|
| 199 |
+
nx.write_edgelist(G, fh, data=True)
|
| 200 |
+
fh.seek(0)
|
| 201 |
+
assert fh.read() == b"1 2 {}\n2 3 {}\n"
|
| 202 |
+
|
| 203 |
+
def test_write_edgelist_3(self):
|
| 204 |
+
fh = io.BytesIO()
|
| 205 |
+
G = nx.Graph()
|
| 206 |
+
G.add_edge(1, 2, weight=2.0)
|
| 207 |
+
G.add_edge(2, 3, weight=3.0)
|
| 208 |
+
nx.write_edgelist(G, fh, data=True)
|
| 209 |
+
fh.seek(0)
|
| 210 |
+
assert fh.read() == b"1 2 {'weight': 2.0}\n2 3 {'weight': 3.0}\n"
|
| 211 |
+
|
| 212 |
+
def test_write_edgelist_4(self):
|
| 213 |
+
fh = io.BytesIO()
|
| 214 |
+
G = nx.Graph()
|
| 215 |
+
G.add_edge(1, 2, weight=2.0)
|
| 216 |
+
G.add_edge(2, 3, weight=3.0)
|
| 217 |
+
nx.write_edgelist(G, fh, data=[("weight")])
|
| 218 |
+
fh.seek(0)
|
| 219 |
+
assert fh.read() == b"1 2 2.0\n2 3 3.0\n"
|
| 220 |
+
|
| 221 |
+
def test_unicode(self, tmp_path):
|
| 222 |
+
G = nx.Graph()
|
| 223 |
+
name1 = chr(2344) + chr(123) + chr(6543)
|
| 224 |
+
name2 = chr(5543) + chr(1543) + chr(324)
|
| 225 |
+
G.add_edge(name1, "Radiohead", **{name2: 3})
|
| 226 |
+
fname = tmp_path / "el.txt"
|
| 227 |
+
nx.write_edgelist(G, fname)
|
| 228 |
+
H = nx.read_edgelist(fname)
|
| 229 |
+
assert graphs_equal(G, H)
|
| 230 |
+
|
| 231 |
+
def test_latin1_issue(self, tmp_path):
|
| 232 |
+
G = nx.Graph()
|
| 233 |
+
name1 = chr(2344) + chr(123) + chr(6543)
|
| 234 |
+
name2 = chr(5543) + chr(1543) + chr(324)
|
| 235 |
+
G.add_edge(name1, "Radiohead", **{name2: 3})
|
| 236 |
+
fname = tmp_path / "el.txt"
|
| 237 |
+
with pytest.raises(UnicodeEncodeError):
|
| 238 |
+
nx.write_edgelist(G, fname, encoding="latin-1")
|
| 239 |
+
|
| 240 |
+
def test_latin1(self, tmp_path):
|
| 241 |
+
G = nx.Graph()
|
| 242 |
+
name1 = "Bj" + chr(246) + "rk"
|
| 243 |
+
name2 = chr(220) + "ber"
|
| 244 |
+
G.add_edge(name1, "Radiohead", **{name2: 3})
|
| 245 |
+
fname = tmp_path / "el.txt"
|
| 246 |
+
|
| 247 |
+
nx.write_edgelist(G, fname, encoding="latin-1")
|
| 248 |
+
H = nx.read_edgelist(fname, encoding="latin-1")
|
| 249 |
+
assert graphs_equal(G, H)
|
| 250 |
+
|
| 251 |
+
def test_edgelist_graph(self, tmp_path):
|
| 252 |
+
G = self.G
|
| 253 |
+
fname = tmp_path / "el.txt"
|
| 254 |
+
nx.write_edgelist(G, fname)
|
| 255 |
+
H = nx.read_edgelist(fname)
|
| 256 |
+
H2 = nx.read_edgelist(fname)
|
| 257 |
+
assert H is not H2 # they should be different graphs
|
| 258 |
+
G.remove_node("g") # isolated nodes are not written in edgelist
|
| 259 |
+
assert nodes_equal(list(H), list(G))
|
| 260 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 261 |
+
|
| 262 |
+
def test_edgelist_digraph(self, tmp_path):
|
| 263 |
+
G = self.DG
|
| 264 |
+
fname = tmp_path / "el.txt"
|
| 265 |
+
nx.write_edgelist(G, fname)
|
| 266 |
+
H = nx.read_edgelist(fname, create_using=nx.DiGraph())
|
| 267 |
+
H2 = nx.read_edgelist(fname, create_using=nx.DiGraph())
|
| 268 |
+
assert H is not H2 # they should be different graphs
|
| 269 |
+
G.remove_node("g") # isolated nodes are not written in edgelist
|
| 270 |
+
assert nodes_equal(list(H), list(G))
|
| 271 |
+
assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
|
| 272 |
+
|
| 273 |
+
def test_edgelist_integers(self, tmp_path):
|
| 274 |
+
G = nx.convert_node_labels_to_integers(self.G)
|
| 275 |
+
fname = tmp_path / "el.txt"
|
| 276 |
+
nx.write_edgelist(G, fname)
|
| 277 |
+
H = nx.read_edgelist(fname, nodetype=int)
|
| 278 |
+
# isolated nodes are not written in edgelist
|
| 279 |
+
G.remove_nodes_from(list(nx.isolates(G)))
|
| 280 |
+
assert nodes_equal(list(H), list(G))
|
| 281 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 282 |
+
|
| 283 |
+
def test_edgelist_multigraph(self, tmp_path):
|
| 284 |
+
G = self.XG
|
| 285 |
+
fname = tmp_path / "el.txt"
|
| 286 |
+
nx.write_edgelist(G, fname)
|
| 287 |
+
H = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph())
|
| 288 |
+
H2 = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph())
|
| 289 |
+
assert H is not H2 # they should be different graphs
|
| 290 |
+
assert nodes_equal(list(H), list(G))
|
| 291 |
+
assert edges_equal(list(H.edges()), list(G.edges()))
|
| 292 |
+
|
| 293 |
+
def test_edgelist_multidigraph(self, tmp_path):
|
| 294 |
+
G = self.XDG
|
| 295 |
+
fname = tmp_path / "el.txt"
|
| 296 |
+
nx.write_edgelist(G, fname)
|
| 297 |
+
H = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiDiGraph())
|
| 298 |
+
H2 = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiDiGraph())
|
| 299 |
+
assert H is not H2 # they should be different graphs
|
| 300 |
+
assert nodes_equal(list(H), list(G))
|
| 301 |
+
assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def test_edgelist_consistent_strip_handling():
|
| 305 |
+
"""See gh-7462
|
| 306 |
+
|
| 307 |
+
Input when printed looks like::
|
| 308 |
+
|
| 309 |
+
1 2 3
|
| 310 |
+
2 3
|
| 311 |
+
3 4 3.0
|
| 312 |
+
|
| 313 |
+
Note the trailing \\t after the `3` in the second row, indicating an empty
|
| 314 |
+
data value.
|
| 315 |
+
"""
|
| 316 |
+
s = io.StringIO("1\t2\t3\n2\t3\t\n3\t4\t3.0")
|
| 317 |
+
G = nx.parse_edgelist(s, delimiter="\t", nodetype=int, data=[("value", str)])
|
| 318 |
+
assert sorted(G.edges(data="value")) == [(1, 2, "3"), (2, 3, ""), (3, 4, "3.0")]
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.py
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_gexf_v1_3(tmp_path):
|
| 10 |
+
"""'Basic graph' example from https://gexf.net/schema.html"""
|
| 11 |
+
# GEXF file from published example
|
| 12 |
+
data = """<?xml version="1.0" encoding="UTF-8"?>
|
| 13 |
+
<gexf xmlns="http://gexf.net/1.3" version="1.3">
|
| 14 |
+
<graph mode="static" defaultedgetype="directed">
|
| 15 |
+
<nodes>
|
| 16 |
+
<node id="0" label="Hello" />
|
| 17 |
+
<node id="1" label="Word" />
|
| 18 |
+
</nodes>
|
| 19 |
+
<edges>
|
| 20 |
+
<edge source="0" target="1" />
|
| 21 |
+
</edges>
|
| 22 |
+
</graph>
|
| 23 |
+
</gexf>
|
| 24 |
+
"""
|
| 25 |
+
with open(fname := (tmp_path / "basic.gexf"), "w") as fh:
|
| 26 |
+
fh.write(data)
|
| 27 |
+
|
| 28 |
+
# Expected output based on xml input
|
| 29 |
+
expected = nx.DiGraph([("0", "1")])
|
| 30 |
+
nx.set_node_attributes(expected, {"0": "Hello", "1": "Word"}, name="label")
|
| 31 |
+
expected.graph = {"mode": "static", "edge_default": {}}
|
| 32 |
+
|
| 33 |
+
# Load example with version explicitly set
|
| 34 |
+
G = nx.read_gexf(fname, version="1.3")
|
| 35 |
+
assert nx.utils.graphs_equal(G, expected)
|
| 36 |
+
|
| 37 |
+
# And with the "default" version
|
| 38 |
+
G = nx.read_gexf(fname)
|
| 39 |
+
assert nx.utils.graphs_equal(G, expected)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize("time_attr", ("start", "end"))
|
| 43 |
+
@pytest.mark.parametrize("dyn_attr", ("static", "dynamic"))
|
| 44 |
+
def test_dynamic_graph_has_timeformat(time_attr, dyn_attr, tmp_path):
|
| 45 |
+
"""Ensure that graphs which have a 'start' or 'stop' attribute get a
|
| 46 |
+
'timeformat' attribute upon parsing. See gh-7914."""
|
| 47 |
+
G = nx.MultiGraph(mode=dyn_attr)
|
| 48 |
+
G.add_node(0)
|
| 49 |
+
G.nodes[0][time_attr] = 1
|
| 50 |
+
# Write out
|
| 51 |
+
fname = tmp_path / "foo.gexf"
|
| 52 |
+
nx.write_gexf(G, fname)
|
| 53 |
+
# Check that timeformat is added to saved data
|
| 54 |
+
with open(fname) as fh:
|
| 55 |
+
assert 'timeformat="long"' in fh.read()
|
| 56 |
+
# Round-trip
|
| 57 |
+
H = nx.read_gexf(fname)
|
| 58 |
+
# If any node has a "start" or "end" attr, it is considered dynamic
|
| 59 |
+
# regardless of the graph "mode" attr
|
| 60 |
+
assert H.graph["mode"] == "dynamic"
|
| 61 |
+
assert nx.utils.nodes_equal(G.edges, H.edges)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class TestGEXF:
|
| 65 |
+
@classmethod
|
| 66 |
+
def setup_class(cls):
|
| 67 |
+
cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?>
|
| 68 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
|
| 69 |
+
<graph mode="static" defaultedgetype="directed">
|
| 70 |
+
<nodes>
|
| 71 |
+
<node id="0" label="Hello" />
|
| 72 |
+
<node id="1" label="Word" />
|
| 73 |
+
</nodes>
|
| 74 |
+
<edges>
|
| 75 |
+
<edge id="0" source="0" target="1" />
|
| 76 |
+
</edges>
|
| 77 |
+
</graph>
|
| 78 |
+
</gexf>
|
| 79 |
+
"""
|
| 80 |
+
cls.simple_directed_graph = nx.DiGraph()
|
| 81 |
+
cls.simple_directed_graph.add_node("0", label="Hello")
|
| 82 |
+
cls.simple_directed_graph.add_node("1", label="World")
|
| 83 |
+
cls.simple_directed_graph.add_edge("0", "1", id="0")
|
| 84 |
+
|
| 85 |
+
cls.simple_directed_fh = io.BytesIO(cls.simple_directed_data.encode("UTF-8"))
|
| 86 |
+
|
| 87 |
+
cls.attribute_data = """<?xml version="1.0" encoding="UTF-8"?>\
|
| 88 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.\
|
| 89 |
+
org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/\
|
| 90 |
+
1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">
|
| 91 |
+
<meta lastmodifieddate="2009-03-20">
|
| 92 |
+
<creator>Gephi.org</creator>
|
| 93 |
+
<description>A Web network</description>
|
| 94 |
+
</meta>
|
| 95 |
+
<graph defaultedgetype="directed">
|
| 96 |
+
<attributes class="node">
|
| 97 |
+
<attribute id="0" title="url" type="string"/>
|
| 98 |
+
<attribute id="1" title="indegree" type="integer"/>
|
| 99 |
+
<attribute id="2" title="frog" type="boolean">
|
| 100 |
+
<default>true</default>
|
| 101 |
+
</attribute>
|
| 102 |
+
</attributes>
|
| 103 |
+
<nodes>
|
| 104 |
+
<node id="0" label="Gephi">
|
| 105 |
+
<attvalues>
|
| 106 |
+
<attvalue for="0" value="https://gephi.org"/>
|
| 107 |
+
<attvalue for="1" value="1"/>
|
| 108 |
+
<attvalue for="2" value="false"/>
|
| 109 |
+
</attvalues>
|
| 110 |
+
</node>
|
| 111 |
+
<node id="1" label="Webatlas">
|
| 112 |
+
<attvalues>
|
| 113 |
+
<attvalue for="0" value="http://webatlas.fr"/>
|
| 114 |
+
<attvalue for="1" value="2"/>
|
| 115 |
+
<attvalue for="2" value="false"/>
|
| 116 |
+
</attvalues>
|
| 117 |
+
</node>
|
| 118 |
+
<node id="2" label="RTGI">
|
| 119 |
+
<attvalues>
|
| 120 |
+
<attvalue for="0" value="http://rtgi.fr"/>
|
| 121 |
+
<attvalue for="1" value="1"/>
|
| 122 |
+
<attvalue for="2" value="true"/>
|
| 123 |
+
</attvalues>
|
| 124 |
+
</node>
|
| 125 |
+
<node id="3" label="BarabasiLab">
|
| 126 |
+
<attvalues>
|
| 127 |
+
<attvalue for="0" value="http://barabasilab.com"/>
|
| 128 |
+
<attvalue for="1" value="1"/>
|
| 129 |
+
<attvalue for="2" value="true"/>
|
| 130 |
+
</attvalues>
|
| 131 |
+
</node>
|
| 132 |
+
</nodes>
|
| 133 |
+
<edges>
|
| 134 |
+
<edge id="0" source="0" target="1" label="foo"/>
|
| 135 |
+
<edge id="1" source="0" target="2"/>
|
| 136 |
+
<edge id="2" source="1" target="0"/>
|
| 137 |
+
<edge id="3" source="2" target="1"/>
|
| 138 |
+
<edge id="4" source="0" target="3"/>
|
| 139 |
+
</edges>
|
| 140 |
+
</graph>
|
| 141 |
+
</gexf>
|
| 142 |
+
"""
|
| 143 |
+
cls.attribute_graph = nx.DiGraph()
|
| 144 |
+
cls.attribute_graph.graph["node_default"] = {"frog": True}
|
| 145 |
+
cls.attribute_graph.add_node(
|
| 146 |
+
"0", label="Gephi", url="https://gephi.org", indegree=1, frog=False
|
| 147 |
+
)
|
| 148 |
+
cls.attribute_graph.add_node(
|
| 149 |
+
"1", label="Webatlas", url="http://webatlas.fr", indegree=2, frog=False
|
| 150 |
+
)
|
| 151 |
+
cls.attribute_graph.add_node(
|
| 152 |
+
"2", label="RTGI", url="http://rtgi.fr", indegree=1, frog=True
|
| 153 |
+
)
|
| 154 |
+
cls.attribute_graph.add_node(
|
| 155 |
+
"3",
|
| 156 |
+
label="BarabasiLab",
|
| 157 |
+
url="http://barabasilab.com",
|
| 158 |
+
indegree=1,
|
| 159 |
+
frog=True,
|
| 160 |
+
)
|
| 161 |
+
cls.attribute_graph.add_edge("0", "1", id="0", label="foo")
|
| 162 |
+
cls.attribute_graph.add_edge("0", "2", id="1")
|
| 163 |
+
cls.attribute_graph.add_edge("1", "0", id="2")
|
| 164 |
+
cls.attribute_graph.add_edge("2", "1", id="3")
|
| 165 |
+
cls.attribute_graph.add_edge("0", "3", id="4")
|
| 166 |
+
cls.attribute_fh = io.BytesIO(cls.attribute_data.encode("UTF-8"))
|
| 167 |
+
|
| 168 |
+
cls.simple_undirected_data = """<?xml version="1.0" encoding="UTF-8"?>
|
| 169 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
|
| 170 |
+
<graph mode="static" defaultedgetype="undirected">
|
| 171 |
+
<nodes>
|
| 172 |
+
<node id="0" label="Hello" />
|
| 173 |
+
<node id="1" label="Word" />
|
| 174 |
+
</nodes>
|
| 175 |
+
<edges>
|
| 176 |
+
<edge id="0" source="0" target="1" />
|
| 177 |
+
</edges>
|
| 178 |
+
</graph>
|
| 179 |
+
</gexf>
|
| 180 |
+
"""
|
| 181 |
+
cls.simple_undirected_graph = nx.Graph()
|
| 182 |
+
cls.simple_undirected_graph.add_node("0", label="Hello")
|
| 183 |
+
cls.simple_undirected_graph.add_node("1", label="World")
|
| 184 |
+
cls.simple_undirected_graph.add_edge("0", "1", id="0")
|
| 185 |
+
|
| 186 |
+
cls.simple_undirected_fh = io.BytesIO(
|
| 187 |
+
cls.simple_undirected_data.encode("UTF-8")
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def test_read_simple_directed_graphml(self):
|
| 191 |
+
G = self.simple_directed_graph
|
| 192 |
+
H = nx.read_gexf(self.simple_directed_fh)
|
| 193 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 194 |
+
assert sorted(G.edges()) == sorted(H.edges())
|
| 195 |
+
assert sorted(G.edges(data=True)) == sorted(H.edges(data=True))
|
| 196 |
+
self.simple_directed_fh.seek(0)
|
| 197 |
+
|
| 198 |
+
def test_write_read_simple_directed_graphml(self):
|
| 199 |
+
G = self.simple_directed_graph
|
| 200 |
+
fh = io.BytesIO()
|
| 201 |
+
nx.write_gexf(G, fh)
|
| 202 |
+
fh.seek(0)
|
| 203 |
+
H = nx.read_gexf(fh)
|
| 204 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 205 |
+
assert sorted(G.edges()) == sorted(H.edges())
|
| 206 |
+
assert sorted(G.edges(data=True)) == sorted(H.edges(data=True))
|
| 207 |
+
self.simple_directed_fh.seek(0)
|
| 208 |
+
|
| 209 |
+
def test_read_simple_undirected_graphml(self):
|
| 210 |
+
G = self.simple_undirected_graph
|
| 211 |
+
H = nx.read_gexf(self.simple_undirected_fh)
|
| 212 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 213 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 214 |
+
sorted(e) for e in H.edges()
|
| 215 |
+
)
|
| 216 |
+
self.simple_undirected_fh.seek(0)
|
| 217 |
+
|
| 218 |
+
def test_read_attribute_graphml(self):
|
| 219 |
+
G = self.attribute_graph
|
| 220 |
+
H = nx.read_gexf(self.attribute_fh)
|
| 221 |
+
assert sorted(G.nodes(True)) == sorted(H.nodes(data=True))
|
| 222 |
+
ge = sorted(G.edges(data=True))
|
| 223 |
+
he = sorted(H.edges(data=True))
|
| 224 |
+
for a, b in zip(ge, he):
|
| 225 |
+
assert a == b
|
| 226 |
+
self.attribute_fh.seek(0)
|
| 227 |
+
|
| 228 |
+
def test_directed_edge_in_undirected(self):
|
| 229 |
+
s = """<?xml version="1.0" encoding="UTF-8"?>
|
| 230 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
|
| 231 |
+
<graph mode="static" defaultedgetype="undirected" name="">
|
| 232 |
+
<nodes>
|
| 233 |
+
<node id="0" label="Hello" />
|
| 234 |
+
<node id="1" label="Word" />
|
| 235 |
+
</nodes>
|
| 236 |
+
<edges>
|
| 237 |
+
<edge id="0" source="0" target="1" type="directed"/>
|
| 238 |
+
</edges>
|
| 239 |
+
</graph>
|
| 240 |
+
</gexf>
|
| 241 |
+
"""
|
| 242 |
+
fh = io.BytesIO(s.encode("UTF-8"))
|
| 243 |
+
pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
|
| 244 |
+
|
| 245 |
+
def test_undirected_edge_in_directed(self):
|
| 246 |
+
s = """<?xml version="1.0" encoding="UTF-8"?>
|
| 247 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
|
| 248 |
+
<graph mode="static" defaultedgetype="directed" name="">
|
| 249 |
+
<nodes>
|
| 250 |
+
<node id="0" label="Hello" />
|
| 251 |
+
<node id="1" label="Word" />
|
| 252 |
+
</nodes>
|
| 253 |
+
<edges>
|
| 254 |
+
<edge id="0" source="0" target="1" type="undirected"/>
|
| 255 |
+
</edges>
|
| 256 |
+
</graph>
|
| 257 |
+
</gexf>
|
| 258 |
+
"""
|
| 259 |
+
fh = io.BytesIO(s.encode("UTF-8"))
|
| 260 |
+
pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
|
| 261 |
+
|
| 262 |
+
def test_key_raises(self):
|
| 263 |
+
s = """<?xml version="1.0" encoding="UTF-8"?>
|
| 264 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
|
| 265 |
+
<graph mode="static" defaultedgetype="directed" name="">
|
| 266 |
+
<nodes>
|
| 267 |
+
<node id="0" label="Hello">
|
| 268 |
+
<attvalues>
|
| 269 |
+
<attvalue for='0' value='1'/>
|
| 270 |
+
</attvalues>
|
| 271 |
+
</node>
|
| 272 |
+
<node id="1" label="Word" />
|
| 273 |
+
</nodes>
|
| 274 |
+
<edges>
|
| 275 |
+
<edge id="0" source="0" target="1" type="undirected"/>
|
| 276 |
+
</edges>
|
| 277 |
+
</graph>
|
| 278 |
+
</gexf>
|
| 279 |
+
"""
|
| 280 |
+
fh = io.BytesIO(s.encode("UTF-8"))
|
| 281 |
+
pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
|
| 282 |
+
|
| 283 |
+
def test_relabel(self):
|
| 284 |
+
s = """<?xml version="1.0" encoding="UTF-8"?>
|
| 285 |
+
<gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
|
| 286 |
+
<graph mode="static" defaultedgetype="directed" name="">
|
| 287 |
+
<nodes>
|
| 288 |
+
<node id="0" label="Hello" />
|
| 289 |
+
<node id="1" label="Word" />
|
| 290 |
+
</nodes>
|
| 291 |
+
<edges>
|
| 292 |
+
<edge id="0" source="0" target="1"/>
|
| 293 |
+
</edges>
|
| 294 |
+
</graph>
|
| 295 |
+
</gexf>
|
| 296 |
+
"""
|
| 297 |
+
fh = io.BytesIO(s.encode("UTF-8"))
|
| 298 |
+
G = nx.read_gexf(fh, relabel=True)
|
| 299 |
+
assert sorted(G.nodes()) == ["Hello", "Word"]
|
| 300 |
+
|
| 301 |
+
def test_default_attribute(self):
|
| 302 |
+
G = nx.Graph()
|
| 303 |
+
G.add_node(1, label="1", color="green")
|
| 304 |
+
nx.add_path(G, [0, 1, 2, 3])
|
| 305 |
+
G.add_edge(1, 2, foo=3)
|
| 306 |
+
G.graph["node_default"] = {"color": "yellow"}
|
| 307 |
+
G.graph["edge_default"] = {"foo": 7}
|
| 308 |
+
fh = io.BytesIO()
|
| 309 |
+
nx.write_gexf(G, fh)
|
| 310 |
+
fh.seek(0)
|
| 311 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 312 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 313 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 314 |
+
sorted(e) for e in H.edges()
|
| 315 |
+
)
|
| 316 |
+
# Reading a gexf graph always sets mode attribute to either
|
| 317 |
+
# 'static' or 'dynamic'. Remove the mode attribute from the
|
| 318 |
+
# read graph for the sake of comparing remaining attributes.
|
| 319 |
+
del H.graph["mode"]
|
| 320 |
+
assert G.graph == H.graph
|
| 321 |
+
|
| 322 |
+
def test_serialize_ints_to_strings(self):
|
| 323 |
+
G = nx.Graph()
|
| 324 |
+
G.add_node(1, id=7, label=77)
|
| 325 |
+
fh = io.BytesIO()
|
| 326 |
+
nx.write_gexf(G, fh)
|
| 327 |
+
fh.seek(0)
|
| 328 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 329 |
+
assert list(H) == [7]
|
| 330 |
+
assert H.nodes[7]["label"] == "77"
|
| 331 |
+
|
| 332 |
+
def test_write_with_node_attributes(self):
|
| 333 |
+
# Addresses #673.
|
| 334 |
+
G = nx.Graph()
|
| 335 |
+
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
|
| 336 |
+
for i in range(4):
|
| 337 |
+
G.nodes[i]["id"] = i
|
| 338 |
+
G.nodes[i]["label"] = i
|
| 339 |
+
G.nodes[i]["pid"] = i
|
| 340 |
+
G.nodes[i]["start"] = i
|
| 341 |
+
G.nodes[i]["end"] = i + 1
|
| 342 |
+
|
| 343 |
+
expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\
|
| 344 |
+
="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=\
|
| 345 |
+
"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/\
|
| 346 |
+
gexf.xsd" version="1.2">
|
| 347 |
+
<meta lastmodifieddate="{time.strftime("%Y-%m-%d")}">
|
| 348 |
+
<creator>NetworkX {nx.__version__}</creator>
|
| 349 |
+
</meta>
|
| 350 |
+
<graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long">
|
| 351 |
+
<nodes>
|
| 352 |
+
<node id="0" label="0" pid="0" start="0" end="1" />
|
| 353 |
+
<node id="1" label="1" pid="1" start="1" end="2" />
|
| 354 |
+
<node id="2" label="2" pid="2" start="2" end="3" />
|
| 355 |
+
<node id="3" label="3" pid="3" start="3" end="4" />
|
| 356 |
+
</nodes>
|
| 357 |
+
<edges>
|
| 358 |
+
<edge source="0" target="1" id="0" />
|
| 359 |
+
<edge source="1" target="2" id="1" />
|
| 360 |
+
<edge source="2" target="3" id="2" />
|
| 361 |
+
</edges>
|
| 362 |
+
</graph>
|
| 363 |
+
</gexf>"""
|
| 364 |
+
obtained = "\n".join(nx.generate_gexf(G))
|
| 365 |
+
assert expected == obtained
|
| 366 |
+
|
| 367 |
+
def test_edge_id_construct(self):
|
| 368 |
+
G = nx.Graph()
|
| 369 |
+
G.add_edges_from([(0, 1, {"id": 0}), (1, 2, {"id": 2}), (2, 3)])
|
| 370 |
+
|
| 371 |
+
expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\
|
| 372 |
+
="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.\
|
| 373 |
+
gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">
|
| 374 |
+
<meta lastmodifieddate="{time.strftime("%Y-%m-%d")}">
|
| 375 |
+
<creator>NetworkX {nx.__version__}</creator>
|
| 376 |
+
</meta>
|
| 377 |
+
<graph defaultedgetype="undirected" mode="static" name="">
|
| 378 |
+
<nodes>
|
| 379 |
+
<node id="0" label="0" />
|
| 380 |
+
<node id="1" label="1" />
|
| 381 |
+
<node id="2" label="2" />
|
| 382 |
+
<node id="3" label="3" />
|
| 383 |
+
</nodes>
|
| 384 |
+
<edges>
|
| 385 |
+
<edge source="0" target="1" id="0" />
|
| 386 |
+
<edge source="1" target="2" id="2" />
|
| 387 |
+
<edge source="2" target="3" id="1" />
|
| 388 |
+
</edges>
|
| 389 |
+
</graph>
|
| 390 |
+
</gexf>"""
|
| 391 |
+
|
| 392 |
+
obtained = "\n".join(nx.generate_gexf(G))
|
| 393 |
+
assert expected == obtained
|
| 394 |
+
|
| 395 |
+
def test_numpy_type(self):
|
| 396 |
+
np = pytest.importorskip("numpy")
|
| 397 |
+
G = nx.path_graph(4)
|
| 398 |
+
nx.set_node_attributes(G, {n: n for n in np.arange(4)}, "number")
|
| 399 |
+
G[0][1]["edge-number"] = np.float64(1.1)
|
| 400 |
+
|
| 401 |
+
expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft"\
|
| 402 |
+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation\
|
| 403 |
+
="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd"\
|
| 404 |
+
version="1.2">
|
| 405 |
+
<meta lastmodifieddate="{time.strftime("%Y-%m-%d")}">
|
| 406 |
+
<creator>NetworkX {nx.__version__}</creator>
|
| 407 |
+
</meta>
|
| 408 |
+
<graph defaultedgetype="undirected" mode="static" name="">
|
| 409 |
+
<attributes mode="static" class="edge">
|
| 410 |
+
<attribute id="1" title="edge-number" type="float" />
|
| 411 |
+
</attributes>
|
| 412 |
+
<attributes mode="static" class="node">
|
| 413 |
+
<attribute id="0" title="number" type="int" />
|
| 414 |
+
</attributes>
|
| 415 |
+
<nodes>
|
| 416 |
+
<node id="0" label="0">
|
| 417 |
+
<attvalues>
|
| 418 |
+
<attvalue for="0" value="0" />
|
| 419 |
+
</attvalues>
|
| 420 |
+
</node>
|
| 421 |
+
<node id="1" label="1">
|
| 422 |
+
<attvalues>
|
| 423 |
+
<attvalue for="0" value="1" />
|
| 424 |
+
</attvalues>
|
| 425 |
+
</node>
|
| 426 |
+
<node id="2" label="2">
|
| 427 |
+
<attvalues>
|
| 428 |
+
<attvalue for="0" value="2" />
|
| 429 |
+
</attvalues>
|
| 430 |
+
</node>
|
| 431 |
+
<node id="3" label="3">
|
| 432 |
+
<attvalues>
|
| 433 |
+
<attvalue for="0" value="3" />
|
| 434 |
+
</attvalues>
|
| 435 |
+
</node>
|
| 436 |
+
</nodes>
|
| 437 |
+
<edges>
|
| 438 |
+
<edge source="0" target="1" id="0">
|
| 439 |
+
<attvalues>
|
| 440 |
+
<attvalue for="1" value="1.1" />
|
| 441 |
+
</attvalues>
|
| 442 |
+
</edge>
|
| 443 |
+
<edge source="1" target="2" id="1" />
|
| 444 |
+
<edge source="2" target="3" id="2" />
|
| 445 |
+
</edges>
|
| 446 |
+
</graph>
|
| 447 |
+
</gexf>"""
|
| 448 |
+
obtained = "\n".join(nx.generate_gexf(G))
|
| 449 |
+
assert expected == obtained
|
| 450 |
+
|
| 451 |
+
def test_bool(self):
|
| 452 |
+
G = nx.Graph()
|
| 453 |
+
G.add_node(1, testattr=True)
|
| 454 |
+
fh = io.BytesIO()
|
| 455 |
+
nx.write_gexf(G, fh)
|
| 456 |
+
fh.seek(0)
|
| 457 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 458 |
+
assert H.nodes[1]["testattr"]
|
| 459 |
+
|
| 460 |
+
# Test for NaN, INF and -INF
|
| 461 |
+
def test_specials(self):
|
| 462 |
+
from math import isnan
|
| 463 |
+
|
| 464 |
+
inf, nan = float("inf"), float("nan")
|
| 465 |
+
G = nx.Graph()
|
| 466 |
+
G.add_node(1, testattr=inf, strdata="inf", key="a")
|
| 467 |
+
G.add_node(2, testattr=nan, strdata="nan", key="b")
|
| 468 |
+
G.add_node(3, testattr=-inf, strdata="-inf", key="c")
|
| 469 |
+
|
| 470 |
+
fh = io.BytesIO()
|
| 471 |
+
nx.write_gexf(G, fh)
|
| 472 |
+
fh.seek(0)
|
| 473 |
+
filetext = fh.read()
|
| 474 |
+
fh.seek(0)
|
| 475 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 476 |
+
|
| 477 |
+
assert b"INF" in filetext
|
| 478 |
+
assert b"NaN" in filetext
|
| 479 |
+
assert b"-INF" in filetext
|
| 480 |
+
|
| 481 |
+
assert H.nodes[1]["testattr"] == inf
|
| 482 |
+
assert isnan(H.nodes[2]["testattr"])
|
| 483 |
+
assert H.nodes[3]["testattr"] == -inf
|
| 484 |
+
|
| 485 |
+
assert H.nodes[1]["strdata"] == "inf"
|
| 486 |
+
assert H.nodes[2]["strdata"] == "nan"
|
| 487 |
+
assert H.nodes[3]["strdata"] == "-inf"
|
| 488 |
+
|
| 489 |
+
assert H.nodes[1]["networkx_key"] == "a"
|
| 490 |
+
assert H.nodes[2]["networkx_key"] == "b"
|
| 491 |
+
assert H.nodes[3]["networkx_key"] == "c"
|
| 492 |
+
|
| 493 |
+
def test_simple_list(self):
|
| 494 |
+
G = nx.Graph()
|
| 495 |
+
list_value = [(1, 2, 3), (9, 1, 2)]
|
| 496 |
+
G.add_node(1, key=list_value)
|
| 497 |
+
fh = io.BytesIO()
|
| 498 |
+
nx.write_gexf(G, fh)
|
| 499 |
+
fh.seek(0)
|
| 500 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 501 |
+
assert H.nodes[1]["networkx_key"] == list_value
|
| 502 |
+
|
| 503 |
+
def test_dynamic_mode(self):
|
| 504 |
+
G = nx.Graph()
|
| 505 |
+
G.add_node(1, label="1", color="green")
|
| 506 |
+
G.graph["mode"] = "dynamic"
|
| 507 |
+
fh = io.BytesIO()
|
| 508 |
+
nx.write_gexf(G, fh)
|
| 509 |
+
fh.seek(0)
|
| 510 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 511 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 512 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 513 |
+
sorted(e) for e in H.edges()
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
def test_multigraph_with_missing_attributes(self):
|
| 517 |
+
G = nx.MultiGraph()
|
| 518 |
+
G.add_node(0, label="1", color="green")
|
| 519 |
+
G.add_node(1, label="2", color="green")
|
| 520 |
+
G.add_edge(0, 1, id="0", weight=3, type="undirected", start=0, end=1)
|
| 521 |
+
G.add_edge(0, 1, id="1", label="foo", start=0, end=1)
|
| 522 |
+
G.add_edge(0, 1)
|
| 523 |
+
fh = io.BytesIO()
|
| 524 |
+
nx.write_gexf(G, fh)
|
| 525 |
+
fh.seek(0)
|
| 526 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 527 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 528 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 529 |
+
sorted(e) for e in H.edges()
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
def test_missing_viz_attributes(self):
|
| 533 |
+
G = nx.Graph()
|
| 534 |
+
G.add_node(0, label="1", color="green")
|
| 535 |
+
G.nodes[0]["viz"] = {"size": 54}
|
| 536 |
+
G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0}
|
| 537 |
+
G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256}
|
| 538 |
+
G.nodes[0]["viz"]["shape"] = "http://random.url"
|
| 539 |
+
G.nodes[0]["viz"]["thickness"] = 2
|
| 540 |
+
fh = io.BytesIO()
|
| 541 |
+
nx.write_gexf(G, fh, version="1.1draft")
|
| 542 |
+
fh.seek(0)
|
| 543 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 544 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 545 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 546 |
+
sorted(e) for e in H.edges()
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
# Test missing alpha value for version >draft1.1 - set default alpha value
|
| 550 |
+
# to 1.0 instead of `None` when writing for better general compatibility
|
| 551 |
+
fh = io.BytesIO()
|
| 552 |
+
# G.nodes[0]["viz"]["color"] does not have an alpha value explicitly defined
|
| 553 |
+
# so the default is used instead
|
| 554 |
+
nx.write_gexf(G, fh, version="1.2draft")
|
| 555 |
+
fh.seek(0)
|
| 556 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 557 |
+
assert H.nodes[0]["viz"]["color"]["a"] == 1.0
|
| 558 |
+
|
| 559 |
+
# Second graph for the other branch
|
| 560 |
+
G = nx.Graph()
|
| 561 |
+
G.add_node(0, label="1", color="green")
|
| 562 |
+
G.nodes[0]["viz"] = {"size": 54}
|
| 563 |
+
G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0}
|
| 564 |
+
G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256, "a": 0.5}
|
| 565 |
+
G.nodes[0]["viz"]["shape"] = "ftp://random.url"
|
| 566 |
+
G.nodes[0]["viz"]["thickness"] = 2
|
| 567 |
+
fh = io.BytesIO()
|
| 568 |
+
nx.write_gexf(G, fh)
|
| 569 |
+
fh.seek(0)
|
| 570 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 571 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 572 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 573 |
+
sorted(e) for e in H.edges()
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
def test_slice_and_spell(self):
|
| 577 |
+
# Test spell first, so version = 1.2
|
| 578 |
+
G = nx.Graph()
|
| 579 |
+
G.add_node(0, label="1", color="green")
|
| 580 |
+
G.nodes[0]["spells"] = [(1, 2)]
|
| 581 |
+
fh = io.BytesIO()
|
| 582 |
+
nx.write_gexf(G, fh)
|
| 583 |
+
fh.seek(0)
|
| 584 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 585 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 586 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 587 |
+
sorted(e) for e in H.edges()
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
G = nx.Graph()
|
| 591 |
+
G.add_node(0, label="1", color="green")
|
| 592 |
+
G.nodes[0]["slices"] = [(1, 2)]
|
| 593 |
+
fh = io.BytesIO()
|
| 594 |
+
nx.write_gexf(G, fh, version="1.1draft")
|
| 595 |
+
fh.seek(0)
|
| 596 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 597 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 598 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 599 |
+
sorted(e) for e in H.edges()
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
def test_add_parent(self):
|
| 603 |
+
G = nx.Graph()
|
| 604 |
+
G.add_node(0, label="1", color="green", parents=[1, 2])
|
| 605 |
+
fh = io.BytesIO()
|
| 606 |
+
nx.write_gexf(G, fh)
|
| 607 |
+
fh.seek(0)
|
| 608 |
+
H = nx.read_gexf(fh, node_type=int)
|
| 609 |
+
assert sorted(G.nodes()) == sorted(H.nodes())
|
| 610 |
+
assert sorted(sorted(e) for e in G.edges()) == sorted(
|
| 611 |
+
sorted(e) for e in H.edges()
|
| 612 |
+
)
|
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gml.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import codecs
|
| 2 |
+
import io
|
| 3 |
+
import math
|
| 4 |
+
from ast import literal_eval
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from textwrap import dedent
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import networkx as nx
|
| 11 |
+
from networkx.readwrite.gml import literal_destringizer, literal_stringizer
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestGraph:
|
| 15 |
+
@classmethod
|
| 16 |
+
def setup_class(cls):
|
| 17 |
+
cls.simple_data = """Creator "me"
|
| 18 |
+
Version "xx"
|
| 19 |
+
graph [
|
| 20 |
+
comment "This is a sample graph"
|
| 21 |
+
directed 1
|
| 22 |
+
IsPlanar 1
|
| 23 |
+
pos [ x 0 y 1 ]
|
| 24 |
+
node [
|
| 25 |
+
id 1
|
| 26 |
+
label "Node 1"
|
| 27 |
+
pos [ x 1 y 1 ]
|
| 28 |
+
]
|
| 29 |
+
node [
|
| 30 |
+
id 2
|
| 31 |
+
pos [ x 1 y 2 ]
|
| 32 |
+
label "Node 2"
|
| 33 |
+
]
|
| 34 |
+
node [
|
| 35 |
+
id 3
|
| 36 |
+
label "Node 3"
|
| 37 |
+
pos [ x 1 y 3 ]
|
| 38 |
+
]
|
| 39 |
+
edge [
|
| 40 |
+
source 1
|
| 41 |
+
target 2
|
| 42 |
+
label "Edge from node 1 to node 2"
|
| 43 |
+
color [line "blue" thickness 3]
|
| 44 |
+
|
| 45 |
+
]
|
| 46 |
+
edge [
|
| 47 |
+
source 2
|
| 48 |
+
target 3
|
| 49 |
+
label "Edge from node 2 to node 3"
|
| 50 |
+
]
|
| 51 |
+
edge [
|
| 52 |
+
source 3
|
| 53 |
+
target 1
|
| 54 |
+
label "Edge from node 3 to node 1"
|
| 55 |
+
]
|
| 56 |
+
]
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def test_parse_gml_cytoscape_bug(self):
|
| 60 |
+
# example from issue #321, originally #324 in trac
|
| 61 |
+
cytoscape_example = """
|
| 62 |
+
Creator "Cytoscape"
|
| 63 |
+
Version 1.0
|
| 64 |
+
graph [
|
| 65 |
+
node [
|
| 66 |
+
root_index -3
|
| 67 |
+
id -3
|
| 68 |
+
graphics [
|
| 69 |
+
x -96.0
|
| 70 |
+
y -67.0
|
| 71 |
+
w 40.0
|
| 72 |
+
h 40.0
|
| 73 |
+
fill "#ff9999"
|
| 74 |
+
type "ellipse"
|
| 75 |
+
outline "#666666"
|
| 76 |
+
outline_width 1.5
|
| 77 |
+
]
|
| 78 |
+
label "node2"
|
| 79 |
+
]
|
| 80 |
+
node [
|
| 81 |
+
root_index -2
|
| 82 |
+
id -2
|
| 83 |
+
graphics [
|
| 84 |
+
x 63.0
|
| 85 |
+
y 37.0
|
| 86 |
+
w 40.0
|
| 87 |
+
h 40.0
|
| 88 |
+
fill "#ff9999"
|
| 89 |
+
type "ellipse"
|
| 90 |
+
outline "#666666"
|
| 91 |
+
outline_width 1.5
|
| 92 |
+
]
|
| 93 |
+
label "node1"
|
| 94 |
+
]
|
| 95 |
+
node [
|
| 96 |
+
root_index -1
|
| 97 |
+
id -1
|
| 98 |
+
graphics [
|
| 99 |
+
x -31.0
|
| 100 |
+
y -17.0
|
| 101 |
+
w 40.0
|
| 102 |
+
h 40.0
|
| 103 |
+
fill "#ff9999"
|
| 104 |
+
type "ellipse"
|
| 105 |
+
outline "#666666"
|
| 106 |
+
outline_width 1.5
|
| 107 |
+
]
|
| 108 |
+
label "node0"
|
| 109 |
+
]
|
| 110 |
+
edge [
|
| 111 |
+
root_index -2
|
| 112 |
+
target -2
|
| 113 |
+
source -1
|
| 114 |
+
graphics [
|
| 115 |
+
width 1.5
|
| 116 |
+
fill "#0000ff"
|
| 117 |
+
type "line"
|
| 118 |
+
Line [
|
| 119 |
+
]
|
| 120 |
+
source_arrow 0
|
| 121 |
+
target_arrow 3
|
| 122 |
+
]
|
| 123 |
+
label "DirectedEdge"
|
| 124 |
+
]
|
| 125 |
+
edge [
|
| 126 |
+
root_index -1
|
| 127 |
+
target -1
|
| 128 |
+
source -3
|
| 129 |
+
graphics [
|
| 130 |
+
width 1.5
|
| 131 |
+
fill "#0000ff"
|
| 132 |
+
type "line"
|
| 133 |
+
Line [
|
| 134 |
+
]
|
| 135 |
+
source_arrow 0
|
| 136 |
+
target_arrow 3
|
| 137 |
+
]
|
| 138 |
+
label "DirectedEdge"
|
| 139 |
+
]
|
| 140 |
+
]
|
| 141 |
+
"""
|
| 142 |
+
nx.parse_gml(cytoscape_example)
|
| 143 |
+
|
| 144 |
+
def test_parse_gml(self):
|
| 145 |
+
G = nx.parse_gml(self.simple_data, label="label")
|
| 146 |
+
assert sorted(G.nodes()) == ["Node 1", "Node 2", "Node 3"]
|
| 147 |
+
assert sorted(G.edges()) == [
|
| 148 |
+
("Node 1", "Node 2"),
|
| 149 |
+
("Node 2", "Node 3"),
|
| 150 |
+
("Node 3", "Node 1"),
|
| 151 |
+
]
|
| 152 |
+
|
| 153 |
+
assert sorted(G.edges(data=True)) == [
|
| 154 |
+
(
|
| 155 |
+
"Node 1",
|
| 156 |
+
"Node 2",
|
| 157 |
+
{
|
| 158 |
+
"color": {"line": "blue", "thickness": 3},
|
| 159 |
+
"label": "Edge from node 1 to node 2",
|
| 160 |
+
},
|
| 161 |
+
),
|
| 162 |
+
("Node 2", "Node 3", {"label": "Edge from node 2 to node 3"}),
|
| 163 |
+
("Node 3", "Node 1", {"label": "Edge from node 3 to node 1"}),
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
def test_read_gml(self, tmp_path):
|
| 167 |
+
fname = tmp_path / "test.gml"
|
| 168 |
+
with open(fname, "w") as fh:
|
| 169 |
+
fh.write(self.simple_data)
|
| 170 |
+
Gin = nx.read_gml(fname, label="label")
|
| 171 |
+
G = nx.parse_gml(self.simple_data, label="label")
|
| 172 |
+
assert sorted(G.nodes(data=True)) == sorted(Gin.nodes(data=True))
|
| 173 |
+
assert sorted(G.edges(data=True)) == sorted(Gin.edges(data=True))
|
| 174 |
+
|
| 175 |
+
def test_labels_are_strings(self):
|
| 176 |
+
# GML requires labels to be strings (i.e., in quotes)
|
| 177 |
+
answer = """graph [
|
| 178 |
+
node [
|
| 179 |
+
id 0
|
| 180 |
+
label "1203"
|
| 181 |
+
]
|
| 182 |
+
]"""
|
| 183 |
+
G = nx.Graph()
|
| 184 |
+
G.add_node(1203)
|
| 185 |
+
data = "\n".join(nx.generate_gml(G, stringizer=literal_stringizer))
|
| 186 |
+
assert data == answer
|
| 187 |
+
|
| 188 |
+
def test_relabel_duplicate(self):
|
| 189 |
+
data = """
|
| 190 |
+
graph
|
| 191 |
+
[
|
| 192 |
+
label ""
|
| 193 |
+
directed 1
|
| 194 |
+
node
|
| 195 |
+
[
|
| 196 |
+
id 0
|
| 197 |
+
label "same"
|
| 198 |
+
]
|
| 199 |
+
node
|
| 200 |
+
[
|
| 201 |
+
id 1
|
| 202 |
+
label "same"
|
| 203 |
+
]
|
| 204 |
+
]
|
| 205 |
+
"""
|
| 206 |
+
fh = io.BytesIO(data.encode("UTF-8"))
|
| 207 |
+
fh.seek(0)
|
| 208 |
+
pytest.raises(nx.NetworkXError, nx.read_gml, fh, label="label")
|
| 209 |
+
|
| 210 |
+
@pytest.mark.parametrize("stringizer", (None, literal_stringizer))
|
| 211 |
+
def test_tuplelabels(self, stringizer):
|
| 212 |
+
# https://github.com/networkx/networkx/pull/1048
|
| 213 |
+
# Writing tuple labels to GML failed.
|
| 214 |
+
G = nx.Graph()
|
| 215 |
+
G.add_edge((0, 1), (1, 0))
|
| 216 |
+
data = "\n".join(nx.generate_gml(G, stringizer=stringizer))
|
| 217 |
+
answer = """graph [
|
| 218 |
+
node [
|
| 219 |
+
id 0
|
| 220 |
+
label "(0,1)"
|
| 221 |
+
]
|
| 222 |
+
node [
|
| 223 |
+
id 1
|
| 224 |
+
label "(1,0)"
|
| 225 |
+
]
|
| 226 |
+
edge [
|
| 227 |
+
source 0
|
| 228 |
+
target 1
|
| 229 |
+
]
|
| 230 |
+
]"""
|
| 231 |
+
assert data == answer
|
| 232 |
+
|
| 233 |
+
def test_quotes(self, tmp_path):
|
| 234 |
+
# https://github.com/networkx/networkx/issues/1061
|
| 235 |
+
# Encoding quotes as HTML entities.
|
| 236 |
+
G = nx.path_graph(1)
|
| 237 |
+
G.name = "path_graph(1)"
|
| 238 |
+
attr = 'This is "quoted" and this is a copyright: ' + chr(169)
|
| 239 |
+
G.nodes[0]["demo"] = attr
|
| 240 |
+
with open(tmp_path / "test.gml", "w+b") as fobj:
|
| 241 |
+
nx.write_gml(G, fobj)
|
| 242 |
+
fobj.seek(0)
|
| 243 |
+
# Should be bytes in 2.x and 3.x
|
| 244 |
+
data = fobj.read().strip().decode("ascii")
|
| 245 |
+
answer = """graph [
|
| 246 |
+
name "path_graph(1)"
|
| 247 |
+
node [
|
| 248 |
+
id 0
|
| 249 |
+
label "0"
|
| 250 |
+
demo "This is "quoted" and this is a copyright: ©"
|
| 251 |
+
]
|
| 252 |
+
]"""
|
| 253 |
+
assert data == answer
|
| 254 |
+
|
| 255 |
+
def test_unicode_node(self, tmp_path):
|
| 256 |
+
node = "node" + chr(169)
|
| 257 |
+
G = nx.Graph()
|
| 258 |
+
G.add_node(node)
|
| 259 |
+
with open(tmp_path / "test.gml", "w+b") as fobj:
|
| 260 |
+
nx.write_gml(G, fobj)
|
| 261 |
+
fobj.seek(0)
|
| 262 |
+
# Should be bytes in 2.x and 3.x
|
| 263 |
+
data = fobj.read().strip().decode("ascii")
|
| 264 |
+
answer = """graph [
|
| 265 |
+
node [
|
| 266 |
+
id 0
|
| 267 |
+
label "node©"
|
| 268 |
+
]
|
| 269 |
+
]"""
|
| 270 |
+
assert data == answer
|
| 271 |
+
|
| 272 |
+
def test_float_label(self, tmp_path):
|
| 273 |
+
node = 1.0
|
| 274 |
+
G = nx.Graph()
|
| 275 |
+
G.add_node(node)
|
| 276 |
+
with open(tmp_path / "test.gml", "w+b") as fobj:
|
| 277 |
+
nx.write_gml(G, fobj)
|
| 278 |
+
fobj.seek(0)
|
| 279 |
+
# Should be bytes in 2.x and 3.x
|
| 280 |
+
data = fobj.read().strip().decode("ascii")
|
| 281 |
+
answer = """graph [
|
| 282 |
+
node [
|
| 283 |
+
id 0
|
| 284 |
+
label "1.0"
|
| 285 |
+
]
|
| 286 |
+
]"""
|
| 287 |
+
assert data == answer
|
| 288 |
+
|
| 289 |
+
def test_special_float_label(self, tmp_path):
|
| 290 |
+
special_floats = [float("nan"), float("+inf"), float("-inf")]
|
| 291 |
+
try:
|
| 292 |
+
import numpy as np
|
| 293 |
+
|
| 294 |
+
special_floats += [np.nan, np.inf, np.inf * -1]
|
| 295 |
+
except ImportError:
|
| 296 |
+
special_floats += special_floats
|
| 297 |
+
|
| 298 |
+
G = nx.cycle_graph(len(special_floats))
|
| 299 |
+
attrs = dict(enumerate(special_floats))
|
| 300 |
+
nx.set_node_attributes(G, attrs, "nodefloat")
|
| 301 |
+
edges = list(G.edges)
|
| 302 |
+
attrs = {edges[i]: value for i, value in enumerate(special_floats)}
|
| 303 |
+
nx.set_edge_attributes(G, attrs, "edgefloat")
|
| 304 |
+
|
| 305 |
+
with open(tmp_path / "test.gml", "w+b") as fobj:
|
| 306 |
+
nx.write_gml(G, fobj)
|
| 307 |
+
fobj.seek(0)
|
| 308 |
+
# Should be bytes in 2.x and 3.x
|
| 309 |
+
data = fobj.read().strip().decode("ascii")
|
| 310 |
+
answer = """graph [
|
| 311 |
+
node [
|
| 312 |
+
id 0
|
| 313 |
+
label "0"
|
| 314 |
+
nodefloat NAN
|
| 315 |
+
]
|
| 316 |
+
node [
|
| 317 |
+
id 1
|
| 318 |
+
label "1"
|
| 319 |
+
nodefloat +INF
|
| 320 |
+
]
|
| 321 |
+
node [
|
| 322 |
+
id 2
|
| 323 |
+
label "2"
|
| 324 |
+
nodefloat -INF
|
| 325 |
+
]
|
| 326 |
+
node [
|
| 327 |
+
id 3
|
| 328 |
+
label "3"
|
| 329 |
+
nodefloat NAN
|
| 330 |
+
]
|
| 331 |
+
node [
|
| 332 |
+
id 4
|
| 333 |
+
label "4"
|
| 334 |
+
nodefloat +INF
|
| 335 |
+
]
|
| 336 |
+
node [
|
| 337 |
+
id 5
|
| 338 |
+
label "5"
|
| 339 |
+
nodefloat -INF
|
| 340 |
+
]
|
| 341 |
+
edge [
|
| 342 |
+
source 0
|
| 343 |
+
target 1
|
| 344 |
+
edgefloat NAN
|
| 345 |
+
]
|
| 346 |
+
edge [
|
| 347 |
+
source 0
|
| 348 |
+
target 5
|
| 349 |
+
edgefloat +INF
|
| 350 |
+
]
|
| 351 |
+
edge [
|
| 352 |
+
source 1
|
| 353 |
+
target 2
|
| 354 |
+
edgefloat -INF
|
| 355 |
+
]
|
| 356 |
+
edge [
|
| 357 |
+
source 2
|
| 358 |
+
target 3
|
| 359 |
+
edgefloat NAN
|
| 360 |
+
]
|
| 361 |
+
edge [
|
| 362 |
+
source 3
|
| 363 |
+
target 4
|
| 364 |
+
edgefloat +INF
|
| 365 |
+
]
|
| 366 |
+
edge [
|
| 367 |
+
source 4
|
| 368 |
+
target 5
|
| 369 |
+
edgefloat -INF
|
| 370 |
+
]
|
| 371 |
+
]"""
|
| 372 |
+
assert data == answer
|
| 373 |
+
|
| 374 |
+
fobj.seek(0)
|
| 375 |
+
graph = nx.read_gml(fobj)
|
| 376 |
+
for indx, value in enumerate(special_floats):
|
| 377 |
+
node_value = graph.nodes[str(indx)]["nodefloat"]
|
| 378 |
+
if math.isnan(value):
|
| 379 |
+
assert math.isnan(node_value)
|
| 380 |
+
else:
|
| 381 |
+
assert node_value == value
|
| 382 |
+
|
| 383 |
+
edge = edges[indx]
|
| 384 |
+
string_edge = (str(edge[0]), str(edge[1]))
|
| 385 |
+
edge_value = graph.edges[string_edge]["edgefloat"]
|
| 386 |
+
if math.isnan(value):
|
| 387 |
+
assert math.isnan(edge_value)
|
| 388 |
+
else:
|
| 389 |
+
assert edge_value == value
|
| 390 |
+
|
| 391 |
+
def test_name(self):
|
| 392 |
+
G = nx.parse_gml('graph [ name "x" node [ id 0 label "x" ] ]')
|
| 393 |
+
assert "x" == G.graph["name"]
|
| 394 |
+
G = nx.parse_gml('graph [ node [ id 0 label "x" ] ]')
|
| 395 |
+
assert "" == G.name
|
| 396 |
+
assert "name" not in G.graph
|
| 397 |
+
|
| 398 |
+
def test_graph_types(self):
|
| 399 |
+
for directed in [None, False, True]:
|
| 400 |
+
for multigraph in [None, False, True]:
|
| 401 |
+
gml = "graph ["
|
| 402 |
+
if directed is not None:
|
| 403 |
+
gml += " directed " + str(int(directed))
|
| 404 |
+
if multigraph is not None:
|
| 405 |
+
gml += " multigraph " + str(int(multigraph))
|
| 406 |
+
gml += ' node [ id 0 label "0" ]'
|
| 407 |
+
gml += " edge [ source 0 target 0 ]"
|
| 408 |
+
gml += " ]"
|
| 409 |
+
G = nx.parse_gml(gml)
|
| 410 |
+
assert bool(directed) == G.is_directed()
|
| 411 |
+
assert bool(multigraph) == G.is_multigraph()
|
| 412 |
+
gml = "graph [\n"
|
| 413 |
+
if directed is True:
|
| 414 |
+
gml += " directed 1\n"
|
| 415 |
+
if multigraph is True:
|
| 416 |
+
gml += " multigraph 1\n"
|
| 417 |
+
gml += """ node [
|
| 418 |
+
id 0
|
| 419 |
+
label "0"
|
| 420 |
+
]
|
| 421 |
+
edge [
|
| 422 |
+
source 0
|
| 423 |
+
target 0
|
| 424 |
+
"""
|
| 425 |
+
if multigraph:
|
| 426 |
+
gml += " key 0\n"
|
| 427 |
+
gml += " ]\n]"
|
| 428 |
+
assert gml == "\n".join(nx.generate_gml(G))
|
| 429 |
+
|
| 430 |
+
def test_data_types(self):
|
| 431 |
+
data = [
|
| 432 |
+
True,
|
| 433 |
+
False,
|
| 434 |
+
10**20,
|
| 435 |
+
-2e33,
|
| 436 |
+
"'",
|
| 437 |
+
'"&&&""',
|
| 438 |
+
[{(b"\xfd",): "\x7f", chr(0x4444): (1, 2)}, (2, "3")],
|
| 439 |
+
]
|
| 440 |
+
data.append(chr(0x14444))
|
| 441 |
+
data.append(literal_eval("{2.3j, 1 - 2.3j, ()}"))
|
| 442 |
+
G = nx.Graph()
|
| 443 |
+
G.name = data
|
| 444 |
+
G.graph["data"] = data
|
| 445 |
+
G.add_node(0, int=-1, data={"data": data})
|
| 446 |
+
G.add_edge(0, 0, float=-2.5, data=data)
|
| 447 |
+
gml = "\n".join(nx.generate_gml(G, stringizer=literal_stringizer))
|
| 448 |
+
G = nx.parse_gml(gml, destringizer=literal_destringizer)
|
| 449 |
+
assert data == G.name
|
| 450 |
+
assert {"name": data, "data": data} == G.graph
|
| 451 |
+
assert list(G.nodes(data=True)) == [(0, {"int": -1, "data": {"data": data}})]
|
| 452 |
+
assert list(G.edges(data=True)) == [(0, 0, {"float": -2.5, "data": data})]
|
| 453 |
+
G = nx.Graph()
|
| 454 |
+
G.graph["data"] = "frozenset([1, 2, 3])"
|
| 455 |
+
G = nx.parse_gml(nx.generate_gml(G), destringizer=literal_eval)
|
| 456 |
+
assert G.graph["data"] == "frozenset([1, 2, 3])"
|
| 457 |
+
|
| 458 |
+
def test_escape_unescape(self):
|
| 459 |
+
gml = """graph [
|
| 460 |
+
name "&"䑄��&unknown;"
|
| 461 |
+
]"""
|
| 462 |
+
G = nx.parse_gml(gml)
|
| 463 |
+
assert (
|
| 464 |
+
'&"\x0f' + chr(0x4444) + "��&unknown;"
|
| 465 |
+
== G.name
|
| 466 |
+
)
|
| 467 |
+
gml = "\n".join(nx.generate_gml(G))
|
| 468 |
+
alnu = "#1234567890;&#x1234567890abcdef"
|
| 469 |
+
answer = (
|
| 470 |
+
"""graph [
|
| 471 |
+
name "&"䑄&"""
|
| 472 |
+
+ alnu
|
| 473 |
+
+ """;&unknown;"
|
| 474 |
+
]"""
|
| 475 |
+
)
|
| 476 |
+
assert answer == gml
|
| 477 |
+
|
| 478 |
+
def test_exceptions(self, tmp_path):
|
| 479 |
+
pytest.raises(ValueError, literal_destringizer, "(")
|
| 480 |
+
pytest.raises(ValueError, literal_destringizer, "frozenset([1, 2, 3])")
|
| 481 |
+
pytest.raises(ValueError, literal_destringizer, literal_destringizer)
|
| 482 |
+
pytest.raises(ValueError, literal_stringizer, frozenset([1, 2, 3]))
|
| 483 |
+
pytest.raises(ValueError, literal_stringizer, literal_stringizer)
|
| 484 |
+
with open(tmp_path / "test.gml", "w+b") as f:
|
| 485 |
+
f.write(codecs.BOM_UTF8 + b"graph[]")
|
| 486 |
+
f.seek(0)
|
| 487 |
+
pytest.raises(nx.NetworkXError, nx.read_gml, f)
|
| 488 |
+
|
| 489 |
+
def assert_parse_error(gml):
|
| 490 |
+
pytest.raises(nx.NetworkXError, nx.parse_gml, gml)
|
| 491 |
+
|
| 492 |
+
assert_parse_error(["graph [\n\n", "]"])
|
| 493 |
+
assert_parse_error("")
|
| 494 |
+
assert_parse_error('Creator ""')
|
| 495 |
+
assert_parse_error("0")
|
| 496 |
+
assert_parse_error("graph ]")
|
| 497 |
+
assert_parse_error("graph [ 1 ]")
|
| 498 |
+
assert_parse_error("graph [ 1.E+2 ]")
|
| 499 |
+
assert_parse_error('graph [ "A" ]')
|
| 500 |
+
assert_parse_error("graph [ ] graph ]")
|
| 501 |
+
assert_parse_error("graph [ ] graph [ ]")
|
| 502 |
+
assert_parse_error("graph [ data [1, 2, 3] ]")
|
| 503 |
+
assert_parse_error("graph [ node [ ] ]")
|
| 504 |
+
assert_parse_error("graph [ node [ id 0 ] ]")
|
| 505 |
+
nx.parse_gml('graph [ node [ id "a" ] ]', label="id")
|
| 506 |
+
assert_parse_error("graph [ node [ id 0 label 0 ] node [ id 0 label 1 ] ]")
|
| 507 |
+
assert_parse_error("graph [ node [ id 0 label 0 ] node [ id 1 label 0 ] ]")
|
| 508 |
+
assert_parse_error("graph [ node [ id 0 label 0 ] edge [ ] ]")
|
| 509 |
+
assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 0 ] ]")
|
| 510 |
+
nx.parse_gml("graph [edge [ source 0 target 0 ] node [ id 0 label 0 ] ]")
|
| 511 |
+
assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 1 target 0 ] ]")
|
| 512 |
+
assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 0 target 1 ] ]")
|
| 513 |
+
assert_parse_error(
|
| 514 |
+
"graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
|
| 515 |
+
"edge [ source 0 target 1 ] edge [ source 1 target 0 ] ]"
|
| 516 |
+
)
|
| 517 |
+
nx.parse_gml(
|
| 518 |
+
"graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
|
| 519 |
+
"edge [ source 0 target 1 ] edge [ source 1 target 0 ] "
|
| 520 |
+
"directed 1 ]"
|
| 521 |
+
)
|
| 522 |
+
nx.parse_gml(
|
| 523 |
+
"graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
|
| 524 |
+
"edge [ source 0 target 1 ] edge [ source 0 target 1 ]"
|
| 525 |
+
"multigraph 1 ]"
|
| 526 |
+
)
|
| 527 |
+
nx.parse_gml(
|
| 528 |
+
"graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
|
| 529 |
+
"edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 ]"
|
| 530 |
+
"multigraph 1 ]"
|
| 531 |
+
)
|
| 532 |
+
assert_parse_error(
|
| 533 |
+
"graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
|
| 534 |
+
"edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 0 ]"
|
| 535 |
+
"multigraph 1 ]"
|
| 536 |
+
)
|
| 537 |
+
nx.parse_gml(
|
| 538 |
+
"graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
|
| 539 |
+
"edge [ source 0 target 1 key 0 ] edge [ source 1 target 0 key 0 ]"
|
| 540 |
+
"directed 1 multigraph 1 ]"
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
# Tests for string convertible alphanumeric id and label values
|
| 544 |
+
nx.parse_gml("graph [edge [ source a target a ] node [ id a label b ] ]")
|
| 545 |
+
nx.parse_gml(
|
| 546 |
+
"graph [ node [ id n42 label 0 ] node [ id x43 label 1 ]"
|
| 547 |
+
"edge [ source n42 target x43 key 0 ]"
|
| 548 |
+
"edge [ source x43 target n42 key 0 ]"
|
| 549 |
+
"directed 1 multigraph 1 ]"
|
| 550 |
+
)
|
| 551 |
+
assert_parse_error(
|
| 552 |
+
"graph [edge [ source '\u4200' target '\u4200' ] "
|
| 553 |
+
+ "node [ id '\u4200' label b ] ]"
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
def assert_generate_error(*args, **kwargs):
|
| 557 |
+
pytest.raises(
|
| 558 |
+
nx.NetworkXError, lambda: list(nx.generate_gml(*args, **kwargs))
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
G = nx.Graph()
|
| 562 |
+
G.graph[3] = 3
|
| 563 |
+
assert_generate_error(G)
|
| 564 |
+
G = nx.Graph()
|
| 565 |
+
G.graph["3"] = 3
|
| 566 |
+
assert_generate_error(G)
|
| 567 |
+
G = nx.Graph()
|
| 568 |
+
G.graph["data"] = frozenset([1, 2, 3])
|
| 569 |
+
assert_generate_error(G, stringizer=literal_stringizer)
|
| 570 |
+
|
| 571 |
+
def test_label_kwarg(self):
|
| 572 |
+
G = nx.parse_gml(self.simple_data, label="id")
|
| 573 |
+
assert sorted(G.nodes) == [1, 2, 3]
|
| 574 |
+
labels = [G.nodes[n]["label"] for n in sorted(G.nodes)]
|
| 575 |
+
assert labels == ["Node 1", "Node 2", "Node 3"]
|
| 576 |
+
|
| 577 |
+
G = nx.parse_gml(self.simple_data, label=None)
|
| 578 |
+
assert sorted(G.nodes) == [1, 2, 3]
|
| 579 |
+
labels = [G.nodes[n]["label"] for n in sorted(G.nodes)]
|
| 580 |
+
assert labels == ["Node 1", "Node 2", "Node 3"]
|
| 581 |
+
|
| 582 |
+
def test_outofrange_integers(self, tmp_path):
|
| 583 |
+
# GML restricts integers to 32 signed bits.
|
| 584 |
+
# Check that we honor this restriction on export
|
| 585 |
+
G = nx.Graph()
|
| 586 |
+
# Test export for numbers that barely fit or don't fit into 32 bits,
|
| 587 |
+
# and 3 numbers in the middle
|
| 588 |
+
numbers = {
|
| 589 |
+
"toosmall": (-(2**31)) - 1,
|
| 590 |
+
"small": -(2**31),
|
| 591 |
+
"med1": -4,
|
| 592 |
+
"med2": 0,
|
| 593 |
+
"med3": 17,
|
| 594 |
+
"big": (2**31) - 1,
|
| 595 |
+
"toobig": 2**31,
|
| 596 |
+
}
|
| 597 |
+
G.add_node("Node", **numbers)
|
| 598 |
+
|
| 599 |
+
fname = tmp_path / "test.gml"
|
| 600 |
+
nx.write_gml(G, fname)
|
| 601 |
+
# Check that the export wrote the nonfitting numbers as strings
|
| 602 |
+
G2 = nx.read_gml(fname)
|
| 603 |
+
for attr, value in G2.nodes["Node"].items():
|
| 604 |
+
if attr == "toosmall" or attr == "toobig":
|
| 605 |
+
assert isinstance(value, str)
|
| 606 |
+
else:
|
| 607 |
+
assert isinstance(value, int)
|
| 608 |
+
|
| 609 |
+
def test_multiline(self):
|
| 610 |
+
# example from issue #6836
|
| 611 |
+
multiline_example = """
|
| 612 |
+
graph
|
| 613 |
+
[
|
| 614 |
+
node
|
| 615 |
+
[
|
| 616 |
+
id 0
|
| 617 |
+
label "multiline node"
|
| 618 |
+
label2 "multiline1
|
| 619 |
+
multiline2
|
| 620 |
+
multiline3"
|
| 621 |
+
alt_name "id 0"
|
| 622 |
+
]
|
| 623 |
+
]
|
| 624 |
+
"""
|
| 625 |
+
G = nx.parse_gml(multiline_example)
|
| 626 |
+
assert G.nodes["multiline node"] == {
|
| 627 |
+
"label2": "multiline1 multiline2 multiline3",
|
| 628 |
+
"alt_name": "id 0",
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
@contextmanager
|
| 633 |
+
def byte_file():
|
| 634 |
+
_file_handle = io.BytesIO()
|
| 635 |
+
yield _file_handle
|
| 636 |
+
_file_handle.seek(0)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
class TestPropertyLists:
|
| 640 |
+
def test_writing_graph_with_multi_element_property_list(self):
|
| 641 |
+
g = nx.Graph()
|
| 642 |
+
g.add_node("n1", properties=["element", 0, 1, 2.5, True, False])
|
| 643 |
+
with byte_file() as f:
|
| 644 |
+
nx.write_gml(g, f)
|
| 645 |
+
result = f.read().decode()
|
| 646 |
+
|
| 647 |
+
assert result == dedent(
|
| 648 |
+
"""\
|
| 649 |
+
graph [
|
| 650 |
+
node [
|
| 651 |
+
id 0
|
| 652 |
+
label "n1"
|
| 653 |
+
properties "element"
|
| 654 |
+
properties 0
|
| 655 |
+
properties 1
|
| 656 |
+
properties 2.5
|
| 657 |
+
properties 1
|
| 658 |
+
properties 0
|
| 659 |
+
]
|
| 660 |
+
]
|
| 661 |
+
"""
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
def test_writing_graph_with_one_element_property_list(self):
|
| 665 |
+
g = nx.Graph()
|
| 666 |
+
g.add_node("n1", properties=["element"])
|
| 667 |
+
with byte_file() as f:
|
| 668 |
+
nx.write_gml(g, f)
|
| 669 |
+
result = f.read().decode()
|
| 670 |
+
|
| 671 |
+
assert result == dedent(
|
| 672 |
+
"""\
|
| 673 |
+
graph [
|
| 674 |
+
node [
|
| 675 |
+
id 0
|
| 676 |
+
label "n1"
|
| 677 |
+
properties "_networkx_list_start"
|
| 678 |
+
properties "element"
|
| 679 |
+
]
|
| 680 |
+
]
|
| 681 |
+
"""
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
def test_reading_graph_with_list_property(self):
|
| 685 |
+
with byte_file() as f:
|
| 686 |
+
f.write(
|
| 687 |
+
dedent(
|
| 688 |
+
"""
|
| 689 |
+
graph [
|
| 690 |
+
node [
|
| 691 |
+
id 0
|
| 692 |
+
label "n1"
|
| 693 |
+
properties "element"
|
| 694 |
+
properties 0
|
| 695 |
+
properties 1
|
| 696 |
+
properties 2.5
|
| 697 |
+
]
|
| 698 |
+
]
|
| 699 |
+
"""
|
| 700 |
+
).encode("ascii")
|
| 701 |
+
)
|
| 702 |
+
f.seek(0)
|
| 703 |
+
graph = nx.read_gml(f)
|
| 704 |
+
assert graph.nodes(data=True)["n1"] == {"properties": ["element", 0, 1, 2.5]}
|
| 705 |
+
|
| 706 |
+
def test_reading_graph_with_single_element_list_property(self):
|
| 707 |
+
with byte_file() as f:
|
| 708 |
+
f.write(
|
| 709 |
+
dedent(
|
| 710 |
+
"""
|
| 711 |
+
graph [
|
| 712 |
+
node [
|
| 713 |
+
id 0
|
| 714 |
+
label "n1"
|
| 715 |
+
properties "_networkx_list_start"
|
| 716 |
+
properties "element"
|
| 717 |
+
]
|
| 718 |
+
]
|
| 719 |
+
"""
|
| 720 |
+
).encode("ascii")
|
| 721 |
+
)
|
| 722 |
+
f.seek(0)
|
| 723 |
+
graph = nx.read_gml(f)
|
| 724 |
+
assert graph.nodes(data=True)["n1"] == {"properties": ["element"]}
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
@pytest.mark.parametrize("coll", ([], ()))
|
| 728 |
+
def test_stringize_empty_list_tuple(coll):
|
| 729 |
+
G = nx.path_graph(2)
|
| 730 |
+
G.nodes[0]["test"] = coll # test serializing an empty collection
|
| 731 |
+
f = io.BytesIO()
|
| 732 |
+
nx.write_gml(G, f) # Smoke test - should not raise
|
| 733 |
+
f.seek(0)
|
| 734 |
+
H = nx.read_gml(f)
|
| 735 |
+
assert H.nodes["0"]["test"] == coll # Check empty list round-trips properly
|
| 736 |
+
# Check full round-tripping. Note that nodes are loaded as strings by
|
| 737 |
+
# default, so there needs to be some remapping prior to comparison
|
| 738 |
+
H = nx.relabel_nodes(H, {"0": 0, "1": 1})
|
| 739 |
+
assert nx.utils.graphs_equal(G, H)
|
| 740 |
+
# Same as above, but use destringizer for node remapping. Should have no
|
| 741 |
+
# effect on node attr
|
| 742 |
+
f.seek(0)
|
| 743 |
+
H = nx.read_gml(f, destringizer=int)
|
| 744 |
+
assert nx.utils.graphs_equal(G, H)
|