aboutsummaryrefslogtreecommitdiff
path: root/.venv/lib/python3.12/site-packages/networkx/readwrite/tests
diff options
context:
space:
mode:
authorS. Solomon Darnell2025-03-28 21:52:21 -0500
committerS. Solomon Darnell2025-03-28 21:52:21 -0500
commit4a52a71956a8d46fcb7294ac71734504bb09bcc2 (patch)
treeee3dc5af3b6313e921cd920906356f5d4febc4ed /.venv/lib/python3.12/site-packages/networkx/readwrite/tests
parentcc961e04ba734dd72309fb548a2f97d67d578813 (diff)
downloadgn-ai-master.tar.gz
two version of R2R are hereHEADmaster
Diffstat (limited to '.venv/lib/python3.12/site-packages/networkx/readwrite/tests')
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.py0
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.py262
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.py314
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.py557
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gml.py744
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graph6.py168
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graphml.py1531
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_leda.py30
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_p2g.py62
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_pajek.py126
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_sparse6.py166
-rw-r--r--.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_text.py1742
12 files changed, 5702 insertions, 0 deletions
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/__init__.py
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.py
new file mode 100644
index 00000000..f2218eba
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_adjlist.py
@@ -0,0 +1,262 @@
+"""
+Unit tests for adjlist.
+"""
+
+import io
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal, graphs_equal, nodes_equal
+
+
+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 line
+1 2
+# comment line
+2
+3
+"""
+ 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()))
+
+ 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()))
+
+ 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()))
+
+ 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()))
+
+ 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)
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.py
new file mode 100644
index 00000000..fe58b3b7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_edgelist.py
@@ -0,0 +1,314 @@
+"""
+Unit tests for edgelists.
+"""
+
+import io
+import textwrap
+
+import pytest
+
+import networkx as nx
+from 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.fixture
+def 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()))
+
+ 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()))
+
+
+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")]
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.py
new file mode 100644
index 00000000..6ff14c99
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gexf.py
@@ -0,0 +1,557 @@
+import io
+import time
+
+import pytest
+
+import networkx as nx
+
+
+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()
+ )
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gml.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gml.py
new file mode 100644
index 00000000..f575ad26
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_gml.py
@@ -0,0 +1,744 @@
+import codecs
+import io
+import math
+from ast import literal_eval
+from contextlib import contextmanager
+from textwrap import dedent
+
+import pytest
+
+import networkx as nx
+from networkx.readwrite.gml import literal_destringizer, literal_stringizer
+
+
+class TestGraph:
+ @classmethod
+ def setup_class(cls):
+ cls.simple_data = """Creator "me"
+Version "xx"
+graph [
+ comment "This is a sample graph"
+ directed 1
+ IsPlanar 1
+ pos [ x 0 y 1 ]
+ node [
+ id 1
+ label "Node 1"
+ pos [ x 1 y 1 ]
+ ]
+ node [
+ id 2
+ pos [ x 1 y 2 ]
+ label "Node 2"
+ ]
+ node [
+ id 3
+ label "Node 3"
+ pos [ x 1 y 3 ]
+ ]
+ edge [
+ source 1
+ target 2
+ label "Edge from node 1 to node 2"
+ color [line "blue" thickness 3]
+
+ ]
+ edge [
+ source 2
+ target 3
+ label "Edge from node 2 to node 3"
+ ]
+ edge [
+ source 3
+ target 1
+ label "Edge from node 3 to node 1"
+ ]
+]
+"""
+
+ def test_parse_gml_cytoscape_bug(self):
+ # example from issue #321, originally #324 in trac
+ cytoscape_example = """
+Creator "Cytoscape"
+Version 1.0
+graph [
+ node [
+ root_index -3
+ id -3
+ graphics [
+ x -96.0
+ y -67.0
+ w 40.0
+ h 40.0
+ fill "#ff9999"
+ type "ellipse"
+ outline "#666666"
+ outline_width 1.5
+ ]
+ label "node2"
+ ]
+ node [
+ root_index -2
+ id -2
+ graphics [
+ x 63.0
+ y 37.0
+ w 40.0
+ h 40.0
+ fill "#ff9999"
+ type "ellipse"
+ outline "#666666"
+ outline_width 1.5
+ ]
+ label "node1"
+ ]
+ node [
+ root_index -1
+ id -1
+ graphics [
+ x -31.0
+ y -17.0
+ w 40.0
+ h 40.0
+ fill "#ff9999"
+ type "ellipse"
+ outline "#666666"
+ outline_width 1.5
+ ]
+ label "node0"
+ ]
+ edge [
+ root_index -2
+ target -2
+ source -1
+ graphics [
+ width 1.5
+ fill "#0000ff"
+ type "line"
+ Line [
+ ]
+ source_arrow 0
+ target_arrow 3
+ ]
+ label "DirectedEdge"
+ ]
+ edge [
+ root_index -1
+ target -1
+ source -3
+ graphics [
+ width 1.5
+ fill "#0000ff"
+ type "line"
+ Line [
+ ]
+ source_arrow 0
+ target_arrow 3
+ ]
+ label "DirectedEdge"
+ ]
+]
+"""
+ nx.parse_gml(cytoscape_example)
+
+ def test_parse_gml(self):
+ G = nx.parse_gml(self.simple_data, label="label")
+ assert sorted(G.nodes()) == ["Node 1", "Node 2", "Node 3"]
+ assert sorted(G.edges()) == [
+ ("Node 1", "Node 2"),
+ ("Node 2", "Node 3"),
+ ("Node 3", "Node 1"),
+ ]
+
+ assert sorted(G.edges(data=True)) == [
+ (
+ "Node 1",
+ "Node 2",
+ {
+ "color": {"line": "blue", "thickness": 3},
+ "label": "Edge from node 1 to node 2",
+ },
+ ),
+ ("Node 2", "Node 3", {"label": "Edge from node 2 to node 3"}),
+ ("Node 3", "Node 1", {"label": "Edge from node 3 to node 1"}),
+ ]
+
+ def test_read_gml(self, tmp_path):
+ fname = tmp_path / "test.gml"
+ with open(fname, "w") as fh:
+ fh.write(self.simple_data)
+ Gin = nx.read_gml(fname, label="label")
+ G = nx.parse_gml(self.simple_data, label="label")
+ assert sorted(G.nodes(data=True)) == sorted(Gin.nodes(data=True))
+ assert sorted(G.edges(data=True)) == sorted(Gin.edges(data=True))
+
+ def test_labels_are_strings(self):
+ # GML requires labels to be strings (i.e., in quotes)
+ answer = """graph [
+ node [
+ id 0
+ label "1203"
+ ]
+]"""
+ G = nx.Graph()
+ G.add_node(1203)
+ data = "\n".join(nx.generate_gml(G, stringizer=literal_stringizer))
+ assert data == answer
+
+ def test_relabel_duplicate(self):
+ data = """
+graph
+[
+ label ""
+ directed 1
+ node
+ [
+ id 0
+ label "same"
+ ]
+ node
+ [
+ id 1
+ label "same"
+ ]
+]
+"""
+ fh = io.BytesIO(data.encode("UTF-8"))
+ fh.seek(0)
+ pytest.raises(nx.NetworkXError, nx.read_gml, fh, label="label")
+
+ @pytest.mark.parametrize("stringizer", (None, literal_stringizer))
+ def test_tuplelabels(self, stringizer):
+ # https://github.com/networkx/networkx/pull/1048
+ # Writing tuple labels to GML failed.
+ G = nx.Graph()
+ G.add_edge((0, 1), (1, 0))
+ data = "\n".join(nx.generate_gml(G, stringizer=stringizer))
+ answer = """graph [
+ node [
+ id 0
+ label "(0,1)"
+ ]
+ node [
+ id 1
+ label "(1,0)"
+ ]
+ edge [
+ source 0
+ target 1
+ ]
+]"""
+ assert data == answer
+
+ def test_quotes(self, tmp_path):
+ # https://github.com/networkx/networkx/issues/1061
+ # Encoding quotes as HTML entities.
+ G = nx.path_graph(1)
+ G.name = "path_graph(1)"
+ attr = 'This is "quoted" and this is a copyright: ' + chr(169)
+ G.nodes[0]["demo"] = attr
+ with open(tmp_path / "test.gml", "w+b") as fobj:
+ nx.write_gml(G, fobj)
+ fobj.seek(0)
+ # Should be bytes in 2.x and 3.x
+ data = fobj.read().strip().decode("ascii")
+ answer = """graph [
+ name "path_graph(1)"
+ node [
+ id 0
+ label "0"
+ demo "This is &#34;quoted&#34; and this is a copyright: &#169;"
+ ]
+]"""
+ assert data == answer
+
+ def test_unicode_node(self, tmp_path):
+ node = "node" + chr(169)
+ G = nx.Graph()
+ G.add_node(node)
+ with open(tmp_path / "test.gml", "w+b") as fobj:
+ nx.write_gml(G, fobj)
+ fobj.seek(0)
+ # Should be bytes in 2.x and 3.x
+ data = fobj.read().strip().decode("ascii")
+ answer = """graph [
+ node [
+ id 0
+ label "node&#169;"
+ ]
+]"""
+ assert data == answer
+
+ def test_float_label(self, tmp_path):
+ node = 1.0
+ G = nx.Graph()
+ G.add_node(node)
+ with open(tmp_path / "test.gml", "w+b") as fobj:
+ nx.write_gml(G, fobj)
+ fobj.seek(0)
+ # Should be bytes in 2.x and 3.x
+ data = fobj.read().strip().decode("ascii")
+ answer = """graph [
+ node [
+ id 0
+ label "1.0"
+ ]
+]"""
+ assert data == answer
+
+ def test_special_float_label(self, tmp_path):
+ special_floats = [float("nan"), float("+inf"), float("-inf")]
+ try:
+ import numpy as np
+
+ special_floats += [np.nan, np.inf, np.inf * -1]
+ except ImportError:
+ special_floats += special_floats
+
+ G = nx.cycle_graph(len(special_floats))
+ attrs = dict(enumerate(special_floats))
+ nx.set_node_attributes(G, attrs, "nodefloat")
+ edges = list(G.edges)
+ attrs = {edges[i]: value for i, value in enumerate(special_floats)}
+ nx.set_edge_attributes(G, attrs, "edgefloat")
+
+ with open(tmp_path / "test.gml", "w+b") as fobj:
+ nx.write_gml(G, fobj)
+ fobj.seek(0)
+ # Should be bytes in 2.x and 3.x
+ data = fobj.read().strip().decode("ascii")
+ answer = """graph [
+ node [
+ id 0
+ label "0"
+ nodefloat NAN
+ ]
+ node [
+ id 1
+ label "1"
+ nodefloat +INF
+ ]
+ node [
+ id 2
+ label "2"
+ nodefloat -INF
+ ]
+ node [
+ id 3
+ label "3"
+ nodefloat NAN
+ ]
+ node [
+ id 4
+ label "4"
+ nodefloat +INF
+ ]
+ node [
+ id 5
+ label "5"
+ nodefloat -INF
+ ]
+ edge [
+ source 0
+ target 1
+ edgefloat NAN
+ ]
+ edge [
+ source 0
+ target 5
+ edgefloat +INF
+ ]
+ edge [
+ source 1
+ target 2
+ edgefloat -INF
+ ]
+ edge [
+ source 2
+ target 3
+ edgefloat NAN
+ ]
+ edge [
+ source 3
+ target 4
+ edgefloat +INF
+ ]
+ edge [
+ source 4
+ target 5
+ edgefloat -INF
+ ]
+]"""
+ assert data == answer
+
+ fobj.seek(0)
+ graph = nx.read_gml(fobj)
+ for indx, value in enumerate(special_floats):
+ node_value = graph.nodes[str(indx)]["nodefloat"]
+ if math.isnan(value):
+ assert math.isnan(node_value)
+ else:
+ assert node_value == value
+
+ edge = edges[indx]
+ string_edge = (str(edge[0]), str(edge[1]))
+ edge_value = graph.edges[string_edge]["edgefloat"]
+ if math.isnan(value):
+ assert math.isnan(edge_value)
+ else:
+ assert edge_value == value
+
+ def test_name(self):
+ G = nx.parse_gml('graph [ name "x" node [ id 0 label "x" ] ]')
+ assert "x" == G.graph["name"]
+ G = nx.parse_gml('graph [ node [ id 0 label "x" ] ]')
+ assert "" == G.name
+ assert "name" not in G.graph
+
+ def test_graph_types(self):
+ for directed in [None, False, True]:
+ for multigraph in [None, False, True]:
+ gml = "graph ["
+ if directed is not None:
+ gml += " directed " + str(int(directed))
+ if multigraph is not None:
+ gml += " multigraph " + str(int(multigraph))
+ gml += ' node [ id 0 label "0" ]'
+ gml += " edge [ source 0 target 0 ]"
+ gml += " ]"
+ G = nx.parse_gml(gml)
+ assert bool(directed) == G.is_directed()
+ assert bool(multigraph) == G.is_multigraph()
+ gml = "graph [\n"
+ if directed is True:
+ gml += " directed 1\n"
+ if multigraph is True:
+ gml += " multigraph 1\n"
+ gml += """ node [
+ id 0
+ label "0"
+ ]
+ edge [
+ source 0
+ target 0
+"""
+ if multigraph:
+ gml += " key 0\n"
+ gml += " ]\n]"
+ assert gml == "\n".join(nx.generate_gml(G))
+
+ def test_data_types(self):
+ data = [
+ True,
+ False,
+ 10**20,
+ -2e33,
+ "'",
+ '"&&amp;&&#34;"',
+ [{(b"\xfd",): "\x7f", chr(0x4444): (1, 2)}, (2, "3")],
+ ]
+ data.append(chr(0x14444))
+ data.append(literal_eval("{2.3j, 1 - 2.3j, ()}"))
+ G = nx.Graph()
+ G.name = data
+ G.graph["data"] = data
+ G.add_node(0, int=-1, data={"data": data})
+ G.add_edge(0, 0, float=-2.5, data=data)
+ gml = "\n".join(nx.generate_gml(G, stringizer=literal_stringizer))
+ G = nx.parse_gml(gml, destringizer=literal_destringizer)
+ assert data == G.name
+ assert {"name": data, "data": data} == G.graph
+ assert list(G.nodes(data=True)) == [(0, {"int": -1, "data": {"data": data}})]
+ assert list(G.edges(data=True)) == [(0, 0, {"float": -2.5, "data": data})]
+ G = nx.Graph()
+ G.graph["data"] = "frozenset([1, 2, 3])"
+ G = nx.parse_gml(nx.generate_gml(G), destringizer=literal_eval)
+ assert G.graph["data"] == "frozenset([1, 2, 3])"
+
+ def test_escape_unescape(self):
+ gml = """graph [
+ name "&amp;&#34;&#xf;&#x4444;&#1234567890;&#x1234567890abcdef;&unknown;"
+]"""
+ G = nx.parse_gml(gml)
+ assert (
+ '&"\x0f' + chr(0x4444) + "&#1234567890;&#x1234567890abcdef;&unknown;"
+ == G.name
+ )
+ gml = "\n".join(nx.generate_gml(G))
+ alnu = "#1234567890;&#38;#x1234567890abcdef"
+ answer = (
+ """graph [
+ name "&#38;&#34;&#15;&#17476;&#38;"""
+ + alnu
+ + """;&#38;unknown;"
+]"""
+ )
+ assert answer == gml
+
+ def test_exceptions(self, tmp_path):
+ pytest.raises(ValueError, literal_destringizer, "(")
+ pytest.raises(ValueError, literal_destringizer, "frozenset([1, 2, 3])")
+ pytest.raises(ValueError, literal_destringizer, literal_destringizer)
+ pytest.raises(ValueError, literal_stringizer, frozenset([1, 2, 3]))
+ pytest.raises(ValueError, literal_stringizer, literal_stringizer)
+ with open(tmp_path / "test.gml", "w+b") as f:
+ f.write(codecs.BOM_UTF8 + b"graph[]")
+ f.seek(0)
+ pytest.raises(nx.NetworkXError, nx.read_gml, f)
+
+ def assert_parse_error(gml):
+ pytest.raises(nx.NetworkXError, nx.parse_gml, gml)
+
+ assert_parse_error(["graph [\n\n", "]"])
+ assert_parse_error("")
+ assert_parse_error('Creator ""')
+ assert_parse_error("0")
+ assert_parse_error("graph ]")
+ assert_parse_error("graph [ 1 ]")
+ assert_parse_error("graph [ 1.E+2 ]")
+ assert_parse_error('graph [ "A" ]')
+ assert_parse_error("graph [ ] graph ]")
+ assert_parse_error("graph [ ] graph [ ]")
+ assert_parse_error("graph [ data [1, 2, 3] ]")
+ assert_parse_error("graph [ node [ ] ]")
+ assert_parse_error("graph [ node [ id 0 ] ]")
+ nx.parse_gml('graph [ node [ id "a" ] ]', label="id")
+ assert_parse_error("graph [ node [ id 0 label 0 ] node [ id 0 label 1 ] ]")
+ assert_parse_error("graph [ node [ id 0 label 0 ] node [ id 1 label 0 ] ]")
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ ] ]")
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 0 ] ]")
+ nx.parse_gml("graph [edge [ source 0 target 0 ] node [ id 0 label 0 ] ]")
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 1 target 0 ] ]")
+ assert_parse_error("graph [ node [ id 0 label 0 ] edge [ source 0 target 1 ] ]")
+ assert_parse_error(
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
+ "edge [ source 0 target 1 ] edge [ source 1 target 0 ] ]"
+ )
+ nx.parse_gml(
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
+ "edge [ source 0 target 1 ] edge [ source 1 target 0 ] "
+ "directed 1 ]"
+ )
+ nx.parse_gml(
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
+ "edge [ source 0 target 1 ] edge [ source 0 target 1 ]"
+ "multigraph 1 ]"
+ )
+ nx.parse_gml(
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
+ "edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 ]"
+ "multigraph 1 ]"
+ )
+ assert_parse_error(
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
+ "edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 0 ]"
+ "multigraph 1 ]"
+ )
+ nx.parse_gml(
+ "graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] "
+ "edge [ source 0 target 1 key 0 ] edge [ source 1 target 0 key 0 ]"
+ "directed 1 multigraph 1 ]"
+ )
+
+ # Tests for string convertible alphanumeric id and label values
+ nx.parse_gml("graph [edge [ source a target a ] node [ id a label b ] ]")
+ nx.parse_gml(
+ "graph [ node [ id n42 label 0 ] node [ id x43 label 1 ]"
+ "edge [ source n42 target x43 key 0 ]"
+ "edge [ source x43 target n42 key 0 ]"
+ "directed 1 multigraph 1 ]"
+ )
+ assert_parse_error(
+ "graph [edge [ source '\u4200' target '\u4200' ] "
+ + "node [ id '\u4200' label b ] ]"
+ )
+
+ def assert_generate_error(*args, **kwargs):
+ pytest.raises(
+ nx.NetworkXError, lambda: list(nx.generate_gml(*args, **kwargs))
+ )
+
+ G = nx.Graph()
+ G.graph[3] = 3
+ assert_generate_error(G)
+ G = nx.Graph()
+ G.graph["3"] = 3
+ assert_generate_error(G)
+ G = nx.Graph()
+ G.graph["data"] = frozenset([1, 2, 3])
+ assert_generate_error(G, stringizer=literal_stringizer)
+
+ def test_label_kwarg(self):
+ G = nx.parse_gml(self.simple_data, label="id")
+ assert sorted(G.nodes) == [1, 2, 3]
+ labels = [G.nodes[n]["label"] for n in sorted(G.nodes)]
+ assert labels == ["Node 1", "Node 2", "Node 3"]
+
+ G = nx.parse_gml(self.simple_data, label=None)
+ assert sorted(G.nodes) == [1, 2, 3]
+ labels = [G.nodes[n]["label"] for n in sorted(G.nodes)]
+ assert labels == ["Node 1", "Node 2", "Node 3"]
+
+ def test_outofrange_integers(self, tmp_path):
+ # GML restricts integers to 32 signed bits.
+ # Check that we honor this restriction on export
+ G = nx.Graph()
+ # Test export for numbers that barely fit or don't fit into 32 bits,
+ # and 3 numbers in the middle
+ numbers = {
+ "toosmall": (-(2**31)) - 1,
+ "small": -(2**31),
+ "med1": -4,
+ "med2": 0,
+ "med3": 17,
+ "big": (2**31) - 1,
+ "toobig": 2**31,
+ }
+ G.add_node("Node", **numbers)
+
+ fname = tmp_path / "test.gml"
+ nx.write_gml(G, fname)
+ # Check that the export wrote the nonfitting numbers as strings
+ G2 = nx.read_gml(fname)
+ for attr, value in G2.nodes["Node"].items():
+ if attr == "toosmall" or attr == "toobig":
+ assert type(value) == str
+ else:
+ assert type(value) == int
+
+ def test_multiline(self):
+ # example from issue #6836
+ multiline_example = """
+graph
+[
+ node
+ [
+ id 0
+ label "multiline node"
+ label2 "multiline1
+ multiline2
+ multiline3"
+ alt_name "id 0"
+ ]
+]
+"""
+ G = nx.parse_gml(multiline_example)
+ assert G.nodes["multiline node"] == {
+ "label2": "multiline1 multiline2 multiline3",
+ "alt_name": "id 0",
+ }
+
+
+@contextmanager
+def byte_file():
+ _file_handle = io.BytesIO()
+ yield _file_handle
+ _file_handle.seek(0)
+
+
+class TestPropertyLists:
+ def test_writing_graph_with_multi_element_property_list(self):
+ g = nx.Graph()
+ g.add_node("n1", properties=["element", 0, 1, 2.5, True, False])
+ with byte_file() as f:
+ nx.write_gml(g, f)
+ result = f.read().decode()
+
+ assert result == dedent(
+ """\
+ graph [
+ node [
+ id 0
+ label "n1"
+ properties "element"
+ properties 0
+ properties 1
+ properties 2.5
+ properties 1
+ properties 0
+ ]
+ ]
+ """
+ )
+
+ def test_writing_graph_with_one_element_property_list(self):
+ g = nx.Graph()
+ g.add_node("n1", properties=["element"])
+ with byte_file() as f:
+ nx.write_gml(g, f)
+ result = f.read().decode()
+
+ assert result == dedent(
+ """\
+ graph [
+ node [
+ id 0
+ label "n1"
+ properties "_networkx_list_start"
+ properties "element"
+ ]
+ ]
+ """
+ )
+
+ def test_reading_graph_with_list_property(self):
+ with byte_file() as f:
+ f.write(
+ dedent(
+ """
+ graph [
+ node [
+ id 0
+ label "n1"
+ properties "element"
+ properties 0
+ properties 1
+ properties 2.5
+ ]
+ ]
+ """
+ ).encode("ascii")
+ )
+ f.seek(0)
+ graph = nx.read_gml(f)
+ assert graph.nodes(data=True)["n1"] == {"properties": ["element", 0, 1, 2.5]}
+
+ def test_reading_graph_with_single_element_list_property(self):
+ with byte_file() as f:
+ f.write(
+ dedent(
+ """
+ graph [
+ node [
+ id 0
+ label "n1"
+ properties "_networkx_list_start"
+ properties "element"
+ ]
+ ]
+ """
+ ).encode("ascii")
+ )
+ f.seek(0)
+ graph = nx.read_gml(f)
+ assert graph.nodes(data=True)["n1"] == {"properties": ["element"]}
+
+
+@pytest.mark.parametrize("coll", ([], ()))
+def test_stringize_empty_list_tuple(coll):
+ G = nx.path_graph(2)
+ G.nodes[0]["test"] = coll # test serializing an empty collection
+ f = io.BytesIO()
+ nx.write_gml(G, f) # Smoke test - should not raise
+ f.seek(0)
+ H = nx.read_gml(f)
+ assert H.nodes["0"]["test"] == coll # Check empty list round-trips properly
+ # Check full round-tripping. Note that nodes are loaded as strings by
+ # default, so there needs to be some remapping prior to comparison
+ H = nx.relabel_nodes(H, {"0": 0, "1": 1})
+ assert nx.utils.graphs_equal(G, H)
+ # Same as above, but use destringizer for node remapping. Should have no
+ # effect on node attr
+ f.seek(0)
+ H = nx.read_gml(f, destringizer=int)
+ assert nx.utils.graphs_equal(G, H)
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graph6.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graph6.py
new file mode 100644
index 00000000..a8032694
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graph6.py
@@ -0,0 +1,168 @@
+from io import BytesIO
+
+import pytest
+
+import networkx as nx
+import networkx.readwrite.graph6 as g6
+from networkx.utils import edges_equal, nodes_equal
+
+
+class TestGraph6Utils:
+ def test_n_data_n_conversion(self):
+ for i in [0, 1, 42, 62, 63, 64, 258047, 258048, 7744773, 68719476735]:
+ assert g6.data_to_n(g6.n_to_data(i))[0] == i
+ assert g6.data_to_n(g6.n_to_data(i))[1] == []
+ assert g6.data_to_n(g6.n_to_data(i) + [42, 43])[1] == [42, 43]
+
+
+class TestFromGraph6Bytes:
+ def test_from_graph6_bytes(self):
+ data = b"DF{"
+ G = nx.from_graph6_bytes(data)
+ assert nodes_equal(G.nodes(), [0, 1, 2, 3, 4])
+ assert edges_equal(
+ G.edges(), [(0, 3), (0, 4), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
+ )
+
+ def test_read_equals_from_bytes(self):
+ data = b"DF{"
+ G = nx.from_graph6_bytes(data)
+ fh = BytesIO(data)
+ Gin = nx.read_graph6(fh)
+ assert nodes_equal(G.nodes(), Gin.nodes())
+ assert edges_equal(G.edges(), Gin.edges())
+
+
+class TestReadGraph6:
+ def test_read_many_graph6(self):
+ """Test for reading many graphs from a file into a list."""
+ data = b"DF{\nD`{\nDqK\nD~{\n"
+ fh = BytesIO(data)
+ glist = nx.read_graph6(fh)
+ assert len(glist) == 4
+ for G in glist:
+ assert sorted(G) == list(range(5))
+
+
+class TestWriteGraph6:
+ """Unit tests for writing a graph to a file in graph6 format."""
+
+ def test_null_graph(self):
+ result = BytesIO()
+ nx.write_graph6(nx.null_graph(), result)
+ assert result.getvalue() == b">>graph6<<?\n"
+
+ def test_trivial_graph(self):
+ result = BytesIO()
+ nx.write_graph6(nx.trivial_graph(), result)
+ assert result.getvalue() == b">>graph6<<@\n"
+
+ def test_complete_graph(self):
+ result = BytesIO()
+ nx.write_graph6(nx.complete_graph(4), result)
+ assert result.getvalue() == b">>graph6<<C~\n"
+
+ def test_large_complete_graph(self):
+ result = BytesIO()
+ nx.write_graph6(nx.complete_graph(67), result, header=False)
+ assert result.getvalue() == b"~?@B" + b"~" * 368 + b"w\n"
+
+ def test_no_header(self):
+ result = BytesIO()
+ nx.write_graph6(nx.complete_graph(4), result, header=False)
+ assert result.getvalue() == b"C~\n"
+
+ def test_complete_bipartite_graph(self):
+ result = BytesIO()
+ G = nx.complete_bipartite_graph(6, 9)
+ nx.write_graph6(G, result, header=False)
+ # The expected encoding here was verified by Sage.
+ assert result.getvalue() == b"N??F~z{~Fw^_~?~?^_?\n"
+
+ @pytest.mark.parametrize("G", (nx.MultiGraph(), nx.DiGraph()))
+ def test_no_directed_or_multi_graphs(self, G):
+ with pytest.raises(nx.NetworkXNotImplemented):
+ nx.write_graph6(G, BytesIO())
+
+ def test_length(self):
+ for i in list(range(13)) + [31, 47, 62, 63, 64, 72]:
+ g = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i)
+ gstr = BytesIO()
+ nx.write_graph6(g, gstr, header=False)
+ # Strip the trailing newline.
+ gstr = gstr.getvalue().rstrip()
+ assert len(gstr) == ((i - 1) * i // 2 + 5) // 6 + (1 if i < 63 else 4)
+
+ def test_roundtrip(self):
+ for i in list(range(13)) + [31, 47, 62, 63, 64, 72]:
+ G = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i)
+ f = BytesIO()
+ nx.write_graph6(G, f)
+ f.seek(0)
+ H = nx.read_graph6(f)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+
+ def test_write_path(self, tmp_path):
+ with open(tmp_path / "test.g6", "w+b") as f:
+ g6.write_graph6_file(nx.null_graph(), f)
+ f.seek(0)
+ assert f.read() == b">>graph6<<?\n"
+
+ @pytest.mark.parametrize("edge", ((0, 1), (1, 2), (1, 42)))
+ def test_relabeling(self, edge):
+ G = nx.Graph([edge])
+ f = BytesIO()
+ nx.write_graph6(G, f)
+ f.seek(0)
+ assert f.read() == b">>graph6<<A_\n"
+
+
+class TestToGraph6Bytes:
+ def test_null_graph(self):
+ G = nx.null_graph()
+ assert g6.to_graph6_bytes(G) == b">>graph6<<?\n"
+
+ def test_trivial_graph(self):
+ G = nx.trivial_graph()
+ assert g6.to_graph6_bytes(G) == b">>graph6<<@\n"
+
+ def test_complete_graph(self):
+ assert g6.to_graph6_bytes(nx.complete_graph(4)) == b">>graph6<<C~\n"
+
+ def test_large_complete_graph(self):
+ G = nx.complete_graph(67)
+ assert g6.to_graph6_bytes(G, header=False) == b"~?@B" + b"~" * 368 + b"w\n"
+
+ def test_no_header(self):
+ G = nx.complete_graph(4)
+ assert g6.to_graph6_bytes(G, header=False) == b"C~\n"
+
+ def test_complete_bipartite_graph(self):
+ G = nx.complete_bipartite_graph(6, 9)
+ assert g6.to_graph6_bytes(G, header=False) == b"N??F~z{~Fw^_~?~?^_?\n"
+
+ @pytest.mark.parametrize("G", (nx.MultiGraph(), nx.DiGraph()))
+ def test_no_directed_or_multi_graphs(self, G):
+ with pytest.raises(nx.NetworkXNotImplemented):
+ g6.to_graph6_bytes(G)
+
+ def test_length(self):
+ for i in list(range(13)) + [31, 47, 62, 63, 64, 72]:
+ G = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i)
+ # Strip the trailing newline.
+ gstr = g6.to_graph6_bytes(G, header=False).rstrip()
+ assert len(gstr) == ((i - 1) * i // 2 + 5) // 6 + (1 if i < 63 else 4)
+
+ def test_roundtrip(self):
+ for i in list(range(13)) + [31, 47, 62, 63, 64, 72]:
+ G = nx.random_graphs.gnm_random_graph(i, i * i // 4, seed=i)
+ data = g6.to_graph6_bytes(G)
+ H = nx.from_graph6_bytes(data.rstrip())
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+
+ @pytest.mark.parametrize("edge", ((0, 1), (1, 2), (1, 42)))
+ def test_relabeling(self, edge):
+ G = nx.Graph([edge])
+ assert g6.to_graph6_bytes(G) == b">>graph6<<A_\n"
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graphml.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graphml.py
new file mode 100644
index 00000000..5ffa837e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_graphml.py
@@ -0,0 +1,1531 @@
+import io
+
+import pytest
+
+import networkx as nx
+from networkx.readwrite.graphml import GraphMLWriter
+from networkx.utils import edges_equal, nodes_equal
+
+
+class BaseGraphML:
+ @classmethod
+ def setup_class(cls):
+ cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?>
+<!-- This file was written by the JAVA GraphML Library.-->
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G" edgedefault="directed">
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <node id="n3"/>
+ <node id="n4"/>
+ <node id="n5"/>
+ <node id="n6"/>
+ <node id="n7"/>
+ <node id="n8"/>
+ <node id="n9"/>
+ <node id="n10"/>
+ <edge id="foo" source="n0" target="n2"/>
+ <edge source="n1" target="n2"/>
+ <edge source="n2" target="n3"/>
+ <edge source="n3" target="n5"/>
+ <edge source="n3" target="n4"/>
+ <edge source="n4" target="n6"/>
+ <edge source="n6" target="n5"/>
+ <edge source="n5" target="n7"/>
+ <edge source="n6" target="n8"/>
+ <edge source="n8" target="n7"/>
+ <edge source="n8" target="n9"/>
+ </graph>
+</graphml>"""
+ cls.simple_directed_graph = nx.DiGraph()
+ cls.simple_directed_graph.add_node("n10")
+ cls.simple_directed_graph.add_edge("n0", "n2", id="foo")
+ cls.simple_directed_graph.add_edge("n0", "n2")
+ cls.simple_directed_graph.add_edges_from(
+ [
+ ("n1", "n2"),
+ ("n2", "n3"),
+ ("n3", "n5"),
+ ("n3", "n4"),
+ ("n4", "n6"),
+ ("n6", "n5"),
+ ("n5", "n7"),
+ ("n6", "n8"),
+ ("n8", "n7"),
+ ("n8", "n9"),
+ ]
+ )
+ cls.simple_directed_fh = io.BytesIO(cls.simple_directed_data.encode("UTF-8"))
+
+ cls.attribute_data = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="d0" for="node" attr.name="color" attr.type="string">
+ <default>yellow</default>
+ </key>
+ <key id="d1" for="edge" attr.name="weight" attr.type="double"/>
+ <graph id="G" edgedefault="directed">
+ <node id="n0">
+ <data key="d0">green</data>
+ </node>
+ <node id="n1"/>
+ <node id="n2">
+ <data key="d0">blue</data>
+ </node>
+ <node id="n3">
+ <data key="d0">red</data>
+ </node>
+ <node id="n4"/>
+ <node id="n5">
+ <data key="d0">turquoise</data>
+ </node>
+ <edge id="e0" source="n0" target="n2">
+ <data key="d1">1.0</data>
+ </edge>
+ <edge id="e1" source="n0" target="n1">
+ <data key="d1">1.0</data>
+ </edge>
+ <edge id="e2" source="n1" target="n3">
+ <data key="d1">2.0</data>
+ </edge>
+ <edge id="e3" source="n3" target="n2"/>
+ <edge id="e4" source="n2" target="n4"/>
+ <edge id="e5" source="n3" target="n5"/>
+ <edge id="e6" source="n5" target="n4">
+ <data key="d1">1.1</data>
+ </edge>
+ </graph>
+</graphml>
+"""
+ cls.attribute_graph = nx.DiGraph(id="G")
+ cls.attribute_graph.graph["node_default"] = {"color": "yellow"}
+ cls.attribute_graph.add_node("n0", color="green")
+ cls.attribute_graph.add_node("n2", color="blue")
+ cls.attribute_graph.add_node("n3", color="red")
+ cls.attribute_graph.add_node("n4")
+ cls.attribute_graph.add_node("n5", color="turquoise")
+ cls.attribute_graph.add_edge("n0", "n2", id="e0", weight=1.0)
+ cls.attribute_graph.add_edge("n0", "n1", id="e1", weight=1.0)
+ cls.attribute_graph.add_edge("n1", "n3", id="e2", weight=2.0)
+ cls.attribute_graph.add_edge("n3", "n2", id="e3")
+ cls.attribute_graph.add_edge("n2", "n4", id="e4")
+ cls.attribute_graph.add_edge("n3", "n5", id="e5")
+ cls.attribute_graph.add_edge("n5", "n4", id="e6", weight=1.1)
+ cls.attribute_fh = io.BytesIO(cls.attribute_data.encode("UTF-8"))
+
+ cls.node_attribute_default_data = """<?xml version="1.0" encoding="UTF-8"?>
+ <graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="d0" for="node" attr.name="boolean_attribute" attr.type="boolean"><default>false</default></key>
+ <key id="d1" for="node" attr.name="int_attribute" attr.type="int"><default>0</default></key>
+ <key id="d2" for="node" attr.name="long_attribute" attr.type="long"><default>0</default></key>
+ <key id="d3" for="node" attr.name="float_attribute" attr.type="float"><default>0.0</default></key>
+ <key id="d4" for="node" attr.name="double_attribute" attr.type="double"><default>0.0</default></key>
+ <key id="d5" for="node" attr.name="string_attribute" attr.type="string"><default>Foo</default></key>
+ <graph id="G" edgedefault="directed">
+ <node id="n0"/>
+ <node id="n1"/>
+ <edge id="e0" source="n0" target="n1"/>
+ </graph>
+ </graphml>
+ """
+ cls.node_attribute_default_graph = nx.DiGraph(id="G")
+ cls.node_attribute_default_graph.graph["node_default"] = {
+ "boolean_attribute": False,
+ "int_attribute": 0,
+ "long_attribute": 0,
+ "float_attribute": 0.0,
+ "double_attribute": 0.0,
+ "string_attribute": "Foo",
+ }
+ cls.node_attribute_default_graph.add_node("n0")
+ cls.node_attribute_default_graph.add_node("n1")
+ cls.node_attribute_default_graph.add_edge("n0", "n1", id="e0")
+ cls.node_attribute_default_fh = io.BytesIO(
+ cls.node_attribute_default_data.encode("UTF-8")
+ )
+
+ cls.attribute_named_key_ids_data = """<?xml version='1.0' encoding='utf-8'?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="edge_prop" for="edge" attr.name="edge_prop" attr.type="string"/>
+ <key id="prop2" for="node" attr.name="prop2" attr.type="string"/>
+ <key id="prop1" for="node" attr.name="prop1" attr.type="string"/>
+ <graph edgedefault="directed">
+ <node id="0">
+ <data key="prop1">val1</data>
+ <data key="prop2">val2</data>
+ </node>
+ <node id="1">
+ <data key="prop1">val_one</data>
+ <data key="prop2">val2</data>
+ </node>
+ <edge source="0" target="1">
+ <data key="edge_prop">edge_value</data>
+ </edge>
+ </graph>
+</graphml>
+"""
+ cls.attribute_named_key_ids_graph = nx.DiGraph()
+ cls.attribute_named_key_ids_graph.add_node("0", prop1="val1", prop2="val2")
+ cls.attribute_named_key_ids_graph.add_node("1", prop1="val_one", prop2="val2")
+ cls.attribute_named_key_ids_graph.add_edge("0", "1", edge_prop="edge_value")
+ fh = io.BytesIO(cls.attribute_named_key_ids_data.encode("UTF-8"))
+ cls.attribute_named_key_ids_fh = fh
+
+ cls.attribute_numeric_type_data = """<?xml version='1.0' encoding='utf-8'?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key attr.name="weight" attr.type="double" for="node" id="d1" />
+ <key attr.name="weight" attr.type="double" for="edge" id="d0" />
+ <graph edgedefault="directed">
+ <node id="n0">
+ <data key="d1">1</data>
+ </node>
+ <node id="n1">
+ <data key="d1">2.0</data>
+ </node>
+ <edge source="n0" target="n1">
+ <data key="d0">1</data>
+ </edge>
+ <edge source="n1" target="n0">
+ <data key="d0">k</data>
+ </edge>
+ <edge source="n1" target="n1">
+ <data key="d0">1.0</data>
+ </edge>
+ </graph>
+</graphml>
+"""
+ cls.attribute_numeric_type_graph = nx.DiGraph()
+ cls.attribute_numeric_type_graph.add_node("n0", weight=1)
+ cls.attribute_numeric_type_graph.add_node("n1", weight=2.0)
+ cls.attribute_numeric_type_graph.add_edge("n0", "n1", weight=1)
+ cls.attribute_numeric_type_graph.add_edge("n1", "n1", weight=1.0)
+ fh = io.BytesIO(cls.attribute_numeric_type_data.encode("UTF-8"))
+ cls.attribute_numeric_type_fh = fh
+
+ cls.simple_undirected_data = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G">
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <node id="n10"/>
+ <edge id="foo" source="n0" target="n2"/>
+ <edge source="n1" target="n2"/>
+ <edge source="n2" target="n3"/>
+ </graph>
+</graphml>"""
+ # <edge source="n8" target="n10" directed="false"/>
+ cls.simple_undirected_graph = nx.Graph()
+ cls.simple_undirected_graph.add_node("n10")
+ cls.simple_undirected_graph.add_edge("n0", "n2", id="foo")
+ cls.simple_undirected_graph.add_edges_from([("n1", "n2"), ("n2", "n3")])
+ fh = io.BytesIO(cls.simple_undirected_data.encode("UTF-8"))
+ cls.simple_undirected_fh = fh
+
+ cls.undirected_multigraph_data = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G">
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <node id="n10"/>
+ <edge id="e0" source="n0" target="n2"/>
+ <edge id="e1" source="n1" target="n2"/>
+ <edge id="e2" source="n2" target="n1"/>
+ </graph>
+</graphml>"""
+ cls.undirected_multigraph = nx.MultiGraph()
+ cls.undirected_multigraph.add_node("n10")
+ cls.undirected_multigraph.add_edge("n0", "n2", id="e0")
+ cls.undirected_multigraph.add_edge("n1", "n2", id="e1")
+ cls.undirected_multigraph.add_edge("n2", "n1", id="e2")
+ fh = io.BytesIO(cls.undirected_multigraph_data.encode("UTF-8"))
+ cls.undirected_multigraph_fh = fh
+
+ cls.undirected_multigraph_no_multiedge_data = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G">
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <node id="n10"/>
+ <edge id="e0" source="n0" target="n2"/>
+ <edge id="e1" source="n1" target="n2"/>
+ <edge id="e2" source="n2" target="n3"/>
+ </graph>
+</graphml>"""
+ cls.undirected_multigraph_no_multiedge = nx.MultiGraph()
+ cls.undirected_multigraph_no_multiedge.add_node("n10")
+ cls.undirected_multigraph_no_multiedge.add_edge("n0", "n2", id="e0")
+ cls.undirected_multigraph_no_multiedge.add_edge("n1", "n2", id="e1")
+ cls.undirected_multigraph_no_multiedge.add_edge("n2", "n3", id="e2")
+ fh = io.BytesIO(cls.undirected_multigraph_no_multiedge_data.encode("UTF-8"))
+ cls.undirected_multigraph_no_multiedge_fh = fh
+
+ cls.multigraph_only_ids_for_multiedges_data = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G">
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <node id="n10"/>
+ <edge source="n0" target="n2"/>
+ <edge id="e1" source="n1" target="n2"/>
+ <edge id="e2" source="n2" target="n1"/>
+ </graph>
+</graphml>"""
+ cls.multigraph_only_ids_for_multiedges = nx.MultiGraph()
+ cls.multigraph_only_ids_for_multiedges.add_node("n10")
+ cls.multigraph_only_ids_for_multiedges.add_edge("n0", "n2")
+ cls.multigraph_only_ids_for_multiedges.add_edge("n1", "n2", id="e1")
+ cls.multigraph_only_ids_for_multiedges.add_edge("n2", "n1", id="e2")
+ fh = io.BytesIO(cls.multigraph_only_ids_for_multiedges_data.encode("UTF-8"))
+ cls.multigraph_only_ids_for_multiedges_fh = fh
+
+
+class TestReadGraphML(BaseGraphML):
+ def test_read_simple_directed_graphml(self):
+ G = self.simple_directed_graph
+ H = nx.read_graphml(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)
+
+ PG = nx.parse_graphml(self.simple_directed_data)
+ assert sorted(G.nodes()) == sorted(PG.nodes())
+ assert sorted(G.edges()) == sorted(PG.edges())
+ assert sorted(G.edges(data=True)) == sorted(PG.edges(data=True))
+
+ def test_read_simple_undirected_graphml(self):
+ G = self.simple_undirected_graph
+ H = nx.read_graphml(self.simple_undirected_fh)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ self.simple_undirected_fh.seek(0)
+
+ PG = nx.parse_graphml(self.simple_undirected_data)
+ assert nodes_equal(G.nodes(), PG.nodes())
+ assert edges_equal(G.edges(), PG.edges())
+
+ def test_read_undirected_multigraph_graphml(self):
+ G = self.undirected_multigraph
+ H = nx.read_graphml(self.undirected_multigraph_fh)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ self.undirected_multigraph_fh.seek(0)
+
+ PG = nx.parse_graphml(self.undirected_multigraph_data)
+ assert nodes_equal(G.nodes(), PG.nodes())
+ assert edges_equal(G.edges(), PG.edges())
+
+ def test_read_undirected_multigraph_no_multiedge_graphml(self):
+ G = self.undirected_multigraph_no_multiedge
+ H = nx.read_graphml(self.undirected_multigraph_no_multiedge_fh)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ self.undirected_multigraph_no_multiedge_fh.seek(0)
+
+ PG = nx.parse_graphml(self.undirected_multigraph_no_multiedge_data)
+ assert nodes_equal(G.nodes(), PG.nodes())
+ assert edges_equal(G.edges(), PG.edges())
+
+ def test_read_undirected_multigraph_only_ids_for_multiedges_graphml(self):
+ G = self.multigraph_only_ids_for_multiedges
+ H = nx.read_graphml(self.multigraph_only_ids_for_multiedges_fh)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ self.multigraph_only_ids_for_multiedges_fh.seek(0)
+
+ PG = nx.parse_graphml(self.multigraph_only_ids_for_multiedges_data)
+ assert nodes_equal(G.nodes(), PG.nodes())
+ assert edges_equal(G.edges(), PG.edges())
+
+ def test_read_attribute_graphml(self):
+ G = self.attribute_graph
+ H = nx.read_graphml(self.attribute_fh)
+ assert nodes_equal(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)
+
+ PG = nx.parse_graphml(self.attribute_data)
+ assert sorted(G.nodes(True)) == sorted(PG.nodes(data=True))
+ ge = sorted(G.edges(data=True))
+ he = sorted(PG.edges(data=True))
+ for a, b in zip(ge, he):
+ assert a == b
+
+ def test_node_default_attribute_graphml(self):
+ G = self.node_attribute_default_graph
+ H = nx.read_graphml(self.node_attribute_default_fh)
+ assert G.graph["node_default"] == H.graph["node_default"]
+
+ def test_directed_edge_in_undirected(self):
+ s = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G">
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <edge source="n0" target="n1"/>
+ <edge source="n1" target="n2" directed='true'/>
+ </graph>
+</graphml>"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ pytest.raises(nx.NetworkXError, nx.read_graphml, fh)
+ pytest.raises(nx.NetworkXError, nx.parse_graphml, s)
+
+ def test_undirected_edge_in_directed(self):
+ s = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G" edgedefault='directed'>
+ <node id="n0"/>
+ <node id="n1"/>
+ <node id="n2"/>
+ <edge source="n0" target="n1"/>
+ <edge source="n1" target="n2" directed='false'/>
+ </graph>
+</graphml>"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ pytest.raises(nx.NetworkXError, nx.read_graphml, fh)
+ pytest.raises(nx.NetworkXError, nx.parse_graphml, s)
+
+ def test_key_raise(self):
+ s = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="d0" for="node" attr.name="color" attr.type="string">
+ <default>yellow</default>
+ </key>
+ <key id="d1" for="edge" attr.name="weight" attr.type="double"/>
+ <graph id="G" edgedefault="directed">
+ <node id="n0">
+ <data key="d0">green</data>
+ </node>
+ <node id="n1"/>
+ <node id="n2">
+ <data key="d0">blue</data>
+ </node>
+ <edge id="e0" source="n0" target="n2">
+ <data key="d2">1.0</data>
+ </edge>
+ </graph>
+</graphml>
+"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ pytest.raises(nx.NetworkXError, nx.read_graphml, fh)
+ pytest.raises(nx.NetworkXError, nx.parse_graphml, s)
+
+ def test_hyperedge_raise(self):
+ s = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="d0" for="node" attr.name="color" attr.type="string">
+ <default>yellow</default>
+ </key>
+ <key id="d1" for="edge" attr.name="weight" attr.type="double"/>
+ <graph id="G" edgedefault="directed">
+ <node id="n0">
+ <data key="d0">green</data>
+ </node>
+ <node id="n1"/>
+ <node id="n2">
+ <data key="d0">blue</data>
+ </node>
+ <hyperedge id="e0" source="n0" target="n2">
+ <endpoint node="n0"/>
+ <endpoint node="n1"/>
+ <endpoint node="n2"/>
+ </hyperedge>
+ </graph>
+</graphml>
+"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ pytest.raises(nx.NetworkXError, nx.read_graphml, fh)
+ pytest.raises(nx.NetworkXError, nx.parse_graphml, s)
+
+ def test_multigraph_keys(self):
+ # Test that reading multigraphs uses edge id attributes as keys
+ s = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <graph id="G" edgedefault="directed">
+ <node id="n0"/>
+ <node id="n1"/>
+ <edge id="e0" source="n0" target="n1"/>
+ <edge id="e1" source="n0" target="n1"/>
+ </graph>
+</graphml>
+"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ G = nx.read_graphml(fh)
+ expected = [("n0", "n1", "e0"), ("n0", "n1", "e1")]
+ assert sorted(G.edges(keys=True)) == expected
+ fh.seek(0)
+ H = nx.parse_graphml(s)
+ assert sorted(H.edges(keys=True)) == expected
+
+ def test_preserve_multi_edge_data(self):
+ """
+ Test that data and keys of edges are preserved on consequent
+ write and reads
+ """
+ G = nx.MultiGraph()
+ G.add_node(1)
+ G.add_node(2)
+ G.add_edges_from(
+ [
+ # edges with no data, no keys:
+ (1, 2),
+ # edges with only data:
+ (1, 2, {"key": "data_key1"}),
+ (1, 2, {"id": "data_id2"}),
+ (1, 2, {"key": "data_key3", "id": "data_id3"}),
+ # edges with both data and keys:
+ (1, 2, 103, {"key": "data_key4"}),
+ (1, 2, 104, {"id": "data_id5"}),
+ (1, 2, 105, {"key": "data_key6", "id": "data_id7"}),
+ ]
+ )
+ fh = io.BytesIO()
+ nx.write_graphml(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(fh, node_type=int)
+ assert edges_equal(G.edges(data=True, keys=True), H.edges(data=True, keys=True))
+ assert G._adj == H._adj
+
+ Gadj = {
+ str(node): {
+ str(nbr): {str(ekey): dd for ekey, dd in key_dict.items()}
+ for nbr, key_dict in nbr_dict.items()
+ }
+ for node, nbr_dict in G._adj.items()
+ }
+ fh.seek(0)
+ HH = nx.read_graphml(fh, node_type=str, edge_key_type=str)
+ assert Gadj == HH._adj
+
+ fh.seek(0)
+ string_fh = fh.read()
+ HH = nx.parse_graphml(string_fh, node_type=str, edge_key_type=str)
+ assert Gadj == HH._adj
+
+ def test_yfiles_extension(self):
+ data = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:y="http://www.yworks.com/xml/graphml"
+ xmlns:yed="http://www.yworks.com/xml/yed/3"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <!--Created by yFiles for Java 2.7-->
+ <key for="graphml" id="d0" yfiles.type="resources"/>
+ <key attr.name="url" attr.type="string" for="node" id="d1"/>
+ <key attr.name="description" attr.type="string" for="node" id="d2"/>
+ <key for="node" id="d3" yfiles.type="nodegraphics"/>
+ <key attr.name="Description" attr.type="string" for="graph" id="d4">
+ <default/>
+ </key>
+ <key attr.name="url" attr.type="string" for="edge" id="d5"/>
+ <key attr.name="description" attr.type="string" for="edge" id="d6"/>
+ <key for="edge" id="d7" yfiles.type="edgegraphics"/>
+ <graph edgedefault="directed" id="G">
+ <node id="n0">
+ <data key="d3">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="125.0" y="100.0"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content"
+ borderDistance="0.0" fontFamily="Dialog" fontSize="13"
+ fontStyle="plain" hasBackgroundColor="false" hasLineColor="false"
+ height="19.1328125" modelName="internal" modelPosition="c"
+ textColor="#000000" visible="true" width="12.27099609375"
+ x="8.864501953125" y="5.43359375">1</y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n1">
+ <data key="d3">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="183.0" y="205.0"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content"
+ borderDistance="0.0" fontFamily="Dialog" fontSize="13"
+ fontStyle="plain" hasBackgroundColor="false" hasLineColor="false"
+ height="19.1328125" modelName="internal" modelPosition="c"
+ textColor="#000000" visible="true" width="12.27099609375"
+ x="8.864501953125" y="5.43359375">2</y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n2">
+ <data key="d6" xml:space="preserve"><![CDATA[description
+line1
+line2]]></data>
+ <data key="d3">
+ <y:GenericNode configuration="com.yworks.flowchart.terminator">
+ <y:Geometry height="40.0" width="80.0" x="950.0" y="286.0"/>
+ <y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content"
+ fontFamily="Dialog" fontSize="12" fontStyle="plain"
+ hasBackgroundColor="false" hasLineColor="false" height="17.96875"
+ horizontalTextPosition="center" iconTextGap="4" modelName="custom"
+ textColor="#000000" verticalTextPosition="bottom" visible="true"
+ width="67.984375" x="6.0078125" xml:space="preserve"
+ y="11.015625">3<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/></y:LabelModel>
+ <y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0"
+ labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0"
+ offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ </y:GenericNode>
+ </data>
+ </node>
+ <edge id="e0" source="n0" target="n1">
+ <data key="d7">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ </graph>
+ <data key="d0">
+ <y:Resources/>
+ </data>
+</graphml>
+"""
+ fh = io.BytesIO(data.encode("UTF-8"))
+ G = nx.read_graphml(fh, force_multigraph=True)
+ assert list(G.edges()) == [("n0", "n1")]
+ assert G.has_edge("n0", "n1", key="e0")
+ assert G.nodes["n0"]["label"] == "1"
+ assert G.nodes["n1"]["label"] == "2"
+ assert G.nodes["n2"]["label"] == "3"
+ assert G.nodes["n0"]["shape_type"] == "rectangle"
+ assert G.nodes["n1"]["shape_type"] == "rectangle"
+ assert G.nodes["n2"]["shape_type"] == "com.yworks.flowchart.terminator"
+ assert G.nodes["n2"]["description"] == "description\nline1\nline2"
+ fh.seek(0)
+ G = nx.read_graphml(fh)
+ assert list(G.edges()) == [("n0", "n1")]
+ assert G["n0"]["n1"]["id"] == "e0"
+ assert G.nodes["n0"]["label"] == "1"
+ assert G.nodes["n1"]["label"] == "2"
+ assert G.nodes["n2"]["label"] == "3"
+ assert G.nodes["n0"]["shape_type"] == "rectangle"
+ assert G.nodes["n1"]["shape_type"] == "rectangle"
+ assert G.nodes["n2"]["shape_type"] == "com.yworks.flowchart.terminator"
+ assert G.nodes["n2"]["description"] == "description\nline1\nline2"
+
+ H = nx.parse_graphml(data, force_multigraph=True)
+ assert list(H.edges()) == [("n0", "n1")]
+ assert H.has_edge("n0", "n1", key="e0")
+ assert H.nodes["n0"]["label"] == "1"
+ assert H.nodes["n1"]["label"] == "2"
+ assert H.nodes["n2"]["label"] == "3"
+
+ H = nx.parse_graphml(data)
+ assert list(H.edges()) == [("n0", "n1")]
+ assert H["n0"]["n1"]["id"] == "e0"
+ assert H.nodes["n0"]["label"] == "1"
+ assert H.nodes["n1"]["label"] == "2"
+ assert H.nodes["n2"]["label"] == "3"
+
+ def test_bool(self):
+ s = """<?xml version="1.0" encoding="UTF-8"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="d0" for="node" attr.name="test" attr.type="boolean">
+ <default>false</default>
+ </key>
+ <graph id="G" edgedefault="directed">
+ <node id="n0">
+ <data key="d0">true</data>
+ </node>
+ <node id="n1"/>
+ <node id="n2">
+ <data key="d0">false</data>
+ </node>
+ <node id="n3">
+ <data key="d0">FaLsE</data>
+ </node>
+ <node id="n4">
+ <data key="d0">True</data>
+ </node>
+ <node id="n5">
+ <data key="d0">0</data>
+ </node>
+ <node id="n6">
+ <data key="d0">1</data>
+ </node>
+ </graph>
+</graphml>
+"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ G = nx.read_graphml(fh)
+ H = nx.parse_graphml(s)
+ for graph in [G, H]:
+ assert graph.nodes["n0"]["test"]
+ assert not graph.nodes["n2"]["test"]
+ assert not graph.nodes["n3"]["test"]
+ assert graph.nodes["n4"]["test"]
+ assert not graph.nodes["n5"]["test"]
+ assert graph.nodes["n6"]["test"]
+
+ def test_graphml_header_line(self):
+ good = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key id="d0" for="node" attr.name="test" attr.type="boolean">
+ <default>false</default>
+ </key>
+ <graph id="G">
+ <node id="n0">
+ <data key="d0">true</data>
+ </node>
+ </graph>
+</graphml>
+"""
+ bad = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<graphml>
+ <key id="d0" for="node" attr.name="test" attr.type="boolean">
+ <default>false</default>
+ </key>
+ <graph id="G">
+ <node id="n0">
+ <data key="d0">true</data>
+ </node>
+ </graph>
+</graphml>
+"""
+ ugly = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<graphml xmlns="https://ghghgh">
+ <key id="d0" for="node" attr.name="test" attr.type="boolean">
+ <default>false</default>
+ </key>
+ <graph id="G">
+ <node id="n0">
+ <data key="d0">true</data>
+ </node>
+ </graph>
+</graphml>
+"""
+ for s in (good, bad):
+ fh = io.BytesIO(s.encode("UTF-8"))
+ G = nx.read_graphml(fh)
+ H = nx.parse_graphml(s)
+ for graph in [G, H]:
+ assert graph.nodes["n0"]["test"]
+
+ fh = io.BytesIO(ugly.encode("UTF-8"))
+ pytest.raises(nx.NetworkXError, nx.read_graphml, fh)
+ pytest.raises(nx.NetworkXError, nx.parse_graphml, ugly)
+
+ def test_read_attributes_with_groups(self):
+ data = """\
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
+ <!--Created by yEd 3.17-->
+ <key attr.name="Description" attr.type="string" for="graph" id="d0"/>
+ <key for="port" id="d1" yfiles.type="portgraphics"/>
+ <key for="port" id="d2" yfiles.type="portgeometry"/>
+ <key for="port" id="d3" yfiles.type="portuserdata"/>
+ <key attr.name="CustomProperty" attr.type="string" for="node" id="d4">
+ <default/>
+ </key>
+ <key attr.name="url" attr.type="string" for="node" id="d5"/>
+ <key attr.name="description" attr.type="string" for="node" id="d6"/>
+ <key for="node" id="d7" yfiles.type="nodegraphics"/>
+ <key for="graphml" id="d8" yfiles.type="resources"/>
+ <key attr.name="url" attr.type="string" for="edge" id="d9"/>
+ <key attr.name="description" attr.type="string" for="edge" id="d10"/>
+ <key for="edge" id="d11" yfiles.type="edgegraphics"/>
+ <graph edgedefault="directed" id="G">
+ <data key="d0"/>
+ <node id="n0">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="125.0" y="-255.4611111111111"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="11.634765625" x="9.1826171875" y="6.015625">2<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/>
+ </y:LabelModel>
+ <y:ModelParameter>
+ <y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
+ </y:ModelParameter>
+ </y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n1" yfiles.foldertype="group">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d5"/>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ProxyAutoBoundsNode>
+ <y:Realizers active="0">
+ <y:GroupNode>
+ <y:Geometry height="250.38333333333333" width="140.0" x="-30.0" y="-330.3833333333333"/>
+ <y:Fill color="#F5F5F5" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="140.0" x="0.0" y="0.0">Group 3</y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:State closed="false" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
+ <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
+ <y:BorderInsets bottom="1" bottomF="1.0" left="0" leftF="0.0" right="0" rightF="0.0" top="1" topF="1.0001736111111086"/>
+ </y:GroupNode>
+ <y:GroupNode>
+ <y:Geometry height="50.0" width="50.0" x="0.0" y="60.0"/>
+ <y:Fill color="#F5F5F5" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="65.201171875" x="-7.6005859375" y="0.0">Folder 3</y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:State closed="true" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
+ <y:Insets bottom="5" bottomF="5.0" left="5" leftF="5.0" right="5" rightF="5.0" top="5" topF="5.0"/>
+ <y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
+ </y:GroupNode>
+ </y:Realizers>
+ </y:ProxyAutoBoundsNode>
+ </data>
+ <graph edgedefault="directed" id="n1:">
+ <node id="n1::n0" yfiles.foldertype="group">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d5"/>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ProxyAutoBoundsNode>
+ <y:Realizers active="0">
+ <y:GroupNode>
+ <y:Geometry height="83.46111111111111" width="110.0" x="-15.0" y="-292.9222222222222"/>
+ <y:Fill color="#F5F5F5" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="110.0" x="0.0" y="0.0">Group 1</y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:State closed="false" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
+ <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
+ <y:BorderInsets bottom="1" bottomF="1.0" left="0" leftF="0.0" right="0" rightF="0.0" top="1" topF="1.0001736111111086"/>
+ </y:GroupNode>
+ <y:GroupNode>
+ <y:Geometry height="50.0" width="50.0" x="0.0" y="60.0"/>
+ <y:Fill color="#F5F5F5" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="65.201171875" x="-7.6005859375" y="0.0">Folder 1</y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:State closed="true" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
+ <y:Insets bottom="5" bottomF="5.0" left="5" leftF="5.0" right="5" rightF="5.0" top="5" topF="5.0"/>
+ <y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
+ </y:GroupNode>
+ </y:Realizers>
+ </y:ProxyAutoBoundsNode>
+ </data>
+ <graph edgedefault="directed" id="n1::n0:">
+ <node id="n1::n0::n0">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="50.0" y="-255.4611111111111"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="11.634765625" x="9.1826171875" y="6.015625">1<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/>
+ </y:LabelModel>
+ <y:ModelParameter>
+ <y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
+ </y:ModelParameter>
+ </y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n1::n0::n1">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="0.0" y="-255.4611111111111"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="11.634765625" x="9.1826171875" y="6.015625">3<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/>
+ </y:LabelModel>
+ <y:ModelParameter>
+ <y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
+ </y:ModelParameter>
+ </y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ </graph>
+ </node>
+ <node id="n1::n1" yfiles.foldertype="group">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d5"/>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ProxyAutoBoundsNode>
+ <y:Realizers active="0">
+ <y:GroupNode>
+ <y:Geometry height="83.46111111111111" width="110.0" x="-15.0" y="-179.4611111111111"/>
+ <y:Fill color="#F5F5F5" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="110.0" x="0.0" y="0.0">Group 2</y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:State closed="false" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
+ <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
+ <y:BorderInsets bottom="1" bottomF="1.0" left="0" leftF="0.0" right="0" rightF="0.0" top="1" topF="1.0001736111111086"/>
+ </y:GroupNode>
+ <y:GroupNode>
+ <y:Geometry height="50.0" width="50.0" x="0.0" y="60.0"/>
+ <y:Fill color="#F5F5F5" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="21.4609375" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#000000" verticalTextPosition="bottom" visible="true" width="65.201171875" x="-7.6005859375" y="0.0">Folder 2</y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:State closed="true" closedHeight="50.0" closedWidth="50.0" innerGraphDisplayEnabled="false"/>
+ <y:Insets bottom="5" bottomF="5.0" left="5" leftF="5.0" right="5" rightF="5.0" top="5" topF="5.0"/>
+ <y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
+ </y:GroupNode>
+ </y:Realizers>
+ </y:ProxyAutoBoundsNode>
+ </data>
+ <graph edgedefault="directed" id="n1::n1:">
+ <node id="n1::n1::n0">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="0.0" y="-142.0"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="11.634765625" x="9.1826171875" y="6.015625">5<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/>
+ </y:LabelModel>
+ <y:ModelParameter>
+ <y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
+ </y:ModelParameter>
+ </y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n1::n1::n1">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="50.0" y="-142.0"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="11.634765625" x="9.1826171875" y="6.015625">6<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/>
+ </y:LabelModel>
+ <y:ModelParameter>
+ <y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
+ </y:ModelParameter>
+ </y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ </graph>
+ </node>
+ </graph>
+ </node>
+ <node id="n2">
+ <data key="d4"><![CDATA[CustomPropertyValue]]></data>
+ <data key="d6"/>
+ <data key="d7">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="125.0" y="-142.0"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="17.96875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="11.634765625" x="9.1826171875" y="6.015625">9<y:LabelModel>
+ <y:SmartNodeLabelModel distance="4.0"/>
+ </y:LabelModel>
+ <y:ModelParameter>
+ <y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
+ </y:ModelParameter>
+ </y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <edge id="n1::n1::e0" source="n1::n1::n0" target="n1::n1::n1">
+ <data key="d10"/>
+ <data key="d11">
+ <y:PolyLineEdge>
+ <y:Path sx="15.0" sy="-0.0" tx="-15.0" ty="-0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="n1::n0::e0" source="n1::n0::n1" target="n1::n0::n0">
+ <data key="d10"/>
+ <data key="d11">
+ <y:PolyLineEdge>
+ <y:Path sx="15.0" sy="-0.0" tx="-15.0" ty="-0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e0" source="n1::n0::n0" target="n0">
+ <data key="d10"/>
+ <data key="d11">
+ <y:PolyLineEdge>
+ <y:Path sx="15.0" sy="-0.0" tx="-15.0" ty="-0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e1" source="n1::n1::n1" target="n2">
+ <data key="d10"/>
+ <data key="d11">
+ <y:PolyLineEdge>
+ <y:Path sx="15.0" sy="-0.0" tx="-15.0" ty="-0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ </graph>
+ <data key="d8">
+ <y:Resources/>
+ </data>
+</graphml>
+"""
+ # verify that nodes / attributes are correctly read when part of a group
+ fh = io.BytesIO(data.encode("UTF-8"))
+ G = nx.read_graphml(fh)
+ data = [x for _, x in G.nodes(data=True)]
+ assert len(data) == 9
+ for node_data in data:
+ assert node_data["CustomProperty"] != ""
+
+ def test_long_attribute_type(self):
+ # test that graphs with attr.type="long" (as produced by botch and
+ # dose3) can be parsed
+ s = """<?xml version='1.0' encoding='utf-8'?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
+ http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
+ <key attr.name="cudfversion" attr.type="long" for="node" id="d6" />
+ <graph edgedefault="directed">
+ <node id="n1">
+ <data key="d6">4284</data>
+ </node>
+ </graph>
+</graphml>"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ G = nx.read_graphml(fh)
+ expected = [("n1", {"cudfversion": 4284})]
+ assert sorted(G.nodes(data=True)) == expected
+ fh.seek(0)
+ H = nx.parse_graphml(s)
+ assert sorted(H.nodes(data=True)) == expected
+
+
+class TestWriteGraphML(BaseGraphML):
+ writer = staticmethod(nx.write_graphml_lxml)
+
+ @classmethod
+ def setup_class(cls):
+ BaseGraphML.setup_class()
+ _ = pytest.importorskip("lxml.etree")
+
+ def test_write_interface(self):
+ try:
+ import lxml.etree
+
+ assert nx.write_graphml == nx.write_graphml_lxml
+ except ImportError:
+ assert nx.write_graphml == nx.write_graphml_xml
+
+ def test_write_read_simple_directed_graphml(self):
+ G = self.simple_directed_graph
+ G.graph["hi"] = "there"
+ fh = io.BytesIO()
+ self.writer(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(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_GraphMLWriter_add_graphs(self):
+ gmlw = GraphMLWriter()
+ G = self.simple_directed_graph
+ H = G.copy()
+ gmlw.add_graphs([G, H])
+
+ def test_write_read_simple_no_prettyprint(self):
+ G = self.simple_directed_graph
+ G.graph["hi"] = "there"
+ G.graph["id"] = "1"
+ fh = io.BytesIO()
+ self.writer(G, fh, prettyprint=False)
+ fh.seek(0)
+ H = nx.read_graphml(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_attribute_named_key_ids_graphml(self):
+ from xml.etree.ElementTree import parse
+
+ G = self.attribute_named_key_ids_graph
+ fh = io.BytesIO()
+ self.writer(G, fh, named_key_ids=True)
+ fh.seek(0)
+ H = nx.read_graphml(fh)
+ fh.seek(0)
+
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ assert edges_equal(G.edges(data=True), H.edges(data=True))
+ self.attribute_named_key_ids_fh.seek(0)
+
+ xml = parse(fh)
+ # Children are the key elements, and the graph element
+ children = list(xml.getroot())
+ assert len(children) == 4
+
+ keys = [child.items() for child in children[:3]]
+
+ assert len(keys) == 3
+ assert ("id", "edge_prop") in keys[0]
+ assert ("attr.name", "edge_prop") in keys[0]
+ assert ("id", "prop2") in keys[1]
+ assert ("attr.name", "prop2") in keys[1]
+ assert ("id", "prop1") in keys[2]
+ assert ("attr.name", "prop1") in keys[2]
+
+ # Confirm the read graph nodes/edge are identical when compared to
+ # default writing behavior.
+ default_behavior_fh = io.BytesIO()
+ nx.write_graphml(G, default_behavior_fh)
+ default_behavior_fh.seek(0)
+ H = nx.read_graphml(default_behavior_fh)
+
+ named_key_ids_behavior_fh = io.BytesIO()
+ nx.write_graphml(G, named_key_ids_behavior_fh, named_key_ids=True)
+ named_key_ids_behavior_fh.seek(0)
+ J = nx.read_graphml(named_key_ids_behavior_fh)
+
+ assert all(n1 == n2 for (n1, n2) in zip(H.nodes, J.nodes))
+ assert all(e1 == e2 for (e1, e2) in zip(H.edges, J.edges))
+
+ def test_write_read_attribute_numeric_type_graphml(self):
+ from xml.etree.ElementTree import parse
+
+ G = self.attribute_numeric_type_graph
+ fh = io.BytesIO()
+ self.writer(G, fh, infer_numeric_types=True)
+ fh.seek(0)
+ H = nx.read_graphml(fh)
+ fh.seek(0)
+
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ assert edges_equal(G.edges(data=True), H.edges(data=True))
+ self.attribute_numeric_type_fh.seek(0)
+
+ xml = parse(fh)
+ # Children are the key elements, and the graph element
+ children = list(xml.getroot())
+ assert len(children) == 3
+
+ keys = [child.items() for child in children[:2]]
+
+ assert len(keys) == 2
+ assert ("attr.type", "double") in keys[0]
+ assert ("attr.type", "double") in keys[1]
+
+ def test_more_multigraph_keys(self, tmp_path):
+ """Writing keys as edge id attributes means keys become strings.
+ The original keys are stored as data, so read them back in
+ if `str(key) == edge_id`
+ This allows the adjacency to remain the same.
+ """
+ G = nx.MultiGraph()
+ G.add_edges_from([("a", "b", 2), ("a", "b", 3)])
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname)
+ H = nx.read_graphml(fname)
+ assert H.is_multigraph()
+ assert edges_equal(G.edges(keys=True), H.edges(keys=True))
+ assert G._adj == H._adj
+
+ def test_default_attribute(self):
+ G = nx.Graph(name="Fred")
+ G.add_node(1, label=1, color="green")
+ nx.add_path(G, [0, 1, 2, 3])
+ G.add_edge(1, 2, weight=3)
+ G.graph["node_default"] = {"color": "yellow"}
+ G.graph["edge_default"] = {"weight": 7}
+ fh = io.BytesIO()
+ self.writer(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(fh, node_type=int)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ assert G.graph == H.graph
+
+ def test_mixed_type_attributes(self):
+ G = nx.MultiGraph()
+ G.add_node("n0", special=False)
+ G.add_node("n1", special=0)
+ G.add_edge("n0", "n1", special=False)
+ G.add_edge("n0", "n1", special=0)
+ fh = io.BytesIO()
+ self.writer(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(fh)
+ assert not H.nodes["n0"]["special"]
+ assert H.nodes["n1"]["special"] == 0
+ assert not H.edges["n0", "n1", 0]["special"]
+ assert H.edges["n0", "n1", 1]["special"] == 0
+
+ def test_str_number_mixed_type_attributes(self):
+ G = nx.MultiGraph()
+ G.add_node("n0", special="hello")
+ G.add_node("n1", special=0)
+ G.add_edge("n0", "n1", special="hello")
+ G.add_edge("n0", "n1", special=0)
+ fh = io.BytesIO()
+ self.writer(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(fh)
+ assert H.nodes["n0"]["special"] == "hello"
+ assert H.nodes["n1"]["special"] == 0
+ assert H.edges["n0", "n1", 0]["special"] == "hello"
+ assert H.edges["n0", "n1", 1]["special"] == 0
+
+ def test_mixed_int_type_number_attributes(self):
+ np = pytest.importorskip("numpy")
+ G = nx.MultiGraph()
+ G.add_node("n0", special=np.int64(0))
+ G.add_node("n1", special=1)
+ G.add_edge("n0", "n1", special=np.int64(2))
+ G.add_edge("n0", "n1", special=3)
+ fh = io.BytesIO()
+ self.writer(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(fh)
+ assert H.nodes["n0"]["special"] == 0
+ assert H.nodes["n1"]["special"] == 1
+ assert H.edges["n0", "n1", 0]["special"] == 2
+ assert H.edges["n0", "n1", 1]["special"] == 3
+
+ def test_multigraph_to_graph(self, tmp_path):
+ # test converting multigraph to graph if no parallel edges found
+ G = nx.MultiGraph()
+ G.add_edges_from([("a", "b", 2), ("b", "c", 3)]) # no multiedges
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname)
+ H = nx.read_graphml(fname)
+ assert not H.is_multigraph()
+ H = nx.read_graphml(fname, force_multigraph=True)
+ assert H.is_multigraph()
+
+ # add a multiedge
+ G.add_edge("a", "b", "e-id")
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname)
+ H = nx.read_graphml(fname)
+ assert H.is_multigraph()
+ H = nx.read_graphml(fname, force_multigraph=True)
+ assert H.is_multigraph()
+
+ def test_write_generate_edge_id_from_attribute(self, tmp_path):
+ from xml.etree.ElementTree import parse
+
+ G = nx.Graph()
+ G.add_edges_from([("a", "b"), ("b", "c"), ("a", "c")])
+ edge_attributes = {e: str(e) for e in G.edges}
+ nx.set_edge_attributes(G, edge_attributes, "eid")
+ fname = tmp_path / "test.graphml"
+ # set edge_id_from_attribute e.g. "eid" for write_graphml()
+ self.writer(G, fname, edge_id_from_attribute="eid")
+ # set edge_id_from_attribute e.g. "eid" for generate_graphml()
+ generator = nx.generate_graphml(G, edge_id_from_attribute="eid")
+
+ H = nx.read_graphml(fname)
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ # NetworkX adds explicit edge "id" from file as attribute
+ nx.set_edge_attributes(G, edge_attributes, "id")
+ assert edges_equal(G.edges(data=True), H.edges(data=True))
+
+ tree = parse(fname)
+ children = list(tree.getroot())
+ assert len(children) == 2
+ edge_ids = [
+ edge.attrib["id"]
+ for edge in tree.getroot().findall(
+ ".//{http://graphml.graphdrawing.org/xmlns}edge"
+ )
+ ]
+ # verify edge id value is equal to specified attribute value
+ assert sorted(edge_ids) == sorted(edge_attributes.values())
+
+ # check graphml generated from generate_graphml()
+ data = "".join(generator)
+ J = nx.parse_graphml(data)
+ assert sorted(G.nodes()) == sorted(J.nodes())
+ assert sorted(G.edges()) == sorted(J.edges())
+ # NetworkX adds explicit edge "id" from file as attribute
+ nx.set_edge_attributes(G, edge_attributes, "id")
+ assert edges_equal(G.edges(data=True), J.edges(data=True))
+
+ def test_multigraph_write_generate_edge_id_from_attribute(self, tmp_path):
+ from xml.etree.ElementTree import parse
+
+ G = nx.MultiGraph()
+ G.add_edges_from([("a", "b"), ("b", "c"), ("a", "c"), ("a", "b")])
+ edge_attributes = {e: str(e) for e in G.edges}
+ nx.set_edge_attributes(G, edge_attributes, "eid")
+ fname = tmp_path / "test.graphml"
+ # set edge_id_from_attribute e.g. "eid" for write_graphml()
+ self.writer(G, fname, edge_id_from_attribute="eid")
+ # set edge_id_from_attribute e.g. "eid" for generate_graphml()
+ generator = nx.generate_graphml(G, edge_id_from_attribute="eid")
+
+ H = nx.read_graphml(fname)
+ assert H.is_multigraph()
+ H = nx.read_graphml(fname, force_multigraph=True)
+ assert H.is_multigraph()
+
+ assert nodes_equal(G.nodes(), H.nodes())
+ assert edges_equal(G.edges(), H.edges())
+ assert sorted(data.get("eid") for u, v, data in H.edges(data=True)) == sorted(
+ edge_attributes.values()
+ )
+ # NetworkX uses edge_ids as keys in multigraphs if no key
+ assert sorted(key for u, v, key in H.edges(keys=True)) == sorted(
+ edge_attributes.values()
+ )
+
+ tree = parse(fname)
+ children = list(tree.getroot())
+ assert len(children) == 2
+ edge_ids = [
+ edge.attrib["id"]
+ for edge in tree.getroot().findall(
+ ".//{http://graphml.graphdrawing.org/xmlns}edge"
+ )
+ ]
+ # verify edge id value is equal to specified attribute value
+ assert sorted(edge_ids) == sorted(edge_attributes.values())
+
+ # check graphml generated from generate_graphml()
+ graphml_data = "".join(generator)
+ J = nx.parse_graphml(graphml_data)
+ assert J.is_multigraph()
+
+ assert nodes_equal(G.nodes(), J.nodes())
+ assert edges_equal(G.edges(), J.edges())
+ assert sorted(data.get("eid") for u, v, data in J.edges(data=True)) == sorted(
+ edge_attributes.values()
+ )
+ # NetworkX uses edge_ids as keys in multigraphs if no key
+ assert sorted(key for u, v, key in J.edges(keys=True)) == sorted(
+ edge_attributes.values()
+ )
+
+ def test_numpy_float64(self, tmp_path):
+ np = pytest.importorskip("numpy")
+ wt = np.float64(3.4)
+ G = nx.Graph([(1, 2, {"weight": wt})])
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname)
+ H = nx.read_graphml(fname, node_type=int)
+ assert G.edges == H.edges
+ wtG = G[1][2]["weight"]
+ wtH = H[1][2]["weight"]
+ assert wtG == pytest.approx(wtH, abs=1e-6)
+ assert type(wtG) == np.float64
+ assert type(wtH) == float
+
+ def test_numpy_float32(self, tmp_path):
+ np = pytest.importorskip("numpy")
+ wt = np.float32(3.4)
+ G = nx.Graph([(1, 2, {"weight": wt})])
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname)
+ H = nx.read_graphml(fname, node_type=int)
+ assert G.edges == H.edges
+ wtG = G[1][2]["weight"]
+ wtH = H[1][2]["weight"]
+ assert wtG == pytest.approx(wtH, abs=1e-6)
+ assert type(wtG) == np.float32
+ assert type(wtH) == float
+
+ def test_numpy_float64_inference(self, tmp_path):
+ np = pytest.importorskip("numpy")
+ G = self.attribute_numeric_type_graph
+ G.edges[("n1", "n1")]["weight"] = np.float64(1.1)
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname, infer_numeric_types=True)
+ H = nx.read_graphml(fname)
+ assert G._adj == H._adj
+
+ def test_unicode_attributes(self, tmp_path):
+ G = nx.Graph()
+ name1 = chr(2344) + chr(123) + chr(6543)
+ name2 = chr(5543) + chr(1543) + chr(324)
+ node_type = str
+ G.add_edge(name1, "Radiohead", foo=name2)
+ fname = tmp_path / "test.graphml"
+ self.writer(G, fname)
+ H = nx.read_graphml(fname, node_type=node_type)
+ assert G._adj == H._adj
+
+ def test_unicode_escape(self):
+ # test for handling json escaped strings in python 2 Issue #1880
+ import json
+
+ a = {"a": '{"a": "123"}'} # an object with many chars to escape
+ sa = json.dumps(a)
+ G = nx.Graph()
+ G.graph["test"] = sa
+ fh = io.BytesIO()
+ self.writer(G, fh)
+ fh.seek(0)
+ H = nx.read_graphml(fh)
+ assert G.graph["test"] == H.graph["test"]
+
+
+class TestXMLGraphML(TestWriteGraphML):
+ writer = staticmethod(nx.write_graphml_xml)
+
+ @classmethod
+ def setup_class(cls):
+ TestWriteGraphML.setup_class()
+
+
+def test_exception_for_unsupported_datatype_node_attr():
+ """Test that a detailed exception is raised when an attribute is of a type
+ not supported by GraphML, e.g. a list"""
+ pytest.importorskip("lxml.etree")
+ # node attribute
+ G = nx.Graph()
+ G.add_node(0, my_list_attribute=[0, 1, 2])
+ fh = io.BytesIO()
+ with pytest.raises(TypeError, match="GraphML does not support"):
+ nx.write_graphml(G, fh)
+
+
+def test_exception_for_unsupported_datatype_edge_attr():
+ """Test that a detailed exception is raised when an attribute is of a type
+ not supported by GraphML, e.g. a list"""
+ pytest.importorskip("lxml.etree")
+ # edge attribute
+ G = nx.Graph()
+ G.add_edge(0, 1, my_list_attribute=[0, 1, 2])
+ fh = io.BytesIO()
+ with pytest.raises(TypeError, match="GraphML does not support"):
+ nx.write_graphml(G, fh)
+
+
+def test_exception_for_unsupported_datatype_graph_attr():
+ """Test that a detailed exception is raised when an attribute is of a type
+ not supported by GraphML, e.g. a list"""
+ pytest.importorskip("lxml.etree")
+ # graph attribute
+ G = nx.Graph()
+ G.graph["my_list_attribute"] = [0, 1, 2]
+ fh = io.BytesIO()
+ with pytest.raises(TypeError, match="GraphML does not support"):
+ nx.write_graphml(G, fh)
+
+
+def test_empty_attribute():
+ """Tests that a GraphML string with an empty attribute can be parsed
+ correctly."""
+ s = """<?xml version='1.0' encoding='utf-8'?>
+ <graphml>
+ <key id="d1" for="node" attr.name="foo" attr.type="string"/>
+ <key id="d2" for="node" attr.name="bar" attr.type="string"/>
+ <graph>
+ <node id="0">
+ <data key="d1">aaa</data>
+ <data key="d2">bbb</data>
+ </node>
+ <node id="1">
+ <data key="d1">ccc</data>
+ <data key="d2"></data>
+ </node>
+ </graph>
+ </graphml>"""
+ fh = io.BytesIO(s.encode("UTF-8"))
+ G = nx.read_graphml(fh)
+ assert G.nodes["0"] == {"foo": "aaa", "bar": "bbb"}
+ assert G.nodes["1"] == {"foo": "ccc", "bar": ""}
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_leda.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_leda.py
new file mode 100644
index 00000000..8ac5ecc3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_leda.py
@@ -0,0 +1,30 @@
+import io
+
+import networkx as nx
+
+
+class TestLEDA:
+ def test_parse_leda(self):
+ data = """#header section \nLEDA.GRAPH \nstring\nint\n-1\n#nodes section\n5 \n|{v1}| \n|{v2}| \n|{v3}| \n|{v4}| \n|{v5}| \n\n#edges section\n7 \n1 2 0 |{4}| \n1 3 0 |{3}| \n2 3 0 |{2}| \n3 4 0 |{3}| \n3 5 0 |{7}| \n4 5 0 |{6}| \n5 1 0 |{foo}|"""
+ G = nx.parse_leda(data)
+ G = nx.parse_leda(data.split("\n"))
+ assert sorted(G.nodes()) == ["v1", "v2", "v3", "v4", "v5"]
+ assert sorted(G.edges(data=True)) == [
+ ("v1", "v2", {"label": "4"}),
+ ("v1", "v3", {"label": "3"}),
+ ("v2", "v3", {"label": "2"}),
+ ("v3", "v4", {"label": "3"}),
+ ("v3", "v5", {"label": "7"}),
+ ("v4", "v5", {"label": "6"}),
+ ("v5", "v1", {"label": "foo"}),
+ ]
+
+ def test_read_LEDA(self):
+ fh = io.BytesIO()
+ data = """#header section \nLEDA.GRAPH \nstring\nint\n-1\n#nodes section\n5 \n|{v1}| \n|{v2}| \n|{v3}| \n|{v4}| \n|{v5}| \n\n#edges section\n7 \n1 2 0 |{4}| \n1 3 0 |{3}| \n2 3 0 |{2}| \n3 4 0 |{3}| \n3 5 0 |{7}| \n4 5 0 |{6}| \n5 1 0 |{foo}|"""
+ G = nx.parse_leda(data)
+ fh.write(data.encode("UTF-8"))
+ fh.seek(0)
+ Gin = nx.read_leda(fh)
+ assert sorted(G.nodes()) == sorted(Gin.nodes())
+ assert sorted(G.edges()) == sorted(Gin.edges())
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_p2g.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_p2g.py
new file mode 100644
index 00000000..e4c50de7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_p2g.py
@@ -0,0 +1,62 @@
+import io
+
+import networkx as nx
+from networkx.readwrite.p2g import read_p2g, write_p2g
+from networkx.utils import edges_equal
+
+
+class TestP2G:
+ @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)
+
+ def test_read_p2g(self):
+ s = b"""\
+name
+3 4
+a
+1 2
+b
+
+c
+0 2
+"""
+ bytesIO = io.BytesIO(s)
+ G = read_p2g(bytesIO)
+ assert G.name == "name"
+ assert sorted(G) == ["a", "b", "c"]
+ edges = [(str(u), str(v)) for u, v in G.edges()]
+ assert edges_equal(G.edges(), [("a", "c"), ("a", "b"), ("c", "a"), ("c", "c")])
+
+ def test_write_p2g(self):
+ s = b"""foo
+3 2
+1
+1
+2
+2
+3
+
+"""
+ fh = io.BytesIO()
+ G = nx.DiGraph()
+ G.name = "foo"
+ G.add_edges_from([(1, 2), (2, 3)])
+ write_p2g(G, fh)
+ fh.seek(0)
+ r = fh.read()
+ assert r == s
+
+ def test_write_read_p2g(self):
+ fh = io.BytesIO()
+ G = nx.DiGraph()
+ G.name = "foo"
+ G.add_edges_from([("a", "b"), ("b", "c")])
+ write_p2g(G, fh)
+ fh.seek(0)
+ H = read_p2g(fh)
+ assert edges_equal(G.edges(), H.edges())
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_pajek.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_pajek.py
new file mode 100644
index 00000000..317ebe8e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_pajek.py
@@ -0,0 +1,126 @@
+"""
+Pajek tests
+"""
+
+import networkx as nx
+from networkx.utils import edges_equal, nodes_equal
+
+
+class TestPajek:
+ @classmethod
+ def setup_class(cls):
+ cls.data = """*network Tralala\n*vertices 4\n 1 "A1" 0.0938 0.0896 ellipse x_fact 1 y_fact 1\n 2 "Bb" 0.8188 0.2458 ellipse x_fact 1 y_fact 1\n 3 "C" 0.3688 0.7792 ellipse x_fact 1\n 4 "D2" 0.9583 0.8563 ellipse x_fact 1\n*arcs\n1 1 1 h2 0 w 3 c Blue s 3 a1 -130 k1 0.6 a2 -130 k2 0.6 ap 0.5 l "Bezier loop" lc BlueViolet fos 20 lr 58 lp 0.3 la 360\n2 1 1 h2 0 a1 120 k1 1.3 a2 -120 k2 0.3 ap 25 l "Bezier arc" lphi 270 la 180 lr 19 lp 0.5\n1 2 1 h2 0 a1 40 k1 2.8 a2 30 k2 0.8 ap 25 l "Bezier arc" lphi 90 la 0 lp 0.65\n4 2 -1 h2 0 w 1 k1 -2 k2 250 ap 25 l "Circular arc" c Red lc OrangeRed\n3 4 1 p Dashed h2 0 w 2 c OliveGreen ap 25 l "Straight arc" lc PineGreen\n1 3 1 p Dashed h2 0 w 5 k1 -1 k2 -20 ap 25 l "Oval arc" c Brown lc Black\n3 3 -1 h1 6 w 1 h2 12 k1 -2 k2 -15 ap 0.5 l "Circular loop" c Red lc OrangeRed lphi 270 la 180"""
+ cls.G = nx.MultiDiGraph()
+ cls.G.add_nodes_from(["A1", "Bb", "C", "D2"])
+ cls.G.add_edges_from(
+ [
+ ("A1", "A1"),
+ ("A1", "Bb"),
+ ("A1", "C"),
+ ("Bb", "A1"),
+ ("C", "C"),
+ ("C", "D2"),
+ ("D2", "Bb"),
+ ]
+ )
+
+ cls.G.graph["name"] = "Tralala"
+
+ def test_parse_pajek_simple(self):
+ # Example without node positions or shape
+ data = """*Vertices 2\n1 "1"\n2 "2"\n*Edges\n1 2\n2 1"""
+ G = nx.parse_pajek(data)
+ assert sorted(G.nodes()) == ["1", "2"]
+ assert edges_equal(G.edges(), [("1", "2"), ("1", "2")])
+
+ def test_parse_pajek(self):
+ G = nx.parse_pajek(self.data)
+ assert sorted(G.nodes()) == ["A1", "Bb", "C", "D2"]
+ assert edges_equal(
+ G.edges(),
+ [
+ ("A1", "A1"),
+ ("A1", "Bb"),
+ ("A1", "C"),
+ ("Bb", "A1"),
+ ("C", "C"),
+ ("C", "D2"),
+ ("D2", "Bb"),
+ ],
+ )
+
+ def test_parse_pajet_mat(self):
+ data = """*Vertices 3\n1 "one"\n2 "two"\n3 "three"\n*Matrix\n1 1 0\n0 1 0\n0 1 0\n"""
+ G = nx.parse_pajek(data)
+ assert set(G.nodes()) == {"one", "two", "three"}
+ assert G.nodes["two"] == {"id": "2"}
+ assert edges_equal(
+ set(G.edges()),
+ {("one", "one"), ("two", "one"), ("two", "two"), ("two", "three")},
+ )
+
+ def test_read_pajek(self, tmp_path):
+ G = nx.parse_pajek(self.data)
+ # Read data from file
+ fname = tmp_path / "test.pjk"
+ with open(fname, "wb") as fh:
+ fh.write(self.data.encode("UTF-8"))
+
+ Gin = nx.read_pajek(fname)
+ assert sorted(G.nodes()) == sorted(Gin.nodes())
+ assert edges_equal(G.edges(), Gin.edges())
+ assert self.G.graph == Gin.graph
+ for n in G:
+ assert G.nodes[n] == Gin.nodes[n]
+
+ def test_write_pajek(self):
+ import io
+
+ G = nx.parse_pajek(self.data)
+ fh = io.BytesIO()
+ nx.write_pajek(G, fh)
+ fh.seek(0)
+ H = nx.read_pajek(fh)
+ assert nodes_equal(list(G), list(H))
+ assert edges_equal(list(G.edges()), list(H.edges()))
+ # Graph name is left out for now, therefore it is not tested.
+ # assert_equal(G.graph, H.graph)
+
+ def test_ignored_attribute(self):
+ import io
+
+ G = nx.Graph()
+ fh = io.BytesIO()
+ G.add_node(1, int_attr=1)
+ G.add_node(2, empty_attr=" ")
+ G.add_edge(1, 2, int_attr=2)
+ G.add_edge(2, 3, empty_attr=" ")
+
+ import warnings
+
+ with warnings.catch_warnings(record=True) as w:
+ nx.write_pajek(G, fh)
+ assert len(w) == 4
+
+ def test_noname(self):
+ # Make sure we can parse a line such as: *network
+ # Issue #952
+ line = "*network\n"
+ other_lines = self.data.split("\n")[1:]
+ data = line + "\n".join(other_lines)
+ G = nx.parse_pajek(data)
+
+ def test_unicode(self):
+ import io
+
+ G = nx.Graph()
+ name1 = chr(2344) + chr(123) + chr(6543)
+ name2 = chr(5543) + chr(1543) + chr(324)
+ G.add_edge(name1, "Radiohead", foo=name2)
+ fh = io.BytesIO()
+ nx.write_pajek(G, fh)
+ fh.seek(0)
+ H = nx.read_pajek(fh)
+ assert nodes_equal(list(G), list(H))
+ assert edges_equal(list(G.edges()), list(H.edges()))
+ assert G.graph == H.graph
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_sparse6.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_sparse6.py
new file mode 100644
index 00000000..344ad0e4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_sparse6.py
@@ -0,0 +1,166 @@
+from io import BytesIO
+
+import pytest
+
+import networkx as nx
+from networkx.utils import edges_equal, nodes_equal
+
+
+class TestSparseGraph6:
+ def test_from_sparse6_bytes(self):
+ data = b":Q___eDcdFcDeFcE`GaJ`IaHbKNbLM"
+ G = nx.from_sparse6_bytes(data)
+ assert nodes_equal(
+ sorted(G.nodes()),
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
+ )
+ assert edges_equal(
+ G.edges(),
+ [
+ (0, 1),
+ (0, 2),
+ (0, 3),
+ (1, 12),
+ (1, 14),
+ (2, 13),
+ (2, 15),
+ (3, 16),
+ (3, 17),
+ (4, 7),
+ (4, 9),
+ (4, 11),
+ (5, 6),
+ (5, 8),
+ (5, 9),
+ (6, 10),
+ (6, 11),
+ (7, 8),
+ (7, 10),
+ (8, 12),
+ (9, 15),
+ (10, 14),
+ (11, 13),
+ (12, 16),
+ (13, 17),
+ (14, 17),
+ (15, 16),
+ ],
+ )
+
+ def test_from_bytes_multigraph_graph(self):
+ graph_data = b":An"
+ G = nx.from_sparse6_bytes(graph_data)
+ assert type(G) == nx.Graph
+ multigraph_data = b":Ab"
+ M = nx.from_sparse6_bytes(multigraph_data)
+ assert type(M) == nx.MultiGraph
+
+ def test_read_sparse6(self):
+ data = b":Q___eDcdFcDeFcE`GaJ`IaHbKNbLM"
+ G = nx.from_sparse6_bytes(data)
+ fh = BytesIO(data)
+ Gin = nx.read_sparse6(fh)
+ assert nodes_equal(G.nodes(), Gin.nodes())
+ assert edges_equal(G.edges(), Gin.edges())
+
+ def test_read_many_graph6(self):
+ # Read many graphs into list
+ data = b":Q___eDcdFcDeFcE`GaJ`IaHbKNbLM\n" b":Q___dCfDEdcEgcbEGbFIaJ`JaHN`IM"
+ fh = BytesIO(data)
+ glist = nx.read_sparse6(fh)
+ assert len(glist) == 2
+ for G in glist:
+ assert nodes_equal(
+ G.nodes(),
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
+ )
+
+
+class TestWriteSparse6:
+ """Unit tests for writing graphs in the sparse6 format.
+
+ Most of the test cases were checked against the sparse6 encoder in Sage.
+
+ """
+
+ def test_null_graph(self):
+ G = nx.null_graph()
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ assert result.getvalue() == b">>sparse6<<:?\n"
+
+ def test_trivial_graph(self):
+ G = nx.trivial_graph()
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ assert result.getvalue() == b">>sparse6<<:@\n"
+
+ def test_empty_graph(self):
+ G = nx.empty_graph(5)
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ assert result.getvalue() == b">>sparse6<<:D\n"
+
+ def test_large_empty_graph(self):
+ G = nx.empty_graph(68)
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ assert result.getvalue() == b">>sparse6<<:~?@C\n"
+
+ def test_very_large_empty_graph(self):
+ G = nx.empty_graph(258049)
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ assert result.getvalue() == b">>sparse6<<:~~???~?@\n"
+
+ def test_complete_graph(self):
+ G = nx.complete_graph(4)
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ assert result.getvalue() == b">>sparse6<<:CcKI\n"
+
+ def test_no_header(self):
+ G = nx.complete_graph(4)
+ result = BytesIO()
+ nx.write_sparse6(G, result, header=False)
+ assert result.getvalue() == b":CcKI\n"
+
+ def test_padding(self):
+ codes = (b":Cdv", b":DaYn", b":EaYnN", b":FaYnL", b":GaYnLz")
+ for n, code in enumerate(codes, start=4):
+ G = nx.path_graph(n)
+ result = BytesIO()
+ nx.write_sparse6(G, result, header=False)
+ assert result.getvalue() == code + b"\n"
+
+ def test_complete_bipartite(self):
+ G = nx.complete_bipartite_graph(6, 9)
+ result = BytesIO()
+ nx.write_sparse6(G, result)
+ # Compared with sage
+ expected = b">>sparse6<<:Nk" + b"?G`cJ" * 9 + b"\n"
+ assert result.getvalue() == expected
+
+ def test_read_write_inverse(self):
+ for i in list(range(13)) + [31, 47, 62, 63, 64, 72]:
+ m = min(2 * i, i * i // 2)
+ g = nx.random_graphs.gnm_random_graph(i, m, seed=i)
+ gstr = BytesIO()
+ nx.write_sparse6(g, gstr, header=False)
+ # Strip the trailing newline.
+ gstr = gstr.getvalue().rstrip()
+ g2 = nx.from_sparse6_bytes(gstr)
+ assert g2.order() == g.order()
+ assert edges_equal(g2.edges(), g.edges())
+
+ def test_no_directed_graphs(self):
+ with pytest.raises(nx.NetworkXNotImplemented):
+ nx.write_sparse6(nx.DiGraph(), BytesIO())
+
+ def test_write_path(self, tmp_path):
+ # Get a valid temporary file name
+ fullfilename = str(tmp_path / "test.s6")
+ # file should be closed now, so write_sparse6 can open it
+ nx.write_sparse6(nx.null_graph(), fullfilename)
+ with open(fullfilename, mode="rb") as fh:
+ assert fh.read() == b">>sparse6<<:?\n"
diff --git a/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_text.py b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_text.py
new file mode 100644
index 00000000..b2b74482
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/networkx/readwrite/tests/test_text.py
@@ -0,0 +1,1742 @@
+import random
+from itertools import product
+from textwrap import dedent
+
+import pytest
+
+import networkx as nx
+
+
+def test_generate_network_text_forest_directed():
+ # Create a directed forest with labels
+ graph = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph)
+ for node in graph.nodes:
+ graph.nodes[node]["label"] = "node_" + chr(ord("a") + node)
+
+ node_target = dedent(
+ """
+ ╙── 0
+ ├─╼ 1
+ │ ├─╼ 3
+ │ └─╼ 4
+ └─╼ 2
+ ├─╼ 5
+ └─╼ 6
+ """
+ ).strip()
+
+ label_target = dedent(
+ """
+ ╙── node_a
+ ├─╼ node_b
+ │ ├─╼ node_d
+ │ └─╼ node_e
+ └─╼ node_c
+ ├─╼ node_f
+ └─╼ node_g
+ """
+ ).strip()
+
+ # Basic node case
+ ret = nx.generate_network_text(graph, with_labels=False)
+ assert "\n".join(ret) == node_target
+
+ # Basic label case
+ ret = nx.generate_network_text(graph, with_labels=True)
+ assert "\n".join(ret) == label_target
+
+
+def test_write_network_text_empty_graph():
+ def _graph_str(g, **kw):
+ printbuf = []
+ nx.write_network_text(g, printbuf.append, end="", **kw)
+ return "\n".join(printbuf)
+
+ assert _graph_str(nx.DiGraph()) == "╙"
+ assert _graph_str(nx.Graph()) == "╙"
+ assert _graph_str(nx.DiGraph(), ascii_only=True) == "+"
+ assert _graph_str(nx.Graph(), ascii_only=True) == "+"
+
+
+def test_write_network_text_within_forest_glyph():
+ g = nx.DiGraph()
+ g.add_nodes_from([1, 2, 3, 4])
+ g.add_edge(2, 4)
+ lines = []
+ write = lines.append
+ nx.write_network_text(g, path=write, end="")
+ nx.write_network_text(g, path=write, ascii_only=True, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╟── 1
+ ╟── 2
+ ╎ └─╼ 4
+ ╙── 3
+ +-- 1
+ +-- 2
+ : L-> 4
+ +-- 3
+ """
+ ).strip()
+ assert text == target
+
+
+def test_generate_network_text_directed_multi_tree():
+ tree1 = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph)
+ tree2 = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph)
+ forest = nx.disjoint_union_all([tree1, tree2])
+ ret = "\n".join(nx.generate_network_text(forest))
+
+ target = dedent(
+ """
+ ╟── 0
+ ╎ ├─╼ 1
+ ╎ │ ├─╼ 3
+ ╎ │ └─╼ 4
+ ╎ └─╼ 2
+ ╎ ├─╼ 5
+ ╎ └─╼ 6
+ ╙── 7
+ ├─╼ 8
+ │ ├─╼ 10
+ │ └─╼ 11
+ └─╼ 9
+ ├─╼ 12
+ └─╼ 13
+ """
+ ).strip()
+ assert ret == target
+
+ tree3 = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph)
+ forest = nx.disjoint_union_all([tree1, tree2, tree3])
+ ret = "\n".join(nx.generate_network_text(forest, sources=[0, 14, 7]))
+
+ target = dedent(
+ """
+ ╟── 0
+ ╎ ├─╼ 1
+ ╎ │ ├─╼ 3
+ ╎ │ └─╼ 4
+ ╎ └─╼ 2
+ ╎ ├─╼ 5
+ ╎ └─╼ 6
+ ╟── 14
+ ╎ ├─╼ 15
+ ╎ │ ├─╼ 17
+ ╎ │ └─╼ 18
+ ╎ └─╼ 16
+ ╎ ├─╼ 19
+ ╎ └─╼ 20
+ ╙── 7
+ ├─╼ 8
+ │ ├─╼ 10
+ │ └─╼ 11
+ └─╼ 9
+ ├─╼ 12
+ └─╼ 13
+ """
+ ).strip()
+ assert ret == target
+
+ ret = "\n".join(
+ nx.generate_network_text(forest, sources=[0, 14, 7], ascii_only=True)
+ )
+
+ target = dedent(
+ """
+ +-- 0
+ : |-> 1
+ : | |-> 3
+ : | L-> 4
+ : L-> 2
+ : |-> 5
+ : L-> 6
+ +-- 14
+ : |-> 15
+ : | |-> 17
+ : | L-> 18
+ : L-> 16
+ : |-> 19
+ : L-> 20
+ +-- 7
+ |-> 8
+ | |-> 10
+ | L-> 11
+ L-> 9
+ |-> 12
+ L-> 13
+ """
+ ).strip()
+ assert ret == target
+
+
+def test_generate_network_text_undirected_multi_tree():
+ tree1 = nx.balanced_tree(r=2, h=2, create_using=nx.Graph)
+ tree2 = nx.balanced_tree(r=2, h=2, create_using=nx.Graph)
+ tree2 = nx.relabel_nodes(tree2, {n: n + len(tree1) for n in tree2.nodes})
+ forest = nx.union(tree1, tree2)
+ ret = "\n".join(nx.generate_network_text(forest, sources=[0, 7]))
+
+ target = dedent(
+ """
+ ╟── 0
+ ╎ ├── 1
+ ╎ │ ├── 3
+ ╎ │ └── 4
+ ╎ └── 2
+ ╎ ├── 5
+ ╎ └── 6
+ ╙── 7
+ ├── 8
+ │ ├── 10
+ │ └── 11
+ └── 9
+ ├── 12
+ └── 13
+ """
+ ).strip()
+ assert ret == target
+
+ ret = "\n".join(nx.generate_network_text(forest, sources=[0, 7], ascii_only=True))
+
+ target = dedent(
+ """
+ +-- 0
+ : |-- 1
+ : | |-- 3
+ : | L-- 4
+ : L-- 2
+ : |-- 5
+ : L-- 6
+ +-- 7
+ |-- 8
+ | |-- 10
+ | L-- 11
+ L-- 9
+ |-- 12
+ L-- 13
+ """
+ ).strip()
+ assert ret == target
+
+
+def test_generate_network_text_forest_undirected():
+ # Create a directed forest
+ graph = nx.balanced_tree(r=2, h=2, create_using=nx.Graph)
+
+ node_target0 = dedent(
+ """
+ ╙── 0
+ ├── 1
+ │ ├── 3
+ │ └── 4
+ └── 2
+ ├── 5
+ └── 6
+ """
+ ).strip()
+
+ # defined starting point
+ ret = "\n".join(nx.generate_network_text(graph, sources=[0]))
+ assert ret == node_target0
+
+ # defined starting point
+ node_target2 = dedent(
+ """
+ ╙── 2
+ ├── 0
+ │ └── 1
+ │ ├── 3
+ │ └── 4
+ ├── 5
+ └── 6
+ """
+ ).strip()
+ ret = "\n".join(nx.generate_network_text(graph, sources=[2]))
+ assert ret == node_target2
+
+
+def test_generate_network_text_overspecified_sources():
+ """
+ When sources are directly specified, we won't be able to determine when we
+ are in the last component, so there will always be a trailing, leftmost
+ pipe.
+ """
+ graph = nx.disjoint_union_all(
+ [
+ nx.balanced_tree(r=2, h=1, create_using=nx.DiGraph),
+ nx.balanced_tree(r=1, h=2, create_using=nx.DiGraph),
+ nx.balanced_tree(r=2, h=1, create_using=nx.DiGraph),
+ ]
+ )
+
+ # defined starting point
+ target1 = dedent(
+ """
+ ╟── 0
+ ╎ ├─╼ 1
+ ╎ └─╼ 2
+ ╟── 3
+ ╎ └─╼ 4
+ ╎ └─╼ 5
+ ╟── 6
+ ╎ ├─╼ 7
+ ╎ └─╼ 8
+ """
+ ).strip()
+
+ target2 = dedent(
+ """
+ ╟── 0
+ ╎ ├─╼ 1
+ ╎ └─╼ 2
+ ╟── 3
+ ╎ └─╼ 4
+ ╎ └─╼ 5
+ ╙── 6
+ ├─╼ 7
+ └─╼ 8
+ """
+ ).strip()
+
+ got1 = "\n".join(nx.generate_network_text(graph, sources=graph.nodes))
+ got2 = "\n".join(nx.generate_network_text(graph))
+ assert got1 == target1
+ assert got2 == target2
+
+
+def test_write_network_text_iterative_add_directed_edges():
+ """
+ Walk through the cases going from a disconnected to fully connected graph
+ """
+ graph = nx.DiGraph()
+ graph.add_nodes_from([1, 2, 3, 4])
+ lines = []
+ write = lines.append
+ write("--- initial state ---")
+ nx.write_network_text(graph, path=write, end="")
+ for i, j in product(graph.nodes, graph.nodes):
+ write(f"--- add_edge({i}, {j}) ---")
+ graph.add_edge(i, j)
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ # defined starting point
+ target = dedent(
+ """
+ --- initial state ---
+ ╟── 1
+ ╟── 2
+ ╟── 3
+ ╙── 4
+ --- add_edge(1, 1) ---
+ ╟── 1 ╾ 1
+ ╎ └─╼ ...
+ ╟── 2
+ ╟── 3
+ ╙── 4
+ --- add_edge(1, 2) ---
+ ╟── 1 ╾ 1
+ ╎ ├─╼ 2
+ ╎ └─╼ ...
+ ╟── 3
+ ╙── 4
+ --- add_edge(1, 3) ---
+ ╟── 1 ╾ 1
+ ╎ ├─╼ 2
+ ╎ ├─╼ 3
+ ╎ └─╼ ...
+ ╙── 4
+ --- add_edge(1, 4) ---
+ ╙── 1 ╾ 1
+ ├─╼ 2
+ ├─╼ 3
+ ├─╼ 4
+ └─╼ ...
+ --- add_edge(2, 1) ---
+ ╙── 2 ╾ 1
+ └─╼ 1 ╾ 1
+ ├─╼ 3
+ ├─╼ 4
+ └─╼ ...
+ --- add_edge(2, 2) ---
+ ╙── 1 ╾ 1, 2
+ ├─╼ 2 ╾ 2
+ │ └─╼ ...
+ ├─╼ 3
+ ├─╼ 4
+ └─╼ ...
+ --- add_edge(2, 3) ---
+ ╙── 1 ╾ 1, 2
+ ├─╼ 2 ╾ 2
+ │ ├─╼ 3 ╾ 1
+ │ └─╼ ...
+ ├─╼ 4
+ └─╼ ...
+ --- add_edge(2, 4) ---
+ ╙── 1 ╾ 1, 2
+ ├─╼ 2 ╾ 2
+ │ ├─╼ 3 ╾ 1
+ │ ├─╼ 4 ╾ 1
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(3, 1) ---
+ ╙── 2 ╾ 1, 2
+ ├─╼ 1 ╾ 1, 3
+ │ ├─╼ 3 ╾ 2
+ │ │ └─╼ ...
+ │ ├─╼ 4 ╾ 2
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(3, 2) ---
+ ╙── 3 ╾ 1, 2
+ ├─╼ 1 ╾ 1, 2
+ │ ├─╼ 2 ╾ 2, 3
+ │ │ ├─╼ 4 ╾ 1
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(3, 3) ---
+ ╙── 1 ╾ 1, 2, 3
+ ├─╼ 2 ╾ 2, 3
+ │ ├─╼ 3 ╾ 1, 3
+ │ │ └─╼ ...
+ │ ├─╼ 4 ╾ 1
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(3, 4) ---
+ ╙── 1 ╾ 1, 2, 3
+ ├─╼ 2 ╾ 2, 3
+ │ ├─╼ 3 ╾ 1, 3
+ │ │ ├─╼ 4 ╾ 1, 2
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(4, 1) ---
+ ╙── 2 ╾ 1, 2, 3
+ ├─╼ 1 ╾ 1, 3, 4
+ │ ├─╼ 3 ╾ 2, 3
+ │ │ ├─╼ 4 ╾ 1, 2
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(4, 2) ---
+ ╙── 3 ╾ 1, 2, 3
+ ├─╼ 1 ╾ 1, 2, 4
+ │ ├─╼ 2 ╾ 2, 3, 4
+ │ │ ├─╼ 4 ╾ 1, 3
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(4, 3) ---
+ ╙── 4 ╾ 1, 2, 3
+ ├─╼ 1 ╾ 1, 2, 3
+ │ ├─╼ 2 ╾ 2, 3, 4
+ │ │ ├─╼ 3 ╾ 1, 3, 4
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(4, 4) ---
+ ╙── 1 ╾ 1, 2, 3, 4
+ ├─╼ 2 ╾ 2, 3, 4
+ │ ├─╼ 3 ╾ 1, 3, 4
+ │ │ ├─╼ 4 ╾ 1, 2, 4
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_iterative_add_undirected_edges():
+ """
+ Walk through the cases going from a disconnected to fully connected graph
+ """
+ graph = nx.Graph()
+ graph.add_nodes_from([1, 2, 3, 4])
+ lines = []
+ write = lines.append
+ write("--- initial state ---")
+ nx.write_network_text(graph, path=write, end="")
+ for i, j in product(graph.nodes, graph.nodes):
+ if i == j:
+ continue
+ write(f"--- add_edge({i}, {j}) ---")
+ graph.add_edge(i, j)
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- initial state ---
+ ╟── 1
+ ╟── 2
+ ╟── 3
+ ╙── 4
+ --- add_edge(1, 2) ---
+ ╟── 3
+ ╟── 4
+ ╙── 1
+ └── 2
+ --- add_edge(1, 3) ---
+ ╟── 4
+ ╙── 2
+ └── 1
+ └── 3
+ --- add_edge(1, 4) ---
+ ╙── 2
+ └── 1
+ ├── 3
+ └── 4
+ --- add_edge(2, 1) ---
+ ╙── 2
+ └── 1
+ ├── 3
+ └── 4
+ --- add_edge(2, 3) ---
+ ╙── 4
+ └── 1
+ ├── 2
+ │ └── 3 ─ 1
+ └── ...
+ --- add_edge(2, 4) ---
+ ╙── 3
+ ├── 1
+ │ ├── 2 ─ 3
+ │ │ └── 4 ─ 1
+ │ └── ...
+ └── ...
+ --- add_edge(3, 1) ---
+ ╙── 3
+ ├── 1
+ │ ├── 2 ─ 3
+ │ │ └── 4 ─ 1
+ │ └── ...
+ └── ...
+ --- add_edge(3, 2) ---
+ ╙── 3
+ ├── 1
+ │ ├── 2 ─ 3
+ │ │ └── 4 ─ 1
+ │ └── ...
+ └── ...
+ --- add_edge(3, 4) ---
+ ╙── 1
+ ├── 2
+ │ ├── 3 ─ 1
+ │ │ └── 4 ─ 1, 2
+ │ └── ...
+ └── ...
+ --- add_edge(4, 1) ---
+ ╙── 1
+ ├── 2
+ │ ├── 3 ─ 1
+ │ │ └── 4 ─ 1, 2
+ │ └── ...
+ └── ...
+ --- add_edge(4, 2) ---
+ ╙── 1
+ ├── 2
+ │ ├── 3 ─ 1
+ │ │ └── 4 ─ 1, 2
+ │ └── ...
+ └── ...
+ --- add_edge(4, 3) ---
+ ╙── 1
+ ├── 2
+ │ ├── 3 ─ 1
+ │ │ └── 4 ─ 1, 2
+ │ └── ...
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_iterative_add_random_directed_edges():
+ """
+ Walk through the cases going from a disconnected to fully connected graph
+ """
+
+ rng = random.Random(724466096)
+ graph = nx.DiGraph()
+ graph.add_nodes_from([1, 2, 3, 4, 5])
+ possible_edges = list(product(graph.nodes, graph.nodes))
+ rng.shuffle(possible_edges)
+ graph.add_edges_from(possible_edges[0:8])
+ lines = []
+ write = lines.append
+ write("--- initial state ---")
+ nx.write_network_text(graph, path=write, end="")
+ for i, j in possible_edges[8:12]:
+ write(f"--- add_edge({i}, {j}) ---")
+ graph.add_edge(i, j)
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- initial state ---
+ ╙── 3 ╾ 5
+ └─╼ 2 ╾ 2
+ ├─╼ 4 ╾ 4
+ │ ├─╼ 5
+ │ │ ├─╼ 1 ╾ 1
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(4, 1) ---
+ ╙── 3 ╾ 5
+ └─╼ 2 ╾ 2
+ ├─╼ 4 ╾ 4
+ │ ├─╼ 5
+ │ │ ├─╼ 1 ╾ 1, 4
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(2, 1) ---
+ ╙── 3 ╾ 5
+ └─╼ 2 ╾ 2
+ ├─╼ 4 ╾ 4
+ │ ├─╼ 5
+ │ │ ├─╼ 1 ╾ 1, 4, 2
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(5, 2) ---
+ ╙── 3 ╾ 5
+ └─╼ 2 ╾ 2, 5
+ ├─╼ 4 ╾ 4
+ │ ├─╼ 5
+ │ │ ├─╼ 1 ╾ 1, 4, 2
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- add_edge(1, 5) ---
+ ╙── 3 ╾ 5
+ └─╼ 2 ╾ 2, 5
+ ├─╼ 4 ╾ 4
+ │ ├─╼ 5 ╾ 1
+ │ │ ├─╼ 1 ╾ 1, 4, 2
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_nearly_forest():
+ g = nx.DiGraph()
+ g.add_edge(1, 2)
+ g.add_edge(1, 5)
+ g.add_edge(2, 3)
+ g.add_edge(3, 4)
+ g.add_edge(5, 6)
+ g.add_edge(6, 7)
+ g.add_edge(6, 8)
+ orig = g.copy()
+ g.add_edge(1, 8) # forward edge
+ g.add_edge(4, 2) # back edge
+ g.add_edge(6, 3) # cross edge
+ lines = []
+ write = lines.append
+ write("--- directed case ---")
+ nx.write_network_text(orig, path=write, end="")
+ write("--- add (1, 8), (4, 2), (6, 3) ---")
+ nx.write_network_text(g, path=write, end="")
+ write("--- undirected case ---")
+ nx.write_network_text(orig.to_undirected(), path=write, sources=[1], end="")
+ write("--- add (1, 8), (4, 2), (6, 3) ---")
+ nx.write_network_text(g.to_undirected(), path=write, sources=[1], end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- directed case ---
+ ╙── 1
+ ├─╼ 2
+ │ └─╼ 3
+ │ └─╼ 4
+ └─╼ 5
+ └─╼ 6
+ ├─╼ 7
+ └─╼ 8
+ --- add (1, 8), (4, 2), (6, 3) ---
+ ╙── 1
+ ├─╼ 2 ╾ 4
+ │ └─╼ 3 ╾ 6
+ │ └─╼ 4
+ │ └─╼ ...
+ ├─╼ 5
+ │ └─╼ 6
+ │ ├─╼ 7
+ │ ├─╼ 8 ╾ 1
+ │ └─╼ ...
+ └─╼ ...
+ --- undirected case ---
+ ╙── 1
+ ├── 2
+ │ └── 3
+ │ └── 4
+ └── 5
+ └── 6
+ ├── 7
+ └── 8
+ --- add (1, 8), (4, 2), (6, 3) ---
+ ╙── 1
+ ├── 2
+ │ ├── 3
+ │ │ ├── 4 ─ 2
+ │ │ └── 6
+ │ │ ├── 5 ─ 1
+ │ │ ├── 7
+ │ │ └── 8 ─ 1
+ │ └── ...
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_complete_graph_ascii_only():
+ graph = nx.generators.complete_graph(5, create_using=nx.DiGraph)
+ lines = []
+ write = lines.append
+ write("--- directed case ---")
+ nx.write_network_text(graph, path=write, ascii_only=True, end="")
+ write("--- undirected case ---")
+ nx.write_network_text(graph.to_undirected(), path=write, ascii_only=True, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- directed case ---
+ +-- 0 <- 1, 2, 3, 4
+ |-> 1 <- 2, 3, 4
+ | |-> 2 <- 0, 3, 4
+ | | |-> 3 <- 0, 1, 4
+ | | | |-> 4 <- 0, 1, 2
+ | | | | L-> ...
+ | | | L-> ...
+ | | L-> ...
+ | L-> ...
+ L-> ...
+ --- undirected case ---
+ +-- 0
+ |-- 1
+ | |-- 2 - 0
+ | | |-- 3 - 0, 1
+ | | | L-- 4 - 0, 1, 2
+ | | L-- ...
+ | L-- ...
+ L-- ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_with_labels():
+ graph = nx.generators.complete_graph(5, create_using=nx.DiGraph)
+ for n in graph.nodes:
+ graph.nodes[n]["label"] = f"Node(n={n})"
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, with_labels=True, ascii_only=False, end="")
+ text = "\n".join(lines)
+ # Non trees with labels can get somewhat out of hand with network text
+ # because we need to immediately show every non-tree edge to the right
+ target = dedent(
+ """
+ ╙── Node(n=0) ╾ Node(n=1), Node(n=2), Node(n=3), Node(n=4)
+ ├─╼ Node(n=1) ╾ Node(n=2), Node(n=3), Node(n=4)
+ │ ├─╼ Node(n=2) ╾ Node(n=0), Node(n=3), Node(n=4)
+ │ │ ├─╼ Node(n=3) ╾ Node(n=0), Node(n=1), Node(n=4)
+ │ │ │ ├─╼ Node(n=4) ╾ Node(n=0), Node(n=1), Node(n=2)
+ │ │ │ │ └─╼ ...
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_complete_graphs():
+ lines = []
+ write = lines.append
+ for k in [0, 1, 2, 3, 4, 5]:
+ g = nx.generators.complete_graph(k)
+ write(f"--- undirected k={k} ---")
+ nx.write_network_text(g, path=write, end="")
+
+ for k in [0, 1, 2, 3, 4, 5]:
+ g = nx.generators.complete_graph(k, nx.DiGraph)
+ write(f"--- directed k={k} ---")
+ nx.write_network_text(g, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- undirected k=0 ---
+ ╙
+ --- undirected k=1 ---
+ ╙── 0
+ --- undirected k=2 ---
+ ╙── 0
+ └── 1
+ --- undirected k=3 ---
+ ╙── 0
+ ├── 1
+ │ └── 2 ─ 0
+ └── ...
+ --- undirected k=4 ---
+ ╙── 0
+ ├── 1
+ │ ├── 2 ─ 0
+ │ │ └── 3 ─ 0, 1
+ │ └── ...
+ └── ...
+ --- undirected k=5 ---
+ ╙── 0
+ ├── 1
+ │ ├── 2 ─ 0
+ │ │ ├── 3 ─ 0, 1
+ │ │ │ └── 4 ─ 0, 1, 2
+ │ │ └── ...
+ │ └── ...
+ └── ...
+ --- directed k=0 ---
+ ╙
+ --- directed k=1 ---
+ ╙── 0
+ --- directed k=2 ---
+ ╙── 0 ╾ 1
+ └─╼ 1
+ └─╼ ...
+ --- directed k=3 ---
+ ╙── 0 ╾ 1, 2
+ ├─╼ 1 ╾ 2
+ │ ├─╼ 2 ╾ 0
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- directed k=4 ---
+ ╙── 0 ╾ 1, 2, 3
+ ├─╼ 1 ╾ 2, 3
+ │ ├─╼ 2 ╾ 0, 3
+ │ │ ├─╼ 3 ╾ 0, 1
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- directed k=5 ---
+ ╙── 0 ╾ 1, 2, 3, 4
+ ├─╼ 1 ╾ 2, 3, 4
+ │ ├─╼ 2 ╾ 0, 3, 4
+ │ │ ├─╼ 3 ╾ 0, 1, 4
+ │ │ │ ├─╼ 4 ╾ 0, 1, 2
+ │ │ │ │ └─╼ ...
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_multiple_sources():
+ g = nx.DiGraph()
+ g.add_edge(1, 2)
+ g.add_edge(1, 3)
+ g.add_edge(2, 4)
+ g.add_edge(3, 5)
+ g.add_edge(3, 6)
+ g.add_edge(5, 4)
+ g.add_edge(4, 1)
+ g.add_edge(1, 5)
+ lines = []
+ write = lines.append
+ # Use each node as the starting point to demonstrate how the representation
+ # changes.
+ nodes = sorted(g.nodes())
+ for n in nodes:
+ write(f"--- source node: {n} ---")
+ nx.write_network_text(g, path=write, sources=[n], end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- source node: 1 ---
+ ╙── 1 ╾ 4
+ ├─╼ 2
+ │ └─╼ 4 ╾ 5
+ │ └─╼ ...
+ ├─╼ 3
+ │ ├─╼ 5 ╾ 1
+ │ │ └─╼ ...
+ │ └─╼ 6
+ └─╼ ...
+ --- source node: 2 ---
+ ╙── 2 ╾ 1
+ └─╼ 4 ╾ 5
+ └─╼ 1
+ ├─╼ 3
+ │ ├─╼ 5 ╾ 1
+ │ │ └─╼ ...
+ │ └─╼ 6
+ └─╼ ...
+ --- source node: 3 ---
+ ╙── 3 ╾ 1
+ ├─╼ 5 ╾ 1
+ │ └─╼ 4 ╾ 2
+ │ └─╼ 1
+ │ ├─╼ 2
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ 6
+ --- source node: 4 ---
+ ╙── 4 ╾ 2, 5
+ └─╼ 1
+ ├─╼ 2
+ │ └─╼ ...
+ ├─╼ 3
+ │ ├─╼ 5 ╾ 1
+ │ │ └─╼ ...
+ │ └─╼ 6
+ └─╼ ...
+ --- source node: 5 ---
+ ╙── 5 ╾ 3, 1
+ └─╼ 4 ╾ 2
+ └─╼ 1
+ ├─╼ 2
+ │ └─╼ ...
+ ├─╼ 3
+ │ ├─╼ 6
+ │ └─╼ ...
+ └─╼ ...
+ --- source node: 6 ---
+ ╙── 6 ╾ 3
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_star_graph():
+ graph = nx.star_graph(5, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╙── 1
+ └── 0
+ ├── 2
+ ├── 3
+ ├── 4
+ └── 5
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_path_graph():
+ graph = nx.path_graph(3, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╙── 0
+ └── 1
+ └── 2
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_lollipop_graph():
+ graph = nx.lollipop_graph(4, 2, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╙── 5
+ └── 4
+ └── 3
+ ├── 0
+ │ ├── 1 ─ 3
+ │ │ └── 2 ─ 0, 3
+ │ └── ...
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_wheel_graph():
+ graph = nx.wheel_graph(7, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╙── 1
+ ├── 0
+ │ ├── 2 ─ 1
+ │ │ └── 3 ─ 0
+ │ │ └── 4 ─ 0
+ │ │ └── 5 ─ 0
+ │ │ └── 6 ─ 0, 1
+ │ └── ...
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_circular_ladder_graph():
+ graph = nx.circular_ladder_graph(4, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╙── 0
+ ├── 1
+ │ ├── 2
+ │ │ ├── 3 ─ 0
+ │ │ │ └── 7
+ │ │ │ ├── 6 ─ 2
+ │ │ │ │ └── 5 ─ 1
+ │ │ │ │ └── 4 ─ 0, 7
+ │ │ │ └── ...
+ │ │ └── ...
+ │ └── ...
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_dorogovtsev_goltsev_mendes_graph():
+ graph = nx.dorogovtsev_goltsev_mendes_graph(4, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ ╙── 15
+ ├── 0
+ │ ├── 1 ─ 15
+ │ │ ├── 2 ─ 0
+ │ │ │ ├── 4 ─ 0
+ │ │ │ │ ├── 9 ─ 0
+ │ │ │ │ │ ├── 22 ─ 0
+ │ │ │ │ │ └── 38 ─ 4
+ │ │ │ │ ├── 13 ─ 2
+ │ │ │ │ │ ├── 34 ─ 2
+ │ │ │ │ │ └── 39 ─ 4
+ │ │ │ │ ├── 18 ─ 0
+ │ │ │ │ ├── 30 ─ 2
+ │ │ │ │ └── ...
+ │ │ │ ├── 5 ─ 1
+ │ │ │ │ ├── 12 ─ 1
+ │ │ │ │ │ ├── 29 ─ 1
+ │ │ │ │ │ └── 40 ─ 5
+ │ │ │ │ ├── 14 ─ 2
+ │ │ │ │ │ ├── 35 ─ 2
+ │ │ │ │ │ └── 41 ─ 5
+ │ │ │ │ ├── 25 ─ 1
+ │ │ │ │ ├── 31 ─ 2
+ │ │ │ │ └── ...
+ │ │ │ ├── 7 ─ 0
+ │ │ │ │ ├── 20 ─ 0
+ │ │ │ │ └── 32 ─ 2
+ │ │ │ ├── 10 ─ 1
+ │ │ │ │ ├── 27 ─ 1
+ │ │ │ │ └── 33 ─ 2
+ │ │ │ ├── 16 ─ 0
+ │ │ │ ├── 23 ─ 1
+ │ │ │ └── ...
+ │ │ ├── 3 ─ 0
+ │ │ │ ├── 8 ─ 0
+ │ │ │ │ ├── 21 ─ 0
+ │ │ │ │ └── 36 ─ 3
+ │ │ │ ├── 11 ─ 1
+ │ │ │ │ ├── 28 ─ 1
+ │ │ │ │ └── 37 ─ 3
+ │ │ │ ├── 17 ─ 0
+ │ │ │ ├── 24 ─ 1
+ │ │ │ └── ...
+ │ │ ├── 6 ─ 0
+ │ │ │ ├── 19 ─ 0
+ │ │ │ └── 26 ─ 1
+ │ │ └── ...
+ │ └── ...
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_tree_max_depth():
+ orig = nx.balanced_tree(r=1, h=3, create_using=nx.DiGraph)
+ lines = []
+ write = lines.append
+ write("--- directed case, max_depth=0 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=0)
+ write("--- directed case, max_depth=1 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=1)
+ write("--- directed case, max_depth=2 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=2)
+ write("--- directed case, max_depth=3 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=3)
+ write("--- directed case, max_depth=4 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=4)
+ write("--- undirected case, max_depth=0 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=0)
+ write("--- undirected case, max_depth=1 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=1)
+ write("--- undirected case, max_depth=2 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=2)
+ write("--- undirected case, max_depth=3 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=3)
+ write("--- undirected case, max_depth=4 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=4)
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- directed case, max_depth=0 ---
+ ╙ ...
+ --- directed case, max_depth=1 ---
+ ╙── 0
+ └─╼ ...
+ --- directed case, max_depth=2 ---
+ ╙── 0
+ └─╼ 1
+ └─╼ ...
+ --- directed case, max_depth=3 ---
+ ╙── 0
+ └─╼ 1
+ └─╼ 2
+ └─╼ ...
+ --- directed case, max_depth=4 ---
+ ╙── 0
+ └─╼ 1
+ └─╼ 2
+ └─╼ 3
+ --- undirected case, max_depth=0 ---
+ ╙ ...
+ --- undirected case, max_depth=1 ---
+ ╙── 0 ─ 1
+ └── ...
+ --- undirected case, max_depth=2 ---
+ ╙── 0
+ └── 1 ─ 2
+ └── ...
+ --- undirected case, max_depth=3 ---
+ ╙── 0
+ └── 1
+ └── 2 ─ 3
+ └── ...
+ --- undirected case, max_depth=4 ---
+ ╙── 0
+ └── 1
+ └── 2
+ └── 3
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_graph_max_depth():
+ orig = nx.erdos_renyi_graph(10, 0.15, directed=True, seed=40392)
+ lines = []
+ write = lines.append
+ write("--- directed case, max_depth=None ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=None)
+ write("--- directed case, max_depth=0 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=0)
+ write("--- directed case, max_depth=1 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=1)
+ write("--- directed case, max_depth=2 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=2)
+ write("--- directed case, max_depth=3 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=3)
+ write("--- undirected case, max_depth=None ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=None)
+ write("--- undirected case, max_depth=0 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=0)
+ write("--- undirected case, max_depth=1 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=1)
+ write("--- undirected case, max_depth=2 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=2)
+ write("--- undirected case, max_depth=3 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=3)
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- directed case, max_depth=None ---
+ ╟── 4
+ ╎ ├─╼ 0 ╾ 3
+ ╎ ├─╼ 5 ╾ 7
+ ╎ │ └─╼ 3
+ ╎ │ ├─╼ 1 ╾ 9
+ ╎ │ │ └─╼ 9 ╾ 6
+ ╎ │ │ ├─╼ 6
+ ╎ │ │ │ └─╼ ...
+ ╎ │ │ ├─╼ 7 ╾ 4
+ ╎ │ │ │ ├─╼ 2
+ ╎ │ │ │ └─╼ ...
+ ╎ │ │ └─╼ ...
+ ╎ │ └─╼ ...
+ ╎ └─╼ ...
+ ╙── 8
+ --- directed case, max_depth=0 ---
+ ╙ ...
+ --- directed case, max_depth=1 ---
+ ╟── 4
+ ╎ └─╼ ...
+ ╙── 8
+ --- directed case, max_depth=2 ---
+ ╟── 4
+ ╎ ├─╼ 0 ╾ 3
+ ╎ ├─╼ 5 ╾ 7
+ ╎ │ └─╼ ...
+ ╎ └─╼ 7 ╾ 9
+ ╎ └─╼ ...
+ ╙── 8
+ --- directed case, max_depth=3 ---
+ ╟── 4
+ ╎ ├─╼ 0 ╾ 3
+ ╎ ├─╼ 5 ╾ 7
+ ╎ │ └─╼ 3
+ ╎ │ └─╼ ...
+ ╎ └─╼ 7 ╾ 9
+ ╎ ├─╼ 2
+ ╎ └─╼ ...
+ ╙── 8
+ --- undirected case, max_depth=None ---
+ ╟── 8
+ ╙── 2
+ └── 7
+ ├── 4
+ │ ├── 0
+ │ │ └── 3
+ │ │ ├── 1
+ │ │ │ └── 9 ─ 7
+ │ │ │ └── 6
+ │ │ └── 5 ─ 4, 7
+ │ └── ...
+ └── ...
+ --- undirected case, max_depth=0 ---
+ ╙ ...
+ --- undirected case, max_depth=1 ---
+ ╟── 8
+ ╙── 2 ─ 7
+ └── ...
+ --- undirected case, max_depth=2 ---
+ ╟── 8
+ ╙── 2
+ └── 7 ─ 4, 5, 9
+ └── ...
+ --- undirected case, max_depth=3 ---
+ ╟── 8
+ ╙── 2
+ └── 7
+ ├── 4 ─ 0, 5
+ │ └── ...
+ ├── 5 ─ 4, 3
+ │ └── ...
+ └── 9 ─ 1, 6
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_clique_max_depth():
+ orig = nx.complete_graph(5, nx.DiGraph)
+ lines = []
+ write = lines.append
+ write("--- directed case, max_depth=None ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=None)
+ write("--- directed case, max_depth=0 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=0)
+ write("--- directed case, max_depth=1 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=1)
+ write("--- directed case, max_depth=2 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=2)
+ write("--- directed case, max_depth=3 ---")
+ nx.write_network_text(orig, path=write, end="", max_depth=3)
+ write("--- undirected case, max_depth=None ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=None)
+ write("--- undirected case, max_depth=0 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=0)
+ write("--- undirected case, max_depth=1 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=1)
+ write("--- undirected case, max_depth=2 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=2)
+ write("--- undirected case, max_depth=3 ---")
+ nx.write_network_text(orig.to_undirected(), path=write, end="", max_depth=3)
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- directed case, max_depth=None ---
+ ╙── 0 ╾ 1, 2, 3, 4
+ ├─╼ 1 ╾ 2, 3, 4
+ │ ├─╼ 2 ╾ 0, 3, 4
+ │ │ ├─╼ 3 ╾ 0, 1, 4
+ │ │ │ ├─╼ 4 ╾ 0, 1, 2
+ │ │ │ │ └─╼ ...
+ │ │ │ └─╼ ...
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- directed case, max_depth=0 ---
+ ╙ ...
+ --- directed case, max_depth=1 ---
+ ╙── 0 ╾ 1, 2, 3, 4
+ └─╼ ...
+ --- directed case, max_depth=2 ---
+ ╙── 0 ╾ 1, 2, 3, 4
+ ├─╼ 1 ╾ 2, 3, 4
+ │ └─╼ ...
+ ├─╼ 2 ╾ 1, 3, 4
+ │ └─╼ ...
+ ├─╼ 3 ╾ 1, 2, 4
+ │ └─╼ ...
+ └─╼ 4 ╾ 1, 2, 3
+ └─╼ ...
+ --- directed case, max_depth=3 ---
+ ╙── 0 ╾ 1, 2, 3, 4
+ ├─╼ 1 ╾ 2, 3, 4
+ │ ├─╼ 2 ╾ 0, 3, 4
+ │ │ └─╼ ...
+ │ ├─╼ 3 ╾ 0, 2, 4
+ │ │ └─╼ ...
+ │ ├─╼ 4 ╾ 0, 2, 3
+ │ │ └─╼ ...
+ │ └─╼ ...
+ └─╼ ...
+ --- undirected case, max_depth=None ---
+ ╙── 0
+ ├── 1
+ │ ├── 2 ─ 0
+ │ │ ├── 3 ─ 0, 1
+ │ │ │ └── 4 ─ 0, 1, 2
+ │ │ └── ...
+ │ └── ...
+ └── ...
+ --- undirected case, max_depth=0 ---
+ ╙ ...
+ --- undirected case, max_depth=1 ---
+ ╙── 0 ─ 1, 2, 3, 4
+ └── ...
+ --- undirected case, max_depth=2 ---
+ ╙── 0
+ ├── 1 ─ 2, 3, 4
+ │ └── ...
+ ├── 2 ─ 1, 3, 4
+ │ └── ...
+ ├── 3 ─ 1, 2, 4
+ │ └── ...
+ └── 4 ─ 1, 2, 3
+ --- undirected case, max_depth=3 ---
+ ╙── 0
+ ├── 1
+ │ ├── 2 ─ 0, 3, 4
+ │ │ └── ...
+ │ ├── 3 ─ 0, 2, 4
+ │ │ └── ...
+ │ └── 4 ─ 0, 2, 3
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_custom_label():
+ # Create a directed forest with labels
+ graph = nx.erdos_renyi_graph(5, 0.4, directed=True, seed=359222358)
+ for node in graph.nodes:
+ graph.nodes[node]["label"] = f"Node({node})"
+ graph.nodes[node]["chr"] = chr(node + ord("a") - 1)
+ if node % 2 == 0:
+ graph.nodes[node]["part"] = chr(node + ord("a"))
+
+ lines = []
+ write = lines.append
+ write("--- when with_labels=True, uses the 'label' attr ---")
+ nx.write_network_text(graph, path=write, with_labels=True, end="", max_depth=None)
+ write("--- when with_labels=False, uses str(node) value ---")
+ nx.write_network_text(graph, path=write, with_labels=False, end="", max_depth=None)
+ write("--- when with_labels is a string, use that attr ---")
+ nx.write_network_text(graph, path=write, with_labels="chr", end="", max_depth=None)
+ write("--- fallback to str(node) when the attr does not exist ---")
+ nx.write_network_text(graph, path=write, with_labels="part", end="", max_depth=None)
+
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- when with_labels=True, uses the 'label' attr ---
+ ╙── Node(1)
+ └─╼ Node(3) ╾ Node(2)
+ ├─╼ Node(0)
+ │ ├─╼ Node(2) ╾ Node(3), Node(4)
+ │ │ └─╼ ...
+ │ └─╼ Node(4)
+ │ └─╼ ...
+ └─╼ ...
+ --- when with_labels=False, uses str(node) value ---
+ ╙── 1
+ └─╼ 3 ╾ 2
+ ├─╼ 0
+ │ ├─╼ 2 ╾ 3, 4
+ │ │ └─╼ ...
+ │ └─╼ 4
+ │ └─╼ ...
+ └─╼ ...
+ --- when with_labels is a string, use that attr ---
+ ╙── a
+ └─╼ c ╾ b
+ ├─╼ `
+ │ ├─╼ b ╾ c, d
+ │ │ └─╼ ...
+ │ └─╼ d
+ │ └─╼ ...
+ └─╼ ...
+ --- fallback to str(node) when the attr does not exist ---
+ ╙── 1
+ └─╼ 3 ╾ c
+ ├─╼ a
+ │ ├─╼ c ╾ 3, e
+ │ │ └─╼ ...
+ │ └─╼ e
+ │ └─╼ ...
+ └─╼ ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_write_network_text_vertical_chains():
+ graph1 = nx.lollipop_graph(4, 2, create_using=nx.Graph)
+ graph1.add_edge(0, -1)
+ graph1.add_edge(-1, -2)
+ graph1.add_edge(-2, -3)
+
+ graph2 = graph1.to_directed()
+ graph2.remove_edges_from([(u, v) for u, v in graph2.edges if v > u])
+
+ lines = []
+ write = lines.append
+ write("--- Undirected UTF ---")
+ nx.write_network_text(graph1, path=write, end="", vertical_chains=True)
+ write("--- Undirected ASCI ---")
+ nx.write_network_text(
+ graph1, path=write, end="", vertical_chains=True, ascii_only=True
+ )
+ write("--- Directed UTF ---")
+ nx.write_network_text(graph2, path=write, end="", vertical_chains=True)
+ write("--- Directed ASCI ---")
+ nx.write_network_text(
+ graph2, path=write, end="", vertical_chains=True, ascii_only=True
+ )
+
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- Undirected UTF ---
+ ╙── 5
+ │
+ 4
+ │
+ 3
+ ├── 0
+ │ ├── 1 ─ 3
+ │ │ │
+ │ │ 2 ─ 0, 3
+ │ ├── -1
+ │ │ │
+ │ │ -2
+ │ │ │
+ │ │ -3
+ │ └── ...
+ └── ...
+ --- Undirected ASCI ---
+ +-- 5
+ |
+ 4
+ |
+ 3
+ |-- 0
+ | |-- 1 - 3
+ | | |
+ | | 2 - 0, 3
+ | |-- -1
+ | | |
+ | | -2
+ | | |
+ | | -3
+ | L-- ...
+ L-- ...
+ --- Directed UTF ---
+ ╙── 5
+ ╽
+ 4
+ ╽
+ 3
+ ├─╼ 0 ╾ 1, 2
+ │ ╽
+ │ -1
+ │ ╽
+ │ -2
+ │ ╽
+ │ -3
+ ├─╼ 1 ╾ 2
+ │ └─╼ ...
+ └─╼ 2
+ └─╼ ...
+ --- Directed ASCI ---
+ +-- 5
+ !
+ 4
+ !
+ 3
+ |-> 0 <- 1, 2
+ | !
+ | -1
+ | !
+ | -2
+ | !
+ | -3
+ |-> 1 <- 2
+ | L-> ...
+ L-> 2
+ L-> ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_collapse_directed():
+ graph = nx.balanced_tree(r=2, h=3, create_using=nx.DiGraph)
+ lines = []
+ write = lines.append
+ write("--- Original ---")
+ nx.write_network_text(graph, path=write, end="")
+ graph.nodes[1]["collapse"] = True
+ write("--- Collapse Node 1 ---")
+ nx.write_network_text(graph, path=write, end="")
+ write("--- Add alternate path (5, 3) to collapsed zone")
+ graph.add_edge(5, 3)
+ nx.write_network_text(graph, path=write, end="")
+ write("--- Collapse Node 0 ---")
+ graph.nodes[0]["collapse"] = True
+ nx.write_network_text(graph, path=write, end="")
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- Original ---
+ ╙── 0
+ ├─╼ 1
+ │ ├─╼ 3
+ │ │ ├─╼ 7
+ │ │ └─╼ 8
+ │ └─╼ 4
+ │ ├─╼ 9
+ │ └─╼ 10
+ └─╼ 2
+ ├─╼ 5
+ │ ├─╼ 11
+ │ └─╼ 12
+ └─╼ 6
+ ├─╼ 13
+ └─╼ 14
+ --- Collapse Node 1 ---
+ ╙── 0
+ ├─╼ 1
+ │ └─╼ ...
+ └─╼ 2
+ ├─╼ 5
+ │ ├─╼ 11
+ │ └─╼ 12
+ └─╼ 6
+ ├─╼ 13
+ └─╼ 14
+ --- Add alternate path (5, 3) to collapsed zone
+ ╙── 0
+ ├─╼ 1
+ │ └─╼ ...
+ └─╼ 2
+ ├─╼ 5
+ │ ├─╼ 11
+ │ ├─╼ 12
+ │ └─╼ 3 ╾ 1
+ │ ├─╼ 7
+ │ └─╼ 8
+ └─╼ 6
+ ├─╼ 13
+ └─╼ 14
+ --- Collapse Node 0 ---
+ ╙── 0
+ └─╼ ...
+ """
+ ).strip()
+ assert target == text
+
+
+def test_collapse_undirected():
+ graph = nx.balanced_tree(r=2, h=3, create_using=nx.Graph)
+ lines = []
+ write = lines.append
+ write("--- Original ---")
+ nx.write_network_text(graph, path=write, end="", sources=[0])
+ graph.nodes[1]["collapse"] = True
+ write("--- Collapse Node 1 ---")
+ nx.write_network_text(graph, path=write, end="", sources=[0])
+ write("--- Add alternate path (5, 3) to collapsed zone")
+ graph.add_edge(5, 3)
+ nx.write_network_text(graph, path=write, end="", sources=[0])
+ write("--- Collapse Node 0 ---")
+ graph.nodes[0]["collapse"] = True
+ nx.write_network_text(graph, path=write, end="", sources=[0])
+ text = "\n".join(lines)
+ target = dedent(
+ """
+ --- Original ---
+ ╙── 0
+ ├── 1
+ │ ├── 3
+ │ │ ├── 7
+ │ │ └── 8
+ │ └── 4
+ │ ├── 9
+ │ └── 10
+ └── 2
+ ├── 5
+ │ ├── 11
+ │ └── 12
+ └── 6
+ ├── 13
+ └── 14
+ --- Collapse Node 1 ---
+ ╙── 0
+ ├── 1 ─ 3, 4
+ │ └── ...
+ └── 2
+ ├── 5
+ │ ├── 11
+ │ └── 12
+ └── 6
+ ├── 13
+ └── 14
+ --- Add alternate path (5, 3) to collapsed zone
+ ╙── 0
+ ├── 1 ─ 3, 4
+ │ └── ...
+ └── 2
+ ├── 5
+ │ ├── 11
+ │ ├── 12
+ │ └── 3 ─ 1
+ │ ├── 7
+ │ └── 8
+ └── 6
+ ├── 13
+ └── 14
+ --- Collapse Node 0 ---
+ ╙── 0 ─ 1, 2
+ └── ...
+ """
+ ).strip()
+ assert target == text
+
+
+def generate_test_graphs():
+ """
+ Generate a gauntlet of different test graphs with different properties
+ """
+ import random
+
+ rng = random.Random(976689776)
+ num_randomized = 3
+
+ for directed in [0, 1]:
+ cls = nx.DiGraph if directed else nx.Graph
+
+ for num_nodes in range(17):
+ # Disconnected graph
+ graph = cls()
+ graph.add_nodes_from(range(num_nodes))
+ yield graph
+
+ # Randomize graphs
+ if num_nodes > 0:
+ for p in [0.1, 0.3, 0.5, 0.7, 0.9]:
+ for seed in range(num_randomized):
+ graph = nx.erdos_renyi_graph(
+ num_nodes, p, directed=directed, seed=rng
+ )
+ yield graph
+
+ yield nx.complete_graph(num_nodes, cls)
+
+ yield nx.path_graph(3, create_using=cls)
+ yield nx.balanced_tree(r=1, h=3, create_using=cls)
+ if not directed:
+ yield nx.circular_ladder_graph(4, create_using=cls)
+ yield nx.star_graph(5, create_using=cls)
+ yield nx.lollipop_graph(4, 2, create_using=cls)
+ yield nx.wheel_graph(7, create_using=cls)
+ yield nx.dorogovtsev_goltsev_mendes_graph(4, create_using=cls)
+
+
+@pytest.mark.parametrize(
+ ("vertical_chains", "ascii_only"),
+ tuple(
+ [
+ (vertical_chains, ascii_only)
+ for vertical_chains in [0, 1]
+ for ascii_only in [0, 1]
+ ]
+ ),
+)
+def test_network_text_round_trip(vertical_chains, ascii_only):
+ """
+ Write the graph to network text format, then parse it back in, assert it is
+ the same as the original graph. Passing this test is strong validation of
+ both the format generator and parser.
+ """
+ from networkx.readwrite.text import _parse_network_text
+
+ for graph in generate_test_graphs():
+ graph = nx.relabel_nodes(graph, {n: str(n) for n in graph.nodes})
+ lines = list(
+ nx.generate_network_text(
+ graph, vertical_chains=vertical_chains, ascii_only=ascii_only
+ )
+ )
+ new = _parse_network_text(lines)
+ try:
+ assert new.nodes == graph.nodes
+ assert new.edges == graph.edges
+ except Exception:
+ nx.write_network_text(graph)
+ raise