Upload folder using huggingface_hub (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+6
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/INSTALLERAdded+1
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/METADATAAdded+177
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/RECORDAdded+603
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/REQUESTEDAdded
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/WHEELAdded+5
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/entry_points.txtAdded+2
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txtAdded+37
- .venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/top_level.txtAdded+1
- .venv/lib/python3.12/site-packages/networkx/linalg/algebraicconnectivity.pyAdded+650
- .venv/lib/python3.12/site-packages/networkx/linalg/attrmatrix.pyAdded+466
- .venv/lib/python3.12/site-packages/networkx/linalg/bethehessianmatrix.pyAdded+77
- .venv/lib/python3.12/site-packages/networkx/linalg/graphmatrix.pyAdded+168
- .venv/lib/python3.12/site-packages/networkx/linalg/laplacianmatrix.pyAdded+512
- .venv/lib/python3.12/site-packages/networkx/linalg/modularitymatrix.pyAdded+166
- .venv/lib/python3.12/site-packages/networkx/linalg/spectrum.pyAdded+186
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/__init__.pyAdded
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_algebraic_connectivity.pyAdded+400
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_attrmatrix.pyAdded+108
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_bethehessian.pyAdded+40
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_graphmatrix.pyAdded+275
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_laplacian.pyAdded+334
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_modularity.pyAdded+86
- .venv/lib/python3.12/site-packages/networkx/linalg/tests/test_spectrum.pyAdded+70
- .venv/lib/python3.12/site-packages/networkx/readwrite/__init__.pyAdded+17
- .venv/lib/python3.12/site-packages/networkx/readwrite/adjlist.pyAdded+330
- .venv/lib/python3.12/site-packages/networkx/readwrite/edgelist.pyAdded+489
- .venv/lib/python3.12/site-packages/networkx/readwrite/gexf.pyAdded+1084
- .venv/lib/python3.12/site-packages/networkx/readwrite/gml.pyAdded+879
- .venv/lib/python3.12/site-packages/networkx/readwrite/graph6.pyAdded+427
- .venv/lib/python3.12/site-packages/networkx/readwrite/graphml.pyAdded+1053
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__init__.pyAdded+19
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/adjacency.pyAdded+156
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/cytoscape.pyAdded+190
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/node_link.pyAdded+261
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__init__.pyAdded
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_adjacency.pyAdded+78
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_cytoscape.pyAdded+78
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_node_link.pyAdded+109
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_tree.pyAdded+48
- .venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tree.pyAdded+137
- .venv/lib/python3.12/site-packages/networkx/readwrite/leda.pyAdded+108
- .venv/lib/python3.12/site-packages/networkx/readwrite/multiline_adjlist.pyAdded+393
- .venv/lib/python3.12/site-packages/networkx/readwrite/p2g.pyAdded+113
- .venv/lib/python3.12/site-packages/networkx/readwrite/pajek.pyAdded+286
- .venv/lib/python3.12/site-packages/networkx/readwrite/sparse6.pyAdded+379
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.pyAdded
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.pyAdded+354
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.pyAdded+318
- .venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.pyAdded+612
53 unmodified lines54555653 unmodified lines.venv/lib/python3.12/site-packages/mpmath/__pycache__/function_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/multidict/_multidict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text53 unmodified lines54555657585960616253 unmodified lines.venv/lib/python3.12/site-packages/mpmath/__pycache__/function_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/multidict/_multidict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/numpy/_core/_multiarray_tests.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/numpy/_core/_multiarray_umath.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/numpy/_core/_simd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/numpy/_core/lib/libnpymath.a filter=lfs diff=lfs merge=lfs -text
1uv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177Metadata-Version: 2.4Name: networkxVersion: 3.6.1Summary: Python package for creating and manipulating graphs and networksAuthor-email: Aric Hagberg <hagberg@lanl.gov>Maintainer-email: NetworkX Developers <networkx-discuss@googlegroups.com>License-Expression: BSD-3-ClauseProject-URL: Homepage, https://networkx.org/Project-URL: Bug Tracker, https://github.com/networkx/networkx/issuesProject-URL: Documentation, https://networkx.org/documentation/stable/Project-URL: Source Code, https://github.com/networkx/networkxKeywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,mathPlatform: LinuxPlatform: Mac OSXPlatform: WindowsPlatform: UnixClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: Science/ResearchClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Scientific/Engineering :: Bio-InformaticsClassifier: Topic :: Scientific/Engineering :: Information AnalysisClassifier: Topic :: Scientific/Engineering :: MathematicsClassifier: Topic :: Scientific/Engineering :: PhysicsRequires-Python: !=3.14.1,>=3.11Description-Content-Type: text/x-rstLicense-File: LICENSE.txtProvides-Extra: benchmarkingRequires-Dist: asv; extra == "benchmarking"Requires-Dist: virtualenv; extra == "benchmarking"Provides-Extra: defaultRequires-Dist: numpy>=1.25; extra == "default"Requires-Dist: scipy>=1.11.2; extra == "default"Requires-Dist: matplotlib>=3.8; extra == "default"Requires-Dist: pandas>=2.0; extra == "default"Provides-Extra: developerRequires-Dist: pre-commit>=4.1; extra == "developer"Requires-Dist: mypy>=1.15; extra == "developer"Provides-Extra: docRequires-Dist: sphinx>=8.0; extra == "doc"Requires-Dist: pydata-sphinx-theme>=0.16; extra == "doc"Requires-Dist: sphinx-gallery>=0.18; extra == "doc"Requires-Dist: numpydoc>=1.8.0; extra == "doc"Requires-Dist: pillow>=10; extra == "doc"Requires-Dist: texext>=0.6.7; extra == "doc"Requires-Dist: myst-nb>=1.1; extra == "doc"Requires-Dist: intersphinx-registry; extra == "doc"Provides-Extra: exampleRequires-Dist: osmnx>=2.0.0; extra == "example"Requires-Dist: momepy>=0.7.2; extra == "example"Requires-Dist: contextily>=1.6; extra == "example"Requires-Dist: seaborn>=0.13; extra == "example"Requires-Dist: cairocffi>=1.7; extra == "example"Requires-Dist: igraph>=0.11; extra == "example"Requires-Dist: scikit-learn>=1.5; extra == "example"Requires-Dist: iplotx>=0.9.0; extra == "example"Provides-Extra: extraRequires-Dist: lxml>=4.6; extra == "extra"Requires-Dist: pygraphviz>=1.14; extra == "extra"Requires-Dist: pydot>=3.0.1; extra == "extra"Requires-Dist: sympy>=1.10; extra == "extra"Provides-Extra: releaseRequires-Dist: build>=0.10; extra == "release"Requires-Dist: twine>=4.0; extra == "release"Requires-Dist: wheel>=0.40; extra == "release"Requires-Dist: changelist==0.5; extra == "release"Provides-Extra: testRequires-Dist: pytest>=7.2; extra == "test"Requires-Dist: pytest-cov>=4.0; extra == "test"Requires-Dist: pytest-xdist>=3.0; extra == "test"Provides-Extra: test-extrasRequires-Dist: pytest-mpl; extra == "test-extras"Requires-Dist: pytest-randomly; extra == "test-extras"Dynamic: license-file
NetworkX========
.. image:: https://github.com/networkx/networkx/actions/workflows/test.yml/badge.svg?branch=main :target: https://github.com/networkx/networkx/actions/workflows/test.yml
.. image:: https://img.shields.io/pypi/v/networkx.svg? :target: https://pypi.python.org/pypi/networkx
.. image:: https://img.shields.io/pypi/l/networkx.svg? :target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
.. image:: https://img.shields.io/pypi/pyversions/networkx.svg? :target: https://pypi.python.org/pypi/networkx
.. image:: https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute :target: https://github.com/networkx/networkx/contribute
.. image:: https://insights.linuxfoundation.org/api/badge/health-score?project=networkx :target: https://insights.linuxfoundation.org/project/networkx
NetworkX is a Python package for the creation, manipulation,and study of the structure, dynamics, and functionsof complex networks.
- **Website (including documentation):** https://networkx.org- **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss- **Source:** https://github.com/networkx/networkx- **Bug reports:** https://github.com/networkx/networkx/issues- **Report a security vulnerability:** https://tidelift.com/security- **Tutorial:** https://networkx.org/documentation/latest/tutorial.html- **GitHub Discussions:** https://github.com/networkx/networkx/discussions- **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz- **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
Simple example--------------
Find the shortest path between two nodes in an undirected graph:
.. code:: pycon
>>> import networkx as nx >>> G = nx.Graph() >>> G.add_edge("A", "B", weight=4) >>> G.add_edge("B", "D", weight=2) >>> G.add_edge("A", "C", weight=3) >>> G.add_edge("C", "D", weight=4) >>> nx.shortest_path(G, "A", "D", weight="weight") ['A', 'B', 'D']
Install-------
Install the latest released version of NetworkX:
.. code:: shell
$ pip install networkx
Install with all optional dependencies:
.. code:: shell
$ pip install networkx[default]
For additional details,please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
Bugs----
Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_and create a pull request (PR). We welcome all changes, big or small, and wewill help you make the PR if you are new to `git` (just ask on the issue and/orsee the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
License-------
Released under the `3-clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
Copyright (c) 2004-2025, NetworkX Developers Aric Hagberg <hagberg@lanl.gov> Dan Schult <dschult@colgate.edu> Pieter Swart <swart@lanl.gov>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603networkx-3.6.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2networkx-3.6.1.dist-info/METADATA,sha256=rKXZSpfR9w8wHQM63bY19uZr6Jc6AKukEnY37tLvMWo,6783networkx-3.6.1.dist-info/RECORD,,networkx-3.6.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx-3.6.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91networkx-3.6.1.dist-info/entry_points.txt,sha256=H2jZaDsDJ_i9H2SwWpwuFel8BrZ9xHKuvh-DQAWW9lQ,94networkx-3.6.1.dist-info/licenses/LICENSE.txt,sha256=PPfDoXnYF7I7i4VoIRdp_v35N5fSB9mEuLL6JNAiCzM,1763networkx-3.6.1.dist-info/top_level.txt,sha256=s3Mk-7KOlu-kD39w8Xg_KXoP5Z_MVvgB-upkyuOE4Hk,9networkx/__init__.py,sha256=OVN8C-x44LgeJWKcb77v-WwfMV7EYqieafkoQdlAl5E,1625networkx/algorithms/__init__.py,sha256=sXdgBEDG0qlsOAymWl9zyT-c_luwOQOhWuus6quro0A,6607networkx/algorithms/approximation/__init__.py,sha256=1W0c3YlSfVQtNI4-WiQdzMfPqmcrCar5hJQmrwcsVoI,1234networkx/algorithms/approximation/clique.py,sha256=b4cnWMJXmmgCyjMI8A_doHZeKS_RQbGqm2L01OpT_Jg,7691networkx/algorithms/approximation/clustering_coefficient.py,sha256=SWpSLEhW3DJc1n2fHlSbJSGg3wdoJkN5Y4_tnntn0Ws,2164networkx/algorithms/approximation/connectivity.py,sha256=aVXSfUiWEG4gUL0R1u6WZ-h-wheuLP1_suO_pRFB8M4,13118networkx/algorithms/approximation/density.py,sha256=_JU9nIH4wneHG6PtEAF_q1oLwy5UUKk--FkTVkkMAMg,15258networkx/algorithms/approximation/distance_measures.py,sha256=UEkmKagNw9sj8kiUDdbAeYuzvZ31pgLMXqzliqMkG84,5805networkx/algorithms/approximation/dominating_set.py,sha256=5fC90w1CgYR4Xkpqact8iukKY0i57bMmyJW-A9CToUQ,4710networkx/algorithms/approximation/kcomponents.py,sha256=MDkoyQbk0gSAm3ZZK35VOsiLJDv7wiDsxfzH5O-ObFs,13285networkx/algorithms/approximation/matching.py,sha256=PFof5m9AIq9Xr5Kaa_-mYxI1IBBP7HEkjf-R9wVE3bo,1175networkx/algorithms/approximation/maxcut.py,sha256=eTQZqsDQAAUaufni-aDJAY2UzIcajDhRMdj-AcqVkPs,4333networkx/algorithms/approximation/ramsey.py,sha256=W5tX7BOQJIM_qNsBeUhCXVWMD8DFdeTycYyk08k4Sqk,1358networkx/algorithms/approximation/steinertree.py,sha256=2t58cQQt9OAMRWP1q0RV9QrdNzgasZtPNp6PbA0LFDU,9363networkx/algorithms/approximation/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/approximation/tests/test_approx_clust_coeff.py,sha256=PGOVEKf2BcJu1vvjZrgTlBBpwM8V6t7yCANjyS9nWF0,1171networkx/algorithms/approximation/tests/test_clique.py,sha256=s6HQB-lK3RAu_ftpe2NvIiMu0Ol8tpAdbGvWzucNL6k,3021networkx/algorithms/approximation/tests/test_connectivity.py,sha256=gDG6tsgP3ux7Dgu0x7r0nso7_yknIxicV42Gq0It5pc,5952networkx/algorithms/approximation/tests/test_density.py,sha256=EgJsX9z2lxWJCpF5NPbYEbE0GIATazCmgj7wFYeObDM,5298networkx/algorithms/approximation/tests/test_distance_measures.py,sha256=axgOojplJIgXdopgkjxjAgvzGTQ1FV1oJ5NG-7ICalo,2023networkx/algorithms/approximation/tests/test_dominating_set.py,sha256=l4pBDY7pK7Fxw-S4tOlNcxf-j2j5GpHPJ9f4TrMs1sI,2686networkx/algorithms/approximation/tests/test_kcomponents.py,sha256=tTljP1FHzXrUwi-oBz5AQcibRw1NgR4N5UE0a2OrOUA,9346networkx/algorithms/approximation/tests/test_matching.py,sha256=nitZncaM0605kaIu1NO6_5TFV2--nohUCO46XTD_lnM,186networkx/algorithms/approximation/tests/test_maxcut.py,sha256=U6CDZFSLfYDII-1nX9XB7avSz10kTx88vNazJFoLQ1k,2804networkx/algorithms/approximation/tests/test_ramsey.py,sha256=h36Ol39csHbIoTDBxbxMgn4371iVUGZ3a2N6l7d56lI,1143networkx/algorithms/approximation/tests/test_steinertree.py,sha256=ifBKzrKjRzfMg2g9BKSXVYLvuEbygQPp9rXR4cK99Q8,10727networkx/algorithms/approximation/tests/test_traveling_salesman.py,sha256=odnyk7CgLbMGI2QuHxj3BPRX4cCfWHK5N65rj0jMLW8,32048networkx/algorithms/approximation/tests/test_treewidth.py,sha256=b_79ZKiW0XX24-GYaeQJ9Zaq7ZFYQT0DcDTkACII3EY,8868networkx/algorithms/approximation/tests/test_vertex_cover.py,sha256=FobHNhG9CAMeB_AOEprUs-7XQdPoc1YvfmXhozDZ8pM,1942networkx/algorithms/approximation/traveling_salesman.py,sha256=HZU6dbPo3Hiz2-Z3QHLFm5kdGBQwkXPefkVUuW-IC2A,56210networkx/algorithms/approximation/treewidth.py,sha256=hfLiPlheQMN7MG6CGR5w7AscKbLu3pTLNYRS13SO0Xo,8389networkx/algorithms/approximation/vertex_cover.py,sha256=oIi_yg5O-IisnfmrSof1P4HD-fsZpW69RpvkR_SM5Og,2803networkx/algorithms/assortativity/__init__.py,sha256=ov3HRRbeYB_6Qezvxp1OTl77GBpw-EWkWGUzgfT8G9c,294networkx/algorithms/assortativity/connectivity.py,sha256=-V0C5MTqtErl86N-gyrZ487MUyiG5x1QFEZKurOpIJA,4220networkx/algorithms/assortativity/correlation.py,sha256=0rc4FDi-e8eQRia7gpFrTqjIy-J7V2GtSwOb4QN6WZk,8689networkx/algorithms/assortativity/mixing.py,sha256=RRqqkuVwo71LosJLDbeVCVBikqC7I_XZORdsonQsf9Y,7586networkx/algorithms/assortativity/neighbor_degree.py,sha256=UMaQWKBkOZ0ZgC8xGt5fXEz8OL1rgwYjt2zKbKEqofI,5282networkx/algorithms/assortativity/pairs.py,sha256=w7xnaWxDDteluHoCsqunLlcM6nlcBenO_5Nz87oOEnE,3841networkx/algorithms/assortativity/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/assortativity/tests/base_test.py,sha256=MNeQMLA3oBUCM8TSyNbBQ_uW0nDc1GEZYdNdUwePAm4,2651networkx/algorithms/assortativity/tests/test_connectivity.py,sha256=Js841GQLYTLWvc6xZhnyqj-JtyrnS0ska1TFYntxyXA,4978networkx/algorithms/assortativity/tests/test_correlation.py,sha256=ddx-yqnVcOfx1dKVNUF695hS3Q-zCmFmCGzK64B7YSE,5068networkx/algorithms/assortativity/tests/test_mixing.py,sha256=1kkiMoQXslY-VnT1j00mFbRdj75A4d1b6OPTUOJVgaY,6802networkx/algorithms/assortativity/tests/test_neighbor_degree.py,sha256=wphbir1e-h-BAq5rjvWBi4WlgWdseyQbh_KLGQvy5Pc,3934networkx/algorithms/assortativity/tests/test_pairs.py,sha256=t05qP_-gfkbiR6aTLtE1owYl9otBSsuJcRkuZsa63UQ,3008networkx/algorithms/asteroidal.py,sha256=hIGg9zI4vylRXkrY5wHverTSOeK6dt1Gn2T_JYvGNnU,5500networkx/algorithms/bipartite/__init__.py,sha256=FZug-pg0FUDgAdysnKXxDpi1ly8ezxf4UxBPRklqjys,3883networkx/algorithms/bipartite/basic.py,sha256=JPC2gGuPvFA6q2CuI5mqLX_9QUGxrsQ8cIwcS0e9P4U,8375networkx/algorithms/bipartite/centrality.py,sha256=G280bAqeyXyCmes5NpRqUv2Tc-EHWrMshJ3_f4uqV9U,9156networkx/algorithms/bipartite/cluster.py,sha256=8aZRmlQ3g0XtzHyF1kUBBwnzMSjtduquHDH8MxKNSEI,7346networkx/algorithms/bipartite/covering.py,sha256=B3ITc016Kk70NBv-1lb30emXnfjlMIQJ7M-FIPCZip0,2163networkx/algorithms/bipartite/edgelist.py,sha256=mmiM2Bvh9CxRKCsspbs-90GZedpt7Gj5AGzvJ-aYDSM,11409networkx/algorithms/bipartite/extendability.py,sha256=OrYHlS4ruQST-dlQOuleiqHFKpVVNOvrG5aDNFgfckg,3989networkx/algorithms/bipartite/generators.py,sha256=p0xgyuJ5hp52NYPu2ryPEKZ0MEktP5VSW2HMK2VdBCo,20408networkx/algorithms/bipartite/link_analysis.py,sha256=eVRRQgwzMcUPPu6ccskPk72yc_lmnF5EGqNIdXe-MxA,12772networkx/algorithms/bipartite/matching.py,sha256=xsT048Ok_uM0Zhpdc34qswV1zaCGOlJQnsbGTDsm5oo,21637networkx/algorithms/bipartite/matrix.py,sha256=rxmjBNHts4hQ-EIlHLE3vIAeGHaMz8Kg_FJ8je5zFyQ,8320networkx/algorithms/bipartite/projection.py,sha256=YIUlreqQQ6IPE37OXF32zNIdzEGeyR8aY-7iUENZYVA,17252networkx/algorithms/bipartite/redundancy.py,sha256=eGNVo0qW-3unhGhY5VTs2vbc8QmOGve70UDY3ykjhNo,3340networkx/algorithms/bipartite/spectral.py,sha256=fu2grV1the_e_G-e_lUdhk8Y9XFe6_p2tPmx3RKntFw,1902networkx/algorithms/bipartite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/bipartite/tests/test_basic.py,sha256=gzbtsQqPi85BznX5REdGBBJVyr9aH4nO06c3eEI4634,4291networkx/algorithms/bipartite/tests/test_centrality.py,sha256=PABPbrIyoAziEEQKXsZLl2jT36N8DZpNRzEO-jeu89Y,6362networkx/algorithms/bipartite/tests/test_cluster.py,sha256=O0VsPVt8vcY_E1FjjLJX2xaUbhVViI5MP6_gLTbEpos,2801networkx/algorithms/bipartite/tests/test_covering.py,sha256=EGVxYQsyLXE5yY5N5u6D4wZq2NcZe9OwlYpEuY6DF3o,1221networkx/algorithms/bipartite/tests/test_edgelist.py,sha256=fK35tSekG_-9Ewr5Bhl1bRdwAy247Z9zZ4dQFFDQ9xw,8471networkx/algorithms/bipartite/tests/test_extendability.py,sha256=XgPmg6bWiHAF1iQ75_r2NqUxExOQNZRUeYUPzlCa5-E,7043networkx/algorithms/bipartite/tests/test_generators.py,sha256=BehRU6SQnWzKsAFoshrN2vpxcPByLAViofGeq38v23E,13203networkx/algorithms/bipartite/tests/test_link_analysis.py,sha256=vJMOtYG0vxYQCif_ztnYTUm_13gApfzFiNxChRefONg,6914networkx/algorithms/bipartite/tests/test_matching.py,sha256=3-2DMl3tF-g4_xNHvEuY4fZW7S5cqMTO_GUpcz1gkeQ,11973networkx/algorithms/bipartite/tests/test_matrix.py,sha256=TlZRVHCTKO2sqhycKFsefvdqP-Se47b_8iZwjtPpQYs,5063networkx/algorithms/bipartite/tests/test_project.py,sha256=WhX_yteTrXOdTZLMXpkW2A5ZFIBkw0WsnJRsNITyYtQ,15294networkx/algorithms/bipartite/tests/test_redundancy.py,sha256=utxcrQaTrkcEN3kqtObgKNpLZai8B5sMAqLyXatOuUo,917networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py,sha256=1jGDgrIx3-TWOCNMSC4zxmZa7LHyMU69DXh3h12Bjag,2358networkx/algorithms/boundary.py,sha256=q3JtWssmn9yCB2mBdkjKZjkaxmBhkG9_dJOzmuJiQos,5339networkx/algorithms/bridges.py,sha256=CsxueHDOB9aFM5D8GP83u1ZKGzxF193XBpvmMReAcQk,6066networkx/algorithms/broadcasting.py,sha256=Amw1oRpr8pdS67aC_9wjJOQomP1IqPvqtE7c0Mf9L70,4974networkx/algorithms/centrality/__init__.py,sha256=Er3YoYoj76UfY4P6I0L-0fCQkO7mMU0b3NLsTT2RGWI,558networkx/algorithms/centrality/betweenness.py,sha256=8829b5ep0pilM2Muqk5U0rPVQ02kwwedXaVGuQ_hY_U,22814networkx/algorithms/centrality/betweenness_subset.py,sha256=CUX0c96gYIORsdjOxVtif2796gOAcMitYoqEnbXDi5c,8114networkx/algorithms/centrality/closeness.py,sha256=ehkntG-gApT9uhWJjGaEZQ-tEQ-hdxDT7luf-uVPNAE,10281networkx/algorithms/centrality/current_flow_betweenness.py,sha256=kbq9XsZQvrCOdCAYvF67hRni1aqA1sT93WU2i0WfKKI,12717networkx/algorithms/centrality/current_flow_betweenness_subset.py,sha256=2qtLgf_3ft5qdDvHFrfYUt6zeQi42Nw7XBpSZRboJIA,8107networkx/algorithms/centrality/current_flow_closeness.py,sha256=IvecI8BZE4SgKayEXhKowIJw7S2fD_dN__N-f9TW-ME,3327networkx/algorithms/centrality/degree_alg.py,sha256=EFTA1b_GWUbmBy5R9beRQp7yh1X_NwZtk5L6is-mFGk,3894networkx/algorithms/centrality/dispersion.py,sha256=M12L2KiVPrC2-SyCXMF0kvxLelgcmvXJkLT_cBHoCTw,3631networkx/algorithms/centrality/eigenvector.py,sha256=LAxVqaT3LmuQw20__t1KrgLKPF1Cz-PkTaiSrgPC1FU,13623networkx/algorithms/centrality/flow_matrix.py,sha256=Y65m6VbWyYjNK0CInE_lufyEkKy9-TyPmBeXb-Gkz70,3834networkx/algorithms/centrality/group.py,sha256=TLlK2eWlcMX7Lvbe2wAcZrmZ9LLTvbRCz-3RbXF0Zug,27960networkx/algorithms/centrality/harmonic.py,sha256=OfrDikASbb0Xejjbd1kJ-lQuGT3Gv-rg3pmTtncAbho,2832networkx/algorithms/centrality/katz.py,sha256=uVGHAyjqndSd4y4idHjkv0mUhmKmHU5vaEfNWfiKlzc,11042networkx/algorithms/centrality/laplacian.py,sha256=qjyW2WnxMFo_mZqiQ4d8PVHLpXi3xNEX148Yikvk_ls,5554networkx/algorithms/centrality/load.py,sha256=M2EdPX4gJEYGjMBIJMFKRWGI9uYHbFOWYxsILeaJuOE,6859networkx/algorithms/centrality/percolation.py,sha256=YJB8iYgbpjJ3EYK8pl26iSnjgfFsK31ufytRHnUTYYE,4419networkx/algorithms/centrality/reaching.py,sha256=Q9rda_dqXBfVaHOi8FgZSYNHKpJ0SHfCbX_myMsIe2I,7255networkx/algorithms/centrality/second_order.py,sha256=4CTboP95B6gUtAtSKLfeeE4s9oq0_3hXsXczxL6c_g8,5012networkx/algorithms/centrality/subgraph_alg.py,sha256=YXkuyhhhZHmobNFpKDUpfeqSPyBvk97MlcJy5ESWh1s,10520networkx/algorithms/centrality/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/centrality/tests/test_betweenness_centrality.py,sha256=LmHNSaqExAT8kE-eOb_67Z6ckSGD_XqO56OHXhNkbFc,33669networkx/algorithms/centrality/tests/test_betweenness_centrality_subset.py,sha256=Y7qigLxQwFJqClJiCrKWGkcOHD467W0b6C5gBb0rFUg,13085networkx/algorithms/centrality/tests/test_closeness_centrality.py,sha256=-LtG4ex192Xjgy4JCTfdjdJ3Cd9Op-3XnVvG2GA3FWQ,8728networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py,sha256=1sipOadh8bsuzHZ0_7haapKU6Vrn0rbZL5HXvbsto5w,10072networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py,sha256=JfRGgPuiF-vJu5fc2_pcJYREEboxcK_dmy-np39c4Aw,5839networkx/algorithms/centrality/tests/test_current_flow_closeness.py,sha256=vflQeoNKngrGUiRb3XNlm2X9wR4vKgMSW_sCyMUCQi8,1379networkx/algorithms/centrality/tests/test_degree_centrality.py,sha256=Jn_p5lThA3__ZBTDAORwo_EchjXKKkK1NwU_73HHI6M,4101networkx/algorithms/centrality/tests/test_dispersion.py,sha256=ROgl_5bGhcNXonNW3ylsvUcA0NCwynsQu_scic371Gw,1959networkx/algorithms/centrality/tests/test_eigenvector_centrality.py,sha256=AfUa7GTve0UX6QOdBF6YMipmo-gKhyCu6aT8OCSf8wc,5254networkx/algorithms/centrality/tests/test_group.py,sha256=833ME4tGlOGQZz8YANw4MSyeVPpjbyCdYh5X88GOprw,8685networkx/algorithms/centrality/tests/test_harmonic_centrality.py,sha256=wI7nStX_kIFJoZQY_i8DXXlZBOJzVnQfOP8yidX0PAU,3867networkx/algorithms/centrality/tests/test_katz_centrality.py,sha256=JL0bZZsJe2MQFL6urXgY82wCAwucUvhjaShYZPxpL6U,11240networkx/algorithms/centrality/tests/test_laplacian_centrality.py,sha256=9Nd9CfiCn2908BgRZ-cQiMQjpOFDu4Bftod1didWyCE,5898networkx/algorithms/centrality/tests/test_load_centrality.py,sha256=Vv3zSW89iELN-8KNbUclmkhOe1LzKdF7U_w34nYovIo,11343networkx/algorithms/centrality/tests/test_percolation_centrality.py,sha256=ycQ1fvEZZcWAfqL11urT7yHiEP77usJDSG25OQiDM2s,2591networkx/algorithms/centrality/tests/test_reaching.py,sha256=_JVeO1Ri-KybdnGCJ_yNPtJQmT_g77z0DAkU0JYFVGQ,5090networkx/algorithms/centrality/tests/test_second_order_centrality.py,sha256=ce0wQ4T33lu23wskzGUnBS7X4BSODlvAX1S5KxlLzOA,1999networkx/algorithms/centrality/tests/test_subgraph.py,sha256=vhE9Uh-_Hlk49k-ny6ORHCgqk7LWH8OHIYOEYM96uz0,3729networkx/algorithms/centrality/tests/test_trophic.py,sha256=mt--0AUc_8qez2SjauEHVnetC3DMwMAlLME6kgb8Lc0,8796networkx/algorithms/centrality/tests/test_voterank.py,sha256=tN5u7pKAnJ_4AiwhPW6EuJZz7FLIG2jYqLKcXFi2urk,1687networkx/algorithms/centrality/trophic.py,sha256=7mpFrpgQhwP3Ad1plpJu1WzTGR1YWrIp_SUhM0D8Zww,5328networkx/algorithms/centrality/voterank_alg.py,sha256=z_1eq8rSDadEO5W5BbAg1zuOJj2di4FUCkmOwiuK12I,3231networkx/algorithms/chains.py,sha256=PPiSq5-GsT1Lsf8fwtGwGDVf1hhv5ZLariWtfzkBbAw,6968networkx/algorithms/chordal.py,sha256=L-ILWdVLWE44OkWmEO_4bSo4z6Ro-_zLglfLfTrwdqQ,13411networkx/algorithms/clique.py,sha256=SAvORAbZrZ-IpTVuEcarETQihNes-glpNiqoZ7hEgnM,27522networkx/algorithms/cluster.py,sha256=sKexvbvRnjuHSAkoJ9_dzCuOWDUDQkT_KjzmkKSoAhE,24851networkx/algorithms/coloring/__init__.py,sha256=P1cmqrAjcaCdObkNZ1e6Hp__ZpxBAhQx0iIipOVW8jg,182networkx/algorithms/coloring/equitable_coloring.py,sha256=uDcza6PD9qbvwVPUX1MBZbopQdrAEKNk6DpCFkc02tU,16315networkx/algorithms/coloring/greedy_coloring.py,sha256=GLXbwSvitsQgmxtOsbgUt4DTkURnb2k0X-7-SNsDW9I,20043networkx/algorithms/coloring/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/coloring/tests/test_coloring.py,sha256=7v_d1xanjYMZCa3dq2hE2hCcyexwWBTEFV5SoLgQDv4,23697networkx/algorithms/communicability_alg.py,sha256=0tZvZKY-_GUUB7GsRILxabS2jEpI51Udg5ADI9ADGZw,4545networkx/algorithms/community/__init__.py,sha256=vfw5aY7eoL7UDk42e0JPoVzRViCzk5cQf83zbls5p90,1279networkx/algorithms/community/asyn_fluid.py,sha256=bsY14UgR5FKLFqhFhHKmPP4-RJsVzH6K8ogsImLnCE8,6010networkx/algorithms/community/bipartitions.py,sha256=jqgJyMKOCs8TwI8YM9DO8qzuVZFe4XCnYRGeVAx5P4c,12238networkx/algorithms/community/centrality.py,sha256=Yyv5kyf1hf_L7iQ_ZbG8_FAkP638Sc_3N4tCSoB6J1w,6635networkx/algorithms/community/community_utils.py,sha256=sUi-AcPYyGrYhnjI9ztt-vrSHLl28lKXxTJPfi5N0c8,908networkx/algorithms/community/divisive.py,sha256=yFcKfKkiI6FqEVlBVxLa1fbqI1Yeiqe_A5fpPnYvlAE,6655networkx/algorithms/community/kclique.py,sha256=DTr9iUT_XWv0S3Y79KQl6OXefjztNMc9SAHWhdFOxcU,2460networkx/algorithms/community/label_propagation.py,sha256=LhzAXSHFCPQ2kG_rPgXb06YKdppO7buApksCC4GI4w8,11878networkx/algorithms/community/leiden.py,sha256=dx1N_KEsy30mfJ4729rJ28qaLsnkxoqDnv3UOXV2hWQ,6964networkx/algorithms/community/local.py,sha256=w-LK7qlMsQ2YHbZRQP95JvqM2gHGSe4yYZi7CXNkj_M,7316networkx/algorithms/community/louvain.py,sha256=jscGGTF6uUnC7yGEZTcE9UFmKsLDFwlZa4ecQyVQrOU,15424networkx/algorithms/community/lukes.py,sha256=gzqnup95RR2UzUiPpIt8qkepzZ9dCWqHGQSVPIJDMx8,8115networkx/algorithms/community/modularity_max.py,sha256=Qzidmvk2QOIb-S2o4erJvLSeQWcPbLq5TVMrxw15Wc4,18093networkx/algorithms/community/quality.py,sha256=oEw-RZBe62janFTTs-ak62APBiF2FpQoBiHv11_4YQY,11943networkx/algorithms/community/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/community/tests/test_asyn_fluid.py,sha256=XziMTOiEhzX6cvJdLeODUC1zjOLWchhHf9Z_9Eb3TME,3738networkx/algorithms/community/tests/test_bipartitions.py,sha256=w7kxfw5WjKzIosCdq3eHsvuYhUoElaO9Q3lK0kVyNg4,4639networkx/algorithms/community/tests/test_centrality.py,sha256=s8q4k5aThR0OgO9CDQk_PXMxfllmf5uC1GlvyUc_8EY,2932networkx/algorithms/community/tests/test_divisive.py,sha256=-Ee40OR-mPDReTngTEhbpx4_uLtNI7cqFkt8cZT9t5Y,3441networkx/algorithms/community/tests/test_kclique.py,sha256=iA0SBqwbDfaD2u7KM6ccs6LfgAQY_xxrnW05UIT_tFA,2413networkx/algorithms/community/tests/test_label_propagation.py,sha256=IHidFEv7MI781zsdk7XT848rLvLwDk2wBK1FjL-CRv4,7985networkx/algorithms/community/tests/test_leiden.py,sha256=bl4jr-Z0m59AISIAl-OLsnATz1lDacNssc-ICKn72Nw,4803networkx/algorithms/community/tests/test_local.py,sha256=c-dy1rs1L0ahhDTQwNZP1zNbffjzRgw5IBFTCBV-fas,1809networkx/algorithms/community/tests/test_louvain.py,sha256=TwW1nlSKWGJeIKr9QOJ8xGehSY6R0Nz01xsnFqzt0Oo,8071networkx/algorithms/community/tests/test_lukes.py,sha256=f_JU-EzY6PwXEkPN8kk5_3NVg6phlX0nrj1f57M49lk,3961networkx/algorithms/community/tests/test_modularity_max.py,sha256=XYyPuDkxL4CYFwnpTdU_qD4GydpqgiRAIJO3CHQN_m4,10617networkx/algorithms/community/tests/test_quality.py,sha256=sZEy10hh3zlelUmww5r2pk5LxpZAht06PC5zCHxV1bs,5275networkx/algorithms/community/tests/test_utils.py,sha256=gomD6rFgAaywxT1Yjdi4ozY-1rC0ina4jgfvWeCvwGE,704networkx/algorithms/components/__init__.py,sha256=Dt74KZWp_cJ_j0lL5hd_S50_hia5DKcC2SjuRnubr6M,173networkx/algorithms/components/attracting.py,sha256=6az3lgqWhHTXaWUUuOPZfW9t7okliAhooFRotQY5JoM,2712networkx/algorithms/components/biconnected.py,sha256=_9GJdPZgqusGKZLzqT9tUSj1XZr2DgohiT6hcHVyil4,12782networkx/algorithms/components/connected.py,sha256=s-uvEdHkY8dNxNPS5G8jnk-qTCum-bet_yKAx8_qTXc,7904networkx/algorithms/components/semiconnected.py,sha256=BaBMFlQ208vuHOo5y1xeV0PDEI3yDUfH6zFb_jkcVhQ,2030networkx/algorithms/components/strongly_connected.py,sha256=oZGBBDzhsrCBQjIfqYlkzvXkE3sF-WTRtYEa5UYy6-k,9911networkx/algorithms/components/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/components/tests/test_attracting.py,sha256=b3N3ZR9E5gLSQWGgaqhcRfRs4KBW6GnnkVYeAjdxC_o,2243networkx/algorithms/components/tests/test_biconnected.py,sha256=N-J-dgBgI77ytYUUrXjduLxtDydH7jS-af98fyPBkYc,6036networkx/algorithms/components/tests/test_connected.py,sha256=KMYm55BpbFdGXk_B2WozS9rIagQROd7_k0LT3HFQmr4,4815networkx/algorithms/components/tests/test_semiconnected.py,sha256=q860lIxZF5M2JmDwwdzy-SGSXnrillOefMx23GcJpw0,1792networkx/algorithms/components/tests/test_strongly_connected.py,sha256=Zm7MgUIZbuPPJu66xZH1zfMZQ_3X1YBl2fLCOjph7NQ,6021networkx/algorithms/components/tests/test_weakly_connected.py,sha256=_eUx7226dxme_K2WNmvSIwZXQlKNoCuglWOOC3kFUW4,3083networkx/algorithms/components/weakly_connected.py,sha256=q5siwSHQYtbKDcVc4dUDzfKh-DClETmuy3jLQN2_K4o,4413networkx/algorithms/connectivity/__init__.py,sha256=EvYKw8LJn7wyZECHAsuEkIaSl-cV-LhymR6tqcn90p8,281networkx/algorithms/connectivity/connectivity.py,sha256=xck9yth1asWFAM9Hp7UP6vdUh-Kr0IOmq046plOAXPQ,29367networkx/algorithms/connectivity/cuts.py,sha256=o-5GRQotOVXsNq7Kx_w7yBBVuGLa57whS2YF5DVb1KQ,23199networkx/algorithms/connectivity/disjoint_paths.py,sha256=57ZerbGqn30B8cwomcsS0GScectvP-mgCMb0GH-RYb8,14649networkx/algorithms/connectivity/edge_augmentation.py,sha256=cK9S6pRnsKLyb_57guKfrAbLiXL6sMALHCf7pR4tzFM,44063networkx/algorithms/connectivity/edge_kcomponents.py,sha256=hqABcfCqZ-rb45I0qYE-X4NtstsKJbxl37FZzzmoXA4,20894networkx/algorithms/connectivity/kcomponents.py,sha256=qDDeMqPb5rWbi6EKZwetBft5Qmv6PSUngQTVunJxyy0,8086networkx/algorithms/connectivity/kcutsets.py,sha256=zYohzgkR2FODi_Ew2M9uMLb_a9ZP5fNqcXJwMYy6P7o,9371networkx/algorithms/connectivity/stoerwagner.py,sha256=WodsJEqKgsmTTcyUBk2u3wV_CXeon-cAzveWgIGgFmA,5431networkx/algorithms/connectivity/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/connectivity/tests/test_connectivity.py,sha256=eSmsi8uQk6MI591JgtSu2elIusb08bmSZS0h9gxb76I,15027networkx/algorithms/connectivity/tests/test_cuts.py,sha256=q8dxYBAnsGtIBBPZCjIvMszZvXOYST2cVVsCJvXbIhw,10356networkx/algorithms/connectivity/tests/test_disjoint_paths.py,sha256=NLHReLoXSKoA6KPBNRbjF84ktg5PEaaktIj2AII3SDY,8392networkx/algorithms/connectivity/tests/test_edge_augmentation.py,sha256=gIu58oxk_uSexawlr3H1ds2HGqkTHHGhhVYUCNmfrb4,15737networkx/algorithms/connectivity/tests/test_edge_kcomponents.py,sha256=Bzo77zG79Lv_-OzdI1ZZKO_c13wrnFmfv60FrkDyXI0,16453networkx/algorithms/connectivity/tests/test_kcomponents.py,sha256=vLwQOLRevXeeid3e7SSKVpd_OyAJE8PxiAU8GYX0Tf0,9276networkx/algorithms/connectivity/tests/test_kcutsets.py,sha256=w5DyrjndNqyT3qxQH6WTBCuBR0ljYXatZCtcT1WeiYM,8974networkx/algorithms/connectivity/tests/test_stoer_wagner.py,sha256=A291C30_t2CI1erPCqN1W0DoAj3zqNA8fThPIj4Rku0,3011networkx/algorithms/connectivity/utils.py,sha256=gL8LmZnK4GKAZQcIPEhVNYmVi18Mqsqwg4O4j_et56s,3217networkx/algorithms/core.py,sha256=6SO5Wz-LSkx6t2DSq0GPmOvFALGe0gVsXdsvno9Fljs,17479networkx/algorithms/covering.py,sha256=I_on4DUgmwbtbo-qlBq4YWhOsNjuSHCfVGZNAL-Sefs,5278networkx/algorithms/cuts.py,sha256=eqwi5bhCMchItKlRAUw4wGVRtHUK0JzTkaXJFUyxXEw,10419networkx/algorithms/cycles.py,sha256=AGpANFoLZ2td8YkGn0cHypASJuRllAwj_-g2Vve7QW8,43302networkx/algorithms/d_separation.py,sha256=DpOl1YaI-72_fgUJ2NI3Piuj7EQRQ8xmyAQCRdLgjTw,26089networkx/algorithms/dag.py,sha256=OPgrOtnKJVMwxu2AxBGWPZyO7ti6qXa6pn57SsO8FAQ,44673networkx/algorithms/distance_measures.py,sha256=cQIRYjP4FtpbA3SP_dOPM6hvwpM1z77oMfmuZ4w8suI,37618networkx/algorithms/distance_regular.py,sha256=M9m6qitAtCXYbv2k9hDjF0CpxdeEXPu2_KOI8CCGc_I,8391networkx/algorithms/dominance.py,sha256=00Ng1SMzAvxodLTfAeLnXexpPb13IlB_S_mDEuT8JhY,3897networkx/algorithms/dominating.py,sha256=yoRB4WCe0wMvJpkbKtNo2fpd0jTVq6b09JsCYcaeR_Y,8145networkx/algorithms/efficiency_measures.py,sha256=VKbLKJgdIbno-YnJaLaCZt7TNXXnQPdz8N99uJCo748,4741networkx/algorithms/euler.py,sha256=yCqKaGchFSRPTRDXq7u1fH2IXZF94wWf9S10K9-Cd6U,14205networkx/algorithms/flow/__init__.py,sha256=rVtMUy6dViPLewjDRntmn15QF0bQwiDdQbZZx9j7Drc,341networkx/algorithms/flow/boykovkolmogorov.py,sha256=qFcppmiXz4VKKFd4RbDsiWOqJODtDTHbNr9_UFTjQaU,13334networkx/algorithms/flow/capacityscaling.py,sha256=8rng2qO5kawNSxq2S8BNlUMmdvNSoC6R8ekiBGU8LxU,14469networkx/algorithms/flow/dinitz_alg.py,sha256=I5nnZVsj0aU8-9Cje0umey407epFzpd7BDJpkI6ESK4,8341networkx/algorithms/flow/edmondskarp.py,sha256=PEIwLftevS2VYHaTzzZMSOLPy7QSBPsWPedjx1lR6Cs,8056networkx/algorithms/flow/gomory_hu.py,sha256=EuibaxPl65shGM9Jxvaa9WMwMmoczDvXXc2b0E81cqM,6345networkx/algorithms/flow/maxflow.py,sha256=GuVA4MlPwdOeCdPRXW2QVW1OdJqgzSpPhEyASr302u4,22975networkx/algorithms/flow/mincost.py,sha256=GzMYInS4QcNe0yImGrVXJ0bRd7t5TSSMa9jSeenIoOk,12853networkx/algorithms/flow/networksimplex.py,sha256=6F1JNT1pMEMt-C27H3PsdZYF-53SrJMrHaakQ8pD7Ng,25098networkx/algorithms/flow/preflowpush.py,sha256=CUKZ0-7X9l7P7qH_2n2Immbf8mFm8vocH2SY0tIwjGo,15721networkx/algorithms/flow/shortestaugmentingpath.py,sha256=gXXdkY3nH4d0hXVn0P2-kzfC3DHcuCdrudFdxetflKI,10372networkx/algorithms/flow/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/flow/tests/gl1.gpickle.bz2,sha256=z4-BzrXqruFiGqYLiS2D5ZamFz9vZRc1m2ef89qhsPg,44623networkx/algorithms/flow/tests/gw1.gpickle.bz2,sha256=b3nw6Q-kxR7HkWXxWWPh7YlHdXbga8qmeuYiwmBBGTE,42248networkx/algorithms/flow/tests/netgen-2.gpickle.bz2,sha256=OxfmbN7ajtuNHexyYmx38fZd1GdeP3bcL8T9hKoDjjA,18972networkx/algorithms/flow/tests/test_gomory_hu.py,sha256=aWtbI3AHofIK6LDJnmj9UH1QOfulXsi5NyB7bNyV2Vw,4471networkx/algorithms/flow/tests/test_maxflow.py,sha256=4CtGOqeyloAxFSajaxPfGuyVhE0R3IdJf2SuIg4kHKQ,18940networkx/algorithms/flow/tests/test_maxflow_large_graph.py,sha256=P2e7G8TKN17zrMeOEbSIkLwK08MjfOtNhPva3nLM-B0,4612networkx/algorithms/flow/tests/test_mincost.py,sha256=vI61ZCLoWAzwYU4hU0AJS8Ori8vAWEPzFDCUoiloVRk,17806networkx/algorithms/flow/tests/test_networksimplex.py,sha256=tCw5C1hLEwbUbt_ySWgkvRyLKj-1T2wfXV9HT4Fx77Q,14162networkx/algorithms/flow/tests/wlm3.gpickle.bz2,sha256=zKy6Hg-_swvsNh8OSOyIyZnTR0_Npd35O9RErOF8-g4,88132networkx/algorithms/flow/utils.py,sha256=jexiKM-_BQfSAy15f4iZ_Km7DvRrcdOKqi6hxu9X0MM,6246networkx/algorithms/graph_hashing.py,sha256=kS881g6vUvMZms856A_tblq3ljB6BanUbt5az37fSlo,16918networkx/algorithms/graphical.py,sha256=1NdlhXuGEgUkHPo47EoNTWUMfdeTpiv7BBVM9ty2ivw,15831networkx/algorithms/hierarchy.py,sha256=_KFhCF1Afr2TrkPhqx-1PXUXEtfYLhbRShC58ZKbDGE,1786networkx/algorithms/hybrid.py,sha256=z3sIFMOpja1wlj-lI8YI6OIbSLZWHr66uSqyVESZWXY,6209networkx/algorithms/isolate.py,sha256=8F4GCBHZIW21CZresBlHuZhvq85ruPH_pnlxYetbHuQ,2251networkx/algorithms/isomorphism/__init__.py,sha256=gPRQ-_X6xN2lJZPQNw86IVj4NemGmbQYTejf5yJ32N4,406networkx/algorithms/isomorphism/ismags.py,sha256=AwJKq94d5e_RU0PZs5Gm7D73v-eOBBP8QDkpPxUocd0,60177networkx/algorithms/isomorphism/isomorph.py,sha256=O2TZtUPe89CsZxoNchv6FyYsGU79kWrwywGFBeonksE,10561networkx/algorithms/isomorphism/isomorphvf2.py,sha256=NTc9uCm2RnR9RxuKsAS_70RWD1zJYCJNPhefcJZUi5U,47637networkx/algorithms/isomorphism/matchhelpers.py,sha256=PaZ7PjmNNsJO9KoeRrf9JgcDHIcFr1tZckQc_ol4e9I,10884networkx/algorithms/isomorphism/temporalisomorphvf2.py,sha256=-1NW81l8kM9orQ2ni9tcNizQzEhOUE9BaBJXjUWqhiI,10948networkx/algorithms/isomorphism/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/isomorphism/tests/iso_r01_s80.A99,sha256=hKzMtYLUR8Oqp9pmJR6RwG7qo31aNPZcnXy4KHDGhqU,1442networkx/algorithms/isomorphism/tests/iso_r01_s80.B99,sha256=AHx_W2xG4JEcz1xKoN5TwCHVE6-UO2PiMByynkd4TPE,1442networkx/algorithms/isomorphism/tests/si2_b06_m200.A99,sha256=NVnPFA52amNl3qM55G1V9eL9ZlP9NwugBlPf-zekTFU,310networkx/algorithms/isomorphism/tests/si2_b06_m200.B99,sha256=-clIDp05LFNRHA2BghhGTeyuXDqBBqA9XpEzpB7Ku7M,1602networkx/algorithms/isomorphism/tests/test_ismags.py,sha256=YIrF8xSbnY8zsxiqjSZkzMFXF9TKwZ91m9araTfxJwE,24323networkx/algorithms/isomorphism/tests/test_isomorphism.py,sha256=e92l9AcYLKISmXB3hOdKanrvgKlUKuQ0TuXz7xuCD1Q,4576networkx/algorithms/isomorphism/tests/test_isomorphvf2.py,sha256=fVZZQgTU_L_kgp6KsiVwy5iLBewVFzXGDl72VQ0CgS0,15303networkx/algorithms/isomorphism/tests/test_match_helpers.py,sha256=uuTcvjgf2LPqSQzzECPIh0dezw8-a1IN0u42u8TxwAw,2483networkx/algorithms/isomorphism/tests/test_temporalisomorphvf2.py,sha256=k8032J4ItZ4aFHeOraOpiF8y4aPm2O1g44UvUfrQJgg,7343networkx/algorithms/isomorphism/tests/test_tree_isomorphism.py,sha256=mZPWRv2sSVJ9PbpGi5MEj5GaFbrp_ha2bL1wre1-Jqo,5681networkx/algorithms/isomorphism/tests/test_vf2pp.py,sha256=u_baOdKDdp34CQWwPob8henY90k8_hdK82SQDGesaO0,51386networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py,sha256=A8Y-FcGsLPWvmci5oHHDowSeh-Fhl_y88TrvboPZwdw,90251networkx/algorithms/isomorphism/tests/test_vf2userfunc.py,sha256=TrXs7E3Ynva18dBmaJDO4QGsySteCwK32cUKw-WkZ0I,6309networkx/algorithms/isomorphism/tree_isomorphism.py,sha256=J4RfMpO5LfL5z_wI3xP2wcbK2vMFEsxAQqBddPdw3YA,9033networkx/algorithms/isomorphism/vf2pp.py,sha256=jM3mzJNC0EutWHDmDkKIh1JfsB9XbpTkzEC6qXD0Lpo,36681networkx/algorithms/isomorphism/vf2userfunc.py,sha256=HiPwyr7nJF1QS9w69MzKf6wGvO8cgjvdS5vW59iwCew,7371networkx/algorithms/link_analysis/__init__.py,sha256=UkcgTDdzsIu-jsJ4jBwP8sF2CsRPC1YcZZT-q5Wlj3I,118networkx/algorithms/link_analysis/hits_alg.py,sha256=ot5sEhIvQ-JruYgcqCoi_EvNk89UWx_skG4KayIuO9I,10439networkx/algorithms/link_analysis/pagerank_alg.py,sha256=e7HuXXXVCG79YG0iuIOr1wqA_zC60hKoXGlMfvh9k1o,17202networkx/algorithms/link_analysis/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/link_analysis/tests/test_hits.py,sha256=BQ7QHXvJDkXtK-_VDFagtdp_-VXxVerwPymjGjzFWA0,2546networkx/algorithms/link_analysis/tests/test_pagerank.py,sha256=rUJNa_2nKDSk75Fg1yygMPAqg_Bdk0gGWMDRKY8g1lk,7282networkx/algorithms/link_prediction.py,sha256=UYo_LJgoVXcM1iLMXswM2g4jvUJmvxln3e5bVfXxQ10,22253networkx/algorithms/lowest_common_ancestors.py,sha256=D1LgoX_ibv2hR-viKEx6l_qp3mWVCkW6YAlGGdoWgXQ,9286networkx/algorithms/matching.py,sha256=Xgi-zy9C2pNvGwTixTFV7ut7W-l8s7zUgJha9v8D0s8,44325networkx/algorithms/minors/__init__.py,sha256=ceeKdsZ6U1H40ED-KmtVGkbADxeWMTVG07Ja8P7N_Pg,587networkx/algorithms/minors/contraction.py,sha256=o5i1UfWpI1KhD4-pVx4yuFJvwi00yJx58Te6GYpys7Y,27606networkx/algorithms/minors/tests/test_contraction.py,sha256=31FgiENkElrScHzJrQ3DcKG8W2ieow6zI7PZ9wgVJKE,17674networkx/algorithms/mis.py,sha256=BEMv_dW8R6CjMMXJQGIhS4HpS8A8AkLJJWnz3GstuS4,2344networkx/algorithms/moral.py,sha256=z5lp42k4kqYk7t_FfszVj5KAC7BxXe6Adik3T2qvA6o,1535networkx/algorithms/node_classification.py,sha256=s2yjsHk4mj_6llCuawgGvJ59HyswbcW6ufGQC4UBmG0,6465networkx/algorithms/non_randomness.py,sha256=rjIoT7-aqKwGSBNoYxgKniDFgqSDwV8Hh21lkWRYGVE,5787networkx/algorithms/operators/__init__.py,sha256=dJ3xOXvHxSzzM3-YcfvjGTJ_ndxULF1TybkIRzUS87Y,201networkx/algorithms/operators/all.py,sha256=v_W9ZT3u4STNvT4YI9zYn1Z2PDMhqfh4vfhtO4glaIA,9718networkx/algorithms/operators/binary.py,sha256=hziSCLDIVIoTWPV56fED5gI1pErOdyLOQ3Z_E_Nz9As,13150networkx/algorithms/operators/product.py,sha256=FQkSIduOv-z1ktVzid2T40759S-BmAfTlya88VytuZc,19632networkx/algorithms/operators/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/operators/tests/test_all.py,sha256=Jn8IfNZ1P4Aa51C0gU58S2A-DPksQUFersWco0kG0Yw,8280networkx/algorithms/operators/tests/test_binary.py,sha256=BdZQS-qsWbEbRXuWANvH2eXEv7myAKyuldtQzHj6n4Y,12190networkx/algorithms/operators/tests/test_product.py,sha256=i4pBb5A4NmaCsllR1XizyhUToaQFMuLZ-JrywkQFdbU,15155networkx/algorithms/operators/tests/test_unary.py,sha256=UZdzbt5GI9hnflEizUWXihGqBWmSFJDkzjwVv6wziQE,1415networkx/algorithms/operators/unary.py,sha256=Eo2yeTg-F5uODGWSWR_im5VaKZQ97LyATIuKZcAFQR8,1795networkx/algorithms/perfect_graph.py,sha256=aMdQkfcXEySVutIOwngHkvDEy1qinO_92uZFJx6Ydnk,2597networkx/algorithms/planar_drawing.py,sha256=AXuoT3aFgEtCeMnAaUsRqjxCABdNYZ8Oo9sGOKBQto0,16254networkx/algorithms/planarity.py,sha256=nN6QCMz9PJYRqnAa06qEDANdd9bxsbO64PQdbVEGwk4,49887networkx/algorithms/polynomials.py,sha256=iP30_mcOlj81Vrzt4iB_ZZxYiRokubs-O1i9RW4pgTw,11278networkx/algorithms/reciprocity.py,sha256=1WMhLbSMkVPxRPlfUvbgO5FgVvJHn1doXQF4WuqSLQk,2855networkx/algorithms/regular.py,sha256=fEHD4VBREbJwSlR48okVZBuwgvD76GXdT28NitJI8qQ,4877networkx/algorithms/richclub.py,sha256=kARzso3M6wnUcAJo2g8ga_ZtigL2czDNzeUDzBtRfqo,4892networkx/algorithms/shortest_paths/__init__.py,sha256=Rmxtsje-mPdQyeYhE8TP2NId-iZEOu4eAsWhVRm2Xqk,285networkx/algorithms/shortest_paths/astar.py,sha256=0pEnYNzG7Z86zWqyFe0OL8HTlQO9PwjDABy_ypC30_A,8937networkx/algorithms/shortest_paths/dense.py,sha256=5Y8ziU-RsWZRTzxEEzg5gB7f4j9yxbNhplTbLaMliG8,8261networkx/algorithms/shortest_paths/generic.py,sha256=-7wIqqDWeScy8brYFkdt68nuxkSgXVs1iXcwGWoBZAU,25337networkx/algorithms/shortest_paths/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/shortest_paths/tests/test_astar.py,sha256=F0zXZ7R0eXP8Et4F3mrCtdtfE1-tQTGB2ATcFveDUHI,8989networkx/algorithms/shortest_paths/tests/test_dense.py,sha256=ievl4gu3Exl_31hp4OKcsAGPb3g3_xFUM4t3NnvrG_A,6747networkx/algorithms/shortest_paths/tests/test_dense_numpy.py,sha256=IEwhjPNTlc2H1on-B3WhFoyLkDkJVdAFBjn675XALHA,2299networkx/algorithms/shortest_paths/tests/test_generic.py,sha256=CQJxa5by1xE1a2E8iZm8GAtiPy_DILcrB4dIyWVM_qM,20609networkx/algorithms/shortest_paths/tests/test_unweighted.py,sha256=r1F5qVEDZnzPn5yJ71Rp-Z7pq33CzJFfZmDhVBekR9Y,5879networkx/algorithms/shortest_paths/tests/test_weighted.py,sha256=dzMts7Y1mMUuz4zEz4adEqYUNoXi9BMf-oyzQ0BMG3s,35502networkx/algorithms/shortest_paths/unweighted.py,sha256=iuJAO3WzB1p-fwpDyGM4snuFB5k57KIsVGcAJUhCpi0,17825networkx/algorithms/shortest_paths/weighted.py,sha256=PphAp7PmN9qpWzkLudePIVgvySh_SGDi5GhdQN5iufk,84155networkx/algorithms/similarity.py,sha256=E8P8vWqCR-r2SFVSqW9Y-Bb4I4R7BzUc_jzhiCYx7tU,72679networkx/algorithms/simple_paths.py,sha256=8oG_bRDVRrBKVCDEjZLHW3Qyzrv5KVynp-Hl0m5SNmA,31091networkx/algorithms/smallworld.py,sha256=3xT-z2_CVdp5-Ap8vF6fsd3DiavDYtspFNZrcwcpXG0,13565networkx/algorithms/smetric.py,sha256=_Aj4BIMnafiXbJtLkvAfAnIEMdI9OcVvMy6kk9KKTns,770networkx/algorithms/sparsifiers.py,sha256=4T8pMlh-usEHA2-rZFh-CmZbBY9dcXIHjoqR-oJ2hSw,10048networkx/algorithms/structuralholes.py,sha256=rYaVkndSJ3kFxbjkhfQd6uMBpYO7NNlcsOPR0Xbiy7Y,12626networkx/algorithms/summarization.py,sha256=CygTsSthyCKHs0ZTZsCgWnyaT8annQbLpUtahmfY9Sw,23251networkx/algorithms/swap.py,sha256=NVZMmlnkdxgwwNw5GDrc8waNERcdCu52ydHcBdOA_hw,14744networkx/algorithms/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/tests/test_asteroidal.py,sha256=DnWI5_jnaaZMxtG44XD0K690HZs8ez7HU_9dSR-p6eA,502networkx/algorithms/tests/test_boundary.py,sha256=1OSJh32FYFhAVYB5zqxhZGEXZLS0HPp9kvfHZvWmD3o,6227networkx/algorithms/tests/test_bridges.py,sha256=jSCguECho0GNHnu0vpRh1twyfGP6tWFcaYL1rgvc8mU,4026networkx/algorithms/tests/test_broadcasting.py,sha256=GqjkpHC5Z7ogZZdf1qsz5B1lmX-Pd5pFMD5e3QRPAkI,3034networkx/algorithms/tests/test_chains.py,sha256=4fR5Uh2NMrTZGT1yR6sAsQEP3uy1U3UnwjcXLFk9d1Y,4196networkx/algorithms/tests/test_chordal.py,sha256=DPdNPY7KtqCsCwYVb4xQfnIm-z35dUJIWxNHtAiQLAQ,4438networkx/algorithms/tests/test_clique.py,sha256=RX1Q38DRDmclLLJ04pfE5RIFAy86EuTZ2QAERrtkjS4,9772networkx/algorithms/tests/test_cluster.py,sha256=b0OXtKvUYGzDxBrnIbPh8A3vo3jmRYOFzW02MVSWYgo,19320networkx/algorithms/tests/test_communicability.py,sha256=4KK9wU9gAUqHAAAyHwAKpq2dV9g415s_X0qd7Tt83gU,2938networkx/algorithms/tests/test_core.py,sha256=Q3bi_c0LpxZ-0VopHU6Lyzkb_JKseVT16H45qDuax9A,9619networkx/algorithms/tests/test_covering.py,sha256=EeBjQ5mxcVctgavqXZ255T8ryFocuxjxdVpIxVUNFvw,2718networkx/algorithms/tests/test_cuts.py,sha256=gKm9VDtnmwFli6kgwV1ktEFI_rw84p2Sg02Em6SoW5Q,5376networkx/algorithms/tests/test_cycles.py,sha256=CBEQ_kNlHg5PHb9vKMS9ot-lqUuvs_cAgaPtnEQn76g,34851networkx/algorithms/tests/test_d_separation.py,sha256=cxoAOA_EahXQHFsFaRopz6cp3h5sMnD7D_isq4_EuWI,10714networkx/algorithms/tests/test_dag.py,sha256=sd6OlsrK57rY7x6vMfWSf11tEiKH5BakNp7747KvCnA,29407networkx/algorithms/tests/test_distance_measures.py,sha256=kF-pR5WbVBs1d_IO-U6Dr-sf8MaRHfxc_D286sBN62E,28793networkx/algorithms/tests/test_distance_regular.py,sha256=w27OTUtAI0VQv7cikkOdJg4bo4q7xTNIVE8nbU_x7b8,2915networkx/algorithms/tests/test_dominance.py,sha256=rD-m7LVQpqrOTCUJrli43lYpezYxajfkcNd3xvGhTj8,9811networkx/algorithms/tests/test_dominating.py,sha256=5WwPlrQ6_pFaVx_-K4D5cHNbCZL23qp-PytgsXDuS4Q,3112networkx/algorithms/tests/test_efficiency.py,sha256=QKWMvyjCG1Byt-oNp7Rz_qxnVeT77Zk27lrzI1qH0mA,1894networkx/algorithms/tests/test_euler.py,sha256=L4L1ljHVxQxjQQludO2r6k3UZU7WAY_N6WYUjFx1fEk,11209networkx/algorithms/tests/test_graph_hashing.py,sha256=ribxC8ZkNxkkBDyjSZ8P2f8J6y5y4g-Ik-k5hBgZcx4,31567networkx/algorithms/tests/test_graphical.py,sha256=uhFjvs04odxABToY4IRig_CaUTpAC3SfZRu1p1T7FwY,5366networkx/algorithms/tests/test_hierarchy.py,sha256=uW8DqCdXiAeypkNPKcAYX7aW86CawYH84Q0bW4cDTXo,1184networkx/algorithms/tests/test_hybrid.py,sha256=kQLzaMoqZcKFaJ3D7PKbY2O-FX59XDZ1pN5un8My-tk,720networkx/algorithms/tests/test_isolate.py,sha256=LyR0YYHJDH5vppQzGzGiJK-aaIV17_Jmla8dMf93olg,555networkx/algorithms/tests/test_link_prediction.py,sha256=lP6slSHwXdzdJzNSeMTUsP88ypSqe6EeVy-bUP2d-48,20451networkx/algorithms/tests/test_lowest_common_ancestors.py,sha256=5ZT_17q-5ipw7NNgNisaVcxIxrY6XeQQaUlBXHx9k9g,14160networkx/algorithms/tests/test_matching.py,sha256=1IKeUi49HR8aAOm2V4cmBL2NGXvF9cb8mqW9jnkNGuY,18319networkx/algorithms/tests/test_max_weight_clique.py,sha256=M1eoy8OtuQVZkEvNMauV9vqR6hHtOCrtq6INv2qzMyA,6739networkx/algorithms/tests/test_mis.py,sha256=Z2tKoqbs-AFPzEBDYO7S8U-F7usLfZJ2l6j2DpZUts4,1865networkx/algorithms/tests/test_moral.py,sha256=15PZgkx7O9aXQB1npQ2JNqBBkEqPPP2RfeZzKqY-GNU,452networkx/algorithms/tests/test_node_classification.py,sha256=NgJJKUHH1GoD1GE3F4QRYBLM3fUo_En3RNtZvhqCjlg,4663networkx/algorithms/tests/test_non_randomness.py,sha256=iDHCFzFvxGXCi_vWnv-DkXHcmO9uU6KVpYGMCpHKQG8,1678networkx/algorithms/tests/test_perfect_graph.py,sha256=Y2mpreh5TNCkqn4PDO57MFkgYozt-tlZFScKH3TZJRg,609networkx/algorithms/tests/test_planar_drawing.py,sha256=fBTd9JzDkTqNQz7GBQCS9lShU1P3lWRQ7L-E5WhSdlA,8765networkx/algorithms/tests/test_planarity.py,sha256=2iy22H4APB2K0DiPcoWmiQV9BTQlJ9JSOexubN14sU0,17312networkx/algorithms/tests/test_polynomials.py,sha256=baI0Kua1pRngRC6Scm5gRRwi1bl0iET5_Xxo3AZTP3A,1983networkx/algorithms/tests/test_reciprocity.py,sha256=X_PXWFOTzuEcyMWpRdwEJfm8lJOfNE_1rb9AAybf4is,1296networkx/algorithms/tests/test_regular.py,sha256=ppXES6zvpsppoZmzXPFim-S4ZMWPG2Zhhmlgc67y_GA,2951networkx/algorithms/tests/test_richclub.py,sha256=Wl8aE0CSswaXJiHCQ42IkyRvjWaJQZ2OQcbC7LpIgfo,3962networkx/algorithms/tests/test_similarity.py,sha256=l02q6PMnweng8EfUm6Z0yor-Uy-zd6WN0Tm28lh3pBU,41248networkx/algorithms/tests/test_simple_paths.py,sha256=7U9wCXz4SHK0XeYrs1k2KjYgrYVQDnts2ggQLzU18p0,25181networkx/algorithms/tests/test_smallworld.py,sha256=bmoNDxIuhV0bBKWh2hgFw0XYTPCc2rgg1y77uMg6rE8,2390networkx/algorithms/tests/test_smetric.py,sha256=VM14L4X1AABvINDL9qKXzlech_Q2g4Aee-ozWM2Qrr4,144networkx/algorithms/tests/test_sparsifiers.py,sha256=1GRbQy1vfmwv6eUhP4Io0aykH2VyTJfFWmncrXmTqi4,4044networkx/algorithms/tests/test_structuralholes.py,sha256=F0xZ1nlKJLGmQDebDiExju4fMffu79qThnyF7ZGA53A,7592networkx/algorithms/tests/test_summarization.py,sha256=uNyaUstobIEu6M_Hexik-3YiYTRSy_XO6LUqoE4wazw,21312networkx/algorithms/tests/test_swap.py,sha256=WJtGMkSbAd1Cv06VaUeDVHosNOtdigsqEspyux0ExCs,6144networkx/algorithms/tests/test_threshold.py,sha256=x0hqqbH65nbDNEUV0vYz0J2TSmmBbJ0daEgLIR7CRm0,9733networkx/algorithms/tests/test_time_dependent.py,sha256=NmuV2kDo4nh2MeN0hwcJf0QSDtqMD0dfSeeKSsYBtQ8,13342networkx/algorithms/tests/test_tournament.py,sha256=tfOPwN7YHnw0oxl9d7-ErPBFKz6KBfSc5S3tbGrGHs8,4107networkx/algorithms/tests/test_triads.py,sha256=CbnFABCMDU0X1mzu3tzW4-WL2qn5ptaDTOShNaTjIwk,8219networkx/algorithms/tests/test_vitality.py,sha256=p5lPWCtVMtbvxDw6TJUaf8vpb0zKPoz5pND722xiypQ,1380networkx/algorithms/tests/test_voronoi.py,sha256=M4B6JtkJUw56ULEWRs1kyVEUsroNrnb5FBq9OioAyHM,3477networkx/algorithms/tests/test_walks.py,sha256=X8cb-YvGHiiqbMEXuKMSdTAb9WtVtbHjIESNSqpJTmU,1499networkx/algorithms/tests/test_wiener.py,sha256=uT6Es_OFbJqxnVY7lImzlJSRTQS4eJnMaKotKbObMd8,4186networkx/algorithms/threshold.py,sha256=maOMixTxDibvBL2BkVcaYz1Co_09jg8d7DpAW2blNnY,30776networkx/algorithms/time_dependent.py,sha256=PAeJ7Yt8kUqbDgvBaz_ZfUFZg-w-vf1gPC0HO6go_TI,5762networkx/algorithms/tournament.py,sha256=TyWD0P-8JYXsckulbyr-bkKOoc0gLUHK59R1RQm2We4,11613networkx/algorithms/traversal/__init__.py,sha256=YtFrfNjciqTOI6jGePQaJ01tRSEQXTHqTGGNhDEDb_8,142networkx/algorithms/traversal/beamsearch.py,sha256=Vn0U4Wck8ICShIAGggv3tVtQWVW0ABEz_hcBsGrql6o,3473networkx/algorithms/traversal/breadth_first_search.py,sha256=KGpFnXuCQrDwcQg27Irtrqu7hcIWlFSlVWGpA26XbHA,18259networkx/algorithms/traversal/depth_first_search.py,sha256=2V4T3tGujcAtV3W6WcTQUjGAAe3b1rqinONowUhLsa8,16795networkx/algorithms/traversal/edgebfs.py,sha256=JJ1mQCmv8WydqQtIVQC1HqkqEFDMeKVzJ_hexwU8sXA,6333networkx/algorithms/traversal/edgedfs.py,sha256=T1xHGr8p_eC1pEUyCP-kpaYlIY_la_ms-J0-50c4EDk,6041networkx/algorithms/traversal/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/traversal/tests/test_beamsearch.py,sha256=bzUcswZ1qo0ecDZYSER_4enbsW6SjTpb_3Nb3fqmkAo,900networkx/algorithms/traversal/tests/test_bfs.py,sha256=tGQSiYhc6BxaZEuw-G3ZxVfYLN7q0zrP_BeKl6EfxkU,6447networkx/algorithms/traversal/tests/test_dfs.py,sha256=rQMq7GToM6CVU3WwIZfmqa-HrqlmvIT1DryRU7NbU_U,10580networkx/algorithms/traversal/tests/test_edgebfs.py,sha256=8oplCu0fct3QipT0JB0-292EA2aOm8zWlMkPedfe6iY,4702networkx/algorithms/traversal/tests/test_edgedfs.py,sha256=HGmC3GUYSn9XLMHQpdefdE6g-Uh3KqbmgEEXBcckdYc,4775networkx/algorithms/tree/__init__.py,sha256=wOh_v70XEdFHL2qUMje7qkJI5RcjFNrDremJYl4zzkg,182networkx/algorithms/tree/branchings.py,sha256=B0c_uKpcnV2SwJMZJRK0BMEz8LkvIcOhv1y0AI0gTnY,34339networkx/algorithms/tree/coding.py,sha256=l9P4jhmhg_9uYBVMNSmLYW8btHJH07-Sl2SIKJtO1LA,13466networkx/algorithms/tree/decomposition.py,sha256=lY_rqx9JxnLEkp1wiAv0mX62PGPwGQ6SW4Jp48o8aiw,3071networkx/algorithms/tree/distance_measures.py,sha256=Dwtk2BRTXmEGjFFtpiAbk02HrX2Hb5kjXusfwn6nm9M,6981networkx/algorithms/tree/mst.py,sha256=UMeSnnpKrPeq7a_w_tR415w9TOLltmzuXyIy_HfqbAU,46145networkx/algorithms/tree/operations.py,sha256=TjfLQpxwlaLgdOnhLkdzHfZ68yFCYz6BMzzh_d_2mJc,4048networkx/algorithms/tree/recognition.py,sha256=bYnaDN0ZaIWTgq0tbPEHAcdxQBWZpDvWypZarBbA334,7569networkx/algorithms/tree/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/algorithms/tree/tests/test_branchings.py,sha256=euky-3tFOV5CVV5v_yFawuVGCaqTuTrKtBIkCygwhiA,17731networkx/algorithms/tree/tests/test_coding.py,sha256=XC6SbfA2zVGH4FyJJyv6o8eOnBu7FNzNot3SKs7QmEo,3955networkx/algorithms/tree/tests/test_decomposition.py,sha256=vnl_xoQzi1LnlZL25vXOZWwvaWmon3-x222OKt4eDqE,1871networkx/algorithms/tree/tests/test_distance_measures.py,sha256=WNzqjgDuFLUt_NgjD4R8gGhbYhQ3F5a4HZfBBipunv0,3389networkx/algorithms/tree/tests/test_mst.py,sha256=D3o217cjuUtf0TxZ9ks1wqQ4cpwVySoOBYfg0Jmr1AU,32376networkx/algorithms/tree/tests/test_operations.py,sha256=ybU96kROTVJRTyjLG7JSJjYlPxaWmYjUVJqbXV5VGGI,1961networkx/algorithms/tree/tests/test_recognition.py,sha256=qeMEIvg-j2MqaU-TNIQhCcXxao8vTBy0wjpU7jr2iw8,4521networkx/algorithms/triads.py,sha256=FqOtB5fi40k4EoA_-bV1TBwimsRihAqrVdFyNnq0hns,14233networkx/algorithms/vitality.py,sha256=8M1cubIydO49El2kwVCURHZ2UwCtfGVFeGS8-JYt1ko,2289networkx/algorithms/voronoi.py,sha256=07SnSpxLDz4k6K59Jo-VTNA-Qy5knaHfBC-y_5vAOLQ,3183networkx/algorithms/walks.py,sha256=5A611YwX9D8IZYbFcQ4aT3cuKZWHq1QOzCpy4mAM6XE,2312networkx/algorithms/wiener.py,sha256=88sTSCXt6gakAmxP4BD_ir1R-_0NOUxXlyZKeElzzvs,9221networkx/classes/__init__.py,sha256=Q9oONJrnTFs874SGpwcbV_kyJTDcrLI69GFt99MiE6I,364networkx/classes/coreviews.py,sha256=5Dgi8PjMZJz_Uun2SXL5a6mxtAfdbm3kPIdbgzSTXgM,13251networkx/classes/digraph.py,sha256=ys8hmrqUjto00TDwBNCwiaNAahFbizNvKkkx84BxS30,48781networkx/classes/filters.py,sha256=PCy7BsoIby8VcamqDjZQiNAe_5egI0WKUq-y5nc9unQ,2817networkx/classes/function.py,sha256=pPpy-TgC33yNX3nPMZoSjfVmaiiSTbfwYJJMFGa35hQ,43794networkx/classes/graph.py,sha256=bY5x7WQHoQxSZow95OUAmU8UZaYV0ZWQvhrEFjSAt0Y,72337networkx/classes/graphviews.py,sha256=ulUTLozEK_hj_4TGHdgvxveR2-rb92Q14jjxH4oH4Go,8520networkx/classes/multidigraph.py,sha256=qBhb2eoiMejz5fkv-ihLsqwQKKYnUjUANHnrWZKYQfI,37036networkx/classes/multigraph.py,sha256=7SD8_ZT7yE1EfIotDzIgITSj4HkKLxZfj6ZnWjQ7hIA,47931networkx/classes/reportviews.py,sha256=u0hNZqaWXCfLMP_lq835XCIVStkZQJ9HaQPeDPPoo88,46132networkx/classes/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/classes/tests/dispatch_interface.py,sha256=gffiIwS4OZWKIgRkfvghixQds5hY0tPBi86p0lpV7eY,6823networkx/classes/tests/historical_tests.py,sha256=oUJSS-QhvInhad9AJCXCCk0x7OzAclIF9RjBSZ6gB58,16291networkx/classes/tests/test_coreviews.py,sha256=qzdozzWK8vLag-CAUqrXAM2CZZwMFN5vMu6Tdrwdf-E,12128networkx/classes/tests/test_digraph.py,sha256=uw0FuEu3y_YI-PSGuQCRytFpXLF7Eye2fqLJaKbXkBc,12283networkx/classes/tests/test_digraph_historical.py,sha256=8TbDcvmLgfllfGomTRStSpT5WIQiTHLt-rS3GyJEItU,3668networkx/classes/tests/test_filters.py,sha256=fBLig8z548gsBBlQw6VJdGZb4IcqJj7_0mi2Fd2ncEM,5851networkx/classes/tests/test_function.py,sha256=PDtKrB31Ix1-abPc8NzuP-h7HOOIRtkL5bvcOE8mshU,35481networkx/classes/tests/test_graph.py,sha256=ST12bvoj72uzUDpnyVz-Zx0mlXV2CegcEg3txT5qS6k,31798networkx/classes/tests/test_graph_historical.py,sha256=EVAndjelyyZ9laQCTrj6KR6lhdmG8Y1raP2IrxkZxdA,258networkx/classes/tests/test_graphviews.py,sha256=JoTS_ZY7u4dBHEttD55WT1pD47FcvELBEzw-uJQiqv4,11496networkx/classes/tests/test_multidigraph.py,sha256=ryTKegCoYixXbAqOn3mIt9vSMb5666Dv-pfMkXEjoUE,16342networkx/classes/tests/test_multigraph.py,sha256=0vFQO3RCJaBpzXvnQzdWa_qYLHNo_I9DICYhPZJNUMk,18777networkx/classes/tests/test_reportviews.py,sha256=MgP9_cKlw4aTU5m1XbsNTM3ZjmO7roOOf-7x-Hn9xKs,41332networkx/classes/tests/test_special.py,sha256=wl-Idzdc55eOQ4Tn5SNqOG21AjwLb2TTp9x102Qx3Ms,4053networkx/classes/tests/test_subgraphviews.py,sha256=iIMkbHdtJsgDlcdphhE_uUTJ0VGTGFzKIVvMd7oamoU,13669networkx/conftest.py,sha256=5-BwqVMgfaZyRZICFpG1plLMJ2G1IchSQVEuRjoBtyc,8041networkx/convert.py,sha256=Xmkhacuyw9CDviBTZPlH6nmD-JabSk0aPcVmGgp4LeY,16143networkx/convert_matrix.py,sha256=9BXSEXzCEIte1nx8f35cWhXo-EVYjOkuW4H3Jutq-oE,45342networkx/drawing/__init__.py,sha256=rnTFNzLc4fis1hTAEpnWTC80neAR88-llVQ-LObN-i4,160networkx/drawing/layout.py,sha256=5MUr2NTp4L3IbOShTb_m7fD4SH1HPZKJPJ4G1mJC3Js,66346networkx/drawing/nx_agraph.py,sha256=4Vd8JQH4BQ7BaRO8TmYlqBKmFPm8e2XcDDJiqFkNMxM,14248networkx/drawing/nx_latex.py,sha256=PySHixo2YhGV0xbKLroaX-_XcI1L5u8IF8nP6xdV2NU,24846networkx/drawing/nx_pydot.py,sha256=9KbNVrVcU5gFmo1GPpB_UMBXcD1tnBYDBzxHvgg6mOs,9992networkx/drawing/nx_pylab.py,sha256=MHoDvYE4FO9kJRogqeB1FfqrStyLcjQTq3fr67vAjOE,103488networkx/drawing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/drawing/tests/baseline/test_display_complex.png,sha256=3YPN6JEuyq1KEpRgSnH-2yECI81frU_5fw0VxHlwo9A,142315networkx/drawing/tests/baseline/test_display_empty_graph.png,sha256=XsOkBCZlt-55c40ElwEapBENVfmdc4TZKIF1ufs5Dzk,3257networkx/drawing/tests/baseline/test_display_house_with_colors.png,sha256=uiEx6_2RddHG-516OsRVM0AG7M5CGiAo4tpDgbgPKIU,26002networkx/drawing/tests/baseline/test_display_labels_and_colors.png,sha256=RfA1OtWYKttP5_LDScIcx8MFbC-_5wljXeDsZAqAqDU,62571networkx/drawing/tests/baseline/test_display_shortest_path.png,sha256=6W7EMitF8jojJ8epmaYEWpjhYRlzBlL7QV98MStxvvQ,35264networkx/drawing/tests/baseline/test_house_with_colors.png,sha256=FQi9pIRFwjq4gvgB8cDdBHL5euQUJFw6sQlABf2kRVo,21918networkx/drawing/tests/test_agraph.py,sha256=5cbqLGEgJmAocWOMSikv_9ykRWfBymjGfalvKbR1_KE,8725networkx/drawing/tests/test_image_comparison_pylab_mpl.py,sha256=2UtGMJFpcWiG0sQtXIYT0j03Q2LhGqWM2G-pfKY3Sw0,6340networkx/drawing/tests/test_latex.py,sha256=YQjLxsZnx7_CX2sJ3nN0cUiJzC7p6UhyFN6ufbox5G0,8621networkx/drawing/tests/test_layout.py,sha256=2_wJfBcCcHwBm1JRrQiLMcnNWoaURX6F4LFcn5OPul4,23709networkx/drawing/tests/test_pydot.py,sha256=X9b66gWqMgdTEyRJ7Zmy5kL9cr22waI688K9BJUf4Bk,4973networkx/drawing/tests/test_pylab.py,sha256=TMGpM6IKm5vTSu9Dbfm8mvyhMqz2aAu1gafGbLiOU1k,54825networkx/exception.py,sha256=hC8efPfIzOFo0jiWiQbTPaNKuNTuUwhp9RPw--pdv4U,3787networkx/generators/__init__.py,sha256=EoYB5c5ZE4rsNKZvl1TRQy2Vo2D3T2H-YunyD2i6sa0,1366networkx/generators/atlas.dat.gz,sha256=c_xBbfAWSSNgd1HLdZ9K6B3rX2VQvyW-Wcht47dH5B0,8887networkx/generators/atlas.py,sha256=cbki_oYDi_7vniSesqJZ-PCEM3BvnzEdjSc3TA3s1xc,6955networkx/generators/classic.py,sha256=Wzey-Pl6Rm-ELYyg2lIb0lFZAxywRr5iQxv7zo3d9Bk,32658networkx/generators/cographs.py,sha256=-WR4_yrNk_X5nj7egb7A22eKPVymOdIYM-IftSRH4WA,1891networkx/generators/community.py,sha256=_p_4OfItbg8nS0b3EvojCXZ8cESdC-0Gj67V5w2veuM,34911networkx/generators/degree_seq.py,sha256=Hxv1rjY2NS8qmnvSWh4rcvublDZzor3D3IiB2OAFXoE,30493networkx/generators/directed.py,sha256=rtgf2Imf34SogrWA0BNgDltlA5kUv_l2NkxKPcJgGtQ,18149networkx/generators/duplication.py,sha256=hmYAHJBez7WlfdVGGa288JFUBHoIUdVqEGCodApKOr4,5831networkx/generators/ego.py,sha256=ylW-UMvg9C8cqygw9vrBNLGAVZJT4U5EWbU4gaT_H1g,1894networkx/generators/expanders.py,sha256=gJioNdyhBOnNcjh0qC-kfbFs1SEMU5_o9GHy85pdJXk,15184networkx/generators/geometric.py,sha256=6slgS0vraxql67AOP9lWzBrpNbx_OBZCoBwYuSkQQXg,39461networkx/generators/harary_graph.py,sha256=N2_b49xrET0bjZ4C7sgcG2xLv64ia9xjvJ2NB75CAz8,4950networkx/generators/internet_as_graphs.py,sha256=RuhEW9rQ8f5VzeIyZe6GqSWgxKtMVuwqnzv0llW3FeY,14226networkx/generators/intersection.py,sha256=EFm0AOjnqyp8KcT7kGWqANq-_vq9kQ0d_0DzVyQyP-o,4101networkx/generators/interval_graph.py,sha256=ZTmdgQbBx3M6sysGWXbGyngYYOC1TAXD3Ozkw4deQFw,2204networkx/generators/joint_degree_seq.py,sha256=nyp86NC_4XvzvwpwwzKrrCSz1i_4bESSDtVjWvpkWFg,24773networkx/generators/lattice.py,sha256=5iujIY5pF_VhbWEE2osM5i7uuYqs5Hv1wS33WGPMn_o,14740networkx/generators/line.py,sha256=DDQZvD2Y2c-4kc_xTuUWpmmViLftTSGKFukgqSiyI_c,17540networkx/generators/mycielski.py,sha256=xBX2m77sCzumoH5cAGitksvEEW-ocbCnbdaN7fKUtVk,3314networkx/generators/nonisomorphic_trees.py,sha256=62FIt4Qx-giwDflNKP5BrDoCv1HbQmlp6oVGjqGeRlE,6993networkx/generators/random_clustered.py,sha256=i_NdvvchHvsvbwgQtoWSY_pLwvhO9Lh02MSZXzgGb7c,4183networkx/generators/random_graphs.py,sha256=WIJ4v8PSNpHePclSCQ3IcLWwcipZJ2Cn9pNx6XenBEo,51669networkx/generators/small.py,sha256=duBVJgz4f2TByU4SdyRGHw7YyLHrlrr0UFw6spVTCbo,30967networkx/generators/social.py,sha256=brzAScpAxWGRExE9J7FuiJ29QZxBm8bXpRgCc0IoHP0,23416networkx/generators/spectral_graph_forge.py,sha256=9r6d9f5Y03KPX138sQTKWG3_RjeiYQVUJJWwCHqG4MA,4282networkx/generators/stochastic.py,sha256=Qg9vWm9EOug2OQVIHL_dZ5HrXc16lxnWyzX52KWNEPI,1981networkx/generators/sudoku.py,sha256=kLM2AP0H4966uYiNO1oAFEmv5qBftU_bOfYucRxexM0,4288networkx/generators/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/generators/tests/test_atlas.py,sha256=nwXJL4O5jUqhTwqhkPxHY8s3KXHQTDEdsfbg4MsSzVQ,2530networkx/generators/tests/test_classic.py,sha256=eRtftt3fcr5kYJI8PffuY3tWOnn4u0yJZwKav1bZACU,24400networkx/generators/tests/test_cographs.py,sha256=v2fYoolmfwfCpJZRKRtH9YKyWcuJkaPOQUpDK9DMsn0,553networkx/generators/tests/test_community.py,sha256=FGcDo3Ajb-yYc5kUkFbVfOJVMG-YppbAtjgBPcVzjLc,11311networkx/generators/tests/test_degree_seq.py,sha256=V_X-Mc0H2sqEy7OTJb4yY9khsi-9HD-DIA_fvngW-VE,7284networkx/generators/tests/test_directed.py,sha256=e8C7AF2whjaqdxga7WSvCrtIx7ByBG_JyJ9gYqJ6HBA,6020networkx/generators/tests/test_duplication.py,sha256=UdIGDF_fishanWid1xO_aH4NDfie8xpIqd26qndhOqI,3155networkx/generators/tests/test_ego.py,sha256=8v1Qjmkli9wIhhUuqzgqCzysr0C1Z2C3oJMCUoNvgY4,1327networkx/generators/tests/test_expanders.py,sha256=Cf0cCJOplngPlN23OVqDcrny2QZlrYMrrWHeIi0APaA,6363networkx/generators/tests/test_geometric.py,sha256=gnVm4dam_Er88YwaNpNZC6mjJjfgwMYhyLOtU9oPn1o,18087networkx/generators/tests/test_harary_graph.py,sha256=GiX5LXXJaNxzjvd-Nyw_QuARzbFGkA6zE1R1eX8mclw,4936networkx/generators/tests/test_internet_as_graphs.py,sha256=3et6aawAPZ9bPNWqADJ3bQN_2KhyqPf8VFgrBAkgABQ,8514networkx/generators/tests/test_intersection.py,sha256=hcIit5fKfOn3VjMhz9KqovZK9tzxZfmC6ezvA7gZAvM,819networkx/generators/tests/test_interval_graph.py,sha256=JYMi-QMkJQdBU9uOdfm0Xr6MEYqIbhU5oSDa6D3tSb0,4277networkx/generators/tests/test_joint_degree_seq.py,sha256=8TXTZI3Um2gBXtP-4yhGKf9vCi78-NVmWZw9r9WG3F8,4270networkx/generators/tests/test_lattice.py,sha256=iYB2F7j1Qt3QAHkhGnGKcgiRNB1Gq9MxtE3152XdS_A,10102networkx/generators/tests/test_line.py,sha256=Dt1R1Hnm47aq_8FX9gRFdby0sV3Oxyap1R5Z4eK0A5o,10516networkx/generators/tests/test_mycielski.py,sha256=fwZLO1ybcltRy6TzCel8tPBil1oZWv9QSXs779H6Xt0,946networkx/generators/tests/test_nonisomorphic_trees.py,sha256=KFRwMfx-x_a9oGvPlhtMlWGk__rKgm77Gk4LtbxFrZE,2945networkx/generators/tests/test_random_clustered.py,sha256=SalHqWvpnXA3QrDRMjLx15dk2c4Us8Ck52clUERoUI8,1297networkx/generators/tests/test_random_graphs.py,sha256=R5dHYuzAbcIBduoP7PUdoV-6CFauqk5r1Ak1Slwlsho,19565networkx/generators/tests/test_small.py,sha256=y9rZHpwQG4Bjp-sHJp18rM3A0uEGOUkbklqlJec11ao,8074networkx/generators/tests/test_spectral_graph_forge.py,sha256=x4jyTiQiydaUPWYaGsNFsIB47PAzSSwQYCNXGa2B4SU,1594networkx/generators/tests/test_stochastic.py,sha256=f-5KD3RpoQf369gXHH7KGebE19g5lCkXR_alcwmFm_s,2179networkx/generators/tests/test_sudoku.py,sha256=dgOmk-B7MxCVkbHdZzsLZppQ61FAArVy4McSVL8Afzo,1968networkx/generators/tests/test_time_series.py,sha256=rgmFcitlKa_kF6TzJ2ze91lSmNJlqjhvgrYet0AUZx8,2230networkx/generators/tests/test_trees.py,sha256=Pvh0MvTKaRuZuwWL-wpJIC0zlBAcnTirpSLJi-9c7qc,7006networkx/generators/tests/test_triads.py,sha256=K8anVEP8R90Y172IrKIOrYRWRJBGeqxNqU9isX7Ybxs,333networkx/generators/time_series.py,sha256=_DMiY9X95O_9sK2BSeeTb2yMWfStBwKFWwn6FUOXN4Q,2439networkx/generators/trees.py,sha256=KvKYhZwwSl1KKMyKBe_6G_UTpLwLLeqdWwRkWJ2Xxz4,36517networkx/generators/triads.py,sha256=7kScTf3ITDi3qsSa-IvGMpa9diEaFwQnRuIf3Tv4UBI,2452networkx/lazy_imports.py,sha256=pZWn3f6NCY-lGtViKQh11NJ5Cn-cXBKhvacMycg3844,5764networkx/linalg/__init__.py,sha256=7iyNZ_YYBnlsW8zSfhUgvEkywOrUWfpIuyS86ZOKlG8,568networkx/linalg/algebraicconnectivity.py,sha256=qAjHk8Ew2av9HM-Sevf99alKHWkeo4R76U-1SFn2so8,20790networkx/linalg/attrmatrix.py,sha256=gG2cZZm4N7PQhXuq5nxZq1S_OmW61641rdRnrDiX_ws,15900networkx/linalg/bethehessianmatrix.py,sha256=Q5dJZOMopwWnvpSdebfo9QSQABEmLy-z1_hGCWsopDo,2513networkx/linalg/graphmatrix.py,sha256=NIs2uWGS_8lJJ5IQ8Og9aIWHawghtlCDWifqOIKV2-c,5623networkx/linalg/laplacianmatrix.py,sha256=YrzwLTLoGIisJVS2NLaD9g4fA3VDKzlYo1u3yOCVrF4,16722networkx/linalg/modularitymatrix.py,sha256=R_VITtgIkGenxlsCLN4u6CYxj3_HiPXfeU29yarntRo,4706networkx/linalg/spectrum.py,sha256=aRY7ApYv5HxrO_4O8brxpZRw3SJU3fYzlgMwhEIXcrc,4215networkx/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/linalg/tests/test_algebraic_connectivity.py,sha256=uXq7h1fCmvcUyJhh3DujyZvJH2SGlgo-JRdLbff3bKI,13735networkx/linalg/tests/test_attrmatrix.py,sha256=I8p_ME5Cq__SZJoxla1y5ynGaa_b4UruZRcuzPOh_wE,2833networkx/linalg/tests/test_bethehessian.py,sha256=WQM3H_y1GWrtM2B659HYQ2vvYGs-4H9V1qeo3Bx75B4,1268networkx/linalg/tests/test_graphmatrix.py,sha256=6y-DSezX5slSms8LtEJcoggI4wP_duBqodNYWKKvM4w,8655networkx/linalg/tests/test_laplacian.py,sha256=sIJ64KVVCUcK3b4ohF-443222vR64myIlV6addwwfWs,13953networkx/linalg/tests/test_modularity.py,sha256=Xs7iaUr_QqcxG0t0xHx54iYbM2VyQNmFeANovTMJomE,3056networkx/linalg/tests/test_spectrum.py,sha256=Hrl3FE0Z0u4urwY5eNMx0VcH4IRTYgudT04EmfhkosA,2769networkx/readwrite/__init__.py,sha256=TvSbnGEHQ5F9CY2tkpjWYOyrUj6BeW3sc6P4_IczbKA,561networkx/readwrite/adjlist.py,sha256=XkmtOO-aP-BGLoIjMoSXEOhCIEQz1TJcSrhMHGPCJTc,9050networkx/readwrite/edgelist.py,sha256=XwemCOs-xNet3mVIGpxol3RgFVJVa1iXsgBonAHDmug,14292networkx/readwrite/gexf.py,sha256=B5rj7Ra1XHSZR4qO5DRJMAEgWwQfiL0IKlE85fzQZ5Q,40438networkx/readwrite/gml.py,sha256=JcP0hsDKwpZOPzZeXdoEiKBBNd94Ox8y7_cjT5AVBT4,31193networkx/readwrite/graph6.py,sha256=dED6yWelHARFvyKniX8xSTtqj1-asDs1vUBWuZOG9cA,11684networkx/readwrite/graphml.py,sha256=sb-D5I5gmqyNj_TSNUvLn-96NBXtOAPFMEKvT3mkdTw,39326networkx/readwrite/json_graph/__init__.py,sha256=37XJPMmilcwwo8KqouLWUly7Yv5tZ7IKraMHbBRx3fI,677networkx/readwrite/json_graph/adjacency.py,sha256=WM6fdncV87WDLPOfF-IbOlOOBMX0utUjJ09UsxtwRAo,4716networkx/readwrite/json_graph/cytoscape.py,sha256=NaHGbwLuQCx_GB5R7Uag2ACKSmrpCFQKsRk3y9hE6Io,5841networkx/readwrite/json_graph/node_link.py,sha256=9hr4sk2fIHYDPuwSyyGNLNKDhahf6aFAEsIRhd5V890,7850networkx/readwrite/json_graph/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/readwrite/json_graph/tests/test_adjacency.py,sha256=jueQE3Z_W5BZuCjr0hEsOWSfoQ2fP51p0o0m7IcXUuE,2456networkx/readwrite/json_graph/tests/test_cytoscape.py,sha256=vFoDzcSRI9THlmp4Fu2HHhIF9AUmECWs5mftVWjaWWs,2044networkx/readwrite/json_graph/tests/test_node_link.py,sha256=3RbMNRlLBLN86EG4YyCvNmA3ISzmECqr17EqTcov3kI,3364networkx/readwrite/json_graph/tests/test_tree.py,sha256=zBXv3_db2XGxFs3XQ35btNf_ku52aLXXiHZmmX4ixAs,1352networkx/readwrite/json_graph/tree.py,sha256=K4rF4Kds4g0JhgcPTrrR_I3Pswpze8yCVH4M-WF9nn0,3851networkx/readwrite/leda.py,sha256=mtuIRKecfykiInePt-oIw91JB1vIgNXuUEbuBInO7Hs,2852networkx/readwrite/multiline_adjlist.py,sha256=TyvVZih3DIYaCQ6MC7XF8GuGBfcYIX-q-ccYu2Qs05M,11384networkx/readwrite/p2g.py,sha256=wDPg_3u42rlsv8pFtVLbZIjo-BN6dd95jCxFAoEC_6E,3253networkx/readwrite/pajek.py,sha256=0Xli27YbjyW5Ny6-qqVOtBmhZkPj4i3cJPvwjU3mMjM,8746networkx/readwrite/sparse6.py,sha256=kGEbDmnK1qcR5I6LZnPKYXLe7Qp6esT6gftkwSt1xcs,10442networkx/readwrite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/readwrite/tests/test_adjlist.py,sha256=aCDyLpv8cekWwEZgv5rB4gtwUvor7_YDArTYvL2ngPs,12756networkx/readwrite/tests/test_edgelist.py,sha256=5_rZ5rI_o8VDJr-R4besR-XcPwKY8-dHn4VmrrlBorc,10190networkx/readwrite/tests/test_gexf.py,sha256=TJLCj0ULSewUt5PlqEuoD8yhZoc6jFPqElIyQYhoKz0,21327networkx/readwrite/tests/test_gml.py,sha256=SIuCCSoH9psZdjKkrJfdGHbMROhUsfms70B71rnozUU,21399networkx/readwrite/tests/test_graph6.py,sha256=WMQmTgrI_VDcli1Gl5cjM17EFKc8_AkwoR14FLS1sXQ,6559networkx/readwrite/tests/test_graphml.py,sha256=RHZqs_-0Vw_NboMK1Sq65Nmk_XPAjfvnsgiPCptnpnI,67633networkx/readwrite/tests/test_leda.py,sha256=_5F4nLLQ1oAZQMZtTQoFncZL0Oc-IsztFBglEdQeH3k,1392networkx/readwrite/tests/test_p2g.py,sha256=0kvtohQuM2zjw88ogoDMhVbFcm85R3Sk2_yFdQ7TcWg,1319networkx/readwrite/tests/test_pajek.py,sha256=VxMk_TXQE1R-2t2B2OTSkwvPepKNYwExDbdlTDb0SOM,4696networkx/readwrite/tests/test_sparse6.py,sha256=zpd0hUPtOqwAJiuke4FXWFaQVa6Fa47dgIdHpCWXQ6U,5288networkx/readwrite/tests/test_text.py,sha256=x1N97hD31HPkj9Wn2PYti5-gcwaFNnStkaN_38HKnIg,55319networkx/readwrite/text.py,sha256=u62a-zG_7NpJD4Bh6kBZbUntORVM4XZId9zGX9wJBGQ,29140networkx/relabel.py,sha256=0HptAQOBToKhLZzxscd6FQpzVCNMlYmiHjHul69ct8o,10300networkx/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/tests/test_all_random_functions.py,sha256=T6bYvfqCmBfqOHAAJAqCv95VceTqdT32cN740HZTWH0,8549networkx/tests/test_convert.py,sha256=SoIVrqJFF9Gu9Jff_apfbpqg8QhkfC6QW4qzoSM-ukM,12731networkx/tests/test_convert_numpy.py,sha256=wivMBF5pmDd2FdrHX72J4Xt26IxTIfb12G-t-TWch40,19032networkx/tests/test_convert_pandas.py,sha256=VXumRYNIV2jdr4dfDsRidqpUDXHlgbhAFhaiqWlcx6s,13361networkx/tests/test_convert_scipy.py,sha256=IO9Xfke5Vk0SC4c7UR4YbQMjVZBuADQBt_wlMaOxTSQ,10381networkx/tests/test_exceptions.py,sha256=XYkpPzqMepSw3MPRUJN5LcFsUsy3YT_fiRDhm0OeAeQ,927networkx/tests/test_import.py,sha256=Gm4ujfH9JkQtDrSjOlwXXXUuubI057wskKLCkF6Z92k,220networkx/tests/test_lazy_imports.py,sha256=PylxEvRtD8ekwH-1M1sjnV_4uyhCYQl4WvlyF6ah0wo,2675networkx/tests/test_relabel.py,sha256=2qua3Z45m9mXkBQYmD82h17-pK6fYHJLpntn6ILj9cg,14554networkx/tests/test_removed_functions_exception_messages.py,sha256=V6AyU-RHQmilakEMJ1kpK4HSgzKbmimIxu0pBQ1DVaY,177networkx/utils/__init__.py,sha256=7pxleRNpBWuL3FEQz3CzKLn17b6_eSwkM7dqnL1okDk,302networkx/utils/backends.py,sha256=IDXNJjBWOfcqPm3Any5-kfwU9hZTH33R16gr3vZ6wnE,96862networkx/utils/configs.py,sha256=1LFNHgkR6CdXxTpNT8j4QdQ5vn5r7BTzPlxFYrEm7_E,15440networkx/utils/decorators.py,sha256=rRgAZw6glxOBYN6n5kkbQ7RS43EH3eVbJ5F91-uk0IM,44713networkx/utils/heaps.py,sha256=98tdylWKqrLQKdNlpjT2NvIpuOF2mT2Lhh5OzVg3Hu8,10355networkx/utils/mapped_queue.py,sha256=WdIRk27D_ArmPs9tdpvQLQCV4Tmus212BQhxsFIMYgk,10184networkx/utils/misc.py,sha256=zifBxwKM3msQsmMVg5vAMDo84ZPByU_yEig0VPS0iek,22844networkx/utils/random_sequence.py,sha256=kk3F8_5cazolIeSL_eDdZzQ15aB3b5lHazef9kM1NNw,5303networkx/utils/rcm.py,sha256=t2LJq6BG39JnPl_353nM8eDfGWy3LVL8BdrBZCcAy2g,4618networkx/utils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0networkx/utils/tests/test__init.py,sha256=QE0i-lNE4pG2eYjB2mZ0uw7jPD-7TdL7Y9p73JoWQmo,363networkx/utils/tests/test_backends.py,sha256=VzzgmdT_ymvQ7EKB4BbdntkBYaO5w6OgXzvr7pbgQsY,7784networkx/utils/tests/test_config.py,sha256=eBAiwADWJgCAIyJjgF3-zn89VPIGftiWMWyccpFnyMU,8717networkx/utils/tests/test_decorators.py,sha256=dm3b5yiQPlnlT_4pSm0FwK-xBGV9dcnhv14Vh9Jiz1o,14050networkx/utils/tests/test_heaps.py,sha256=qCuWMzpcMH1Gwu014CAams78o151QD5YL0mB1fz16Yw,3711networkx/utils/tests/test_mapped_queue.py,sha256=l1Nguzz68Fv91FnAT7y7B0GXSoje9uoWiObHo7TliGM,7354networkx/utils/tests/test_misc.py,sha256=3rKc5wy3qAwk1JdVZYD8FaTF4_4Y1_Tq1nbza6eR_jc,13965networkx/utils/tests/test_random_sequence.py,sha256=yvfWhJQJJqM1W-_etHo7BsLXA18YiHcLaF-IdhSwcYA,1502networkx/utils/tests/test_rcm.py,sha256=UvUAkgmQMGk_Nn94TJyQsle4A5SLQFqMQWld1tiQ2lk,1421networkx/utils/tests/test_unionfind.py,sha256=j-DF5XyeJzq1hoeAgN5Nye2Au7EPD040t8oS4Aw2IwU,1579networkx/utils/union_find.py,sha256=NxKlBlyS71A1Wlnt28L-wyZoI9ExZvJth_0e2XSVris,333812345Wheel-Version: 1.0Generator: setuptools (80.9.0)Root-Is-Purelib: trueTag: py3-none-any
12[networkx.backends]nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface12345678910111213141516171819202122232425262728293031323334353637NetworkX is distributed with the 3-clause BSD license.
::
Copyright (c) 2004-2025, NetworkX Developers Aric Hagberg <hagberg@lanl.gov> Dan Schult <dschult@colgate.edu> Pieter Swart <swart@lanl.gov> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the NetworkX Developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.1networkx123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650"""Algebraic connectivity and Fiedler vectors of undirected graphs."""
import networkx as nxfrom networkx.utils import ( not_implemented_for, np_random_state, reverse_cuthill_mckee_ordering,)
__all__ = [ "algebraic_connectivity", "fiedler_vector", "spectral_ordering", "spectral_bisection",]
class _PCGSolver: """Preconditioned conjugate gradient method.
To solve Ax = b: M = A.diagonal() # or some other preconditioner solver = _PCGSolver(lambda x: A * x, lambda x: M * x) x = solver.solve(b)
The inputs A and M are functions which compute matrix multiplication on the argument. A - multiply by the matrix A in Ax=b M - multiply by M, the preconditioner surrogate for A
Warning: There is no limit on number of iterations. """
def __init__(self, A, M): self._A = A self._M = M
def solve(self, B, tol): import numpy as np
# Densifying step - can this be kept sparse? B = np.asarray(B) X = np.ndarray(B.shape, order="F") for j in range(B.shape[1]): X[:, j] = self._solve(B[:, j], tol) return X
def _solve(self, b, tol): import numpy as np import scipy as sp
A = self._A M = self._M tol *= sp.linalg.blas.dasum(b) # Initialize. x = np.zeros(b.shape) r = b.copy() z = M(r) rz = sp.linalg.blas.ddot(r, z) p = z.copy() # Iterate. while True: Ap = A(p) alpha = rz / sp.linalg.blas.ddot(p, Ap) x = sp.linalg.blas.daxpy(p, x, a=alpha) r = sp.linalg.blas.daxpy(Ap, r, a=-alpha) if sp.linalg.blas.dasum(r) < tol: return x z = M(r) beta = sp.linalg.blas.ddot(r, z) beta, rz = beta / rz, beta p = sp.linalg.blas.daxpy(p, z, a=beta)
class _LUSolver: """LU factorization.
To solve Ax = b: solver = _LUSolver(A) x = solver.solve(b)
optional argument `tol` on solve method is ignored but included to match _PCGsolver API. """
def __init__(self, A): import scipy as sp
self._LU = sp.sparse.linalg.splu( A, permc_spec="MMD_AT_PLUS_A", diag_pivot_thresh=0.0, options={"Equil": True, "SymmetricMode": True}, )
def solve(self, B, tol=None): import numpy as np
B = np.asarray(B) X = np.ndarray(B.shape, order="F") for j in range(B.shape[1]): X[:, j] = self._LU.solve(B[:, j]) return X
def _preprocess_graph(G, weight): """Compute edge weights and eliminate zero-weight edges.""" if G.is_directed(): H = nx.MultiGraph() H.add_nodes_from(G) H.add_weighted_edges_from( ((u, v, e.get(weight, 1.0)) for u, v, e in G.edges(data=True) if u != v), weight=weight, ) G = H if not G.is_multigraph(): edges = ( (u, v, abs(e.get(weight, 1.0))) for u, v, e in G.edges(data=True) if u != v ) else: edges = ( (u, v, sum(abs(e.get(weight, 1.0)) for e in G[u][v].values())) for u, v in G.edges() if u != v ) H = nx.Graph() H.add_nodes_from(G) H.add_weighted_edges_from((u, v, e) for u, v, e in edges if e != 0) return H
def _rcm_estimate(G, nodelist): """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering.""" import numpy as np
G = G.subgraph(nodelist) order = reverse_cuthill_mckee_ordering(G) n = len(nodelist) index = dict(zip(nodelist, range(n))) x = np.ndarray(n, dtype=float) for i, u in enumerate(order): x[index[u]] = i x -= (n - 1) / 2.0 return x
def _tracemin_fiedler(L, X, normalized, tol, method): """Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
The Fiedler vector of a connected undirected graph is the eigenvector corresponding to the second smallest eigenvalue of the Laplacian matrix of the graph. This function starts with the Laplacian L, not the Graph.
Parameters ---------- L : Laplacian of a possibly weighted or normalized, but undirected graph
X : Initial guess for a solution. Usually a matrix of random numbers. This function allows more than one column in X to identify more than one eigenvector if desired.
normalized : bool Whether the normalized Laplacian matrix is used.
tol : float Tolerance of relative residual in eigenvalue computation. Warning: There is no limit on number of iterations.
method : string Should be 'tracemin_pcg' or 'tracemin_lu'. Otherwise exception is raised.
Returns ------- sigma, X : Two NumPy arrays of floats. The lowest eigenvalues and corresponding eigenvectors of L. The size of input X determines the size of these outputs. As this is for Fiedler vectors, the zero eigenvalue (and constant eigenvector) are avoided. """ import numpy as np import scipy as sp
n = X.shape[0]
if normalized: # Form the normalized Laplacian matrix and determine the eigenvector of # its nullspace. e = np.sqrt(L.diagonal()) D = sp.sparse.dia_array((1 / e, 0), shape=(n, n)).tocsr() L = D @ L @ D e *= 1.0 / np.linalg.norm(e, 2)
if normalized:
def project(X): """Make X orthogonal to the nullspace of L.""" X = np.asarray(X) for j in range(X.shape[1]): X[:, j] -= (X[:, j] @ e) * e
else:
def project(X): """Make X orthogonal to the nullspace of L.""" X = np.asarray(X) for j in range(X.shape[1]): X[:, j] -= X[:, j].sum() / n
if method == "tracemin_pcg": D = L.diagonal().astype(float) solver = _PCGSolver(lambda x: L @ x, lambda x: D * x) elif method == "tracemin_lu": # Convert A to CSC to suppress SparseEfficiencyWarning. A = sp.sparse.csc_array(L, dtype=float, copy=True) # Force A to be nonsingular. Since A is the Laplacian matrix of a # connected graph, its rank deficiency is one, and thus one diagonal # element needs to modified. Changing to infinity forces a zero in the # corresponding element in the solution. i = (A.indptr[1:] - A.indptr[:-1]).argmax() A[i, i] = np.inf solver = _LUSolver(A) else: raise nx.NetworkXError(f"Unknown linear system solver: {method}")
# Initialize. Lnorm = abs(L).sum(axis=1).flatten().max() project(X) W = np.ndarray(X.shape, order="F")
while True: # Orthonormalize X. X = np.linalg.qr(X)[0] # Compute iteration matrix H. W[:, :] = L @ X H = X.T @ W sigma, Y = sp.linalg.eigh(H, overwrite_a=True) # Compute the Ritz vectors. X = X @ Y # Test for convergence exploiting the fact that L * X == W * Y. res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm if res < tol: break # Compute X = L \ X / (X' * (L \ X)). # L \ X can have an arbitrary projection on the nullspace of L, # which will be eliminated. W[:, :] = solver.solve(X, tol) X = (sp.linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order. project(X)
return sigma, np.asarray(X)
def _get_fiedler_func(method): """Returns a function that solves the Fiedler eigenvalue problem.""" import numpy as np
if method == "tracemin": # old style keyword <v2.1 method = "tracemin_pcg" if method in ("tracemin_pcg", "tracemin_lu"):
def find_fiedler(L, x, normalized, tol, seed): q = 1 if method == "tracemin_pcg" else min(4, L.shape[0] - 1) X = np.asarray(seed.normal(size=(q, L.shape[0]))).T sigma, X = _tracemin_fiedler(L, X, normalized, tol, method) return sigma[0], X[:, 0]
elif method == "lanczos" or method == "lobpcg":
def find_fiedler(L, x, normalized, tol, seed): import scipy as sp
L = sp.sparse.csc_array(L, dtype=float) n = L.shape[0] if normalized: D = sp.sparse.dia_array( (1.0 / np.sqrt(L.diagonal()), 0), shape=(n, n) ).tocsc() L = D @ L @ D if method == "lanczos" or n < 10: # Avoid LOBPCG when n < 10 due to # https://github.com/scipy/scipy/issues/3592 # https://github.com/scipy/scipy/pull/3594 sigma, X = sp.sparse.linalg.eigsh( L, 2, which="SM", tol=tol, return_eigenvectors=True ) return sigma[1], X[:, 1] else: X = np.asarray(np.atleast_2d(x).T) M = sp.sparse.dia_array((1.0 / L.diagonal(), 0), shape=(n, n)).tocsr() Y = np.ones(n) if normalized: Y /= D.diagonal() sigma, X = sp.sparse.linalg.lobpcg( L, X, M=M, Y=np.atleast_2d(Y).T, tol=tol, maxiter=n, largest=False ) return sigma[0], X[:, 0]
else: raise nx.NetworkXError(f"unknown method {method!r}.")
return find_fiedler
@not_implemented_for("directed")@np_random_state(5)@nx._dispatchable(edge_attrs="weight")def algebraic_connectivity( G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None): r"""Returns the algebraic connectivity of an undirected graph.
The algebraic connectivity of a connected undirected graph is the second smallest eigenvalue of its Laplacian matrix.
Parameters ---------- G : NetworkX graph An undirected graph.
weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight.
normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used.
tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation.
method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG).
The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used.
=============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ========================================
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- algebraic_connectivity : float Algebraic connectivity.
Raises ------ NetworkXNotImplemented If G is directed.
NetworkXError If G has less than two nodes.
Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored.
See Also -------- laplacian_matrix
Examples -------- For undirected graphs algebraic connectivity can tell us if a graph is connected or not `G` is connected iff ``algebraic_connectivity(G) > 0``:
>>> G = nx.complete_graph(5) >>> nx.algebraic_connectivity(G) > 0 True >>> G.add_node(10) # G is no longer connected >>> nx.algebraic_connectivity(G) > 0 False
""" if len(G) < 2: raise nx.NetworkXError("graph has less than two nodes.") G = _preprocess_graph(G, weight) if not nx.is_connected(G): return 0.0
L = nx.laplacian_matrix(G) if L.shape[0] == 2: return 2.0 * float(L[0, 0]) if not normalized else 2.0
find_fiedler = _get_fiedler_func(method) x = None if method != "lobpcg" else _rcm_estimate(G, G) sigma, fiedler = find_fiedler(L, x, normalized, tol, seed) return float(sigma)
@not_implemented_for("directed")@np_random_state(5)@nx._dispatchable(edge_attrs="weight")def fiedler_vector( G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None): """Returns the Fiedler vector of a connected undirected graph.
The Fiedler vector of a connected undirected graph is the eigenvector corresponding to the second smallest eigenvalue of the Laplacian matrix of the graph.
Parameters ---------- G : NetworkX graph An undirected graph.
weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight.
normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used.
tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation.
method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG).
The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used.
=============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ========================================
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- fiedler_vector : NumPy array of floats. Fiedler vector.
Raises ------ NetworkXNotImplemented If G is directed.
NetworkXError If G has less than two nodes or is not connected.
Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored.
See Also -------- laplacian_matrix
Examples -------- Given a connected graph the signs of the values in the Fiedler vector can be used to partition the graph into two components.
>>> G = nx.barbell_graph(5, 0) >>> nx.fiedler_vector(G, normalized=True, seed=1) array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899, 0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129])
The connected components are the two 5-node cliques of the barbell graph. """ import numpy as np
if len(G) < 2: raise nx.NetworkXError("graph has less than two nodes.") G = _preprocess_graph(G, weight) if not nx.is_connected(G): raise nx.NetworkXError("graph is not connected.")
if len(G) == 2: return np.array([1.0, -1.0])
find_fiedler = _get_fiedler_func(method) L = nx.laplacian_matrix(G) x = None if method != "lobpcg" else _rcm_estimate(G, G) sigma, fiedler = find_fiedler(L, x, normalized, tol, seed) return fiedler
@np_random_state(5)@nx._dispatchable(edge_attrs="weight")def spectral_ordering( G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None): """Compute the spectral_ordering of a graph.
The spectral ordering of a graph is an ordering of its nodes where nodes in the same weakly connected components appear contiguous and ordered by their corresponding elements in the Fiedler vector of the component.
Parameters ---------- G : NetworkX graph A graph.
weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight.
normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used.
tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation.
method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG).
The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used.
=============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ========================================
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- spectral_ordering : NumPy array of floats. Spectral ordering of nodes.
Raises ------ NetworkXError If G is empty.
Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored.
See Also -------- laplacian_matrix """ if len(G) == 0: raise nx.NetworkXError("graph is empty.") G = _preprocess_graph(G, weight)
find_fiedler = _get_fiedler_func(method) order = [] for component in nx.connected_components(G): size = len(component) if size > 2: L = nx.laplacian_matrix(G, component) x = None if method != "lobpcg" else _rcm_estimate(G, component) sigma, fiedler = find_fiedler(L, x, normalized, tol, seed) sort_info = zip(fiedler, range(size), component) order.extend(u for x, c, u in sorted(sort_info)) else: order.extend(component)
return order
@nx._dispatchable(edge_attrs="weight")def spectral_bisection( G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None): """Bisect the graph using the Fiedler vector.
This method uses the Fiedler vector to bisect a graph. The partition is defined by the nodes which are associated with either positive or negative values in the vector.
Parameters ---------- G : NetworkX Graph
weight : str, optional (default: weight) The data key used to determine the weight of each edge. If None, then each edge has unit weight.
normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used.
tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation.
method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG).
The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used.
=============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ========================================
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- bisection : tuple of sets Sets with the bisection of nodes
Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.spectral_bisection(G) ({0, 1, 2}, {3, 4, 5})
References ---------- .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370 Oxford University Press 2011. """ import numpy as np
v = nx.fiedler_vector(G, weight, normalized, tol, method, seed) nodes = np.array(list(G)) pos_vals = v >= 0
return set(nodes[~pos_vals].tolist()), set(nodes[pos_vals].tolist())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466"""Functions for constructing matrix-like objects from graph attributes."""
import networkx as nx
__all__ = ["attr_matrix", "attr_sparse_matrix"]
def _node_value(G, node_attr): """Returns a function that returns a value from G.nodes[u].
We return a function expecting a node as its sole argument. Then, in the simplest scenario, the returned function will return G.nodes[u][node_attr]. However, we also handle the case when `node_attr` is None (returns the node) or when `node_attr` is a function itself.
Parameters ---------- G : graph A NetworkX graph
node_attr : {None, str, callable} Specification of how the value of the node attribute should be obtained from the node attribute dictionary.
Returns ------- value : function A function expecting a node as its sole argument. The function will returns a value from G.nodes[u] that depends on `edge_attr`.
""" if node_attr is None:
def value(u): return u
elif not callable(node_attr): # assume it is a key for the node attribute dictionary def value(u): return G.nodes[u][node_attr]
else: # Advanced: Allow users to specify something else. # # For example, # node_attr = lambda u: G.nodes[u].get('size', .5) * 3 # value = node_attr
return value
def _edge_value(G, edge_attr): """Returns a function that returns a value from G[u][v].
Suppose there exists an edge between u and v. Then we return a function expecting u and v as arguments. For Graph and DiGraph, G[u][v] is the edge attribute dictionary, and the function (essentially) returns G[u][v][edge_attr]. However, we also handle cases when `edge_attr` is None and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v] is a dictionary of all edges between u and v. In this case, the returned function sums the value of `edge_attr` for every edge between u and v.
Parameters ---------- G : graph A NetworkX graph
edge_attr : {None, str, callable} Specification of how the value of the edge attribute should be obtained from the edge attribute dictionary, G[u][v]. For multigraphs, G[u][v] is a dictionary of all the edges between u and v. This allows for special treatment of multiedges.
Returns ------- value : function A function expecting two nodes as parameters. The nodes should represent the from- and to- node of an edge. The function will return a value from G[u][v] that depends on `edge_attr`.
"""
if edge_attr is None: # topological count of edges
if G.is_multigraph():
def value(u, v): return len(G[u][v])
else:
def value(u, v): return 1
elif not callable(edge_attr): # assume it is a key for the edge attribute dictionary
if edge_attr == "weight": # provide a default value if G.is_multigraph():
def value(u, v): return sum(d.get(edge_attr, 1) for d in G[u][v].values())
else:
def value(u, v): return G[u][v].get(edge_attr, 1)
else: # otherwise, the edge attribute MUST exist for each edge if G.is_multigraph():
def value(u, v): return sum(d[edge_attr] for d in G[u][v].values())
else:
def value(u, v): return G[u][v][edge_attr]
else: # Advanced: Allow users to specify something else. # # Alternative default value: # edge_attr = lambda u,v: G[u][v].get('thickness', .5) # # Function on an attribute: # edge_attr = lambda u,v: abs(G[u][v]['weight']) # # Handle Multi(Di)Graphs differently: # edge_attr = lambda u,v: numpy.prod([d['size'] for d in G[u][v].values()]) # # Ignore multiple edges # edge_attr = lambda u,v: 1 if len(G[u][v]) else 0 # value = edge_attr
return value
@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")def attr_matrix( G, edge_attr=None, node_attr=None, normalized=False, rc_order=None, dtype=None, order=None,): """Returns the attribute matrix using attributes from `G` as a numpy array.
If only `G` is passed in, then the adjacency matrix is constructed.
Let A be a discrete set of values for the node attribute `node_attr`. Then the elements of A represent the rows and columns of the constructed matrix. Now, iterate through every edge e=(u,v) in `G` and consider the value of the edge attribute `edge_attr`. If ua and va are the values of the node attribute `node_attr` for u and v, respectively, then the value of the edge attribute is added to the matrix element at (ua, va).
Parameters ---------- G : graph The NetworkX graph used to construct the attribute matrix.
edge_attr : str, optional (default: number of edges for each matrix element) Each element of the matrix represents a running total of the specified edge attribute for edges whose node attributes correspond to the rows/cols of the matrix. The attribute must be present for all edges in the graph. If no attribute is specified, then we just count the number of edges whose node attributes correspond to the matrix element.
node_attr : str, optional (default: use nodes of the graph) Each row and column in the matrix represents a particular value of the node attribute. The attribute must be present for all nodes in the graph. Note, the values of this attribute should be reliably hashable. So, float values are not recommended. If no attribute is specified, then the rows and columns will be the nodes of the graph.
normalized : bool, optional (default: False) If True, then each row is normalized by the summation of its values.
rc_order : list, optional (default: order of nodes in G) A list of the node attribute values. This list specifies the ordering of rows and columns of the array. If no ordering is provided, then the ordering will be the same as the node order in `G`. When `rc_order` is `None`, the function returns a 2-tuple ``(matrix, ordering)``
Other Parameters ---------------- dtype : NumPy data-type, optional A valid NumPy dtype used to initialize the array. Keep in mind certain dtypes can yield unexpected results if the array is to be normalized. The parameter is passed to numpy.zeros(). If unspecified, the NumPy default is used.
order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. This parameter is passed to numpy.zeros(). If unspecified, the NumPy default is used.
Returns ------- M : 2D NumPy ndarray The attribute matrix.
ordering : list If `rc_order` was specified, then only the attribute matrix is returned. However, if `rc_order` was None, then the ordering used to construct the matrix is returned as well.
Examples -------- Construct an adjacency matrix:
>>> G = nx.Graph() >>> G.add_edge(0, 1, thickness=1, weight=3) >>> G.add_edge(0, 2, thickness=2) >>> G.add_edge(1, 2, thickness=3) >>> nx.attr_matrix(G, rc_order=[0, 1, 2]) array([[0., 1., 1.], [1., 0., 1.], [1., 1., 0.]])
Alternatively, we can obtain the matrix describing edge thickness.
>>> nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2]) array([[0., 1., 2.], [1., 0., 3.], [2., 3., 0.]])
We can also color the nodes and ask for the probability distribution over all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.nodes[0]["color"] = "red" >>> G.nodes[1]["color"] = "red" >>> G.nodes[2]["color"] = "blue" >>> rc = ["red", "blue"] >>> nx.attr_matrix(G, node_attr="color", normalized=True, rc_order=rc) array([[0.33333333, 0.66666667], [1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3 Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1 Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> nx.attr_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc) array([[3., 2.], [2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1) (red, blue) is 2 # contributions from edges (0,2) and (1,2) (blue, red) is 2 # same as (red, blue) since graph is undirected (blue, blue) is 0 # there are no edges with blue endpoints
""" import numpy as np
edge_value = _edge_value(G, edge_attr) node_value = _node_value(G, node_attr)
if rc_order is None: ordering = list({node_value(n) for n in G}) else: ordering = rc_order
N = len(ordering) undirected = not G.is_directed() index = dict(zip(ordering, range(N))) M = np.zeros((N, N), dtype=dtype, order=order)
seen = set() for u, nbrdict in G.adjacency(): for v in nbrdict: # Obtain the node attribute values. i, j = index[node_value(u)], index[node_value(v)] if v not in seen: M[i, j] += edge_value(u, v) if undirected: M[j, i] = M[i, j]
if undirected: seen.add(u)
if normalized: M /= M.sum(axis=1).reshape((N, 1))
if rc_order is None: return M, ordering else: return M
@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")def attr_sparse_matrix( G, edge_attr=None, node_attr=None, normalized=False, rc_order=None, dtype=None): """Returns a SciPy sparse array using attributes from G.
If only `G` is passed in, then the adjacency matrix is constructed.
Let A be a discrete set of values for the node attribute `node_attr`. Then the elements of A represent the rows and columns of the constructed matrix. Now, iterate through every edge e=(u,v) in `G` and consider the value of the edge attribute `edge_attr`. If ua and va are the values of the node attribute `node_attr` for u and v, respectively, then the value of the edge attribute is added to the matrix element at (ua, va).
Parameters ---------- G : graph The NetworkX graph used to construct the NumPy matrix.
edge_attr : str, optional (default: number of edges for each matrix element) Each element of the matrix represents a running total of the specified edge attribute for edges whose node attributes correspond to the rows/cols of the matrix. The attribute must be present for all edges in the graph. If no attribute is specified, then we just count the number of edges whose node attributes correspond to the matrix element.
node_attr : str, optional (default: use nodes of the graph) Each row and column in the matrix represents a particular value of the node attribute. The attribute must be present for all nodes in the graph. Note, the values of this attribute should be reliably hashable. So, float values are not recommended. If no attribute is specified, then the rows and columns will be the nodes of the graph.
normalized : bool, optional (default: False) If True, then each row is normalized by the summation of its values.
rc_order : list, optional (default: order of nodes in G) A list of the node attribute values. This list specifies the ordering of rows and columns of the array and the return value. If no ordering is provided, then the ordering will be that of nodes in `G`.
Other Parameters ---------------- dtype : NumPy data-type, optional A valid NumPy dtype used to initialize the array. Keep in mind certain dtypes can yield unexpected results if the array is to be normalized. The parameter is passed to numpy.zeros(). If unspecified, the NumPy default is used.
Returns ------- M : SciPy sparse array The attribute matrix.
ordering : list If `rc_order` was specified, then only the matrix is returned. However, if `rc_order` was None, then the ordering used to construct the matrix is returned as well.
Examples -------- Construct an adjacency matrix:
>>> G = nx.Graph() >>> G.add_edge(0, 1, thickness=1, weight=3) >>> G.add_edge(0, 2, thickness=2) >>> G.add_edge(1, 2, thickness=3) >>> M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2]) >>> M.toarray() array([[0., 1., 1.], [1., 0., 1.], [1., 1., 0.]])
Alternatively, we can obtain the matrix describing edge thickness.
>>> M = nx.attr_sparse_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2]) >>> M.toarray() array([[0., 1., 2.], [1., 0., 3.], [2., 3., 0.]])
We can also color the nodes and ask for the probability distribution over all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.nodes[0]["color"] = "red" >>> G.nodes[1]["color"] = "red" >>> G.nodes[2]["color"] = "blue" >>> rc = ["red", "blue"] >>> M = nx.attr_sparse_matrix(G, node_attr="color", normalized=True, rc_order=rc) >>> M.toarray() array([[0.33333333, 0.66666667], [1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3 Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1 Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> M = nx.attr_sparse_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc) >>> M.toarray() array([[3., 2.], [2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1) (red, blue) is 2 # contributions from edges (0,2) and (1,2) (blue, red) is 2 # same as (red, blue) since graph is undirected (blue, blue) is 0 # there are no edges with blue endpoints
""" import numpy as np import scipy as sp
edge_value = _edge_value(G, edge_attr) node_value = _node_value(G, node_attr)
if rc_order is None: ordering = list({node_value(n) for n in G}) else: ordering = rc_order
N = len(ordering) undirected = not G.is_directed() index = dict(zip(ordering, range(N))) M = sp.sparse.lil_array((N, N), dtype=dtype)
seen = set() for u, nbrdict in G.adjacency(): for v in nbrdict: # Obtain the node attribute values. i, j = index[node_value(u)], index[node_value(v)] if v not in seen: M[i, j] += edge_value(u, v) if undirected: M[j, i] = M[i, j]
if undirected: seen.add(u)
if normalized: M *= 1 / M.sum(axis=1)[:, np.newaxis] # in-place mult preserves sparse
if rc_order is None: return M, ordering else: return M1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Bethe Hessian or deformed Laplacian matrix of graphs."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["bethe_hessian_matrix"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef bethe_hessian_matrix(G, r=None, nodelist=None): r"""Returns the Bethe Hessian matrix of G.
The Bethe Hessian is a family of matrices parametrized by r, defined as H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the diagonal matrix of node degrees, and I is the identify matrix. It is equal to the graph laplacian when the regularizer r = 1.
The default choice of regularizer should be the ratio [2]_
.. math:: r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1
Parameters ---------- G : Graph A NetworkX graph r : float Regularizer parameter nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by ``G.nodes()``.
Returns ------- H : scipy.sparse.csr_array The Bethe Hessian matrix of `G`, with parameter `r`.
Examples -------- >>> k = [3, 2, 2, 1, 0] >>> G = nx.havel_hakimi_graph(k) >>> H = nx.bethe_hessian_matrix(G) >>> H.toarray() array([[ 3.5625, -1.25 , -1.25 , -1.25 , 0. ], [-1.25 , 2.5625, -1.25 , 0. , 0. ], [-1.25 , -1.25 , 2.5625, 0. , 0. ], [-1.25 , 0. , 0. , 1.5625, 0. ], [ 0. , 0. , 0. , 0. , 0.5625]])
See Also -------- bethe_hessian_spectrum adjacency_matrix laplacian_matrix
References ---------- .. [1] A. Saade, F. Krzakala and L. Zdeborová "Spectral Clustering of Graphs with the Bethe Hessian", Advances in Neural Information Processing Systems, 2014. .. [2] C. M. Le, E. Levina "Estimating the number of communities in networks by spectral methods" arXiv:1507.00827, 2015. """ import scipy as sp
if nodelist is None: nodelist = list(G) if r is None: r = sum(d**2 for v, d in nx.degree(G)) / sum(d for v, d in nx.degree(G)) - 1 A = nx.to_scipy_sparse_array(G, nodelist=nodelist, format="csr") n, m = A.shape D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(m, n)).tocsr() I = sp.sparse.eye_array(m, n, format="csr") return (r**2 - 1) * I - r * A + D123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Adjacency matrix and incidence matrix of graphs."""
import networkx as nx
__all__ = ["incidence_matrix", "adjacency_matrix"]
@nx._dispatchable(edge_attrs="weight")def incidence_matrix( G, nodelist=None, edgelist=None, oriented=False, weight=None, *, dtype=None): """Returns incidence matrix of G.
The incidence matrix assigns each row to a node and each column to an edge. For a standard incidence matrix a 1 appears wherever a row's node is incident on the column's edge. For an oriented incidence matrix each edge is assigned an orientation (arbitrarily for undirected and aligning to direction for directed). A -1 appears for the source (tail) of an edge and 1 for the destination (head) of the edge. The elements are zero otherwise.
Parameters ---------- G : graph A NetworkX graph
nodelist : list, optional (default= all nodes in G) The rows are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
edgelist : list, optional (default= all edges in G) The columns are ordered according to the edges in edgelist. If edgelist is None, then the ordering is produced by G.edges().
oriented: bool, optional (default=False) If True, matrix elements are +1 or -1 for the head or tail node respectively of each edge. If False, +1 occurs at both nodes.
weight : string or None, optional (default=None) The edge data key used to provide each value in the matrix. If None, then each edge has weight 1. Edge weights, if used, should be positive so that the orientation can provide the sign.
dtype : a NumPy dtype or None (default=None) The dtype of the output sparse array. This type should be a compatible type of the weight argument, eg. if weight would return a float this argument should also be a float. If None, then the default for SciPy is used.
Returns ------- A : SciPy sparse array The incidence matrix of G.
Notes ----- For MultiGraph/MultiDiGraph, the edges in edgelist should be (u,v,key) 3-tuples.
"Networks are the best discrete model for so many problems in applied mathematics" [1]_.
References ---------- .. [1] Gil Strang, Network applications: A = incidence matrix, http://videolectures.net/mit18085f07_strang_lec03/ """ import scipy as sp
if nodelist is None: nodelist = list(G) if edgelist is None: if G.is_multigraph(): edgelist = list(G.edges(keys=True)) else: edgelist = list(G.edges()) A = sp.sparse.lil_array((len(nodelist), len(edgelist)), dtype=dtype) node_index = {node: i for i, node in enumerate(nodelist)} for ei, e in enumerate(edgelist): (u, v) = e[:2] if u == v: continue # self loops give zero column try: ui = node_index[u] vi = node_index[v] except KeyError as err: raise nx.NetworkXError( f"node {u} or {v} in edgelist but not in nodelist" ) from err if weight is None: wt = 1 else: if G.is_multigraph(): ekey = e[2] wt = G[u][v][ekey].get(weight, 1) else: wt = G[u][v].get(weight, 1) if oriented: A[ui, ei] = -wt A[vi, ei] = wt else: A[ui, ei] = wt A[vi, ei] = wt return A.asformat("csc")
@nx._dispatchable(edge_attrs="weight")def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"): """Returns adjacency matrix of `G`.
Parameters ---------- G : graph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If ``nodelist=None`` (the default), then the ordering is produced by ``G.nodes()``.
dtype : NumPy data-type, optional The desired data-type for the array. If `None`, then the NumPy default is used.
weight : string or None, optional (default='weight') The edge data key used to provide each value in the matrix. If None, then each edge has weight 1.
Returns ------- A : SciPy sparse array Adjacency matrix representation of G.
Notes ----- For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
If you want a pure Python adjacency matrix representation try :func:`~networkx.convert.to_dict_of_dicts` which will return a dictionary-of-dictionaries format that can be addressed as a sparse matrix.
For multigraphs with parallel edges the weights are summed. See :func:`networkx.convert_matrix.to_numpy_array` for other options.
The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the edge weight attribute (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting SciPy sparse array can be modified as follows::
>>> G = nx.Graph([(1, 1)]) >>> A = nx.adjacency_matrix(G) >>> A.toarray() array([[1]]) >>> A.setdiag(A.diagonal() * 2) >>> A.toarray() array([[2]])
See Also -------- to_numpy_array to_scipy_sparse_array to_dict_of_dicts adjacency_spectrum """ return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512"""Laplacian matrix of graphs.
All calculations here are done using the out-degree. For Laplacians usingin-degree, use `G.reverse(copy=False)` instead of `G` and take the transpose.
The `laplacian_matrix` function provides an unnormalized matrix,while `normalized_laplacian_matrix`, `directed_laplacian_matrix`,and `directed_combinatorial_laplacian_matrix` are all normalized."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = [ "laplacian_matrix", "normalized_laplacian_matrix", "directed_laplacian_matrix", "directed_combinatorial_laplacian_matrix",]
@nx._dispatchable(edge_attrs="weight")def laplacian_matrix(G, nodelist=None, weight="weight"): """Returns the Laplacian matrix of G.
The graph Laplacian is the matrix L = D - A, where A is the adjacency matrix and D is the diagonal matrix of node degrees.
Parameters ---------- G : graph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
Returns ------- L : SciPy sparse array The Laplacian matrix of G.
Notes ----- For MultiGraph, the edges weights are summed.
This returns an unnormalized matrix. For a normalized output, use `normalized_laplacian_matrix`, `directed_laplacian_matrix`, or `directed_combinatorial_laplacian_matrix`.
This calculation uses the out-degree of the graph `G`. To use the in-degree for calculations instead, use `G.reverse(copy=False)` and take the transpose.
See Also -------- :func:`~networkx.convert_matrix.to_numpy_array` normalized_laplacian_matrix directed_laplacian_matrix directed_combinatorial_laplacian_matrix :func:`~networkx.linalg.spectrum.laplacian_spectrum`
Examples -------- For graphs with multiple connected components, L is permutation-similar to a block diagonal matrix where each block is the respective Laplacian matrix for each component.
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)]) >>> print(nx.laplacian_matrix(G).toarray()) [[ 1 -1 0 0 0] [-1 2 -1 0 0] [ 0 -1 1 0 0] [ 0 0 0 1 -1] [ 0 0 0 -1 1]]
>>> edges = [ ... (1, 2), ... (2, 1), ... (2, 4), ... (4, 3), ... (3, 4), ... ] >>> DiG = nx.DiGraph(edges) >>> print(nx.laplacian_matrix(DiG).toarray()) [[ 1 -1 0 0] [-1 2 -1 0] [ 0 0 1 -1] [ 0 0 -1 1]]
Notice that node 4 is represented by the third column and row. This is because by default the row/column order is the order of `G.nodes` (i.e. the node added order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).) To control the node order of the matrix, use the `nodelist` argument.
>>> print(nx.laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray()) [[ 1 -1 0 0] [-1 2 0 -1] [ 0 0 1 -1] [ 0 0 -1 1]]
This calculation uses the out-degree of the graph `G`. To use the in-degree for calculations instead, use `G.reverse(copy=False)` and take the transpose.
>>> print(nx.laplacian_matrix(DiG.reverse(copy=False)).toarray().T) [[ 1 -1 0 0] [-1 1 -1 0] [ 0 0 2 -1] [ 0 0 -1 1]]
References ---------- .. [1] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond: The Science of Search Engine Rankings. Princeton University Press, 2006.
""" import scipy as sp
if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr") n, m = A.shape D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(m, n)).tocsr() return D - A
@nx._dispatchable(edge_attrs="weight")def normalized_laplacian_matrix(G, nodelist=None, weight="weight"): r"""Returns the normalized Laplacian matrix of G.
The normalized graph Laplacian is the matrix
.. math::
N = D^{-1/2} L D^{-1/2}
where `L` is the graph Laplacian and `D` is the diagonal matrix of node degrees [1]_.
Parameters ---------- G : graph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
Returns ------- N : SciPy sparse array The normalized Laplacian matrix of G.
Notes ----- For MultiGraph, the edges weights are summed. See :func:`to_numpy_array` for other options.
If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is the adjacency matrix [2]_.
This calculation uses the out-degree of the graph `G`. To use the in-degree for calculations instead, use `G.reverse(copy=False)` and take the transpose.
For an unnormalized output, use `laplacian_matrix`.
Examples --------
>>> import numpy as np >>> edges = [ ... (1, 2), ... (2, 1), ... (2, 4), ... (4, 3), ... (3, 4), ... ] >>> DiG = nx.DiGraph(edges) >>> print(nx.normalized_laplacian_matrix(DiG).toarray()) [[ 1. -0.70710678 0. 0. ] [-0.70710678 1. -0.70710678 0. ] [ 0. 0. 1. -1. ] [ 0. 0. -1. 1. ]]
Notice that node 4 is represented by the third column and row. This is because by default the row/column order is the order of `G.nodes` (i.e. the node added order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).) To control the node order of the matrix, use the `nodelist` argument.
>>> print(nx.normalized_laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray()) [[ 1. -0.70710678 0. 0. ] [-0.70710678 1. 0. -0.70710678] [ 0. 0. 1. -1. ] [ 0. 0. -1. 1. ]] >>> G = nx.Graph(edges) >>> print(nx.normalized_laplacian_matrix(G).toarray()) [[ 1. -0.70710678 0. 0. ] [-0.70710678 1. -0.5 0. ] [ 0. -0.5 1. -0.70710678] [ 0. 0. -0.70710678 1. ]]
See Also -------- laplacian_matrix normalized_laplacian_spectrum directed_laplacian_matrix directed_combinatorial_laplacian_matrix
References ---------- .. [1] Fan Chung-Graham, Spectral Graph Theory, CBMS Regional Conference Series in Mathematics, Number 92, 1997. .. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98, March 2007. .. [3] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond: The Science of Search Engine Rankings. Princeton University Press, 2006. """ import numpy as np import scipy as sp
if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr") n, _ = A.shape diags = A.sum(axis=1) D = sp.sparse.dia_array((diags, 0), shape=(n, n)).tocsr() L = D - A with np.errstate(divide="ignore"): diags_sqrt = 1.0 / np.sqrt(diags) diags_sqrt[np.isinf(diags_sqrt)] = 0 DH = sp.sparse.dia_array((diags_sqrt, 0), shape=(n, n)).tocsr() return DH @ (L @ DH)
################################################################################ Code based on work from https://github.com/bjedwards
@not_implemented_for("undirected")@not_implemented_for("multigraph")@nx._dispatchable(edge_attrs="weight")def directed_laplacian_matrix( G, nodelist=None, weight="weight", walk_type=None, alpha=0.95): r"""Returns the directed Laplacian matrix of G.
The graph directed Laplacian is the matrix
.. math::
L = I - \frac{1}{2} \left (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} \right )
where `I` is the identity matrix, `P` is the transition matrix of the graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
Depending on the value of walk_type, `P` can be the transition matrix induced by a random walk, a lazy random walk, or a random walk with teleportation (PageRank).
Parameters ---------- G : DiGraph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
walk_type : string or None, optional (default=None) One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None`` (the default), then a value is selected according to the properties of `G`: - ``walk_type="random"`` if `G` is strongly connected and aperiodic - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic - ``walk_type="pagerank"`` for all other cases.
alpha : real (1 - alpha) is the teleportation probability used with pagerank
Returns ------- L : NumPy matrix Normalized Laplacian of G.
Notes ----- Only implemented for DiGraphs
The result is always a symmetric matrix.
This calculation uses the out-degree of the graph `G`. To use the in-degree for calculations instead, use `G.reverse(copy=False)` and take the transpose.
See Also -------- laplacian_matrix normalized_laplacian_matrix directed_combinatorial_laplacian_matrix
References ---------- .. [1] Fan Chung (2005). Laplacians and the Cheeger inequality for directed graphs. Annals of Combinatorics, 9(1), 2005 """ import numpy as np import scipy as sp
# NOTE: P has type ndarray if walk_type=="pagerank", else csr_array P = _transition_matrix( G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha )
n, m = P.shape
evals, evecs = sp.sparse.linalg.eigs(P.T, k=1) v = evecs.flatten().real p = v / v.sum() # p>=0 by Perron-Frobenius Thm. Use abs() to fix roundoff across zero gh-6865 sqrtp = np.sqrt(np.abs(p)) Q = ( sp.sparse.dia_array((sqrtp, 0), shape=(n, n)).tocsr() @ P @ sp.sparse.dia_array((1.0 / sqrtp, 0), shape=(n, n)).tocsr() ) # NOTE: This could be sparsified for the non-pagerank cases I = np.identity(len(G))
return I - (Q + Q.T) / 2.0
@not_implemented_for("undirected")@not_implemented_for("multigraph")@nx._dispatchable(edge_attrs="weight")def directed_combinatorial_laplacian_matrix( G, nodelist=None, weight="weight", walk_type=None, alpha=0.95): r"""Return the directed combinatorial Laplacian matrix of G.
The graph directed combinatorial Laplacian is the matrix
.. math::
L = \Phi - \frac{1}{2} \left (\Phi P + P^T \Phi \right)
where `P` is the transition matrix of the graph and `\Phi` a matrix with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
Depending on the value of walk_type, `P` can be the transition matrix induced by a random walk, a lazy random walk, or a random walk with teleportation (PageRank).
Parameters ---------- G : DiGraph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
walk_type : string or None, optional (default=None) One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None`` (the default), then a value is selected according to the properties of `G`: - ``walk_type="random"`` if `G` is strongly connected and aperiodic - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic - ``walk_type="pagerank"`` for all other cases.
alpha : real (1 - alpha) is the teleportation probability used with pagerank
Returns ------- L : NumPy matrix Combinatorial Laplacian of G.
Notes ----- Only implemented for DiGraphs
The result is always a symmetric matrix.
This calculation uses the out-degree of the graph `G`. To use the in-degree for calculations instead, use `G.reverse(copy=False)` and take the transpose.
See Also -------- laplacian_matrix normalized_laplacian_matrix directed_laplacian_matrix
References ---------- .. [1] Fan Chung (2005). Laplacians and the Cheeger inequality for directed graphs. Annals of Combinatorics, 9(1), 2005 """ import scipy as sp
P = _transition_matrix( G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha )
n, m = P.shape
evals, evecs = sp.sparse.linalg.eigs(P.T, k=1) v = evecs.flatten().real p = v / v.sum() # NOTE: could be improved by not densifying Phi = sp.sparse.dia_array((p, 0), shape=(n, n)).toarray()
return Phi - (Phi @ P + P.T @ Phi) / 2.0
def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha=0.95): """Returns the transition matrix of G.
This is a row stochastic giving the transition probabilities while performing a random walk on the graph. Depending on the value of walk_type, P can be the transition matrix induced by a random walk, a lazy random walk, or a random walk with teleportation (PageRank).
Parameters ---------- G : DiGraph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
walk_type : string or None, optional (default=None) One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None`` (the default), then a value is selected according to the properties of `G`: - ``walk_type="random"`` if `G` is strongly connected and aperiodic - ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic - ``walk_type="pagerank"`` for all other cases.
alpha : real (1 - alpha) is the teleportation probability used with pagerank
Returns ------- P : numpy.ndarray transition matrix of G.
Raises ------ NetworkXError If walk_type not specified or alpha not in valid range """ import numpy as np import scipy as sp
if walk_type is None: if nx.is_strongly_connected(G): if nx.is_aperiodic(G): walk_type = "random" else: walk_type = "lazy" else: walk_type = "pagerank"
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float) n, m = A.shape if walk_type in ["random", "lazy"]: DI = sp.sparse.dia_array((1.0 / A.sum(axis=1), 0), shape=(n, n)).tocsr() if walk_type == "random": P = DI @ A else: I = sp.sparse.eye_array(n, format="csr") P = (I + DI @ A) / 2.0
elif walk_type == "pagerank": if not (0 < alpha < 1): raise nx.NetworkXError("alpha must be between 0 and 1") # this is using a dense representation. NOTE: This should be sparsified! A = A.toarray() # add constant to dangling nodes' row A[A.sum(axis=1) == 0, :] = 1 / n # normalize A = A / A.sum(axis=1)[np.newaxis, :].T P = alpha * A + (1 - alpha) / n else: raise nx.NetworkXError("walk_type must be random, lazy, or pagerank")
return P123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Modularity matrix of graphs."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["modularity_matrix", "directed_modularity_matrix"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchable(edge_attrs="weight")def modularity_matrix(G, nodelist=None, weight=None): r"""Returns the modularity matrix of G.
The modularity matrix is the matrix B = A - <A>, where A is the adjacency matrix and <A> is the average adjacency matrix, assuming that the graph is described by the configuration model.
More specifically, the element B_ij of B is defined as
.. math:: A_{ij} - {k_i k_j \over 2 m}
where k_i is the degree of node i, and where m is the number of edges in the graph. When weight is set to a name of an attribute edge, Aij, k_i, k_j and m are computed using its value.
Parameters ---------- G : Graph A NetworkX graph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used for the edge weight. If None then all edge weights are 1.
Returns ------- B : Numpy array The modularity matrix of G.
Examples -------- >>> k = [3, 2, 2, 1, 0] >>> G = nx.havel_hakimi_graph(k) >>> B = nx.modularity_matrix(G)
See Also -------- to_numpy_array modularity_spectrum adjacency_matrix directed_modularity_matrix
References ---------- .. [1] M. E. J. Newman, "Modularity and community structure in networks", Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006. """ import numpy as np
if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr") k = A.sum(axis=1) m = k.sum() * 0.5 # Expected adjacency matrix X = np.outer(k, k) / (2 * m)
return A - X
@not_implemented_for("undirected")@not_implemented_for("multigraph")@nx._dispatchable(edge_attrs="weight")def directed_modularity_matrix(G, nodelist=None, weight=None): """Returns the directed modularity matrix of G.
The modularity matrix is the matrix B = A - <A>, where A is the adjacency matrix and <A> is the expected adjacency matrix, assuming that the graph is described by the configuration model.
More specifically, the element B_ij of B is defined as
.. math:: B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree of node j, with m the number of edges in the graph. When weight is set to a name of an attribute edge, Aij, k_i, k_j and m are computed using its value.
Parameters ---------- G : DiGraph A NetworkX DiGraph
nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used for the edge weight. If None then all edge weights are 1.
Returns ------- B : Numpy array The modularity matrix of G.
Examples -------- >>> G = nx.DiGraph() >>> G.add_edges_from( ... ( ... (1, 2), ... (1, 3), ... (3, 1), ... (3, 2), ... (3, 5), ... (4, 5), ... (4, 6), ... (5, 4), ... (5, 6), ... (6, 4), ... ) ... ) >>> B = nx.directed_modularity_matrix(G)
Notes ----- NetworkX defines the element A_ij of the adjacency matrix as 1 if there is a link going from node i to node j. Leicht and Newman use the opposite definition. This explains the different expression for B_ij.
See Also -------- to_numpy_array modularity_spectrum adjacency_matrix modularity_matrix
References ---------- .. [1] E. A. Leicht, M. E. J. Newman, "Community structure in directed networks", Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008. """ import numpy as np
if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr") k_in = A.sum(axis=0) k_out = A.sum(axis=1) m = k_in.sum() # Expected adjacency matrix X = np.outer(k_out, k_in) / m
return A - X123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186"""Eigenvalue spectrum of graphs."""
import networkx as nx
__all__ = [ "laplacian_spectrum", "adjacency_spectrum", "modularity_spectrum", "normalized_laplacian_spectrum", "bethe_hessian_spectrum",]
@nx._dispatchable(edge_attrs="weight")def laplacian_spectrum(G, weight="weight"): """Returns eigenvalues of the Laplacian of G
Parameters ---------- G : graph A NetworkX graph
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
Returns ------- evals : NumPy array Eigenvalues
Notes ----- For MultiGraph/MultiDiGraph, the edges weights are summed. See :func:`~networkx.convert_matrix.to_numpy_array` for other options.
See Also -------- laplacian_matrix
Examples -------- The multiplicity of 0 as an eigenvalue of the laplacian matrix is equal to the number of connected components of G.
>>> G = nx.Graph() # Create a graph with 5 nodes and 3 connected components >>> G.add_nodes_from(range(5)) >>> G.add_edges_from([(0, 2), (3, 4)]) >>> nx.laplacian_spectrum(G) array([0., 0., 0., 2., 2.])
""" import scipy as sp
return sp.linalg.eigvalsh(nx.laplacian_matrix(G, weight=weight).todense())
@nx._dispatchable(edge_attrs="weight")def normalized_laplacian_spectrum(G, weight="weight"): """Return eigenvalues of the normalized Laplacian of G
Parameters ---------- G : graph A NetworkX graph
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
Returns ------- evals : NumPy array Eigenvalues
Notes ----- For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_array for other options.
See Also -------- normalized_laplacian_matrix """ import scipy as sp
return sp.linalg.eigvalsh( nx.normalized_laplacian_matrix(G, weight=weight).todense() )
@nx._dispatchable(edge_attrs="weight")def adjacency_spectrum(G, weight="weight"): """Returns eigenvalues of the adjacency matrix of G.
Parameters ---------- G : graph A NetworkX graph
weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge has weight 1.
Returns ------- evals : NumPy array Eigenvalues
Notes ----- For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_array for other options.
See Also -------- adjacency_matrix """ import scipy as sp
return sp.linalg.eigvals(nx.adjacency_matrix(G, weight=weight).todense())
@nx._dispatchabledef modularity_spectrum(G): """Returns eigenvalues of the modularity matrix of G.
Parameters ---------- G : Graph A NetworkX Graph or DiGraph
Returns ------- evals : NumPy array Eigenvalues
See Also -------- modularity_matrix
References ---------- .. [1] M. E. J. Newman, "Modularity and community structure in networks", Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006. """ import scipy as sp
if G.is_directed(): return sp.linalg.eigvals(nx.directed_modularity_matrix(G)) else: return sp.linalg.eigvals(nx.modularity_matrix(G))
@nx._dispatchabledef bethe_hessian_spectrum(G, r=None): """Returns eigenvalues of the Bethe Hessian matrix of G.
Parameters ---------- G : Graph A NetworkX Graph or DiGraph
r : float Regularizer parameter
Returns ------- evals : NumPy array Eigenvalues
See Also -------- bethe_hessian_matrix
References ---------- .. [1] A. Saade, F. Krzakala and L. Zdeborová "Spectral clustering of graphs with the bethe hessian", Advances in Neural Information Processing Systems. 2014. """ import scipy as sp
return sp.linalg.eigvalsh(nx.bethe_hessian_matrix(G, r).todense())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400from math import sqrt
import pytest
import networkx as nx
np = pytest.importorskip("numpy")methods = ("tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg")
def test_algebraic_connectivity_tracemin_chol(): """Test that "tracemin_chol" raises an exception.""" pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) with pytest.raises(nx.NetworkXError): nx.algebraic_connectivity(G, method="tracemin_chol")
def test_fiedler_vector_tracemin_chol(): """Test that "tracemin_chol" raises an exception.""" pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) with pytest.raises(nx.NetworkXError): nx.fiedler_vector(G, method="tracemin_chol")
def test_spectral_ordering_tracemin_chol(): """Test that "tracemin_chol" raises an exception.""" pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) with pytest.raises(nx.NetworkXError): nx.spectral_ordering(G, method="tracemin_chol")
def test_fiedler_vector_tracemin_unknown(): """Test that "tracemin_unknown" raises an exception.""" pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) L = nx.laplacian_matrix(G) X = np.asarray(np.random.normal(size=(1, L.shape[0]))).T with pytest.raises(nx.NetworkXError, match="Unknown linear system solver"): nx.linalg.algebraicconnectivity._tracemin_fiedler( L, X, normalized=False, tol=1e-8, method="tracemin_unknown" )
def test_spectral_bisection(): pytest.importorskip("scipy") G = nx.barbell_graph(3, 0) C = nx.spectral_bisection(G) assert C == ({0, 1, 2}, {3, 4, 5})
mapping = dict(enumerate("badfec")) G = nx.relabel_nodes(G, mapping) C = nx.spectral_bisection(G) assert C == ( {mapping[0], mapping[1], mapping[2]}, {mapping[3], mapping[4], mapping[5]}, )
def check_eigenvector(A, l, x): nx = np.linalg.norm(x) # Check zeroness. assert nx != pytest.approx(0, abs=1e-07) y = A @ x ny = np.linalg.norm(y) # Check collinearity. assert x @ y == pytest.approx(nx * ny, abs=1e-7) # Check eigenvalue. assert ny == pytest.approx(l * nx, abs=1e-7)
class TestAlgebraicConnectivity: @pytest.mark.parametrize("method", methods) def test_directed(self, method): G = nx.DiGraph() pytest.raises( nx.NetworkXNotImplemented, nx.algebraic_connectivity, G, method=method ) pytest.raises(nx.NetworkXNotImplemented, nx.fiedler_vector, G, method=method)
@pytest.mark.parametrize("method", methods) def test_null_and_singleton(self, method): G = nx.Graph() pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method=method) pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method) G.add_edge(0, 0) pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method=method) pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
@pytest.mark.parametrize("method", methods) def test_disconnected(self, method): G = nx.Graph() G.add_nodes_from(range(2)) assert nx.algebraic_connectivity(G) == 0 pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method) G.add_edge(0, 1, weight=0) assert nx.algebraic_connectivity(G) == 0 pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
def test_unrecognized_method(self): pytest.importorskip("scipy") G = nx.path_graph(4) pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method="unknown") pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method="unknown")
@pytest.mark.parametrize("method", methods) def test_two_nodes(self, method): pytest.importorskip("scipy") G = nx.Graph() G.add_edge(0, 1, weight=1) A = nx.laplacian_matrix(G) assert nx.algebraic_connectivity(G, tol=1e-12, method=method) == pytest.approx( 2, abs=1e-7 ) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, 2, x)
@pytest.mark.parametrize("method", methods) def test_two_nodes_multigraph(self, method): pytest.importorskip("scipy") G = nx.MultiGraph() G.add_edge(0, 0, spam=1e8) G.add_edge(0, 1, spam=1) G.add_edge(0, 1, spam=-2) A = -3 * nx.laplacian_matrix(G, weight="spam") assert nx.algebraic_connectivity( G, weight="spam", tol=1e-12, method=method ) == pytest.approx(6, abs=1e-7) x = nx.fiedler_vector(G, weight="spam", tol=1e-12, method=method) check_eigenvector(A, 6, x)
def test_abbreviation_of_method(self): pytest.importorskip("scipy") G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) ac = nx.algebraic_connectivity(G, tol=1e-12, method="tracemin") assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method="tracemin") check_eigenvector(A, sigma, x)
@pytest.mark.parametrize("method", methods) def test_path(self, method): pytest.importorskip("scipy") G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
@pytest.mark.parametrize("method", methods) def test_problematic_graph_issue_2381(self, method): pytest.importorskip("scipy") G = nx.path_graph(4) G.add_edges_from([(4, 2), (5, 1)]) A = nx.laplacian_matrix(G) sigma = 0.438447187191 ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
@pytest.mark.parametrize("method", methods) def test_cycle(self, method): pytest.importorskip("scipy") G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method) assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method) check_eigenvector(A, sigma, x)
@pytest.mark.parametrize("method", methods) def test_seed_argument(self, method): pytest.importorskip("scipy") G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) ac = nx.algebraic_connectivity(G, tol=1e-12, method=method, seed=1) assert ac == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, tol=1e-12, method=method, seed=1) check_eigenvector(A, sigma, x)
@pytest.mark.parametrize( ("normalized", "sigma", "laplacian_fn"), ( (False, 0.2434017461399311, nx.laplacian_matrix), (True, 0.08113391537997749, nx.normalized_laplacian_matrix), ), ) @pytest.mark.parametrize("method", methods) def test_buckminsterfullerene(self, normalized, sigma, laplacian_fn, method): pytest.importorskip("scipy") G = nx.Graph( [ (1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6), (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56), (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12), (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53), (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27), (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54), (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42), (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58), (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51), (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56), (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45), (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49), (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47), (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55), (47, 54), (48, 55), ] ) A = laplacian_fn(G) try: assert nx.algebraic_connectivity( G, normalized=normalized, tol=1e-12, method=method ) == pytest.approx(sigma, abs=1e-7) x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method) check_eigenvector(A, sigma, x) except nx.NetworkXError as err: if err.args not in ( ("Cholesky solver unavailable.",), ("LU solver unavailable.",), ): raise
class TestSpectralOrdering: _graphs = (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
@pytest.mark.parametrize("graph", _graphs) def test_nullgraph(self, graph): G = graph() pytest.raises(nx.NetworkXError, nx.spectral_ordering, G)
@pytest.mark.parametrize("graph", _graphs) def test_singleton(self, graph): G = graph() G.add_node("x") assert nx.spectral_ordering(G) == ["x"] G.add_edge("x", "x", weight=33) G.add_edge("x", "x", weight=33) assert nx.spectral_ordering(G) == ["x"]
def test_unrecognized_method(self): G = nx.path_graph(4) pytest.raises(nx.NetworkXError, nx.spectral_ordering, G, method="unknown")
@pytest.mark.parametrize("method", methods) def test_three_nodes(self, method): pytest.importorskip("scipy") G = nx.Graph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1)], weight="spam") order = nx.spectral_ordering(G, weight="spam", method=method) assert set(order) == set(G) assert {1, 3} in (set(order[:-1]), set(order[1:]))
@pytest.mark.parametrize("method", methods) def test_three_nodes_multigraph(self, method): pytest.importorskip("scipy") G = nx.MultiDiGraph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1), (2, 3, 2)]) order = nx.spectral_ordering(G, method=method) assert set(order) == set(G) assert {2, 3} in (set(order[:-1]), set(order[1:]))
@pytest.mark.parametrize("method", methods) def test_path(self, method): pytest.importorskip("scipy") path = list(range(10)) np.random.shuffle(path) G = nx.Graph() nx.add_path(G, path) order = nx.spectral_ordering(G, method=method) assert order in [path, list(reversed(path))]
@pytest.mark.parametrize("method", methods) def test_seed_argument(self, method): pytest.importorskip("scipy") path = list(range(10)) np.random.shuffle(path) G = nx.Graph() nx.add_path(G, path) order = nx.spectral_ordering(G, method=method, seed=1) assert order in [path, list(reversed(path))]
@pytest.mark.parametrize("method", methods) def test_disconnected(self, method): pytest.importorskip("scipy") G = nx.Graph() nx.add_path(G, range(0, 10, 2)) nx.add_path(G, range(1, 10, 2)) order = nx.spectral_ordering(G, method=method) assert set(order) == set(G) seqs = [ list(range(0, 10, 2)), list(range(8, -1, -2)), list(range(1, 10, 2)), list(range(9, -1, -2)), ] assert order[:5] in seqs assert order[5:] in seqs
@pytest.mark.parametrize( ("normalized", "expected_order"), ( (False, [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8], [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]]), (True, [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8], [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]), ), ) @pytest.mark.parametrize("method", methods) def test_cycle(self, normalized, expected_order, method): pytest.importorskip("scipy") path = list(range(10)) G = nx.Graph() nx.add_path(G, path, weight=5) G.add_edge(path[-1], path[0], weight=1) A = nx.laplacian_matrix(G).todense() order = nx.spectral_ordering(G, normalized=normalized, method=method) assert order in expected_order123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import pytest
import networkx as nx
np = pytest.importorskip("numpy")
def test_attr_matrix(): G = nx.Graph() G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 2, thickness=2) G.add_edge(1, 2, thickness=3)
def node_attr(u): return G.nodes[u].get("size", 0.5) * 3
def edge_attr(u, v): return G[u][v].get("thickness", 0.5)
M = nx.attr_matrix(G, edge_attr=edge_attr, node_attr=node_attr) np.testing.assert_equal(M[0], np.array([[6.0]])) assert M[1] == [1.5]
def test_attr_matrix_directed(): G = nx.DiGraph() G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 2, thickness=2) G.add_edge(1, 2, thickness=3) M = nx.attr_matrix(G, rc_order=[0, 1, 2]) # fmt: off data = np.array( [[0., 1., 1.], [0., 0., 1.], [0., 0., 0.]] ) # fmt: on np.testing.assert_equal(M, np.array(data))
def test_attr_matrix_multigraph(): G = nx.MultiGraph() G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 2, thickness=2) G.add_edge(1, 2, thickness=3) M = nx.attr_matrix(G, rc_order=[0, 1, 2]) # fmt: off data = np.array( [[0., 3., 1.], [3., 0., 1.], [1., 1., 0.]] ) # fmt: on np.testing.assert_equal(M, np.array(data)) M = nx.attr_matrix(G, edge_attr="weight", rc_order=[0, 1, 2]) # fmt: off data = np.array( [[0., 9., 1.], [9., 0., 1.], [1., 1., 0.]] ) # fmt: on np.testing.assert_equal(M, np.array(data)) M = nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2]) # fmt: off data = np.array( [[0., 3., 2.], [3., 0., 3.], [2., 3., 0.]] ) # fmt: on np.testing.assert_equal(M, np.array(data))
def test_attr_sparse_matrix(): pytest.importorskip("scipy") G = nx.Graph() G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 2, thickness=2) G.add_edge(1, 2, thickness=3) M = nx.attr_sparse_matrix(G) mtx = M[0] data = np.ones((3, 3), float) np.fill_diagonal(data, 0) np.testing.assert_equal(mtx.todense(), np.array(data)) assert M[1] == [0, 1, 2]
def test_attr_sparse_matrix_directed(): pytest.importorskip("scipy") G = nx.DiGraph() G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 1, thickness=1, weight=3) G.add_edge(0, 2, thickness=2) G.add_edge(1, 2, thickness=3) M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2]) # fmt: off data = np.array( [[0., 1., 1.], [0., 0., 1.], [0., 0., 0.]] ) # fmt: on np.testing.assert_equal(M.todense(), np.array(data))12345678910111213141516171819202122232425262728293031323334353637383940import pytest
import networkx as nx
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
class TestBetheHessian: @classmethod def setup_class(cls): deg = [3, 2, 2, 1, 0] cls.G = nx.havel_hakimi_graph(deg) cls.P = nx.path_graph(3)
def test_bethe_hessian(self): "Bethe Hessian matrix" # fmt: off H = np.array([[4, -2, 0], [-2, 5, -2], [0, -2, 4]]) # fmt: on permutation = [2, 0, 1] # Bethe Hessian gives expected form np.testing.assert_equal(nx.bethe_hessian_matrix(self.P, r=2).todense(), H) # nodelist is correctly implemented np.testing.assert_equal( nx.bethe_hessian_matrix(self.P, r=2, nodelist=permutation).todense(), H[np.ix_(permutation, permutation)], ) # Equal to Laplacian matrix when r=1 np.testing.assert_equal( nx.bethe_hessian_matrix(self.G, r=1).todense(), nx.laplacian_matrix(self.G).todense(), ) # Correct default for the regularizer r np.testing.assert_equal( nx.bethe_hessian_matrix(self.G).todense(), nx.bethe_hessian_matrix(self.G, r=1.25).todense(), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275import pytest
import networkx as nxfrom networkx.exception import NetworkXError
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
def test_incidence_matrix_simple(): deg = [3, 2, 2, 1, 0] G = nx.havel_hakimi_graph(deg) deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)] MG = nx.random_clustered_graph(deg, seed=42)
I = nx.incidence_matrix(G, dtype=int).todense() # fmt: off expected = np.array( [[1, 1, 1, 0], [0, 1, 0, 1], [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]] ) # fmt: on np.testing.assert_equal(I, expected)
I = nx.incidence_matrix(MG, dtype=int).todense() # fmt: off expected = np.array( [[1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 0, 1]] ) # fmt: on np.testing.assert_equal(I, expected)
with pytest.raises(NetworkXError): nx.incidence_matrix(G, nodelist=[0, 1])
class TestGraphMatrix: @classmethod def setup_class(cls): deg = [3, 2, 2, 1, 0] cls.G = nx.havel_hakimi_graph(deg) # fmt: off cls.OI = np.array( [[-1, -1, -1, 0], [1, 0, 0, -1], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]] ) cls.A = np.array( [[0, 1, 1, 1, 0], [1, 0, 1, 0, 0], [1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0]] ) # fmt: on cls.WG = nx.havel_hakimi_graph(deg) cls.WG.add_edges_from( (u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.G.edges() ) # fmt: off cls.WA = np.array( [[0, 0.5, 0.5, 0.5, 0], [0.5, 0, 0.5, 0, 0], [0.5, 0.5, 0, 0, 0], [0.5, 0, 0, 0, 0], [0, 0, 0, 0, 0]] ) # fmt: on cls.MG = nx.MultiGraph(cls.G) cls.MG2 = cls.MG.copy() cls.MG2.add_edge(0, 1) # fmt: off cls.MG2A = np.array( [[0, 2, 1, 1, 0], [2, 0, 1, 0, 0], [1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0]] ) cls.MGOI = np.array( [[-1, -1, -1, -1, 0], [1, 1, 0, 0, -1], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]] ) # fmt: on cls.no_edges_G = nx.Graph([(1, 2), (3, 2, {"weight": 8})]) cls.no_edges_A = np.array([[0, 0], [0, 0]])
def test_incidence_matrix(self): "Conversion to incidence matrix" I = nx.incidence_matrix( self.G, nodelist=sorted(self.G), edgelist=sorted(self.G.edges()), oriented=True, dtype=int, ).todense() np.testing.assert_equal(I, self.OI)
I = nx.incidence_matrix( self.G, nodelist=sorted(self.G), edgelist=sorted(self.G.edges()), oriented=False, dtype=int, ).todense() np.testing.assert_equal(I, np.abs(self.OI))
I = nx.incidence_matrix( self.MG, nodelist=sorted(self.MG), edgelist=sorted(self.MG.edges()), oriented=True, dtype=int, ).todense() np.testing.assert_equal(I, self.OI)
I = nx.incidence_matrix( self.MG, nodelist=sorted(self.MG), edgelist=sorted(self.MG.edges()), oriented=False, dtype=int, ).todense() np.testing.assert_equal(I, np.abs(self.OI))
I = nx.incidence_matrix( self.MG2, nodelist=sorted(self.MG2), edgelist=sorted(self.MG2.edges()), oriented=True, dtype=int, ).todense() np.testing.assert_equal(I, self.MGOI)
I = nx.incidence_matrix( self.MG2, nodelist=sorted(self.MG), edgelist=sorted(self.MG2.edges()), oriented=False, dtype=int, ).todense() np.testing.assert_equal(I, np.abs(self.MGOI))
I = nx.incidence_matrix(self.G, dtype=np.uint8) assert I.dtype == np.uint8
def test_weighted_incidence_matrix(self): I = nx.incidence_matrix( self.WG, nodelist=sorted(self.WG), edgelist=sorted(self.WG.edges()), oriented=True, dtype=int, ).todense() np.testing.assert_equal(I, self.OI)
I = nx.incidence_matrix( self.WG, nodelist=sorted(self.WG), edgelist=sorted(self.WG.edges()), oriented=False, dtype=int, ).todense() np.testing.assert_equal(I, np.abs(self.OI))
# np.testing.assert_equal(nx.incidence_matrix(self.WG,oriented=True, # weight='weight').todense(),0.5*self.OI) # np.testing.assert_equal(nx.incidence_matrix(self.WG,weight='weight').todense(), # np.abs(0.5*self.OI)) # np.testing.assert_equal(nx.incidence_matrix(self.WG,oriented=True,weight='other').todense(), # 0.3*self.OI)
I = nx.incidence_matrix( self.WG, nodelist=sorted(self.WG), edgelist=sorted(self.WG.edges()), oriented=True, weight="weight", ).todense() np.testing.assert_equal(I, 0.5 * self.OI)
I = nx.incidence_matrix( self.WG, nodelist=sorted(self.WG), edgelist=sorted(self.WG.edges()), oriented=False, weight="weight", ).todense() np.testing.assert_equal(I, np.abs(0.5 * self.OI))
I = nx.incidence_matrix( self.WG, nodelist=sorted(self.WG), edgelist=sorted(self.WG.edges()), oriented=True, weight="other", ).todense() np.testing.assert_equal(I, 0.3 * self.OI)
# WMG=nx.MultiGraph(self.WG) # WMG.add_edge(0,1,weight=0.5,other=0.3) # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='weight').todense(), # np.abs(0.5*self.MGOI)) # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='weight',oriented=True).todense(), # 0.5*self.MGOI) # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='other',oriented=True).todense(), # 0.3*self.MGOI)
WMG = nx.MultiGraph(self.WG) WMG.add_edge(0, 1, weight=0.5, other=0.3)
I = nx.incidence_matrix( WMG, nodelist=sorted(WMG), edgelist=sorted(WMG.edges(keys=True)), oriented=True, weight="weight", ).todense() np.testing.assert_equal(I, 0.5 * self.MGOI)
I = nx.incidence_matrix( WMG, nodelist=sorted(WMG), edgelist=sorted(WMG.edges(keys=True)), oriented=False, weight="weight", ).todense() np.testing.assert_equal(I, np.abs(0.5 * self.MGOI))
I = nx.incidence_matrix( WMG, nodelist=sorted(WMG), edgelist=sorted(WMG.edges(keys=True)), oriented=True, weight="other", ).todense() np.testing.assert_equal(I, 0.3 * self.MGOI)
def test_adjacency_matrix(self): "Conversion to adjacency matrix" np.testing.assert_equal(nx.adjacency_matrix(self.G).todense(), self.A) np.testing.assert_equal(nx.adjacency_matrix(self.MG).todense(), self.A) np.testing.assert_equal(nx.adjacency_matrix(self.MG2).todense(), self.MG2A) np.testing.assert_equal( nx.adjacency_matrix(self.G, nodelist=[0, 1]).todense(), self.A[:2, :2] ) np.testing.assert_equal(nx.adjacency_matrix(self.WG).todense(), self.WA) np.testing.assert_equal( nx.adjacency_matrix(self.WG, weight=None).todense(), self.A ) np.testing.assert_equal( nx.adjacency_matrix(self.MG2, weight=None).todense(), self.MG2A ) np.testing.assert_equal( nx.adjacency_matrix(self.WG, weight="other").todense(), 0.6 * self.WA ) np.testing.assert_equal( nx.adjacency_matrix(self.no_edges_G, nodelist=[1, 3]).todense(), self.no_edges_A, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334import pytest
import networkx as nx
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
class TestLaplacian: @classmethod def setup_class(cls): deg = [3, 2, 2, 1, 0] cls.G = nx.havel_hakimi_graph(deg) cls.WG = nx.Graph( (u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.G.edges() ) cls.WG.add_node(4) cls.MG = nx.MultiGraph(cls.G)
# Graph with clsloops cls.Gsl = cls.G.copy() for node in cls.Gsl.nodes(): cls.Gsl.add_edge(node, node)
# Graph used as an example in Sec. 4.1 of Langville and Meyer, # "Google's PageRank and Beyond". cls.DiG = nx.DiGraph() cls.DiG.add_edges_from( ( (1, 2), (1, 3), (3, 1), (3, 2), (3, 5), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), ) ) cls.DiMG = nx.MultiDiGraph(cls.DiG) cls.DiWG = nx.DiGraph( (u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.DiG.edges() ) cls.DiGsl = cls.DiG.copy() for node in cls.DiGsl.nodes(): cls.DiGsl.add_edge(node, node)
def test_laplacian(self): "Graph Laplacian" # fmt: off NL = np.array([[ 3, -1, -1, -1, 0], [-1, 2, -1, 0, 0], [-1, -1, 2, 0, 0], [-1, 0, 0, 1, 0], [ 0, 0, 0, 0, 0]]) # fmt: on WL = 0.5 * NL OL = 0.3 * NL # fmt: off DiNL = np.array([[ 2, -1, -1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0], [-1, -1, 3, -1, 0, 0], [ 0, 0, 0, 2, -1, -1], [ 0, 0, 0, -1, 2, -1], [ 0, 0, 0, 0, -1, 1]]) # fmt: on DiWL = 0.5 * DiNL DiOL = 0.3 * DiNL np.testing.assert_equal(nx.laplacian_matrix(self.G).todense(), NL) np.testing.assert_equal(nx.laplacian_matrix(self.MG).todense(), NL) np.testing.assert_equal( nx.laplacian_matrix(self.G, nodelist=[0, 1]).todense(), np.array([[1, -1], [-1, 1]]), ) np.testing.assert_equal(nx.laplacian_matrix(self.WG).todense(), WL) np.testing.assert_equal(nx.laplacian_matrix(self.WG, weight=None).todense(), NL) np.testing.assert_equal( nx.laplacian_matrix(self.WG, weight="other").todense(), OL )
np.testing.assert_equal(nx.laplacian_matrix(self.DiG).todense(), DiNL) np.testing.assert_equal(nx.laplacian_matrix(self.DiMG).todense(), DiNL) np.testing.assert_equal( nx.laplacian_matrix(self.DiG, nodelist=[1, 2]).todense(), np.array([[1, -1], [0, 0]]), ) np.testing.assert_equal(nx.laplacian_matrix(self.DiWG).todense(), DiWL) np.testing.assert_equal( nx.laplacian_matrix(self.DiWG, weight=None).todense(), DiNL ) np.testing.assert_equal( nx.laplacian_matrix(self.DiWG, weight="other").todense(), DiOL )
def test_normalized_laplacian(self): "Generalized Graph Laplacian" # fmt: off G = np.array([[ 1. , -0.408, -0.408, -0.577, 0.], [-0.408, 1. , -0.5 , 0. , 0.], [-0.408, -0.5 , 1. , 0. , 0.], [-0.577, 0. , 0. , 1. , 0.], [ 0. , 0. , 0. , 0. , 0.]]) GL = np.array([[ 1. , -0.408, -0.408, -0.577, 0. ], [-0.408, 1. , -0.5 , 0. , 0. ], [-0.408, -0.5 , 1. , 0. , 0. ], [-0.577, 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 0. , 0. ]]) Lsl = np.array([[ 0.75 , -0.2887, -0.2887, -0.3536, 0. ], [-0.2887, 0.6667, -0.3333, 0. , 0. ], [-0.2887, -0.3333, 0.6667, 0. , 0. ], [-0.3536, 0. , 0. , 0.5 , 0. ], [ 0. , 0. , 0. , 0. , 0. ]])
DiG = np.array([[ 1. , 0. , -0.4082, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [-0.4082, 0. , 1. , 0. , -0.4082, 0. ], [ 0. , 0. , 0. , 1. , -0.5 , -0.7071], [ 0. , 0. , 0. , -0.5 , 1. , -0.7071], [ 0. , 0. , 0. , -0.7071, 0. , 1. ]]) DiGL = np.array([[ 1. , 0. , -0.4082, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [-0.4082, 0. , 1. , -0.4082, 0. , 0. ], [ 0. , 0. , 0. , 1. , -0.5 , -0.7071], [ 0. , 0. , 0. , -0.5 , 1. , -0.7071], [ 0. , 0. , 0. , 0. , -0.7071, 1. ]]) DiLsl = np.array([[ 0.6667, -0.5774, -0.2887, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [-0.2887, -0.5 , 0.75 , -0.2887, 0. , 0. ], [ 0. , 0. , 0. , 0.6667, -0.3333, -0.4082], [ 0. , 0. , 0. , -0.3333, 0.6667, -0.4082], [ 0. , 0. , 0. , 0. , -0.4082, 0.5 ]]) # fmt: on
np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.G, nodelist=range(5)).todense(), G, decimal=3, ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.G).todense(), GL, decimal=3 ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.MG).todense(), GL, decimal=3 ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.WG).todense(), GL, decimal=3 ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.WG, weight="other").todense(), GL, decimal=3, ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.Gsl).todense(), Lsl, decimal=3 )
np.testing.assert_almost_equal( nx.normalized_laplacian_matrix( self.DiG, nodelist=range(1, 1 + 6), ).todense(), DiG, decimal=3, ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.DiG).todense(), DiGL, decimal=3 ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.DiMG).todense(), DiGL, decimal=3 ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.DiWG).todense(), DiGL, decimal=3 ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.DiWG, weight="other").todense(), DiGL, decimal=3, ) np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.DiGsl).todense(), DiLsl, decimal=3 )
def test_directed_laplacian(): "Directed Laplacian" # Graph used as an example in Sec. 4.1 of Langville and Meyer, # "Google's PageRank and Beyond". The graph contains dangling nodes, so # the pagerank random walk is selected by directed_laplacian G = nx.DiGraph() G.add_edges_from( ( (1, 2), (1, 3), (3, 1), (3, 2), (3, 5), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), ) ) # fmt: off GL = np.array([[ 0.9833, -0.2941, -0.3882, -0.0291, -0.0231, -0.0261], [-0.2941, 0.8333, -0.2339, -0.0536, -0.0589, -0.0554], [-0.3882, -0.2339, 0.9833, -0.0278, -0.0896, -0.0251], [-0.0291, -0.0536, -0.0278, 0.9833, -0.4878, -0.6675], [-0.0231, -0.0589, -0.0896, -0.4878, 0.9833, -0.2078], [-0.0261, -0.0554, -0.0251, -0.6675, -0.2078, 0.9833]]) # fmt: on L = nx.directed_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G)) np.testing.assert_almost_equal(L, GL, decimal=3)
# Make the graph strongly connected, so we can use a random and lazy walk G.add_edges_from(((2, 5), (6, 1))) # fmt: off GL = np.array([[ 1. , -0.3062, -0.4714, 0. , 0. , -0.3227], [-0.3062, 1. , -0.1443, 0. , -0.3162, 0. ], [-0.4714, -0.1443, 1. , 0. , -0.0913, 0. ], [ 0. , 0. , 0. , 1. , -0.5 , -0.5 ], [ 0. , -0.3162, -0.0913, -0.5 , 1. , -0.25 ], [-0.3227, 0. , 0. , -0.5 , -0.25 , 1. ]]) # fmt: on L = nx.directed_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="random" ) np.testing.assert_almost_equal(L, GL, decimal=3)
# fmt: off GL = np.array([[ 0.5 , -0.1531, -0.2357, 0. , 0. , -0.1614], [-0.1531, 0.5 , -0.0722, 0. , -0.1581, 0. ], [-0.2357, -0.0722, 0.5 , 0. , -0.0456, 0. ], [ 0. , 0. , 0. , 0.5 , -0.25 , -0.25 ], [ 0. , -0.1581, -0.0456, -0.25 , 0.5 , -0.125 ], [-0.1614, 0. , 0. , -0.25 , -0.125 , 0.5 ]]) # fmt: on L = nx.directed_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G), walk_type="lazy") np.testing.assert_almost_equal(L, GL, decimal=3)
# Make a strongly connected periodic graph G = nx.DiGraph() G.add_edges_from(((1, 2), (2, 4), (4, 1), (1, 3), (3, 4))) # fmt: off GL = np.array([[ 0.5 , -0.176, -0.176, -0.25 ], [-0.176, 0.5 , 0. , -0.176], [-0.176, 0. , 0.5 , -0.176], [-0.25 , -0.176, -0.176, 0.5 ]]) # fmt: on L = nx.directed_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G)) np.testing.assert_almost_equal(L, GL, decimal=3)
def test_directed_combinatorial_laplacian(): "Directed combinatorial Laplacian" # Graph used as an example in Sec. 4.1 of Langville and Meyer, # "Google's PageRank and Beyond". The graph contains dangling nodes, so # the pagerank random walk is selected by directed_laplacian G = nx.DiGraph() G.add_edges_from( ( (1, 2), (1, 3), (3, 1), (3, 2), (3, 5), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), ) ) # fmt: off GL = np.array([[ 0.0366, -0.0132, -0.0153, -0.0034, -0.0020, -0.0027], [-0.0132, 0.0450, -0.0111, -0.0076, -0.0062, -0.0069], [-0.0153, -0.0111, 0.0408, -0.0035, -0.0083, -0.0027], [-0.0034, -0.0076, -0.0035, 0.3688, -0.1356, -0.2187], [-0.0020, -0.0062, -0.0083, -0.1356, 0.2026, -0.0505], [-0.0027, -0.0069, -0.0027, -0.2187, -0.0505, 0.2815]]) # fmt: on
L = nx.directed_combinatorial_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G)) np.testing.assert_almost_equal(L, GL, decimal=3)
# Make the graph strongly connected, so we can use a random and lazy walk G.add_edges_from(((2, 5), (6, 1)))
# fmt: off GL = np.array([[ 0.1395, -0.0349, -0.0465, 0. , 0. , -0.0581], [-0.0349, 0.093 , -0.0116, 0. , -0.0465, 0. ], [-0.0465, -0.0116, 0.0698, 0. , -0.0116, 0. ], [ 0. , 0. , 0. , 0.2326, -0.1163, -0.1163], [ 0. , -0.0465, -0.0116, -0.1163, 0.2326, -0.0581], [-0.0581, 0. , 0. , -0.1163, -0.0581, 0.2326]]) # fmt: on
L = nx.directed_combinatorial_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="random" ) np.testing.assert_almost_equal(L, GL, decimal=3)
# fmt: off GL = np.array([[ 0.0698, -0.0174, -0.0233, 0. , 0. , -0.0291], [-0.0174, 0.0465, -0.0058, 0. , -0.0233, 0. ], [-0.0233, -0.0058, 0.0349, 0. , -0.0058, 0. ], [ 0. , 0. , 0. , 0.1163, -0.0581, -0.0581], [ 0. , -0.0233, -0.0058, -0.0581, 0.1163, -0.0291], [-0.0291, 0. , 0. , -0.0581, -0.0291, 0.1163]]) # fmt: on
L = nx.directed_combinatorial_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="lazy" ) np.testing.assert_almost_equal(L, GL, decimal=3)
E = nx.DiGraph(nx.margulis_gabber_galil_graph(2)) L = nx.directed_combinatorial_laplacian_matrix(E) # fmt: off expected = np.array( [[ 0.16666667, -0.08333333, -0.08333333, 0. ], [-0.08333333, 0.16666667, 0. , -0.08333333], [-0.08333333, 0. , 0.16666667, -0.08333333], [ 0. , -0.08333333, -0.08333333, 0.16666667]] ) # fmt: on np.testing.assert_almost_equal(L, expected, decimal=6)
with pytest.raises(nx.NetworkXError): nx.directed_combinatorial_laplacian_matrix(G, walk_type="pagerank", alpha=100) with pytest.raises(nx.NetworkXError): nx.directed_combinatorial_laplacian_matrix(G, walk_type="silly")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import pytest
import networkx as nx
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
class TestModularity: @classmethod def setup_class(cls): deg = [3, 2, 2, 1, 0] cls.G = nx.havel_hakimi_graph(deg) # Graph used as an example in Sec. 4.1 of Langville and Meyer, # "Google's PageRank and Beyond". (Used for test_directed_laplacian) cls.DG = nx.DiGraph() cls.DG.add_edges_from( ( (1, 2), (1, 3), (3, 1), (3, 2), (3, 5), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), ) )
def test_modularity(self): "Modularity matrix" # fmt: off B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.], [0.25, -0.5, 0.5, -0.25, 0.], [0.25, 0.5, -0.5, -0.25, 0.], [0.625, -0.25, -0.25, -0.125, 0.], [0., 0., 0., 0., 0.]]) # fmt: on
permutation = [4, 0, 1, 2, 3] np.testing.assert_equal(nx.modularity_matrix(self.G), B) np.testing.assert_equal( nx.modularity_matrix(self.G, nodelist=permutation), B[np.ix_(permutation, permutation)], )
def test_modularity_weight(self): "Modularity matrix with weights" # fmt: off B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.], [0.25, -0.5, 0.5, -0.25, 0.], [0.25, 0.5, -0.5, -0.25, 0.], [0.625, -0.25, -0.25, -0.125, 0.], [0., 0., 0., 0., 0.]]) # fmt: on
G_weighted = self.G.copy() for n1, n2 in G_weighted.edges(): G_weighted.edges[n1, n2]["weight"] = 0.5 # The following test would fail in networkx 1.1 np.testing.assert_equal(nx.modularity_matrix(G_weighted), B) # The following test that the modularity matrix get rescaled accordingly np.testing.assert_equal( nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B )
def test_directed_modularity(self): "Directed Modularity matrix" # fmt: off B = np.array([[-0.2, 0.6, 0.8, -0.4, -0.4, -0.4], [0., 0., 0., 0., 0., 0.], [0.7, 0.4, -0.3, -0.6, 0.4, -0.6], [-0.2, -0.4, -0.2, -0.4, 0.6, 0.6], [-0.2, -0.4, -0.2, 0.6, -0.4, 0.6], [-0.1, -0.2, -0.1, 0.8, -0.2, -0.2]]) # fmt: on node_permutation = [5, 1, 2, 3, 4, 6] idx_permutation = [4, 0, 1, 2, 3, 5] mm = nx.directed_modularity_matrix(self.DG, nodelist=sorted(self.DG)) np.testing.assert_equal(mm, B) np.testing.assert_equal( nx.directed_modularity_matrix(self.DG, nodelist=node_permutation), B[np.ix_(idx_permutation, idx_permutation)], )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import pytest
import networkx as nx
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
class TestSpectrum: @classmethod def setup_class(cls): deg = [3, 2, 2, 1, 0] cls.G = nx.havel_hakimi_graph(deg) cls.P = nx.path_graph(3) cls.WG = nx.Graph( (u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.G.edges() ) cls.WG.add_node(4) cls.DG = nx.DiGraph() nx.add_path(cls.DG, [0, 1, 2])
def test_laplacian_spectrum(self): "Laplacian eigenvalues" evals = np.array([0, 0, 1, 3, 4]) e = sorted(nx.laplacian_spectrum(self.G)) np.testing.assert_almost_equal(e, evals) e = sorted(nx.laplacian_spectrum(self.WG, weight=None)) np.testing.assert_almost_equal(e, evals) e = sorted(nx.laplacian_spectrum(self.WG)) np.testing.assert_almost_equal(e, 0.5 * evals) e = sorted(nx.laplacian_spectrum(self.WG, weight="other")) np.testing.assert_almost_equal(e, 0.3 * evals)
def test_normalized_laplacian_spectrum(self): "Normalized Laplacian eigenvalues" evals = np.array([0, 0, 0.7712864461218, 1.5, 1.7287135538781]) e = sorted(nx.normalized_laplacian_spectrum(self.G)) np.testing.assert_almost_equal(e, evals) e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight=None)) np.testing.assert_almost_equal(e, evals) e = sorted(nx.normalized_laplacian_spectrum(self.WG)) np.testing.assert_almost_equal(e, evals) e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight="other")) np.testing.assert_almost_equal(e, evals)
def test_adjacency_spectrum(self): "Adjacency eigenvalues" evals = np.array([-np.sqrt(2), 0, np.sqrt(2)]) e = sorted(nx.adjacency_spectrum(self.P)) np.testing.assert_almost_equal(e, evals)
def test_modularity_spectrum(self): "Modularity eigenvalues" evals = np.array([-1.5, 0.0, 0.0]) e = sorted(nx.modularity_spectrum(self.P)) np.testing.assert_almost_equal(e, evals) # Directed modularity eigenvalues evals = np.array([-0.5, 0.0, 0.0]) e = sorted(nx.modularity_spectrum(self.DG)) np.testing.assert_almost_equal(e, evals)
def test_bethe_hessian_spectrum(self): "Bethe Hessian eigenvalues" evals = np.array([0.5 * (9 - np.sqrt(33)), 4, 0.5 * (9 + np.sqrt(33))]) e = sorted(nx.bethe_hessian_spectrum(self.P, r=2)) np.testing.assert_almost_equal(e, evals) # Collapses back to Laplacian: e1 = sorted(nx.bethe_hessian_spectrum(self.P, r=1)) e2 = sorted(nx.laplacian_spectrum(self.P)) np.testing.assert_almost_equal(e1, e2)1234567891011121314151617"""A package for reading and writing graphs in various formats.
"""
from networkx.readwrite.adjlist import *from networkx.readwrite.multiline_adjlist import *from networkx.readwrite.edgelist import *from networkx.readwrite.pajek import *from networkx.readwrite.leda import *from networkx.readwrite.sparse6 import *from networkx.readwrite.graph6 import *from networkx.readwrite.gml import *from networkx.readwrite.graphml import *from networkx.readwrite.gexf import *from networkx.readwrite.json_graph import *from networkx.readwrite.text import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""**************Adjacency List**************Read and write NetworkX graphs as adjacency lists.
Adjacency list format is useful for graphs without data associatedwith nodes or edges and for nodes that can be meaningfully representedas strings.
Format------The adjacency list format consists of lines with node labels. Thefirst label in a line is the source node. Further labels in the lineare considered target nodes and are added to the graph along with an edgebetween the source node and target node.
The graph with edges a-b, a-c, d-e can be represented as the followingadjacency list (anything following the # in a line is a comment)::
a b c # source target target d e"""
__all__ = ["generate_adjlist", "write_adjlist", "parse_adjlist", "read_adjlist"]
import networkx as nxfrom networkx.utils import open_file
def generate_adjlist(G, delimiter=" "): """Generate lines representing a graph in adjacency list format.
Parameters ---------- G : NetworkX graph
delimiter : str, default=" " Separator for node labels.
Yields ------ str Adjacency list for a node in `G`. The first item is the node label, followed by the labels of its neighbors.
Examples -------- >>> G = nx.lollipop_graph(4, 3) >>> for line in nx.generate_adjlist(G): ... print(line) 0 1 2 3 1 2 3 2 3 3 4 4 5 5 6 6
When `G` is undirected, each edge is only listed once. For directed graphs, edges appear once for each direction.
>>> G = nx.complete_graph(3, create_using=nx.DiGraph) >>> for line in nx.generate_adjlist(G): ... print(line) 0 1 2 1 0 2 2 0 1
Node labels are shown multiple times for multiedges, but edge data (including keys) are not included in the output.
>>> G = nx.MultiGraph([(0, 1, {"weight": 1}), (0, 1, {"weight": 2})]) >>> for line in nx.generate_adjlist(G): ... print(line) 0 1 1 1
See Also -------- write_adjlist, read_adjlist
Notes ----- The default `delimiter=" "` will result in unexpected results if node names contain whitespace characters. To avoid this problem, specify an alternate delimiter when spaces are valid in node names.
NB: This option is not available for data that isn't user-generated.
""" seen = set() directed = G.is_directed() multigraph = G.is_multigraph() for s, nbrs in G.adjacency(): nodes = [str(s)] for t, data in nbrs.items(): if t in seen: continue if multigraph and len(data) > 1: nodes.extend((str(t),) * len(data)) else: nodes.append(str(t)) if not directed: seen.add(s) yield delimiter.join(nodes)
@open_file(1, mode="wb")def write_adjlist(G, path, comments="#", delimiter=" ", encoding="utf-8"): """Write graph G in single-line adjacency-list format to path.
Parameters ---------- G : NetworkX graph
path : string or file Filename or file handle for data output. Filenames ending in .gz or .bz2 will be compressed.
comments : string, optional Marker for comment lines
delimiter : string, optional Separator for node labels
encoding : string, optional Text encoding.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_adjlist(G, "path4.adjlist")
The path can be a filehandle or a string with the name of the file. If a filehandle is provided, it has to be opened in 'wb' mode.
>>> fh = open("path4.adjlist2", "wb") >>> nx.write_adjlist(G, fh)
Notes ----- The default `delimiter=" "` will result in unexpected results if node names contain whitespace characters. To avoid this problem, specify an alternate delimiter when spaces are valid in node names. NB: This option is not available for data that isn't user-generated.
This format does not store graph, node, or edge data.
See Also -------- read_adjlist, generate_adjlist """ import sys import time
pargs = comments + " ".join(sys.argv) + "\n" header = ( pargs + comments + f" GMT {time.asctime(time.gmtime())}\n" + comments + f" {G.name}\n" ) path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter): line += "\n" path.write(line.encode(encoding))
@nx._dispatchable(graphs=None, returns_graph=True)def parse_adjlist( lines, comments="#", delimiter=None, create_using=None, nodetype=None): """Parse lines of a graph adjacency list representation.
Parameters ---------- lines : list or iterator of strings Input data in adjlist format
create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated.
nodetype : Python type, optional Convert nodes to this type.
comments : string, optional Marker for comment lines
delimiter : string, optional Separator for node labels. The default is whitespace.
Returns ------- G: NetworkX graph The graph corresponding to the lines in adjacency list format.
Examples -------- >>> lines = ["1 2 5", "2 3 4", "3 5", "4", "5"] >>> G = nx.parse_adjlist(lines, nodetype=int) >>> nodes = [1, 2, 3, 4, 5] >>> all(node in G for node in nodes) True >>> edges = [(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)] >>> all((u, v) in G.edges() or (v, u) in G.edges() for (u, v) in edges) True
See Also -------- read_adjlist
""" G = nx.empty_graph(0, create_using) for line in lines: p = line.find(comments) if p >= 0: line = line[:p] if not len(line): continue vlist = line.rstrip("\n").split(delimiter) u = vlist.pop(0) # convert types if nodetype is not None: try: u = nodetype(u) except BaseException as err: raise TypeError( f"Failed to convert node ({u}) to type {nodetype}" ) from err G.add_node(u) if nodetype is not None: try: vlist = list(map(nodetype, vlist)) except BaseException as err: raise TypeError( f"Failed to convert nodes ({','.join(vlist)}) to type {nodetype}" ) from err G.add_edges_from([(u, v) for v in vlist]) return G
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_adjlist( path, comments="#", delimiter=None, create_using=None, nodetype=None, encoding="utf-8",): """Read graph in adjacency list format from path.
Parameters ---------- path : string or file Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated.
nodetype : Python type, optional Convert nodes to this type.
comments : string, optional Marker for comment lines
delimiter : string, optional Separator for node labels. The default is whitespace.
Returns ------- G: NetworkX graph The graph corresponding to the lines in adjacency list format.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_adjlist(G, "test.adjlist") >>> G = nx.read_adjlist("test.adjlist")
The path can be a filehandle or a string with the name of the file. If a filehandle is provided, it has to be opened in 'rb' mode.
>>> fh = open("test.adjlist", "rb") >>> G = nx.read_adjlist(fh)
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_adjlist(G, "test.adjlist.gz") >>> G = nx.read_adjlist("test.adjlist.gz")
The optional nodetype is a function to convert node strings to nodetype.
For example
>>> G = nx.read_adjlist("test.adjlist", nodetype=int)
will attempt to convert all nodes to integer type.
Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.)
The optional create_using parameter indicates the type of NetworkX graph created. The default is `nx.Graph`, an undirected graph. To read the data as a directed graph use
>>> G = nx.read_adjlist("test.adjlist", create_using=nx.DiGraph)
Notes ----- This format does not store graph or node data.
See Also -------- write_adjlist """ lines = (line.decode(encoding) for line in path) return parse_adjlist( lines, comments=comments, delimiter=delimiter, create_using=create_using, nodetype=nodetype, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489"""**********Edge Lists**********Read and write NetworkX graphs as edge lists.
The multi-line adjacency list format is useful for graphs with nodesthat can be meaningfully represented as strings. With the edgelistformat simple edge data can be stored but node or graph data is not.There is no way of representing isolated nodes unless the node has aself-loop edge.
Format------You can read or write three formats of edge lists with these functions.
Node pairs with no data::
1 2
Python dictionary as data::
1 2 {'weight':7, 'color':'green'}
Arbitrary data::
1 2 7 green"""
__all__ = [ "generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist", "read_weighted_edgelist", "write_weighted_edgelist",]
import networkx as nxfrom networkx.utils import open_file
def generate_edgelist(G, delimiter=" ", data=True): """Generate a single line of the graph G in edge list format.
Parameters ---------- G : NetworkX graph
delimiter : string, optional Separator for node labels
data : bool or list of keys If False generate no edge data. If True use a dictionary representation of edge data. If a list of keys use a list of data values corresponding to the keys.
Returns ------- lines : string Lines of data in adjlist format.
Examples -------- >>> G = nx.lollipop_graph(4, 3) >>> G[1][2]["weight"] = 3 >>> G[3][4]["capacity"] = 12 >>> for line in nx.generate_edgelist(G, data=False): ... print(line) 0 1 0 2 0 3 1 2 1 3 2 3 3 4 4 5 5 6
>>> for line in nx.generate_edgelist(G): ... print(line) 0 1 {} 0 2 {} 0 3 {} 1 2 {'weight': 3} 1 3 {} 2 3 {} 3 4 {'capacity': 12} 4 5 {} 5 6 {}
>>> for line in nx.generate_edgelist(G, data=["weight"]): ... print(line) 0 1 0 2 0 3 1 2 3 1 3 2 3 3 4 4 5 5 6
See Also -------- write_adjlist, read_adjlist """ if data is True: for u, v, d in G.edges(data=True): e = u, v, dict(d) yield delimiter.join(map(str, e)) elif data is False: for u, v in G.edges(data=False): e = u, v yield delimiter.join(map(str, e)) else: for u, v, d in G.edges(data=True): e = [u, v] try: e.extend(d[k] for k in data) except KeyError: pass # missing data for this edge, should warn? yield delimiter.join(map(str, e))
@open_file(1, mode="wb")def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"): """Write graph as a list of edges.
Parameters ---------- G : graph A NetworkX graph path : file or string File or filename to write. If a file is provided, it must be opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed. comments : string, optional The character used to indicate the start of a comment delimiter : string, optional The string used to separate values. The default is whitespace. data : bool or list, optional If False write no edge data. If True write a string representation of the edge data dictionary.. If a list (or other iterable) is provided, write the keys specified in the list. encoding: string, optional Specify which encoding to use when writing file.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_edgelist(G, "test.edgelist") >>> G = nx.path_graph(4) >>> fh = open("test.edgelist", "wb") >>> nx.write_edgelist(G, fh) >>> nx.write_edgelist(G, "test.edgelist.gz") >>> nx.write_edgelist(G, "test.edgelist_nodata.gz", data=False)
>>> G = nx.Graph() >>> G.add_edge(1, 2, weight=7, color="red") >>> nx.write_edgelist(G, "test.edgelist_bigger_nodata", data=False) >>> nx.write_edgelist(G, "test.edgelist_color", data=["color"]) >>> nx.write_edgelist(G, "test.edgelist_color_weight", data=["color", "weight"])
See Also -------- read_edgelist write_weighted_edgelist """
for line in generate_edgelist(G, delimiter, data): line += "\n" path.write(line.encode(encoding))
@nx._dispatchable(graphs=None, returns_graph=True)def parse_edgelist( lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True): """Parse lines of an edge list representation of a graph.
Parameters ---------- lines : list or iterator of strings Input data in edgelist format comments : string, optional Marker for comment lines. Default is `'#'`. To specify that no character should be treated as a comment, use ``comments=None``. delimiter : string, optional Separator for node labels. Default is `None`, meaning any whitespace. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : Python type, optional Convert nodes to this type. Default is `None`, meaning no conversion is performed. data : bool or list of (label,type) tuples If `False` generate no edge data or if `True` use a dictionary representation of edge data or a list tuples specifying dictionary key names and types for edge data.
Returns ------- G: NetworkX Graph The graph corresponding to lines
Examples -------- Edgelist with no data:
>>> lines = ["1 2", "2 3", "3 4"] >>> G = nx.parse_edgelist(lines, nodetype=int) >>> list(G) [1, 2, 3, 4] >>> list(G.edges()) [(1, 2), (2, 3), (3, 4)]
Edgelist with data in Python dictionary representation:
>>> lines = ["1 2 {'weight': 3}", "2 3 {'weight': 27}", "3 4 {'weight': 3.0}"] >>> G = nx.parse_edgelist(lines, nodetype=int) >>> list(G) [1, 2, 3, 4] >>> list(G.edges(data=True)) [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
Edgelist with data in a list:
>>> lines = ["1 2 3", "2 3 27", "3 4 3.0"] >>> G = nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),)) >>> list(G) [1, 2, 3, 4] >>> list(G.edges(data=True)) [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
See Also -------- read_weighted_edgelist """ from ast import literal_eval
G = nx.empty_graph(0, create_using) for line in lines: if comments is not None: p = line.find(comments) if p >= 0: line = line[:p] if not line: continue # split line, should have 2 or more s = line.rstrip("\n").split(delimiter) if len(s) < 2: continue u = s.pop(0) v = s.pop(0) d = s if nodetype is not None: try: u = nodetype(u) v = nodetype(v) except Exception as err: raise TypeError( f"Failed to convert nodes {u},{v} to type {nodetype}." ) from err
if len(d) == 0 or data is False: # no data or data type specified edgedata = {} elif data is True: # no edge types specified try: # try to evaluate as dictionary if delimiter == ",": edgedata_str = ",".join(d) else: edgedata_str = " ".join(d) edgedata = dict(literal_eval(edgedata_str.strip())) except Exception as err: raise TypeError( f"Failed to convert edge data ({d}) to dictionary." ) from err else: # convert edge data to dictionary with specified keys and type if len(d) != len(data): raise IndexError( f"Edge data {d} and data_keys {data} are not the same length" ) edgedata = {} for (edge_key, edge_type), edge_value in zip(data, d): try: edge_value = edge_type(edge_value) except Exception as err: raise TypeError( f"Failed to convert {edge_key} data {edge_value} " f"to type {edge_type}." ) from err edgedata.update({edge_key: edge_value}) G.add_edge(u, v, **edgedata) return G
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_edgelist( path, comments="#", delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding="utf-8",): """Read a graph from a list of edges.
Parameters ---------- path : file or string File or filename to read. If a file is provided, it must be opened in 'rb' mode. Filenames ending in .gz or .bz2 will be decompressed. comments : string, optional The character used to indicate the start of a comment. To specify that no character should be treated as a comment, use ``comments=None``. delimiter : string, optional The string used to separate values. The default is whitespace. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : int, float, str, Python type, optional Convert node data from strings to specified type data : bool or list of (label,type) tuples Tuples specifying dictionary key names and types for edge data edgetype : int, float, str, Python type, optional OBSOLETE Convert edge data from strings to specified type and use as 'weight' encoding: string, optional Specify which encoding to use when reading file.
Returns ------- G : graph A networkx Graph or other type specified with create_using
Examples -------- >>> nx.write_edgelist(nx.path_graph(4), "test.edgelist_P4") >>> G = nx.read_edgelist("test.edgelist_P4")
>>> fh = open("test.edgelist_P4", "rb") >>> G = nx.read_edgelist(fh) >>> fh.close()
>>> G = nx.read_edgelist("test.edgelist_P4", nodetype=int) >>> G = nx.read_edgelist("test.edgelist_P4", create_using=nx.DiGraph)
Edgelist with data in a list:
>>> textline = "1 2 3" >>> fh = open("test.textline", "w") >>> d = fh.write(textline) >>> fh.close() >>> G = nx.read_edgelist("test.textline", nodetype=int, data=(("weight", float),)) >>> list(G) [1, 2] >>> list(G.edges(data=True)) [(1, 2, {'weight': 3.0})]
See parse_edgelist() for more examples of formatting.
See Also -------- parse_edgelist write_edgelist
Notes ----- Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.) """ lines = (line if isinstance(line, str) else line.decode(encoding) for line in path) return parse_edgelist( lines, comments=comments, delimiter=delimiter, create_using=create_using, nodetype=nodetype, data=data, )
def write_weighted_edgelist(G, path, comments="#", delimiter=" ", encoding="utf-8"): """Write graph G as a list of edges with numeric weights.
Parameters ---------- G : graph A NetworkX graph path : file or string File or filename to write. If a file is provided, it must be opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed. comments : string, optional The character used to indicate the start of a comment delimiter : string, optional The string used to separate values. The default is whitespace. encoding: string, optional Specify which encoding to use when writing file.
Examples -------- >>> G = nx.Graph() >>> G.add_edge(1, 2, weight=7) >>> nx.write_weighted_edgelist(G, "test.weighted.edgelist")
See Also -------- read_edgelist write_edgelist read_weighted_edgelist """ write_edgelist( G, path, comments=comments, delimiter=delimiter, data=("weight",), encoding=encoding, )
@nx._dispatchable(graphs=None, returns_graph=True)def read_weighted_edgelist( path, comments="#", delimiter=None, create_using=None, nodetype=None, encoding="utf-8",): """Read a graph as list of edges with numeric weights.
Parameters ---------- path : file or string File or filename to read. If a file is provided, it must be opened in 'rb' mode. Filenames ending in .gz or .bz2 will be decompressed. comments : string, optional The character used to indicate the start of a comment. delimiter : string, optional The string used to separate values. The default is whitespace. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : int, float, str, Python type, optional Convert node data from strings to specified type encoding: string, optional Specify which encoding to use when reading file.
Returns ------- G : graph A networkx Graph or other type specified with create_using
Notes ----- Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.)
Example edgelist file format.
With numeric edge data::
# read with # >>> G=nx.read_weighted_edgelist(fh) # source target data a b 1 a c 3.14159 d e 42
See Also -------- write_weighted_edgelist """ return read_edgelist( path, comments=comments, delimiter=delimiter, create_using=create_using, nodetype=nodetype, data=(("weight", float),), encoding=encoding, )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084"""Read and write graphs in GEXF format.
.. warning:: This parser uses the standard xml library present in Python, which is insecure - see :external+python:mod:`xml` for additional information. Only parse GEFX files you trust.
GEXF (Graph Exchange XML Format) is a language for describing complexnetwork structures, their associated data and dynamics.
This implementation does not support mixed graphs (directed andundirected edges together).
Format------GEXF is an XML format. See http://gexf.net/schema.html for thespecification and http://gexf.net/basic.html for examples."""
import itertoolsimport timefrom xml.etree.ElementTree import ( Element, ElementTree, SubElement, register_namespace, tostring,)
import networkx as nxfrom networkx.utils import open_file
__all__ = ["write_gexf", "read_gexf", "relabel_gexf_graph", "generate_gexf"]
@open_file(1, mode="wb")def write_gexf(G, path, encoding="utf-8", prettyprint=True, version="1.2draft"): """Write G in GEXF format to path.
"GEXF (Graph Exchange XML Format) is a language for describing complex networks structures, their associated data and dynamics" [1]_.
Node attributes are checked according to the version of the GEXF schemas used for parameters which are not user defined, e.g. visualization 'viz' [2]_. See example for usage.
.. warning::
The `GEXF specification <https://gexf.net/schema.html>`_ reserves some keywords (e.g. ``id``, ``pid``, ``label``, etc.) for specifying node/edge metadata in the file format. Ensure NetworkX node/edge attribute names do not use these special keywords to guarantee all attributes are preserved as expected when roundtripping to/from GEXF format.
Parameters ---------- G : graph A NetworkX graph path : file or string File or file name to write. File names ending in .gz or .bz2 will be compressed. encoding : string (optional, default: 'utf-8') Encoding for text data. prettyprint : bool (optional, default: True) If True use line breaks and indenting in output XML. version: string (optional, default: '1.2draft') The version of GEXF to be used for nodes attributes checking
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_gexf(G, "test.gexf")
# visualization data >>> G.nodes[0]["viz"] = {"size": 54} >>> G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1} >>> G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256}
Notes ----- This implementation does not support mixed graphs (directed and undirected edges together).
The node id attribute is set to be the string of the node label. If you want to specify an id use set it as node data, e.g. node['a']['id']=1 to set the id of node 'a' to 1.
References ---------- .. [1] GEXF File Format, http://gexf.net/ .. [2] GEXF schema, http://gexf.net/schema.html """ writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version) writer.add_graph(G) writer.write(path)
def generate_gexf(G, encoding="utf-8", prettyprint=True, version="1.2draft"): """Generate lines of GEXF format representation of G.
"GEXF (Graph Exchange XML Format) is a language for describing complex networks structures, their associated data and dynamics" [1]_.
Parameters ---------- G : graph A NetworkX graph encoding : string (optional, default: 'utf-8') Encoding for text data. prettyprint : bool (optional, default: True) If True use line breaks and indenting in output XML. version : string (default: 1.2draft) Version of GEFX File Format (see http://gexf.net/schema.html) Supported values: "1.1draft", "1.2draft"
Examples -------- >>> G = nx.path_graph(4) >>> linefeed = chr(10) # linefeed=\n >>> s = linefeed.join(nx.generate_gexf(G)) >>> for line in nx.generate_gexf(G): # doctest: +SKIP ... print(line)
Notes ----- This implementation does not support mixed graphs (directed and undirected edges together).
The node id attribute is set to be the string of the node label. If you want to specify an id use set it as node data, e.g. node['a']['id']=1 to set the id of node 'a' to 1.
References ---------- .. [1] GEXF File Format, https://gephi.org/gexf/format/ """ writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version) writer.add_graph(G) yield from str(writer).splitlines()
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_gexf(path, node_type=None, relabel=False, version="1.2draft"): """Read graph in GEXF format from path.
"GEXF (Graph Exchange XML Format) is a language for describing complex networks structures, their associated data and dynamics" [1]_.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed. node_type: Python type (default: None) Convert node ids to this type if not None. relabel : bool (default: False) If True relabel the nodes to use the GEXF node "label" attribute instead of the node "id" attribute as the NetworkX node label. version : string (default: 1.2draft) Version of GEFX File Format (see http://gexf.net/schema.html) Supported values: "1.1draft", "1.2draft"
Returns ------- graph: NetworkX graph If no parallel edges are found a Graph or DiGraph is returned. Otherwise a MultiGraph or MultiDiGraph is returned.
Notes ----- This implementation does not support mixed graphs (directed and undirected edges together).
References ---------- .. [1] GEXF File Format, http://gexf.net/ """ reader = GEXFReader(node_type=node_type, version=version) if relabel: G = relabel_gexf_graph(reader(path)) else: G = reader(path) return G
class GEXF: versions = { "1.1draft": { "NS_GEXF": "http://www.gexf.net/1.1draft", "NS_VIZ": "http://www.gexf.net/1.1draft/viz", "NS_XSI": "http://www.w3.org/2001/XMLSchema-instance", "SCHEMALOCATION": " ".join( [ "http://www.gexf.net/1.1draft", "http://www.gexf.net/1.1draft/gexf.xsd", ] ), "VERSION": "1.1", }, "1.2draft": { "NS_GEXF": "http://www.gexf.net/1.2draft", "NS_VIZ": "http://www.gexf.net/1.2draft/viz", "NS_XSI": "http://www.w3.org/2001/XMLSchema-instance", "SCHEMALOCATION": " ".join( [ "http://www.gexf.net/1.2draft", "http://www.gexf.net/1.2draft/gexf.xsd", ] ), "VERSION": "1.2", }, "1.3": { "NS_GEXF": "http://gexf.net/1.3", "NS_VIZ": "http://gexf.net/1.3/viz", "NS_XSI": "http://w3.org/2001/XMLSchema-instance", "SCHEMALOCATION": " ".join( [ "http://gexf.net/1.3", "http://gexf.net/1.3/gexf.xsd", ] ), "VERSION": "1.3", }, }
def construct_types(self): types = [ (int, "integer"), (float, "float"), (float, "double"), (bool, "boolean"), (list, "string"), (dict, "string"), (int, "long"), (str, "liststring"), (str, "anyURI"), (str, "string"), ]
# These additions to types allow writing numpy types try: import numpy as np except ImportError: pass else: # prepend so that python types are created upon read (last entry wins) types = [ (np.float64, "float"), (np.float32, "float"), (np.float16, "float"), (np.int_, "int"), (np.int8, "int"), (np.int16, "int"), (np.int32, "int"), (np.int64, "int"), (np.uint8, "int"), (np.uint16, "int"), (np.uint32, "int"), (np.uint64, "int"), (np.int_, "int"), (np.intc, "int"), (np.intp, "int"), ] + types
self.xml_type = dict(types) self.python_type = dict(reversed(a) for a in types)
# http://www.w3.org/TR/xmlschema-2/#boolean convert_bool = { "true": True, "false": False, "True": True, "False": False, "0": False, 0: False, "1": True, 1: True, }
def set_version(self, version): d = self.versions.get(version) if d is None: raise nx.NetworkXError(f"Unknown GEXF version {version}.") self.NS_GEXF = d["NS_GEXF"] self.NS_VIZ = d["NS_VIZ"] self.NS_XSI = d["NS_XSI"] self.SCHEMALOCATION = d["SCHEMALOCATION"] self.VERSION = d["VERSION"] self.version = version
class GEXFWriter(GEXF): # class for writing GEXF format files # use write_gexf() function def __init__( self, graph=None, encoding="utf-8", prettyprint=True, version="1.2draft" ): self.construct_types() self.prettyprint = prettyprint self.encoding = encoding self.set_version(version) self.xml = Element( "gexf", { "xmlns": self.NS_GEXF, "xmlns:xsi": self.NS_XSI, "xsi:schemaLocation": self.SCHEMALOCATION, "version": self.VERSION, }, )
# Make meta element a non-graph element # Also add lastmodifieddate as attribute, not tag meta_element = Element("meta") subelement_text = f"NetworkX {nx.__version__}" SubElement(meta_element, "creator").text = subelement_text meta_element.set("lastmodifieddate", time.strftime("%Y-%m-%d")) self.xml.append(meta_element)
register_namespace("viz", self.NS_VIZ)
# counters for edge and attribute identifiers self.edge_id = itertools.count() self.attr_id = itertools.count() self.all_edge_ids = set() # default attributes are stored in dictionaries self.attr = {} self.attr["node"] = {} self.attr["edge"] = {} self.attr["node"]["dynamic"] = {} self.attr["node"]["static"] = {} self.attr["edge"]["dynamic"] = {} self.attr["edge"]["static"] = {}
if graph is not None: self.add_graph(graph)
def __str__(self): if self.prettyprint: self.indent(self.xml) s = tostring(self.xml).decode(self.encoding) return s
def add_graph(self, G): # first pass through G collecting edge ids for u, v, dd in G.edges(data=True): eid = dd.get("id") if eid is not None: self.all_edge_ids.add(str(eid)) # set graph attributes if G.graph.get("mode") == "dynamic": mode = "dynamic" else: mode = "static" # Add a graph element to the XML if G.is_directed(): default = "directed" else: default = "undirected" name = G.graph.get("name", "") graph_element = Element("graph", defaultedgetype=default, mode=mode, name=name) self.graph_element = graph_element self.add_nodes(G, graph_element) self.add_edges(G, graph_element) self.xml.append(graph_element)
def add_nodes(self, G, graph_element): nodes_element = Element("nodes") for node, data in G.nodes(data=True): node_data = data.copy() node_id = str(node_data.pop("id", node)) kw = {"id": node_id} label = str(node_data.pop("label", node)) kw["label"] = label try: pid = node_data.pop("pid") kw["pid"] = str(pid) except KeyError: pass try: start = node_data.pop("start") kw["start"] = str(start) self.alter_graph_mode_timeformat(start) except KeyError: pass try: end = node_data.pop("end") kw["end"] = str(end) self.alter_graph_mode_timeformat(end) except KeyError: pass # add node element with attributes node_element = Element("node", **kw) # add node element and attr subelements default = G.graph.get("node_default", {}) node_data = self.add_parents(node_element, node_data) if self.VERSION == "1.1": node_data = self.add_slices(node_element, node_data) else: node_data = self.add_spells(node_element, node_data) node_data = self.add_viz(node_element, node_data) node_data = self.add_attributes("node", node_element, node_data, default) nodes_element.append(node_element) graph_element.append(nodes_element)
def add_edges(self, G, graph_element): def edge_key_data(G): # helper function to unify multigraph and graph edge iterator if G.is_multigraph(): for u, v, key, data in G.edges(data=True, keys=True): edge_data = data.copy() edge_data.update(key=key) edge_id = edge_data.pop("id", None) if edge_id is None: edge_id = next(self.edge_id) while str(edge_id) in self.all_edge_ids: edge_id = next(self.edge_id) self.all_edge_ids.add(str(edge_id)) yield u, v, edge_id, edge_data else: for u, v, data in G.edges(data=True): edge_data = data.copy() edge_id = edge_data.pop("id", None) if edge_id is None: edge_id = next(self.edge_id) while str(edge_id) in self.all_edge_ids: edge_id = next(self.edge_id) self.all_edge_ids.add(str(edge_id)) yield u, v, edge_id, edge_data
edges_element = Element("edges") for u, v, key, edge_data in edge_key_data(G): kw = {"id": str(key)} try: edge_label = edge_data.pop("label") kw["label"] = str(edge_label) except KeyError: pass try: edge_weight = edge_data.pop("weight") kw["weight"] = str(edge_weight) except KeyError: pass try: edge_type = edge_data.pop("type") kw["type"] = str(edge_type) except KeyError: pass try: start = edge_data.pop("start") kw["start"] = str(start) self.alter_graph_mode_timeformat(start) except KeyError: pass try: end = edge_data.pop("end") kw["end"] = str(end) self.alter_graph_mode_timeformat(end) except KeyError: pass source_id = str(G.nodes[u].get("id", u)) target_id = str(G.nodes[v].get("id", v)) edge_element = Element("edge", source=source_id, target=target_id, **kw) default = G.graph.get("edge_default", {}) if self.VERSION == "1.1": edge_data = self.add_slices(edge_element, edge_data) else: edge_data = self.add_spells(edge_element, edge_data) edge_data = self.add_viz(edge_element, edge_data) edge_data = self.add_attributes("edge", edge_element, edge_data, default) edges_element.append(edge_element) graph_element.append(edges_element)
def add_attributes(self, node_or_edge, xml_obj, data, default): # Add attrvalues to node or edge attvalues = Element("attvalues") if len(data) == 0: return data mode = "static" for k, v in data.items(): # rename generic multigraph key to avoid any name conflict if k == "key": k = "networkx_key" val_type = type(v) if val_type not in self.xml_type: raise TypeError(f"attribute value type is not allowed: {val_type}") if isinstance(v, list): # dynamic data for val, start, end in v: val_type = type(val) if start is not None or end is not None: mode = "dynamic" self.alter_graph_mode_timeformat(start) self.alter_graph_mode_timeformat(end) break attr_id = self.get_attr_id( str(k), self.xml_type[val_type], node_or_edge, default, mode ) for val, start, end in v: e = Element("attvalue") e.attrib["for"] = attr_id e.attrib["value"] = str(val) # Handle nan, inf, -inf differently if val_type is float: if e.attrib["value"] == "inf": e.attrib["value"] = "INF" elif e.attrib["value"] == "nan": e.attrib["value"] = "NaN" elif e.attrib["value"] == "-inf": e.attrib["value"] = "-INF" if start is not None: e.attrib["start"] = str(start) if end is not None: e.attrib["end"] = str(end) attvalues.append(e) else: # static data mode = "static" attr_id = self.get_attr_id( str(k), self.xml_type[val_type], node_or_edge, default, mode ) e = Element("attvalue") e.attrib["for"] = attr_id if isinstance(v, bool): e.attrib["value"] = str(v).lower() else: e.attrib["value"] = str(v) # Handle float nan, inf, -inf differently if val_type is float: if e.attrib["value"] == "inf": e.attrib["value"] = "INF" elif e.attrib["value"] == "nan": e.attrib["value"] = "NaN" elif e.attrib["value"] == "-inf": e.attrib["value"] = "-INF" attvalues.append(e) xml_obj.append(attvalues) return data
def get_attr_id(self, title, attr_type, edge_or_node, default, mode): # find the id of the attribute or generate a new id try: return self.attr[edge_or_node][mode][title] except KeyError: # generate new id new_id = str(next(self.attr_id)) self.attr[edge_or_node][mode][title] = new_id attr_kwargs = {"id": new_id, "title": title, "type": attr_type} attribute = Element("attribute", **attr_kwargs) # add subelement for data default value if present default_title = default.get(title) if default_title is not None: default_element = Element("default") default_element.text = str(default_title) attribute.append(default_element) # new insert it into the XML attributes_element = None for a in self.graph_element.findall("attributes"): # find existing attributes element by class and mode a_class = a.get("class") a_mode = a.get("mode", "static") if a_class == edge_or_node and a_mode == mode: attributes_element = a if attributes_element is None: # create new attributes element attr_kwargs = {"mode": mode, "class": edge_or_node} attributes_element = Element("attributes", **attr_kwargs) self.graph_element.insert(0, attributes_element) attributes_element.append(attribute) return new_id
def add_viz(self, element, node_data): viz = node_data.pop("viz", False) if viz: color = viz.get("color") if color is not None: if self.VERSION == "1.1": e = Element( f"{{{self.NS_VIZ}}}color", r=str(color.get("r")), g=str(color.get("g")), b=str(color.get("b")), ) else: e = Element( f"{{{self.NS_VIZ}}}color", r=str(color.get("r")), g=str(color.get("g")), b=str(color.get("b")), a=str(color.get("a", 1.0)), ) element.append(e)
size = viz.get("size") if size is not None: e = Element(f"{{{self.NS_VIZ}}}size", value=str(size)) element.append(e)
thickness = viz.get("thickness") if thickness is not None: e = Element(f"{{{self.NS_VIZ}}}thickness", value=str(thickness)) element.append(e)
shape = viz.get("shape") if shape is not None: if shape.startswith("http"): e = Element( f"{{{self.NS_VIZ}}}shape", value="image", uri=str(shape) ) else: e = Element(f"{{{self.NS_VIZ}}}shape", value=str(shape)) element.append(e)
position = viz.get("position") if position is not None: e = Element( f"{{{self.NS_VIZ}}}position", x=str(position.get("x")), y=str(position.get("y")), z=str(position.get("z")), ) element.append(e) return node_data
def add_parents(self, node_element, node_data): parents = node_data.pop("parents", False) if parents: parents_element = Element("parents") for p in parents: e = Element("parent") e.attrib["for"] = str(p) parents_element.append(e) node_element.append(parents_element) return node_data
def add_slices(self, node_or_edge_element, node_or_edge_data): slices = node_or_edge_data.pop("slices", False) if slices: slices_element = Element("slices") for start, end in slices: e = Element("slice", start=str(start), end=str(end)) slices_element.append(e) node_or_edge_element.append(slices_element) return node_or_edge_data
def add_spells(self, node_or_edge_element, node_or_edge_data): spells = node_or_edge_data.pop("spells", False) if spells: spells_element = Element("spells") for start, end in spells: e = Element("spell") if start is not None: e.attrib["start"] = str(start) self.alter_graph_mode_timeformat(start) if end is not None: e.attrib["end"] = str(end) self.alter_graph_mode_timeformat(end) spells_element.append(e) node_or_edge_element.append(spells_element) return node_or_edge_data
def alter_graph_mode_timeformat(self, start_or_end): # If 'start' or 'end' appears, set timeformat if start_or_end is not None: if isinstance(start_or_end, str): timeformat = "date" elif isinstance(start_or_end, float): timeformat = "double" elif isinstance(start_or_end, int): timeformat = "long" else: raise nx.NetworkXError( "timeformat should be of the type int, float or str" ) self.graph_element.set("timeformat", timeformat) # If Graph mode is static, alter to dynamic if self.graph_element.get("mode") == "static": self.graph_element.set("mode", "dynamic")
def write(self, fh): # Serialize graph G in GEXF to the open fh if self.prettyprint: self.indent(self.xml) document = ElementTree(self.xml) document.write(fh, encoding=self.encoding, xml_declaration=True)
def indent(self, elem, level=0): # in-place prettyprint formatter i = "\n" + " " * level if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: self.indent(elem, level + 1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i
class GEXFReader(GEXF): # Class to read GEXF format files # use read_gexf() function def __init__(self, node_type=None, version="1.2draft"): self.construct_types() self.node_type = node_type # assume simple graph and test for multigraph on read self.simple_graph = True self.set_version(version)
def __call__(self, stream): self.xml = ElementTree(file=stream) g = self.xml.find(f"{{{self.NS_GEXF}}}graph") if g is not None: return self.make_graph(g) # try all the versions for version in self.versions: self.set_version(version) g = self.xml.find(f"{{{self.NS_GEXF}}}graph") if g is not None: return self.make_graph(g) raise nx.NetworkXError("No <graph> element in GEXF file.")
def make_graph(self, graph_xml): # start with empty DiGraph or MultiDiGraph edgedefault = graph_xml.get("defaultedgetype", None) if edgedefault == "directed": G = nx.MultiDiGraph() else: G = nx.MultiGraph()
# graph attributes graph_name = graph_xml.get("name", "") if graph_name != "": G.graph["name"] = graph_name graph_start = graph_xml.get("start") if graph_start is not None: G.graph["start"] = graph_start graph_end = graph_xml.get("end") if graph_end is not None: G.graph["end"] = graph_end graph_mode = graph_xml.get("mode", "") if graph_mode == "dynamic": G.graph["mode"] = "dynamic" else: G.graph["mode"] = "static"
# timeformat self.timeformat = graph_xml.get("timeformat") if self.timeformat == "date": self.timeformat = "string"
# node and edge attributes attributes_elements = graph_xml.findall(f"{{{self.NS_GEXF}}}attributes") # dictionaries to hold attributes and attribute defaults node_attr = {} node_default = {} edge_attr = {} edge_default = {} for a in attributes_elements: attr_class = a.get("class") if attr_class == "node": na, nd = self.find_gexf_attributes(a) node_attr.update(na) node_default.update(nd) G.graph["node_default"] = node_default elif attr_class == "edge": ea, ed = self.find_gexf_attributes(a) edge_attr.update(ea) edge_default.update(ed) G.graph["edge_default"] = edge_default else: raise # unknown attribute class
# Hack to handle Gephi0.7beta bug # add weight attribute ea = {"weight": {"type": "double", "mode": "static", "title": "weight"}} ed = {} edge_attr.update(ea) edge_default.update(ed) G.graph["edge_default"] = edge_default
# add nodes nodes_element = graph_xml.find(f"{{{self.NS_GEXF}}}nodes") if nodes_element is not None: for node_xml in nodes_element.findall(f"{{{self.NS_GEXF}}}node"): self.add_node(G, node_xml, node_attr)
# add edges edges_element = graph_xml.find(f"{{{self.NS_GEXF}}}edges") if edges_element is not None: for edge_xml in edges_element.findall(f"{{{self.NS_GEXF}}}edge"): self.add_edge(G, edge_xml, edge_attr)
# switch to Graph or DiGraph if no parallel edges were found. if self.simple_graph: if G.is_directed(): G = nx.DiGraph(G) else: G = nx.Graph(G) return G
def add_node(self, G, node_xml, node_attr, node_pid=None): # add a single node with attributes to the graph
# get attributes and subattributues for node data = self.decode_attr_elements(node_attr, node_xml) data = self.add_parents(data, node_xml) # add any parents if self.VERSION == "1.1": data = self.add_slices(data, node_xml) # add slices else: data = self.add_spells(data, node_xml) # add spells data = self.add_viz(data, node_xml) # add viz data = self.add_start_end(data, node_xml) # add start/end
# find the node id and cast it to the appropriate type node_id = node_xml.get("id") if self.node_type is not None: node_id = self.node_type(node_id)
# every node should have a label node_label = node_xml.get("label") data["label"] = node_label
# parent node id node_pid = node_xml.get("pid", node_pid) if node_pid is not None: data["pid"] = node_pid
# check for subnodes, recursive subnodes = node_xml.find(f"{{{self.NS_GEXF}}}nodes") if subnodes is not None: for node_xml in subnodes.findall(f"{{{self.NS_GEXF}}}node"): self.add_node(G, node_xml, node_attr, node_pid=node_id)
G.add_node(node_id, **data)
def add_start_end(self, data, xml): # start and end times ttype = self.timeformat node_start = xml.get("start") if node_start is not None: data["start"] = self.python_type[ttype](node_start) node_end = xml.get("end") if node_end is not None: data["end"] = self.python_type[ttype](node_end) return data
def add_viz(self, data, node_xml): # add viz element for node viz = {} color = node_xml.find(f"{{{self.NS_VIZ}}}color") if color is not None: if self.VERSION == "1.1": viz["color"] = { "r": int(color.get("r")), "g": int(color.get("g")), "b": int(color.get("b")), } else: viz["color"] = { "r": int(color.get("r")), "g": int(color.get("g")), "b": int(color.get("b")), "a": float(color.get("a", 1)), }
size = node_xml.find(f"{{{self.NS_VIZ}}}size") if size is not None: viz["size"] = float(size.get("value"))
thickness = node_xml.find(f"{{{self.NS_VIZ}}}thickness") if thickness is not None: viz["thickness"] = float(thickness.get("value"))
shape = node_xml.find(f"{{{self.NS_VIZ}}}shape") if shape is not None: viz["shape"] = shape.get("shape") if viz["shape"] == "image": viz["shape"] = shape.get("uri")
position = node_xml.find(f"{{{self.NS_VIZ}}}position") if position is not None: viz["position"] = { "x": float(position.get("x", 0)), "y": float(position.get("y", 0)), "z": float(position.get("z", 0)), }
if len(viz) > 0: data["viz"] = viz return data
def add_parents(self, data, node_xml): parents_element = node_xml.find(f"{{{self.NS_GEXF}}}parents") if parents_element is not None: data["parents"] = [] for p in parents_element.findall(f"{{{self.NS_GEXF}}}parent"): parent = p.get("for") data["parents"].append(parent) return data
def add_slices(self, data, node_or_edge_xml): slices_element = node_or_edge_xml.find(f"{{{self.NS_GEXF}}}slices") if slices_element is not None: data["slices"] = [] for s in slices_element.findall(f"{{{self.NS_GEXF}}}slice"): start = s.get("start") end = s.get("end") data["slices"].append((start, end)) return data
def add_spells(self, data, node_or_edge_xml): spells_element = node_or_edge_xml.find(f"{{{self.NS_GEXF}}}spells") if spells_element is not None: data["spells"] = [] ttype = self.timeformat for s in spells_element.findall(f"{{{self.NS_GEXF}}}spell"): start = self.python_type[ttype](s.get("start")) end = self.python_type[ttype](s.get("end")) data["spells"].append((start, end)) return data
def add_edge(self, G, edge_element, edge_attr): # add an edge to the graph
# raise error if we find mixed directed and undirected edges edge_direction = edge_element.get("type") if G.is_directed() and edge_direction == "undirected": raise nx.NetworkXError("Undirected edge found in directed graph.") if (not G.is_directed()) and edge_direction == "directed": raise nx.NetworkXError("Directed edge found in undirected graph.")
# Get source and target and recast type if required source = edge_element.get("source") target = edge_element.get("target") if self.node_type is not None: source = self.node_type(source) target = self.node_type(target)
data = self.decode_attr_elements(edge_attr, edge_element) data = self.add_start_end(data, edge_element)
if self.VERSION == "1.1": data = self.add_slices(data, edge_element) # add slices else: data = self.add_spells(data, edge_element) # add spells
# GEXF stores edge ids as an attribute # NetworkX uses them as keys in multigraphs # if networkx_key is not specified as an attribute edge_id = edge_element.get("id") if edge_id is not None: data["id"] = edge_id
# check if there is a 'multigraph_key' and use that as edge_id multigraph_key = data.pop("networkx_key", None) if multigraph_key is not None: edge_id = multigraph_key
weight = edge_element.get("weight") if weight is not None: data["weight"] = float(weight)
edge_label = edge_element.get("label") if edge_label is not None: data["label"] = edge_label
if G.has_edge(source, target): # seen this edge before - this is a multigraph self.simple_graph = False G.add_edge(source, target, key=edge_id, **data) if edge_direction == "mutual": G.add_edge(target, source, key=edge_id, **data)
def decode_attr_elements(self, gexf_keys, obj_xml): # Use the key information to decode the attr XML attr = {} # look for outer '<attvalues>' element attr_element = obj_xml.find(f"{{{self.NS_GEXF}}}attvalues") if attr_element is not None: # loop over <attvalue> elements for a in attr_element.findall(f"{{{self.NS_GEXF}}}attvalue"): key = a.get("for") # for is required try: # should be in our gexf_keys dictionary title = gexf_keys[key]["title"] except KeyError as err: raise nx.NetworkXError(f"No attribute defined for={key}.") from err atype = gexf_keys[key]["type"] value = a.get("value") if atype == "boolean": value = self.convert_bool[value] else: value = self.python_type[atype](value) if gexf_keys[key]["mode"] == "dynamic": # for dynamic graphs use list of three-tuples # [(value1,start1,end1), (value2,start2,end2), etc] ttype = self.timeformat start = self.python_type[ttype](a.get("start")) end = self.python_type[ttype](a.get("end")) if title in attr: attr[title].append((value, start, end)) else: attr[title] = [(value, start, end)] else: # for static graphs just assign the value attr[title] = value return attr
def find_gexf_attributes(self, attributes_element): # Extract all the attributes and defaults attrs = {} defaults = {} mode = attributes_element.get("mode") for k in attributes_element.findall(f"{{{self.NS_GEXF}}}attribute"): attr_id = k.get("id") title = k.get("title") atype = k.get("type") attrs[attr_id] = {"title": title, "type": atype, "mode": mode} # check for the 'default' subelement of key element and add default = k.find(f"{{{self.NS_GEXF}}}default") if default is not None: if atype == "boolean": value = self.convert_bool[default.text] else: value = self.python_type[atype](default.text) defaults[title] = value return attrs, defaults
def relabel_gexf_graph(G): """Relabel graph using "label" node keyword for node label.
Parameters ---------- G : graph A NetworkX graph read from GEXF data
Returns ------- H : graph A NetworkX graph with relabeled nodes
Raises ------ NetworkXError If node labels are missing or not unique while relabel=True.
Notes ----- This function relabels the nodes in a NetworkX graph with the "label" attribute. It also handles relabeling the specific GEXF node attributes "parents", and "pid". """ # build mapping of node labels, do some error checking try: mapping = [(u, G.nodes[u]["label"]) for u in G] except KeyError as err: raise nx.NetworkXError( "Failed to relabel nodes: missing node labels found. Use relabel=False." ) from err x, y = zip(*mapping) if len(set(y)) != len(G): raise nx.NetworkXError( "Failed to relabel nodes: duplicate node labels found. Use relabel=False." ) mapping = dict(mapping) H = nx.relabel_nodes(G, mapping) # relabel attributes for n in G: m = mapping[n] H.nodes[m]["id"] = n H.nodes[m].pop("label") if "pid" in H.nodes[m]: H.nodes[m]["pid"] = mapping[G.nodes[n]["pid"]] if "parents" in H.nodes[m]: H.nodes[m]["parents"] = [mapping[p] for p in G.nodes[n]["parents"]] return H123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879"""Read graphs in GML format.
"GML, the Graph Modelling Language, is our proposal for a portablefile format for graphs. GML's key features are portability, simplesyntax, extensibility and flexibility. A GML file consists of ahierarchical key-value lists. Graphs can be annotated with arbitrarydata structures. The idea for a common file format was born at theGD'95; this proposal is the outcome of many discussions. GML is thestandard file format in the Graphlet graph editor system. It has beenovertaken and adapted by several other systems for drawing graphs."
GML files are stored using a 7-bit ASCII encoding with any extendedASCII characters (iso8859-1) appearing as HTML character entities.You will need to give some thought into how the exported data shouldinteract with different languages and even different Python versions.Re-importing from gml is also a concern.
Without specifying a `stringizer`/`destringizer`, the code is capable ofwriting `int`/`float`/`str`/`dict`/`list` data as required by the GMLspecification. For writing other data types, and for reading data otherthan `str` you need to explicitly supply a `stringizer`/`destringizer`.
For additional documentation on the GML file format, please see the`GML website <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
Several example graphs in GML format may be found on Mark Newman's`Network data page <http://www-personal.umich.edu/~mejn/netdata/>`_."""
import html.entities as htmlentitydefsimport refrom ast import literal_evalfrom collections import defaultdictfrom enum import Enumfrom io import StringIOfrom typing import Any, NamedTuple
import networkx as nxfrom networkx.exception import NetworkXErrorfrom networkx.utils import open_file
__all__ = ["read_gml", "parse_gml", "generate_gml", "write_gml"]
def escape(text): """Use XML character references to escape characters.
Use XML character references for unprintable or non-ASCII characters, double quotes and ampersands in a string """
def fixup(m): ch = m.group(0) return "&#" + str(ord(ch)) + ";"
text = re.sub('[^ -~]|[&"]', fixup, text) return text if isinstance(text, str) else str(text)
def unescape(text): """Replace XML character references with the referenced characters"""
def fixup(m): text = m.group(0) if text[1] == "#": # Character reference if text[2] == "x": code = int(text[3:-1], 16) else: code = int(text[2:-1]) else: # Named entity try: code = htmlentitydefs.name2codepoint[text[1:-1]] except KeyError: return text # leave unchanged try: return chr(code) except (ValueError, OverflowError): return text # leave unchanged
return re.sub("&(?:[0-9A-Za-z]+|#(?:[0-9]+|x[0-9A-Fa-f]+));", fixup, text)
def literal_destringizer(rep): """Convert a Python literal to the value it represents.
Parameters ---------- rep : string A Python literal.
Returns ------- value : object The value of the Python literal.
Raises ------ ValueError If `rep` is not a Python literal. """ if isinstance(rep, str): orig_rep = rep try: return literal_eval(rep) except SyntaxError as err: raise ValueError(f"{orig_rep!r} is not a valid Python literal") from err else: raise ValueError(f"{rep!r} is not a string")
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_gml(path, label="label", destringizer=None): """Read graph in GML format from `path`.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
label : string, optional If not None, the parsed nodes will be renamed according to node attributes indicated by `label`. Default value: 'label'.
destringizer : callable, optional A `destringizer` that recovers values stored as strings in GML. If it cannot convert a string to a value, a `ValueError` is raised. Default value : None.
Returns ------- G : NetworkX graph The parsed graph.
Raises ------ NetworkXError If the input cannot be parsed.
See Also -------- write_gml, parse_gml literal_destringizer
Notes ----- GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of writing `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For writing other data types, and for reading data other than `str` you need to explicitly supply a `stringizer`/`destringizer`.
For additional documentation on the GML file format, please see the `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
See the module docstring :mod:`networkx.readwrite.gml` for more details.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_gml(G, "test_path4.gml")
GML values are interpreted as strings by default:
>>> H = nx.read_gml("test_path4.gml") >>> H.nodes NodeView(('0', '1', '2', '3'))
When a `destringizer` is provided, GML values are converted to the provided type. For example, integer nodes can be recovered as shown below:
>>> J = nx.read_gml("test_path4.gml", destringizer=int) >>> J.nodes NodeView((0, 1, 2, 3))
"""
def filter_lines(lines): for line in lines: try: line = line.decode("ascii") except UnicodeDecodeError as err: raise NetworkXError("input is not ASCII-encoded") from err if not isinstance(line, str): lines = str(lines) if line and line[-1] == "\n": line = line[:-1] yield line
G = parse_gml_lines(filter_lines(path), label, destringizer) return G
@nx._dispatchable(graphs=None, returns_graph=True)def parse_gml(lines, label="label", destringizer=None): """Parse GML graph from a string or iterable.
Parameters ---------- lines : string or iterable of strings Data in GML format.
label : string, optional If not None, the parsed nodes will be renamed according to node attributes indicated by `label`. Default value: 'label'.
destringizer : callable, optional A `destringizer` that recovers values stored as strings in GML. If it cannot convert a string to a value, a `ValueError` is raised. Default value : None.
Returns ------- G : NetworkX graph The parsed graph.
Raises ------ NetworkXError If the input cannot be parsed.
See Also -------- write_gml, read_gml
Notes ----- This stores nested GML attributes as dictionaries in the NetworkX graph, node, and edge attribute structures.
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of writing `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For writing other data types, and for reading data other than `str` you need to explicitly supply a `stringizer`/`destringizer`.
For additional documentation on the GML file format, please see the `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
See the module docstring :mod:`networkx.readwrite.gml` for more details. """
def decode_line(line): if isinstance(line, bytes): try: line.decode("ascii") except UnicodeDecodeError as err: raise NetworkXError("input is not ASCII-encoded") from err if not isinstance(line, str): line = str(line) return line
def filter_lines(lines): if isinstance(lines, str): lines = decode_line(lines) lines = lines.splitlines() yield from lines else: for line in lines: line = decode_line(line) if line and line[-1] == "\n": line = line[:-1] if line.find("\n") != -1: raise NetworkXError("input line contains newline") yield line
G = parse_gml_lines(filter_lines(lines), label, destringizer) return G
class Pattern(Enum): """encodes the index of each token-matching pattern in `tokenize`."""
KEYS = 0 REALS = 1 INTS = 2 STRINGS = 3 DICT_START = 4 DICT_END = 5 COMMENT_WHITESPACE = 6
class Token(NamedTuple): category: Pattern value: Any line: int position: int
LIST_START_VALUE = "_networkx_list_start"
def parse_gml_lines(lines, label, destringizer): """Parse GML `lines` into a graph."""
def tokenize(): patterns = [ r"[A-Za-z][0-9A-Za-z_]*\b", # keys # reals r"[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|INF)(?:[Ee][+-]?[0-9]+)?", r"[+-]?[0-9]+", # ints r'".*?"', # strings r"\[", # dict start r"\]", # dict end r"#.*$|\s+", # comments and whitespaces ] tokens = re.compile("|".join(f"({pattern})" for pattern in patterns)) lineno = 0 multilines = [] # entries spread across multiple lines for line in lines: pos = 0
# deal with entries spread across multiple lines # # should we actually have to deal with escaped "s then do it here if multilines: multilines.append(line.strip()) if line[-1] == '"': # closing multiline entry # multiline entries will be joined by space. cannot # reintroduce newlines as this will break the tokenizer line = " ".join(multilines) multilines = [] else: # continued multiline entry lineno += 1 continue else: if line.count('"') == 1: # opening multiline entry if line.strip()[0] != '"' and line.strip()[-1] != '"': # since we expect something like key "value", the " should not be found at ends # otherwise tokenizer will pick up the formatting mistake. multilines = [line.rstrip()] lineno += 1 continue
length = len(line)
while pos < length: match = tokens.match(line, pos) if match is None: m = f"cannot tokenize {line[pos:]} at ({lineno + 1}, {pos + 1})" raise NetworkXError(m) for i in range(len(patterns)): group = match.group(i + 1) if group is not None: if i == 0: # keys value = group.rstrip() elif i == 1: # reals value = float(group) elif i == 2: # ints value = int(group) else: value = group if i != 6: # comments and whitespaces yield Token(Pattern(i), value, lineno + 1, pos + 1) pos += len(group) break lineno += 1 yield Token(None, None, lineno + 1, 1) # EOF
def unexpected(curr_token, expected): category, value, lineno, pos = curr_token value = repr(value) if value is not None else "EOF" raise NetworkXError(f"expected {expected}, found {value} at ({lineno}, {pos})")
def consume(curr_token, category, expected): if curr_token.category == category: return next(tokens) unexpected(curr_token, expected)
def parse_kv(curr_token): dct = defaultdict(list) while curr_token.category == Pattern.KEYS: key = curr_token.value curr_token = next(tokens) category = curr_token.category if category == Pattern.REALS or category == Pattern.INTS: value = curr_token.value curr_token = next(tokens) elif category == Pattern.STRINGS: value = unescape(curr_token.value[1:-1]) if destringizer: try: value = destringizer(value) except ValueError: pass # Special handling for empty lists and tuples if value == "()": value = () if value == "[]": value = [] curr_token = next(tokens) elif category == Pattern.DICT_START: curr_token, value = parse_dict(curr_token) else: # Allow for string convertible id and label values if key in ("id", "label", "source", "target"): try: # String convert the token value value = unescape(str(curr_token.value)) if destringizer: try: value = destringizer(value) except ValueError: pass curr_token = next(tokens) except Exception: msg = ( "an int, float, string, '[' or string" + " convertible ASCII value for node id or label" ) unexpected(curr_token, msg) # Special handling for nan and infinity. Since the gml language # defines unquoted strings as keys, the numeric and string branches # are skipped and we end up in this special branch, so we need to # convert the current token value to a float for NAN and plain INF. # +/-INF are handled in the pattern for 'reals' in tokenize(). This # allows labels and values to be nan or infinity, but not keys. elif curr_token.value in {"NAN", "INF"}: value = float(curr_token.value) curr_token = next(tokens) else: # Otherwise error out unexpected(curr_token, "an int, float, string or '['") dct[key].append(value)
def clean_dict_value(value): if not isinstance(value, list): return value if len(value) == 1: return value[0] if value[0] == LIST_START_VALUE: return value[1:] return value
dct = {key: clean_dict_value(value) for key, value in dct.items()} return curr_token, dct
def parse_dict(curr_token): # dict start curr_token = consume(curr_token, Pattern.DICT_START, "'['") # dict contents curr_token, dct = parse_kv(curr_token) # dict end curr_token = consume(curr_token, Pattern.DICT_END, "']'") return curr_token, dct
def parse_graph(): curr_token, dct = parse_kv(next(tokens)) if curr_token.category is not None: # EOF unexpected(curr_token, "EOF") if "graph" not in dct: raise NetworkXError("input contains no graph") graph = dct["graph"] if isinstance(graph, list): raise NetworkXError("input contains more than one graph") return graph
tokens = tokenize() graph = parse_graph()
directed = graph.pop("directed", False) multigraph = graph.pop("multigraph", False) if not multigraph: G = nx.DiGraph() if directed else nx.Graph() else: G = nx.MultiDiGraph() if directed else nx.MultiGraph() graph_attr = {k: v for k, v in graph.items() if k not in ("node", "edge")} G.graph.update(graph_attr)
def pop_attr(dct, category, attr, i): try: return dct.pop(attr) except KeyError as err: raise NetworkXError(f"{category} #{i} has no {attr!r} attribute") from err
nodes = graph.get("node", []) mapping = {} node_labels = set() for i, node in enumerate(nodes if isinstance(nodes, list) else [nodes]): id = pop_attr(node, "node", "id", i) if id in G: raise NetworkXError(f"node id {id!r} is duplicated") if label is not None and label != "id": node_label = pop_attr(node, "node", label, i) if node_label in node_labels: raise NetworkXError(f"node label {node_label!r} is duplicated") node_labels.add(node_label) mapping[id] = node_label G.add_node(id, **node)
edges = graph.get("edge", []) for i, edge in enumerate(edges if isinstance(edges, list) else [edges]): source = pop_attr(edge, "edge", "source", i) target = pop_attr(edge, "edge", "target", i) if source not in G: raise NetworkXError(f"edge #{i} has undefined source {source!r}") if target not in G: raise NetworkXError(f"edge #{i} has undefined target {target!r}") if not multigraph: if not G.has_edge(source, target): G.add_edge(source, target, **edge) else: arrow = "->" if directed else "--" msg = f"edge #{i} ({source!r}{arrow}{target!r}) is duplicated" raise nx.NetworkXError(msg) else: key = edge.pop("key", None) if key is not None and G.has_edge(source, target, key): arrow = "->" if directed else "--" msg = f"edge #{i} ({source!r}{arrow}{target!r}, {key!r})" msg2 = 'Hint: If multigraph add "multigraph 1" to file header.' raise nx.NetworkXError(msg + " is duplicated\n" + msg2) G.add_edge(source, target, key, **edge)
if label is not None and label != "id": G = nx.relabel_nodes(G, mapping) return G
def literal_stringizer(value): """Convert a `value` to a Python literal in GML representation.
Parameters ---------- value : object The `value` to be converted to GML representation.
Returns ------- rep : string A double-quoted Python literal representing value. Unprintable characters are replaced by XML character references.
Raises ------ ValueError If `value` cannot be converted to GML.
Notes ----- The original value can be recovered using the :func:`networkx.readwrite.gml.literal_destringizer` function. """
def stringize(value): if isinstance(value, int | bool) or value is None: if value is True: # GML uses 1/0 for boolean values. buf.write(str(1)) elif value is False: buf.write(str(0)) else: buf.write(str(value)) elif isinstance(value, str): text = repr(value) if text[0] != "u": try: value.encode("latin1") except UnicodeEncodeError: text = "u" + text buf.write(text) elif isinstance(value, float | complex | str | bytes): buf.write(repr(value)) elif isinstance(value, list): buf.write("[") first = True for item in value: if not first: buf.write(",") else: first = False stringize(item) buf.write("]") elif isinstance(value, tuple): if len(value) > 1: buf.write("(") first = True for item in value: if not first: buf.write(",") else: first = False stringize(item) buf.write(")") elif value: buf.write("(") stringize(value[0]) buf.write(",)") else: buf.write("()") elif isinstance(value, dict): buf.write("{") first = True for key, value in value.items(): if not first: buf.write(",") else: first = False stringize(key) buf.write(":") stringize(value) buf.write("}") elif isinstance(value, set): buf.write("{") first = True for item in value: if not first: buf.write(",") else: first = False stringize(item) buf.write("}") else: msg = f"{value!r} cannot be converted into a Python literal" raise ValueError(msg)
buf = StringIO() stringize(value) return buf.getvalue()
def generate_gml(G, stringizer=None): r"""Generate a single entry of the graph `G` in GML format.
Parameters ---------- G : NetworkX graph The graph to be converted to GML.
stringizer : callable, optional A `stringizer` which converts non-int/non-float/non-dict values into strings. If it cannot convert a value into a string, it should raise a `ValueError` to indicate that. Default value: None.
Returns ------- lines: generator of strings Lines of GML data. Newlines are not appended.
Raises ------ NetworkXError If `stringizer` cannot convert a value into a string, or the value to convert is not a string while `stringizer` is None.
See Also -------- literal_stringizer
Notes ----- Graph attributes named 'directed', 'multigraph', 'node' or 'edge', node attributes named 'id' or 'label', edge attributes named 'source' or 'target' (or 'key' if `G` is a multigraph) are ignored because these attribute names are used to encode the graph structure.
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of writing `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For writing other data types, and for reading data other than `str` you need to explicitly supply a `stringizer`/`destringizer`.
For additional documentation on the GML file format, please see the `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
See the module docstring :mod:`networkx.readwrite.gml` for more details.
Examples -------- >>> G = nx.Graph() >>> G.add_node("1") >>> print("\n".join(nx.generate_gml(G))) graph [ node [ id 0 label "1" ] ] >>> G = nx.MultiGraph([("a", "b"), ("a", "b")]) >>> print("\n".join(nx.generate_gml(G))) graph [ multigraph 1 node [ id 0 label "a" ] node [ id 1 label "b" ] edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 1 ] ] """ valid_keys = re.compile("^[A-Za-z][0-9A-Za-z_]*$")
def stringize(key, value, ignored_keys, indent, in_list=False): if not isinstance(key, str): raise NetworkXError(f"{key!r} is not a string") if not valid_keys.match(key): raise NetworkXError(f"{key!r} is not a valid key") if not isinstance(key, str): key = str(key) if key not in ignored_keys: if isinstance(value, int | bool): if key == "label": yield indent + key + ' "' + str(value) + '"' elif value is True: # python bool is an instance of int yield indent + key + " 1" elif value is False: yield indent + key + " 0" # GML only supports signed 32-bit integers elif value < -(2**31) or value >= 2**31: yield indent + key + ' "' + str(value) + '"' else: yield indent + key + " " + str(value) elif isinstance(value, float): text = repr(value).upper() # GML matches INF to keys, so prepend + to INF. Use repr(float(*)) # instead of string literal to future proof against changes to repr. if text == repr(float("inf")).upper(): text = "+" + text else: # GML requires that a real literal contain a decimal point, but # repr may not output a decimal point when the mantissa is # integral and hence needs fixing. epos = text.rfind("E") if epos != -1 and text.find(".", 0, epos) == -1: text = text[:epos] + "." + text[epos:] if key == "label": yield indent + key + ' "' + text + '"' else: yield indent + key + " " + text elif isinstance(value, dict): yield indent + key + " [" next_indent = indent + " " for key, value in value.items(): yield from stringize(key, value, (), next_indent) yield indent + "]" elif isinstance(value, tuple) and key == "label": yield indent + key + f' "({",".join(repr(v) for v in value)})"' elif isinstance(value, list | tuple) and key != "label" and not in_list: if len(value) == 0: yield indent + key + " " + f'"{value!r}"' if len(value) == 1: yield indent + key + " " + f'"{LIST_START_VALUE}"' for val in value: yield from stringize(key, val, (), indent, True) else: if stringizer: try: value = stringizer(value) except ValueError as err: raise NetworkXError( f"{value!r} cannot be converted into a string" ) from err if not isinstance(value, str): raise NetworkXError(f"{value!r} is not a string") yield indent + key + ' "' + escape(value) + '"'
multigraph = G.is_multigraph() yield "graph ["
# Output graph attributes if G.is_directed(): yield " directed 1" if multigraph: yield " multigraph 1" ignored_keys = {"directed", "multigraph", "node", "edge"} for attr, value in G.graph.items(): yield from stringize(attr, value, ignored_keys, " ")
# Output node data node_id = dict(zip(G, range(len(G)))) ignored_keys = {"id", "label"} for node, attrs in G.nodes.items(): yield " node [" yield " id " + str(node_id[node]) yield from stringize("label", node, (), " ") for attr, value in attrs.items(): yield from stringize(attr, value, ignored_keys, " ") yield " ]"
# Output edge data ignored_keys = {"source", "target"} kwargs = {"data": True} if multigraph: ignored_keys.add("key") kwargs["keys"] = True for e in G.edges(**kwargs): yield " edge [" yield " source " + str(node_id[e[0]]) yield " target " + str(node_id[e[1]]) if multigraph: yield from stringize("key", e[2], (), " ") for attr, value in e[-1].items(): yield from stringize(attr, value, ignored_keys, " ") yield " ]" yield "]"
@open_file(1, mode="wb")def write_gml(G, path, stringizer=None): """Write a graph `G` in GML format to the file or file handle `path`.
Parameters ---------- G : NetworkX graph The graph to be converted to GML.
path : string or file Filename or file handle to write to. Filenames ending in .gz or .bz2 will be compressed.
stringizer : callable, optional A `stringizer` which converts non-int/non-float/non-dict values into strings. If it cannot convert a value into a string, it should raise a `ValueError` to indicate that. Default value: None.
Raises ------ NetworkXError If `stringizer` cannot convert a value into a string, or the value to convert is not a string while `stringizer` is None.
See Also -------- read_gml, generate_gml literal_stringizer
Notes ----- Graph attributes named 'directed', 'multigraph', 'node' or 'edge', node attributes named 'id' or 'label', edge attributes named 'source' or 'target' (or 'key' if `G` is a multigraph) are ignored because these attribute names are used to encode the graph structure.
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of writing `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For writing other data types, and for reading data other than `str` you need to explicitly supply a `stringizer`/`destringizer`.
Note that while we allow non-standard GML to be read from a file, we make sure to write GML format. In particular, underscores are not allowed in attribute names. For additional documentation on the GML file format, please see the `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_.
See the module docstring :mod:`networkx.readwrite.gml` for more details.
Examples -------- >>> G = nx.path_graph(5) >>> nx.write_gml(G, "test_path5.gml")
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_gml(G, "test_path5.gml.gz") """ for line in generate_gml(G, stringizer): path.write((line + "\n").encode("ascii"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427# Original author: D. Eppstein, UC Irvine, August 12, 2003.# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain."""Functions for reading and writing graphs in the *graph6* format.
The *graph6* file format is suitable for small graphs or large densegraphs. For large sparse graphs, use the *sparse6* format.
For more information, see the `graph6`_ homepage.
.. _graph6: http://users.cecs.anu.edu.au/~bdm/data/formats.html
"""
from itertools import islice
import networkx as nxfrom networkx.exception import NetworkXErrorfrom networkx.utils import not_implemented_for, open_file
__all__ = ["from_graph6_bytes", "read_graph6", "to_graph6_bytes", "write_graph6"]
def _generate_graph6_bytes(G, nodes, header): """Yield bytes in the graph6 encoding of a graph.
`G` is an undirected simple graph. `nodes` is the list of nodes for which the node-induced subgraph will be encoded; if `nodes` is the list of all nodes in the graph, the entire graph will be encoded. `header` is a Boolean that specifies whether to generate the header ``b'>>graph6<<'`` before the remaining data.
This function generates `bytes` objects in the following order:
1. the header (if requested), 2. the encoding of the number of nodes, 3. each character, one-at-a-time, in the encoding of the requested node-induced subgraph, 4. a newline character.
This function raises :exc:`ValueError` if the graph is too large for the graph6 format (that is, greater than ``2 ** 36`` nodes).
""" n = len(G) if n >= 2**36: raise ValueError( "graph6 is only defined if number of nodes is less than 2 ** 36" ) if header: yield b">>graph6<<" for d in n_to_data(n): yield str.encode(chr(d + 63)) # This generates the same as `(v in G[u] for u, v in combinations(G, 2))`, # but in "column-major" order instead of "row-major" order. bits = (nodes[j] in G[nodes[i]] for j in range(1, n) for i in range(j)) chunk = list(islice(bits, 6)) while chunk: d = sum(b << 5 - i for i, b in enumerate(chunk)) yield str.encode(chr(d + 63)) chunk = list(islice(bits, 6)) yield b"\n"
@nx._dispatchable(graphs=None, returns_graph=True)def from_graph6_bytes(bytes_in): """Read a simple undirected graph in graph6 format from bytes.
Parameters ---------- bytes_in : bytes Data in graph6 format
Returns ------- G : Graph
Raises ------ NetworkXError If `bytes_in` is unable to be parsed in graph6 format
ValueError If any character ``c`` in bytes_in does not satisfy ``63 <= ord(c) < 127``.
Examples -------- >>> G = nx.from_graph6_bytes(b"A_") >>> sorted(G.edges()) [(0, 1)]
Notes ----- Per the graph6 spec, the header (e.g. ``b'>>graph6<<'``) must not be followed by a newline character.
See Also -------- read_graph6, write_graph6
References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
"""
def bits(): """Returns sequence of individual bits from 6-bit-per-value list of data values.""" for d in data: for i in [5, 4, 3, 2, 1, 0]: yield (d >> i) & 1
# Ignore trailing newline bytes_in = bytes_in.rstrip(b"\n")
if bytes_in.startswith(b">>graph6<<"): bytes_in = bytes_in[10:]
data = [c - 63 for c in bytes_in] if any(c > 63 for c in data): raise ValueError("each input character must be in range(63, 127)")
n, data = data_to_n(data) nd = (n * (n - 1) // 2 + 5) // 6 if len(data) != nd: raise NetworkXError( f"Expected {n * (n - 1) // 2} bits but got {len(data) * 6} in graph6" )
G = nx.Graph() G.add_nodes_from(range(n)) for (i, j), b in zip(((i, j) for j in range(1, n) for i in range(j)), bits()): if b: G.add_edge(i, j)
return G
@not_implemented_for("directed")@not_implemented_for("multigraph")def to_graph6_bytes(G, nodes=None, header=True): """Convert a simple undirected graph to bytes in graph6 format.
Parameters ---------- G : Graph (undirected)
nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used.
header: bool If True add '>>graph6<<' bytes to head of data.
Raises ------ NetworkXNotImplemented If the graph is directed or is a multigraph.
ValueError If the graph has at least ``2 ** 36`` nodes; the graph6 format is only defined for graphs of order less than ``2 ** 36``.
Examples -------- >>> nx.to_graph6_bytes(nx.path_graph(2)) b'>>graph6<<A_\\n'
See Also -------- from_graph6_bytes, read_graph6, write_graph6_bytes
Notes ----- The returned bytes end with a newline character.
The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are silently ignored.
References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" if nodes is not None: G = G.subgraph(nodes) H = nx.convert_node_labels_to_integers(G) nodes = sorted(H.nodes()) return b"".join(_generate_graph6_bytes(H, nodes, header))
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_graph6(path): """Read simple undirected graphs in graph6 format from path.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
Returns ------- G : Graph or list of Graphs If the file contains multiple lines then a list of graphs is returned
Raises ------ NetworkXError If the string is unable to be parsed in graph6 format
Examples -------- You can read a graph6 file by giving the path to the file::
>>> import tempfile >>> with tempfile.NamedTemporaryFile(delete=False) as f: ... _ = f.write(b">>graph6<<A_\\n") ... _ = f.seek(0) ... G = nx.read_graph6(f.name) >>> list(G.edges()) [(0, 1)]
You can also read a graph6 file by giving an open file-like object::
>>> import tempfile >>> with tempfile.NamedTemporaryFile() as f: ... _ = f.write(b">>graph6<<A_\\n") ... _ = f.seek(0) ... G = nx.read_graph6(f) >>> list(G.edges()) [(0, 1)]
See Also -------- from_graph6_bytes, write_graph6
References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" glist = [] for line in path: line = line.strip() if not len(line): continue glist.append(from_graph6_bytes(line)) if len(glist) == 1: return glist[0] else: return glist
@not_implemented_for("directed")@not_implemented_for("multigraph")@open_file(1, mode="wb")def write_graph6(G, path, nodes=None, header=True): """Write a simple undirected graph to a path in graph6 format.
Parameters ---------- G : Graph (undirected)
path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed.
nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used.
header: bool If True add '>>graph6<<' string to head of data
Raises ------ NetworkXNotImplemented If the graph is directed or is a multigraph.
ValueError If the graph has at least ``2 ** 36`` nodes; the graph6 format is only defined for graphs of order less than ``2 ** 36``.
Examples -------- You can write a graph6 file by giving the path to a file::
>>> import tempfile >>> with tempfile.NamedTemporaryFile(delete=False) as f: ... nx.write_graph6(nx.path_graph(2), f.name) ... _ = f.seek(0) ... print(f.read()) b'>>graph6<<A_\\n'
See Also -------- from_graph6_bytes, read_graph6
Notes ----- The function writes a newline character after writing the encoding of the graph.
The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are silently ignored.
References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" return write_graph6_file(G, path, nodes=nodes, header=header)
@not_implemented_for("directed")@not_implemented_for("multigraph")def write_graph6_file(G, f, nodes=None, header=True): """Write a simple undirected graph to a file-like object in graph6 format.
Parameters ---------- G : Graph (undirected)
f : file-like object The file to write.
nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used.
header: bool If True add '>>graph6<<' string to head of data
Raises ------ NetworkXNotImplemented If the graph is directed or is a multigraph.
ValueError If the graph has at least ``2 ** 36`` nodes; the graph6 format is only defined for graphs of order less than ``2 ** 36``.
Examples -------- You can write a graph6 file by giving an open file-like object::
>>> import tempfile >>> with tempfile.NamedTemporaryFile() as f: ... nx.write_graph6(nx.path_graph(2), f) ... _ = f.seek(0) ... print(f.read()) b'>>graph6<<A_\\n'
See Also -------- from_graph6_bytes, read_graph6
Notes ----- The function writes a newline character after writing the encoding of the graph.
The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are silently ignored.
References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" if nodes is not None: G = G.subgraph(nodes) H = nx.convert_node_labels_to_integers(G) nodes = sorted(H.nodes()) for b in _generate_graph6_bytes(H, nodes, header): f.write(b)
def data_to_n(data): """Read initial one-, four- or eight-unit value from graph6 integer sequence.
Return (value, rest of seq.)""" if data[0] <= 62: return data[0], data[1:] if data[1] <= 62: return (data[1] << 12) + (data[2] << 6) + data[3], data[4:] return ( (data[2] << 30) + (data[3] << 24) + (data[4] << 18) + (data[5] << 12) + (data[6] << 6) + data[7], data[8:], )
def n_to_data(n): """Convert an integer to one-, four- or eight-unit graph6 sequence.
This function is undefined if `n` is not in ``range(2 ** 36)``.
""" if n <= 62: return [n] elif n <= 258047: return [63, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F] else: # if n <= 68719476735: return [ 63, 63, (n >> 30) & 0x3F, (n >> 24) & 0x3F, (n >> 18) & 0x3F, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F, ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053"""*******GraphML*******Read and write graphs in GraphML format.
.. warning::
This parser uses the standard xml library present in Python, which is insecure - see :external+python:mod:`xml` for additional information. Only parse GraphML files you trust.
This implementation does not support mixed graphs (directed and unidirectededges together), hyperedges, nested graphs, or ports.
"GraphML is a comprehensive and easy-to-use file format for graphs. Itconsists of a language core to describe the structural properties of agraph and a flexible extension mechanism to add application-specificdata. Its main features include support of
* directed, undirected, and mixed graphs, * hypergraphs, * hierarchical graphs, * graphical representations, * references to external data, * application-specific attribute data, and * light-weight parsers.
Unlike many other file formats for graphs, GraphML does not use acustom syntax. Instead, it is based on XML and hence ideally suited asa common denominator for all kinds of services generating, archiving,or processing graphs."
http://graphml.graphdrawing.org/
Format------GraphML is an XML format. Seehttp://graphml.graphdrawing.org/specification.html for the specification andhttp://graphml.graphdrawing.org/primer/graphml-primer.htmlfor examples."""
import warningsfrom collections import defaultdict
import networkx as nxfrom networkx.utils import open_file
__all__ = [ "write_graphml", "read_graphml", "generate_graphml", "write_graphml_xml", "write_graphml_lxml", "parse_graphml", "GraphMLWriter", "GraphMLReader",]
@open_file(1, mode="wb")def write_graphml_xml( G, path, encoding="utf-8", prettyprint=True, infer_numeric_types=False, named_key_ids=False, edge_id_from_attribute=None,): """Write G in GraphML XML format to path
Parameters ---------- G : graph A networkx graph path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. encoding : string (optional) Encoding for text data. prettyprint : bool (optional) If True use line breaks and indenting in output XML. infer_numeric_types : boolean Determine if numeric types should be generalized. For example, if edges have both int and float 'weight' attributes, we infer in GraphML that both are floats. named_key_ids : bool (optional) If True use attr.name as value for key elements' id attribute. edge_id_from_attribute : dict key (optional) If provided, the graphml edge id is set by looking up the corresponding edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data, the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_graphml(G, "test.graphml")
Notes ----- This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges, nested graphs, or ports. """ writer = GraphMLWriter( encoding=encoding, prettyprint=prettyprint, infer_numeric_types=infer_numeric_types, named_key_ids=named_key_ids, edge_id_from_attribute=edge_id_from_attribute, ) writer.add_graph_element(G) writer.dump(path)
@open_file(1, mode="wb")def write_graphml_lxml( G, path, encoding="utf-8", prettyprint=True, infer_numeric_types=False, named_key_ids=False, edge_id_from_attribute=None,): """Write G in GraphML XML format to path
This function uses the LXML framework and should be faster than the version using the xml library.
Parameters ---------- G : graph A networkx graph path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. encoding : string (optional) Encoding for text data. prettyprint : bool (optional) If True use line breaks and indenting in output XML. infer_numeric_types : boolean Determine if numeric types should be generalized. For example, if edges have both int and float 'weight' attributes, we infer in GraphML that both are floats. named_key_ids : bool (optional) If True use attr.name as value for key elements' id attribute. edge_id_from_attribute : dict key (optional) If provided, the graphml edge id is set by looking up the corresponding edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data, the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_graphml_lxml(G, "fourpath.graphml")
Notes ----- This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges, nested graphs, or ports. """ try: import lxml.etree as lxmletree except ImportError: return write_graphml_xml( G, path, encoding, prettyprint, infer_numeric_types, named_key_ids, edge_id_from_attribute, )
writer = GraphMLWriterLxml( path, graph=G, encoding=encoding, prettyprint=prettyprint, infer_numeric_types=infer_numeric_types, named_key_ids=named_key_ids, edge_id_from_attribute=edge_id_from_attribute, ) writer.dump()
def generate_graphml( G, encoding="utf-8", prettyprint=True, named_key_ids=False, edge_id_from_attribute=None,): """Generate GraphML lines for G
Parameters ---------- G : graph A networkx graph encoding : string (optional) Encoding for text data. prettyprint : bool (optional) If True use line breaks and indenting in output XML. named_key_ids : bool (optional) If True use attr.name as value for key elements' id attribute. edge_id_from_attribute : dict key (optional) If provided, the graphml edge id is set by looking up the corresponding edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data, the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
Examples -------- >>> G = nx.path_graph(4) >>> linefeed = chr(10) # linefeed = \n >>> s = linefeed.join(nx.generate_graphml(G)) >>> for line in nx.generate_graphml(G): # doctest: +SKIP ... print(line)
Notes ----- This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges, nested graphs, or ports. """ writer = GraphMLWriter( encoding=encoding, prettyprint=prettyprint, named_key_ids=named_key_ids, edge_id_from_attribute=edge_id_from_attribute, ) writer.add_graph_element(G) yield from str(writer).splitlines()
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_graphml(path, node_type=str, edge_key_type=int, force_multigraph=False): """Read graph in GraphML format from path.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
node_type: Python type (default: str) Convert node ids to this type
edge_key_type: Python type (default: int) Convert graphml edge ids to this type. Multigraphs use id as edge key. Non-multigraphs add to edge attribute dict with name "id".
force_multigraph : bool (default: False) If True, return a multigraph with edge keys. If False (the default) return a multigraph when multiedges are in the graph.
Returns ------- graph: NetworkX graph If parallel edges are present or `force_multigraph=True` then a MultiGraph or MultiDiGraph is returned. Otherwise a Graph/DiGraph. The returned graph is directed if the file indicates it should be.
Notes ----- Default node and edge attributes are not propagated to each node and edge. They can be obtained from `G.graph` and applied to node and edge attributes if desired using something like this:
>>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP >>> for node, data in G.nodes(data=True): # doctest: +SKIP ... if "color" not in data: ... data["color"] = default_color >>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP >>> for u, v, data in G.edges(data=True): # doctest: +SKIP ... if "color" not in data: ... data["color"] = default_color
This implementation does not support mixed graphs (directed and unidirected edges together), hypergraphs, nested graphs, or ports.
For multigraphs the GraphML edge "id" will be used as the edge key. If not specified then they "key" attribute will be used. If there is no "key" attribute a default NetworkX multigraph edge key will be provided.
Files with the yEd "yfiles" extension can be read. The type of the node's shape is preserved in the `shape_type` node attribute.
yEd compressed files ("file.graphmlz" extension) can be read by renaming the file to "file.graphml.gz".
""" reader = GraphMLReader(node_type, edge_key_type, force_multigraph) # need to check for multiple graphs glist = list(reader(path=path)) if len(glist) == 0: # If no graph comes back, try looking for an incomplete header header = b'<graphml xmlns="http://graphml.graphdrawing.org/xmlns">' path.seek(0) old_bytes = path.read() new_bytes = old_bytes.replace(b"<graphml>", header) glist = list(reader(string=new_bytes)) if len(glist) == 0: raise nx.NetworkXError("file not successfully read as graphml") return glist[0]
@nx._dispatchable(graphs=None, returns_graph=True)def parse_graphml( graphml_string, node_type=str, edge_key_type=int, force_multigraph=False): """Read graph in GraphML format from string.
Parameters ---------- graphml_string : string String containing graphml information (e.g., contents of a graphml file).
node_type: Python type (default: str) Convert node ids to this type
edge_key_type: Python type (default: int) Convert graphml edge ids to this type. Multigraphs use id as edge key. Non-multigraphs add to edge attribute dict with name "id".
force_multigraph : bool (default: False) If True, return a multigraph with edge keys. If False (the default) return a multigraph when multiedges are in the graph.
Returns ------- graph: NetworkX graph If no parallel edges are found a Graph or DiGraph is returned. Otherwise a MultiGraph or MultiDiGraph is returned.
Examples -------- >>> G = nx.path_graph(4) >>> linefeed = chr(10) # linefeed = \n >>> s = linefeed.join(nx.generate_graphml(G)) >>> H = nx.parse_graphml(s)
Notes ----- Default node and edge attributes are not propagated to each node and edge. They can be obtained from `G.graph` and applied to node and edge attributes if desired using something like this:
>>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP >>> for node, data in G.nodes(data=True): # doctest: +SKIP ... if "color" not in data: ... data["color"] = default_color >>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP >>> for u, v, data in G.edges(data=True): # doctest: +SKIP ... if "color" not in data: ... data["color"] = default_color
This implementation does not support mixed graphs (directed and unidirected edges together), hypergraphs, nested graphs, or ports.
For multigraphs the GraphML edge "id" will be used as the edge key. If not specified then they "key" attribute will be used. If there is no "key" attribute a default NetworkX multigraph edge key will be provided.
""" reader = GraphMLReader(node_type, edge_key_type, force_multigraph) # need to check for multiple graphs glist = list(reader(string=graphml_string)) if len(glist) == 0: # If no graph comes back, try looking for an incomplete header header = '<graphml xmlns="http://graphml.graphdrawing.org/xmlns">' new_string = graphml_string.replace("<graphml>", header) glist = list(reader(string=new_string)) if len(glist) == 0: raise nx.NetworkXError("file not successfully read as graphml") return glist[0]
class GraphML: NS_GRAPHML = "http://graphml.graphdrawing.org/xmlns" NS_XSI = "http://www.w3.org/2001/XMLSchema-instance" # xmlns:y="http://www.yworks.com/xml/graphml" NS_Y = "http://www.yworks.com/xml/graphml" SCHEMALOCATION = " ".join( [ "http://graphml.graphdrawing.org/xmlns", "http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd", ] )
def construct_types(self): types = [ (int, "integer"), # for Gephi GraphML bug (str, "yfiles"), (str, "string"), (int, "int"), (int, "long"), (float, "float"), (float, "double"), (bool, "boolean"), ]
# These additions to types allow writing numpy types try: import numpy as np except: pass else: # prepend so that python types are created upon read (last entry wins) types = [ (np.float64, "float"), (np.float32, "float"), (np.float16, "float"), (np.int_, "int"), (np.int8, "int"), (np.int16, "int"), (np.int32, "int"), (np.int64, "int"), (np.uint8, "int"), (np.uint16, "int"), (np.uint32, "int"), (np.uint64, "int"), (np.int_, "int"), (np.intc, "int"), (np.intp, "int"), ] + types
self.xml_type = dict(types) self.python_type = dict(reversed(a) for a in types)
# This page says that data types in GraphML follow Java(TM). # http://graphml.graphdrawing.org/primer/graphml-primer.html#AttributesDefinition # true and false are the only boolean literals: # http://en.wikibooks.org/wiki/Java_Programming/Literals#Boolean_Literals convert_bool = { # We use data.lower() in actual use. "true": True, "false": False, # Include integer strings for convenience. "0": False, 0: False, "1": True, 1: True, }
def get_xml_type(self, key): """Wrapper around the xml_type dict that raises a more informative exception message when a user attempts to use data of a type not supported by GraphML.""" try: return self.xml_type[key] except KeyError as err: raise TypeError( f"GraphML does not support type {key} as data values." ) from err
class GraphMLWriter(GraphML): def __init__( self, graph=None, encoding="utf-8", prettyprint=True, infer_numeric_types=False, named_key_ids=False, edge_id_from_attribute=None, ): self.construct_types() from xml.etree.ElementTree import Element
self.myElement = Element
self.infer_numeric_types = infer_numeric_types self.prettyprint = prettyprint self.named_key_ids = named_key_ids self.edge_id_from_attribute = edge_id_from_attribute self.encoding = encoding self.xml = self.myElement( "graphml", { "xmlns": self.NS_GRAPHML, "xmlns:xsi": self.NS_XSI, "xsi:schemaLocation": self.SCHEMALOCATION, }, ) self.keys = {} self.attributes = defaultdict(list) self.attribute_types = defaultdict(set)
if graph is not None: self.add_graph_element(graph)
def __str__(self): from xml.etree.ElementTree import tostring
if self.prettyprint: self.indent(self.xml) s = tostring(self.xml).decode(self.encoding) return s
def attr_type(self, name, scope, value): """Infer the attribute type of data named name. Currently this only supports inference of numeric types.
If self.infer_numeric_types is false, type is used. Otherwise, pick the most general of types found across all values with name and scope. This means edges with data named 'weight' are treated separately from nodes with data named 'weight'. """ if self.infer_numeric_types: types = self.attribute_types[(name, scope)]
if len(types) > 1: types = {self.get_xml_type(t) for t in types} if "string" in types: return str elif "float" in types or "double" in types: return float else: return int else: return list(types)[0] else: return type(value)
def get_key(self, name, attr_type, scope, default): keys_key = (name, attr_type, scope) try: return self.keys[keys_key] except KeyError: if self.named_key_ids: new_id = name else: new_id = f"d{len(list(self.keys))}"
self.keys[keys_key] = new_id key_kwargs = { "id": new_id, "for": scope, "attr.name": name, "attr.type": attr_type, } key_element = self.myElement("key", **key_kwargs) # add subelement for data default value if present if default is not None: default_element = self.myElement("default") default_element.text = str(default) key_element.append(default_element) self.xml.insert(0, key_element) return new_id
def add_data(self, name, element_type, value, scope="all", default=None): """ Make a data element for an edge or a node. Keep a log of the type in the keys table. """ if element_type not in self.xml_type: raise nx.NetworkXError( f"GraphML writer does not support {element_type} as data values." ) keyid = self.get_key(name, self.get_xml_type(element_type), scope, default) data_element = self.myElement("data", key=keyid) data_element.text = str(value) return data_element
def add_attributes(self, scope, xml_obj, data, default): """Appends attribute data to edges or nodes, and stores type information to be added later. See add_graph_element. """ for k, v in data.items(): self.attribute_types[(str(k), scope)].add(type(v)) self.attributes[xml_obj].append([k, v, scope, default.get(k)])
def add_nodes(self, G, graph_element): default = G.graph.get("node_default", {}) for node, data in G.nodes(data=True): node_element = self.myElement("node", id=str(node)) self.add_attributes("node", node_element, data, default) graph_element.append(node_element)
def add_edges(self, G, graph_element): if G.is_multigraph(): for u, v, key, data in G.edges(data=True, keys=True): edge_element = self.myElement( "edge", source=str(u), target=str(v), id=str(data.get(self.edge_id_from_attribute)) if self.edge_id_from_attribute and self.edge_id_from_attribute in data else str(key), ) default = G.graph.get("edge_default", {}) self.add_attributes("edge", edge_element, data, default) graph_element.append(edge_element) else: for u, v, data in G.edges(data=True): if self.edge_id_from_attribute and self.edge_id_from_attribute in data: # select attribute to be edge id edge_element = self.myElement( "edge", source=str(u), target=str(v), id=str(data.get(self.edge_id_from_attribute)), ) else: # default: no edge id edge_element = self.myElement("edge", source=str(u), target=str(v)) default = G.graph.get("edge_default", {}) self.add_attributes("edge", edge_element, data, default) graph_element.append(edge_element)
def add_graph_element(self, G): """ Serialize graph G in GraphML to the stream. """ if G.is_directed(): default_edge_type = "directed" else: default_edge_type = "undirected"
graphid = G.graph.pop("id", None) if graphid is None: graph_element = self.myElement("graph", edgedefault=default_edge_type) else: graph_element = self.myElement( "graph", edgedefault=default_edge_type, id=graphid ) default = {} data = { k: v for (k, v) in G.graph.items() if k not in ["node_default", "edge_default"] } self.add_attributes("graph", graph_element, data, default) self.add_nodes(G, graph_element) self.add_edges(G, graph_element)
# self.attributes contains a mapping from XML Objects to a list of # data that needs to be added to them. # We postpone processing in order to do type inference/generalization. # See self.attr_type for xml_obj, data in self.attributes.items(): for k, v, scope, default in data: xml_obj.append( self.add_data( str(k), self.attr_type(k, scope, v), str(v), scope, default ) ) self.xml.append(graph_element)
def add_graphs(self, graph_list): """Add many graphs to this GraphML document.""" for G in graph_list: self.add_graph_element(G)
def dump(self, stream): from xml.etree.ElementTree import ElementTree
if self.prettyprint: self.indent(self.xml) document = ElementTree(self.xml) document.write(stream, encoding=self.encoding, xml_declaration=True)
def indent(self, elem, level=0): # in-place prettyprint formatter i = "\n" + level * " " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: self.indent(elem, level + 1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i
class IncrementalElement: """Wrapper for _IncrementalWriter providing an Element like interface.
This wrapper does not intend to be a complete implementation but rather to deal with those calls used in GraphMLWriter. """
def __init__(self, xml, prettyprint): self.xml = xml self.prettyprint = prettyprint
def append(self, element): self.xml.write(element, pretty_print=self.prettyprint)
class GraphMLWriterLxml(GraphMLWriter): def __init__( self, path, graph=None, encoding="utf-8", prettyprint=True, infer_numeric_types=False, named_key_ids=False, edge_id_from_attribute=None, ): self.construct_types() import lxml.etree as lxmletree
self.myElement = lxmletree.Element
self._encoding = encoding self._prettyprint = prettyprint self.named_key_ids = named_key_ids self.edge_id_from_attribute = edge_id_from_attribute self.infer_numeric_types = infer_numeric_types
self._xml_base = lxmletree.xmlfile(path, encoding=encoding) self._xml = self._xml_base.__enter__() self._xml.write_declaration()
# We need to have a xml variable that support insertion. This call is # used for adding the keys to the document. # We will store those keys in a plain list, and then after the graph # element is closed we will add them to the main graphml element. self.xml = [] self._keys = self.xml self._graphml = self._xml.element( "graphml", { "xmlns": self.NS_GRAPHML, "xmlns:xsi": self.NS_XSI, "xsi:schemaLocation": self.SCHEMALOCATION, }, ) self._graphml.__enter__() self.keys = {} self.attribute_types = defaultdict(set)
if graph is not None: self.add_graph_element(graph)
def add_graph_element(self, G): """ Serialize graph G in GraphML to the stream. """ if G.is_directed(): default_edge_type = "directed" else: default_edge_type = "undirected"
graphid = G.graph.pop("id", None) if graphid is None: graph_element = self._xml.element("graph", edgedefault=default_edge_type) else: graph_element = self._xml.element( "graph", edgedefault=default_edge_type, id=graphid )
# gather attributes types for the whole graph # to find the most general numeric format needed. # Then pass through attributes to create key_id for each. graphdata = { k: v for k, v in G.graph.items() if k not in ("node_default", "edge_default") } node_default = G.graph.get("node_default", {}) edge_default = G.graph.get("edge_default", {}) # Graph attributes for k, v in graphdata.items(): self.attribute_types[(str(k), "graph")].add(type(v)) for k, v in graphdata.items(): element_type = self.get_xml_type(self.attr_type(k, "graph", v)) self.get_key(str(k), element_type, "graph", None) # Nodes and data for node, d in G.nodes(data=True): for k, v in d.items(): self.attribute_types[(str(k), "node")].add(type(v)) for node, d in G.nodes(data=True): for k, v in d.items(): T = self.get_xml_type(self.attr_type(k, "node", v)) self.get_key(str(k), T, "node", node_default.get(k)) # Edges and data if G.is_multigraph(): for u, v, ekey, d in G.edges(keys=True, data=True): for k, v in d.items(): self.attribute_types[(str(k), "edge")].add(type(v)) for u, v, ekey, d in G.edges(keys=True, data=True): for k, v in d.items(): T = self.get_xml_type(self.attr_type(k, "edge", v)) self.get_key(str(k), T, "edge", edge_default.get(k)) else: for u, v, d in G.edges(data=True): for k, v in d.items(): self.attribute_types[(str(k), "edge")].add(type(v)) for u, v, d in G.edges(data=True): for k, v in d.items(): T = self.get_xml_type(self.attr_type(k, "edge", v)) self.get_key(str(k), T, "edge", edge_default.get(k))
# Now add attribute keys to the xml file for key in self.xml: self._xml.write(key, pretty_print=self._prettyprint)
# The incremental_writer writes each node/edge as it is created incremental_writer = IncrementalElement(self._xml, self._prettyprint) with graph_element: self.add_attributes("graph", incremental_writer, graphdata, {}) self.add_nodes(G, incremental_writer) # adds attributes too self.add_edges(G, incremental_writer) # adds attributes too
def add_attributes(self, scope, xml_obj, data, default): """Appends attribute data.""" for k, v in data.items(): data_element = self.add_data( str(k), self.attr_type(str(k), scope, v), str(v), scope, default.get(k) ) xml_obj.append(data_element)
def __str__(self): return object.__str__(self)
def dump(self, stream=None): self._graphml.__exit__(None, None, None) self._xml_base.__exit__(None, None, None)
# default is lxml is present.write_graphml = write_graphml_lxml
class GraphMLReader(GraphML): """Read a GraphML document. Produces NetworkX graph objects."""
def __init__(self, node_type=str, edge_key_type=int, force_multigraph=False): self.construct_types() self.node_type = node_type self.edge_key_type = edge_key_type self.multigraph = force_multigraph # If False, test for multiedges self.edge_ids = {} # dict mapping (u,v) tuples to edge id attributes
def __call__(self, path=None, string=None): from xml.etree.ElementTree import ElementTree, fromstring
if path is not None: self.xml = ElementTree(file=path) elif string is not None: self.xml = fromstring(string) else: raise ValueError("Must specify either 'path' or 'string' as kwarg") (keys, defaults) = self.find_graphml_keys(self.xml) for g in self.xml.findall(f"{{{self.NS_GRAPHML}}}graph"): yield self.make_graph(g, keys, defaults)
def make_graph(self, graph_xml, graphml_keys, defaults, G=None): # set default graph type edgedefault = graph_xml.get("edgedefault", None) if G is None: if edgedefault == "directed": G = nx.MultiDiGraph() else: G = nx.MultiGraph() # set defaults for graph attributes G.graph["node_default"] = {} G.graph["edge_default"] = {} for key_id, value in defaults.items(): key_for = graphml_keys[key_id]["for"] name = graphml_keys[key_id]["name"] python_type = graphml_keys[key_id]["type"] if key_for == "node": G.graph["node_default"].update({name: python_type(value)}) if key_for == "edge": G.graph["edge_default"].update({name: python_type(value)}) # hyperedges are not supported hyperedge = graph_xml.find(f"{{{self.NS_GRAPHML}}}hyperedge") if hyperedge is not None: raise nx.NetworkXError("GraphML reader doesn't support hyperedges") # add nodes for node_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}node"): self.add_node(G, node_xml, graphml_keys, defaults) # add edges for edge_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}edge"): self.add_edge(G, edge_xml, graphml_keys) # add graph data data = self.decode_data_elements(graphml_keys, graph_xml) G.graph.update(data)
# switch to Graph or DiGraph if no parallel edges were found if self.multigraph: return G
G = nx.DiGraph(G) if G.is_directed() else nx.Graph(G) # add explicit edge "id" from file as attribute in NX graph. nx.set_edge_attributes(G, values=self.edge_ids, name="id") return G
def add_node(self, G, node_xml, graphml_keys, defaults): """Add a node to the graph.""" # warn on finding unsupported ports tag ports = node_xml.find(f"{{{self.NS_GRAPHML}}}port") if ports is not None: warnings.warn("GraphML port tag not supported.") # find the node by id and cast it to the appropriate type node_id = self.node_type(node_xml.get("id")) # get data/attributes for node data = self.decode_data_elements(graphml_keys, node_xml) G.add_node(node_id, **data) # get child nodes if node_xml.attrib.get("yfiles.foldertype") == "group": graph_xml = node_xml.find(f"{{{self.NS_GRAPHML}}}graph") self.make_graph(graph_xml, graphml_keys, defaults, G)
def add_edge(self, G, edge_element, graphml_keys): """Add an edge to the graph.""" # warn on finding unsupported ports tag ports = edge_element.find(f"{{{self.NS_GRAPHML}}}port") if ports is not None: warnings.warn("GraphML port tag not supported.")
# raise error if we find mixed directed and undirected edges directed = edge_element.get("directed") if G.is_directed() and directed == "false": msg = "directed=false edge found in directed graph." raise nx.NetworkXError(msg) if (not G.is_directed()) and directed == "true": msg = "directed=true edge found in undirected graph." raise nx.NetworkXError(msg)
source = self.node_type(edge_element.get("source")) target = self.node_type(edge_element.get("target")) data = self.decode_data_elements(graphml_keys, edge_element) # GraphML stores edge ids as an attribute # NetworkX uses them as keys in multigraphs too if no key # attribute is specified edge_id = edge_element.get("id") if edge_id: # self.edge_ids is used by `make_graph` method for non-multigraphs self.edge_ids[source, target] = edge_id try: edge_id = self.edge_key_type(edge_id) except ValueError: # Could not convert. pass else: edge_id = data.get("key")
if G.has_edge(source, target): # mark this as a multigraph self.multigraph = True
# Use add_edges_from to avoid error with add_edge when `'key' in data` # Note there is only one edge here... G.add_edges_from([(source, target, edge_id, data)])
def decode_data_elements(self, graphml_keys, obj_xml): """Use the key information to decode the data XML if present.""" data = {} for data_element in obj_xml.findall(f"{{{self.NS_GRAPHML}}}data"): key = data_element.get("key") try: data_name = graphml_keys[key]["name"] data_type = graphml_keys[key]["type"] except KeyError as err: raise nx.NetworkXError(f"Bad GraphML data: no key {key}") from err text = data_element.text # assume anything with subelements is a yfiles extension if text is not None and len(list(data_element)) == 0: if data_type is bool: # Ignore cases. # http://docs.oracle.com/javase/6/docs/api/java/lang/ # Boolean.html#parseBoolean%28java.lang.String%29 data[data_name] = self.convert_bool[text.lower()] else: data[data_name] = data_type(text) elif len(list(data_element)) > 0: # Assume yfiles as subelements, try to extract node_label node_label = None # set GenericNode's configuration as shape type gn = data_element.find(f"{{{self.NS_Y}}}GenericNode") if gn is not None: data["shape_type"] = gn.get("configuration") for node_type in ["GenericNode", "ShapeNode", "SVGNode", "ImageNode"]: pref = f"{{{self.NS_Y}}}{node_type}/{{{self.NS_Y}}}" geometry = data_element.find(f"{pref}Geometry") if geometry is not None: data["x"] = geometry.get("x") data["y"] = geometry.get("y") if node_label is None: node_label = data_element.find(f"{pref}NodeLabel") shape = data_element.find(f"{pref}Shape") if shape is not None: data["shape_type"] = shape.get("type") if node_label is not None: data["label"] = node_label.text
# check all the different types of edges available in yEd. for edge_type in [ "PolyLineEdge", "SplineEdge", "QuadCurveEdge", "BezierEdge", "ArcEdge", ]: pref = f"{{{self.NS_Y}}}{edge_type}/{{{self.NS_Y}}}" edge_label = data_element.find(f"{pref}EdgeLabel") if edge_label is not None: break if edge_label is not None: data["label"] = edge_label.text elif text is None: data[data_name] = "" return data
def find_graphml_keys(self, graph_element): """Extracts all the keys and key defaults from the xml.""" graphml_keys = {} graphml_key_defaults = {} for k in graph_element.findall(f"{{{self.NS_GRAPHML}}}key"): attr_id = k.get("id") attr_type = k.get("attr.type") attr_name = k.get("attr.name") yfiles_type = k.get("yfiles.type") if yfiles_type is not None: attr_name = yfiles_type attr_type = "yfiles" if attr_type is None: attr_type = "string" warnings.warn(f"No key type for id {attr_id}. Using string") if attr_name is None: raise nx.NetworkXError(f"Unknown key for id {attr_id}.") graphml_keys[attr_id] = { "name": attr_name, "type": self.python_type[attr_type], "for": k.get("for"), } # check for "default" sub-element of key element default = k.find(f"{{{self.NS_GRAPHML}}}default") if default is not None: # Handle default values identically to data element values python_type = graphml_keys[attr_id]["type"] if python_type is bool: graphml_key_defaults[attr_id] = self.convert_bool[ default.text.lower() ] else: graphml_key_defaults[attr_id] = python_type(default.text) return graphml_keys, graphml_key_defaults12345678910111213141516171819"""*********JSON data*********Generate and parse JSON serializable data for NetworkX graphs.
These formats are suitable for use with the d3.js examples https://d3js.org/
The three formats that you can generate with NetworkX are:
- node-link like in the d3.js example https://bl.ocks.org/mbostock/4062045 - tree like in the d3.js example https://bl.ocks.org/mbostock/4063550 - adjacency like in the d3.js example https://bost.ocks.org/mike/miserables/"""
from networkx.readwrite.json_graph.node_link import *from networkx.readwrite.json_graph.adjacency import *from networkx.readwrite.json_graph.tree import *from networkx.readwrite.json_graph.cytoscape import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import networkx as nx
__all__ = ["adjacency_data", "adjacency_graph"]
_attrs = {"id": "id", "key": "key"}
def adjacency_data(G, attrs=_attrs): """Returns data in adjacency format that is suitable for JSON serialization and use in JavaScript documents.
Parameters ---------- G : NetworkX graph
attrs : dict A dictionary that contains two keys 'id' and 'key'. The corresponding values provide the attribute names for storing NetworkX-internal graph data. The values should be unique. Default value: :samp:`dict(id='id', key='key')`.
If some user-defined graph data use these attribute names as data keys, they may be silently dropped.
Returns ------- data : dict A dictionary with adjacency formatted data.
Raises ------ NetworkXError If values in attrs are not unique.
Examples -------- >>> from networkx.readwrite import json_graph >>> G = nx.Graph([(1, 2)]) >>> data = json_graph.adjacency_data(G)
To serialize with json
>>> import json >>> s = json.dumps(data)
Notes ----- Graph, node, and link attributes will be written when using this format but attribute keys must be strings if you want to serialize the resulting data with JSON.
The default value of attrs will be changed in a future release of NetworkX.
See Also -------- adjacency_graph, node_link_data, tree_data """ multigraph = G.is_multigraph() id_ = attrs["id"] # Allow 'key' to be omitted from attrs if the graph is not a multigraph. key = None if not multigraph else attrs["key"] if id_ == key: raise nx.NetworkXError("Attribute names are not unique.") data = {} data["directed"] = G.is_directed() data["multigraph"] = multigraph data["graph"] = list(G.graph.items()) data["nodes"] = [] data["adjacency"] = [] for n, nbrdict in G.adjacency(): data["nodes"].append({**G.nodes[n], id_: n}) adj = [] if multigraph: for nbr, keys in nbrdict.items(): for k, d in keys.items(): adj.append({**d, id_: nbr, key: k}) else: for nbr, d in nbrdict.items(): adj.append({**d, id_: nbr}) data["adjacency"].append(adj) return data
@nx._dispatchable(graphs=None, returns_graph=True)def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs): """Returns graph from adjacency data format.
Parameters ---------- data : dict Adjacency list formatted graph data
directed : bool If True, and direction not specified in data, return a directed graph.
multigraph : bool If True, and multigraph not specified in data, return a multigraph.
attrs : dict A dictionary that contains two keys 'id' and 'key'. The corresponding values provide the attribute names for storing NetworkX-internal graph data. The values should be unique. Default value: :samp:`dict(id='id', key='key')`.
Returns ------- G : NetworkX graph A NetworkX graph object
Examples -------- >>> from networkx.readwrite import json_graph >>> G = nx.Graph([(1, 2)]) >>> data = json_graph.adjacency_data(G) >>> H = json_graph.adjacency_graph(data)
Notes ----- The default value of attrs will be changed in a future release of NetworkX.
See Also -------- adjacency_graph, node_link_data, tree_data """ multigraph = data.get("multigraph", multigraph) directed = data.get("directed", directed) if multigraph: graph = nx.MultiGraph() else: graph = nx.Graph() if directed: graph = graph.to_directed() id_ = attrs["id"] # Allow 'key' to be omitted from attrs if the graph is not a multigraph. key = None if not multigraph else attrs["key"] graph.graph = dict(data.get("graph", [])) mapping = [] for d in data["nodes"]: node_data = d.copy() node = node_data.pop(id_) mapping.append(node) graph.add_node(node) graph.nodes[node].update(node_data) for i, d in enumerate(data["adjacency"]): source = mapping[i] for tdata in d: target_data = tdata.copy() target = target_data.pop(id_) if not multigraph: graph.add_edge(source, target) graph[source][target].update(target_data) else: ky = target_data.pop(key, None) graph.add_edge(source, target, key=ky) graph[source][target][ky].update(target_data) return graph123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190import networkx as nx
__all__ = ["cytoscape_data", "cytoscape_graph"]
def cytoscape_data(G, name="name", ident="id"): """Returns data in Cytoscape JSON format (cyjs).
Parameters ---------- G : NetworkX Graph The graph to convert to cytoscape format name : string A string which is mapped to the 'name' node element in cyjs format. Must not have the same value as `ident`. ident : string A string which is mapped to the 'id' node element in cyjs format. Must not have the same value as `name`.
Returns ------- data: dict A dictionary with cyjs formatted data.
Raises ------ NetworkXError If the values for `name` and `ident` are identical.
See Also -------- cytoscape_graph: convert a dictionary in cyjs format to a graph
References ---------- .. [1] Cytoscape user's manual: http://manual.cytoscape.org/en/stable/index.html
Examples -------- >>> from pprint import pprint >>> G = nx.path_graph(2) >>> cyto_data = nx.cytoscape_data(G) >>> pprint(cyto_data, sort_dicts=False) {'data': [], 'directed': False, 'multigraph': False, 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}}, {'data': {'id': '1', 'value': 1, 'name': '1'}}], 'edges': [{'data': {'source': 0, 'target': 1}}]}}
The :mod:`json` package can be used to serialize the resulting data
>>> import io, json >>> with io.StringIO() as fh: # replace io with `open(...)` to write to disk ... json.dump(cyto_data, fh) ... fh.seek(0) # doctest: +SKIP ... print(fh.getvalue()[:64]) # View the first 64 characters {"data": [], "directed": false, "multigraph": false, "elements":
""" if name == ident: raise nx.NetworkXError("name and ident must be different.")
jsondata = {"data": list(G.graph.items())} jsondata["directed"] = G.is_directed() jsondata["multigraph"] = G.is_multigraph() jsondata["elements"] = {"nodes": [], "edges": []} nodes = jsondata["elements"]["nodes"] edges = jsondata["elements"]["edges"]
for i, j in G.nodes.items(): n = {"data": j.copy()} n["data"]["id"] = j.get(ident) or str(i) n["data"]["value"] = i n["data"]["name"] = j.get(name) or str(i) nodes.append(n)
if G.is_multigraph(): for e in G.edges(keys=True): n = {"data": G.adj[e[0]][e[1]][e[2]].copy()} n["data"]["source"] = e[0] n["data"]["target"] = e[1] n["data"]["key"] = e[2] edges.append(n) else: for e in G.edges(): n = {"data": G.adj[e[0]][e[1]].copy()} n["data"]["source"] = e[0] n["data"]["target"] = e[1] edges.append(n) return jsondata
@nx._dispatchable(graphs=None, returns_graph=True)def cytoscape_graph(data, name="name", ident="id"): """ Create a NetworkX graph from a dictionary in cytoscape JSON format.
Parameters ---------- data : dict A dictionary of data conforming to cytoscape JSON format. name : string A string which is mapped to the 'name' node element in cyjs format. Must not have the same value as `ident`. ident : string A string which is mapped to the 'id' node element in cyjs format. Must not have the same value as `name`.
Returns ------- graph : a NetworkX graph instance The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or `MultiDiGraph` depending on the input data.
Raises ------ NetworkXError If the `name` and `ident` attributes are identical.
See Also -------- cytoscape_data: convert a NetworkX graph to a dict in cyjs format
References ---------- .. [1] Cytoscape user's manual: http://manual.cytoscape.org/en/stable/index.html
Examples -------- >>> data_dict = { ... "data": [], ... "directed": False, ... "multigraph": False, ... "elements": { ... "nodes": [ ... {"data": {"id": "0", "value": 0, "name": "0"}}, ... {"data": {"id": "1", "value": 1, "name": "1"}}, ... ], ... "edges": [{"data": {"source": 0, "target": 1}}], ... }, ... } >>> G = nx.cytoscape_graph(data_dict) >>> G.name '' >>> G.nodes() NodeView((0, 1)) >>> G.nodes(data=True)[0] {'id': '0', 'value': 0, 'name': '0'} >>> G.edges(data=True) EdgeDataView([(0, 1, {'source': 0, 'target': 1})]) """ if name == ident: raise nx.NetworkXError("name and ident must be different.")
multigraph = data.get("multigraph") directed = data.get("directed") if multigraph: graph = nx.MultiGraph() else: graph = nx.Graph() if directed: graph = graph.to_directed() graph.graph = dict(data.get("data")) for d in data["elements"]["nodes"]: node_data = d["data"].copy() node = d["data"]["value"]
if d["data"].get(name): node_data[name] = d["data"].get(name) if d["data"].get(ident): node_data[ident] = d["data"].get(ident)
graph.add_node(node) graph.nodes[node].update(node_data)
for d in data["elements"]["edges"]: edge_data = d["data"].copy() sour = d["data"]["source"] targ = d["data"]["target"] if multigraph: key = d["data"].get("key", 0) graph.add_edge(sour, targ, key=key) graph.edges[sour, targ, key].update(edge_data) else: graph.add_edge(sour, targ) graph.edges[sour, targ].update(edge_data) return graph123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261import warningsfrom itertools import count
import networkx as nx
__all__ = ["node_link_data", "node_link_graph"]
def _to_tuple(x): """Converts lists to tuples, including nested lists.
All other non-list inputs are passed through unmodified. This function is intended to be used to convert potentially nested lists from json files into valid nodes.
Examples -------- >>> _to_tuple([1, 2, [3, 4]]) (1, 2, (3, 4)) """ if not isinstance(x, tuple | list): return x return tuple(map(_to_tuple, x))
def node_link_data( G, *, source="source", target="target", name="id", key="key", edges="edges", nodes="nodes",): """Returns data in node-link format that is suitable for JSON serialization and use in JavaScript documents.
Parameters ---------- G : NetworkX graph source : string A string that provides the 'source' attribute name for storing NetworkX-internal graph data. target : string A string that provides the 'target' attribute name for storing NetworkX-internal graph data. name : string A string that provides the 'name' attribute name for storing NetworkX-internal graph data. key : string A string that provides the 'key' attribute name for storing NetworkX-internal graph data. edges : string A string that provides the 'edges' attribute name for storing NetworkX-internal graph data. nodes : string A string that provides the 'nodes' attribute name for storing NetworkX-internal graph data.
Returns ------- data : dict A dictionary with node-link formatted data.
Raises ------ NetworkXError If the values of 'source', 'target' and 'key' are not unique.
Examples -------- >>> from pprint import pprint >>> G = nx.Graph([("A", "B")]) >>> data1 = nx.node_link_data(G) >>> pprint(data1) {'directed': False, 'edges': [{'source': 'A', 'target': 'B'}], 'graph': {}, 'multigraph': False, 'nodes': [{'id': 'A'}, {'id': 'B'}]}
To serialize with JSON
>>> import json >>> s1 = json.dumps(data1) >>> pprint(s1) ('{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, ' '{"id": "B"}], "edges": [{"source": "A", "target": "B"}]}')
A graph can also be serialized by passing `node_link_data` as an encoder function.
>>> s1 = json.dumps(G, default=nx.node_link_data) >>> pprint(s1) ('{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, ' '{"id": "B"}], "edges": [{"source": "A", "target": "B"}]}')
The attribute names for storing NetworkX-internal graph data can be specified as keyword options.
>>> H = nx.gn_graph(2) >>> data2 = nx.node_link_data( ... H, edges="links", source="from", target="to", nodes="vertices" ... ) >>> pprint(data2) {'directed': True, 'graph': {}, 'links': [{'from': 1, 'to': 0}], 'multigraph': False, 'vertices': [{'id': 0}, {'id': 1}]}
Notes ----- Graph, node, and edge attributes are stored in this format. Note that attribute keys will be converted to strings in order to comply with JSON.
Attribute 'key' is only used for multigraphs.
To use `node_link_data` in conjunction with `node_link_graph`, the keyword names for the attributes must match.
See Also -------- node_link_graph, adjacency_data, tree_data """ multigraph = G.is_multigraph()
# Allow 'key' to be omitted from attrs if the graph is not a multigraph. key = None if not multigraph else key if len({source, target, key}) < 3: raise nx.NetworkXError("Attribute names are not unique.") data = { "directed": G.is_directed(), "multigraph": multigraph, "graph": G.graph, nodes: [{**G.nodes[n], name: n} for n in G], } if multigraph: data[edges] = [ {**d, source: u, target: v, key: k} for u, v, k, d in G.edges(keys=True, data=True) ] else: data[edges] = [{**d, source: u, target: v} for u, v, d in G.edges(data=True)] return data
@nx._dispatchable(graphs=None, returns_graph=True)def node_link_graph( data, directed=False, multigraph=True, *, source="source", target="target", name="id", key="key", edges="edges", nodes="nodes",): """Returns graph from node-link data format.
Useful for de-serialization from JSON.
Parameters ---------- data : dict node-link formatted graph data
directed : bool If True, and direction not specified in data, return a directed graph.
multigraph : bool If True, and multigraph not specified in data, return a multigraph.
source : string A string that provides the 'source' attribute name for storing NetworkX-internal graph data. target : string A string that provides the 'target' attribute name for storing NetworkX-internal graph data. name : string A string that provides the 'name' attribute name for storing NetworkX-internal graph data. key : string A string that provides the 'key' attribute name for storing NetworkX-internal graph data. edges : string A string that provides the 'edges' attribute name for storing NetworkX-internal graph data. nodes : string A string that provides the 'nodes' attribute name for storing NetworkX-internal graph data.
Returns ------- G : NetworkX graph A NetworkX graph object
Examples --------
Create data in node-link format by converting a graph.
>>> from pprint import pprint >>> G = nx.Graph([("A", "B")]) >>> data = nx.node_link_data(G) >>> pprint(data) {'directed': False, 'edges': [{'source': 'A', 'target': 'B'}], 'graph': {}, 'multigraph': False, 'nodes': [{'id': 'A'}, {'id': 'B'}]}
Revert data in node-link format to a graph.
>>> H = nx.node_link_graph(data) >>> print(H.edges) [('A', 'B')]
To serialize and deserialize a graph with JSON,
>>> import json >>> d = json.dumps(nx.node_link_data(G)) >>> H = nx.node_link_graph(json.loads(d)) >>> print(G.edges, H.edges) [('A', 'B')] [('A', 'B')]
Notes ----- Attribute 'key' is only used for multigraphs.
To use `node_link_data` in conjunction with `node_link_graph`, the keyword names for the attributes must match.
See Also -------- node_link_data, adjacency_data, tree_data """ multigraph = data.get("multigraph", multigraph) directed = data.get("directed", directed) if multigraph: graph = nx.MultiGraph() else: graph = nx.Graph() if directed: graph = graph.to_directed()
# Allow 'key' to be omitted from attrs if the graph is not a multigraph. key = None if not multigraph else key graph.graph = data.get("graph", {}) c = count() for d in data[nodes]: node = _to_tuple(d.get(name, next(c))) nodedata = {str(k): v for k, v in d.items() if k != name} graph.add_node(node, **nodedata) for d in data[edges]: src = tuple(d[source]) if isinstance(d[source], list) else d[source] tgt = tuple(d[target]) if isinstance(d[target], list) else d[target] if not multigraph: edgedata = {str(k): v for k, v in d.items() if k != source and k != target} graph.add_edge(src, tgt, **edgedata) else: ky = d.get(key, None) edgedata = { str(k): v for k, v in d.items() if k != source and k != target and k != key } graph.add_edge(src, tgt, ky, **edgedata) return graph123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import copyimport json
import pytest
import networkx as nxfrom networkx.readwrite.json_graph import adjacency_data, adjacency_graphfrom networkx.utils import graphs_equal
class TestAdjacency: def test_graph(self): G = nx.path_graph(4) H = adjacency_graph(adjacency_data(G)) assert graphs_equal(G, H)
def test_graph_attributes(self): G = nx.path_graph(4) G.add_node(1, color="red") G.add_edge(1, 2, width=7) G.graph["foo"] = "bar" G.graph[1] = "one"
H = adjacency_graph(adjacency_data(G)) assert graphs_equal(G, H) assert H.graph["foo"] == "bar" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7
d = json.dumps(adjacency_data(G)) H = adjacency_graph(json.loads(d)) assert graphs_equal(G, H) assert H.graph["foo"] == "bar" assert H.graph[1] == "one" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7
def test_digraph(self): G = nx.DiGraph() nx.add_path(G, [1, 2, 3]) H = adjacency_graph(adjacency_data(G)) assert H.is_directed() assert graphs_equal(G, H)
def test_multidigraph(self): G = nx.MultiDiGraph() nx.add_path(G, [1, 2, 3]) H = adjacency_graph(adjacency_data(G)) assert H.is_directed() assert H.is_multigraph() assert graphs_equal(G, H)
def test_multigraph(self): G = nx.MultiGraph() G.add_edge(1, 2, key="first") G.add_edge(1, 2, key="second", color="blue") H = adjacency_graph(adjacency_data(G)) assert graphs_equal(G, H) assert H[1][2]["second"]["color"] == "blue"
def test_input_data_is_not_modified_when_building_graph(self): G = nx.path_graph(4) input_data = adjacency_data(G) orig_data = copy.deepcopy(input_data) # Ensure input is unmodified by deserialisation assert graphs_equal(G, adjacency_graph(input_data)) assert input_data == orig_data
def test_adjacency_form_json_serialisable(self): G = nx.path_graph(4) H = adjacency_graph(json.loads(json.dumps(adjacency_data(G)))) assert graphs_equal(G, H)
def test_exception(self): with pytest.raises(nx.NetworkXError): G = nx.MultiDiGraph() attrs = {"id": "node", "key": "node"} adjacency_data(G, attrs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import copyimport json
import pytest
import networkx as nxfrom networkx.readwrite.json_graph import cytoscape_data, cytoscape_graph
def test_graph(): G = nx.path_graph(4) H = cytoscape_graph(cytoscape_data(G)) assert nx.is_isomorphic(G, H)
def test_input_data_is_not_modified_when_building_graph(): G = nx.path_graph(4) input_data = cytoscape_data(G) orig_data = copy.deepcopy(input_data) # Ensure input is unmodified by cytoscape_graph (gh-4173) cytoscape_graph(input_data) assert input_data == orig_data
def test_graph_attributes(): G = nx.path_graph(4) G.add_node(1, color="red") G.add_edge(1, 2, width=7) G.graph["foo"] = "bar" G.graph[1] = "one" G.add_node(3, name="node", id="123")
H = cytoscape_graph(cytoscape_data(G)) assert H.graph["foo"] == "bar" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7 assert H.nodes[3]["name"] == "node" assert H.nodes[3]["id"] == "123"
d = json.dumps(cytoscape_data(G)) H = cytoscape_graph(json.loads(d)) assert H.graph["foo"] == "bar" assert H.graph[1] == "one" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7 assert H.nodes[3]["name"] == "node" assert H.nodes[3]["id"] == "123"
def test_digraph(): G = nx.DiGraph() nx.add_path(G, [1, 2, 3]) H = cytoscape_graph(cytoscape_data(G)) assert H.is_directed() assert nx.is_isomorphic(G, H)
def test_multidigraph(): G = nx.MultiDiGraph() nx.add_path(G, [1, 2, 3]) H = cytoscape_graph(cytoscape_data(G)) assert H.is_directed() assert H.is_multigraph()
def test_multigraph(): G = nx.MultiGraph() G.add_edge(1, 2, key="first") G.add_edge(1, 2, key="second", color="blue") H = cytoscape_graph(cytoscape_data(G)) assert nx.is_isomorphic(G, H) assert H[1][2]["second"]["color"] == "blue"
def test_exception(): with pytest.raises(nx.NetworkXError): G = nx.MultiDiGraph() cytoscape_data(G, name="foo", ident="foo")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import json
import pytest
import networkx as nxfrom networkx.readwrite.json_graph import node_link_data, node_link_graph
class TestNodeLink: def test_exception_dep(self): G = nx.MultiDiGraph() with pytest.raises(nx.NetworkXError): node_link_data(G, name="node", source="node", target="node", key="node")
def test_graph(self): G = nx.path_graph(4) H = node_link_graph(node_link_data(G)) assert nx.is_isomorphic(G, H)
def test_graph_attributes(self): G = nx.path_graph(4) G.add_node(1, color="red") G.add_edge(1, 2, width=7) G.graph[1] = "one" G.graph["foo"] = "bar"
H = node_link_graph(node_link_data(G)) assert H.graph["foo"] == "bar" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7
d = json.dumps(node_link_data(G)) H = node_link_graph(json.loads(d)) assert H.graph["foo"] == "bar" assert H.graph["1"] == "one" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7
def test_digraph(self): G = nx.DiGraph() H = node_link_graph(node_link_data(G)) assert H.is_directed()
def test_multigraph(self): G = nx.MultiGraph() G.add_edge(1, 2, key="first") G.add_edge(1, 2, key="second", color="blue") H = node_link_graph(node_link_data(G)) assert nx.is_isomorphic(G, H) assert H[1][2]["second"]["color"] == "blue"
def test_graph_with_tuple_nodes(self): G = nx.Graph() G.add_edge((0, 0), (1, 0), color=[255, 255, 0]) d = node_link_data(G) dumped_d = json.dumps(d) dd = json.loads(dumped_d) H = node_link_graph(dd) assert H.nodes[(0, 0)] == G.nodes[(0, 0)] assert H[(0, 0)][(1, 0)]["color"] == [255, 255, 0]
def test_unicode_keys(self): q = "qualité" G = nx.Graph() G.add_node(1, **{q: q}) s = node_link_data(G) output = json.dumps(s, ensure_ascii=False) data = json.loads(output) H = node_link_graph(data) assert H.nodes[1][q] == q
def test_exception(self): G = nx.MultiDiGraph() attrs = {"name": "node", "source": "node", "target": "node", "key": "node"} with pytest.raises(nx.NetworkXError): node_link_data(G, **attrs)
def test_string_ids(self): q = "qualité" G = nx.DiGraph() G.add_node("A") G.add_node(q) G.add_edge("A", q) data = node_link_data(G) assert data["edges"][0]["source"] == "A" assert data["edges"][0]["target"] == q H = node_link_graph(data) assert nx.is_isomorphic(G, H)
def test_custom_attrs(self): G = nx.path_graph(4) G.add_node(1, color="red") G.add_edge(1, 2, width=7) G.graph[1] = "one" G.graph["foo"] = "bar"
attrs = { "source": "c_source", "target": "c_target", "name": "c_id", "key": "c_key", "edges": "c_links", }
H = node_link_graph(node_link_data(G, **attrs), multigraph=False, **attrs) assert nx.is_isomorphic(G, H) assert H.graph["foo"] == "bar" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import json
import pytest
import networkx as nxfrom networkx.readwrite.json_graph import tree_data, tree_graph
def test_graph(): G = nx.DiGraph() G.add_nodes_from([1, 2, 3], color="red") G.add_edge(1, 2, foo=7) G.add_edge(1, 3, foo=10) G.add_edge(3, 4, foo=10) H = tree_graph(tree_data(G, 1)) assert nx.is_isomorphic(G, H)
def test_graph_attributes(): G = nx.DiGraph() G.add_nodes_from([1, 2, 3], color="red") G.add_edge(1, 2, foo=7) G.add_edge(1, 3, foo=10) G.add_edge(3, 4, foo=10) H = tree_graph(tree_data(G, 1)) assert H.nodes[1]["color"] == "red"
d = json.dumps(tree_data(G, 1)) H = tree_graph(json.loads(d)) assert H.nodes[1]["color"] == "red"
def test_exceptions(): with pytest.raises(TypeError, match="is not a tree."): G = nx.complete_graph(3) tree_data(G, 0) with pytest.raises(TypeError, match="is not directed."): G = nx.path_graph(3) tree_data(G, 0) with pytest.raises(TypeError, match="is not weakly connected."): G = nx.path_graph(3, create_using=nx.DiGraph) G.add_edge(2, 0) G.add_node(3) tree_data(G, 0) with pytest.raises(nx.NetworkXError, match="must be different."): G = nx.MultiDiGraph() G.add_node(0) tree_data(G, 0, ident="node", children="node")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from itertools import chain
import networkx as nx
__all__ = ["tree_data", "tree_graph"]
def tree_data(G, root, ident="id", children="children"): """Returns data in tree format that is suitable for JSON serialization and use in JavaScript documents.
Parameters ---------- G : NetworkX graph G must be an oriented tree
root : node The root of the tree
ident : string Attribute name for storing NetworkX-internal graph data. `ident` must have a different value than `children`. The default is 'id'.
children : string Attribute name for storing NetworkX-internal graph data. `children` must have a different value than `ident`. The default is 'children'.
Returns ------- data : dict A dictionary with node-link formatted data.
Raises ------ NetworkXError If `children` and `ident` attributes are identical.
Examples -------- >>> from networkx.readwrite import json_graph >>> G = nx.DiGraph([(1, 2)]) >>> data = json_graph.tree_data(G, root=1)
To serialize with json
>>> import json >>> s = json.dumps(data)
Notes ----- Node attributes are stored in this format but keys for attributes must be strings if you want to serialize with JSON.
Graph and edge attributes are not stored.
See Also -------- tree_graph, node_link_data, adjacency_data """ if G.number_of_nodes() != G.number_of_edges() + 1: raise TypeError("G is not a tree.") if not G.is_directed(): raise TypeError("G is not directed.") if not nx.is_weakly_connected(G): raise TypeError("G is not weakly connected.")
if ident == children: raise nx.NetworkXError("The values for `id` and `children` must be different.")
def add_children(n, G): nbrs = G[n] if len(nbrs) == 0: return [] children_ = [] for child in nbrs: d = {**G.nodes[child], ident: child} c = add_children(child, G) if c: d[children] = c children_.append(d) return children_
return {**G.nodes[root], ident: root, children: add_children(root, G)}
@nx._dispatchable(graphs=None, returns_graph=True)def tree_graph(data, ident="id", children="children"): """Returns graph from tree data format.
Parameters ---------- data : dict Tree formatted graph data
ident : string Attribute name for storing NetworkX-internal graph data. `ident` must have a different value than `children`. The default is 'id'.
children : string Attribute name for storing NetworkX-internal graph data. `children` must have a different value than `ident`. The default is 'children'.
Returns ------- G : NetworkX DiGraph
Examples -------- >>> from networkx.readwrite import json_graph >>> G = nx.DiGraph([(1, 2)]) >>> data = json_graph.tree_data(G, root=1) >>> H = json_graph.tree_graph(data)
See Also -------- tree_data, node_link_data, adjacency_data """ graph = nx.DiGraph()
def add_children(parent, children_): for data in children_: child = data[ident] graph.add_edge(parent, child) grandchildren = data.get(children, []) if grandchildren: add_children(child, grandchildren) nodedata = { str(k): v for k, v in data.items() if k != ident and k != children } graph.add_node(child, **nodedata)
root = data[ident] children_ = data.get(children, []) nodedata = {str(k): v for k, v in data.items() if k != ident and k != children} graph.add_node(root, **nodedata) add_children(root, children_) return graph123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Read graphs in LEDA format.
LEDA is a C++ class library for efficient data types and algorithms.
Format------See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
"""# Original author: D. Eppstein, UC Irvine, August 12, 2003.# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
__all__ = ["read_leda", "parse_leda"]
import networkx as nxfrom networkx.exception import NetworkXErrorfrom networkx.utils import open_file
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_leda(path, encoding="UTF-8"): """Read graph in LEDA format from path.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
Returns ------- G : NetworkX graph
Examples -------- >>> G = nx.read_leda("file.leda") # doctest: +SKIP
References ---------- .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html """ lines = (line.decode(encoding) for line in path) G = parse_leda(lines) return G
@nx._dispatchable(graphs=None, returns_graph=True)def parse_leda(lines): """Read graph in LEDA format from string or iterable.
Parameters ---------- lines : string or iterable Data in LEDA format.
Returns ------- G : NetworkX graph
Examples -------- >>> G = nx.parse_leda(string) # doctest: +SKIP
References ---------- .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html """ if isinstance(lines, str): lines = iter(lines.split("\n")) lines = iter( [ line.rstrip("\n") for line in lines if not (line.startswith(("#", "\n")) or line == "") ] ) for i in range(3): next(lines) # Graph du = int(next(lines)) # -1=directed, -2=undirected if du == -1: G = nx.DiGraph() else: G = nx.Graph()
# Nodes n = int(next(lines)) # number of nodes node = {} for i in range(1, n + 1): # LEDA counts from 1 to n symbol = next(lines).rstrip().strip("|{}| ") if symbol == "": symbol = str(i) # use int if no label - could be trouble node[i] = symbol
G.add_nodes_from([s for i, s in node.items()])
# Edges m = int(next(lines)) # number of edges for i in range(m): try: s, t, reversal, label = next(lines).split() except BaseException as err: raise NetworkXError(f"Too few fields in LEDA.GRAPH edge {i + 1}") from err # BEWARE: no handling of reversal edges G.add_edge(node[int(s)], node[int(t)], label=label[2:-2]) return G123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393"""*************************Multi-line Adjacency List*************************Read and write NetworkX graphs as multi-line adjacency lists.
The multi-line adjacency list format is useful for graphs withnodes that can be meaningfully represented as strings. With this formatsimple edge data can be stored but node or graph data is not.
Format------The first label in a line is the source node label followed by the node degreed. The next d lines are target node labels and optional edge data.That pattern repeats for all nodes in the graph.
The graph with edges a-b, a-c, d-e can be represented as the followingadjacency list (anything following the # in a line is a comment)::
# example.multiline-adjlist a 2 b c d 1 e"""
__all__ = [ "generate_multiline_adjlist", "write_multiline_adjlist", "parse_multiline_adjlist", "read_multiline_adjlist",]
import networkx as nxfrom networkx.utils import open_file
def generate_multiline_adjlist(G, delimiter=" "): """Generate a single line of the graph G in multiline adjacency list format.
Parameters ---------- G : NetworkX graph
delimiter : string, optional Separator for node labels
Returns ------- lines : string Lines of data in multiline adjlist format.
Examples -------- >>> G = nx.lollipop_graph(4, 3) >>> for line in nx.generate_multiline_adjlist(G): ... print(line) 0 3 1 {} 2 {} 3 {} 1 2 2 {} 3 {} 2 1 3 {} 3 1 4 {} 4 1 5 {} 5 1 6 {} 6 0
See Also -------- write_multiline_adjlist, read_multiline_adjlist """ if G.is_directed(): if G.is_multigraph(): for s, nbrs in G.adjacency(): nbr_edges = [ (u, data) for u, datadict in nbrs.items() for key, data in datadict.items() ] deg = len(nbr_edges) yield str(s) + delimiter + str(deg) for u, d in nbr_edges: if d is None: yield str(u) else: yield str(u) + delimiter + str(d) else: # directed single edges for s, nbrs in G.adjacency(): deg = len(nbrs) yield str(s) + delimiter + str(deg) for u, d in nbrs.items(): if d is None: yield str(u) else: yield str(u) + delimiter + str(d) else: # undirected if G.is_multigraph(): seen = set() # helper dict used to avoid duplicate edges for s, nbrs in G.adjacency(): nbr_edges = [ (u, data) for u, datadict in nbrs.items() if u not in seen for key, data in datadict.items() ] deg = len(nbr_edges) yield str(s) + delimiter + str(deg) for u, d in nbr_edges: if d is None: yield str(u) else: yield str(u) + delimiter + str(d) seen.add(s) else: # undirected single edges seen = set() # helper dict used to avoid duplicate edges for s, nbrs in G.adjacency(): nbr_edges = [(u, d) for u, d in nbrs.items() if u not in seen] deg = len(nbr_edges) yield str(s) + delimiter + str(deg) for u, d in nbr_edges: if d is None: yield str(u) else: yield str(u) + delimiter + str(d) seen.add(s)
@open_file(1, mode="wb")def write_multiline_adjlist(G, path, delimiter=" ", comments="#", encoding="utf-8"): """Write the graph G in multiline adjacency list format to path
Parameters ---------- G : NetworkX graph
path : string or file Filename or file handle to write to. Filenames ending in .gz or .bz2 will be compressed.
comments : string, optional Marker for comment lines
delimiter : string, optional Separator for node labels
encoding : string, optional Text encoding.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_multiline_adjlist(G, "test.multi_adjlist")
The path can be a file handle or a string with the name of the file. If a file handle is provided, it has to be opened in 'wb' mode.
>>> fh = open("test.multi_adjlist2", "wb") >>> nx.write_multiline_adjlist(G, fh)
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_multiline_adjlist(G, "test.multi_adjlist.gz")
See Also -------- read_multiline_adjlist """ import sys import time
pargs = comments + " ".join(sys.argv) header = ( f"{pargs}\n" + comments + f" GMT {time.asctime(time.gmtime())}\n" + comments + f" {G.name}\n" ) path.write(header.encode(encoding))
for multiline in generate_multiline_adjlist(G, delimiter): multiline += "\n" path.write(multiline.encode(encoding))
@nx._dispatchable(graphs=None, returns_graph=True)def parse_multiline_adjlist( lines, comments="#", delimiter=None, create_using=None, nodetype=None, edgetype=None): """Parse lines of a multiline adjacency list representation of a graph.
Parameters ---------- lines : list or iterator of strings Input data in multiline adjlist format
create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated.
nodetype : Python type, optional Convert nodes to this type.
edgetype : Python type, optional Convert edges to this type.
comments : string, optional Marker for comment lines
delimiter : string, optional Separator for node labels. The default is whitespace.
Returns ------- G: NetworkX graph The graph corresponding to the lines in multiline adjacency list format.
Examples -------- >>> lines = [ ... "1 2", ... "2 {'weight':3, 'name': 'Frodo'}", ... "3 {}", ... "2 1", ... "5 {'weight':6, 'name': 'Saruman'}", ... ] >>> G = nx.parse_multiline_adjlist(iter(lines), nodetype=int) >>> list(G) [1, 2, 3, 5]
""" from ast import literal_eval
G = nx.empty_graph(0, create_using) for line in lines: p = line.find(comments) if p >= 0: line = line[:p] if not line: continue try: (u, deg) = line.rstrip("\n").split(delimiter) deg = int(deg) except BaseException as err: raise TypeError(f"Failed to read node and degree on line ({line})") from err if nodetype is not None: try: u = nodetype(u) except BaseException as err: raise TypeError( f"Failed to convert node ({u}) to type {nodetype}" ) from err G.add_node(u) for i in range(deg): while True: try: line = next(lines) except StopIteration as err: msg = f"Failed to find neighbor for node ({u})" raise TypeError(msg) from err p = line.find(comments) if p >= 0: line = line[:p] if line: break vlist = line.rstrip("\n").split(delimiter) numb = len(vlist) if numb < 1: continue # isolated node v = vlist.pop(0) data = "".join(vlist) if nodetype is not None: try: v = nodetype(v) except BaseException as err: raise TypeError( f"Failed to convert node ({v}) to type {nodetype}" ) from err if edgetype is not None: try: edgedata = {"weight": edgetype(data)} except BaseException as err: raise TypeError( f"Failed to convert edge data ({data}) to type {edgetype}" ) from err else: try: # try to evaluate edgedata = literal_eval(data) except: edgedata = {} G.add_edge(u, v, **edgedata)
return G
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_multiline_adjlist( path, comments="#", delimiter=None, create_using=None, nodetype=None, edgetype=None, encoding="utf-8",): """Read graph in multi-line adjacency list format from path.
Parameters ---------- path : string or file Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated.
nodetype : Python type, optional Convert nodes to this type.
edgetype : Python type, optional Convert edge data to this type.
comments : string, optional Marker for comment lines
delimiter : string, optional Separator for node labels. The default is whitespace.
Returns ------- G: NetworkX graph
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4") >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
The path can be a file or a string with the name of the file. If a file s provided, it has to be opened in 'rb' mode.
>>> fh = open("test.multi_adjlistP4", "rb") >>> G = nx.read_multiline_adjlist(fh)
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4.gz") >>> G = nx.read_multiline_adjlist("test.multi_adjlistP4.gz")
The optional nodetype is a function to convert node strings to nodetype.
For example
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", nodetype=int)
will attempt to convert all nodes to integer type.
The optional edgetype is a function to convert edge data strings to edgetype.
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
The optional create_using parameter is a NetworkX graph container. The default is Graph(), an undirected graph. To read the data as a directed graph use
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", create_using=nx.DiGraph)
Notes ----- This format does not store graph, node, or edge data.
See Also -------- write_multiline_adjlist """ lines = (line.decode(encoding) for line in path) return parse_multiline_adjlist( lines, comments=comments, delimiter=delimiter, create_using=create_using, nodetype=nodetype, edgetype=edgetype, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""This module provides the following: read and write of p2g formatused in metabolic pathway studies.
See:<https://web.archive.org/web/20080626113807/http://www.cs.purdue.edu/homes/koyuturk/pathway/>for a description.
The summary is included here:
A file that describes a uniquely labeled graph (with extension ".gr")format looks like the following:
name3 4a1 2b
c0 2
"name" is simply a description of what the graph corresponds to. Thesecond line displays the number of nodes and number of edges,respectively. This sample graph contains three nodes labeled "a", "b",and "c". The rest of the graph contains two lines for each node. Thefirst line for a node contains the node label. After the declarationof the node label, the out-edges of that node in the graph areprovided. For instance, "a" is linked to nodes 1 and 2, which arelabeled "b" and "c", while the node labeled "b" has no outgoingedges. Observe that node labeled "c" has an outgoing edge toitself. Indeed, self-loops are allowed. Node index starts from 0.
"""
import networkx as nxfrom networkx.utils import open_file
@open_file(1, mode="w")def write_p2g(G, path, encoding="utf-8"): """Write NetworkX graph in p2g format.
Notes ----- This format is meant to be used with directed graphs with possible self loops. """ path.write((f"{G.name}\n").encode(encoding)) path.write((f"{G.order()} {G.size()}\n").encode(encoding)) nodes = list(G) # make dictionary mapping nodes to integers nodenumber = dict(zip(nodes, range(len(nodes)))) for n in nodes: path.write((f"{n}\n").encode(encoding)) for nbr in G.neighbors(n): path.write((f"{nodenumber[nbr]} ").encode(encoding)) path.write("\n".encode(encoding))
@open_file(0, mode="r")@nx._dispatchable(graphs=None, returns_graph=True)def read_p2g(path, encoding="utf-8"): """Read graph in p2g format from path.
Parameters ---------- path : string or file Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
Returns ------- MultiDiGraph
Notes ----- If you want a DiGraph (with no self loops allowed and no edge data) use D=nx.DiGraph(read_p2g(path)) """ lines = (line.decode(encoding) for line in path) G = parse_p2g(lines) return G
@nx._dispatchable(graphs=None, returns_graph=True)def parse_p2g(lines): """Parse p2g format graph from string or iterable.
Returns ------- MultiDiGraph """ description = next(lines).strip() # are multiedges (parallel edges) allowed? G = nx.MultiDiGraph(name=description, selfloops=True) nnodes, nedges = map(int, next(lines).split()) nodelabel = {} nbrs = {} # loop over the nodes keeping track of node labels and out neighbors # defer adding edges until all node labels are known for i in range(nnodes): n = next(lines).strip() nodelabel[i] = n G.add_node(n) nbrs[n] = map(int, next(lines).split()) # now we know all of the node labels so we can add the edges # with the correct labels for n in G: for nbr in nbrs[n]: G.add_edge(n, nodelabel[nbr]) return G123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""*****Pajek*****Read graphs in Pajek format.
This implementation handles directed and undirected graphs includingthose with self loops and parallel edges.
Format------See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htmfor format information.
"""
import warnings
import networkx as nxfrom networkx.utils import open_file
__all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"]
def generate_pajek(G): """Generate lines in Pajek graph format.
Parameters ---------- G : graph A Networkx graph
References ---------- See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm for format information. """ if G.name == "": name = "NetworkX" else: name = G.name # Apparently many Pajek format readers can't process this line # So we'll leave it out for now. # yield '*network %s'%name
# write nodes with attributes yield f"*vertices {G.order()}" nodes = list(G) # make dictionary mapping nodes to integers nodenumber = dict(zip(nodes, range(1, len(nodes) + 1))) for n in nodes: # copy node attributes and pop mandatory attributes # to avoid duplication. na = G.nodes.get(n, {}).copy() x = na.pop("x", 0.0) y = na.pop("y", 0.0) try: id = int(na.pop("id", nodenumber[n])) except ValueError as err: err.args += ( ( "Pajek format requires 'id' to be an int()." " Refer to the 'Relabeling nodes' section." ), ) raise nodenumber[n] = id shape = na.pop("shape", "ellipse") s = " ".join(map(make_qstr, (id, n, x, y, shape))) # only optional attributes are left in na. for k, v in na.items(): if isinstance(v, str) and v.strip() != "": s += f" {make_qstr(k)} {make_qstr(v)}" else: warnings.warn( f"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}." ) yield s
# write edges with attributes if G.is_directed(): yield "*arcs" else: yield "*edges" for u, v, edgedata in G.edges(data=True): d = edgedata.copy() value = d.pop("weight", 1.0) # use 1 as default edge value s = " ".join(map(make_qstr, (nodenumber[u], nodenumber[v], value))) for k, v in d.items(): if isinstance(v, str) and v.strip() != "": s += f" {make_qstr(k)} {make_qstr(v)}" else: warnings.warn( f"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}." ) yield s
@open_file(1, mode="wb")def write_pajek(G, path, encoding="UTF-8"): """Write graph in Pajek format to path.
Parameters ---------- G : graph A Networkx graph path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_pajek(G, "test.netP4")
Warnings -------- Optional node attributes and edge attributes must be non-empty strings. Otherwise it will not be written into the file. You will need to convert those attributes to strings if you want to keep them.
References ---------- See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm for format information. """ for line in generate_pajek(G): line += "\n" path.write(line.encode(encoding))
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_pajek(path, encoding="UTF-8"): """Read graph in Pajek format from path.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
Returns ------- G : NetworkX MultiGraph or MultiDiGraph.
Examples -------- >>> G = nx.path_graph(4) >>> nx.write_pajek(G, "test.net") >>> G = nx.read_pajek("test.net")
To create a Graph instead of a MultiGraph use
>>> G1 = nx.Graph(G)
References ---------- See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm for format information. """ lines = (line.decode(encoding) for line in path) return parse_pajek(lines)
@nx._dispatchable(graphs=None, returns_graph=True)def parse_pajek(lines): """Parse Pajek format graph from string or iterable.
Parameters ---------- lines : string or iterable Data in Pajek format.
Returns ------- G : NetworkX graph
See Also -------- read_pajek
""" import shlex
# multigraph=False if isinstance(lines, str): lines = iter(lines.split("\n")) lines = iter([line.rstrip("\n") for line in lines]) G = nx.MultiDiGraph() # are multiedges allowed in Pajek? assume yes labels = [] # in the order of the file, needed for matrix while lines: try: l = next(lines) except: # EOF break if l.lower().startswith("*network"): try: label, name = l.split(None, 1) except ValueError: # Line was not of the form: *network NAME pass else: G.graph["name"] = name elif l.lower().startswith("*vertices"): nodelabels = {} l, nnodes = l.split() for i in range(int(nnodes)): l = next(lines) try: splitline = [ x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8")) ] except AttributeError: splitline = shlex.split(str(l)) id, label = splitline[0:2] labels.append(label) G.add_node(label) nodelabels[id] = label G.nodes[label]["id"] = id try: x, y, shape = splitline[2:5] G.nodes[label].update( {"x": float(x), "y": float(y), "shape": shape} ) except: pass extra_attr = zip(splitline[5::2], splitline[6::2]) G.nodes[label].update(extra_attr) elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"): if l.lower().startswith("*edge"): # switch from multidigraph to multigraph G = nx.MultiGraph(G) if l.lower().startswith("*arcs"): # switch to directed with multiple arcs for each existing edge G = G.to_directed() for l in lines: try: splitline = [ x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8")) ] except AttributeError: splitline = shlex.split(str(l))
if len(splitline) < 2: continue ui, vi = splitline[0:2] u = nodelabels.get(ui, ui) v = nodelabels.get(vi, vi) # parse the data attached to this edge and put in a dictionary edge_data = {} try: # there should always be a single value on the edge? w = splitline[2:3] edge_data.update({"weight": float(w[0])}) except: pass # if there isn't, just assign a 1 # edge_data.update({'value':1}) extra_attr = zip(splitline[3::2], splitline[4::2]) edge_data.update(extra_attr) # if G.has_edge(u,v): # multigraph=True G.add_edge(u, v, **edge_data) elif l.lower().startswith("*matrix"): G = nx.DiGraph(G) adj_list = ( (labels[row], labels[col], {"weight": int(data)}) for (row, line) in enumerate(lines) for (col, data) in enumerate(line.split()) if int(data) != 0 ) G.add_edges_from(adj_list)
return G
def make_qstr(t): """Returns the string representation of t. Add outer double-quotes if the string has a space. """ if not isinstance(t, str): t = str(t) if " " in t: t = f'"{t}"' return t123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379# Original author: D. Eppstein, UC Irvine, August 12, 2003.# The original code at https://www.ics.uci.edu/~eppstein/PADS/ is public domain."""Functions for reading and writing graphs in the *sparse6* format.
The *sparse6* file format is a space-efficient format for large sparsegraphs. For small graphs or large dense graphs, use the *graph6* fileformat.
For more information, see the `sparse6`_ homepage.
.. _sparse6: https://users.cecs.anu.edu.au/~bdm/data/formats.html
"""
import networkx as nxfrom networkx.exception import NetworkXErrorfrom networkx.readwrite.graph6 import data_to_n, n_to_datafrom networkx.utils import not_implemented_for, open_file
__all__ = ["from_sparse6_bytes", "read_sparse6", "to_sparse6_bytes", "write_sparse6"]
def _generate_sparse6_bytes(G, nodes, header): """Yield bytes in the sparse6 encoding of a graph.
`G` is an undirected simple graph. `nodes` is the list of nodes for which the node-induced subgraph will be encoded; if `nodes` is the list of all nodes in the graph, the entire graph will be encoded. `header` is a Boolean that specifies whether to generate the header ``b'>>sparse6<<'`` before the remaining data.
This function generates `bytes` objects in the following order:
1. the header (if requested), 2. the encoding of the number of nodes, 3. each character, one-at-a-time, in the encoding of the requested node-induced subgraph, 4. a newline character.
This function raises :exc:`ValueError` if the graph is too large for the graph6 format (that is, greater than ``2 ** 36`` nodes).
""" n = len(G) if n >= 2**36: raise ValueError( "sparse6 is only defined if number of nodes is less than 2 ** 36" ) if header: yield b">>sparse6<<" yield b":" for d in n_to_data(n): yield str.encode(chr(d + 63))
k = 1 while 1 << k < n: k += 1
def enc(x): """Big endian k-bit encoding of x""" return [1 if (x & 1 << (k - 1 - i)) else 0 for i in range(k)]
edges = sorted((max(u, v), min(u, v)) for u, v in G.edges()) bits = [] curv = 0 for v, u in edges: if v == curv: # current vertex edge bits.append(0) bits.extend(enc(u)) elif v == curv + 1: # next vertex edge curv += 1 bits.append(1) bits.extend(enc(u)) else: # skip to vertex v and then add edge to u curv = v bits.append(1) bits.extend(enc(v)) bits.append(0) bits.extend(enc(u)) if k < 6 and n == (1 << k) and ((-len(bits)) % 6) >= k and curv < (n - 1): # Padding special case: small k, n=2^k, # more than k bits of padding needed, # current vertex is not (n-1) -- # appending 1111... would add a loop on (n-1) bits.append(0) bits.extend([1] * ((-len(bits)) % 6)) else: bits.extend([1] * ((-len(bits)) % 6))
data = [ (bits[i + 0] << 5) + (bits[i + 1] << 4) + (bits[i + 2] << 3) + (bits[i + 3] << 2) + (bits[i + 4] << 1) + (bits[i + 5] << 0) for i in range(0, len(bits), 6) ]
for d in data: yield str.encode(chr(d + 63)) yield b"\n"
@nx._dispatchable(graphs=None, returns_graph=True)def from_sparse6_bytes(string): """Read an undirected graph in sparse6 format from string.
Parameters ---------- string : string Data in sparse6 format
Returns ------- G : Graph
Raises ------ NetworkXError If the string is unable to be parsed in sparse6 format
Examples -------- >>> G = nx.from_sparse6_bytes(b":A_") >>> sorted(G.edges()) [(0, 1), (0, 1), (0, 1)]
See Also -------- read_sparse6, write_sparse6
References ---------- .. [1] Sparse6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" if string.startswith(b">>sparse6<<"): string = string[11:] if not string.startswith(b":"): raise NetworkXError("Expected leading colon in sparse6")
chars = [c - 63 for c in string[1:]] n, data = data_to_n(chars) k = 1 while 1 << k < n: k += 1
def parseData(): """Returns stream of pairs b[i], x[i] for sparse6 format.""" chunks = iter(data) d = None # partial data word dLen = 0 # how many unparsed bits are left in d
while 1: if dLen < 1: try: d = next(chunks) except StopIteration: return dLen = 6 dLen -= 1 b = (d >> dLen) & 1 # grab top remaining bit
x = d & ((1 << dLen) - 1) # partially built up value of x xLen = dLen # how many bits included so far in x while xLen < k: # now grab full chunks until we have enough try: d = next(chunks) except StopIteration: return dLen = 6 x = (x << 6) + d xLen += 6 x = x >> (xLen - k) # shift back the extra bits dLen = xLen - k yield b, x
v = 0
G = nx.MultiGraph() G.add_nodes_from(range(n))
multigraph = False for b, x in parseData(): if b == 1: v += 1 # padding with ones can cause overlarge number here if x >= n or v >= n: break elif x > v: v = x else: if G.has_edge(x, v): multigraph = True G.add_edge(x, v) if not multigraph: G = nx.Graph(G) return G
def to_sparse6_bytes(G, nodes=None, header=True): """Convert an undirected graph to bytes in sparse6 format.
Parameters ---------- G : Graph (undirected)
nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used.
header: bool If True add '>>sparse6<<' bytes to head of data.
Raises ------ NetworkXNotImplemented If the graph is directed.
ValueError If the graph has at least ``2 ** 36`` nodes; the sparse6 format is only defined for graphs of order less than ``2 ** 36``.
Examples -------- >>> nx.to_sparse6_bytes(nx.path_graph(2)) b'>>sparse6<<:An\\n'
See Also -------- to_sparse6_bytes, read_sparse6, write_sparse6_bytes
Notes ----- The returned bytes end with a newline character.
The format does not support edge or node labels.
References ---------- .. [1] Graph6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" if nodes is not None: G = G.subgraph(nodes) G = nx.convert_node_labels_to_integers(G, ordering="sorted") return b"".join(_generate_sparse6_bytes(G, nodes, header))
@open_file(0, mode="rb")@nx._dispatchable(graphs=None, returns_graph=True)def read_sparse6(path): """Read an undirected graph in sparse6 format from path.
Parameters ---------- path : file or string Filename or file handle to read. Filenames ending in .gz or .bz2 will be decompressed.
Returns ------- G : Graph/Multigraph or list of Graphs/MultiGraphs If the file contains multiple lines then a list of graphs is returned
Raises ------ NetworkXError If the string is unable to be parsed in sparse6 format
Examples -------- You can read a sparse6 file by giving the path to the file::
>>> import tempfile >>> with tempfile.NamedTemporaryFile(delete=False) as f: ... _ = f.write(b">>sparse6<<:An\\n") ... _ = f.seek(0) ... G = nx.read_sparse6(f.name) >>> list(G.edges()) [(0, 1)]
You can also read a sparse6 file by giving an open file-like object::
>>> import tempfile >>> with tempfile.NamedTemporaryFile() as f: ... _ = f.write(b">>sparse6<<:An\\n") ... _ = f.seek(0) ... G = nx.read_sparse6(f) >>> list(G.edges()) [(0, 1)]
See Also -------- read_sparse6, from_sparse6_bytes
References ---------- .. [1] Sparse6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" glist = [] for line in path: line = line.strip() if not len(line): continue glist.append(from_sparse6_bytes(line)) if len(glist) == 1: return glist[0] else: return glist
@not_implemented_for("directed")@open_file(1, mode="wb")def write_sparse6(G, path, nodes=None, header=True): """Write graph G to given path in sparse6 format.
Parameters ---------- G : Graph (undirected)
path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed.
nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by G.nodes() is used.
header: bool If True add '>>sparse6<<' string to head of data
Raises ------ NetworkXError If the graph is directed
Examples -------- You can write a sparse6 file by giving the path to the file::
>>> import tempfile >>> with tempfile.NamedTemporaryFile(delete=False) as f: ... nx.write_sparse6(nx.path_graph(2), f.name) ... print(f.read()) b'>>sparse6<<:An\\n'
You can also write a sparse6 file by giving an open file-like object::
>>> with tempfile.NamedTemporaryFile() as f: ... nx.write_sparse6(nx.path_graph(2), f) ... _ = f.seek(0) ... print(f.read()) b'>>sparse6<<:An\\n'
See Also -------- read_sparse6, from_sparse6_bytes
Notes ----- The format does not support edge or node labels.
References ---------- .. [1] Sparse6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html>
""" if nodes is not None: G = G.subgraph(nodes) G = nx.convert_node_labels_to_integers(G, ordering="sorted") for b in _generate_sparse6_bytes(G, nodes, header): path.write(b)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354"""Unit tests for adjlist."""
import io
import pytest
import networkx as nxfrom networkx.utils import edges_equal, graphs_equal, nodes_equal
class TestGenerateAdjlist: @pytest.mark.parametrize("graph_type", [nx.Graph, nx.MultiGraph]) def test_undirected(self, graph_type): G = nx.complete_graph(5, create_using=graph_type) lines = [ "0 1 2 3 4", "1 2 3 4", "2 3 4", "3 4", "4", ] assert list(nx.generate_adjlist(G)) == lines
@pytest.mark.parametrize("graph_type", [nx.DiGraph, nx.MultiDiGraph]) def test_directed(self, graph_type): G = nx.complete_graph(5, create_using=graph_type) lines = [ "0 1 2 3 4", "1 0 2 3 4", "2 0 1 3 4", "3 0 1 2 4", "4 0 1 2 3", ] assert list(nx.generate_adjlist(G)) == lines
G = nx.path_graph(5, create_using=graph_type) G.add_edge(1, 0) lines = [ "0 1", "1 2 0", "2 3", "3 4", "4", ] assert list(nx.generate_adjlist(G)) == lines
@pytest.mark.parametrize("delimiter", [" ", ",", "\t"]) def test_delimiter(self, delimiter): G = nx.complete_graph(3) lines = [ f"0{delimiter}1{delimiter}2", f"1{delimiter}2", f"2", ] assert list(nx.generate_adjlist(G, delimiter=delimiter)) == lines
def test_multiple_edges_undirected(self): G = nx.complete_graph(3, create_using=nx.MultiGraph) G.add_edge(0, 1) lines = [ "0 1 1 2", "1 2", "2", ] assert list(nx.generate_adjlist(G)) == lines
def test_multiple_edges_directed(self): G = nx.complete_graph(3, create_using=nx.MultiDiGraph) G.add_edge(0, 1) lines = [ "0 1 1 2", "1 0 2", "2 0 1", ] assert list(nx.generate_adjlist(G)) == lines
G.add_edge(1, 0) lines[1] = "1 0 0 2" assert list(nx.generate_adjlist(G)) == lines
def test_multiple_edges_with_data(self): G = nx.complete_graph(3, create_using=nx.MultiGraph) G.add_edge(0, 1, weight=1) G.add_edge(0, 1, weight=2) lines = [ "0 1 1 1 2", "1 2", "2", ] assert list(nx.generate_adjlist(G)) == lines
def test_with_self_loop(self): G = nx.complete_graph(3) G.add_edge(0, 0) lines = [ "0 1 2 0", "1 2", "2", ] assert list(nx.generate_adjlist(G)) == lines
class TestAdjlist: @classmethod def setup_class(cls): cls.G = nx.Graph(name="test") e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] cls.G.add_edges_from(e) cls.G.add_node("g") cls.DG = nx.DiGraph(cls.G) cls.XG = nx.MultiGraph() cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)]) cls.XDG = nx.MultiDiGraph(cls.XG)
def test_read_multiline_adjlist_1(self): # Unit test for https://networkx.lanl.gov/trac/ticket/252 s = b"""# comment line1 2# comment line23""" bytesIO = io.BytesIO(s) G = nx.read_multiline_adjlist(bytesIO) adj = {"1": {"3": {}, "2": {}}, "3": {"1": {}}, "2": {"1": {}}} assert graphs_equal(G, nx.Graph(adj))
def test_unicode(self, tmp_path): G = nx.Graph() name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) G.add_edge(name1, "Radiohead", **{name2: 3})
fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist(fname) assert graphs_equal(G, H)
def test_latin1_err(self, tmp_path): G = nx.Graph() name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "adjlist.txt" with pytest.raises(UnicodeEncodeError): nx.write_multiline_adjlist(G, fname, encoding="latin-1")
def test_latin1(self, tmp_path): G = nx.Graph() name1 = "Bj" + chr(246) + "rk" name2 = chr(220) + "ber" G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname, encoding="latin-1") H = nx.read_multiline_adjlist(fname, encoding="latin-1") assert graphs_equal(G, H)
def test_parse_adjlist(self): lines = ["1 2 5", "2 3 4", "3 5", "4", "5"] nx.parse_adjlist(lines, nodetype=int) # smoke test with pytest.raises(TypeError): nx.parse_adjlist(lines, nodetype="int") lines = ["1 2 5", "2 b", "c"] with pytest.raises(TypeError): nx.parse_adjlist(lines, nodetype=int)
def test_adjlist_graph(self, tmp_path): G = self.G fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname) H2 = nx.read_adjlist(fname) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_adjlist_digraph(self, tmp_path): G = self.DG fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, create_using=nx.DiGraph()) H2 = nx.read_adjlist(fname, create_using=nx.DiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
def test_adjlist_integers(self, tmp_path): fname = tmp_path / "adjlist.txt" G = nx.convert_node_labels_to_integers(self.G) nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, nodetype=int) H2 = nx.read_adjlist(fname, nodetype=int) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_adjlist_multigraph(self, tmp_path): G = self.XG fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph()) H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_adjlist_multidigraph(self, tmp_path): G = self.XDG fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph()) H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
def test_adjlist_delimiter(self): fh = io.BytesIO() G = nx.path_graph(3) nx.write_adjlist(G, fh, delimiter=":") fh.seek(0) H = nx.read_adjlist(fh, nodetype=int, delimiter=":") assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
class TestMultilineAdjlist: @classmethod def setup_class(cls): cls.G = nx.Graph(name="test") e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] cls.G.add_edges_from(e) cls.G.add_node("g") cls.DG = nx.DiGraph(cls.G) cls.DG.remove_edge("b", "a") cls.DG.remove_edge("b", "c") cls.XG = nx.MultiGraph() cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)]) cls.XDG = nx.MultiDiGraph(cls.XG)
def test_parse_multiline_adjlist(self): lines = [ "1 2", "b {'weight':3, 'name': 'Frodo'}", "c {}", "d 1", "e {'weight':6, 'name': 'Saruman'}", ] nx.parse_multiline_adjlist(iter(lines)) # smoke test with pytest.raises(TypeError): nx.parse_multiline_adjlist(iter(lines), nodetype=int) nx.parse_multiline_adjlist(iter(lines), edgetype=str) # smoke test with pytest.raises(TypeError): nx.parse_multiline_adjlist(iter(lines), nodetype=int) lines = ["1 a"] with pytest.raises(TypeError): nx.parse_multiline_adjlist(iter(lines)) lines = ["a 2"] with pytest.raises(TypeError): nx.parse_multiline_adjlist(iter(lines), nodetype=int) lines = ["1 2"] with pytest.raises(TypeError): nx.parse_multiline_adjlist(iter(lines)) lines = ["1 2", "2 {}"] with pytest.raises(TypeError): nx.parse_multiline_adjlist(iter(lines))
def test_multiline_adjlist_graph(self, tmp_path): G = self.G fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist(fname) H2 = nx.read_multiline_adjlist(fname) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_multiline_adjlist_digraph(self, tmp_path): G = self.DG fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist(fname, create_using=nx.DiGraph()) H2 = nx.read_multiline_adjlist(fname, create_using=nx.DiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
def test_multiline_adjlist_integers(self, tmp_path): fname = tmp_path / "adjlist.txt" G = nx.convert_node_labels_to_integers(self.G) nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist(fname, nodetype=int) H2 = nx.read_multiline_adjlist(fname, nodetype=int) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_multiline_adjlist_multigraph(self, tmp_path): G = self.XG fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist(fname, nodetype=int, create_using=nx.MultiGraph()) H2 = nx.read_multiline_adjlist( fname, nodetype=int, create_using=nx.MultiGraph() ) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_multiline_adjlist_multidigraph(self, tmp_path): G = self.XDG fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist( fname, nodetype=int, create_using=nx.MultiDiGraph() ) H2 = nx.read_multiline_adjlist( fname, nodetype=int, create_using=nx.MultiDiGraph() ) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
def test_multiline_adjlist_delimiter(self): fh = io.BytesIO() G = nx.path_graph(3) nx.write_multiline_adjlist(G, fh, delimiter=":") fh.seek(0) H = nx.read_multiline_adjlist(fh, nodetype=int, delimiter=":") assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
@pytest.mark.parametrize( ("lines", "delim"), ( (["1 2 5", "2 3 4", "3 5", "4", "5"], None), # No extra whitespace (["1\t2\t5", "2\t3\t4", "3\t5", "4", "5"], "\t"), # tab-delimited ( ["1\t2\t5", "2\t3\t4", "3\t5\t", "4\t", "5"], "\t", ), # tab-delimited, extra delims ( ["1\t2\t5", "2\t3\t4", "3\t5\t\t\n", "4\t", "5"], "\t", ), # extra delim+newlines ),)def test_adjlist_rstrip_parsing(lines, delim): """Regression test related to gh-7465""" expected = nx.Graph([(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)]) nx.utils.graphs_equal(nx.parse_adjlist(lines, delimiter=delim), expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318"""Unit tests for edgelists."""
import ioimport textwrap
import pytest
import networkx as nxfrom networkx.utils import edges_equal, graphs_equal, nodes_equal
edges_no_data = textwrap.dedent( """ # comment line 1 2 # comment line 2 3 """)
edges_with_values = textwrap.dedent( """ # comment line 1 2 2.0 # comment line 2 3 3.0 """)
edges_with_weight = textwrap.dedent( """ # comment line 1 2 {'weight':2.0} # comment line 2 3 {'weight':3.0} """)
edges_with_multiple_attrs = textwrap.dedent( """ # comment line 1 2 {'weight':2.0, 'color':'green'} # comment line 2 3 {'weight':3.0, 'color':'red'} """)
edges_with_multiple_attrs_csv = textwrap.dedent( """ # comment line 1, 2, {'weight':2.0, 'color':'green'} # comment line 2, 3, {'weight':3.0, 'color':'red'} """)
_expected_edges_weights = [(1, 2, {"weight": 2.0}), (2, 3, {"weight": 3.0})]_expected_edges_multiattr = [ (1, 2, {"weight": 2.0, "color": "green"}), (2, 3, {"weight": 3.0, "color": "red"}),]
@pytest.mark.parametrize( ("data", "extra_kwargs"), ( (edges_no_data, {}), (edges_with_values, {}), (edges_with_weight, {}), (edges_with_multiple_attrs, {}), (edges_with_multiple_attrs_csv, {"delimiter": ","}), ),)def test_read_edgelist_no_data(data, extra_kwargs): bytesIO = io.BytesIO(data.encode("utf-8")) G = nx.read_edgelist(bytesIO, nodetype=int, data=False, **extra_kwargs) assert edges_equal(G.edges(), [(1, 2), (2, 3)])
def test_read_weighted_edgelist(): bytesIO = io.BytesIO(edges_with_values.encode("utf-8")) G = nx.read_weighted_edgelist(bytesIO, nodetype=int) assert edges_equal(G.edges(data=True), _expected_edges_weights)
@pytest.mark.parametrize( ("data", "extra_kwargs", "expected"), ( (edges_with_weight, {}, _expected_edges_weights), (edges_with_multiple_attrs, {}, _expected_edges_multiattr), ( edges_with_multiple_attrs_csv, {"delimiter": ","}, _expected_edges_multiattr, ), ),)def test_read_edgelist_with_data(data, extra_kwargs, expected): bytesIO = io.BytesIO(data.encode("utf-8")) G = nx.read_edgelist(bytesIO, nodetype=int, **extra_kwargs) assert edges_equal(G.edges(data=True), expected)
@pytest.fixturedef example_graph(): G = nx.Graph() G.add_weighted_edges_from([(1, 2, 3.0), (2, 3, 27.0), (3, 4, 3.0)]) return G
def test_parse_edgelist_no_data(example_graph): G = example_graph H = nx.parse_edgelist(["1 2", "2 3", "3 4"], nodetype=int) assert nodes_equal(G.nodes, H.nodes) assert edges_equal(G.edges, H.edges)
def test_parse_edgelist_with_data_dict(example_graph): G = example_graph H = nx.parse_edgelist( ["1 2 {'weight': 3}", "2 3 {'weight': 27}", "3 4 {'weight': 3.0}"], nodetype=int ) assert nodes_equal(G.nodes, H.nodes) assert edges_equal(G.edges(data=True), H.edges(data=True))
def test_parse_edgelist_with_data_list(example_graph): G = example_graph H = nx.parse_edgelist( ["1 2 3", "2 3 27", "3 4 3.0"], nodetype=int, data=(("weight", float),) ) assert nodes_equal(G.nodes, H.nodes) assert edges_equal(G.edges(data=True), H.edges(data=True))
def test_parse_edgelist(): # ignore lines with less than 2 nodes lines = ["1;2", "2 3", "3 4"] G = nx.parse_edgelist(lines, nodetype=int) assert list(G.edges()) == [(2, 3), (3, 4)] # unknown nodetype with pytest.raises(TypeError, match="Failed to convert nodes"): lines = ["1 2", "2 3", "3 4"] nx.parse_edgelist(lines, nodetype="nope") # lines have invalid edge format with pytest.raises(TypeError, match="Failed to convert edge data"): lines = ["1 2 3", "2 3", "3 4"] nx.parse_edgelist(lines, nodetype=int) # edge data and data_keys not the same length with pytest.raises(IndexError, match="not the same length"): lines = ["1 2 3", "2 3 27", "3 4 3.0"] nx.parse_edgelist( lines, nodetype=int, data=(("weight", float), ("capacity", int)) ) # edge data can't be converted to edge type with pytest.raises(TypeError, match="Failed to convert"): lines = ["1 2 't1'", "2 3 't3'", "3 4 't3'"] nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
def test_comments_None(): edgelist = ["node#1 node#2", "node#2 node#3"] # comments=None supported to ignore all comment characters G = nx.parse_edgelist(edgelist, comments=None) H = nx.Graph([e.split(" ") for e in edgelist]) assert edges_equal(G.edges, H.edges)
class TestEdgelist: @classmethod def setup_class(cls): cls.G = nx.Graph(name="test") e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] cls.G.add_edges_from(e) cls.G.add_node("g") cls.DG = nx.DiGraph(cls.G) cls.XG = nx.MultiGraph() cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)]) cls.XDG = nx.MultiDiGraph(cls.XG)
def test_write_edgelist_1(self): fh = io.BytesIO() G = nx.Graph() G.add_edges_from([(1, 2), (2, 3)]) nx.write_edgelist(G, fh, data=False) fh.seek(0) assert fh.read() == b"1 2\n2 3\n"
def test_write_edgelist_2(self): fh = io.BytesIO() G = nx.Graph() G.add_edges_from([(1, 2), (2, 3)]) nx.write_edgelist(G, fh, data=True) fh.seek(0) assert fh.read() == b"1 2 {}\n2 3 {}\n"
def test_write_edgelist_3(self): fh = io.BytesIO() G = nx.Graph() G.add_edge(1, 2, weight=2.0) G.add_edge(2, 3, weight=3.0) nx.write_edgelist(G, fh, data=True) fh.seek(0) assert fh.read() == b"1 2 {'weight': 2.0}\n2 3 {'weight': 3.0}\n"
def test_write_edgelist_4(self): fh = io.BytesIO() G = nx.Graph() G.add_edge(1, 2, weight=2.0) G.add_edge(2, 3, weight=3.0) nx.write_edgelist(G, fh, data=[("weight")]) fh.seek(0) assert fh.read() == b"1 2 2.0\n2 3 3.0\n"
def test_unicode(self, tmp_path): G = nx.Graph() name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "el.txt" nx.write_edgelist(G, fname) H = nx.read_edgelist(fname) assert graphs_equal(G, H)
def test_latin1_issue(self, tmp_path): G = nx.Graph() name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "el.txt" with pytest.raises(UnicodeEncodeError): nx.write_edgelist(G, fname, encoding="latin-1")
def test_latin1(self, tmp_path): G = nx.Graph() name1 = "Bj" + chr(246) + "rk" name2 = chr(220) + "ber" G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "el.txt"
nx.write_edgelist(G, fname, encoding="latin-1") H = nx.read_edgelist(fname, encoding="latin-1") assert graphs_equal(G, H)
def test_edgelist_graph(self, tmp_path): G = self.G fname = tmp_path / "el.txt" nx.write_edgelist(G, fname) H = nx.read_edgelist(fname) H2 = nx.read_edgelist(fname) assert H is not H2 # they should be different graphs G.remove_node("g") # isolated nodes are not written in edgelist assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_edgelist_digraph(self, tmp_path): G = self.DG fname = tmp_path / "el.txt" nx.write_edgelist(G, fname) H = nx.read_edgelist(fname, create_using=nx.DiGraph()) H2 = nx.read_edgelist(fname, create_using=nx.DiGraph()) assert H is not H2 # they should be different graphs G.remove_node("g") # isolated nodes are not written in edgelist assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
def test_edgelist_integers(self, tmp_path): G = nx.convert_node_labels_to_integers(self.G) fname = tmp_path / "el.txt" nx.write_edgelist(G, fname) H = nx.read_edgelist(fname, nodetype=int) # isolated nodes are not written in edgelist G.remove_nodes_from(list(nx.isolates(G))) assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_edgelist_multigraph(self, tmp_path): G = self.XG fname = tmp_path / "el.txt" nx.write_edgelist(G, fname) H = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph()) H2 = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
def test_edgelist_multidigraph(self, tmp_path): G = self.XDG fname = tmp_path / "el.txt" nx.write_edgelist(G, fname) H = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiDiGraph()) H2 = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiDiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True)
def test_edgelist_consistent_strip_handling(): """See gh-7462
Input when printed looks like::
1 2 3 2 3 3 4 3.0
Note the trailing \\t after the `3` in the second row, indicating an empty data value. """ s = io.StringIO("1\t2\t3\n2\t3\t\n3\t4\t3.0") G = nx.parse_edgelist(s, delimiter="\t", nodetype=int, data=[("value", str)]) assert sorted(G.edges(data="value")) == [(1, 2, "3"), (2, 3, ""), (3, 4, "3.0")]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612import ioimport time
import pytest
import networkx as nx
def test_gexf_v1_3(tmp_path): """'Basic graph' example from https://gexf.net/schema.html""" # GEXF file from published example data = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://gexf.net/1.3" version="1.3"> <graph mode="static" defaultedgetype="directed"> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge source="0" target="1" /> </edges> </graph></gexf>""" with open(fname := (tmp_path / "basic.gexf"), "w") as fh: fh.write(data)
# Expected output based on xml input expected = nx.DiGraph([("0", "1")]) nx.set_node_attributes(expected, {"0": "Hello", "1": "Word"}, name="label") expected.graph = {"mode": "static", "edge_default": {}}
# Load example with version explicitly set G = nx.read_gexf(fname, version="1.3") assert nx.utils.graphs_equal(G, expected)
# And with the "default" version G = nx.read_gexf(fname) assert nx.utils.graphs_equal(G, expected)
@pytest.mark.parametrize("time_attr", ("start", "end"))@pytest.mark.parametrize("dyn_attr", ("static", "dynamic"))def test_dynamic_graph_has_timeformat(time_attr, dyn_attr, tmp_path): """Ensure that graphs which have a 'start' or 'stop' attribute get a 'timeformat' attribute upon parsing. See gh-7914.""" G = nx.MultiGraph(mode=dyn_attr) G.add_node(0) G.nodes[0][time_attr] = 1 # Write out fname = tmp_path / "foo.gexf" nx.write_gexf(G, fname) # Check that timeformat is added to saved data with open(fname) as fh: assert 'timeformat="long"' in fh.read() # Round-trip H = nx.read_gexf(fname) # If any node has a "start" or "end" attr, it is considered dynamic # regardless of the graph "mode" attr assert H.graph["mode"] == "dynamic" assert nx.utils.nodes_equal(G.edges, H.edges)
class TestGEXF: @classmethod def setup_class(cls): cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://www.gexf.net/1.2draft" version="1.2"> <graph mode="static" defaultedgetype="directed"> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" /> </edges> </graph></gexf>""" cls.simple_directed_graph = nx.DiGraph() cls.simple_directed_graph.add_node("0", label="Hello") cls.simple_directed_graph.add_node("1", label="World") cls.simple_directed_graph.add_edge("0", "1", id="0")
cls.simple_directed_fh = io.BytesIO(cls.simple_directed_data.encode("UTF-8"))
cls.attribute_data = """<?xml version="1.0" encoding="UTF-8"?>\<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.\org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/\1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2"> <meta lastmodifieddate="2009-03-20"> <creator>Gephi.org</creator> <description>A Web network</description> </meta> <graph defaultedgetype="directed"> <attributes class="node"> <attribute id="0" title="url" type="string"/> <attribute id="1" title="indegree" type="integer"/> <attribute id="2" title="frog" type="boolean"> <default>true</default> </attribute> </attributes> <nodes> <node id="0" label="Gephi"> <attvalues> <attvalue for="0" value="https://gephi.org"/> <attvalue for="1" value="1"/> <attvalue for="2" value="false"/> </attvalues> </node> <node id="1" label="Webatlas"> <attvalues> <attvalue for="0" value="http://webatlas.fr"/> <attvalue for="1" value="2"/> <attvalue for="2" value="false"/> </attvalues> </node> <node id="2" label="RTGI"> <attvalues> <attvalue for="0" value="http://rtgi.fr"/> <attvalue for="1" value="1"/> <attvalue for="2" value="true"/> </attvalues> </node> <node id="3" label="BarabasiLab"> <attvalues> <attvalue for="0" value="http://barabasilab.com"/> <attvalue for="1" value="1"/> <attvalue for="2" value="true"/> </attvalues> </node> </nodes> <edges> <edge id="0" source="0" target="1" label="foo"/> <edge id="1" source="0" target="2"/> <edge id="2" source="1" target="0"/> <edge id="3" source="2" target="1"/> <edge id="4" source="0" target="3"/> </edges> </graph></gexf>""" cls.attribute_graph = nx.DiGraph() cls.attribute_graph.graph["node_default"] = {"frog": True} cls.attribute_graph.add_node( "0", label="Gephi", url="https://gephi.org", indegree=1, frog=False ) cls.attribute_graph.add_node( "1", label="Webatlas", url="http://webatlas.fr", indegree=2, frog=False ) cls.attribute_graph.add_node( "2", label="RTGI", url="http://rtgi.fr", indegree=1, frog=True ) cls.attribute_graph.add_node( "3", label="BarabasiLab", url="http://barabasilab.com", indegree=1, frog=True, ) cls.attribute_graph.add_edge("0", "1", id="0", label="foo") cls.attribute_graph.add_edge("0", "2", id="1") cls.attribute_graph.add_edge("1", "0", id="2") cls.attribute_graph.add_edge("2", "1", id="3") cls.attribute_graph.add_edge("0", "3", id="4") cls.attribute_fh = io.BytesIO(cls.attribute_data.encode("UTF-8"))
cls.simple_undirected_data = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://www.gexf.net/1.2draft" version="1.2"> <graph mode="static" defaultedgetype="undirected"> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" /> </edges> </graph></gexf>""" cls.simple_undirected_graph = nx.Graph() cls.simple_undirected_graph.add_node("0", label="Hello") cls.simple_undirected_graph.add_node("1", label="World") cls.simple_undirected_graph.add_edge("0", "1", id="0")
cls.simple_undirected_fh = io.BytesIO( cls.simple_undirected_data.encode("UTF-8") )
def test_read_simple_directed_graphml(self): G = self.simple_directed_graph H = nx.read_gexf(self.simple_directed_fh) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(G.edges()) == sorted(H.edges()) assert sorted(G.edges(data=True)) == sorted(H.edges(data=True)) self.simple_directed_fh.seek(0)
def test_write_read_simple_directed_graphml(self): G = self.simple_directed_graph fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(G.edges()) == sorted(H.edges()) assert sorted(G.edges(data=True)) == sorted(H.edges(data=True)) self.simple_directed_fh.seek(0)
def test_read_simple_undirected_graphml(self): G = self.simple_undirected_graph H = nx.read_gexf(self.simple_undirected_fh) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) self.simple_undirected_fh.seek(0)
def test_read_attribute_graphml(self): G = self.attribute_graph H = nx.read_gexf(self.attribute_fh) assert sorted(G.nodes(True)) == sorted(H.nodes(data=True)) ge = sorted(G.edges(data=True)) he = sorted(H.edges(data=True)) for a, b in zip(ge, he): assert a == b self.attribute_fh.seek(0)
def test_directed_edge_in_undirected(self): s = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="undirected" name=""> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" type="directed"/> </edges> </graph></gexf>""" fh = io.BytesIO(s.encode("UTF-8")) pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
def test_undirected_edge_in_directed(self): s = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="directed" name=""> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" type="undirected"/> </edges> </graph></gexf>""" fh = io.BytesIO(s.encode("UTF-8")) pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
def test_key_raises(self): s = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="directed" name=""> <nodes> <node id="0" label="Hello"> <attvalues> <attvalue for='0' value='1'/> </attvalues> </node> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" type="undirected"/> </edges> </graph></gexf>""" fh = io.BytesIO(s.encode("UTF-8")) pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
def test_relabel(self): s = """<?xml version="1.0" encoding="UTF-8"?><gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="directed" name=""> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1"/> </edges> </graph></gexf>""" fh = io.BytesIO(s.encode("UTF-8")) G = nx.read_gexf(fh, relabel=True) assert sorted(G.nodes()) == ["Hello", "Word"]
def test_default_attribute(self): G = nx.Graph() G.add_node(1, label="1", color="green") nx.add_path(G, [0, 1, 2, 3]) G.add_edge(1, 2, foo=3) G.graph["node_default"] = {"color": "yellow"} G.graph["edge_default"] = {"foo": 7} fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) # Reading a gexf graph always sets mode attribute to either # 'static' or 'dynamic'. Remove the mode attribute from the # read graph for the sake of comparing remaining attributes. del H.graph["mode"] assert G.graph == H.graph
def test_serialize_ints_to_strings(self): G = nx.Graph() G.add_node(1, id=7, label=77) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert list(H) == [7] assert H.nodes[7]["label"] == "77"
def test_write_with_node_attributes(self): # Addresses #673. G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 3)]) for i in range(4): G.nodes[i]["id"] = i G.nodes[i]["label"] = i G.nodes[i]["pid"] = i G.nodes[i]["start"] = i G.nodes[i]["end"] = i + 1
expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/\gexf.xsd" version="1.2"> <meta lastmodifieddate="{time.strftime("%Y-%m-%d")}"> <creator>NetworkX {nx.__version__}</creator> </meta> <graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long"> <nodes> <node id="0" label="0" pid="0" start="0" end="1" /> <node id="1" label="1" pid="1" start="1" end="2" /> <node id="2" label="2" pid="2" start="2" end="3" /> <node id="3" label="3" pid="3" start="3" end="4" /> </nodes> <edges> <edge source="0" target="1" id="0" /> <edge source="1" target="2" id="1" /> <edge source="2" target="3" id="2" /> </edges> </graph></gexf>""" obtained = "\n".join(nx.generate_gexf(G)) assert expected == obtained
def test_edge_id_construct(self): G = nx.Graph() G.add_edges_from([(0, 1, {"id": 0}), (1, 2, {"id": 2}), (2, 3)])
expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.\gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2"> <meta lastmodifieddate="{time.strftime("%Y-%m-%d")}"> <creator>NetworkX {nx.__version__}</creator> </meta> <graph defaultedgetype="undirected" mode="static" name=""> <nodes> <node id="0" label="0" /> <node id="1" label="1" /> <node id="2" label="2" /> <node id="3" label="3" /> </nodes> <edges> <edge source="0" target="1" id="0" /> <edge source="1" target="2" id="2" /> <edge source="2" target="3" id="1" /> </edges> </graph></gexf>"""
obtained = "\n".join(nx.generate_gexf(G)) assert expected == obtained
def test_numpy_type(self): np = pytest.importorskip("numpy") G = nx.path_graph(4) nx.set_node_attributes(G, {n: n for n in np.arange(4)}, "number") G[0][1]["edge-number"] = np.float64(1.1)
expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft"\ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation\="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd"\ version="1.2"> <meta lastmodifieddate="{time.strftime("%Y-%m-%d")}"> <creator>NetworkX {nx.__version__}</creator> </meta> <graph defaultedgetype="undirected" mode="static" name=""> <attributes mode="static" class="edge"> <attribute id="1" title="edge-number" type="float" /> </attributes> <attributes mode="static" class="node"> <attribute id="0" title="number" type="int" /> </attributes> <nodes> <node id="0" label="0"> <attvalues> <attvalue for="0" value="0" /> </attvalues> </node> <node id="1" label="1"> <attvalues> <attvalue for="0" value="1" /> </attvalues> </node> <node id="2" label="2"> <attvalues> <attvalue for="0" value="2" /> </attvalues> </node> <node id="3" label="3"> <attvalues> <attvalue for="0" value="3" /> </attvalues> </node> </nodes> <edges> <edge source="0" target="1" id="0"> <attvalues> <attvalue for="1" value="1.1" /> </attvalues> </edge> <edge source="1" target="2" id="1" /> <edge source="2" target="3" id="2" /> </edges> </graph></gexf>""" obtained = "\n".join(nx.generate_gexf(G)) assert expected == obtained
def test_bool(self): G = nx.Graph() G.add_node(1, testattr=True) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert H.nodes[1]["testattr"]
# Test for NaN, INF and -INF def test_specials(self): from math import isnan
inf, nan = float("inf"), float("nan") G = nx.Graph() G.add_node(1, testattr=inf, strdata="inf", key="a") G.add_node(2, testattr=nan, strdata="nan", key="b") G.add_node(3, testattr=-inf, strdata="-inf", key="c")
fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) filetext = fh.read() fh.seek(0) H = nx.read_gexf(fh, node_type=int)
assert b"INF" in filetext assert b"NaN" in filetext assert b"-INF" in filetext
assert H.nodes[1]["testattr"] == inf assert isnan(H.nodes[2]["testattr"]) assert H.nodes[3]["testattr"] == -inf
assert H.nodes[1]["strdata"] == "inf" assert H.nodes[2]["strdata"] == "nan" assert H.nodes[3]["strdata"] == "-inf"
assert H.nodes[1]["networkx_key"] == "a" assert H.nodes[2]["networkx_key"] == "b" assert H.nodes[3]["networkx_key"] == "c"
def test_simple_list(self): G = nx.Graph() list_value = [(1, 2, 3), (9, 1, 2)] G.add_node(1, key=list_value) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert H.nodes[1]["networkx_key"] == list_value
def test_dynamic_mode(self): G = nx.Graph() G.add_node(1, label="1", color="green") G.graph["mode"] = "dynamic" fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
def test_multigraph_with_missing_attributes(self): G = nx.MultiGraph() G.add_node(0, label="1", color="green") G.add_node(1, label="2", color="green") G.add_edge(0, 1, id="0", weight=3, type="undirected", start=0, end=1) G.add_edge(0, 1, id="1", label="foo", start=0, end=1) G.add_edge(0, 1) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
def test_missing_viz_attributes(self): G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["viz"] = {"size": 54} G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0} G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256} G.nodes[0]["viz"]["shape"] = "http://random.url" G.nodes[0]["viz"]["thickness"] = 2 fh = io.BytesIO() nx.write_gexf(G, fh, version="1.1draft") fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
# Test missing alpha value for version >draft1.1 - set default alpha value # to 1.0 instead of `None` when writing for better general compatibility fh = io.BytesIO() # G.nodes[0]["viz"]["color"] does not have an alpha value explicitly defined # so the default is used instead nx.write_gexf(G, fh, version="1.2draft") fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert H.nodes[0]["viz"]["color"]["a"] == 1.0
# Second graph for the other branch G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["viz"] = {"size": 54} G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0} G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256, "a": 0.5} G.nodes[0]["viz"]["shape"] = "ftp://random.url" G.nodes[0]["viz"]["thickness"] = 2 fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
def test_slice_and_spell(self): # Test spell first, so version = 1.2 G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["spells"] = [(1, 2)] fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["slices"] = [(1, 2)] fh = io.BytesIO() nx.write_gexf(G, fh, version="1.1draft") fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
def test_add_parent(self): G = nx.Graph() G.add_node(0, label="1", color="green", parents=[1, 2]) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ).gitattributes+6
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/INSTALLERAdded+1
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/METADATAAdded+177
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/RECORDAdded+603
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/REQUESTEDAdded
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/WHEELAdded+5
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/entry_points.txtAdded+2
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txtAdded+37
.venv/lib/python3.12/site-packages/networkx-3.6.1.dist-info/top_level.txtAdded+1
.venv/lib/python3.12/site-packages/networkx/linalg/algebraicconnectivity.pyAdded+650
.venv/lib/python3.12/site-packages/networkx/linalg/attrmatrix.pyAdded+466
.venv/lib/python3.12/site-packages/networkx/linalg/bethehessianmatrix.pyAdded+77
.venv/lib/python3.12/site-packages/networkx/linalg/graphmatrix.pyAdded+168
.venv/lib/python3.12/site-packages/networkx/linalg/laplacianmatrix.pyAdded+512
.venv/lib/python3.12/site-packages/networkx/linalg/modularitymatrix.pyAdded+166
.venv/lib/python3.12/site-packages/networkx/linalg/spectrum.pyAdded+186
.venv/lib/python3.12/site-packages/networkx/linalg/tests/__init__.pyAdded
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_algebraic_connectivity.pyAdded+400
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_attrmatrix.pyAdded+108
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_bethehessian.pyAdded+40
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_graphmatrix.pyAdded+275
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_laplacian.pyAdded+334
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_modularity.pyAdded+86
.venv/lib/python3.12/site-packages/networkx/linalg/tests/test_spectrum.pyAdded+70
.venv/lib/python3.12/site-packages/networkx/readwrite/__init__.pyAdded+17
.venv/lib/python3.12/site-packages/networkx/readwrite/adjlist.pyAdded+330
.venv/lib/python3.12/site-packages/networkx/readwrite/edgelist.pyAdded+489
.venv/lib/python3.12/site-packages/networkx/readwrite/gexf.pyAdded+1084
.venv/lib/python3.12/site-packages/networkx/readwrite/gml.pyAdded+879
.venv/lib/python3.12/site-packages/networkx/readwrite/graph6.pyAdded+427
.venv/lib/python3.12/site-packages/networkx/readwrite/graphml.pyAdded+1053
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/__init__.pyAdded+19
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/adjacency.pyAdded+156
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/cytoscape.pyAdded+190
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/node_link.pyAdded+261
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/__init__.pyAdded
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_adjacency.pyAdded+78
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_cytoscape.pyAdded+78
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_node_link.pyAdded+109
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tests/test_tree.pyAdded+48
.venv/lib/python3.12/site-packages/networkx/readwrite/json_graph/tree.pyAdded+137
.venv/lib/python3.12/site-packages/networkx/readwrite/leda.pyAdded+108
.venv/lib/python3.12/site-packages/networkx/readwrite/multiline_adjlist.pyAdded+393
.venv/lib/python3.12/site-packages/networkx/readwrite/p2g.pyAdded+113
.venv/lib/python3.12/site-packages/networkx/readwrite/pajek.pyAdded+286
.venv/lib/python3.12/site-packages/networkx/readwrite/sparse6.pyAdded+379
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.pyAdded
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.pyAdded+354
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.pyAdded+318
.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.pyAdded+612