Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/graph.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph_historical.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_function.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graph_historical.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graphviews.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multidigraph.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multigraph.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_subgraphviews.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/historical_tests.py +474 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_coreviews.py +362 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_graph.py +920 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_graph_historical.py +12 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_graphviews.py +350 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_multidigraph.py +459 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_special.py +131 -0
- env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_subgraphviews.py +362 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__init__.py +18 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/edgelist.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/leda.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/sparse6.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/text.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/gexf.py +1065 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/graphml.py +1052 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/__init__.py +18 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/adjacency.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/cytoscape.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/adjacency.py +156 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/cytoscape.py +178 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/node_link.py +244 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/tree.py +137 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/multiline_adjlist.py +393 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/pajek.py +286 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/sparse6.py +376 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/test_adjlist.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/networkx/classes/__pycache__/graph.cpython-310.pyc
ADDED
Binary file (69.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (187 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-310.pyc
ADDED
Binary file (4.97 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-310.pyc
ADDED
Binary file (14 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph_historical.cpython-310.pyc
ADDED
Binary file (4.89 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-310.pyc
ADDED
Binary file (5.04 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_function.cpython-310.pyc
ADDED
Binary file (22.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graph_historical.cpython-310.pyc
ADDED
Binary file (704 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graphviews.cpython-310.pyc
ADDED
Binary file (13.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multidigraph.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multigraph.cpython-310.pyc
ADDED
Binary file (17.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_subgraphviews.cpython-310.pyc
ADDED
Binary file (12.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/historical_tests.py
ADDED
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Original NetworkX graph tests"""
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
6 |
+
from networkx.utils import edges_equal, nodes_equal
|
7 |
+
|
8 |
+
|
9 |
+
class HistoricalTests:
|
10 |
+
@classmethod
|
11 |
+
def setup_class(cls):
|
12 |
+
cls.null = nx.null_graph()
|
13 |
+
cls.P1 = cnlti(nx.path_graph(1), first_label=1)
|
14 |
+
cls.P3 = cnlti(nx.path_graph(3), first_label=1)
|
15 |
+
cls.P10 = cnlti(nx.path_graph(10), first_label=1)
|
16 |
+
cls.K1 = cnlti(nx.complete_graph(1), first_label=1)
|
17 |
+
cls.K3 = cnlti(nx.complete_graph(3), first_label=1)
|
18 |
+
cls.K4 = cnlti(nx.complete_graph(4), first_label=1)
|
19 |
+
cls.K5 = cnlti(nx.complete_graph(5), first_label=1)
|
20 |
+
cls.K10 = cnlti(nx.complete_graph(10), first_label=1)
|
21 |
+
cls.G = nx.Graph
|
22 |
+
|
23 |
+
def test_name(self):
|
24 |
+
G = self.G(name="test")
|
25 |
+
assert G.name == "test"
|
26 |
+
H = self.G()
|
27 |
+
assert H.name == ""
|
28 |
+
|
29 |
+
# Nodes
|
30 |
+
|
31 |
+
def test_add_remove_node(self):
|
32 |
+
G = self.G()
|
33 |
+
G.add_node("A")
|
34 |
+
assert G.has_node("A")
|
35 |
+
G.remove_node("A")
|
36 |
+
assert not G.has_node("A")
|
37 |
+
|
38 |
+
def test_nonhashable_node(self):
|
39 |
+
# Test if a non-hashable object is in the Graph. A python dict will
|
40 |
+
# raise a TypeError, but for a Graph class a simple False should be
|
41 |
+
# returned (see Graph __contains__). If it cannot be a node then it is
|
42 |
+
# not a node.
|
43 |
+
G = self.G()
|
44 |
+
assert not G.has_node(["A"])
|
45 |
+
assert not G.has_node({"A": 1})
|
46 |
+
|
47 |
+
def test_add_nodes_from(self):
|
48 |
+
G = self.G()
|
49 |
+
G.add_nodes_from(list("ABCDEFGHIJKL"))
|
50 |
+
assert G.has_node("L")
|
51 |
+
G.remove_nodes_from(["H", "I", "J", "K", "L"])
|
52 |
+
G.add_nodes_from([1, 2, 3, 4])
|
53 |
+
assert sorted(G.nodes(), key=str) == [
|
54 |
+
1,
|
55 |
+
2,
|
56 |
+
3,
|
57 |
+
4,
|
58 |
+
"A",
|
59 |
+
"B",
|
60 |
+
"C",
|
61 |
+
"D",
|
62 |
+
"E",
|
63 |
+
"F",
|
64 |
+
"G",
|
65 |
+
]
|
66 |
+
# test __iter__
|
67 |
+
assert sorted(G, key=str) == [1, 2, 3, 4, "A", "B", "C", "D", "E", "F", "G"]
|
68 |
+
|
69 |
+
def test_contains(self):
|
70 |
+
G = self.G()
|
71 |
+
G.add_node("A")
|
72 |
+
assert "A" in G
|
73 |
+
assert [] not in G # never raise a Key or TypeError in this test
|
74 |
+
assert {1: 1} not in G
|
75 |
+
|
76 |
+
def test_add_remove(self):
|
77 |
+
# Test add_node and remove_node acting for various nbunch
|
78 |
+
G = self.G()
|
79 |
+
G.add_node("m")
|
80 |
+
assert G.has_node("m")
|
81 |
+
G.add_node("m") # no complaints
|
82 |
+
pytest.raises(nx.NetworkXError, G.remove_node, "j")
|
83 |
+
G.remove_node("m")
|
84 |
+
assert list(G) == []
|
85 |
+
|
86 |
+
def test_nbunch_is_list(self):
|
87 |
+
G = self.G()
|
88 |
+
G.add_nodes_from(list("ABCD"))
|
89 |
+
G.add_nodes_from(self.P3) # add nbunch of nodes (nbunch=Graph)
|
90 |
+
assert sorted(G.nodes(), key=str) == [1, 2, 3, "A", "B", "C", "D"]
|
91 |
+
G.remove_nodes_from(self.P3) # remove nbunch of nodes (nbunch=Graph)
|
92 |
+
assert sorted(G.nodes(), key=str) == ["A", "B", "C", "D"]
|
93 |
+
|
94 |
+
def test_nbunch_is_set(self):
|
95 |
+
G = self.G()
|
96 |
+
nbunch = set("ABCDEFGHIJKL")
|
97 |
+
G.add_nodes_from(nbunch)
|
98 |
+
assert G.has_node("L")
|
99 |
+
|
100 |
+
def test_nbunch_dict(self):
|
101 |
+
# nbunch is a dict with nodes as keys
|
102 |
+
G = self.G()
|
103 |
+
nbunch = set("ABCDEFGHIJKL")
|
104 |
+
G.add_nodes_from(nbunch)
|
105 |
+
nbunch = {"I": "foo", "J": 2, "K": True, "L": "spam"}
|
106 |
+
G.remove_nodes_from(nbunch)
|
107 |
+
assert sorted(G.nodes(), key=str), ["A", "B", "C", "D", "E", "F", "G", "H"]
|
108 |
+
|
109 |
+
def test_nbunch_iterator(self):
|
110 |
+
G = self.G()
|
111 |
+
G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
|
112 |
+
n_iter = self.P3.nodes()
|
113 |
+
G.add_nodes_from(n_iter)
|
114 |
+
assert sorted(G.nodes(), key=str) == [
|
115 |
+
1,
|
116 |
+
2,
|
117 |
+
3,
|
118 |
+
"A",
|
119 |
+
"B",
|
120 |
+
"C",
|
121 |
+
"D",
|
122 |
+
"E",
|
123 |
+
"F",
|
124 |
+
"G",
|
125 |
+
"H",
|
126 |
+
]
|
127 |
+
n_iter = self.P3.nodes() # rebuild same iterator
|
128 |
+
G.remove_nodes_from(n_iter) # remove nbunch of nodes (nbunch=iterator)
|
129 |
+
assert sorted(G.nodes(), key=str) == ["A", "B", "C", "D", "E", "F", "G", "H"]
|
130 |
+
|
131 |
+
def test_nbunch_graph(self):
|
132 |
+
G = self.G()
|
133 |
+
G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
|
134 |
+
nbunch = self.K3
|
135 |
+
G.add_nodes_from(nbunch)
|
136 |
+
assert sorted(G.nodes(), key=str), [
|
137 |
+
1,
|
138 |
+
2,
|
139 |
+
3,
|
140 |
+
"A",
|
141 |
+
"B",
|
142 |
+
"C",
|
143 |
+
"D",
|
144 |
+
"E",
|
145 |
+
"F",
|
146 |
+
"G",
|
147 |
+
"H",
|
148 |
+
]
|
149 |
+
|
150 |
+
# Edges
|
151 |
+
|
152 |
+
def test_add_edge(self):
|
153 |
+
G = self.G()
|
154 |
+
pytest.raises(TypeError, G.add_edge, "A")
|
155 |
+
|
156 |
+
G.add_edge("A", "B") # testing add_edge()
|
157 |
+
G.add_edge("A", "B") # should fail silently
|
158 |
+
assert G.has_edge("A", "B")
|
159 |
+
assert not G.has_edge("A", "C")
|
160 |
+
assert G.has_edge(*("A", "B"))
|
161 |
+
if G.is_directed():
|
162 |
+
assert not G.has_edge("B", "A")
|
163 |
+
else:
|
164 |
+
# G is undirected, so B->A is an edge
|
165 |
+
assert G.has_edge("B", "A")
|
166 |
+
|
167 |
+
G.add_edge("A", "C") # test directedness
|
168 |
+
G.add_edge("C", "A")
|
169 |
+
G.remove_edge("C", "A")
|
170 |
+
if G.is_directed():
|
171 |
+
assert G.has_edge("A", "C")
|
172 |
+
else:
|
173 |
+
assert not G.has_edge("A", "C")
|
174 |
+
assert not G.has_edge("C", "A")
|
175 |
+
|
176 |
+
def test_self_loop(self):
|
177 |
+
G = self.G()
|
178 |
+
G.add_edge("A", "A") # test self loops
|
179 |
+
assert G.has_edge("A", "A")
|
180 |
+
G.remove_edge("A", "A")
|
181 |
+
G.add_edge("X", "X")
|
182 |
+
assert G.has_node("X")
|
183 |
+
G.remove_node("X")
|
184 |
+
G.add_edge("A", "Z") # should add the node silently
|
185 |
+
assert G.has_node("Z")
|
186 |
+
|
187 |
+
def test_add_edges_from(self):
|
188 |
+
G = self.G()
|
189 |
+
G.add_edges_from([("B", "C")]) # test add_edges_from()
|
190 |
+
assert G.has_edge("B", "C")
|
191 |
+
if G.is_directed():
|
192 |
+
assert not G.has_edge("C", "B")
|
193 |
+
else:
|
194 |
+
assert G.has_edge("C", "B") # undirected
|
195 |
+
|
196 |
+
G.add_edges_from([("D", "F"), ("B", "D")])
|
197 |
+
assert G.has_edge("D", "F")
|
198 |
+
assert G.has_edge("B", "D")
|
199 |
+
|
200 |
+
if G.is_directed():
|
201 |
+
assert not G.has_edge("D", "B")
|
202 |
+
else:
|
203 |
+
assert G.has_edge("D", "B") # undirected
|
204 |
+
|
205 |
+
def test_add_edges_from2(self):
|
206 |
+
G = self.G()
|
207 |
+
# after failing silently, should add 2nd edge
|
208 |
+
G.add_edges_from([tuple("IJ"), list("KK"), tuple("JK")])
|
209 |
+
assert G.has_edge(*("I", "J"))
|
210 |
+
assert G.has_edge(*("K", "K"))
|
211 |
+
assert G.has_edge(*("J", "K"))
|
212 |
+
if G.is_directed():
|
213 |
+
assert not G.has_edge(*("K", "J"))
|
214 |
+
else:
|
215 |
+
assert G.has_edge(*("K", "J"))
|
216 |
+
|
217 |
+
def test_add_edges_from3(self):
|
218 |
+
G = self.G()
|
219 |
+
G.add_edges_from(zip(list("ACD"), list("CDE")))
|
220 |
+
assert G.has_edge("D", "E")
|
221 |
+
assert not G.has_edge("E", "C")
|
222 |
+
|
223 |
+
def test_remove_edge(self):
|
224 |
+
G = self.G()
|
225 |
+
G.add_nodes_from([1, 2, 3, "A", "B", "C", "D", "E", "F", "G", "H"])
|
226 |
+
|
227 |
+
G.add_edges_from(zip(list("MNOP"), list("NOPM")))
|
228 |
+
assert G.has_edge("O", "P")
|
229 |
+
assert G.has_edge("P", "M")
|
230 |
+
G.remove_node("P") # tests remove_node()'s handling of edges.
|
231 |
+
assert not G.has_edge("P", "M")
|
232 |
+
pytest.raises(TypeError, G.remove_edge, "M")
|
233 |
+
|
234 |
+
G.add_edge("N", "M")
|
235 |
+
assert G.has_edge("M", "N")
|
236 |
+
G.remove_edge("M", "N")
|
237 |
+
assert not G.has_edge("M", "N")
|
238 |
+
|
239 |
+
# self loop fails silently
|
240 |
+
G.remove_edges_from([list("HI"), list("DF"), tuple("KK"), tuple("JK")])
|
241 |
+
assert not G.has_edge("H", "I")
|
242 |
+
assert not G.has_edge("J", "K")
|
243 |
+
G.remove_edges_from([list("IJ"), list("KK"), list("JK")])
|
244 |
+
assert not G.has_edge("I", "J")
|
245 |
+
G.remove_nodes_from(set("ZEFHIMNO"))
|
246 |
+
G.add_edge("J", "K")
|
247 |
+
|
248 |
+
def test_edges_nbunch(self):
|
249 |
+
# Test G.edges(nbunch) with various forms of nbunch
|
250 |
+
G = self.G()
|
251 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
252 |
+
# node not in nbunch should be quietly ignored
|
253 |
+
pytest.raises(nx.NetworkXError, G.edges, 6)
|
254 |
+
assert list(G.edges("Z")) == [] # iterable non-node
|
255 |
+
# nbunch can be an empty list
|
256 |
+
assert list(G.edges([])) == []
|
257 |
+
if G.is_directed():
|
258 |
+
elist = [("A", "B"), ("A", "C"), ("B", "D")]
|
259 |
+
else:
|
260 |
+
elist = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D")]
|
261 |
+
# nbunch can be a list
|
262 |
+
assert edges_equal(list(G.edges(["A", "B"])), elist)
|
263 |
+
# nbunch can be a set
|
264 |
+
assert edges_equal(G.edges({"A", "B"}), elist)
|
265 |
+
# nbunch can be a graph
|
266 |
+
G1 = self.G()
|
267 |
+
G1.add_nodes_from("AB")
|
268 |
+
assert edges_equal(G.edges(G1), elist)
|
269 |
+
# nbunch can be a dict with nodes as keys
|
270 |
+
ndict = {"A": "thing1", "B": "thing2"}
|
271 |
+
assert edges_equal(G.edges(ndict), elist)
|
272 |
+
# nbunch can be a single node
|
273 |
+
assert edges_equal(list(G.edges("A")), [("A", "B"), ("A", "C")])
|
274 |
+
assert nodes_equal(sorted(G), ["A", "B", "C", "D"])
|
275 |
+
|
276 |
+
# nbunch can be nothing (whole graph)
|
277 |
+
assert edges_equal(
|
278 |
+
list(G.edges()),
|
279 |
+
[("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")],
|
280 |
+
)
|
281 |
+
|
282 |
+
def test_degree(self):
|
283 |
+
G = self.G()
|
284 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
285 |
+
assert G.degree("A") == 2
|
286 |
+
|
287 |
+
# degree of single node in iterable container must return dict
|
288 |
+
assert list(G.degree(["A"])) == [("A", 2)]
|
289 |
+
assert sorted(d for n, d in G.degree(["A", "B"])) == [2, 3]
|
290 |
+
assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
|
291 |
+
|
292 |
+
def test_degree2(self):
|
293 |
+
H = self.G()
|
294 |
+
H.add_edges_from([(1, 24), (1, 2)])
|
295 |
+
assert sorted(d for n, d in H.degree([1, 24])) == [1, 2]
|
296 |
+
|
297 |
+
def test_degree_graph(self):
|
298 |
+
P3 = nx.path_graph(3)
|
299 |
+
P5 = nx.path_graph(5)
|
300 |
+
# silently ignore nodes not in P3
|
301 |
+
assert dict(d for n, d in P3.degree(["A", "B"])) == {}
|
302 |
+
# nbunch can be a graph
|
303 |
+
assert sorted(d for n, d in P5.degree(P3)) == [1, 2, 2]
|
304 |
+
# nbunch can be a graph that's way too big
|
305 |
+
assert sorted(d for n, d in P3.degree(P5)) == [1, 1, 2]
|
306 |
+
assert list(P5.degree([])) == []
|
307 |
+
assert dict(P5.degree([])) == {}
|
308 |
+
|
309 |
+
def test_null(self):
|
310 |
+
null = nx.null_graph()
|
311 |
+
assert list(null.degree()) == []
|
312 |
+
assert dict(null.degree()) == {}
|
313 |
+
|
314 |
+
def test_order_size(self):
|
315 |
+
G = self.G()
|
316 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
317 |
+
assert G.order() == 4
|
318 |
+
assert G.size() == 5
|
319 |
+
assert G.number_of_edges() == 5
|
320 |
+
assert G.number_of_edges("A", "B") == 1
|
321 |
+
assert G.number_of_edges("A", "D") == 0
|
322 |
+
|
323 |
+
def test_copy(self):
|
324 |
+
G = self.G()
|
325 |
+
H = G.copy() # copy
|
326 |
+
assert H.adj == G.adj
|
327 |
+
assert H.name == G.name
|
328 |
+
assert H is not G
|
329 |
+
|
330 |
+
def test_subgraph(self):
|
331 |
+
G = self.G()
|
332 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
333 |
+
SG = G.subgraph(["A", "B", "D"])
|
334 |
+
assert nodes_equal(list(SG), ["A", "B", "D"])
|
335 |
+
assert edges_equal(list(SG.edges()), [("A", "B"), ("B", "D")])
|
336 |
+
|
337 |
+
def test_to_directed(self):
|
338 |
+
G = self.G()
|
339 |
+
if not G.is_directed():
|
340 |
+
G.add_edges_from(
|
341 |
+
[("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
|
342 |
+
)
|
343 |
+
|
344 |
+
DG = G.to_directed()
|
345 |
+
assert DG is not G # directed copy or copy
|
346 |
+
|
347 |
+
assert DG.is_directed()
|
348 |
+
assert DG.name == G.name
|
349 |
+
assert DG.adj == G.adj
|
350 |
+
assert sorted(DG.out_edges(list("AB"))) == [
|
351 |
+
("A", "B"),
|
352 |
+
("A", "C"),
|
353 |
+
("B", "A"),
|
354 |
+
("B", "C"),
|
355 |
+
("B", "D"),
|
356 |
+
]
|
357 |
+
DG.remove_edge("A", "B")
|
358 |
+
assert DG.has_edge("B", "A") # this removes B-A but not A-B
|
359 |
+
assert not DG.has_edge("A", "B")
|
360 |
+
|
361 |
+
def test_to_undirected(self):
|
362 |
+
G = self.G()
|
363 |
+
if G.is_directed():
|
364 |
+
G.add_edges_from(
|
365 |
+
[("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
|
366 |
+
)
|
367 |
+
UG = G.to_undirected() # to_undirected
|
368 |
+
assert UG is not G
|
369 |
+
assert not UG.is_directed()
|
370 |
+
assert G.is_directed()
|
371 |
+
assert UG.name == G.name
|
372 |
+
assert UG.adj != G.adj
|
373 |
+
assert sorted(UG.edges(list("AB"))) == [
|
374 |
+
("A", "B"),
|
375 |
+
("A", "C"),
|
376 |
+
("B", "C"),
|
377 |
+
("B", "D"),
|
378 |
+
]
|
379 |
+
assert sorted(UG.edges(["A", "B"])) == [
|
380 |
+
("A", "B"),
|
381 |
+
("A", "C"),
|
382 |
+
("B", "C"),
|
383 |
+
("B", "D"),
|
384 |
+
]
|
385 |
+
UG.remove_edge("A", "B")
|
386 |
+
assert not UG.has_edge("B", "A")
|
387 |
+
assert not UG.has_edge("A", "B")
|
388 |
+
|
389 |
+
def test_neighbors(self):
|
390 |
+
G = self.G()
|
391 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
392 |
+
G.add_nodes_from("GJK")
|
393 |
+
assert sorted(G["A"]) == ["B", "C"]
|
394 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
395 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
396 |
+
assert sorted(G.neighbors("G")) == []
|
397 |
+
pytest.raises(nx.NetworkXError, G.neighbors, "j")
|
398 |
+
|
399 |
+
def test_iterators(self):
|
400 |
+
G = self.G()
|
401 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
402 |
+
G.add_nodes_from("GJK")
|
403 |
+
assert sorted(G.nodes()) == ["A", "B", "C", "D", "G", "J", "K"]
|
404 |
+
assert edges_equal(
|
405 |
+
G.edges(), [("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
|
406 |
+
)
|
407 |
+
|
408 |
+
assert sorted(v for k, v in G.degree()) == [0, 0, 0, 2, 2, 3, 3]
|
409 |
+
assert sorted(G.degree(), key=str) == [
|
410 |
+
("A", 2),
|
411 |
+
("B", 3),
|
412 |
+
("C", 3),
|
413 |
+
("D", 2),
|
414 |
+
("G", 0),
|
415 |
+
("J", 0),
|
416 |
+
("K", 0),
|
417 |
+
]
|
418 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
419 |
+
pytest.raises(nx.NetworkXError, G.neighbors, "X")
|
420 |
+
G.clear()
|
421 |
+
assert nx.number_of_nodes(G) == 0
|
422 |
+
assert nx.number_of_edges(G) == 0
|
423 |
+
|
424 |
+
def test_null_subgraph(self):
|
425 |
+
# Subgraph of a null graph is a null graph
|
426 |
+
nullgraph = nx.null_graph()
|
427 |
+
G = nx.null_graph()
|
428 |
+
H = G.subgraph([])
|
429 |
+
assert nx.is_isomorphic(H, nullgraph)
|
430 |
+
|
431 |
+
def test_empty_subgraph(self):
|
432 |
+
# Subgraph of an empty graph is an empty graph. test 1
|
433 |
+
nullgraph = nx.null_graph()
|
434 |
+
E5 = nx.empty_graph(5)
|
435 |
+
E10 = nx.empty_graph(10)
|
436 |
+
H = E10.subgraph([])
|
437 |
+
assert nx.is_isomorphic(H, nullgraph)
|
438 |
+
H = E10.subgraph([1, 2, 3, 4, 5])
|
439 |
+
assert nx.is_isomorphic(H, E5)
|
440 |
+
|
441 |
+
def test_complete_subgraph(self):
|
442 |
+
# Subgraph of a complete graph is a complete graph
|
443 |
+
K1 = nx.complete_graph(1)
|
444 |
+
K3 = nx.complete_graph(3)
|
445 |
+
K5 = nx.complete_graph(5)
|
446 |
+
H = K5.subgraph([1, 2, 3])
|
447 |
+
assert nx.is_isomorphic(H, K3)
|
448 |
+
|
449 |
+
def test_subgraph_nbunch(self):
|
450 |
+
nullgraph = nx.null_graph()
|
451 |
+
K1 = nx.complete_graph(1)
|
452 |
+
K3 = nx.complete_graph(3)
|
453 |
+
K5 = nx.complete_graph(5)
|
454 |
+
# Test G.subgraph(nbunch), where nbunch is a single node
|
455 |
+
H = K5.subgraph(1)
|
456 |
+
assert nx.is_isomorphic(H, K1)
|
457 |
+
# Test G.subgraph(nbunch), where nbunch is a set
|
458 |
+
H = K5.subgraph({1})
|
459 |
+
assert nx.is_isomorphic(H, K1)
|
460 |
+
# Test G.subgraph(nbunch), where nbunch is an iterator
|
461 |
+
H = K5.subgraph(iter(K3))
|
462 |
+
assert nx.is_isomorphic(H, K3)
|
463 |
+
# Test G.subgraph(nbunch), where nbunch is another graph
|
464 |
+
H = K5.subgraph(K3)
|
465 |
+
assert nx.is_isomorphic(H, K3)
|
466 |
+
H = K5.subgraph([9])
|
467 |
+
assert nx.is_isomorphic(H, nullgraph)
|
468 |
+
|
469 |
+
def test_node_tuple_issue(self):
|
470 |
+
H = self.G()
|
471 |
+
# Test error handling of tuple as a node
|
472 |
+
pytest.raises(nx.NetworkXError, H.remove_node, (1, 2))
|
473 |
+
H.remove_nodes_from([(1, 2)]) # no error
|
474 |
+
pytest.raises(nx.NetworkXError, H.neighbors, (1, 2))
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_coreviews.py
ADDED
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pickle
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
|
8 |
+
class TestAtlasView:
|
9 |
+
# node->data
|
10 |
+
def setup_method(self):
|
11 |
+
self.d = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
|
12 |
+
self.av = nx.classes.coreviews.AtlasView(self.d)
|
13 |
+
|
14 |
+
def test_pickle(self):
|
15 |
+
view = self.av
|
16 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
17 |
+
assert view == pview
|
18 |
+
assert view.__slots__ == pview.__slots__
|
19 |
+
pview = pickle.loads(pickle.dumps(view))
|
20 |
+
assert view == pview
|
21 |
+
assert view.__slots__ == pview.__slots__
|
22 |
+
|
23 |
+
def test_len(self):
|
24 |
+
assert len(self.av) == len(self.d)
|
25 |
+
|
26 |
+
def test_iter(self):
|
27 |
+
assert list(self.av) == list(self.d)
|
28 |
+
|
29 |
+
def test_getitem(self):
|
30 |
+
assert self.av[1] is self.d[1]
|
31 |
+
assert self.av[2]["color"] == 1
|
32 |
+
pytest.raises(KeyError, self.av.__getitem__, 3)
|
33 |
+
|
34 |
+
def test_copy(self):
|
35 |
+
avcopy = self.av.copy()
|
36 |
+
assert avcopy[0] == self.av[0]
|
37 |
+
assert avcopy == self.av
|
38 |
+
assert avcopy[0] is not self.av[0]
|
39 |
+
assert avcopy is not self.av
|
40 |
+
avcopy[5] = {}
|
41 |
+
assert avcopy != self.av
|
42 |
+
|
43 |
+
avcopy[0]["ht"] = 4
|
44 |
+
assert avcopy[0] != self.av[0]
|
45 |
+
self.av[0]["ht"] = 4
|
46 |
+
assert avcopy[0] == self.av[0]
|
47 |
+
del self.av[0]["ht"]
|
48 |
+
|
49 |
+
assert not hasattr(self.av, "__setitem__")
|
50 |
+
|
51 |
+
def test_items(self):
|
52 |
+
assert sorted(self.av.items()) == sorted(self.d.items())
|
53 |
+
|
54 |
+
def test_str(self):
|
55 |
+
out = str(self.d)
|
56 |
+
assert str(self.av) == out
|
57 |
+
|
58 |
+
def test_repr(self):
|
59 |
+
out = "AtlasView(" + str(self.d) + ")"
|
60 |
+
assert repr(self.av) == out
|
61 |
+
|
62 |
+
|
63 |
+
class TestAdjacencyView:
|
64 |
+
# node->nbr->data
|
65 |
+
def setup_method(self):
|
66 |
+
dd = {"color": "blue", "weight": 1.2}
|
67 |
+
self.nd = {0: dd, 1: {}, 2: {"color": 1}}
|
68 |
+
self.adj = {3: self.nd, 0: {3: dd}, 1: {}, 2: {3: {"color": 1}}}
|
69 |
+
self.adjview = nx.classes.coreviews.AdjacencyView(self.adj)
|
70 |
+
|
71 |
+
def test_pickle(self):
|
72 |
+
view = self.adjview
|
73 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
74 |
+
assert view == pview
|
75 |
+
assert view.__slots__ == pview.__slots__
|
76 |
+
|
77 |
+
def test_len(self):
|
78 |
+
assert len(self.adjview) == len(self.adj)
|
79 |
+
|
80 |
+
def test_iter(self):
|
81 |
+
assert list(self.adjview) == list(self.adj)
|
82 |
+
|
83 |
+
def test_getitem(self):
|
84 |
+
assert self.adjview[1] is not self.adj[1]
|
85 |
+
assert self.adjview[3][0] is self.adjview[0][3]
|
86 |
+
assert self.adjview[2][3]["color"] == 1
|
87 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
88 |
+
|
89 |
+
def test_copy(self):
|
90 |
+
avcopy = self.adjview.copy()
|
91 |
+
assert avcopy[0] == self.adjview[0]
|
92 |
+
assert avcopy[0] is not self.adjview[0]
|
93 |
+
|
94 |
+
avcopy[2][3]["ht"] = 4
|
95 |
+
assert avcopy[2] != self.adjview[2]
|
96 |
+
self.adjview[2][3]["ht"] = 4
|
97 |
+
assert avcopy[2] == self.adjview[2]
|
98 |
+
del self.adjview[2][3]["ht"]
|
99 |
+
|
100 |
+
assert not hasattr(self.adjview, "__setitem__")
|
101 |
+
|
102 |
+
def test_items(self):
|
103 |
+
view_items = sorted((n, dict(d)) for n, d in self.adjview.items())
|
104 |
+
assert view_items == sorted(self.adj.items())
|
105 |
+
|
106 |
+
def test_str(self):
|
107 |
+
out = str(dict(self.adj))
|
108 |
+
assert str(self.adjview) == out
|
109 |
+
|
110 |
+
def test_repr(self):
|
111 |
+
out = self.adjview.__class__.__name__ + "(" + str(self.adj) + ")"
|
112 |
+
assert repr(self.adjview) == out
|
113 |
+
|
114 |
+
|
115 |
+
class TestMultiAdjacencyView(TestAdjacencyView):
|
116 |
+
# node->nbr->key->data
|
117 |
+
def setup_method(self):
|
118 |
+
dd = {"color": "blue", "weight": 1.2}
|
119 |
+
self.kd = {0: dd, 1: {}, 2: {"color": 1}}
|
120 |
+
self.nd = {3: self.kd, 0: {3: dd}, 1: {0: {}}, 2: {3: {"color": 1}}}
|
121 |
+
self.adj = {3: self.nd, 0: {3: {3: dd}}, 1: {}, 2: {3: {8: {}}}}
|
122 |
+
self.adjview = nx.classes.coreviews.MultiAdjacencyView(self.adj)
|
123 |
+
|
124 |
+
def test_getitem(self):
|
125 |
+
assert self.adjview[1] is not self.adj[1]
|
126 |
+
assert self.adjview[3][0][3] is self.adjview[0][3][3]
|
127 |
+
assert self.adjview[3][2][3]["color"] == 1
|
128 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
129 |
+
|
130 |
+
def test_copy(self):
|
131 |
+
avcopy = self.adjview.copy()
|
132 |
+
assert avcopy[0] == self.adjview[0]
|
133 |
+
assert avcopy[0] is not self.adjview[0]
|
134 |
+
|
135 |
+
avcopy[2][3][8]["ht"] = 4
|
136 |
+
assert avcopy[2] != self.adjview[2]
|
137 |
+
self.adjview[2][3][8]["ht"] = 4
|
138 |
+
assert avcopy[2] == self.adjview[2]
|
139 |
+
del self.adjview[2][3][8]["ht"]
|
140 |
+
|
141 |
+
assert not hasattr(self.adjview, "__setitem__")
|
142 |
+
|
143 |
+
|
144 |
+
class TestUnionAtlas:
|
145 |
+
# node->data
|
146 |
+
def setup_method(self):
|
147 |
+
self.s = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
|
148 |
+
self.p = {3: {"color": "blue", "weight": 1.2}, 4: {}, 2: {"watch": 2}}
|
149 |
+
self.av = nx.classes.coreviews.UnionAtlas(self.s, self.p)
|
150 |
+
|
151 |
+
def test_pickle(self):
|
152 |
+
view = self.av
|
153 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
154 |
+
assert view == pview
|
155 |
+
assert view.__slots__ == pview.__slots__
|
156 |
+
|
157 |
+
def test_len(self):
|
158 |
+
assert len(self.av) == len(self.s.keys() | self.p.keys()) == 5
|
159 |
+
|
160 |
+
def test_iter(self):
|
161 |
+
assert set(self.av) == set(self.s) | set(self.p)
|
162 |
+
|
163 |
+
def test_getitem(self):
|
164 |
+
assert self.av[0] is self.s[0]
|
165 |
+
assert self.av[4] is self.p[4]
|
166 |
+
assert self.av[2]["color"] == 1
|
167 |
+
pytest.raises(KeyError, self.av[2].__getitem__, "watch")
|
168 |
+
pytest.raises(KeyError, self.av.__getitem__, 8)
|
169 |
+
|
170 |
+
def test_copy(self):
|
171 |
+
avcopy = self.av.copy()
|
172 |
+
assert avcopy[0] == self.av[0]
|
173 |
+
assert avcopy[0] is not self.av[0]
|
174 |
+
assert avcopy is not self.av
|
175 |
+
avcopy[5] = {}
|
176 |
+
assert avcopy != self.av
|
177 |
+
|
178 |
+
avcopy[0]["ht"] = 4
|
179 |
+
assert avcopy[0] != self.av[0]
|
180 |
+
self.av[0]["ht"] = 4
|
181 |
+
assert avcopy[0] == self.av[0]
|
182 |
+
del self.av[0]["ht"]
|
183 |
+
|
184 |
+
assert not hasattr(self.av, "__setitem__")
|
185 |
+
|
186 |
+
def test_items(self):
|
187 |
+
expected = dict(self.p.items())
|
188 |
+
expected.update(self.s)
|
189 |
+
assert sorted(self.av.items()) == sorted(expected.items())
|
190 |
+
|
191 |
+
def test_str(self):
|
192 |
+
out = str(dict(self.av))
|
193 |
+
assert str(self.av) == out
|
194 |
+
|
195 |
+
def test_repr(self):
|
196 |
+
out = f"{self.av.__class__.__name__}({self.s}, {self.p})"
|
197 |
+
assert repr(self.av) == out
|
198 |
+
|
199 |
+
|
200 |
+
class TestUnionAdjacency:
|
201 |
+
# node->nbr->data
|
202 |
+
def setup_method(self):
|
203 |
+
dd = {"color": "blue", "weight": 1.2}
|
204 |
+
self.nd = {0: dd, 1: {}, 2: {"color": 1}}
|
205 |
+
self.s = {3: self.nd, 0: {}, 1: {}, 2: {3: {"color": 1}}}
|
206 |
+
self.p = {3: {}, 0: {3: dd}, 1: {0: {}}, 2: {1: {"color": 1}}}
|
207 |
+
self.adjview = nx.classes.coreviews.UnionAdjacency(self.s, self.p)
|
208 |
+
|
209 |
+
def test_pickle(self):
|
210 |
+
view = self.adjview
|
211 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
212 |
+
assert view == pview
|
213 |
+
assert view.__slots__ == pview.__slots__
|
214 |
+
|
215 |
+
def test_len(self):
|
216 |
+
assert len(self.adjview) == len(self.s)
|
217 |
+
|
218 |
+
def test_iter(self):
|
219 |
+
assert sorted(self.adjview) == sorted(self.s)
|
220 |
+
|
221 |
+
def test_getitem(self):
|
222 |
+
assert self.adjview[1] is not self.s[1]
|
223 |
+
assert self.adjview[3][0] is self.adjview[0][3]
|
224 |
+
assert self.adjview[2][3]["color"] == 1
|
225 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
226 |
+
|
227 |
+
def test_copy(self):
|
228 |
+
avcopy = self.adjview.copy()
|
229 |
+
assert avcopy[0] == self.adjview[0]
|
230 |
+
assert avcopy[0] is not self.adjview[0]
|
231 |
+
|
232 |
+
avcopy[2][3]["ht"] = 4
|
233 |
+
assert avcopy[2] != self.adjview[2]
|
234 |
+
self.adjview[2][3]["ht"] = 4
|
235 |
+
assert avcopy[2] == self.adjview[2]
|
236 |
+
del self.adjview[2][3]["ht"]
|
237 |
+
|
238 |
+
assert not hasattr(self.adjview, "__setitem__")
|
239 |
+
|
240 |
+
def test_str(self):
|
241 |
+
out = str(dict(self.adjview))
|
242 |
+
assert str(self.adjview) == out
|
243 |
+
|
244 |
+
def test_repr(self):
|
245 |
+
clsname = self.adjview.__class__.__name__
|
246 |
+
out = f"{clsname}({self.s}, {self.p})"
|
247 |
+
assert repr(self.adjview) == out
|
248 |
+
|
249 |
+
|
250 |
+
class TestUnionMultiInner(TestUnionAdjacency):
|
251 |
+
# nbr->key->data
|
252 |
+
def setup_method(self):
|
253 |
+
dd = {"color": "blue", "weight": 1.2}
|
254 |
+
self.kd = {7: {}, "ekey": {}, 9: {"color": 1}}
|
255 |
+
self.s = {3: self.kd, 0: {7: dd}, 1: {}, 2: {"key": {"color": 1}}}
|
256 |
+
self.p = {3: {}, 0: {3: dd}, 1: {}, 2: {1: {"span": 2}}}
|
257 |
+
self.adjview = nx.classes.coreviews.UnionMultiInner(self.s, self.p)
|
258 |
+
|
259 |
+
def test_len(self):
|
260 |
+
assert len(self.adjview) == len(self.s.keys() | self.p.keys()) == 4
|
261 |
+
|
262 |
+
def test_getitem(self):
|
263 |
+
assert self.adjview[1] is not self.s[1]
|
264 |
+
assert self.adjview[0][7] is self.adjview[0][3]
|
265 |
+
assert self.adjview[2]["key"]["color"] == 1
|
266 |
+
assert self.adjview[2][1]["span"] == 2
|
267 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
268 |
+
pytest.raises(KeyError, self.adjview[1].__getitem__, "key")
|
269 |
+
|
270 |
+
def test_copy(self):
|
271 |
+
avcopy = self.adjview.copy()
|
272 |
+
assert avcopy[0] == self.adjview[0]
|
273 |
+
assert avcopy[0] is not self.adjview[0]
|
274 |
+
|
275 |
+
avcopy[2][1]["width"] = 8
|
276 |
+
assert avcopy[2] != self.adjview[2]
|
277 |
+
self.adjview[2][1]["width"] = 8
|
278 |
+
assert avcopy[2] == self.adjview[2]
|
279 |
+
del self.adjview[2][1]["width"]
|
280 |
+
|
281 |
+
assert not hasattr(self.adjview, "__setitem__")
|
282 |
+
assert hasattr(avcopy, "__setitem__")
|
283 |
+
|
284 |
+
|
285 |
+
class TestUnionMultiAdjacency(TestUnionAdjacency):
|
286 |
+
# node->nbr->key->data
|
287 |
+
def setup_method(self):
|
288 |
+
dd = {"color": "blue", "weight": 1.2}
|
289 |
+
self.kd = {7: {}, 8: {}, 9: {"color": 1}}
|
290 |
+
self.nd = {3: self.kd, 0: {9: dd}, 1: {8: {}}, 2: {9: {"color": 1}}}
|
291 |
+
self.s = {3: self.nd, 0: {3: {7: dd}}, 1: {}, 2: {3: {8: {}}}}
|
292 |
+
self.p = {3: {}, 0: {3: {9: dd}}, 1: {}, 2: {1: {8: {}}}}
|
293 |
+
self.adjview = nx.classes.coreviews.UnionMultiAdjacency(self.s, self.p)
|
294 |
+
|
295 |
+
def test_getitem(self):
|
296 |
+
assert self.adjview[1] is not self.s[1]
|
297 |
+
assert self.adjview[3][0][9] is self.adjview[0][3][9]
|
298 |
+
assert self.adjview[3][2][9]["color"] == 1
|
299 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
300 |
+
|
301 |
+
def test_copy(self):
|
302 |
+
avcopy = self.adjview.copy()
|
303 |
+
assert avcopy[0] == self.adjview[0]
|
304 |
+
assert avcopy[0] is not self.adjview[0]
|
305 |
+
|
306 |
+
avcopy[2][3][8]["ht"] = 4
|
307 |
+
assert avcopy[2] != self.adjview[2]
|
308 |
+
self.adjview[2][3][8]["ht"] = 4
|
309 |
+
assert avcopy[2] == self.adjview[2]
|
310 |
+
del self.adjview[2][3][8]["ht"]
|
311 |
+
|
312 |
+
assert not hasattr(self.adjview, "__setitem__")
|
313 |
+
assert hasattr(avcopy, "__setitem__")
|
314 |
+
|
315 |
+
|
316 |
+
class TestFilteredGraphs:
|
317 |
+
def setup_method(self):
|
318 |
+
self.Graphs = [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
|
319 |
+
|
320 |
+
def test_hide_show_nodes(self):
|
321 |
+
SubGraph = nx.subgraph_view
|
322 |
+
for Graph in self.Graphs:
|
323 |
+
G = nx.path_graph(4, Graph)
|
324 |
+
SG = G.subgraph([2, 3])
|
325 |
+
RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
|
326 |
+
assert SG.nodes == RG.nodes
|
327 |
+
assert SG.edges == RG.edges
|
328 |
+
SGC = SG.copy()
|
329 |
+
RGC = RG.copy()
|
330 |
+
assert SGC.nodes == RGC.nodes
|
331 |
+
assert SGC.edges == RGC.edges
|
332 |
+
|
333 |
+
def test_str_repr(self):
|
334 |
+
SubGraph = nx.subgraph_view
|
335 |
+
for Graph in self.Graphs:
|
336 |
+
G = nx.path_graph(4, Graph)
|
337 |
+
SG = G.subgraph([2, 3])
|
338 |
+
RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
|
339 |
+
str(SG.adj)
|
340 |
+
str(RG.adj)
|
341 |
+
repr(SG.adj)
|
342 |
+
repr(RG.adj)
|
343 |
+
str(SG.adj[2])
|
344 |
+
str(RG.adj[2])
|
345 |
+
repr(SG.adj[2])
|
346 |
+
repr(RG.adj[2])
|
347 |
+
|
348 |
+
def test_copy(self):
|
349 |
+
SubGraph = nx.subgraph_view
|
350 |
+
for Graph in self.Graphs:
|
351 |
+
G = nx.path_graph(4, Graph)
|
352 |
+
SG = G.subgraph([2, 3])
|
353 |
+
RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
|
354 |
+
RsG = SubGraph(G, filter_node=nx.filters.show_nodes([2, 3]))
|
355 |
+
assert G.adj.copy() == G.adj
|
356 |
+
assert G.adj[2].copy() == G.adj[2]
|
357 |
+
assert SG.adj.copy() == SG.adj
|
358 |
+
assert SG.adj[2].copy() == SG.adj[2]
|
359 |
+
assert RG.adj.copy() == RG.adj
|
360 |
+
assert RG.adj[2].copy() == RG.adj[2]
|
361 |
+
assert RsG.adj.copy() == RsG.adj
|
362 |
+
assert RsG.adj[2].copy() == RsG.adj[2]
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_graph.py
ADDED
@@ -0,0 +1,920 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gc
|
2 |
+
import pickle
|
3 |
+
import platform
|
4 |
+
import weakref
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
from networkx.utils import edges_equal, graphs_equal, nodes_equal
|
10 |
+
|
11 |
+
|
12 |
+
class BaseGraphTester:
|
13 |
+
"""Tests for data-structure independent graph class features."""
|
14 |
+
|
15 |
+
def test_contains(self):
|
16 |
+
G = self.K3
|
17 |
+
assert 1 in G
|
18 |
+
assert 4 not in G
|
19 |
+
assert "b" not in G
|
20 |
+
assert [] not in G # no exception for nonhashable
|
21 |
+
assert {1: 1} not in G # no exception for nonhashable
|
22 |
+
|
23 |
+
def test_order(self):
|
24 |
+
G = self.K3
|
25 |
+
assert len(G) == 3
|
26 |
+
assert G.order() == 3
|
27 |
+
assert G.number_of_nodes() == 3
|
28 |
+
|
29 |
+
def test_nodes(self):
|
30 |
+
G = self.K3
|
31 |
+
assert isinstance(G._node, G.node_dict_factory)
|
32 |
+
assert isinstance(G._adj, G.adjlist_outer_dict_factory)
|
33 |
+
assert all(
|
34 |
+
isinstance(adj, G.adjlist_inner_dict_factory) for adj in G._adj.values()
|
35 |
+
)
|
36 |
+
assert sorted(G.nodes()) == self.k3nodes
|
37 |
+
assert sorted(G.nodes(data=True)) == [(0, {}), (1, {}), (2, {})]
|
38 |
+
|
39 |
+
def test_none_node(self):
|
40 |
+
G = self.Graph()
|
41 |
+
with pytest.raises(ValueError):
|
42 |
+
G.add_node(None)
|
43 |
+
with pytest.raises(ValueError):
|
44 |
+
G.add_nodes_from([None])
|
45 |
+
with pytest.raises(ValueError):
|
46 |
+
G.add_edge(0, None)
|
47 |
+
with pytest.raises(ValueError):
|
48 |
+
G.add_edges_from([(0, None)])
|
49 |
+
|
50 |
+
def test_has_node(self):
|
51 |
+
G = self.K3
|
52 |
+
assert G.has_node(1)
|
53 |
+
assert not G.has_node(4)
|
54 |
+
assert not G.has_node([]) # no exception for nonhashable
|
55 |
+
assert not G.has_node({1: 1}) # no exception for nonhashable
|
56 |
+
|
57 |
+
def test_has_edge(self):
|
58 |
+
G = self.K3
|
59 |
+
assert G.has_edge(0, 1)
|
60 |
+
assert not G.has_edge(0, -1)
|
61 |
+
|
62 |
+
def test_neighbors(self):
|
63 |
+
G = self.K3
|
64 |
+
assert sorted(G.neighbors(0)) == [1, 2]
|
65 |
+
with pytest.raises(nx.NetworkXError):
|
66 |
+
G.neighbors(-1)
|
67 |
+
|
68 |
+
@pytest.mark.skipif(
|
69 |
+
platform.python_implementation() == "PyPy", reason="PyPy gc is different"
|
70 |
+
)
|
71 |
+
def test_memory_leak(self):
|
72 |
+
G = self.Graph()
|
73 |
+
|
74 |
+
def count_objects_of_type(_type):
|
75 |
+
# Iterating over all objects tracked by gc can include weak references
|
76 |
+
# whose weakly-referenced objects may no longer exist. Calling `isinstance`
|
77 |
+
# on such a weak reference will raise ReferenceError. There are at least
|
78 |
+
# three workarounds for this: one is to compare type names instead of using
|
79 |
+
# `isinstance` such as `type(obj).__name__ == typename`, another is to use
|
80 |
+
# `type(obj) == _type`, and the last is to ignore ProxyTypes as we do below.
|
81 |
+
# NOTE: even if this safeguard is deemed unnecessary to pass NetworkX tests,
|
82 |
+
# we should still keep it for maximum safety for other NetworkX backends.
|
83 |
+
return sum(
|
84 |
+
1
|
85 |
+
for obj in gc.get_objects()
|
86 |
+
if not isinstance(obj, weakref.ProxyTypes) and isinstance(obj, _type)
|
87 |
+
)
|
88 |
+
|
89 |
+
gc.collect()
|
90 |
+
before = count_objects_of_type(self.Graph)
|
91 |
+
G.copy()
|
92 |
+
gc.collect()
|
93 |
+
after = count_objects_of_type(self.Graph)
|
94 |
+
assert before == after
|
95 |
+
|
96 |
+
# test a subgraph of the base class
|
97 |
+
class MyGraph(self.Graph):
|
98 |
+
pass
|
99 |
+
|
100 |
+
gc.collect()
|
101 |
+
G = MyGraph()
|
102 |
+
before = count_objects_of_type(MyGraph)
|
103 |
+
G.copy()
|
104 |
+
gc.collect()
|
105 |
+
after = count_objects_of_type(MyGraph)
|
106 |
+
assert before == after
|
107 |
+
|
108 |
+
def test_edges(self):
|
109 |
+
G = self.K3
|
110 |
+
assert isinstance(G._adj, G.adjlist_outer_dict_factory)
|
111 |
+
assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
|
112 |
+
assert edges_equal(G.edges(0), [(0, 1), (0, 2)])
|
113 |
+
assert edges_equal(G.edges([0, 1]), [(0, 1), (0, 2), (1, 2)])
|
114 |
+
with pytest.raises(nx.NetworkXError):
|
115 |
+
G.edges(-1)
|
116 |
+
|
117 |
+
def test_degree(self):
|
118 |
+
G = self.K3
|
119 |
+
assert sorted(G.degree()) == [(0, 2), (1, 2), (2, 2)]
|
120 |
+
assert dict(G.degree()) == {0: 2, 1: 2, 2: 2}
|
121 |
+
assert G.degree(0) == 2
|
122 |
+
with pytest.raises(nx.NetworkXError):
|
123 |
+
G.degree(-1) # node not in graph
|
124 |
+
|
125 |
+
def test_size(self):
|
126 |
+
G = self.K3
|
127 |
+
assert G.size() == 3
|
128 |
+
assert G.number_of_edges() == 3
|
129 |
+
|
130 |
+
def test_nbunch_iter(self):
|
131 |
+
G = self.K3
|
132 |
+
assert nodes_equal(G.nbunch_iter(), self.k3nodes) # all nodes
|
133 |
+
assert nodes_equal(G.nbunch_iter(0), [0]) # single node
|
134 |
+
assert nodes_equal(G.nbunch_iter([0, 1]), [0, 1]) # sequence
|
135 |
+
# sequence with none in graph
|
136 |
+
assert nodes_equal(G.nbunch_iter([-1]), [])
|
137 |
+
# string sequence with none in graph
|
138 |
+
assert nodes_equal(G.nbunch_iter("foo"), [])
|
139 |
+
# node not in graph doesn't get caught upon creation of iterator
|
140 |
+
bunch = G.nbunch_iter(-1)
|
141 |
+
# but gets caught when iterator used
|
142 |
+
with pytest.raises(nx.NetworkXError, match="is not a node or a sequence"):
|
143 |
+
list(bunch)
|
144 |
+
# unhashable doesn't get caught upon creation of iterator
|
145 |
+
bunch = G.nbunch_iter([0, 1, 2, {}])
|
146 |
+
# but gets caught when iterator hits the unhashable
|
147 |
+
with pytest.raises(
|
148 |
+
nx.NetworkXError, match="in sequence nbunch is not a valid node"
|
149 |
+
):
|
150 |
+
list(bunch)
|
151 |
+
|
152 |
+
def test_nbunch_iter_node_format_raise(self):
|
153 |
+
# Tests that a node that would have failed string formatting
|
154 |
+
# doesn't cause an error when attempting to raise a
|
155 |
+
# :exc:`nx.NetworkXError`.
|
156 |
+
|
157 |
+
# For more information, see pull request #1813.
|
158 |
+
G = self.Graph()
|
159 |
+
nbunch = [("x", set())]
|
160 |
+
with pytest.raises(nx.NetworkXError):
|
161 |
+
list(G.nbunch_iter(nbunch))
|
162 |
+
|
163 |
+
def test_selfloop_degree(self):
|
164 |
+
G = self.Graph()
|
165 |
+
G.add_edge(1, 1)
|
166 |
+
assert sorted(G.degree()) == [(1, 2)]
|
167 |
+
assert dict(G.degree()) == {1: 2}
|
168 |
+
assert G.degree(1) == 2
|
169 |
+
assert sorted(G.degree([1])) == [(1, 2)]
|
170 |
+
assert G.degree(1, weight="weight") == 2
|
171 |
+
|
172 |
+
def test_selfloops(self):
|
173 |
+
G = self.K3.copy()
|
174 |
+
G.add_edge(0, 0)
|
175 |
+
assert nodes_equal(nx.nodes_with_selfloops(G), [0])
|
176 |
+
assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
|
177 |
+
assert nx.number_of_selfloops(G) == 1
|
178 |
+
G.remove_edge(0, 0)
|
179 |
+
G.add_edge(0, 0)
|
180 |
+
G.remove_edges_from([(0, 0)])
|
181 |
+
G.add_edge(1, 1)
|
182 |
+
G.remove_node(1)
|
183 |
+
G.add_edge(0, 0)
|
184 |
+
G.add_edge(1, 1)
|
185 |
+
G.remove_nodes_from([0, 1])
|
186 |
+
|
187 |
+
def test_cache_reset(self):
|
188 |
+
G = self.K3.copy()
|
189 |
+
old_adj = G.adj
|
190 |
+
assert id(G.adj) == id(old_adj)
|
191 |
+
G._adj = {}
|
192 |
+
assert id(G.adj) != id(old_adj)
|
193 |
+
|
194 |
+
old_nodes = G.nodes
|
195 |
+
assert id(G.nodes) == id(old_nodes)
|
196 |
+
G._node = {}
|
197 |
+
assert id(G.nodes) != id(old_nodes)
|
198 |
+
|
199 |
+
def test_attributes_cached(self):
|
200 |
+
G = self.K3.copy()
|
201 |
+
assert id(G.nodes) == id(G.nodes)
|
202 |
+
assert id(G.edges) == id(G.edges)
|
203 |
+
assert id(G.degree) == id(G.degree)
|
204 |
+
assert id(G.adj) == id(G.adj)
|
205 |
+
|
206 |
+
|
207 |
+
class BaseAttrGraphTester(BaseGraphTester):
|
208 |
+
"""Tests of graph class attribute features."""
|
209 |
+
|
210 |
+
def test_weighted_degree(self):
|
211 |
+
G = self.Graph()
|
212 |
+
G.add_edge(1, 2, weight=2, other=3)
|
213 |
+
G.add_edge(2, 3, weight=3, other=4)
|
214 |
+
assert sorted(d for n, d in G.degree(weight="weight")) == [2, 3, 5]
|
215 |
+
assert dict(G.degree(weight="weight")) == {1: 2, 2: 5, 3: 3}
|
216 |
+
assert G.degree(1, weight="weight") == 2
|
217 |
+
assert nodes_equal((G.degree([1], weight="weight")), [(1, 2)])
|
218 |
+
|
219 |
+
assert nodes_equal((d for n, d in G.degree(weight="other")), [3, 7, 4])
|
220 |
+
assert dict(G.degree(weight="other")) == {1: 3, 2: 7, 3: 4}
|
221 |
+
assert G.degree(1, weight="other") == 3
|
222 |
+
assert edges_equal((G.degree([1], weight="other")), [(1, 3)])
|
223 |
+
|
224 |
+
def add_attributes(self, G):
|
225 |
+
G.graph["foo"] = []
|
226 |
+
G.nodes[0]["foo"] = []
|
227 |
+
G.remove_edge(1, 2)
|
228 |
+
ll = []
|
229 |
+
G.add_edge(1, 2, foo=ll)
|
230 |
+
G.add_edge(2, 1, foo=ll)
|
231 |
+
|
232 |
+
def test_name(self):
|
233 |
+
G = self.Graph(name="")
|
234 |
+
assert G.name == ""
|
235 |
+
G = self.Graph(name="test")
|
236 |
+
assert G.name == "test"
|
237 |
+
|
238 |
+
def test_str_unnamed(self):
|
239 |
+
G = self.Graph()
|
240 |
+
G.add_edges_from([(1, 2), (2, 3)])
|
241 |
+
assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges"
|
242 |
+
|
243 |
+
def test_str_named(self):
|
244 |
+
G = self.Graph(name="foo")
|
245 |
+
G.add_edges_from([(1, 2), (2, 3)])
|
246 |
+
assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges"
|
247 |
+
|
248 |
+
def test_graph_chain(self):
|
249 |
+
G = self.Graph([(0, 1), (1, 2)])
|
250 |
+
DG = G.to_directed(as_view=True)
|
251 |
+
SDG = DG.subgraph([0, 1])
|
252 |
+
RSDG = SDG.reverse(copy=False)
|
253 |
+
assert G is DG._graph
|
254 |
+
assert DG is SDG._graph
|
255 |
+
assert SDG is RSDG._graph
|
256 |
+
|
257 |
+
def test_copy(self):
|
258 |
+
G = self.Graph()
|
259 |
+
G.add_node(0)
|
260 |
+
G.add_edge(1, 2)
|
261 |
+
self.add_attributes(G)
|
262 |
+
# copy edge datadict but any container attr are same
|
263 |
+
H = G.copy()
|
264 |
+
self.graphs_equal(H, G)
|
265 |
+
self.different_attrdict(H, G)
|
266 |
+
self.shallow_copy_attrdict(H, G)
|
267 |
+
|
268 |
+
def test_class_copy(self):
|
269 |
+
G = self.Graph()
|
270 |
+
G.add_node(0)
|
271 |
+
G.add_edge(1, 2)
|
272 |
+
self.add_attributes(G)
|
273 |
+
# copy edge datadict but any container attr are same
|
274 |
+
H = G.__class__(G)
|
275 |
+
self.graphs_equal(H, G)
|
276 |
+
self.different_attrdict(H, G)
|
277 |
+
self.shallow_copy_attrdict(H, G)
|
278 |
+
|
279 |
+
def test_fresh_copy(self):
|
280 |
+
G = self.Graph()
|
281 |
+
G.add_node(0)
|
282 |
+
G.add_edge(1, 2)
|
283 |
+
self.add_attributes(G)
|
284 |
+
# copy graph structure but use fresh datadict
|
285 |
+
H = G.__class__()
|
286 |
+
H.add_nodes_from(G)
|
287 |
+
H.add_edges_from(G.edges())
|
288 |
+
assert len(G.nodes[0]) == 1
|
289 |
+
ddict = G.adj[1][2][0] if G.is_multigraph() else G.adj[1][2]
|
290 |
+
assert len(ddict) == 1
|
291 |
+
assert len(H.nodes[0]) == 0
|
292 |
+
ddict = H.adj[1][2][0] if H.is_multigraph() else H.adj[1][2]
|
293 |
+
assert len(ddict) == 0
|
294 |
+
|
295 |
+
def is_deepcopy(self, H, G):
|
296 |
+
self.graphs_equal(H, G)
|
297 |
+
self.different_attrdict(H, G)
|
298 |
+
self.deep_copy_attrdict(H, G)
|
299 |
+
|
300 |
+
def deep_copy_attrdict(self, H, G):
|
301 |
+
self.deepcopy_graph_attr(H, G)
|
302 |
+
self.deepcopy_node_attr(H, G)
|
303 |
+
self.deepcopy_edge_attr(H, G)
|
304 |
+
|
305 |
+
def deepcopy_graph_attr(self, H, G):
|
306 |
+
assert G.graph["foo"] == H.graph["foo"]
|
307 |
+
G.graph["foo"].append(1)
|
308 |
+
assert G.graph["foo"] != H.graph["foo"]
|
309 |
+
|
310 |
+
def deepcopy_node_attr(self, H, G):
|
311 |
+
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
|
312 |
+
G.nodes[0]["foo"].append(1)
|
313 |
+
assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
|
314 |
+
|
315 |
+
def deepcopy_edge_attr(self, H, G):
|
316 |
+
assert G[1][2]["foo"] == H[1][2]["foo"]
|
317 |
+
G[1][2]["foo"].append(1)
|
318 |
+
assert G[1][2]["foo"] != H[1][2]["foo"]
|
319 |
+
|
320 |
+
def is_shallow_copy(self, H, G):
|
321 |
+
self.graphs_equal(H, G)
|
322 |
+
self.shallow_copy_attrdict(H, G)
|
323 |
+
|
324 |
+
def shallow_copy_attrdict(self, H, G):
|
325 |
+
self.shallow_copy_graph_attr(H, G)
|
326 |
+
self.shallow_copy_node_attr(H, G)
|
327 |
+
self.shallow_copy_edge_attr(H, G)
|
328 |
+
|
329 |
+
def shallow_copy_graph_attr(self, H, G):
|
330 |
+
assert G.graph["foo"] == H.graph["foo"]
|
331 |
+
G.graph["foo"].append(1)
|
332 |
+
assert G.graph["foo"] == H.graph["foo"]
|
333 |
+
|
334 |
+
def shallow_copy_node_attr(self, H, G):
|
335 |
+
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
|
336 |
+
G.nodes[0]["foo"].append(1)
|
337 |
+
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
|
338 |
+
|
339 |
+
def shallow_copy_edge_attr(self, H, G):
|
340 |
+
assert G[1][2]["foo"] == H[1][2]["foo"]
|
341 |
+
G[1][2]["foo"].append(1)
|
342 |
+
assert G[1][2]["foo"] == H[1][2]["foo"]
|
343 |
+
|
344 |
+
def same_attrdict(self, H, G):
|
345 |
+
old_foo = H[1][2]["foo"]
|
346 |
+
H.adj[1][2]["foo"] = "baz"
|
347 |
+
assert G.edges == H.edges
|
348 |
+
H.adj[1][2]["foo"] = old_foo
|
349 |
+
assert G.edges == H.edges
|
350 |
+
|
351 |
+
old_foo = H.nodes[0]["foo"]
|
352 |
+
H.nodes[0]["foo"] = "baz"
|
353 |
+
assert G.nodes == H.nodes
|
354 |
+
H.nodes[0]["foo"] = old_foo
|
355 |
+
assert G.nodes == H.nodes
|
356 |
+
|
357 |
+
def different_attrdict(self, H, G):
|
358 |
+
old_foo = H[1][2]["foo"]
|
359 |
+
H.adj[1][2]["foo"] = "baz"
|
360 |
+
assert G._adj != H._adj
|
361 |
+
H.adj[1][2]["foo"] = old_foo
|
362 |
+
assert G._adj == H._adj
|
363 |
+
|
364 |
+
old_foo = H.nodes[0]["foo"]
|
365 |
+
H.nodes[0]["foo"] = "baz"
|
366 |
+
assert G._node != H._node
|
367 |
+
H.nodes[0]["foo"] = old_foo
|
368 |
+
assert G._node == H._node
|
369 |
+
|
370 |
+
def graphs_equal(self, H, G):
|
371 |
+
assert G._adj == H._adj
|
372 |
+
assert G._node == H._node
|
373 |
+
assert G.graph == H.graph
|
374 |
+
assert G.name == H.name
|
375 |
+
if not G.is_directed() and not H.is_directed():
|
376 |
+
assert H._adj[1][2] is H._adj[2][1]
|
377 |
+
assert G._adj[1][2] is G._adj[2][1]
|
378 |
+
else: # at least one is directed
|
379 |
+
if not G.is_directed():
|
380 |
+
G._pred = G._adj
|
381 |
+
G._succ = G._adj
|
382 |
+
if not H.is_directed():
|
383 |
+
H._pred = H._adj
|
384 |
+
H._succ = H._adj
|
385 |
+
assert G._pred == H._pred
|
386 |
+
assert G._succ == H._succ
|
387 |
+
assert H._succ[1][2] is H._pred[2][1]
|
388 |
+
assert G._succ[1][2] is G._pred[2][1]
|
389 |
+
|
390 |
+
def test_graph_attr(self):
|
391 |
+
G = self.K3.copy()
|
392 |
+
G.graph["foo"] = "bar"
|
393 |
+
assert isinstance(G.graph, G.graph_attr_dict_factory)
|
394 |
+
assert G.graph["foo"] == "bar"
|
395 |
+
del G.graph["foo"]
|
396 |
+
assert G.graph == {}
|
397 |
+
H = self.Graph(foo="bar")
|
398 |
+
assert H.graph["foo"] == "bar"
|
399 |
+
|
400 |
+
def test_node_attr(self):
|
401 |
+
G = self.K3.copy()
|
402 |
+
G.add_node(1, foo="bar")
|
403 |
+
assert all(
|
404 |
+
isinstance(d, G.node_attr_dict_factory) for u, d in G.nodes(data=True)
|
405 |
+
)
|
406 |
+
assert nodes_equal(G.nodes(), [0, 1, 2])
|
407 |
+
assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "bar"}), (2, {})])
|
408 |
+
G.nodes[1]["foo"] = "baz"
|
409 |
+
assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "baz"}), (2, {})])
|
410 |
+
assert nodes_equal(G.nodes(data="foo"), [(0, None), (1, "baz"), (2, None)])
|
411 |
+
assert nodes_equal(
|
412 |
+
G.nodes(data="foo", default="bar"), [(0, "bar"), (1, "baz"), (2, "bar")]
|
413 |
+
)
|
414 |
+
|
415 |
+
def test_node_attr2(self):
|
416 |
+
G = self.K3.copy()
|
417 |
+
a = {"foo": "bar"}
|
418 |
+
G.add_node(3, **a)
|
419 |
+
assert nodes_equal(G.nodes(), [0, 1, 2, 3])
|
420 |
+
assert nodes_equal(
|
421 |
+
G.nodes(data=True), [(0, {}), (1, {}), (2, {}), (3, {"foo": "bar"})]
|
422 |
+
)
|
423 |
+
|
424 |
+
def test_edge_lookup(self):
|
425 |
+
G = self.Graph()
|
426 |
+
G.add_edge(1, 2, foo="bar")
|
427 |
+
assert edges_equal(G.edges[1, 2], {"foo": "bar"})
|
428 |
+
|
429 |
+
def test_edge_attr(self):
|
430 |
+
G = self.Graph()
|
431 |
+
G.add_edge(1, 2, foo="bar")
|
432 |
+
assert all(
|
433 |
+
isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True)
|
434 |
+
)
|
435 |
+
assert edges_equal(G.edges(data=True), [(1, 2, {"foo": "bar"})])
|
436 |
+
assert edges_equal(G.edges(data="foo"), [(1, 2, "bar")])
|
437 |
+
|
438 |
+
def test_edge_attr2(self):
|
439 |
+
G = self.Graph()
|
440 |
+
G.add_edges_from([(1, 2), (3, 4)], foo="foo")
|
441 |
+
assert edges_equal(
|
442 |
+
G.edges(data=True), [(1, 2, {"foo": "foo"}), (3, 4, {"foo": "foo"})]
|
443 |
+
)
|
444 |
+
assert edges_equal(G.edges(data="foo"), [(1, 2, "foo"), (3, 4, "foo")])
|
445 |
+
|
446 |
+
def test_edge_attr3(self):
|
447 |
+
G = self.Graph()
|
448 |
+
G.add_edges_from([(1, 2, {"weight": 32}), (3, 4, {"weight": 64})], foo="foo")
|
449 |
+
assert edges_equal(
|
450 |
+
G.edges(data=True),
|
451 |
+
[
|
452 |
+
(1, 2, {"foo": "foo", "weight": 32}),
|
453 |
+
(3, 4, {"foo": "foo", "weight": 64}),
|
454 |
+
],
|
455 |
+
)
|
456 |
+
|
457 |
+
G.remove_edges_from([(1, 2), (3, 4)])
|
458 |
+
G.add_edge(1, 2, data=7, spam="bar", bar="foo")
|
459 |
+
assert edges_equal(
|
460 |
+
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
|
461 |
+
)
|
462 |
+
|
463 |
+
def test_edge_attr4(self):
|
464 |
+
G = self.Graph()
|
465 |
+
G.add_edge(1, 2, data=7, spam="bar", bar="foo")
|
466 |
+
assert edges_equal(
|
467 |
+
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
|
468 |
+
)
|
469 |
+
G[1][2]["data"] = 10 # OK to set data like this
|
470 |
+
assert edges_equal(
|
471 |
+
G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
|
472 |
+
)
|
473 |
+
|
474 |
+
G.adj[1][2]["data"] = 20
|
475 |
+
assert edges_equal(
|
476 |
+
G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
|
477 |
+
)
|
478 |
+
G.edges[1, 2]["data"] = 21 # another spelling, "edge"
|
479 |
+
assert edges_equal(
|
480 |
+
G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
|
481 |
+
)
|
482 |
+
G.adj[1][2]["listdata"] = [20, 200]
|
483 |
+
G.adj[1][2]["weight"] = 20
|
484 |
+
dd = {
|
485 |
+
"data": 21,
|
486 |
+
"spam": "bar",
|
487 |
+
"bar": "foo",
|
488 |
+
"listdata": [20, 200],
|
489 |
+
"weight": 20,
|
490 |
+
}
|
491 |
+
assert edges_equal(G.edges(data=True), [(1, 2, dd)])
|
492 |
+
|
493 |
+
def test_to_undirected(self):
|
494 |
+
G = self.K3
|
495 |
+
self.add_attributes(G)
|
496 |
+
H = nx.Graph(G)
|
497 |
+
self.is_shallow_copy(H, G)
|
498 |
+
self.different_attrdict(H, G)
|
499 |
+
H = G.to_undirected()
|
500 |
+
self.is_deepcopy(H, G)
|
501 |
+
|
502 |
+
def test_to_directed_as_view(self):
|
503 |
+
H = nx.path_graph(2, create_using=self.Graph)
|
504 |
+
H2 = H.to_directed(as_view=True)
|
505 |
+
assert H is H2._graph
|
506 |
+
assert H2.has_edge(0, 1)
|
507 |
+
assert H2.has_edge(1, 0) or H.is_directed()
|
508 |
+
pytest.raises(nx.NetworkXError, H2.add_node, -1)
|
509 |
+
pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2)
|
510 |
+
H.add_edge(1, 2)
|
511 |
+
assert H2.has_edge(1, 2)
|
512 |
+
assert H2.has_edge(2, 1) or H.is_directed()
|
513 |
+
|
514 |
+
def test_to_undirected_as_view(self):
|
515 |
+
H = nx.path_graph(2, create_using=self.Graph)
|
516 |
+
H2 = H.to_undirected(as_view=True)
|
517 |
+
assert H is H2._graph
|
518 |
+
assert H2.has_edge(0, 1)
|
519 |
+
assert H2.has_edge(1, 0)
|
520 |
+
pytest.raises(nx.NetworkXError, H2.add_node, -1)
|
521 |
+
pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2)
|
522 |
+
H.add_edge(1, 2)
|
523 |
+
assert H2.has_edge(1, 2)
|
524 |
+
assert H2.has_edge(2, 1)
|
525 |
+
|
526 |
+
def test_directed_class(self):
|
527 |
+
G = self.Graph()
|
528 |
+
|
529 |
+
class newGraph(G.to_undirected_class()):
|
530 |
+
def to_directed_class(self):
|
531 |
+
return newDiGraph
|
532 |
+
|
533 |
+
def to_undirected_class(self):
|
534 |
+
return newGraph
|
535 |
+
|
536 |
+
class newDiGraph(G.to_directed_class()):
|
537 |
+
def to_directed_class(self):
|
538 |
+
return newDiGraph
|
539 |
+
|
540 |
+
def to_undirected_class(self):
|
541 |
+
return newGraph
|
542 |
+
|
543 |
+
G = newDiGraph() if G.is_directed() else newGraph()
|
544 |
+
H = G.to_directed()
|
545 |
+
assert isinstance(H, newDiGraph)
|
546 |
+
H = G.to_undirected()
|
547 |
+
assert isinstance(H, newGraph)
|
548 |
+
|
549 |
+
def test_to_directed(self):
|
550 |
+
G = self.K3
|
551 |
+
self.add_attributes(G)
|
552 |
+
H = nx.DiGraph(G)
|
553 |
+
self.is_shallow_copy(H, G)
|
554 |
+
self.different_attrdict(H, G)
|
555 |
+
H = G.to_directed()
|
556 |
+
self.is_deepcopy(H, G)
|
557 |
+
|
558 |
+
def test_subgraph(self):
|
559 |
+
G = self.K3
|
560 |
+
self.add_attributes(G)
|
561 |
+
H = G.subgraph([0, 1, 2, 5])
|
562 |
+
self.graphs_equal(H, G)
|
563 |
+
self.same_attrdict(H, G)
|
564 |
+
self.shallow_copy_attrdict(H, G)
|
565 |
+
|
566 |
+
H = G.subgraph(0)
|
567 |
+
assert H.adj == {0: {}}
|
568 |
+
H = G.subgraph([])
|
569 |
+
assert H.adj == {}
|
570 |
+
assert G.adj != {}
|
571 |
+
|
572 |
+
def test_selfloops_attr(self):
|
573 |
+
G = self.K3.copy()
|
574 |
+
G.add_edge(0, 0)
|
575 |
+
G.add_edge(1, 1, weight=2)
|
576 |
+
assert edges_equal(
|
577 |
+
nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
|
578 |
+
)
|
579 |
+
assert edges_equal(
|
580 |
+
nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)]
|
581 |
+
)
|
582 |
+
|
583 |
+
|
584 |
+
class TestGraph(BaseAttrGraphTester):
|
585 |
+
"""Tests specific to dict-of-dict-of-dict graph data structure"""
|
586 |
+
|
587 |
+
def setup_method(self):
|
588 |
+
self.Graph = nx.Graph
|
589 |
+
# build dict-of-dict-of-dict K3
|
590 |
+
ed1, ed2, ed3 = ({}, {}, {})
|
591 |
+
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
|
592 |
+
self.k3edges = [(0, 1), (0, 2), (1, 2)]
|
593 |
+
self.k3nodes = [0, 1, 2]
|
594 |
+
self.K3 = self.Graph()
|
595 |
+
self.K3._adj = self.k3adj
|
596 |
+
self.K3._node = {}
|
597 |
+
self.K3._node[0] = {}
|
598 |
+
self.K3._node[1] = {}
|
599 |
+
self.K3._node[2] = {}
|
600 |
+
|
601 |
+
def test_pickle(self):
|
602 |
+
G = self.K3
|
603 |
+
pg = pickle.loads(pickle.dumps(G, -1))
|
604 |
+
self.graphs_equal(pg, G)
|
605 |
+
pg = pickle.loads(pickle.dumps(G))
|
606 |
+
self.graphs_equal(pg, G)
|
607 |
+
|
608 |
+
def test_data_input(self):
|
609 |
+
G = self.Graph({1: [2], 2: [1]}, name="test")
|
610 |
+
assert G.name == "test"
|
611 |
+
assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
|
612 |
+
|
613 |
+
def test_adjacency(self):
|
614 |
+
G = self.K3
|
615 |
+
assert dict(G.adjacency()) == {
|
616 |
+
0: {1: {}, 2: {}},
|
617 |
+
1: {0: {}, 2: {}},
|
618 |
+
2: {0: {}, 1: {}},
|
619 |
+
}
|
620 |
+
|
621 |
+
def test_getitem(self):
|
622 |
+
G = self.K3
|
623 |
+
assert G.adj[0] == {1: {}, 2: {}}
|
624 |
+
assert G[0] == {1: {}, 2: {}}
|
625 |
+
with pytest.raises(KeyError):
|
626 |
+
G.__getitem__("j")
|
627 |
+
with pytest.raises(TypeError):
|
628 |
+
G.__getitem__(["A"])
|
629 |
+
|
630 |
+
def test_add_node(self):
|
631 |
+
G = self.Graph()
|
632 |
+
G.add_node(0)
|
633 |
+
assert G.adj == {0: {}}
|
634 |
+
# test add attributes
|
635 |
+
G.add_node(1, c="red")
|
636 |
+
G.add_node(2, c="blue")
|
637 |
+
G.add_node(3, c="red")
|
638 |
+
assert G.nodes[1]["c"] == "red"
|
639 |
+
assert G.nodes[2]["c"] == "blue"
|
640 |
+
assert G.nodes[3]["c"] == "red"
|
641 |
+
# test updating attributes
|
642 |
+
G.add_node(1, c="blue")
|
643 |
+
G.add_node(2, c="red")
|
644 |
+
G.add_node(3, c="blue")
|
645 |
+
assert G.nodes[1]["c"] == "blue"
|
646 |
+
assert G.nodes[2]["c"] == "red"
|
647 |
+
assert G.nodes[3]["c"] == "blue"
|
648 |
+
|
649 |
+
def test_add_nodes_from(self):
|
650 |
+
G = self.Graph()
|
651 |
+
G.add_nodes_from([0, 1, 2])
|
652 |
+
assert G.adj == {0: {}, 1: {}, 2: {}}
|
653 |
+
# test add attributes
|
654 |
+
G.add_nodes_from([0, 1, 2], c="red")
|
655 |
+
assert G.nodes[0]["c"] == "red"
|
656 |
+
assert G.nodes[2]["c"] == "red"
|
657 |
+
# test that attribute dicts are not the same
|
658 |
+
assert G.nodes[0] is not G.nodes[1]
|
659 |
+
# test updating attributes
|
660 |
+
G.add_nodes_from([0, 1, 2], c="blue")
|
661 |
+
assert G.nodes[0]["c"] == "blue"
|
662 |
+
assert G.nodes[2]["c"] == "blue"
|
663 |
+
assert G.nodes[0] is not G.nodes[1]
|
664 |
+
# test tuple input
|
665 |
+
H = self.Graph()
|
666 |
+
H.add_nodes_from(G.nodes(data=True))
|
667 |
+
assert H.nodes[0]["c"] == "blue"
|
668 |
+
assert H.nodes[2]["c"] == "blue"
|
669 |
+
assert H.nodes[0] is not H.nodes[1]
|
670 |
+
# specific overrides general
|
671 |
+
H.add_nodes_from([0, (1, {"c": "green"}), (3, {"c": "cyan"})], c="red")
|
672 |
+
assert H.nodes[0]["c"] == "red"
|
673 |
+
assert H.nodes[1]["c"] == "green"
|
674 |
+
assert H.nodes[2]["c"] == "blue"
|
675 |
+
assert H.nodes[3]["c"] == "cyan"
|
676 |
+
|
677 |
+
def test_remove_node(self):
|
678 |
+
G = self.K3.copy()
|
679 |
+
G.remove_node(0)
|
680 |
+
assert G.adj == {1: {2: {}}, 2: {1: {}}}
|
681 |
+
with pytest.raises(nx.NetworkXError):
|
682 |
+
G.remove_node(-1)
|
683 |
+
|
684 |
+
# generator here to implement list,set,string...
|
685 |
+
|
686 |
+
def test_remove_nodes_from(self):
|
687 |
+
G = self.K3.copy()
|
688 |
+
G.remove_nodes_from([0, 1])
|
689 |
+
assert G.adj == {2: {}}
|
690 |
+
G.remove_nodes_from([-1]) # silent fail
|
691 |
+
|
692 |
+
def test_add_edge(self):
|
693 |
+
G = self.Graph()
|
694 |
+
G.add_edge(0, 1)
|
695 |
+
assert G.adj == {0: {1: {}}, 1: {0: {}}}
|
696 |
+
G = self.Graph()
|
697 |
+
G.add_edge(*(0, 1))
|
698 |
+
assert G.adj == {0: {1: {}}, 1: {0: {}}}
|
699 |
+
G = self.Graph()
|
700 |
+
with pytest.raises(ValueError):
|
701 |
+
G.add_edge(None, "anything")
|
702 |
+
|
703 |
+
def test_add_edges_from(self):
|
704 |
+
G = self.Graph()
|
705 |
+
G.add_edges_from([(0, 1), (0, 2, {"weight": 3})])
|
706 |
+
assert G.adj == {
|
707 |
+
0: {1: {}, 2: {"weight": 3}},
|
708 |
+
1: {0: {}},
|
709 |
+
2: {0: {"weight": 3}},
|
710 |
+
}
|
711 |
+
G = self.Graph()
|
712 |
+
G.add_edges_from([(0, 1), (0, 2, {"weight": 3}), (1, 2, {"data": 4})], data=2)
|
713 |
+
assert G.adj == {
|
714 |
+
0: {1: {"data": 2}, 2: {"weight": 3, "data": 2}},
|
715 |
+
1: {0: {"data": 2}, 2: {"data": 4}},
|
716 |
+
2: {0: {"weight": 3, "data": 2}, 1: {"data": 4}},
|
717 |
+
}
|
718 |
+
|
719 |
+
with pytest.raises(nx.NetworkXError):
|
720 |
+
G.add_edges_from([(0,)]) # too few in tuple
|
721 |
+
with pytest.raises(nx.NetworkXError):
|
722 |
+
G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
|
723 |
+
with pytest.raises(TypeError):
|
724 |
+
G.add_edges_from([0]) # not a tuple
|
725 |
+
with pytest.raises(ValueError):
|
726 |
+
G.add_edges_from([(None, 3), (3, 2)]) # None cannot be a node
|
727 |
+
|
728 |
+
def test_remove_edge(self):
|
729 |
+
G = self.K3.copy()
|
730 |
+
G.remove_edge(0, 1)
|
731 |
+
assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
|
732 |
+
with pytest.raises(nx.NetworkXError):
|
733 |
+
G.remove_edge(-1, 0)
|
734 |
+
|
735 |
+
def test_remove_edges_from(self):
|
736 |
+
G = self.K3.copy()
|
737 |
+
G.remove_edges_from([(0, 1)])
|
738 |
+
assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
|
739 |
+
G.remove_edges_from([(0, 0)]) # silent fail
|
740 |
+
|
741 |
+
def test_clear(self):
|
742 |
+
G = self.K3.copy()
|
743 |
+
G.graph["name"] = "K3"
|
744 |
+
G.clear()
|
745 |
+
assert list(G.nodes) == []
|
746 |
+
assert G.adj == {}
|
747 |
+
assert G.graph == {}
|
748 |
+
|
749 |
+
def test_clear_edges(self):
|
750 |
+
G = self.K3.copy()
|
751 |
+
G.graph["name"] = "K3"
|
752 |
+
nodes = list(G.nodes)
|
753 |
+
G.clear_edges()
|
754 |
+
assert list(G.nodes) == nodes
|
755 |
+
assert G.adj == {0: {}, 1: {}, 2: {}}
|
756 |
+
assert list(G.edges) == []
|
757 |
+
assert G.graph["name"] == "K3"
|
758 |
+
|
759 |
+
def test_edges_data(self):
|
760 |
+
G = self.K3
|
761 |
+
all_edges = [(0, 1, {}), (0, 2, {}), (1, 2, {})]
|
762 |
+
assert edges_equal(G.edges(data=True), all_edges)
|
763 |
+
assert edges_equal(G.edges(0, data=True), [(0, 1, {}), (0, 2, {})])
|
764 |
+
assert edges_equal(G.edges([0, 1], data=True), all_edges)
|
765 |
+
with pytest.raises(nx.NetworkXError):
|
766 |
+
G.edges(-1, True)
|
767 |
+
|
768 |
+
def test_get_edge_data(self):
|
769 |
+
G = self.K3.copy()
|
770 |
+
assert G.get_edge_data(0, 1) == {}
|
771 |
+
assert G[0][1] == {}
|
772 |
+
assert G.get_edge_data(10, 20) is None
|
773 |
+
assert G.get_edge_data(-1, 0) is None
|
774 |
+
assert G.get_edge_data(-1, 0, default=1) == 1
|
775 |
+
|
776 |
+
def test_update(self):
|
777 |
+
# specify both edges and nodes
|
778 |
+
G = self.K3.copy()
|
779 |
+
G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})])
|
780 |
+
nlist = [
|
781 |
+
(0, {}),
|
782 |
+
(1, {}),
|
783 |
+
(2, {}),
|
784 |
+
(3, {}),
|
785 |
+
(4, {"size": 2}),
|
786 |
+
(5, {}),
|
787 |
+
(6, {}),
|
788 |
+
(7, {}),
|
789 |
+
]
|
790 |
+
assert sorted(G.nodes.data()) == nlist
|
791 |
+
if G.is_directed():
|
792 |
+
elist = [
|
793 |
+
(0, 1, {}),
|
794 |
+
(0, 2, {}),
|
795 |
+
(1, 0, {}),
|
796 |
+
(1, 2, {}),
|
797 |
+
(2, 0, {}),
|
798 |
+
(2, 1, {}),
|
799 |
+
(4, 5, {}),
|
800 |
+
(6, 7, {"weight": 2}),
|
801 |
+
]
|
802 |
+
else:
|
803 |
+
elist = [
|
804 |
+
(0, 1, {}),
|
805 |
+
(0, 2, {}),
|
806 |
+
(1, 2, {}),
|
807 |
+
(4, 5, {}),
|
808 |
+
(6, 7, {"weight": 2}),
|
809 |
+
]
|
810 |
+
assert sorted(G.edges.data()) == elist
|
811 |
+
assert G.graph == {}
|
812 |
+
|
813 |
+
# no keywords -- order is edges, nodes
|
814 |
+
G = self.K3.copy()
|
815 |
+
G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})])
|
816 |
+
assert sorted(G.nodes.data()) == nlist
|
817 |
+
assert sorted(G.edges.data()) == elist
|
818 |
+
assert G.graph == {}
|
819 |
+
|
820 |
+
# update using only a graph
|
821 |
+
G = self.Graph()
|
822 |
+
G.graph["foo"] = "bar"
|
823 |
+
G.add_node(2, data=4)
|
824 |
+
G.add_edge(0, 1, weight=0.5)
|
825 |
+
GG = G.copy()
|
826 |
+
H = self.Graph()
|
827 |
+
GG.update(H)
|
828 |
+
assert graphs_equal(G, GG)
|
829 |
+
H.update(G)
|
830 |
+
assert graphs_equal(H, G)
|
831 |
+
|
832 |
+
# update nodes only
|
833 |
+
H = self.Graph()
|
834 |
+
H.update(nodes=[3, 4])
|
835 |
+
assert H.nodes ^ {3, 4} == set()
|
836 |
+
assert H.size() == 0
|
837 |
+
|
838 |
+
# update edges only
|
839 |
+
H = self.Graph()
|
840 |
+
H.update(edges=[(3, 4)])
|
841 |
+
assert sorted(H.edges.data()) == [(3, 4, {})]
|
842 |
+
assert H.size() == 1
|
843 |
+
|
844 |
+
# No inputs -> exception
|
845 |
+
with pytest.raises(nx.NetworkXError):
|
846 |
+
nx.Graph().update()
|
847 |
+
|
848 |
+
|
849 |
+
class TestEdgeSubgraph:
|
850 |
+
"""Unit tests for the :meth:`Graph.edge_subgraph` method."""
|
851 |
+
|
852 |
+
def setup_method(self):
|
853 |
+
# Create a path graph on five nodes.
|
854 |
+
G = nx.path_graph(5)
|
855 |
+
# Add some node, edge, and graph attributes.
|
856 |
+
for i in range(5):
|
857 |
+
G.nodes[i]["name"] = f"node{i}"
|
858 |
+
G.edges[0, 1]["name"] = "edge01"
|
859 |
+
G.edges[3, 4]["name"] = "edge34"
|
860 |
+
G.graph["name"] = "graph"
|
861 |
+
# Get the subgraph induced by the first and last edges.
|
862 |
+
self.G = G
|
863 |
+
self.H = G.edge_subgraph([(0, 1), (3, 4)])
|
864 |
+
|
865 |
+
def test_correct_nodes(self):
|
866 |
+
"""Tests that the subgraph has the correct nodes."""
|
867 |
+
assert [0, 1, 3, 4] == sorted(self.H.nodes())
|
868 |
+
|
869 |
+
def test_correct_edges(self):
|
870 |
+
"""Tests that the subgraph has the correct edges."""
|
871 |
+
assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name"))
|
872 |
+
|
873 |
+
def test_add_node(self):
|
874 |
+
"""Tests that adding a node to the original graph does not
|
875 |
+
affect the nodes of the subgraph.
|
876 |
+
|
877 |
+
"""
|
878 |
+
self.G.add_node(5)
|
879 |
+
assert [0, 1, 3, 4] == sorted(self.H.nodes())
|
880 |
+
|
881 |
+
def test_remove_node(self):
|
882 |
+
"""Tests that removing a node in the original graph does
|
883 |
+
affect the nodes of the subgraph.
|
884 |
+
|
885 |
+
"""
|
886 |
+
self.G.remove_node(0)
|
887 |
+
assert [1, 3, 4] == sorted(self.H.nodes())
|
888 |
+
|
889 |
+
def test_node_attr_dict(self):
|
890 |
+
"""Tests that the node attribute dictionary of the two graphs is
|
891 |
+
the same object.
|
892 |
+
|
893 |
+
"""
|
894 |
+
for v in self.H:
|
895 |
+
assert self.G.nodes[v] == self.H.nodes[v]
|
896 |
+
# Making a change to G should make a change in H and vice versa.
|
897 |
+
self.G.nodes[0]["name"] = "foo"
|
898 |
+
assert self.G.nodes[0] == self.H.nodes[0]
|
899 |
+
self.H.nodes[1]["name"] = "bar"
|
900 |
+
assert self.G.nodes[1] == self.H.nodes[1]
|
901 |
+
|
902 |
+
def test_edge_attr_dict(self):
|
903 |
+
"""Tests that the edge attribute dictionary of the two graphs is
|
904 |
+
the same object.
|
905 |
+
|
906 |
+
"""
|
907 |
+
for u, v in self.H.edges():
|
908 |
+
assert self.G.edges[u, v] == self.H.edges[u, v]
|
909 |
+
# Making a change to G should make a change in H and vice versa.
|
910 |
+
self.G.edges[0, 1]["name"] = "foo"
|
911 |
+
assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
|
912 |
+
self.H.edges[3, 4]["name"] = "bar"
|
913 |
+
assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
|
914 |
+
|
915 |
+
def test_graph_attr_dict(self):
|
916 |
+
"""Tests that the graph attribute dictionary of the two graphs
|
917 |
+
is the same object.
|
918 |
+
|
919 |
+
"""
|
920 |
+
assert self.G.graph is self.H.graph
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_graph_historical.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Original NetworkX graph tests"""
|
2 |
+
import networkx
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
from .historical_tests import HistoricalTests
|
6 |
+
|
7 |
+
|
8 |
+
class TestGraphHistorical(HistoricalTests):
|
9 |
+
@classmethod
|
10 |
+
def setup_class(cls):
|
11 |
+
HistoricalTests.setup_class()
|
12 |
+
cls.G = nx.Graph
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_graphviews.py
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.utils import edges_equal, nodes_equal
|
5 |
+
|
6 |
+
# Note: SubGraph views are not tested here. They have their own testing file
|
7 |
+
|
8 |
+
|
9 |
+
class TestReverseView:
|
10 |
+
def setup_method(self):
|
11 |
+
self.G = nx.path_graph(9, create_using=nx.DiGraph())
|
12 |
+
self.rv = nx.reverse_view(self.G)
|
13 |
+
|
14 |
+
def test_pickle(self):
|
15 |
+
import pickle
|
16 |
+
|
17 |
+
rv = self.rv
|
18 |
+
prv = pickle.loads(pickle.dumps(rv, -1))
|
19 |
+
assert rv._node == prv._node
|
20 |
+
assert rv._adj == prv._adj
|
21 |
+
assert rv.graph == prv.graph
|
22 |
+
|
23 |
+
def test_contains(self):
|
24 |
+
assert (2, 3) in self.G.edges
|
25 |
+
assert (3, 2) not in self.G.edges
|
26 |
+
assert (2, 3) not in self.rv.edges
|
27 |
+
assert (3, 2) in self.rv.edges
|
28 |
+
|
29 |
+
def test_iter(self):
|
30 |
+
expected = sorted(tuple(reversed(e)) for e in self.G.edges)
|
31 |
+
assert sorted(self.rv.edges) == expected
|
32 |
+
|
33 |
+
def test_exceptions(self):
|
34 |
+
G = nx.Graph()
|
35 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.reverse_view, G)
|
36 |
+
|
37 |
+
def test_subclass(self):
|
38 |
+
class MyGraph(nx.DiGraph):
|
39 |
+
def my_method(self):
|
40 |
+
return "me"
|
41 |
+
|
42 |
+
def to_directed_class(self):
|
43 |
+
return MyGraph()
|
44 |
+
|
45 |
+
M = MyGraph()
|
46 |
+
M.add_edge(1, 2)
|
47 |
+
RM = nx.reverse_view(M)
|
48 |
+
print("RM class", RM.__class__)
|
49 |
+
RMC = RM.copy()
|
50 |
+
print("RMC class", RMC.__class__)
|
51 |
+
print(RMC.edges)
|
52 |
+
assert RMC.has_edge(2, 1)
|
53 |
+
assert RMC.my_method() == "me"
|
54 |
+
|
55 |
+
|
56 |
+
class TestMultiReverseView:
|
57 |
+
def setup_method(self):
|
58 |
+
self.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
|
59 |
+
self.G.add_edge(4, 5)
|
60 |
+
self.rv = nx.reverse_view(self.G)
|
61 |
+
|
62 |
+
def test_pickle(self):
|
63 |
+
import pickle
|
64 |
+
|
65 |
+
rv = self.rv
|
66 |
+
prv = pickle.loads(pickle.dumps(rv, -1))
|
67 |
+
assert rv._node == prv._node
|
68 |
+
assert rv._adj == prv._adj
|
69 |
+
assert rv.graph == prv.graph
|
70 |
+
|
71 |
+
def test_contains(self):
|
72 |
+
assert (2, 3, 0) in self.G.edges
|
73 |
+
assert (3, 2, 0) not in self.G.edges
|
74 |
+
assert (2, 3, 0) not in self.rv.edges
|
75 |
+
assert (3, 2, 0) in self.rv.edges
|
76 |
+
assert (5, 4, 1) in self.rv.edges
|
77 |
+
assert (4, 5, 1) not in self.rv.edges
|
78 |
+
|
79 |
+
def test_iter(self):
|
80 |
+
expected = sorted((v, u, k) for u, v, k in self.G.edges)
|
81 |
+
assert sorted(self.rv.edges) == expected
|
82 |
+
|
83 |
+
def test_exceptions(self):
|
84 |
+
MG = nx.MultiGraph(self.G)
|
85 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.reverse_view, MG)
|
86 |
+
|
87 |
+
|
88 |
+
def test_generic_multitype():
|
89 |
+
nxg = nx.graphviews
|
90 |
+
G = nx.DiGraph([(1, 2)])
|
91 |
+
with pytest.raises(nx.NetworkXError):
|
92 |
+
nxg.generic_graph_view(G, create_using=nx.MultiGraph)
|
93 |
+
G = nx.MultiDiGraph([(1, 2)])
|
94 |
+
with pytest.raises(nx.NetworkXError):
|
95 |
+
nxg.generic_graph_view(G, create_using=nx.DiGraph)
|
96 |
+
|
97 |
+
|
98 |
+
class TestToDirected:
|
99 |
+
def setup_method(self):
|
100 |
+
self.G = nx.path_graph(9)
|
101 |
+
self.dv = nx.to_directed(self.G)
|
102 |
+
self.MG = nx.path_graph(9, create_using=nx.MultiGraph())
|
103 |
+
self.Mdv = nx.to_directed(self.MG)
|
104 |
+
|
105 |
+
def test_directed(self):
|
106 |
+
assert not self.G.is_directed()
|
107 |
+
assert self.dv.is_directed()
|
108 |
+
|
109 |
+
def test_already_directed(self):
|
110 |
+
dd = nx.to_directed(self.dv)
|
111 |
+
Mdd = nx.to_directed(self.Mdv)
|
112 |
+
assert edges_equal(dd.edges, self.dv.edges)
|
113 |
+
assert edges_equal(Mdd.edges, self.Mdv.edges)
|
114 |
+
|
115 |
+
def test_pickle(self):
|
116 |
+
import pickle
|
117 |
+
|
118 |
+
dv = self.dv
|
119 |
+
pdv = pickle.loads(pickle.dumps(dv, -1))
|
120 |
+
assert dv._node == pdv._node
|
121 |
+
assert dv._succ == pdv._succ
|
122 |
+
assert dv._pred == pdv._pred
|
123 |
+
assert dv.graph == pdv.graph
|
124 |
+
|
125 |
+
def test_contains(self):
|
126 |
+
assert (2, 3) in self.G.edges
|
127 |
+
assert (3, 2) in self.G.edges
|
128 |
+
assert (2, 3) in self.dv.edges
|
129 |
+
assert (3, 2) in self.dv.edges
|
130 |
+
|
131 |
+
def test_iter(self):
|
132 |
+
revd = [tuple(reversed(e)) for e in self.G.edges]
|
133 |
+
expected = sorted(list(self.G.edges) + revd)
|
134 |
+
assert sorted(self.dv.edges) == expected
|
135 |
+
|
136 |
+
|
137 |
+
class TestToUndirected:
|
138 |
+
def setup_method(self):
|
139 |
+
self.DG = nx.path_graph(9, create_using=nx.DiGraph())
|
140 |
+
self.uv = nx.to_undirected(self.DG)
|
141 |
+
self.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph())
|
142 |
+
self.Muv = nx.to_undirected(self.MDG)
|
143 |
+
|
144 |
+
def test_directed(self):
|
145 |
+
assert self.DG.is_directed()
|
146 |
+
assert not self.uv.is_directed()
|
147 |
+
|
148 |
+
def test_already_directed(self):
|
149 |
+
uu = nx.to_undirected(self.uv)
|
150 |
+
Muu = nx.to_undirected(self.Muv)
|
151 |
+
assert edges_equal(uu.edges, self.uv.edges)
|
152 |
+
assert edges_equal(Muu.edges, self.Muv.edges)
|
153 |
+
|
154 |
+
def test_pickle(self):
|
155 |
+
import pickle
|
156 |
+
|
157 |
+
uv = self.uv
|
158 |
+
puv = pickle.loads(pickle.dumps(uv, -1))
|
159 |
+
assert uv._node == puv._node
|
160 |
+
assert uv._adj == puv._adj
|
161 |
+
assert uv.graph == puv.graph
|
162 |
+
assert hasattr(uv, "_graph")
|
163 |
+
|
164 |
+
def test_contains(self):
|
165 |
+
assert (2, 3) in self.DG.edges
|
166 |
+
assert (3, 2) not in self.DG.edges
|
167 |
+
assert (2, 3) in self.uv.edges
|
168 |
+
assert (3, 2) in self.uv.edges
|
169 |
+
|
170 |
+
def test_iter(self):
|
171 |
+
expected = sorted(self.DG.edges)
|
172 |
+
assert sorted(self.uv.edges) == expected
|
173 |
+
|
174 |
+
|
175 |
+
class TestChainsOfViews:
|
176 |
+
@classmethod
|
177 |
+
def setup_class(cls):
|
178 |
+
cls.G = nx.path_graph(9)
|
179 |
+
cls.DG = nx.path_graph(9, create_using=nx.DiGraph())
|
180 |
+
cls.MG = nx.path_graph(9, create_using=nx.MultiGraph())
|
181 |
+
cls.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph())
|
182 |
+
cls.Gv = nx.to_undirected(cls.DG)
|
183 |
+
cls.DGv = nx.to_directed(cls.G)
|
184 |
+
cls.MGv = nx.to_undirected(cls.MDG)
|
185 |
+
cls.MDGv = nx.to_directed(cls.MG)
|
186 |
+
cls.Rv = cls.DG.reverse()
|
187 |
+
cls.MRv = cls.MDG.reverse()
|
188 |
+
cls.graphs = [
|
189 |
+
cls.G,
|
190 |
+
cls.DG,
|
191 |
+
cls.MG,
|
192 |
+
cls.MDG,
|
193 |
+
cls.Gv,
|
194 |
+
cls.DGv,
|
195 |
+
cls.MGv,
|
196 |
+
cls.MDGv,
|
197 |
+
cls.Rv,
|
198 |
+
cls.MRv,
|
199 |
+
]
|
200 |
+
for G in cls.graphs:
|
201 |
+
G.edges, G.nodes, G.degree
|
202 |
+
|
203 |
+
def test_pickle(self):
|
204 |
+
import pickle
|
205 |
+
|
206 |
+
for G in self.graphs:
|
207 |
+
H = pickle.loads(pickle.dumps(G, -1))
|
208 |
+
assert edges_equal(H.edges, G.edges)
|
209 |
+
assert nodes_equal(H.nodes, G.nodes)
|
210 |
+
|
211 |
+
def test_subgraph_of_subgraph(self):
|
212 |
+
SGv = nx.subgraph(self.G, range(3, 7))
|
213 |
+
SDGv = nx.subgraph(self.DG, range(3, 7))
|
214 |
+
SMGv = nx.subgraph(self.MG, range(3, 7))
|
215 |
+
SMDGv = nx.subgraph(self.MDG, range(3, 7))
|
216 |
+
for G in self.graphs + [SGv, SDGv, SMGv, SMDGv]:
|
217 |
+
SG = nx.induced_subgraph(G, [4, 5, 6])
|
218 |
+
assert list(SG) == [4, 5, 6]
|
219 |
+
SSG = SG.subgraph([6, 7])
|
220 |
+
assert list(SSG) == [6]
|
221 |
+
# subgraph-subgraph chain is short-cut in base class method
|
222 |
+
assert SSG._graph is G
|
223 |
+
|
224 |
+
def test_restricted_induced_subgraph_chains(self):
|
225 |
+
"""Test subgraph chains that both restrict and show nodes/edges.
|
226 |
+
|
227 |
+
A restricted_view subgraph should allow induced subgraphs using
|
228 |
+
G.subgraph that automagically without a chain (meaning the result
|
229 |
+
is a subgraph view of the original graph not a subgraph-of-subgraph.
|
230 |
+
"""
|
231 |
+
hide_nodes = [3, 4, 5]
|
232 |
+
hide_edges = [(6, 7)]
|
233 |
+
RG = nx.restricted_view(self.G, hide_nodes, hide_edges)
|
234 |
+
nodes = [4, 5, 6, 7, 8]
|
235 |
+
SG = nx.induced_subgraph(RG, nodes)
|
236 |
+
SSG = RG.subgraph(nodes)
|
237 |
+
assert RG._graph is self.G
|
238 |
+
assert SSG._graph is self.G
|
239 |
+
assert SG._graph is RG
|
240 |
+
assert edges_equal(SG.edges, SSG.edges)
|
241 |
+
# should be same as morphing the graph
|
242 |
+
CG = self.G.copy()
|
243 |
+
CG.remove_nodes_from(hide_nodes)
|
244 |
+
CG.remove_edges_from(hide_edges)
|
245 |
+
assert edges_equal(CG.edges(nodes), SSG.edges)
|
246 |
+
CG.remove_nodes_from([0, 1, 2, 3])
|
247 |
+
assert edges_equal(CG.edges, SSG.edges)
|
248 |
+
# switch order: subgraph first, then restricted view
|
249 |
+
SSSG = self.G.subgraph(nodes)
|
250 |
+
RSG = nx.restricted_view(SSSG, hide_nodes, hide_edges)
|
251 |
+
assert RSG._graph is not self.G
|
252 |
+
assert edges_equal(RSG.edges, CG.edges)
|
253 |
+
|
254 |
+
def test_subgraph_copy(self):
|
255 |
+
for origG in self.graphs:
|
256 |
+
G = nx.Graph(origG)
|
257 |
+
SG = G.subgraph([4, 5, 6])
|
258 |
+
H = SG.copy()
|
259 |
+
assert type(G) == type(H)
|
260 |
+
|
261 |
+
def test_subgraph_todirected(self):
|
262 |
+
SG = nx.induced_subgraph(self.G, [4, 5, 6])
|
263 |
+
SSG = SG.to_directed()
|
264 |
+
assert sorted(SSG) == [4, 5, 6]
|
265 |
+
assert sorted(SSG.edges) == [(4, 5), (5, 4), (5, 6), (6, 5)]
|
266 |
+
|
267 |
+
def test_subgraph_toundirected(self):
|
268 |
+
SG = nx.induced_subgraph(self.G, [4, 5, 6])
|
269 |
+
SSG = SG.to_undirected()
|
270 |
+
assert list(SSG) == [4, 5, 6]
|
271 |
+
assert sorted(SSG.edges) == [(4, 5), (5, 6)]
|
272 |
+
|
273 |
+
def test_reverse_subgraph_toundirected(self):
|
274 |
+
G = self.DG.reverse(copy=False)
|
275 |
+
SG = G.subgraph([4, 5, 6])
|
276 |
+
SSG = SG.to_undirected()
|
277 |
+
assert list(SSG) == [4, 5, 6]
|
278 |
+
assert sorted(SSG.edges) == [(4, 5), (5, 6)]
|
279 |
+
|
280 |
+
def test_reverse_reverse_copy(self):
|
281 |
+
G = self.DG.reverse(copy=False)
|
282 |
+
H = G.reverse(copy=True)
|
283 |
+
assert H.nodes == self.DG.nodes
|
284 |
+
assert H.edges == self.DG.edges
|
285 |
+
G = self.MDG.reverse(copy=False)
|
286 |
+
H = G.reverse(copy=True)
|
287 |
+
assert H.nodes == self.MDG.nodes
|
288 |
+
assert H.edges == self.MDG.edges
|
289 |
+
|
290 |
+
def test_subgraph_edgesubgraph_toundirected(self):
|
291 |
+
G = self.G.copy()
|
292 |
+
SG = G.subgraph([4, 5, 6])
|
293 |
+
SSG = SG.edge_subgraph([(4, 5), (5, 4)])
|
294 |
+
USSG = SSG.to_undirected()
|
295 |
+
assert list(USSG) == [4, 5]
|
296 |
+
assert sorted(USSG.edges) == [(4, 5)]
|
297 |
+
|
298 |
+
def test_copy_subgraph(self):
|
299 |
+
G = self.G.copy()
|
300 |
+
SG = G.subgraph([4, 5, 6])
|
301 |
+
CSG = SG.copy(as_view=True)
|
302 |
+
DCSG = SG.copy(as_view=False)
|
303 |
+
assert hasattr(CSG, "_graph") # is a view
|
304 |
+
assert not hasattr(DCSG, "_graph") # not a view
|
305 |
+
|
306 |
+
def test_copy_disubgraph(self):
|
307 |
+
G = self.DG.copy()
|
308 |
+
SG = G.subgraph([4, 5, 6])
|
309 |
+
CSG = SG.copy(as_view=True)
|
310 |
+
DCSG = SG.copy(as_view=False)
|
311 |
+
assert hasattr(CSG, "_graph") # is a view
|
312 |
+
assert not hasattr(DCSG, "_graph") # not a view
|
313 |
+
|
314 |
+
def test_copy_multidisubgraph(self):
|
315 |
+
G = self.MDG.copy()
|
316 |
+
SG = G.subgraph([4, 5, 6])
|
317 |
+
CSG = SG.copy(as_view=True)
|
318 |
+
DCSG = SG.copy(as_view=False)
|
319 |
+
assert hasattr(CSG, "_graph") # is a view
|
320 |
+
assert not hasattr(DCSG, "_graph") # not a view
|
321 |
+
|
322 |
+
def test_copy_multisubgraph(self):
|
323 |
+
G = self.MG.copy()
|
324 |
+
SG = G.subgraph([4, 5, 6])
|
325 |
+
CSG = SG.copy(as_view=True)
|
326 |
+
DCSG = SG.copy(as_view=False)
|
327 |
+
assert hasattr(CSG, "_graph") # is a view
|
328 |
+
assert not hasattr(DCSG, "_graph") # not a view
|
329 |
+
|
330 |
+
def test_copy_of_view(self):
|
331 |
+
G = nx.MultiGraph(self.MGv)
|
332 |
+
assert G.__class__.__name__ == "MultiGraph"
|
333 |
+
G = G.copy(as_view=True)
|
334 |
+
assert G.__class__.__name__ == "MultiGraph"
|
335 |
+
|
336 |
+
def test_subclass(self):
|
337 |
+
class MyGraph(nx.DiGraph):
|
338 |
+
def my_method(self):
|
339 |
+
return "me"
|
340 |
+
|
341 |
+
def to_directed_class(self):
|
342 |
+
return MyGraph()
|
343 |
+
|
344 |
+
for origG in self.graphs:
|
345 |
+
G = MyGraph(origG)
|
346 |
+
SG = G.subgraph([4, 5, 6])
|
347 |
+
H = SG.copy()
|
348 |
+
assert SG.my_method() == "me"
|
349 |
+
assert H.my_method() == "me"
|
350 |
+
assert 3 not in H or 3 in SG
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_multidigraph.py
ADDED
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import UserDict
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx.utils import edges_equal
|
7 |
+
|
8 |
+
from .test_multigraph import BaseMultiGraphTester
|
9 |
+
from .test_multigraph import TestEdgeSubgraph as _TestMultiGraphEdgeSubgraph
|
10 |
+
from .test_multigraph import TestMultiGraph as _TestMultiGraph
|
11 |
+
|
12 |
+
|
13 |
+
class BaseMultiDiGraphTester(BaseMultiGraphTester):
|
14 |
+
def test_edges(self):
|
15 |
+
G = self.K3
|
16 |
+
edges = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
17 |
+
assert sorted(G.edges()) == edges
|
18 |
+
assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
|
19 |
+
pytest.raises((KeyError, nx.NetworkXError), G.edges, -1)
|
20 |
+
|
21 |
+
def test_edges_data(self):
|
22 |
+
G = self.K3
|
23 |
+
edges = [(0, 1, {}), (0, 2, {}), (1, 0, {}), (1, 2, {}), (2, 0, {}), (2, 1, {})]
|
24 |
+
assert sorted(G.edges(data=True)) == edges
|
25 |
+
assert sorted(G.edges(0, data=True)) == [(0, 1, {}), (0, 2, {})]
|
26 |
+
pytest.raises((KeyError, nx.NetworkXError), G.neighbors, -1)
|
27 |
+
|
28 |
+
def test_edges_multi(self):
|
29 |
+
G = self.K3
|
30 |
+
assert sorted(G.edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
31 |
+
assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
|
32 |
+
G.add_edge(0, 1)
|
33 |
+
assert sorted(G.edges()) == [
|
34 |
+
(0, 1),
|
35 |
+
(0, 1),
|
36 |
+
(0, 2),
|
37 |
+
(1, 0),
|
38 |
+
(1, 2),
|
39 |
+
(2, 0),
|
40 |
+
(2, 1),
|
41 |
+
]
|
42 |
+
|
43 |
+
def test_out_edges(self):
|
44 |
+
G = self.K3
|
45 |
+
assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
46 |
+
assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
|
47 |
+
pytest.raises((KeyError, nx.NetworkXError), G.out_edges, -1)
|
48 |
+
assert sorted(G.out_edges(0, keys=True)) == [(0, 1, 0), (0, 2, 0)]
|
49 |
+
|
50 |
+
def test_out_edges_multi(self):
|
51 |
+
G = self.K3
|
52 |
+
assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
53 |
+
assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
|
54 |
+
G.add_edge(0, 1, 2)
|
55 |
+
assert sorted(G.out_edges()) == [
|
56 |
+
(0, 1),
|
57 |
+
(0, 1),
|
58 |
+
(0, 2),
|
59 |
+
(1, 0),
|
60 |
+
(1, 2),
|
61 |
+
(2, 0),
|
62 |
+
(2, 1),
|
63 |
+
]
|
64 |
+
|
65 |
+
def test_out_edges_data(self):
|
66 |
+
G = self.K3
|
67 |
+
assert sorted(G.edges(0, data=True)) == [(0, 1, {}), (0, 2, {})]
|
68 |
+
G.remove_edge(0, 1)
|
69 |
+
G.add_edge(0, 1, data=1)
|
70 |
+
assert sorted(G.edges(0, data=True)) == [(0, 1, {"data": 1}), (0, 2, {})]
|
71 |
+
assert sorted(G.edges(0, data="data")) == [(0, 1, 1), (0, 2, None)]
|
72 |
+
assert sorted(G.edges(0, data="data", default=-1)) == [(0, 1, 1), (0, 2, -1)]
|
73 |
+
|
74 |
+
def test_in_edges(self):
|
75 |
+
G = self.K3
|
76 |
+
assert sorted(G.in_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
77 |
+
assert sorted(G.in_edges(0)) == [(1, 0), (2, 0)]
|
78 |
+
pytest.raises((KeyError, nx.NetworkXError), G.in_edges, -1)
|
79 |
+
G.add_edge(0, 1, 2)
|
80 |
+
assert sorted(G.in_edges()) == [
|
81 |
+
(0, 1),
|
82 |
+
(0, 1),
|
83 |
+
(0, 2),
|
84 |
+
(1, 0),
|
85 |
+
(1, 2),
|
86 |
+
(2, 0),
|
87 |
+
(2, 1),
|
88 |
+
]
|
89 |
+
assert sorted(G.in_edges(0, keys=True)) == [(1, 0, 0), (2, 0, 0)]
|
90 |
+
|
91 |
+
def test_in_edges_no_keys(self):
|
92 |
+
G = self.K3
|
93 |
+
assert sorted(G.in_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
94 |
+
assert sorted(G.in_edges(0)) == [(1, 0), (2, 0)]
|
95 |
+
G.add_edge(0, 1, 2)
|
96 |
+
assert sorted(G.in_edges()) == [
|
97 |
+
(0, 1),
|
98 |
+
(0, 1),
|
99 |
+
(0, 2),
|
100 |
+
(1, 0),
|
101 |
+
(1, 2),
|
102 |
+
(2, 0),
|
103 |
+
(2, 1),
|
104 |
+
]
|
105 |
+
|
106 |
+
assert sorted(G.in_edges(data=True, keys=False)) == [
|
107 |
+
(0, 1, {}),
|
108 |
+
(0, 1, {}),
|
109 |
+
(0, 2, {}),
|
110 |
+
(1, 0, {}),
|
111 |
+
(1, 2, {}),
|
112 |
+
(2, 0, {}),
|
113 |
+
(2, 1, {}),
|
114 |
+
]
|
115 |
+
|
116 |
+
def test_in_edges_data(self):
|
117 |
+
G = self.K3
|
118 |
+
assert sorted(G.in_edges(0, data=True)) == [(1, 0, {}), (2, 0, {})]
|
119 |
+
G.remove_edge(1, 0)
|
120 |
+
G.add_edge(1, 0, data=1)
|
121 |
+
assert sorted(G.in_edges(0, data=True)) == [(1, 0, {"data": 1}), (2, 0, {})]
|
122 |
+
assert sorted(G.in_edges(0, data="data")) == [(1, 0, 1), (2, 0, None)]
|
123 |
+
assert sorted(G.in_edges(0, data="data", default=-1)) == [(1, 0, 1), (2, 0, -1)]
|
124 |
+
|
125 |
+
def is_shallow(self, H, G):
|
126 |
+
# graph
|
127 |
+
assert G.graph["foo"] == H.graph["foo"]
|
128 |
+
G.graph["foo"].append(1)
|
129 |
+
assert G.graph["foo"] == H.graph["foo"]
|
130 |
+
# node
|
131 |
+
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
|
132 |
+
G.nodes[0]["foo"].append(1)
|
133 |
+
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
|
134 |
+
# edge
|
135 |
+
assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
|
136 |
+
G[1][2][0]["foo"].append(1)
|
137 |
+
assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
|
138 |
+
|
139 |
+
def is_deep(self, H, G):
|
140 |
+
# graph
|
141 |
+
assert G.graph["foo"] == H.graph["foo"]
|
142 |
+
G.graph["foo"].append(1)
|
143 |
+
assert G.graph["foo"] != H.graph["foo"]
|
144 |
+
# node
|
145 |
+
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
|
146 |
+
G.nodes[0]["foo"].append(1)
|
147 |
+
assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
|
148 |
+
# edge
|
149 |
+
assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
|
150 |
+
G[1][2][0]["foo"].append(1)
|
151 |
+
assert G[1][2][0]["foo"] != H[1][2][0]["foo"]
|
152 |
+
|
153 |
+
def test_to_undirected(self):
|
154 |
+
# MultiDiGraph -> MultiGraph changes number of edges so it is
|
155 |
+
# not a copy operation... use is_shallow, not is_shallow_copy
|
156 |
+
G = self.K3
|
157 |
+
self.add_attributes(G)
|
158 |
+
H = nx.MultiGraph(G)
|
159 |
+
# self.is_shallow(H,G)
|
160 |
+
# the result is traversal order dependent so we
|
161 |
+
# can't use the is_shallow() test here.
|
162 |
+
try:
|
163 |
+
assert edges_equal(H.edges(), [(0, 1), (1, 2), (2, 0)])
|
164 |
+
except AssertionError:
|
165 |
+
assert edges_equal(H.edges(), [(0, 1), (1, 2), (1, 2), (2, 0)])
|
166 |
+
H = G.to_undirected()
|
167 |
+
self.is_deep(H, G)
|
168 |
+
|
169 |
+
def test_has_successor(self):
|
170 |
+
G = self.K3
|
171 |
+
assert G.has_successor(0, 1)
|
172 |
+
assert not G.has_successor(0, -1)
|
173 |
+
|
174 |
+
def test_successors(self):
|
175 |
+
G = self.K3
|
176 |
+
assert sorted(G.successors(0)) == [1, 2]
|
177 |
+
pytest.raises((KeyError, nx.NetworkXError), G.successors, -1)
|
178 |
+
|
179 |
+
def test_has_predecessor(self):
|
180 |
+
G = self.K3
|
181 |
+
assert G.has_predecessor(0, 1)
|
182 |
+
assert not G.has_predecessor(0, -1)
|
183 |
+
|
184 |
+
def test_predecessors(self):
|
185 |
+
G = self.K3
|
186 |
+
assert sorted(G.predecessors(0)) == [1, 2]
|
187 |
+
pytest.raises((KeyError, nx.NetworkXError), G.predecessors, -1)
|
188 |
+
|
189 |
+
def test_degree(self):
|
190 |
+
G = self.K3
|
191 |
+
assert sorted(G.degree()) == [(0, 4), (1, 4), (2, 4)]
|
192 |
+
assert dict(G.degree()) == {0: 4, 1: 4, 2: 4}
|
193 |
+
assert G.degree(0) == 4
|
194 |
+
assert list(G.degree(iter([0]))) == [(0, 4)]
|
195 |
+
G.add_edge(0, 1, weight=0.3, other=1.2)
|
196 |
+
assert sorted(G.degree(weight="weight")) == [(0, 4.3), (1, 4.3), (2, 4)]
|
197 |
+
assert sorted(G.degree(weight="other")) == [(0, 5.2), (1, 5.2), (2, 4)]
|
198 |
+
|
199 |
+
def test_in_degree(self):
|
200 |
+
G = self.K3
|
201 |
+
assert sorted(G.in_degree()) == [(0, 2), (1, 2), (2, 2)]
|
202 |
+
assert dict(G.in_degree()) == {0: 2, 1: 2, 2: 2}
|
203 |
+
assert G.in_degree(0) == 2
|
204 |
+
assert list(G.in_degree(iter([0]))) == [(0, 2)]
|
205 |
+
assert G.in_degree(0, weight="weight") == 2
|
206 |
+
|
207 |
+
def test_out_degree(self):
|
208 |
+
G = self.K3
|
209 |
+
assert sorted(G.out_degree()) == [(0, 2), (1, 2), (2, 2)]
|
210 |
+
assert dict(G.out_degree()) == {0: 2, 1: 2, 2: 2}
|
211 |
+
assert G.out_degree(0) == 2
|
212 |
+
assert list(G.out_degree(iter([0]))) == [(0, 2)]
|
213 |
+
assert G.out_degree(0, weight="weight") == 2
|
214 |
+
|
215 |
+
def test_size(self):
|
216 |
+
G = self.K3
|
217 |
+
assert G.size() == 6
|
218 |
+
assert G.number_of_edges() == 6
|
219 |
+
G.add_edge(0, 1, weight=0.3, other=1.2)
|
220 |
+
assert round(G.size(weight="weight"), 2) == 6.3
|
221 |
+
assert round(G.size(weight="other"), 2) == 7.2
|
222 |
+
|
223 |
+
def test_to_undirected_reciprocal(self):
|
224 |
+
G = self.Graph()
|
225 |
+
G.add_edge(1, 2)
|
226 |
+
assert G.to_undirected().has_edge(1, 2)
|
227 |
+
assert not G.to_undirected(reciprocal=True).has_edge(1, 2)
|
228 |
+
G.add_edge(2, 1)
|
229 |
+
assert G.to_undirected(reciprocal=True).has_edge(1, 2)
|
230 |
+
|
231 |
+
def test_reverse_copy(self):
|
232 |
+
G = nx.MultiDiGraph([(0, 1), (0, 1)])
|
233 |
+
R = G.reverse()
|
234 |
+
assert sorted(R.edges()) == [(1, 0), (1, 0)]
|
235 |
+
R.remove_edge(1, 0)
|
236 |
+
assert sorted(R.edges()) == [(1, 0)]
|
237 |
+
assert sorted(G.edges()) == [(0, 1), (0, 1)]
|
238 |
+
|
239 |
+
def test_reverse_nocopy(self):
|
240 |
+
G = nx.MultiDiGraph([(0, 1), (0, 1)])
|
241 |
+
R = G.reverse(copy=False)
|
242 |
+
assert sorted(R.edges()) == [(1, 0), (1, 0)]
|
243 |
+
pytest.raises(nx.NetworkXError, R.remove_edge, 1, 0)
|
244 |
+
|
245 |
+
def test_di_attributes_cached(self):
|
246 |
+
G = self.K3.copy()
|
247 |
+
assert id(G.in_edges) == id(G.in_edges)
|
248 |
+
assert id(G.out_edges) == id(G.out_edges)
|
249 |
+
assert id(G.in_degree) == id(G.in_degree)
|
250 |
+
assert id(G.out_degree) == id(G.out_degree)
|
251 |
+
assert id(G.succ) == id(G.succ)
|
252 |
+
assert id(G.pred) == id(G.pred)
|
253 |
+
|
254 |
+
|
255 |
+
class TestMultiDiGraph(BaseMultiDiGraphTester, _TestMultiGraph):
|
256 |
+
def setup_method(self):
|
257 |
+
self.Graph = nx.MultiDiGraph
|
258 |
+
# build K3
|
259 |
+
self.k3edges = [(0, 1), (0, 2), (1, 2)]
|
260 |
+
self.k3nodes = [0, 1, 2]
|
261 |
+
self.K3 = self.Graph()
|
262 |
+
self.K3._succ = {0: {}, 1: {}, 2: {}}
|
263 |
+
# K3._adj is synced with K3._succ
|
264 |
+
self.K3._pred = {0: {}, 1: {}, 2: {}}
|
265 |
+
for u in self.k3nodes:
|
266 |
+
for v in self.k3nodes:
|
267 |
+
if u == v:
|
268 |
+
continue
|
269 |
+
d = {0: {}}
|
270 |
+
self.K3._succ[u][v] = d
|
271 |
+
self.K3._pred[v][u] = d
|
272 |
+
self.K3._node = {}
|
273 |
+
self.K3._node[0] = {}
|
274 |
+
self.K3._node[1] = {}
|
275 |
+
self.K3._node[2] = {}
|
276 |
+
|
277 |
+
def test_add_edge(self):
|
278 |
+
G = self.Graph()
|
279 |
+
G.add_edge(0, 1)
|
280 |
+
assert G._adj == {0: {1: {0: {}}}, 1: {}}
|
281 |
+
assert G._succ == {0: {1: {0: {}}}, 1: {}}
|
282 |
+
assert G._pred == {0: {}, 1: {0: {0: {}}}}
|
283 |
+
G = self.Graph()
|
284 |
+
G.add_edge(*(0, 1))
|
285 |
+
assert G._adj == {0: {1: {0: {}}}, 1: {}}
|
286 |
+
assert G._succ == {0: {1: {0: {}}}, 1: {}}
|
287 |
+
assert G._pred == {0: {}, 1: {0: {0: {}}}}
|
288 |
+
with pytest.raises(ValueError, match="None cannot be a node"):
|
289 |
+
G.add_edge(None, 3)
|
290 |
+
|
291 |
+
def test_add_edges_from(self):
|
292 |
+
G = self.Graph()
|
293 |
+
G.add_edges_from([(0, 1), (0, 1, {"weight": 3})])
|
294 |
+
assert G._adj == {0: {1: {0: {}, 1: {"weight": 3}}}, 1: {}}
|
295 |
+
assert G._succ == {0: {1: {0: {}, 1: {"weight": 3}}}, 1: {}}
|
296 |
+
assert G._pred == {0: {}, 1: {0: {0: {}, 1: {"weight": 3}}}}
|
297 |
+
|
298 |
+
G.add_edges_from([(0, 1), (0, 1, {"weight": 3})], weight=2)
|
299 |
+
assert G._succ == {
|
300 |
+
0: {1: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
|
301 |
+
1: {},
|
302 |
+
}
|
303 |
+
assert G._pred == {
|
304 |
+
0: {},
|
305 |
+
1: {0: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
|
306 |
+
}
|
307 |
+
|
308 |
+
G = self.Graph()
|
309 |
+
edges = [
|
310 |
+
(0, 1, {"weight": 3}),
|
311 |
+
(0, 1, (("weight", 2),)),
|
312 |
+
(0, 1, 5),
|
313 |
+
(0, 1, "s"),
|
314 |
+
]
|
315 |
+
G.add_edges_from(edges)
|
316 |
+
keydict = {0: {"weight": 3}, 1: {"weight": 2}, 5: {}, "s": {}}
|
317 |
+
assert G._succ == {0: {1: keydict}, 1: {}}
|
318 |
+
assert G._pred == {1: {0: keydict}, 0: {}}
|
319 |
+
|
320 |
+
# too few in tuple
|
321 |
+
pytest.raises(nx.NetworkXError, G.add_edges_from, [(0,)])
|
322 |
+
# too many in tuple
|
323 |
+
pytest.raises(nx.NetworkXError, G.add_edges_from, [(0, 1, 2, 3, 4)])
|
324 |
+
# not a tuple
|
325 |
+
pytest.raises(TypeError, G.add_edges_from, [0])
|
326 |
+
with pytest.raises(ValueError, match="None cannot be a node"):
|
327 |
+
G.add_edges_from([(None, 3), (3, 2)])
|
328 |
+
|
329 |
+
def test_remove_edge(self):
|
330 |
+
G = self.K3
|
331 |
+
G.remove_edge(0, 1)
|
332 |
+
assert G._succ == {
|
333 |
+
0: {2: {0: {}}},
|
334 |
+
1: {0: {0: {}}, 2: {0: {}}},
|
335 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
336 |
+
}
|
337 |
+
assert G._pred == {
|
338 |
+
0: {1: {0: {}}, 2: {0: {}}},
|
339 |
+
1: {2: {0: {}}},
|
340 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
341 |
+
}
|
342 |
+
pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
|
343 |
+
pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, 0, 2, key=1)
|
344 |
+
|
345 |
+
def test_remove_multiedge(self):
|
346 |
+
G = self.K3
|
347 |
+
G.add_edge(0, 1, key="parallel edge")
|
348 |
+
G.remove_edge(0, 1, key="parallel edge")
|
349 |
+
assert G._adj == {
|
350 |
+
0: {1: {0: {}}, 2: {0: {}}},
|
351 |
+
1: {0: {0: {}}, 2: {0: {}}},
|
352 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
353 |
+
}
|
354 |
+
|
355 |
+
assert G._succ == {
|
356 |
+
0: {1: {0: {}}, 2: {0: {}}},
|
357 |
+
1: {0: {0: {}}, 2: {0: {}}},
|
358 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
359 |
+
}
|
360 |
+
|
361 |
+
assert G._pred == {
|
362 |
+
0: {1: {0: {}}, 2: {0: {}}},
|
363 |
+
1: {0: {0: {}}, 2: {0: {}}},
|
364 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
365 |
+
}
|
366 |
+
G.remove_edge(0, 1)
|
367 |
+
assert G._succ == {
|
368 |
+
0: {2: {0: {}}},
|
369 |
+
1: {0: {0: {}}, 2: {0: {}}},
|
370 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
371 |
+
}
|
372 |
+
assert G._pred == {
|
373 |
+
0: {1: {0: {}}, 2: {0: {}}},
|
374 |
+
1: {2: {0: {}}},
|
375 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
376 |
+
}
|
377 |
+
pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
|
378 |
+
|
379 |
+
def test_remove_edges_from(self):
|
380 |
+
G = self.K3
|
381 |
+
G.remove_edges_from([(0, 1)])
|
382 |
+
assert G._succ == {
|
383 |
+
0: {2: {0: {}}},
|
384 |
+
1: {0: {0: {}}, 2: {0: {}}},
|
385 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
386 |
+
}
|
387 |
+
assert G._pred == {
|
388 |
+
0: {1: {0: {}}, 2: {0: {}}},
|
389 |
+
1: {2: {0: {}}},
|
390 |
+
2: {0: {0: {}}, 1: {0: {}}},
|
391 |
+
}
|
392 |
+
G.remove_edges_from([(0, 0)]) # silent fail
|
393 |
+
|
394 |
+
|
395 |
+
class TestEdgeSubgraph(_TestMultiGraphEdgeSubgraph):
|
396 |
+
"""Unit tests for the :meth:`MultiDiGraph.edge_subgraph` method."""
|
397 |
+
|
398 |
+
def setup_method(self):
|
399 |
+
# Create a quadruply-linked path graph on five nodes.
|
400 |
+
G = nx.MultiDiGraph()
|
401 |
+
nx.add_path(G, range(5))
|
402 |
+
nx.add_path(G, range(5))
|
403 |
+
nx.add_path(G, reversed(range(5)))
|
404 |
+
nx.add_path(G, reversed(range(5)))
|
405 |
+
# Add some node, edge, and graph attributes.
|
406 |
+
for i in range(5):
|
407 |
+
G.nodes[i]["name"] = f"node{i}"
|
408 |
+
G.adj[0][1][0]["name"] = "edge010"
|
409 |
+
G.adj[0][1][1]["name"] = "edge011"
|
410 |
+
G.adj[3][4][0]["name"] = "edge340"
|
411 |
+
G.adj[3][4][1]["name"] = "edge341"
|
412 |
+
G.graph["name"] = "graph"
|
413 |
+
# Get the subgraph induced by one of the first edges and one of
|
414 |
+
# the last edges.
|
415 |
+
self.G = G
|
416 |
+
self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)])
|
417 |
+
|
418 |
+
|
419 |
+
class CustomDictClass(UserDict):
|
420 |
+
pass
|
421 |
+
|
422 |
+
|
423 |
+
class MultiDiGraphSubClass(nx.MultiDiGraph):
|
424 |
+
node_dict_factory = CustomDictClass # type: ignore[assignment]
|
425 |
+
node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
|
426 |
+
adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
|
427 |
+
adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignment]
|
428 |
+
edge_key_dict_factory = CustomDictClass # type: ignore[assignment]
|
429 |
+
edge_attr_dict_factory = CustomDictClass # type: ignore[assignment]
|
430 |
+
graph_attr_dict_factory = CustomDictClass # type: ignore[assignment]
|
431 |
+
|
432 |
+
|
433 |
+
class TestMultiDiGraphSubclass(TestMultiDiGraph):
|
434 |
+
def setup_method(self):
|
435 |
+
self.Graph = MultiDiGraphSubClass
|
436 |
+
# build K3
|
437 |
+
self.k3edges = [(0, 1), (0, 2), (1, 2)]
|
438 |
+
self.k3nodes = [0, 1, 2]
|
439 |
+
self.K3 = self.Graph()
|
440 |
+
self.K3._succ = self.K3.adjlist_outer_dict_factory(
|
441 |
+
{
|
442 |
+
0: self.K3.adjlist_inner_dict_factory(),
|
443 |
+
1: self.K3.adjlist_inner_dict_factory(),
|
444 |
+
2: self.K3.adjlist_inner_dict_factory(),
|
445 |
+
}
|
446 |
+
)
|
447 |
+
# K3._adj is synced with K3._succ
|
448 |
+
self.K3._pred = {0: {}, 1: {}, 2: {}}
|
449 |
+
for u in self.k3nodes:
|
450 |
+
for v in self.k3nodes:
|
451 |
+
if u == v:
|
452 |
+
continue
|
453 |
+
d = {0: {}}
|
454 |
+
self.K3._succ[u][v] = d
|
455 |
+
self.K3._pred[v][u] = d
|
456 |
+
self.K3._node = self.K3.node_dict_factory()
|
457 |
+
self.K3._node[0] = self.K3.node_attr_dict_factory()
|
458 |
+
self.K3._node[1] = self.K3.node_attr_dict_factory()
|
459 |
+
self.K3._node[2] = self.K3.node_attr_dict_factory()
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_special.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
|
3 |
+
from .test_digraph import BaseDiGraphTester
|
4 |
+
from .test_digraph import TestDiGraph as _TestDiGraph
|
5 |
+
from .test_graph import BaseGraphTester
|
6 |
+
from .test_graph import TestGraph as _TestGraph
|
7 |
+
from .test_multidigraph import TestMultiDiGraph as _TestMultiDiGraph
|
8 |
+
from .test_multigraph import TestMultiGraph as _TestMultiGraph
|
9 |
+
|
10 |
+
|
11 |
+
def test_factories():
|
12 |
+
class mydict1(dict):
|
13 |
+
pass
|
14 |
+
|
15 |
+
class mydict2(dict):
|
16 |
+
pass
|
17 |
+
|
18 |
+
class mydict3(dict):
|
19 |
+
pass
|
20 |
+
|
21 |
+
class mydict4(dict):
|
22 |
+
pass
|
23 |
+
|
24 |
+
class mydict5(dict):
|
25 |
+
pass
|
26 |
+
|
27 |
+
for Graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):
|
28 |
+
# print("testing class: ", Graph.__name__)
|
29 |
+
class MyGraph(Graph):
|
30 |
+
node_dict_factory = mydict1
|
31 |
+
adjlist_outer_dict_factory = mydict2
|
32 |
+
adjlist_inner_dict_factory = mydict3
|
33 |
+
edge_key_dict_factory = mydict4
|
34 |
+
edge_attr_dict_factory = mydict5
|
35 |
+
|
36 |
+
G = MyGraph()
|
37 |
+
assert isinstance(G._node, mydict1)
|
38 |
+
assert isinstance(G._adj, mydict2)
|
39 |
+
G.add_node(1)
|
40 |
+
assert isinstance(G._adj[1], mydict3)
|
41 |
+
if G.is_directed():
|
42 |
+
assert isinstance(G._pred, mydict2)
|
43 |
+
assert isinstance(G._succ, mydict2)
|
44 |
+
assert isinstance(G._pred[1], mydict3)
|
45 |
+
G.add_edge(1, 2)
|
46 |
+
if G.is_multigraph():
|
47 |
+
assert isinstance(G._adj[1][2], mydict4)
|
48 |
+
assert isinstance(G._adj[1][2][0], mydict5)
|
49 |
+
else:
|
50 |
+
assert isinstance(G._adj[1][2], mydict5)
|
51 |
+
|
52 |
+
|
53 |
+
class TestSpecialGraph(_TestGraph):
|
54 |
+
def setup_method(self):
|
55 |
+
_TestGraph.setup_method(self)
|
56 |
+
self.Graph = nx.Graph
|
57 |
+
|
58 |
+
|
59 |
+
class TestThinGraph(BaseGraphTester):
|
60 |
+
def setup_method(self):
|
61 |
+
all_edge_dict = {"weight": 1}
|
62 |
+
|
63 |
+
class MyGraph(nx.Graph):
|
64 |
+
def edge_attr_dict_factory(self):
|
65 |
+
return all_edge_dict
|
66 |
+
|
67 |
+
self.Graph = MyGraph
|
68 |
+
# build dict-of-dict-of-dict K3
|
69 |
+
ed1, ed2, ed3 = (all_edge_dict, all_edge_dict, all_edge_dict)
|
70 |
+
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
|
71 |
+
self.k3edges = [(0, 1), (0, 2), (1, 2)]
|
72 |
+
self.k3nodes = [0, 1, 2]
|
73 |
+
self.K3 = self.Graph()
|
74 |
+
self.K3._adj = self.k3adj
|
75 |
+
self.K3._node = {}
|
76 |
+
self.K3._node[0] = {}
|
77 |
+
self.K3._node[1] = {}
|
78 |
+
self.K3._node[2] = {}
|
79 |
+
|
80 |
+
|
81 |
+
class TestSpecialDiGraph(_TestDiGraph):
|
82 |
+
def setup_method(self):
|
83 |
+
_TestDiGraph.setup_method(self)
|
84 |
+
self.Graph = nx.DiGraph
|
85 |
+
|
86 |
+
|
87 |
+
class TestThinDiGraph(BaseDiGraphTester):
|
88 |
+
def setup_method(self):
|
89 |
+
all_edge_dict = {"weight": 1}
|
90 |
+
|
91 |
+
class MyGraph(nx.DiGraph):
|
92 |
+
def edge_attr_dict_factory(self):
|
93 |
+
return all_edge_dict
|
94 |
+
|
95 |
+
self.Graph = MyGraph
|
96 |
+
# build dict-of-dict-of-dict K3
|
97 |
+
ed1, ed2, ed3 = (all_edge_dict, all_edge_dict, all_edge_dict)
|
98 |
+
ed4, ed5, ed6 = (all_edge_dict, all_edge_dict, all_edge_dict)
|
99 |
+
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
|
100 |
+
self.k3edges = [(0, 1), (0, 2), (1, 2)]
|
101 |
+
self.k3nodes = [0, 1, 2]
|
102 |
+
self.K3 = self.Graph()
|
103 |
+
self.K3._succ = self.k3adj
|
104 |
+
# K3._adj is synced with K3._succ
|
105 |
+
self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
|
106 |
+
self.K3._node = {}
|
107 |
+
self.K3._node[0] = {}
|
108 |
+
self.K3._node[1] = {}
|
109 |
+
self.K3._node[2] = {}
|
110 |
+
|
111 |
+
ed1, ed2 = (all_edge_dict, all_edge_dict)
|
112 |
+
self.P3 = self.Graph()
|
113 |
+
self.P3._succ = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
|
114 |
+
# P3._adj is synced with P3._succ
|
115 |
+
self.P3._pred = {0: {}, 1: {0: ed1}, 2: {1: ed2}}
|
116 |
+
self.P3._node = {}
|
117 |
+
self.P3._node[0] = {}
|
118 |
+
self.P3._node[1] = {}
|
119 |
+
self.P3._node[2] = {}
|
120 |
+
|
121 |
+
|
122 |
+
class TestSpecialMultiGraph(_TestMultiGraph):
|
123 |
+
def setup_method(self):
|
124 |
+
_TestMultiGraph.setup_method(self)
|
125 |
+
self.Graph = nx.MultiGraph
|
126 |
+
|
127 |
+
|
128 |
+
class TestSpecialMultiDiGraph(_TestMultiDiGraph):
|
129 |
+
def setup_method(self):
|
130 |
+
_TestMultiDiGraph.setup_method(self)
|
131 |
+
self.Graph = nx.MultiDiGraph
|
env-llmeval/lib/python3.10/site-packages/networkx/classes/tests/test_subgraphviews.py
ADDED
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.utils import edges_equal
|
5 |
+
|
6 |
+
|
7 |
+
class TestSubGraphView:
|
8 |
+
gview = staticmethod(nx.subgraph_view)
|
9 |
+
graph = nx.Graph
|
10 |
+
hide_edges_filter = staticmethod(nx.filters.hide_edges)
|
11 |
+
show_edges_filter = staticmethod(nx.filters.show_edges)
|
12 |
+
|
13 |
+
@classmethod
|
14 |
+
def setup_class(cls):
|
15 |
+
cls.G = nx.path_graph(9, create_using=cls.graph())
|
16 |
+
cls.hide_edges_w_hide_nodes = {(3, 4), (4, 5), (5, 6)}
|
17 |
+
|
18 |
+
def test_hidden_nodes(self):
|
19 |
+
hide_nodes = [4, 5, 111]
|
20 |
+
nodes_gone = nx.filters.hide_nodes(hide_nodes)
|
21 |
+
gview = self.gview
|
22 |
+
G = gview(self.G, filter_node=nodes_gone)
|
23 |
+
assert self.G.nodes - G.nodes == {4, 5}
|
24 |
+
assert self.G.edges - G.edges == self.hide_edges_w_hide_nodes
|
25 |
+
if G.is_directed():
|
26 |
+
assert list(G[3]) == []
|
27 |
+
assert list(G[2]) == [3]
|
28 |
+
else:
|
29 |
+
assert list(G[3]) == [2]
|
30 |
+
assert set(G[2]) == {1, 3}
|
31 |
+
pytest.raises(KeyError, G.__getitem__, 4)
|
32 |
+
pytest.raises(KeyError, G.__getitem__, 112)
|
33 |
+
pytest.raises(KeyError, G.__getitem__, 111)
|
34 |
+
assert G.degree(3) == (3 if G.is_multigraph() else 1)
|
35 |
+
assert G.size() == (7 if G.is_multigraph() else 5)
|
36 |
+
|
37 |
+
def test_hidden_edges(self):
|
38 |
+
hide_edges = [(2, 3), (8, 7), (222, 223)]
|
39 |
+
edges_gone = self.hide_edges_filter(hide_edges)
|
40 |
+
gview = self.gview
|
41 |
+
G = gview(self.G, filter_edge=edges_gone)
|
42 |
+
assert self.G.nodes == G.nodes
|
43 |
+
if G.is_directed():
|
44 |
+
assert self.G.edges - G.edges == {(2, 3)}
|
45 |
+
assert list(G[2]) == []
|
46 |
+
assert list(G.pred[3]) == []
|
47 |
+
assert list(G.pred[2]) == [1]
|
48 |
+
assert G.size() == 7
|
49 |
+
else:
|
50 |
+
assert self.G.edges - G.edges == {(2, 3), (7, 8)}
|
51 |
+
assert list(G[2]) == [1]
|
52 |
+
assert G.size() == 6
|
53 |
+
assert list(G[3]) == [4]
|
54 |
+
pytest.raises(KeyError, G.__getitem__, 221)
|
55 |
+
pytest.raises(KeyError, G.__getitem__, 222)
|
56 |
+
assert G.degree(3) == 1
|
57 |
+
|
58 |
+
def test_shown_node(self):
|
59 |
+
induced_subgraph = nx.filters.show_nodes([2, 3, 111])
|
60 |
+
gview = self.gview
|
61 |
+
G = gview(self.G, filter_node=induced_subgraph)
|
62 |
+
assert set(G.nodes) == {2, 3}
|
63 |
+
if G.is_directed():
|
64 |
+
assert list(G[3]) == []
|
65 |
+
else:
|
66 |
+
assert list(G[3]) == [2]
|
67 |
+
assert list(G[2]) == [3]
|
68 |
+
pytest.raises(KeyError, G.__getitem__, 4)
|
69 |
+
pytest.raises(KeyError, G.__getitem__, 112)
|
70 |
+
pytest.raises(KeyError, G.__getitem__, 111)
|
71 |
+
assert G.degree(3) == (3 if G.is_multigraph() else 1)
|
72 |
+
assert G.size() == (3 if G.is_multigraph() else 1)
|
73 |
+
|
74 |
+
def test_shown_edges(self):
|
75 |
+
show_edges = [(2, 3), (8, 7), (222, 223)]
|
76 |
+
edge_subgraph = self.show_edges_filter(show_edges)
|
77 |
+
G = self.gview(self.G, filter_edge=edge_subgraph)
|
78 |
+
assert self.G.nodes == G.nodes
|
79 |
+
if G.is_directed():
|
80 |
+
assert G.edges == {(2, 3)}
|
81 |
+
assert list(G[3]) == []
|
82 |
+
assert list(G[2]) == [3]
|
83 |
+
assert list(G.pred[3]) == [2]
|
84 |
+
assert list(G.pred[2]) == []
|
85 |
+
assert G.size() == 1
|
86 |
+
else:
|
87 |
+
assert G.edges == {(2, 3), (7, 8)}
|
88 |
+
assert list(G[3]) == [2]
|
89 |
+
assert list(G[2]) == [3]
|
90 |
+
assert G.size() == 2
|
91 |
+
pytest.raises(KeyError, G.__getitem__, 221)
|
92 |
+
pytest.raises(KeyError, G.__getitem__, 222)
|
93 |
+
assert G.degree(3) == 1
|
94 |
+
|
95 |
+
|
96 |
+
class TestSubDiGraphView(TestSubGraphView):
|
97 |
+
gview = staticmethod(nx.subgraph_view)
|
98 |
+
graph = nx.DiGraph
|
99 |
+
hide_edges_filter = staticmethod(nx.filters.hide_diedges)
|
100 |
+
show_edges_filter = staticmethod(nx.filters.show_diedges)
|
101 |
+
hide_edges = [(2, 3), (8, 7), (222, 223)]
|
102 |
+
excluded = {(2, 3), (3, 4), (4, 5), (5, 6)}
|
103 |
+
|
104 |
+
def test_inoutedges(self):
|
105 |
+
edges_gone = self.hide_edges_filter(self.hide_edges)
|
106 |
+
hide_nodes = [4, 5, 111]
|
107 |
+
nodes_gone = nx.filters.hide_nodes(hide_nodes)
|
108 |
+
G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
|
109 |
+
|
110 |
+
assert self.G.in_edges - G.in_edges == self.excluded
|
111 |
+
assert self.G.out_edges - G.out_edges == self.excluded
|
112 |
+
|
113 |
+
def test_pred(self):
|
114 |
+
edges_gone = self.hide_edges_filter(self.hide_edges)
|
115 |
+
hide_nodes = [4, 5, 111]
|
116 |
+
nodes_gone = nx.filters.hide_nodes(hide_nodes)
|
117 |
+
G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
|
118 |
+
|
119 |
+
assert list(G.pred[2]) == [1]
|
120 |
+
assert list(G.pred[6]) == []
|
121 |
+
|
122 |
+
def test_inout_degree(self):
|
123 |
+
edges_gone = self.hide_edges_filter(self.hide_edges)
|
124 |
+
hide_nodes = [4, 5, 111]
|
125 |
+
nodes_gone = nx.filters.hide_nodes(hide_nodes)
|
126 |
+
G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
|
127 |
+
|
128 |
+
assert G.degree(2) == 1
|
129 |
+
assert G.out_degree(2) == 0
|
130 |
+
assert G.in_degree(2) == 1
|
131 |
+
assert G.size() == 4
|
132 |
+
|
133 |
+
|
134 |
+
# multigraph
|
135 |
+
class TestMultiGraphView(TestSubGraphView):
|
136 |
+
gview = staticmethod(nx.subgraph_view)
|
137 |
+
graph = nx.MultiGraph
|
138 |
+
hide_edges_filter = staticmethod(nx.filters.hide_multiedges)
|
139 |
+
show_edges_filter = staticmethod(nx.filters.show_multiedges)
|
140 |
+
|
141 |
+
@classmethod
|
142 |
+
def setup_class(cls):
|
143 |
+
cls.G = nx.path_graph(9, create_using=cls.graph())
|
144 |
+
multiedges = {(2, 3, 4), (2, 3, 5)}
|
145 |
+
cls.G.add_edges_from(multiedges)
|
146 |
+
cls.hide_edges_w_hide_nodes = {(3, 4, 0), (4, 5, 0), (5, 6, 0)}
|
147 |
+
|
148 |
+
def test_hidden_edges(self):
|
149 |
+
hide_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
|
150 |
+
edges_gone = self.hide_edges_filter(hide_edges)
|
151 |
+
G = self.gview(self.G, filter_edge=edges_gone)
|
152 |
+
assert self.G.nodes == G.nodes
|
153 |
+
if G.is_directed():
|
154 |
+
assert self.G.edges - G.edges == {(2, 3, 4)}
|
155 |
+
assert list(G[3]) == [4]
|
156 |
+
assert list(G[2]) == [3]
|
157 |
+
assert list(G.pred[3]) == [2] # only one 2 but two edges
|
158 |
+
assert list(G.pred[2]) == [1]
|
159 |
+
assert G.size() == 9
|
160 |
+
else:
|
161 |
+
assert self.G.edges - G.edges == {(2, 3, 4), (7, 8, 0)}
|
162 |
+
assert list(G[3]) == [2, 4]
|
163 |
+
assert list(G[2]) == [1, 3]
|
164 |
+
assert G.size() == 8
|
165 |
+
assert G.degree(3) == 3
|
166 |
+
pytest.raises(KeyError, G.__getitem__, 221)
|
167 |
+
pytest.raises(KeyError, G.__getitem__, 222)
|
168 |
+
|
169 |
+
def test_shown_edges(self):
|
170 |
+
show_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
|
171 |
+
edge_subgraph = self.show_edges_filter(show_edges)
|
172 |
+
G = self.gview(self.G, filter_edge=edge_subgraph)
|
173 |
+
assert self.G.nodes == G.nodes
|
174 |
+
if G.is_directed():
|
175 |
+
assert G.edges == {(2, 3, 4)}
|
176 |
+
assert list(G[3]) == []
|
177 |
+
assert list(G.pred[3]) == [2]
|
178 |
+
assert list(G.pred[2]) == []
|
179 |
+
assert G.size() == 1
|
180 |
+
else:
|
181 |
+
assert G.edges == {(2, 3, 4), (7, 8, 0)}
|
182 |
+
assert G.size() == 2
|
183 |
+
assert list(G[3]) == [2]
|
184 |
+
assert G.degree(3) == 1
|
185 |
+
assert list(G[2]) == [3]
|
186 |
+
pytest.raises(KeyError, G.__getitem__, 221)
|
187 |
+
pytest.raises(KeyError, G.__getitem__, 222)
|
188 |
+
|
189 |
+
|
190 |
+
# multidigraph
|
191 |
+
class TestMultiDiGraphView(TestMultiGraphView, TestSubDiGraphView):
|
192 |
+
gview = staticmethod(nx.subgraph_view)
|
193 |
+
graph = nx.MultiDiGraph
|
194 |
+
hide_edges_filter = staticmethod(nx.filters.hide_multidiedges)
|
195 |
+
show_edges_filter = staticmethod(nx.filters.show_multidiedges)
|
196 |
+
hide_edges = [(2, 3, 0), (8, 7, 0), (222, 223, 0)]
|
197 |
+
excluded = {(2, 3, 0), (3, 4, 0), (4, 5, 0), (5, 6, 0)}
|
198 |
+
|
199 |
+
def test_inout_degree(self):
|
200 |
+
edges_gone = self.hide_edges_filter(self.hide_edges)
|
201 |
+
hide_nodes = [4, 5, 111]
|
202 |
+
nodes_gone = nx.filters.hide_nodes(hide_nodes)
|
203 |
+
G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
|
204 |
+
|
205 |
+
assert G.degree(2) == 3
|
206 |
+
assert G.out_degree(2) == 2
|
207 |
+
assert G.in_degree(2) == 1
|
208 |
+
assert G.size() == 6
|
209 |
+
|
210 |
+
|
211 |
+
# induced_subgraph
|
212 |
+
class TestInducedSubGraph:
|
213 |
+
@classmethod
|
214 |
+
def setup_class(cls):
|
215 |
+
cls.K3 = G = nx.complete_graph(3)
|
216 |
+
G.graph["foo"] = []
|
217 |
+
G.nodes[0]["foo"] = []
|
218 |
+
G.remove_edge(1, 2)
|
219 |
+
ll = []
|
220 |
+
G.add_edge(1, 2, foo=ll)
|
221 |
+
G.add_edge(2, 1, foo=ll)
|
222 |
+
|
223 |
+
def test_full_graph(self):
|
224 |
+
G = self.K3
|
225 |
+
H = nx.induced_subgraph(G, [0, 1, 2, 5])
|
226 |
+
assert H.name == G.name
|
227 |
+
self.graphs_equal(H, G)
|
228 |
+
self.same_attrdict(H, G)
|
229 |
+
|
230 |
+
def test_partial_subgraph(self):
|
231 |
+
G = self.K3
|
232 |
+
H = nx.induced_subgraph(G, 0)
|
233 |
+
assert dict(H.adj) == {0: {}}
|
234 |
+
assert dict(G.adj) != {0: {}}
|
235 |
+
|
236 |
+
H = nx.induced_subgraph(G, [0, 1])
|
237 |
+
assert dict(H.adj) == {0: {1: {}}, 1: {0: {}}}
|
238 |
+
|
239 |
+
def same_attrdict(self, H, G):
|
240 |
+
old_foo = H[1][2]["foo"]
|
241 |
+
H.edges[1, 2]["foo"] = "baz"
|
242 |
+
assert G.edges == H.edges
|
243 |
+
H.edges[1, 2]["foo"] = old_foo
|
244 |
+
assert G.edges == H.edges
|
245 |
+
old_foo = H.nodes[0]["foo"]
|
246 |
+
H.nodes[0]["foo"] = "baz"
|
247 |
+
assert G.nodes == H.nodes
|
248 |
+
H.nodes[0]["foo"] = old_foo
|
249 |
+
assert G.nodes == H.nodes
|
250 |
+
|
251 |
+
def graphs_equal(self, H, G):
|
252 |
+
assert G._adj == H._adj
|
253 |
+
assert G._node == H._node
|
254 |
+
assert G.graph == H.graph
|
255 |
+
assert G.name == H.name
|
256 |
+
if not G.is_directed() and not H.is_directed():
|
257 |
+
assert H._adj[1][2] is H._adj[2][1]
|
258 |
+
assert G._adj[1][2] is G._adj[2][1]
|
259 |
+
else: # at least one is directed
|
260 |
+
if not G.is_directed():
|
261 |
+
G._pred = G._adj
|
262 |
+
G._succ = G._adj
|
263 |
+
if not H.is_directed():
|
264 |
+
H._pred = H._adj
|
265 |
+
H._succ = H._adj
|
266 |
+
assert G._pred == H._pred
|
267 |
+
assert G._succ == H._succ
|
268 |
+
assert H._succ[1][2] is H._pred[2][1]
|
269 |
+
assert G._succ[1][2] is G._pred[2][1]
|
270 |
+
|
271 |
+
|
272 |
+
# edge_subgraph
|
273 |
+
class TestEdgeSubGraph:
|
274 |
+
@classmethod
|
275 |
+
def setup_class(cls):
|
276 |
+
# Create a path graph on five nodes.
|
277 |
+
cls.G = G = nx.path_graph(5)
|
278 |
+
# Add some node, edge, and graph attributes.
|
279 |
+
for i in range(5):
|
280 |
+
G.nodes[i]["name"] = f"node{i}"
|
281 |
+
G.edges[0, 1]["name"] = "edge01"
|
282 |
+
G.edges[3, 4]["name"] = "edge34"
|
283 |
+
G.graph["name"] = "graph"
|
284 |
+
# Get the subgraph induced by the first and last edges.
|
285 |
+
cls.H = nx.edge_subgraph(G, [(0, 1), (3, 4)])
|
286 |
+
|
287 |
+
def test_correct_nodes(self):
|
288 |
+
"""Tests that the subgraph has the correct nodes."""
|
289 |
+
assert [(0, "node0"), (1, "node1"), (3, "node3"), (4, "node4")] == sorted(
|
290 |
+
self.H.nodes.data("name")
|
291 |
+
)
|
292 |
+
|
293 |
+
def test_correct_edges(self):
|
294 |
+
"""Tests that the subgraph has the correct edges."""
|
295 |
+
assert edges_equal(
|
296 |
+
[(0, 1, "edge01"), (3, 4, "edge34")], self.H.edges.data("name")
|
297 |
+
)
|
298 |
+
|
299 |
+
def test_add_node(self):
|
300 |
+
"""Tests that adding a node to the original graph does not
|
301 |
+
affect the nodes of the subgraph.
|
302 |
+
|
303 |
+
"""
|
304 |
+
self.G.add_node(5)
|
305 |
+
assert [0, 1, 3, 4] == sorted(self.H.nodes)
|
306 |
+
self.G.remove_node(5)
|
307 |
+
|
308 |
+
def test_remove_node(self):
|
309 |
+
"""Tests that removing a node in the original graph
|
310 |
+
removes the nodes of the subgraph.
|
311 |
+
|
312 |
+
"""
|
313 |
+
self.G.remove_node(0)
|
314 |
+
assert [1, 3, 4] == sorted(self.H.nodes)
|
315 |
+
self.G.add_node(0, name="node0")
|
316 |
+
self.G.add_edge(0, 1, name="edge01")
|
317 |
+
|
318 |
+
def test_node_attr_dict(self):
|
319 |
+
"""Tests that the node attribute dictionary of the two graphs is
|
320 |
+
the same object.
|
321 |
+
|
322 |
+
"""
|
323 |
+
for v in self.H:
|
324 |
+
assert self.G.nodes[v] == self.H.nodes[v]
|
325 |
+
# Making a change to G should make a change in H and vice versa.
|
326 |
+
self.G.nodes[0]["name"] = "foo"
|
327 |
+
assert self.G.nodes[0] == self.H.nodes[0]
|
328 |
+
self.H.nodes[1]["name"] = "bar"
|
329 |
+
assert self.G.nodes[1] == self.H.nodes[1]
|
330 |
+
# Revert the change, so tests pass with pytest-randomly
|
331 |
+
self.G.nodes[0]["name"] = "node0"
|
332 |
+
self.H.nodes[1]["name"] = "node1"
|
333 |
+
|
334 |
+
def test_edge_attr_dict(self):
|
335 |
+
"""Tests that the edge attribute dictionary of the two graphs is
|
336 |
+
the same object.
|
337 |
+
|
338 |
+
"""
|
339 |
+
for u, v in self.H.edges():
|
340 |
+
assert self.G.edges[u, v] == self.H.edges[u, v]
|
341 |
+
# Making a change to G should make a change in H and vice versa.
|
342 |
+
self.G.edges[0, 1]["name"] = "foo"
|
343 |
+
assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
|
344 |
+
self.H.edges[3, 4]["name"] = "bar"
|
345 |
+
assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
|
346 |
+
# Revert the change, so tests pass with pytest-randomly
|
347 |
+
self.G.edges[0, 1]["name"] = "edge01"
|
348 |
+
self.H.edges[3, 4]["name"] = "edge34"
|
349 |
+
|
350 |
+
def test_graph_attr_dict(self):
|
351 |
+
"""Tests that the graph attribute dictionary of the two graphs
|
352 |
+
is the same object.
|
353 |
+
|
354 |
+
"""
|
355 |
+
assert self.G.graph is self.H.graph
|
356 |
+
|
357 |
+
def test_readonly(self):
|
358 |
+
"""Tests that the subgraph cannot change the graph structure"""
|
359 |
+
pytest.raises(nx.NetworkXError, self.H.add_node, 5)
|
360 |
+
pytest.raises(nx.NetworkXError, self.H.remove_node, 0)
|
361 |
+
pytest.raises(nx.NetworkXError, self.H.add_edge, 5, 6)
|
362 |
+
pytest.raises(nx.NetworkXError, self.H.remove_edge, 0, 1)
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__init__.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A package for reading and writing graphs in various formats.
|
3 |
+
|
4 |
+
"""
|
5 |
+
|
6 |
+
|
7 |
+
from networkx.readwrite.adjlist import *
|
8 |
+
from networkx.readwrite.multiline_adjlist import *
|
9 |
+
from networkx.readwrite.edgelist import *
|
10 |
+
from networkx.readwrite.pajek import *
|
11 |
+
from networkx.readwrite.leda import *
|
12 |
+
from networkx.readwrite.sparse6 import *
|
13 |
+
from networkx.readwrite.graph6 import *
|
14 |
+
from networkx.readwrite.gml import *
|
15 |
+
from networkx.readwrite.graphml import *
|
16 |
+
from networkx.readwrite.gexf import *
|
17 |
+
from networkx.readwrite.json_graph import *
|
18 |
+
from networkx.readwrite.text import *
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (722 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/adjlist.cpython-310.pyc
ADDED
Binary file (8.34 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/edgelist.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gexf.cpython-310.pyc
ADDED
Binary file (25.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/gml.cpython-310.pyc
ADDED
Binary file (24.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graph6.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/graphml.cpython-310.pyc
ADDED
Binary file (28.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/leda.cpython-310.pyc
ADDED
Binary file (2.89 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/multiline_adjlist.cpython-310.pyc
ADDED
Binary file (9.53 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/p2g.cpython-310.pyc
ADDED
Binary file (3.08 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/pajek.cpython-310.pyc
ADDED
Binary file (6.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/sparse6.cpython-310.pyc
ADDED
Binary file (9.78 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/__pycache__/text.cpython-310.pyc
ADDED
Binary file (23 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/gexf.py
ADDED
@@ -0,0 +1,1065 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Read and write graphs in GEXF format.
|
2 |
+
|
3 |
+
.. warning::
|
4 |
+
This parser uses the standard xml library present in Python, which is
|
5 |
+
insecure - see :external+python:mod:`xml` for additional information.
|
6 |
+
Only parse GEFX files you trust.
|
7 |
+
|
8 |
+
GEXF (Graph Exchange XML Format) is a language for describing complex
|
9 |
+
network structures, their associated data and dynamics.
|
10 |
+
|
11 |
+
This implementation does not support mixed graphs (directed and
|
12 |
+
undirected edges together).
|
13 |
+
|
14 |
+
Format
|
15 |
+
------
|
16 |
+
GEXF is an XML format. See http://gexf.net/schema.html for the
|
17 |
+
specification and http://gexf.net/basic.html for examples.
|
18 |
+
"""
|
19 |
+
import itertools
|
20 |
+
import time
|
21 |
+
from xml.etree.ElementTree import (
|
22 |
+
Element,
|
23 |
+
ElementTree,
|
24 |
+
SubElement,
|
25 |
+
register_namespace,
|
26 |
+
tostring,
|
27 |
+
)
|
28 |
+
|
29 |
+
import networkx as nx
|
30 |
+
from networkx.utils import open_file
|
31 |
+
|
32 |
+
__all__ = ["write_gexf", "read_gexf", "relabel_gexf_graph", "generate_gexf"]
|
33 |
+
|
34 |
+
|
35 |
+
@open_file(1, mode="wb")
|
36 |
+
def write_gexf(G, path, encoding="utf-8", prettyprint=True, version="1.2draft"):
|
37 |
+
"""Write G in GEXF format to path.
|
38 |
+
|
39 |
+
"GEXF (Graph Exchange XML Format) is a language for describing
|
40 |
+
complex networks structures, their associated data and dynamics" [1]_.
|
41 |
+
|
42 |
+
Node attributes are checked according to the version of the GEXF
|
43 |
+
schemas used for parameters which are not user defined,
|
44 |
+
e.g. visualization 'viz' [2]_. See example for usage.
|
45 |
+
|
46 |
+
Parameters
|
47 |
+
----------
|
48 |
+
G : graph
|
49 |
+
A NetworkX graph
|
50 |
+
path : file or string
|
51 |
+
File or file name to write.
|
52 |
+
File names ending in .gz or .bz2 will be compressed.
|
53 |
+
encoding : string (optional, default: 'utf-8')
|
54 |
+
Encoding for text data.
|
55 |
+
prettyprint : bool (optional, default: True)
|
56 |
+
If True use line breaks and indenting in output XML.
|
57 |
+
version: string (optional, default: '1.2draft')
|
58 |
+
The version of GEXF to be used for nodes attributes checking
|
59 |
+
|
60 |
+
Examples
|
61 |
+
--------
|
62 |
+
>>> G = nx.path_graph(4)
|
63 |
+
>>> nx.write_gexf(G, "test.gexf")
|
64 |
+
|
65 |
+
# visualization data
|
66 |
+
>>> G.nodes[0]["viz"] = {"size": 54}
|
67 |
+
>>> G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1}
|
68 |
+
>>> G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256}
|
69 |
+
|
70 |
+
|
71 |
+
Notes
|
72 |
+
-----
|
73 |
+
This implementation does not support mixed graphs (directed and undirected
|
74 |
+
edges together).
|
75 |
+
|
76 |
+
The node id attribute is set to be the string of the node label.
|
77 |
+
If you want to specify an id use set it as node data, e.g.
|
78 |
+
node['a']['id']=1 to set the id of node 'a' to 1.
|
79 |
+
|
80 |
+
References
|
81 |
+
----------
|
82 |
+
.. [1] GEXF File Format, http://gexf.net/
|
83 |
+
.. [2] GEXF schema, http://gexf.net/schema.html
|
84 |
+
"""
|
85 |
+
writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version)
|
86 |
+
writer.add_graph(G)
|
87 |
+
writer.write(path)
|
88 |
+
|
89 |
+
|
90 |
+
def generate_gexf(G, encoding="utf-8", prettyprint=True, version="1.2draft"):
|
91 |
+
"""Generate lines of GEXF format representation of G.
|
92 |
+
|
93 |
+
"GEXF (Graph Exchange XML Format) is a language for describing
|
94 |
+
complex networks structures, their associated data and dynamics" [1]_.
|
95 |
+
|
96 |
+
Parameters
|
97 |
+
----------
|
98 |
+
G : graph
|
99 |
+
A NetworkX graph
|
100 |
+
encoding : string (optional, default: 'utf-8')
|
101 |
+
Encoding for text data.
|
102 |
+
prettyprint : bool (optional, default: True)
|
103 |
+
If True use line breaks and indenting in output XML.
|
104 |
+
version : string (default: 1.2draft)
|
105 |
+
Version of GEFX File Format (see http://gexf.net/schema.html)
|
106 |
+
Supported values: "1.1draft", "1.2draft"
|
107 |
+
|
108 |
+
|
109 |
+
Examples
|
110 |
+
--------
|
111 |
+
>>> G = nx.path_graph(4)
|
112 |
+
>>> linefeed = chr(10) # linefeed=\n
|
113 |
+
>>> s = linefeed.join(nx.generate_gexf(G))
|
114 |
+
>>> for line in nx.generate_gexf(G): # doctest: +SKIP
|
115 |
+
... print(line)
|
116 |
+
|
117 |
+
Notes
|
118 |
+
-----
|
119 |
+
This implementation does not support mixed graphs (directed and undirected
|
120 |
+
edges together).
|
121 |
+
|
122 |
+
The node id attribute is set to be the string of the node label.
|
123 |
+
If you want to specify an id use set it as node data, e.g.
|
124 |
+
node['a']['id']=1 to set the id of node 'a' to 1.
|
125 |
+
|
126 |
+
References
|
127 |
+
----------
|
128 |
+
.. [1] GEXF File Format, https://gephi.org/gexf/format/
|
129 |
+
"""
|
130 |
+
writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint, version=version)
|
131 |
+
writer.add_graph(G)
|
132 |
+
yield from str(writer).splitlines()
|
133 |
+
|
134 |
+
|
135 |
+
@open_file(0, mode="rb")
|
136 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
137 |
+
def read_gexf(path, node_type=None, relabel=False, version="1.2draft"):
|
138 |
+
"""Read graph in GEXF format from path.
|
139 |
+
|
140 |
+
"GEXF (Graph Exchange XML Format) is a language for describing
|
141 |
+
complex networks structures, their associated data and dynamics" [1]_.
|
142 |
+
|
143 |
+
Parameters
|
144 |
+
----------
|
145 |
+
path : file or string
|
146 |
+
File or file name to read.
|
147 |
+
File names ending in .gz or .bz2 will be decompressed.
|
148 |
+
node_type: Python type (default: None)
|
149 |
+
Convert node ids to this type if not None.
|
150 |
+
relabel : bool (default: False)
|
151 |
+
If True relabel the nodes to use the GEXF node "label" attribute
|
152 |
+
instead of the node "id" attribute as the NetworkX node label.
|
153 |
+
version : string (default: 1.2draft)
|
154 |
+
Version of GEFX File Format (see http://gexf.net/schema.html)
|
155 |
+
Supported values: "1.1draft", "1.2draft"
|
156 |
+
|
157 |
+
Returns
|
158 |
+
-------
|
159 |
+
graph: NetworkX graph
|
160 |
+
If no parallel edges are found a Graph or DiGraph is returned.
|
161 |
+
Otherwise a MultiGraph or MultiDiGraph is returned.
|
162 |
+
|
163 |
+
Notes
|
164 |
+
-----
|
165 |
+
This implementation does not support mixed graphs (directed and undirected
|
166 |
+
edges together).
|
167 |
+
|
168 |
+
References
|
169 |
+
----------
|
170 |
+
.. [1] GEXF File Format, http://gexf.net/
|
171 |
+
"""
|
172 |
+
reader = GEXFReader(node_type=node_type, version=version)
|
173 |
+
if relabel:
|
174 |
+
G = relabel_gexf_graph(reader(path))
|
175 |
+
else:
|
176 |
+
G = reader(path)
|
177 |
+
return G
|
178 |
+
|
179 |
+
|
180 |
+
class GEXF:
|
181 |
+
versions = {
|
182 |
+
"1.1draft": {
|
183 |
+
"NS_GEXF": "http://www.gexf.net/1.1draft",
|
184 |
+
"NS_VIZ": "http://www.gexf.net/1.1draft/viz",
|
185 |
+
"NS_XSI": "http://www.w3.org/2001/XMLSchema-instance",
|
186 |
+
"SCHEMALOCATION": " ".join(
|
187 |
+
[
|
188 |
+
"http://www.gexf.net/1.1draft",
|
189 |
+
"http://www.gexf.net/1.1draft/gexf.xsd",
|
190 |
+
]
|
191 |
+
),
|
192 |
+
"VERSION": "1.1",
|
193 |
+
},
|
194 |
+
"1.2draft": {
|
195 |
+
"NS_GEXF": "http://www.gexf.net/1.2draft",
|
196 |
+
"NS_VIZ": "http://www.gexf.net/1.2draft/viz",
|
197 |
+
"NS_XSI": "http://www.w3.org/2001/XMLSchema-instance",
|
198 |
+
"SCHEMALOCATION": " ".join(
|
199 |
+
[
|
200 |
+
"http://www.gexf.net/1.2draft",
|
201 |
+
"http://www.gexf.net/1.2draft/gexf.xsd",
|
202 |
+
]
|
203 |
+
),
|
204 |
+
"VERSION": "1.2",
|
205 |
+
},
|
206 |
+
}
|
207 |
+
|
208 |
+
def construct_types(self):
|
209 |
+
types = [
|
210 |
+
(int, "integer"),
|
211 |
+
(float, "float"),
|
212 |
+
(float, "double"),
|
213 |
+
(bool, "boolean"),
|
214 |
+
(list, "string"),
|
215 |
+
(dict, "string"),
|
216 |
+
(int, "long"),
|
217 |
+
(str, "liststring"),
|
218 |
+
(str, "anyURI"),
|
219 |
+
(str, "string"),
|
220 |
+
]
|
221 |
+
|
222 |
+
# These additions to types allow writing numpy types
|
223 |
+
try:
|
224 |
+
import numpy as np
|
225 |
+
except ImportError:
|
226 |
+
pass
|
227 |
+
else:
|
228 |
+
# prepend so that python types are created upon read (last entry wins)
|
229 |
+
types = [
|
230 |
+
(np.float64, "float"),
|
231 |
+
(np.float32, "float"),
|
232 |
+
(np.float16, "float"),
|
233 |
+
(np.int_, "int"),
|
234 |
+
(np.int8, "int"),
|
235 |
+
(np.int16, "int"),
|
236 |
+
(np.int32, "int"),
|
237 |
+
(np.int64, "int"),
|
238 |
+
(np.uint8, "int"),
|
239 |
+
(np.uint16, "int"),
|
240 |
+
(np.uint32, "int"),
|
241 |
+
(np.uint64, "int"),
|
242 |
+
(np.int_, "int"),
|
243 |
+
(np.intc, "int"),
|
244 |
+
(np.intp, "int"),
|
245 |
+
] + types
|
246 |
+
|
247 |
+
self.xml_type = dict(types)
|
248 |
+
self.python_type = dict(reversed(a) for a in types)
|
249 |
+
|
250 |
+
# http://www.w3.org/TR/xmlschema-2/#boolean
|
251 |
+
convert_bool = {
|
252 |
+
"true": True,
|
253 |
+
"false": False,
|
254 |
+
"True": True,
|
255 |
+
"False": False,
|
256 |
+
"0": False,
|
257 |
+
0: False,
|
258 |
+
"1": True,
|
259 |
+
1: True,
|
260 |
+
}
|
261 |
+
|
262 |
+
def set_version(self, version):
|
263 |
+
d = self.versions.get(version)
|
264 |
+
if d is None:
|
265 |
+
raise nx.NetworkXError(f"Unknown GEXF version {version}.")
|
266 |
+
self.NS_GEXF = d["NS_GEXF"]
|
267 |
+
self.NS_VIZ = d["NS_VIZ"]
|
268 |
+
self.NS_XSI = d["NS_XSI"]
|
269 |
+
self.SCHEMALOCATION = d["SCHEMALOCATION"]
|
270 |
+
self.VERSION = d["VERSION"]
|
271 |
+
self.version = version
|
272 |
+
|
273 |
+
|
274 |
+
class GEXFWriter(GEXF):
|
275 |
+
# class for writing GEXF format files
|
276 |
+
# use write_gexf() function
|
277 |
+
def __init__(
|
278 |
+
self, graph=None, encoding="utf-8", prettyprint=True, version="1.2draft"
|
279 |
+
):
|
280 |
+
self.construct_types()
|
281 |
+
self.prettyprint = prettyprint
|
282 |
+
self.encoding = encoding
|
283 |
+
self.set_version(version)
|
284 |
+
self.xml = Element(
|
285 |
+
"gexf",
|
286 |
+
{
|
287 |
+
"xmlns": self.NS_GEXF,
|
288 |
+
"xmlns:xsi": self.NS_XSI,
|
289 |
+
"xsi:schemaLocation": self.SCHEMALOCATION,
|
290 |
+
"version": self.VERSION,
|
291 |
+
},
|
292 |
+
)
|
293 |
+
|
294 |
+
# Make meta element a non-graph element
|
295 |
+
# Also add lastmodifieddate as attribute, not tag
|
296 |
+
meta_element = Element("meta")
|
297 |
+
subelement_text = f"NetworkX {nx.__version__}"
|
298 |
+
SubElement(meta_element, "creator").text = subelement_text
|
299 |
+
meta_element.set("lastmodifieddate", time.strftime("%Y-%m-%d"))
|
300 |
+
self.xml.append(meta_element)
|
301 |
+
|
302 |
+
register_namespace("viz", self.NS_VIZ)
|
303 |
+
|
304 |
+
# counters for edge and attribute identifiers
|
305 |
+
self.edge_id = itertools.count()
|
306 |
+
self.attr_id = itertools.count()
|
307 |
+
self.all_edge_ids = set()
|
308 |
+
# default attributes are stored in dictionaries
|
309 |
+
self.attr = {}
|
310 |
+
self.attr["node"] = {}
|
311 |
+
self.attr["edge"] = {}
|
312 |
+
self.attr["node"]["dynamic"] = {}
|
313 |
+
self.attr["node"]["static"] = {}
|
314 |
+
self.attr["edge"]["dynamic"] = {}
|
315 |
+
self.attr["edge"]["static"] = {}
|
316 |
+
|
317 |
+
if graph is not None:
|
318 |
+
self.add_graph(graph)
|
319 |
+
|
320 |
+
def __str__(self):
|
321 |
+
if self.prettyprint:
|
322 |
+
self.indent(self.xml)
|
323 |
+
s = tostring(self.xml).decode(self.encoding)
|
324 |
+
return s
|
325 |
+
|
326 |
+
def add_graph(self, G):
|
327 |
+
# first pass through G collecting edge ids
|
328 |
+
for u, v, dd in G.edges(data=True):
|
329 |
+
eid = dd.get("id")
|
330 |
+
if eid is not None:
|
331 |
+
self.all_edge_ids.add(str(eid))
|
332 |
+
# set graph attributes
|
333 |
+
if G.graph.get("mode") == "dynamic":
|
334 |
+
mode = "dynamic"
|
335 |
+
else:
|
336 |
+
mode = "static"
|
337 |
+
# Add a graph element to the XML
|
338 |
+
if G.is_directed():
|
339 |
+
default = "directed"
|
340 |
+
else:
|
341 |
+
default = "undirected"
|
342 |
+
name = G.graph.get("name", "")
|
343 |
+
graph_element = Element("graph", defaultedgetype=default, mode=mode, name=name)
|
344 |
+
self.graph_element = graph_element
|
345 |
+
self.add_nodes(G, graph_element)
|
346 |
+
self.add_edges(G, graph_element)
|
347 |
+
self.xml.append(graph_element)
|
348 |
+
|
349 |
+
def add_nodes(self, G, graph_element):
|
350 |
+
nodes_element = Element("nodes")
|
351 |
+
for node, data in G.nodes(data=True):
|
352 |
+
node_data = data.copy()
|
353 |
+
node_id = str(node_data.pop("id", node))
|
354 |
+
kw = {"id": node_id}
|
355 |
+
label = str(node_data.pop("label", node))
|
356 |
+
kw["label"] = label
|
357 |
+
try:
|
358 |
+
pid = node_data.pop("pid")
|
359 |
+
kw["pid"] = str(pid)
|
360 |
+
except KeyError:
|
361 |
+
pass
|
362 |
+
try:
|
363 |
+
start = node_data.pop("start")
|
364 |
+
kw["start"] = str(start)
|
365 |
+
self.alter_graph_mode_timeformat(start)
|
366 |
+
except KeyError:
|
367 |
+
pass
|
368 |
+
try:
|
369 |
+
end = node_data.pop("end")
|
370 |
+
kw["end"] = str(end)
|
371 |
+
self.alter_graph_mode_timeformat(end)
|
372 |
+
except KeyError:
|
373 |
+
pass
|
374 |
+
# add node element with attributes
|
375 |
+
node_element = Element("node", **kw)
|
376 |
+
# add node element and attr subelements
|
377 |
+
default = G.graph.get("node_default", {})
|
378 |
+
node_data = self.add_parents(node_element, node_data)
|
379 |
+
if self.VERSION == "1.1":
|
380 |
+
node_data = self.add_slices(node_element, node_data)
|
381 |
+
else:
|
382 |
+
node_data = self.add_spells(node_element, node_data)
|
383 |
+
node_data = self.add_viz(node_element, node_data)
|
384 |
+
node_data = self.add_attributes("node", node_element, node_data, default)
|
385 |
+
nodes_element.append(node_element)
|
386 |
+
graph_element.append(nodes_element)
|
387 |
+
|
388 |
+
def add_edges(self, G, graph_element):
|
389 |
+
def edge_key_data(G):
|
390 |
+
# helper function to unify multigraph and graph edge iterator
|
391 |
+
if G.is_multigraph():
|
392 |
+
for u, v, key, data in G.edges(data=True, keys=True):
|
393 |
+
edge_data = data.copy()
|
394 |
+
edge_data.update(key=key)
|
395 |
+
edge_id = edge_data.pop("id", None)
|
396 |
+
if edge_id is None:
|
397 |
+
edge_id = next(self.edge_id)
|
398 |
+
while str(edge_id) in self.all_edge_ids:
|
399 |
+
edge_id = next(self.edge_id)
|
400 |
+
self.all_edge_ids.add(str(edge_id))
|
401 |
+
yield u, v, edge_id, edge_data
|
402 |
+
else:
|
403 |
+
for u, v, data in G.edges(data=True):
|
404 |
+
edge_data = data.copy()
|
405 |
+
edge_id = edge_data.pop("id", None)
|
406 |
+
if edge_id is None:
|
407 |
+
edge_id = next(self.edge_id)
|
408 |
+
while str(edge_id) in self.all_edge_ids:
|
409 |
+
edge_id = next(self.edge_id)
|
410 |
+
self.all_edge_ids.add(str(edge_id))
|
411 |
+
yield u, v, edge_id, edge_data
|
412 |
+
|
413 |
+
edges_element = Element("edges")
|
414 |
+
for u, v, key, edge_data in edge_key_data(G):
|
415 |
+
kw = {"id": str(key)}
|
416 |
+
try:
|
417 |
+
edge_label = edge_data.pop("label")
|
418 |
+
kw["label"] = str(edge_label)
|
419 |
+
except KeyError:
|
420 |
+
pass
|
421 |
+
try:
|
422 |
+
edge_weight = edge_data.pop("weight")
|
423 |
+
kw["weight"] = str(edge_weight)
|
424 |
+
except KeyError:
|
425 |
+
pass
|
426 |
+
try:
|
427 |
+
edge_type = edge_data.pop("type")
|
428 |
+
kw["type"] = str(edge_type)
|
429 |
+
except KeyError:
|
430 |
+
pass
|
431 |
+
try:
|
432 |
+
start = edge_data.pop("start")
|
433 |
+
kw["start"] = str(start)
|
434 |
+
self.alter_graph_mode_timeformat(start)
|
435 |
+
except KeyError:
|
436 |
+
pass
|
437 |
+
try:
|
438 |
+
end = edge_data.pop("end")
|
439 |
+
kw["end"] = str(end)
|
440 |
+
self.alter_graph_mode_timeformat(end)
|
441 |
+
except KeyError:
|
442 |
+
pass
|
443 |
+
source_id = str(G.nodes[u].get("id", u))
|
444 |
+
target_id = str(G.nodes[v].get("id", v))
|
445 |
+
edge_element = Element("edge", source=source_id, target=target_id, **kw)
|
446 |
+
default = G.graph.get("edge_default", {})
|
447 |
+
if self.VERSION == "1.1":
|
448 |
+
edge_data = self.add_slices(edge_element, edge_data)
|
449 |
+
else:
|
450 |
+
edge_data = self.add_spells(edge_element, edge_data)
|
451 |
+
edge_data = self.add_viz(edge_element, edge_data)
|
452 |
+
edge_data = self.add_attributes("edge", edge_element, edge_data, default)
|
453 |
+
edges_element.append(edge_element)
|
454 |
+
graph_element.append(edges_element)
|
455 |
+
|
456 |
+
def add_attributes(self, node_or_edge, xml_obj, data, default):
|
457 |
+
# Add attrvalues to node or edge
|
458 |
+
attvalues = Element("attvalues")
|
459 |
+
if len(data) == 0:
|
460 |
+
return data
|
461 |
+
mode = "static"
|
462 |
+
for k, v in data.items():
|
463 |
+
# rename generic multigraph key to avoid any name conflict
|
464 |
+
if k == "key":
|
465 |
+
k = "networkx_key"
|
466 |
+
val_type = type(v)
|
467 |
+
if val_type not in self.xml_type:
|
468 |
+
raise TypeError(f"attribute value type is not allowed: {val_type}")
|
469 |
+
if isinstance(v, list):
|
470 |
+
# dynamic data
|
471 |
+
for val, start, end in v:
|
472 |
+
val_type = type(val)
|
473 |
+
if start is not None or end is not None:
|
474 |
+
mode = "dynamic"
|
475 |
+
self.alter_graph_mode_timeformat(start)
|
476 |
+
self.alter_graph_mode_timeformat(end)
|
477 |
+
break
|
478 |
+
attr_id = self.get_attr_id(
|
479 |
+
str(k), self.xml_type[val_type], node_or_edge, default, mode
|
480 |
+
)
|
481 |
+
for val, start, end in v:
|
482 |
+
e = Element("attvalue")
|
483 |
+
e.attrib["for"] = attr_id
|
484 |
+
e.attrib["value"] = str(val)
|
485 |
+
# Handle nan, inf, -inf differently
|
486 |
+
if val_type == float:
|
487 |
+
if e.attrib["value"] == "inf":
|
488 |
+
e.attrib["value"] = "INF"
|
489 |
+
elif e.attrib["value"] == "nan":
|
490 |
+
e.attrib["value"] = "NaN"
|
491 |
+
elif e.attrib["value"] == "-inf":
|
492 |
+
e.attrib["value"] = "-INF"
|
493 |
+
if start is not None:
|
494 |
+
e.attrib["start"] = str(start)
|
495 |
+
if end is not None:
|
496 |
+
e.attrib["end"] = str(end)
|
497 |
+
attvalues.append(e)
|
498 |
+
else:
|
499 |
+
# static data
|
500 |
+
mode = "static"
|
501 |
+
attr_id = self.get_attr_id(
|
502 |
+
str(k), self.xml_type[val_type], node_or_edge, default, mode
|
503 |
+
)
|
504 |
+
e = Element("attvalue")
|
505 |
+
e.attrib["for"] = attr_id
|
506 |
+
if isinstance(v, bool):
|
507 |
+
e.attrib["value"] = str(v).lower()
|
508 |
+
else:
|
509 |
+
e.attrib["value"] = str(v)
|
510 |
+
# Handle float nan, inf, -inf differently
|
511 |
+
if val_type == float:
|
512 |
+
if e.attrib["value"] == "inf":
|
513 |
+
e.attrib["value"] = "INF"
|
514 |
+
elif e.attrib["value"] == "nan":
|
515 |
+
e.attrib["value"] = "NaN"
|
516 |
+
elif e.attrib["value"] == "-inf":
|
517 |
+
e.attrib["value"] = "-INF"
|
518 |
+
attvalues.append(e)
|
519 |
+
xml_obj.append(attvalues)
|
520 |
+
return data
|
521 |
+
|
522 |
+
def get_attr_id(self, title, attr_type, edge_or_node, default, mode):
|
523 |
+
# find the id of the attribute or generate a new id
|
524 |
+
try:
|
525 |
+
return self.attr[edge_or_node][mode][title]
|
526 |
+
except KeyError:
|
527 |
+
# generate new id
|
528 |
+
new_id = str(next(self.attr_id))
|
529 |
+
self.attr[edge_or_node][mode][title] = new_id
|
530 |
+
attr_kwargs = {"id": new_id, "title": title, "type": attr_type}
|
531 |
+
attribute = Element("attribute", **attr_kwargs)
|
532 |
+
# add subelement for data default value if present
|
533 |
+
default_title = default.get(title)
|
534 |
+
if default_title is not None:
|
535 |
+
default_element = Element("default")
|
536 |
+
default_element.text = str(default_title)
|
537 |
+
attribute.append(default_element)
|
538 |
+
# new insert it into the XML
|
539 |
+
attributes_element = None
|
540 |
+
for a in self.graph_element.findall("attributes"):
|
541 |
+
# find existing attributes element by class and mode
|
542 |
+
a_class = a.get("class")
|
543 |
+
a_mode = a.get("mode", "static")
|
544 |
+
if a_class == edge_or_node and a_mode == mode:
|
545 |
+
attributes_element = a
|
546 |
+
if attributes_element is None:
|
547 |
+
# create new attributes element
|
548 |
+
attr_kwargs = {"mode": mode, "class": edge_or_node}
|
549 |
+
attributes_element = Element("attributes", **attr_kwargs)
|
550 |
+
self.graph_element.insert(0, attributes_element)
|
551 |
+
attributes_element.append(attribute)
|
552 |
+
return new_id
|
553 |
+
|
554 |
+
def add_viz(self, element, node_data):
|
555 |
+
viz = node_data.pop("viz", False)
|
556 |
+
if viz:
|
557 |
+
color = viz.get("color")
|
558 |
+
if color is not None:
|
559 |
+
if self.VERSION == "1.1":
|
560 |
+
e = Element(
|
561 |
+
f"{{{self.NS_VIZ}}}color",
|
562 |
+
r=str(color.get("r")),
|
563 |
+
g=str(color.get("g")),
|
564 |
+
b=str(color.get("b")),
|
565 |
+
)
|
566 |
+
else:
|
567 |
+
e = Element(
|
568 |
+
f"{{{self.NS_VIZ}}}color",
|
569 |
+
r=str(color.get("r")),
|
570 |
+
g=str(color.get("g")),
|
571 |
+
b=str(color.get("b")),
|
572 |
+
a=str(color.get("a", 1.0)),
|
573 |
+
)
|
574 |
+
element.append(e)
|
575 |
+
|
576 |
+
size = viz.get("size")
|
577 |
+
if size is not None:
|
578 |
+
e = Element(f"{{{self.NS_VIZ}}}size", value=str(size))
|
579 |
+
element.append(e)
|
580 |
+
|
581 |
+
thickness = viz.get("thickness")
|
582 |
+
if thickness is not None:
|
583 |
+
e = Element(f"{{{self.NS_VIZ}}}thickness", value=str(thickness))
|
584 |
+
element.append(e)
|
585 |
+
|
586 |
+
shape = viz.get("shape")
|
587 |
+
if shape is not None:
|
588 |
+
if shape.startswith("http"):
|
589 |
+
e = Element(
|
590 |
+
f"{{{self.NS_VIZ}}}shape", value="image", uri=str(shape)
|
591 |
+
)
|
592 |
+
else:
|
593 |
+
e = Element(f"{{{self.NS_VIZ}}}shape", value=str(shape))
|
594 |
+
element.append(e)
|
595 |
+
|
596 |
+
position = viz.get("position")
|
597 |
+
if position is not None:
|
598 |
+
e = Element(
|
599 |
+
f"{{{self.NS_VIZ}}}position",
|
600 |
+
x=str(position.get("x")),
|
601 |
+
y=str(position.get("y")),
|
602 |
+
z=str(position.get("z")),
|
603 |
+
)
|
604 |
+
element.append(e)
|
605 |
+
return node_data
|
606 |
+
|
607 |
+
def add_parents(self, node_element, node_data):
|
608 |
+
parents = node_data.pop("parents", False)
|
609 |
+
if parents:
|
610 |
+
parents_element = Element("parents")
|
611 |
+
for p in parents:
|
612 |
+
e = Element("parent")
|
613 |
+
e.attrib["for"] = str(p)
|
614 |
+
parents_element.append(e)
|
615 |
+
node_element.append(parents_element)
|
616 |
+
return node_data
|
617 |
+
|
618 |
+
def add_slices(self, node_or_edge_element, node_or_edge_data):
|
619 |
+
slices = node_or_edge_data.pop("slices", False)
|
620 |
+
if slices:
|
621 |
+
slices_element = Element("slices")
|
622 |
+
for start, end in slices:
|
623 |
+
e = Element("slice", start=str(start), end=str(end))
|
624 |
+
slices_element.append(e)
|
625 |
+
node_or_edge_element.append(slices_element)
|
626 |
+
return node_or_edge_data
|
627 |
+
|
628 |
+
def add_spells(self, node_or_edge_element, node_or_edge_data):
|
629 |
+
spells = node_or_edge_data.pop("spells", False)
|
630 |
+
if spells:
|
631 |
+
spells_element = Element("spells")
|
632 |
+
for start, end in spells:
|
633 |
+
e = Element("spell")
|
634 |
+
if start is not None:
|
635 |
+
e.attrib["start"] = str(start)
|
636 |
+
self.alter_graph_mode_timeformat(start)
|
637 |
+
if end is not None:
|
638 |
+
e.attrib["end"] = str(end)
|
639 |
+
self.alter_graph_mode_timeformat(end)
|
640 |
+
spells_element.append(e)
|
641 |
+
node_or_edge_element.append(spells_element)
|
642 |
+
return node_or_edge_data
|
643 |
+
|
644 |
+
def alter_graph_mode_timeformat(self, start_or_end):
|
645 |
+
# If 'start' or 'end' appears, alter Graph mode to dynamic and
|
646 |
+
# set timeformat
|
647 |
+
if self.graph_element.get("mode") == "static":
|
648 |
+
if start_or_end is not None:
|
649 |
+
if isinstance(start_or_end, str):
|
650 |
+
timeformat = "date"
|
651 |
+
elif isinstance(start_or_end, float):
|
652 |
+
timeformat = "double"
|
653 |
+
elif isinstance(start_or_end, int):
|
654 |
+
timeformat = "long"
|
655 |
+
else:
|
656 |
+
raise nx.NetworkXError(
|
657 |
+
"timeformat should be of the type int, float or str"
|
658 |
+
)
|
659 |
+
self.graph_element.set("timeformat", timeformat)
|
660 |
+
self.graph_element.set("mode", "dynamic")
|
661 |
+
|
662 |
+
def write(self, fh):
|
663 |
+
# Serialize graph G in GEXF to the open fh
|
664 |
+
if self.prettyprint:
|
665 |
+
self.indent(self.xml)
|
666 |
+
document = ElementTree(self.xml)
|
667 |
+
document.write(fh, encoding=self.encoding, xml_declaration=True)
|
668 |
+
|
669 |
+
def indent(self, elem, level=0):
|
670 |
+
# in-place prettyprint formatter
|
671 |
+
i = "\n" + " " * level
|
672 |
+
if len(elem):
|
673 |
+
if not elem.text or not elem.text.strip():
|
674 |
+
elem.text = i + " "
|
675 |
+
if not elem.tail or not elem.tail.strip():
|
676 |
+
elem.tail = i
|
677 |
+
for elem in elem:
|
678 |
+
self.indent(elem, level + 1)
|
679 |
+
if not elem.tail or not elem.tail.strip():
|
680 |
+
elem.tail = i
|
681 |
+
else:
|
682 |
+
if level and (not elem.tail or not elem.tail.strip()):
|
683 |
+
elem.tail = i
|
684 |
+
|
685 |
+
|
686 |
+
class GEXFReader(GEXF):
|
687 |
+
# Class to read GEXF format files
|
688 |
+
# use read_gexf() function
|
689 |
+
def __init__(self, node_type=None, version="1.2draft"):
|
690 |
+
self.construct_types()
|
691 |
+
self.node_type = node_type
|
692 |
+
# assume simple graph and test for multigraph on read
|
693 |
+
self.simple_graph = True
|
694 |
+
self.set_version(version)
|
695 |
+
|
696 |
+
def __call__(self, stream):
|
697 |
+
self.xml = ElementTree(file=stream)
|
698 |
+
g = self.xml.find(f"{{{self.NS_GEXF}}}graph")
|
699 |
+
if g is not None:
|
700 |
+
return self.make_graph(g)
|
701 |
+
# try all the versions
|
702 |
+
for version in self.versions:
|
703 |
+
self.set_version(version)
|
704 |
+
g = self.xml.find(f"{{{self.NS_GEXF}}}graph")
|
705 |
+
if g is not None:
|
706 |
+
return self.make_graph(g)
|
707 |
+
raise nx.NetworkXError("No <graph> element in GEXF file.")
|
708 |
+
|
709 |
+
def make_graph(self, graph_xml):
|
710 |
+
# start with empty DiGraph or MultiDiGraph
|
711 |
+
edgedefault = graph_xml.get("defaultedgetype", None)
|
712 |
+
if edgedefault == "directed":
|
713 |
+
G = nx.MultiDiGraph()
|
714 |
+
else:
|
715 |
+
G = nx.MultiGraph()
|
716 |
+
|
717 |
+
# graph attributes
|
718 |
+
graph_name = graph_xml.get("name", "")
|
719 |
+
if graph_name != "":
|
720 |
+
G.graph["name"] = graph_name
|
721 |
+
graph_start = graph_xml.get("start")
|
722 |
+
if graph_start is not None:
|
723 |
+
G.graph["start"] = graph_start
|
724 |
+
graph_end = graph_xml.get("end")
|
725 |
+
if graph_end is not None:
|
726 |
+
G.graph["end"] = graph_end
|
727 |
+
graph_mode = graph_xml.get("mode", "")
|
728 |
+
if graph_mode == "dynamic":
|
729 |
+
G.graph["mode"] = "dynamic"
|
730 |
+
else:
|
731 |
+
G.graph["mode"] = "static"
|
732 |
+
|
733 |
+
# timeformat
|
734 |
+
self.timeformat = graph_xml.get("timeformat")
|
735 |
+
if self.timeformat == "date":
|
736 |
+
self.timeformat = "string"
|
737 |
+
|
738 |
+
# node and edge attributes
|
739 |
+
attributes_elements = graph_xml.findall(f"{{{self.NS_GEXF}}}attributes")
|
740 |
+
# dictionaries to hold attributes and attribute defaults
|
741 |
+
node_attr = {}
|
742 |
+
node_default = {}
|
743 |
+
edge_attr = {}
|
744 |
+
edge_default = {}
|
745 |
+
for a in attributes_elements:
|
746 |
+
attr_class = a.get("class")
|
747 |
+
if attr_class == "node":
|
748 |
+
na, nd = self.find_gexf_attributes(a)
|
749 |
+
node_attr.update(na)
|
750 |
+
node_default.update(nd)
|
751 |
+
G.graph["node_default"] = node_default
|
752 |
+
elif attr_class == "edge":
|
753 |
+
ea, ed = self.find_gexf_attributes(a)
|
754 |
+
edge_attr.update(ea)
|
755 |
+
edge_default.update(ed)
|
756 |
+
G.graph["edge_default"] = edge_default
|
757 |
+
else:
|
758 |
+
raise # unknown attribute class
|
759 |
+
|
760 |
+
# Hack to handle Gephi0.7beta bug
|
761 |
+
# add weight attribute
|
762 |
+
ea = {"weight": {"type": "double", "mode": "static", "title": "weight"}}
|
763 |
+
ed = {}
|
764 |
+
edge_attr.update(ea)
|
765 |
+
edge_default.update(ed)
|
766 |
+
G.graph["edge_default"] = edge_default
|
767 |
+
|
768 |
+
# add nodes
|
769 |
+
nodes_element = graph_xml.find(f"{{{self.NS_GEXF}}}nodes")
|
770 |
+
if nodes_element is not None:
|
771 |
+
for node_xml in nodes_element.findall(f"{{{self.NS_GEXF}}}node"):
|
772 |
+
self.add_node(G, node_xml, node_attr)
|
773 |
+
|
774 |
+
# add edges
|
775 |
+
edges_element = graph_xml.find(f"{{{self.NS_GEXF}}}edges")
|
776 |
+
if edges_element is not None:
|
777 |
+
for edge_xml in edges_element.findall(f"{{{self.NS_GEXF}}}edge"):
|
778 |
+
self.add_edge(G, edge_xml, edge_attr)
|
779 |
+
|
780 |
+
# switch to Graph or DiGraph if no parallel edges were found.
|
781 |
+
if self.simple_graph:
|
782 |
+
if G.is_directed():
|
783 |
+
G = nx.DiGraph(G)
|
784 |
+
else:
|
785 |
+
G = nx.Graph(G)
|
786 |
+
return G
|
787 |
+
|
788 |
+
def add_node(self, G, node_xml, node_attr, node_pid=None):
|
789 |
+
# add a single node with attributes to the graph
|
790 |
+
|
791 |
+
# get attributes and subattributues for node
|
792 |
+
data = self.decode_attr_elements(node_attr, node_xml)
|
793 |
+
data = self.add_parents(data, node_xml) # add any parents
|
794 |
+
if self.VERSION == "1.1":
|
795 |
+
data = self.add_slices(data, node_xml) # add slices
|
796 |
+
else:
|
797 |
+
data = self.add_spells(data, node_xml) # add spells
|
798 |
+
data = self.add_viz(data, node_xml) # add viz
|
799 |
+
data = self.add_start_end(data, node_xml) # add start/end
|
800 |
+
|
801 |
+
# find the node id and cast it to the appropriate type
|
802 |
+
node_id = node_xml.get("id")
|
803 |
+
if self.node_type is not None:
|
804 |
+
node_id = self.node_type(node_id)
|
805 |
+
|
806 |
+
# every node should have a label
|
807 |
+
node_label = node_xml.get("label")
|
808 |
+
data["label"] = node_label
|
809 |
+
|
810 |
+
# parent node id
|
811 |
+
node_pid = node_xml.get("pid", node_pid)
|
812 |
+
if node_pid is not None:
|
813 |
+
data["pid"] = node_pid
|
814 |
+
|
815 |
+
# check for subnodes, recursive
|
816 |
+
subnodes = node_xml.find(f"{{{self.NS_GEXF}}}nodes")
|
817 |
+
if subnodes is not None:
|
818 |
+
for node_xml in subnodes.findall(f"{{{self.NS_GEXF}}}node"):
|
819 |
+
self.add_node(G, node_xml, node_attr, node_pid=node_id)
|
820 |
+
|
821 |
+
G.add_node(node_id, **data)
|
822 |
+
|
823 |
+
def add_start_end(self, data, xml):
|
824 |
+
# start and end times
|
825 |
+
ttype = self.timeformat
|
826 |
+
node_start = xml.get("start")
|
827 |
+
if node_start is not None:
|
828 |
+
data["start"] = self.python_type[ttype](node_start)
|
829 |
+
node_end = xml.get("end")
|
830 |
+
if node_end is not None:
|
831 |
+
data["end"] = self.python_type[ttype](node_end)
|
832 |
+
return data
|
833 |
+
|
834 |
+
def add_viz(self, data, node_xml):
|
835 |
+
# add viz element for node
|
836 |
+
viz = {}
|
837 |
+
color = node_xml.find(f"{{{self.NS_VIZ}}}color")
|
838 |
+
if color is not None:
|
839 |
+
if self.VERSION == "1.1":
|
840 |
+
viz["color"] = {
|
841 |
+
"r": int(color.get("r")),
|
842 |
+
"g": int(color.get("g")),
|
843 |
+
"b": int(color.get("b")),
|
844 |
+
}
|
845 |
+
else:
|
846 |
+
viz["color"] = {
|
847 |
+
"r": int(color.get("r")),
|
848 |
+
"g": int(color.get("g")),
|
849 |
+
"b": int(color.get("b")),
|
850 |
+
"a": float(color.get("a", 1)),
|
851 |
+
}
|
852 |
+
|
853 |
+
size = node_xml.find(f"{{{self.NS_VIZ}}}size")
|
854 |
+
if size is not None:
|
855 |
+
viz["size"] = float(size.get("value"))
|
856 |
+
|
857 |
+
thickness = node_xml.find(f"{{{self.NS_VIZ}}}thickness")
|
858 |
+
if thickness is not None:
|
859 |
+
viz["thickness"] = float(thickness.get("value"))
|
860 |
+
|
861 |
+
shape = node_xml.find(f"{{{self.NS_VIZ}}}shape")
|
862 |
+
if shape is not None:
|
863 |
+
viz["shape"] = shape.get("shape")
|
864 |
+
if viz["shape"] == "image":
|
865 |
+
viz["shape"] = shape.get("uri")
|
866 |
+
|
867 |
+
position = node_xml.find(f"{{{self.NS_VIZ}}}position")
|
868 |
+
if position is not None:
|
869 |
+
viz["position"] = {
|
870 |
+
"x": float(position.get("x", 0)),
|
871 |
+
"y": float(position.get("y", 0)),
|
872 |
+
"z": float(position.get("z", 0)),
|
873 |
+
}
|
874 |
+
|
875 |
+
if len(viz) > 0:
|
876 |
+
data["viz"] = viz
|
877 |
+
return data
|
878 |
+
|
879 |
+
def add_parents(self, data, node_xml):
|
880 |
+
parents_element = node_xml.find(f"{{{self.NS_GEXF}}}parents")
|
881 |
+
if parents_element is not None:
|
882 |
+
data["parents"] = []
|
883 |
+
for p in parents_element.findall(f"{{{self.NS_GEXF}}}parent"):
|
884 |
+
parent = p.get("for")
|
885 |
+
data["parents"].append(parent)
|
886 |
+
return data
|
887 |
+
|
888 |
+
def add_slices(self, data, node_or_edge_xml):
|
889 |
+
slices_element = node_or_edge_xml.find(f"{{{self.NS_GEXF}}}slices")
|
890 |
+
if slices_element is not None:
|
891 |
+
data["slices"] = []
|
892 |
+
for s in slices_element.findall(f"{{{self.NS_GEXF}}}slice"):
|
893 |
+
start = s.get("start")
|
894 |
+
end = s.get("end")
|
895 |
+
data["slices"].append((start, end))
|
896 |
+
return data
|
897 |
+
|
898 |
+
def add_spells(self, data, node_or_edge_xml):
|
899 |
+
spells_element = node_or_edge_xml.find(f"{{{self.NS_GEXF}}}spells")
|
900 |
+
if spells_element is not None:
|
901 |
+
data["spells"] = []
|
902 |
+
ttype = self.timeformat
|
903 |
+
for s in spells_element.findall(f"{{{self.NS_GEXF}}}spell"):
|
904 |
+
start = self.python_type[ttype](s.get("start"))
|
905 |
+
end = self.python_type[ttype](s.get("end"))
|
906 |
+
data["spells"].append((start, end))
|
907 |
+
return data
|
908 |
+
|
909 |
+
def add_edge(self, G, edge_element, edge_attr):
|
910 |
+
# add an edge to the graph
|
911 |
+
|
912 |
+
# raise error if we find mixed directed and undirected edges
|
913 |
+
edge_direction = edge_element.get("type")
|
914 |
+
if G.is_directed() and edge_direction == "undirected":
|
915 |
+
raise nx.NetworkXError("Undirected edge found in directed graph.")
|
916 |
+
if (not G.is_directed()) and edge_direction == "directed":
|
917 |
+
raise nx.NetworkXError("Directed edge found in undirected graph.")
|
918 |
+
|
919 |
+
# Get source and target and recast type if required
|
920 |
+
source = edge_element.get("source")
|
921 |
+
target = edge_element.get("target")
|
922 |
+
if self.node_type is not None:
|
923 |
+
source = self.node_type(source)
|
924 |
+
target = self.node_type(target)
|
925 |
+
|
926 |
+
data = self.decode_attr_elements(edge_attr, edge_element)
|
927 |
+
data = self.add_start_end(data, edge_element)
|
928 |
+
|
929 |
+
if self.VERSION == "1.1":
|
930 |
+
data = self.add_slices(data, edge_element) # add slices
|
931 |
+
else:
|
932 |
+
data = self.add_spells(data, edge_element) # add spells
|
933 |
+
|
934 |
+
# GEXF stores edge ids as an attribute
|
935 |
+
# NetworkX uses them as keys in multigraphs
|
936 |
+
# if networkx_key is not specified as an attribute
|
937 |
+
edge_id = edge_element.get("id")
|
938 |
+
if edge_id is not None:
|
939 |
+
data["id"] = edge_id
|
940 |
+
|
941 |
+
# check if there is a 'multigraph_key' and use that as edge_id
|
942 |
+
multigraph_key = data.pop("networkx_key", None)
|
943 |
+
if multigraph_key is not None:
|
944 |
+
edge_id = multigraph_key
|
945 |
+
|
946 |
+
weight = edge_element.get("weight")
|
947 |
+
if weight is not None:
|
948 |
+
data["weight"] = float(weight)
|
949 |
+
|
950 |
+
edge_label = edge_element.get("label")
|
951 |
+
if edge_label is not None:
|
952 |
+
data["label"] = edge_label
|
953 |
+
|
954 |
+
if G.has_edge(source, target):
|
955 |
+
# seen this edge before - this is a multigraph
|
956 |
+
self.simple_graph = False
|
957 |
+
G.add_edge(source, target, key=edge_id, **data)
|
958 |
+
if edge_direction == "mutual":
|
959 |
+
G.add_edge(target, source, key=edge_id, **data)
|
960 |
+
|
961 |
+
def decode_attr_elements(self, gexf_keys, obj_xml):
|
962 |
+
# Use the key information to decode the attr XML
|
963 |
+
attr = {}
|
964 |
+
# look for outer '<attvalues>' element
|
965 |
+
attr_element = obj_xml.find(f"{{{self.NS_GEXF}}}attvalues")
|
966 |
+
if attr_element is not None:
|
967 |
+
# loop over <attvalue> elements
|
968 |
+
for a in attr_element.findall(f"{{{self.NS_GEXF}}}attvalue"):
|
969 |
+
key = a.get("for") # for is required
|
970 |
+
try: # should be in our gexf_keys dictionary
|
971 |
+
title = gexf_keys[key]["title"]
|
972 |
+
except KeyError as err:
|
973 |
+
raise nx.NetworkXError(f"No attribute defined for={key}.") from err
|
974 |
+
atype = gexf_keys[key]["type"]
|
975 |
+
value = a.get("value")
|
976 |
+
if atype == "boolean":
|
977 |
+
value = self.convert_bool[value]
|
978 |
+
else:
|
979 |
+
value = self.python_type[atype](value)
|
980 |
+
if gexf_keys[key]["mode"] == "dynamic":
|
981 |
+
# for dynamic graphs use list of three-tuples
|
982 |
+
# [(value1,start1,end1), (value2,start2,end2), etc]
|
983 |
+
ttype = self.timeformat
|
984 |
+
start = self.python_type[ttype](a.get("start"))
|
985 |
+
end = self.python_type[ttype](a.get("end"))
|
986 |
+
if title in attr:
|
987 |
+
attr[title].append((value, start, end))
|
988 |
+
else:
|
989 |
+
attr[title] = [(value, start, end)]
|
990 |
+
else:
|
991 |
+
# for static graphs just assign the value
|
992 |
+
attr[title] = value
|
993 |
+
return attr
|
994 |
+
|
995 |
+
def find_gexf_attributes(self, attributes_element):
|
996 |
+
# Extract all the attributes and defaults
|
997 |
+
attrs = {}
|
998 |
+
defaults = {}
|
999 |
+
mode = attributes_element.get("mode")
|
1000 |
+
for k in attributes_element.findall(f"{{{self.NS_GEXF}}}attribute"):
|
1001 |
+
attr_id = k.get("id")
|
1002 |
+
title = k.get("title")
|
1003 |
+
atype = k.get("type")
|
1004 |
+
attrs[attr_id] = {"title": title, "type": atype, "mode": mode}
|
1005 |
+
# check for the 'default' subelement of key element and add
|
1006 |
+
default = k.find(f"{{{self.NS_GEXF}}}default")
|
1007 |
+
if default is not None:
|
1008 |
+
if atype == "boolean":
|
1009 |
+
value = self.convert_bool[default.text]
|
1010 |
+
else:
|
1011 |
+
value = self.python_type[atype](default.text)
|
1012 |
+
defaults[title] = value
|
1013 |
+
return attrs, defaults
|
1014 |
+
|
1015 |
+
|
1016 |
+
def relabel_gexf_graph(G):
|
1017 |
+
"""Relabel graph using "label" node keyword for node label.
|
1018 |
+
|
1019 |
+
Parameters
|
1020 |
+
----------
|
1021 |
+
G : graph
|
1022 |
+
A NetworkX graph read from GEXF data
|
1023 |
+
|
1024 |
+
Returns
|
1025 |
+
-------
|
1026 |
+
H : graph
|
1027 |
+
A NetworkX graph with relabeled nodes
|
1028 |
+
|
1029 |
+
Raises
|
1030 |
+
------
|
1031 |
+
NetworkXError
|
1032 |
+
If node labels are missing or not unique while relabel=True.
|
1033 |
+
|
1034 |
+
Notes
|
1035 |
+
-----
|
1036 |
+
This function relabels the nodes in a NetworkX graph with the
|
1037 |
+
"label" attribute. It also handles relabeling the specific GEXF
|
1038 |
+
node attributes "parents", and "pid".
|
1039 |
+
"""
|
1040 |
+
# build mapping of node labels, do some error checking
|
1041 |
+
try:
|
1042 |
+
mapping = [(u, G.nodes[u]["label"]) for u in G]
|
1043 |
+
except KeyError as err:
|
1044 |
+
raise nx.NetworkXError(
|
1045 |
+
"Failed to relabel nodes: missing node labels found. Use relabel=False."
|
1046 |
+
) from err
|
1047 |
+
x, y = zip(*mapping)
|
1048 |
+
if len(set(y)) != len(G):
|
1049 |
+
raise nx.NetworkXError(
|
1050 |
+
"Failed to relabel nodes: "
|
1051 |
+
"duplicate node labels found. "
|
1052 |
+
"Use relabel=False."
|
1053 |
+
)
|
1054 |
+
mapping = dict(mapping)
|
1055 |
+
H = nx.relabel_nodes(G, mapping)
|
1056 |
+
# relabel attributes
|
1057 |
+
for n in G:
|
1058 |
+
m = mapping[n]
|
1059 |
+
H.nodes[m]["id"] = n
|
1060 |
+
H.nodes[m].pop("label")
|
1061 |
+
if "pid" in H.nodes[m]:
|
1062 |
+
H.nodes[m]["pid"] = mapping[G.nodes[n]["pid"]]
|
1063 |
+
if "parents" in H.nodes[m]:
|
1064 |
+
H.nodes[m]["parents"] = [mapping[p] for p in G.nodes[n]["parents"]]
|
1065 |
+
return H
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/graphml.py
ADDED
@@ -0,0 +1,1052 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
*******
|
3 |
+
GraphML
|
4 |
+
*******
|
5 |
+
Read and write graphs in GraphML format.
|
6 |
+
|
7 |
+
.. warning::
|
8 |
+
|
9 |
+
This parser uses the standard xml library present in Python, which is
|
10 |
+
insecure - see :external+python:mod:`xml` for additional information.
|
11 |
+
Only parse GraphML files you trust.
|
12 |
+
|
13 |
+
This implementation does not support mixed graphs (directed and unidirected
|
14 |
+
edges together), hyperedges, nested graphs, or ports.
|
15 |
+
|
16 |
+
"GraphML is a comprehensive and easy-to-use file format for graphs. It
|
17 |
+
consists of a language core to describe the structural properties of a
|
18 |
+
graph and a flexible extension mechanism to add application-specific
|
19 |
+
data. Its main features include support of
|
20 |
+
|
21 |
+
* directed, undirected, and mixed graphs,
|
22 |
+
* hypergraphs,
|
23 |
+
* hierarchical graphs,
|
24 |
+
* graphical representations,
|
25 |
+
* references to external data,
|
26 |
+
* application-specific attribute data, and
|
27 |
+
* light-weight parsers.
|
28 |
+
|
29 |
+
Unlike many other file formats for graphs, GraphML does not use a
|
30 |
+
custom syntax. Instead, it is based on XML and hence ideally suited as
|
31 |
+
a common denominator for all kinds of services generating, archiving,
|
32 |
+
or processing graphs."
|
33 |
+
|
34 |
+
http://graphml.graphdrawing.org/
|
35 |
+
|
36 |
+
Format
|
37 |
+
------
|
38 |
+
GraphML is an XML format. See
|
39 |
+
http://graphml.graphdrawing.org/specification.html for the specification and
|
40 |
+
http://graphml.graphdrawing.org/primer/graphml-primer.html
|
41 |
+
for examples.
|
42 |
+
"""
|
43 |
+
import warnings
|
44 |
+
from collections import defaultdict
|
45 |
+
|
46 |
+
import networkx as nx
|
47 |
+
from networkx.utils import open_file
|
48 |
+
|
49 |
+
__all__ = [
|
50 |
+
"write_graphml",
|
51 |
+
"read_graphml",
|
52 |
+
"generate_graphml",
|
53 |
+
"write_graphml_xml",
|
54 |
+
"write_graphml_lxml",
|
55 |
+
"parse_graphml",
|
56 |
+
"GraphMLWriter",
|
57 |
+
"GraphMLReader",
|
58 |
+
]
|
59 |
+
|
60 |
+
|
61 |
+
@open_file(1, mode="wb")
|
62 |
+
def write_graphml_xml(
|
63 |
+
G,
|
64 |
+
path,
|
65 |
+
encoding="utf-8",
|
66 |
+
prettyprint=True,
|
67 |
+
infer_numeric_types=False,
|
68 |
+
named_key_ids=False,
|
69 |
+
edge_id_from_attribute=None,
|
70 |
+
):
|
71 |
+
"""Write G in GraphML XML format to path
|
72 |
+
|
73 |
+
Parameters
|
74 |
+
----------
|
75 |
+
G : graph
|
76 |
+
A networkx graph
|
77 |
+
path : file or string
|
78 |
+
File or filename to write.
|
79 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
80 |
+
encoding : string (optional)
|
81 |
+
Encoding for text data.
|
82 |
+
prettyprint : bool (optional)
|
83 |
+
If True use line breaks and indenting in output XML.
|
84 |
+
infer_numeric_types : boolean
|
85 |
+
Determine if numeric types should be generalized.
|
86 |
+
For example, if edges have both int and float 'weight' attributes,
|
87 |
+
we infer in GraphML that both are floats.
|
88 |
+
named_key_ids : bool (optional)
|
89 |
+
If True use attr.name as value for key elements' id attribute.
|
90 |
+
edge_id_from_attribute : dict key (optional)
|
91 |
+
If provided, the graphml edge id is set by looking up the corresponding
|
92 |
+
edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
|
93 |
+
the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
|
94 |
+
|
95 |
+
Examples
|
96 |
+
--------
|
97 |
+
>>> G = nx.path_graph(4)
|
98 |
+
>>> nx.write_graphml(G, "test.graphml")
|
99 |
+
|
100 |
+
Notes
|
101 |
+
-----
|
102 |
+
This implementation does not support mixed graphs (directed
|
103 |
+
and unidirected edges together) hyperedges, nested graphs, or ports.
|
104 |
+
"""
|
105 |
+
writer = GraphMLWriter(
|
106 |
+
encoding=encoding,
|
107 |
+
prettyprint=prettyprint,
|
108 |
+
infer_numeric_types=infer_numeric_types,
|
109 |
+
named_key_ids=named_key_ids,
|
110 |
+
edge_id_from_attribute=edge_id_from_attribute,
|
111 |
+
)
|
112 |
+
writer.add_graph_element(G)
|
113 |
+
writer.dump(path)
|
114 |
+
|
115 |
+
|
116 |
+
@open_file(1, mode="wb")
|
117 |
+
def write_graphml_lxml(
|
118 |
+
G,
|
119 |
+
path,
|
120 |
+
encoding="utf-8",
|
121 |
+
prettyprint=True,
|
122 |
+
infer_numeric_types=False,
|
123 |
+
named_key_ids=False,
|
124 |
+
edge_id_from_attribute=None,
|
125 |
+
):
|
126 |
+
"""Write G in GraphML XML format to path
|
127 |
+
|
128 |
+
This function uses the LXML framework and should be faster than
|
129 |
+
the version using the xml library.
|
130 |
+
|
131 |
+
Parameters
|
132 |
+
----------
|
133 |
+
G : graph
|
134 |
+
A networkx graph
|
135 |
+
path : file or string
|
136 |
+
File or filename to write.
|
137 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
138 |
+
encoding : string (optional)
|
139 |
+
Encoding for text data.
|
140 |
+
prettyprint : bool (optional)
|
141 |
+
If True use line breaks and indenting in output XML.
|
142 |
+
infer_numeric_types : boolean
|
143 |
+
Determine if numeric types should be generalized.
|
144 |
+
For example, if edges have both int and float 'weight' attributes,
|
145 |
+
we infer in GraphML that both are floats.
|
146 |
+
named_key_ids : bool (optional)
|
147 |
+
If True use attr.name as value for key elements' id attribute.
|
148 |
+
edge_id_from_attribute : dict key (optional)
|
149 |
+
If provided, the graphml edge id is set by looking up the corresponding
|
150 |
+
edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
|
151 |
+
the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
|
152 |
+
|
153 |
+
Examples
|
154 |
+
--------
|
155 |
+
>>> G = nx.path_graph(4)
|
156 |
+
>>> nx.write_graphml_lxml(G, "fourpath.graphml")
|
157 |
+
|
158 |
+
Notes
|
159 |
+
-----
|
160 |
+
This implementation does not support mixed graphs (directed
|
161 |
+
and unidirected edges together) hyperedges, nested graphs, or ports.
|
162 |
+
"""
|
163 |
+
try:
|
164 |
+
import lxml.etree as lxmletree
|
165 |
+
except ImportError:
|
166 |
+
return write_graphml_xml(
|
167 |
+
G,
|
168 |
+
path,
|
169 |
+
encoding,
|
170 |
+
prettyprint,
|
171 |
+
infer_numeric_types,
|
172 |
+
named_key_ids,
|
173 |
+
edge_id_from_attribute,
|
174 |
+
)
|
175 |
+
|
176 |
+
writer = GraphMLWriterLxml(
|
177 |
+
path,
|
178 |
+
graph=G,
|
179 |
+
encoding=encoding,
|
180 |
+
prettyprint=prettyprint,
|
181 |
+
infer_numeric_types=infer_numeric_types,
|
182 |
+
named_key_ids=named_key_ids,
|
183 |
+
edge_id_from_attribute=edge_id_from_attribute,
|
184 |
+
)
|
185 |
+
writer.dump()
|
186 |
+
|
187 |
+
|
188 |
+
def generate_graphml(
|
189 |
+
G,
|
190 |
+
encoding="utf-8",
|
191 |
+
prettyprint=True,
|
192 |
+
named_key_ids=False,
|
193 |
+
edge_id_from_attribute=None,
|
194 |
+
):
|
195 |
+
"""Generate GraphML lines for G
|
196 |
+
|
197 |
+
Parameters
|
198 |
+
----------
|
199 |
+
G : graph
|
200 |
+
A networkx graph
|
201 |
+
encoding : string (optional)
|
202 |
+
Encoding for text data.
|
203 |
+
prettyprint : bool (optional)
|
204 |
+
If True use line breaks and indenting in output XML.
|
205 |
+
named_key_ids : bool (optional)
|
206 |
+
If True use attr.name as value for key elements' id attribute.
|
207 |
+
edge_id_from_attribute : dict key (optional)
|
208 |
+
If provided, the graphml edge id is set by looking up the corresponding
|
209 |
+
edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
|
210 |
+
the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.
|
211 |
+
|
212 |
+
Examples
|
213 |
+
--------
|
214 |
+
>>> G = nx.path_graph(4)
|
215 |
+
>>> linefeed = chr(10) # linefeed = \n
|
216 |
+
>>> s = linefeed.join(nx.generate_graphml(G))
|
217 |
+
>>> for line in nx.generate_graphml(G): # doctest: +SKIP
|
218 |
+
... print(line)
|
219 |
+
|
220 |
+
Notes
|
221 |
+
-----
|
222 |
+
This implementation does not support mixed graphs (directed and unidirected
|
223 |
+
edges together) hyperedges, nested graphs, or ports.
|
224 |
+
"""
|
225 |
+
writer = GraphMLWriter(
|
226 |
+
encoding=encoding,
|
227 |
+
prettyprint=prettyprint,
|
228 |
+
named_key_ids=named_key_ids,
|
229 |
+
edge_id_from_attribute=edge_id_from_attribute,
|
230 |
+
)
|
231 |
+
writer.add_graph_element(G)
|
232 |
+
yield from str(writer).splitlines()
|
233 |
+
|
234 |
+
|
235 |
+
@open_file(0, mode="rb")
|
236 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
237 |
+
def read_graphml(path, node_type=str, edge_key_type=int, force_multigraph=False):
|
238 |
+
"""Read graph in GraphML format from path.
|
239 |
+
|
240 |
+
Parameters
|
241 |
+
----------
|
242 |
+
path : file or string
|
243 |
+
File or filename to write.
|
244 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
245 |
+
|
246 |
+
node_type: Python type (default: str)
|
247 |
+
Convert node ids to this type
|
248 |
+
|
249 |
+
edge_key_type: Python type (default: int)
|
250 |
+
Convert graphml edge ids to this type. Multigraphs use id as edge key.
|
251 |
+
Non-multigraphs add to edge attribute dict with name "id".
|
252 |
+
|
253 |
+
force_multigraph : bool (default: False)
|
254 |
+
If True, return a multigraph with edge keys. If False (the default)
|
255 |
+
return a multigraph when multiedges are in the graph.
|
256 |
+
|
257 |
+
Returns
|
258 |
+
-------
|
259 |
+
graph: NetworkX graph
|
260 |
+
If parallel edges are present or `force_multigraph=True` then
|
261 |
+
a MultiGraph or MultiDiGraph is returned. Otherwise a Graph/DiGraph.
|
262 |
+
The returned graph is directed if the file indicates it should be.
|
263 |
+
|
264 |
+
Notes
|
265 |
+
-----
|
266 |
+
Default node and edge attributes are not propagated to each node and edge.
|
267 |
+
They can be obtained from `G.graph` and applied to node and edge attributes
|
268 |
+
if desired using something like this:
|
269 |
+
|
270 |
+
>>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP
|
271 |
+
>>> for node, data in G.nodes(data=True): # doctest: +SKIP
|
272 |
+
... if "color" not in data:
|
273 |
+
... data["color"] = default_color
|
274 |
+
>>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP
|
275 |
+
>>> for u, v, data in G.edges(data=True): # doctest: +SKIP
|
276 |
+
... if "color" not in data:
|
277 |
+
... data["color"] = default_color
|
278 |
+
|
279 |
+
This implementation does not support mixed graphs (directed and unidirected
|
280 |
+
edges together), hypergraphs, nested graphs, or ports.
|
281 |
+
|
282 |
+
For multigraphs the GraphML edge "id" will be used as the edge
|
283 |
+
key. If not specified then they "key" attribute will be used. If
|
284 |
+
there is no "key" attribute a default NetworkX multigraph edge key
|
285 |
+
will be provided.
|
286 |
+
|
287 |
+
Files with the yEd "yfiles" extension can be read. The type of the node's
|
288 |
+
shape is preserved in the `shape_type` node attribute.
|
289 |
+
|
290 |
+
yEd compressed files ("file.graphmlz" extension) can be read by renaming
|
291 |
+
the file to "file.graphml.gz".
|
292 |
+
|
293 |
+
"""
|
294 |
+
reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
|
295 |
+
# need to check for multiple graphs
|
296 |
+
glist = list(reader(path=path))
|
297 |
+
if len(glist) == 0:
|
298 |
+
# If no graph comes back, try looking for an incomplete header
|
299 |
+
header = b'<graphml xmlns="http://graphml.graphdrawing.org/xmlns">'
|
300 |
+
path.seek(0)
|
301 |
+
old_bytes = path.read()
|
302 |
+
new_bytes = old_bytes.replace(b"<graphml>", header)
|
303 |
+
glist = list(reader(string=new_bytes))
|
304 |
+
if len(glist) == 0:
|
305 |
+
raise nx.NetworkXError("file not successfully read as graphml")
|
306 |
+
return glist[0]
|
307 |
+
|
308 |
+
|
309 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
310 |
+
def parse_graphml(
|
311 |
+
graphml_string, node_type=str, edge_key_type=int, force_multigraph=False
|
312 |
+
):
|
313 |
+
"""Read graph in GraphML format from string.
|
314 |
+
|
315 |
+
Parameters
|
316 |
+
----------
|
317 |
+
graphml_string : string
|
318 |
+
String containing graphml information
|
319 |
+
(e.g., contents of a graphml file).
|
320 |
+
|
321 |
+
node_type: Python type (default: str)
|
322 |
+
Convert node ids to this type
|
323 |
+
|
324 |
+
edge_key_type: Python type (default: int)
|
325 |
+
Convert graphml edge ids to this type. Multigraphs use id as edge key.
|
326 |
+
Non-multigraphs add to edge attribute dict with name "id".
|
327 |
+
|
328 |
+
force_multigraph : bool (default: False)
|
329 |
+
If True, return a multigraph with edge keys. If False (the default)
|
330 |
+
return a multigraph when multiedges are in the graph.
|
331 |
+
|
332 |
+
|
333 |
+
Returns
|
334 |
+
-------
|
335 |
+
graph: NetworkX graph
|
336 |
+
If no parallel edges are found a Graph or DiGraph is returned.
|
337 |
+
Otherwise a MultiGraph or MultiDiGraph is returned.
|
338 |
+
|
339 |
+
Examples
|
340 |
+
--------
|
341 |
+
>>> G = nx.path_graph(4)
|
342 |
+
>>> linefeed = chr(10) # linefeed = \n
|
343 |
+
>>> s = linefeed.join(nx.generate_graphml(G))
|
344 |
+
>>> H = nx.parse_graphml(s)
|
345 |
+
|
346 |
+
Notes
|
347 |
+
-----
|
348 |
+
Default node and edge attributes are not propagated to each node and edge.
|
349 |
+
They can be obtained from `G.graph` and applied to node and edge attributes
|
350 |
+
if desired using something like this:
|
351 |
+
|
352 |
+
>>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP
|
353 |
+
>>> for node, data in G.nodes(data=True): # doctest: +SKIP
|
354 |
+
... if "color" not in data:
|
355 |
+
... data["color"] = default_color
|
356 |
+
>>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP
|
357 |
+
>>> for u, v, data in G.edges(data=True): # doctest: +SKIP
|
358 |
+
... if "color" not in data:
|
359 |
+
... data["color"] = default_color
|
360 |
+
|
361 |
+
This implementation does not support mixed graphs (directed and unidirected
|
362 |
+
edges together), hypergraphs, nested graphs, or ports.
|
363 |
+
|
364 |
+
For multigraphs the GraphML edge "id" will be used as the edge
|
365 |
+
key. If not specified then they "key" attribute will be used. If
|
366 |
+
there is no "key" attribute a default NetworkX multigraph edge key
|
367 |
+
will be provided.
|
368 |
+
|
369 |
+
"""
|
370 |
+
reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
|
371 |
+
# need to check for multiple graphs
|
372 |
+
glist = list(reader(string=graphml_string))
|
373 |
+
if len(glist) == 0:
|
374 |
+
# If no graph comes back, try looking for an incomplete header
|
375 |
+
header = '<graphml xmlns="http://graphml.graphdrawing.org/xmlns">'
|
376 |
+
new_string = graphml_string.replace("<graphml>", header)
|
377 |
+
glist = list(reader(string=new_string))
|
378 |
+
if len(glist) == 0:
|
379 |
+
raise nx.NetworkXError("file not successfully read as graphml")
|
380 |
+
return glist[0]
|
381 |
+
|
382 |
+
|
383 |
+
class GraphML:
|
384 |
+
NS_GRAPHML = "http://graphml.graphdrawing.org/xmlns"
|
385 |
+
NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
|
386 |
+
# xmlns:y="http://www.yworks.com/xml/graphml"
|
387 |
+
NS_Y = "http://www.yworks.com/xml/graphml"
|
388 |
+
SCHEMALOCATION = " ".join(
|
389 |
+
[
|
390 |
+
"http://graphml.graphdrawing.org/xmlns",
|
391 |
+
"http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd",
|
392 |
+
]
|
393 |
+
)
|
394 |
+
|
395 |
+
def construct_types(self):
|
396 |
+
types = [
|
397 |
+
(int, "integer"), # for Gephi GraphML bug
|
398 |
+
(str, "yfiles"),
|
399 |
+
(str, "string"),
|
400 |
+
(int, "int"),
|
401 |
+
(int, "long"),
|
402 |
+
(float, "float"),
|
403 |
+
(float, "double"),
|
404 |
+
(bool, "boolean"),
|
405 |
+
]
|
406 |
+
|
407 |
+
# These additions to types allow writing numpy types
|
408 |
+
try:
|
409 |
+
import numpy as np
|
410 |
+
except:
|
411 |
+
pass
|
412 |
+
else:
|
413 |
+
# prepend so that python types are created upon read (last entry wins)
|
414 |
+
types = [
|
415 |
+
(np.float64, "float"),
|
416 |
+
(np.float32, "float"),
|
417 |
+
(np.float16, "float"),
|
418 |
+
(np.int_, "int"),
|
419 |
+
(np.int8, "int"),
|
420 |
+
(np.int16, "int"),
|
421 |
+
(np.int32, "int"),
|
422 |
+
(np.int64, "int"),
|
423 |
+
(np.uint8, "int"),
|
424 |
+
(np.uint16, "int"),
|
425 |
+
(np.uint32, "int"),
|
426 |
+
(np.uint64, "int"),
|
427 |
+
(np.int_, "int"),
|
428 |
+
(np.intc, "int"),
|
429 |
+
(np.intp, "int"),
|
430 |
+
] + types
|
431 |
+
|
432 |
+
self.xml_type = dict(types)
|
433 |
+
self.python_type = dict(reversed(a) for a in types)
|
434 |
+
|
435 |
+
# This page says that data types in GraphML follow Java(TM).
|
436 |
+
# http://graphml.graphdrawing.org/primer/graphml-primer.html#AttributesDefinition
|
437 |
+
# true and false are the only boolean literals:
|
438 |
+
# http://en.wikibooks.org/wiki/Java_Programming/Literals#Boolean_Literals
|
439 |
+
convert_bool = {
|
440 |
+
# We use data.lower() in actual use.
|
441 |
+
"true": True,
|
442 |
+
"false": False,
|
443 |
+
# Include integer strings for convenience.
|
444 |
+
"0": False,
|
445 |
+
0: False,
|
446 |
+
"1": True,
|
447 |
+
1: True,
|
448 |
+
}
|
449 |
+
|
450 |
+
def get_xml_type(self, key):
|
451 |
+
"""Wrapper around the xml_type dict that raises a more informative
|
452 |
+
exception message when a user attempts to use data of a type not
|
453 |
+
supported by GraphML."""
|
454 |
+
try:
|
455 |
+
return self.xml_type[key]
|
456 |
+
except KeyError as err:
|
457 |
+
raise TypeError(
|
458 |
+
f"GraphML does not support type {key} as data values."
|
459 |
+
) from err
|
460 |
+
|
461 |
+
|
462 |
+
class GraphMLWriter(GraphML):
|
463 |
+
def __init__(
|
464 |
+
self,
|
465 |
+
graph=None,
|
466 |
+
encoding="utf-8",
|
467 |
+
prettyprint=True,
|
468 |
+
infer_numeric_types=False,
|
469 |
+
named_key_ids=False,
|
470 |
+
edge_id_from_attribute=None,
|
471 |
+
):
|
472 |
+
self.construct_types()
|
473 |
+
from xml.etree.ElementTree import Element
|
474 |
+
|
475 |
+
self.myElement = Element
|
476 |
+
|
477 |
+
self.infer_numeric_types = infer_numeric_types
|
478 |
+
self.prettyprint = prettyprint
|
479 |
+
self.named_key_ids = named_key_ids
|
480 |
+
self.edge_id_from_attribute = edge_id_from_attribute
|
481 |
+
self.encoding = encoding
|
482 |
+
self.xml = self.myElement(
|
483 |
+
"graphml",
|
484 |
+
{
|
485 |
+
"xmlns": self.NS_GRAPHML,
|
486 |
+
"xmlns:xsi": self.NS_XSI,
|
487 |
+
"xsi:schemaLocation": self.SCHEMALOCATION,
|
488 |
+
},
|
489 |
+
)
|
490 |
+
self.keys = {}
|
491 |
+
self.attributes = defaultdict(list)
|
492 |
+
self.attribute_types = defaultdict(set)
|
493 |
+
|
494 |
+
if graph is not None:
|
495 |
+
self.add_graph_element(graph)
|
496 |
+
|
497 |
+
def __str__(self):
|
498 |
+
from xml.etree.ElementTree import tostring
|
499 |
+
|
500 |
+
if self.prettyprint:
|
501 |
+
self.indent(self.xml)
|
502 |
+
s = tostring(self.xml).decode(self.encoding)
|
503 |
+
return s
|
504 |
+
|
505 |
+
def attr_type(self, name, scope, value):
|
506 |
+
"""Infer the attribute type of data named name. Currently this only
|
507 |
+
supports inference of numeric types.
|
508 |
+
|
509 |
+
If self.infer_numeric_types is false, type is used. Otherwise, pick the
|
510 |
+
most general of types found across all values with name and scope. This
|
511 |
+
means edges with data named 'weight' are treated separately from nodes
|
512 |
+
with data named 'weight'.
|
513 |
+
"""
|
514 |
+
if self.infer_numeric_types:
|
515 |
+
types = self.attribute_types[(name, scope)]
|
516 |
+
|
517 |
+
if len(types) > 1:
|
518 |
+
types = {self.get_xml_type(t) for t in types}
|
519 |
+
if "string" in types:
|
520 |
+
return str
|
521 |
+
elif "float" in types or "double" in types:
|
522 |
+
return float
|
523 |
+
else:
|
524 |
+
return int
|
525 |
+
else:
|
526 |
+
return list(types)[0]
|
527 |
+
else:
|
528 |
+
return type(value)
|
529 |
+
|
530 |
+
def get_key(self, name, attr_type, scope, default):
|
531 |
+
keys_key = (name, attr_type, scope)
|
532 |
+
try:
|
533 |
+
return self.keys[keys_key]
|
534 |
+
except KeyError:
|
535 |
+
if self.named_key_ids:
|
536 |
+
new_id = name
|
537 |
+
else:
|
538 |
+
new_id = f"d{len(list(self.keys))}"
|
539 |
+
|
540 |
+
self.keys[keys_key] = new_id
|
541 |
+
key_kwargs = {
|
542 |
+
"id": new_id,
|
543 |
+
"for": scope,
|
544 |
+
"attr.name": name,
|
545 |
+
"attr.type": attr_type,
|
546 |
+
}
|
547 |
+
key_element = self.myElement("key", **key_kwargs)
|
548 |
+
# add subelement for data default value if present
|
549 |
+
if default is not None:
|
550 |
+
default_element = self.myElement("default")
|
551 |
+
default_element.text = str(default)
|
552 |
+
key_element.append(default_element)
|
553 |
+
self.xml.insert(0, key_element)
|
554 |
+
return new_id
|
555 |
+
|
556 |
+
def add_data(self, name, element_type, value, scope="all", default=None):
|
557 |
+
"""
|
558 |
+
Make a data element for an edge or a node. Keep a log of the
|
559 |
+
type in the keys table.
|
560 |
+
"""
|
561 |
+
if element_type not in self.xml_type:
|
562 |
+
raise nx.NetworkXError(
|
563 |
+
f"GraphML writer does not support {element_type} as data values."
|
564 |
+
)
|
565 |
+
keyid = self.get_key(name, self.get_xml_type(element_type), scope, default)
|
566 |
+
data_element = self.myElement("data", key=keyid)
|
567 |
+
data_element.text = str(value)
|
568 |
+
return data_element
|
569 |
+
|
570 |
+
def add_attributes(self, scope, xml_obj, data, default):
|
571 |
+
"""Appends attribute data to edges or nodes, and stores type information
|
572 |
+
to be added later. See add_graph_element.
|
573 |
+
"""
|
574 |
+
for k, v in data.items():
|
575 |
+
self.attribute_types[(str(k), scope)].add(type(v))
|
576 |
+
self.attributes[xml_obj].append([k, v, scope, default.get(k)])
|
577 |
+
|
578 |
+
def add_nodes(self, G, graph_element):
|
579 |
+
default = G.graph.get("node_default", {})
|
580 |
+
for node, data in G.nodes(data=True):
|
581 |
+
node_element = self.myElement("node", id=str(node))
|
582 |
+
self.add_attributes("node", node_element, data, default)
|
583 |
+
graph_element.append(node_element)
|
584 |
+
|
585 |
+
def add_edges(self, G, graph_element):
|
586 |
+
if G.is_multigraph():
|
587 |
+
for u, v, key, data in G.edges(data=True, keys=True):
|
588 |
+
edge_element = self.myElement(
|
589 |
+
"edge",
|
590 |
+
source=str(u),
|
591 |
+
target=str(v),
|
592 |
+
id=str(data.get(self.edge_id_from_attribute))
|
593 |
+
if self.edge_id_from_attribute
|
594 |
+
and self.edge_id_from_attribute in data
|
595 |
+
else str(key),
|
596 |
+
)
|
597 |
+
default = G.graph.get("edge_default", {})
|
598 |
+
self.add_attributes("edge", edge_element, data, default)
|
599 |
+
graph_element.append(edge_element)
|
600 |
+
else:
|
601 |
+
for u, v, data in G.edges(data=True):
|
602 |
+
if self.edge_id_from_attribute and self.edge_id_from_attribute in data:
|
603 |
+
# select attribute to be edge id
|
604 |
+
edge_element = self.myElement(
|
605 |
+
"edge",
|
606 |
+
source=str(u),
|
607 |
+
target=str(v),
|
608 |
+
id=str(data.get(self.edge_id_from_attribute)),
|
609 |
+
)
|
610 |
+
else:
|
611 |
+
# default: no edge id
|
612 |
+
edge_element = self.myElement("edge", source=str(u), target=str(v))
|
613 |
+
default = G.graph.get("edge_default", {})
|
614 |
+
self.add_attributes("edge", edge_element, data, default)
|
615 |
+
graph_element.append(edge_element)
|
616 |
+
|
617 |
+
def add_graph_element(self, G):
|
618 |
+
"""
|
619 |
+
Serialize graph G in GraphML to the stream.
|
620 |
+
"""
|
621 |
+
if G.is_directed():
|
622 |
+
default_edge_type = "directed"
|
623 |
+
else:
|
624 |
+
default_edge_type = "undirected"
|
625 |
+
|
626 |
+
graphid = G.graph.pop("id", None)
|
627 |
+
if graphid is None:
|
628 |
+
graph_element = self.myElement("graph", edgedefault=default_edge_type)
|
629 |
+
else:
|
630 |
+
graph_element = self.myElement(
|
631 |
+
"graph", edgedefault=default_edge_type, id=graphid
|
632 |
+
)
|
633 |
+
default = {}
|
634 |
+
data = {
|
635 |
+
k: v
|
636 |
+
for (k, v) in G.graph.items()
|
637 |
+
if k not in ["node_default", "edge_default"]
|
638 |
+
}
|
639 |
+
self.add_attributes("graph", graph_element, data, default)
|
640 |
+
self.add_nodes(G, graph_element)
|
641 |
+
self.add_edges(G, graph_element)
|
642 |
+
|
643 |
+
# self.attributes contains a mapping from XML Objects to a list of
|
644 |
+
# data that needs to be added to them.
|
645 |
+
# We postpone processing in order to do type inference/generalization.
|
646 |
+
# See self.attr_type
|
647 |
+
for xml_obj, data in self.attributes.items():
|
648 |
+
for k, v, scope, default in data:
|
649 |
+
xml_obj.append(
|
650 |
+
self.add_data(
|
651 |
+
str(k), self.attr_type(k, scope, v), str(v), scope, default
|
652 |
+
)
|
653 |
+
)
|
654 |
+
self.xml.append(graph_element)
|
655 |
+
|
656 |
+
def add_graphs(self, graph_list):
|
657 |
+
"""Add many graphs to this GraphML document."""
|
658 |
+
for G in graph_list:
|
659 |
+
self.add_graph_element(G)
|
660 |
+
|
661 |
+
def dump(self, stream):
|
662 |
+
from xml.etree.ElementTree import ElementTree
|
663 |
+
|
664 |
+
if self.prettyprint:
|
665 |
+
self.indent(self.xml)
|
666 |
+
document = ElementTree(self.xml)
|
667 |
+
document.write(stream, encoding=self.encoding, xml_declaration=True)
|
668 |
+
|
669 |
+
def indent(self, elem, level=0):
|
670 |
+
# in-place prettyprint formatter
|
671 |
+
i = "\n" + level * " "
|
672 |
+
if len(elem):
|
673 |
+
if not elem.text or not elem.text.strip():
|
674 |
+
elem.text = i + " "
|
675 |
+
if not elem.tail or not elem.tail.strip():
|
676 |
+
elem.tail = i
|
677 |
+
for elem in elem:
|
678 |
+
self.indent(elem, level + 1)
|
679 |
+
if not elem.tail or not elem.tail.strip():
|
680 |
+
elem.tail = i
|
681 |
+
else:
|
682 |
+
if level and (not elem.tail or not elem.tail.strip()):
|
683 |
+
elem.tail = i
|
684 |
+
|
685 |
+
|
686 |
+
class IncrementalElement:
|
687 |
+
"""Wrapper for _IncrementalWriter providing an Element like interface.
|
688 |
+
|
689 |
+
This wrapper does not intend to be a complete implementation but rather to
|
690 |
+
deal with those calls used in GraphMLWriter.
|
691 |
+
"""
|
692 |
+
|
693 |
+
def __init__(self, xml, prettyprint):
|
694 |
+
self.xml = xml
|
695 |
+
self.prettyprint = prettyprint
|
696 |
+
|
697 |
+
def append(self, element):
|
698 |
+
self.xml.write(element, pretty_print=self.prettyprint)
|
699 |
+
|
700 |
+
|
701 |
+
class GraphMLWriterLxml(GraphMLWriter):
|
702 |
+
def __init__(
|
703 |
+
self,
|
704 |
+
path,
|
705 |
+
graph=None,
|
706 |
+
encoding="utf-8",
|
707 |
+
prettyprint=True,
|
708 |
+
infer_numeric_types=False,
|
709 |
+
named_key_ids=False,
|
710 |
+
edge_id_from_attribute=None,
|
711 |
+
):
|
712 |
+
self.construct_types()
|
713 |
+
import lxml.etree as lxmletree
|
714 |
+
|
715 |
+
self.myElement = lxmletree.Element
|
716 |
+
|
717 |
+
self._encoding = encoding
|
718 |
+
self._prettyprint = prettyprint
|
719 |
+
self.named_key_ids = named_key_ids
|
720 |
+
self.edge_id_from_attribute = edge_id_from_attribute
|
721 |
+
self.infer_numeric_types = infer_numeric_types
|
722 |
+
|
723 |
+
self._xml_base = lxmletree.xmlfile(path, encoding=encoding)
|
724 |
+
self._xml = self._xml_base.__enter__()
|
725 |
+
self._xml.write_declaration()
|
726 |
+
|
727 |
+
# We need to have a xml variable that support insertion. This call is
|
728 |
+
# used for adding the keys to the document.
|
729 |
+
# We will store those keys in a plain list, and then after the graph
|
730 |
+
# element is closed we will add them to the main graphml element.
|
731 |
+
self.xml = []
|
732 |
+
self._keys = self.xml
|
733 |
+
self._graphml = self._xml.element(
|
734 |
+
"graphml",
|
735 |
+
{
|
736 |
+
"xmlns": self.NS_GRAPHML,
|
737 |
+
"xmlns:xsi": self.NS_XSI,
|
738 |
+
"xsi:schemaLocation": self.SCHEMALOCATION,
|
739 |
+
},
|
740 |
+
)
|
741 |
+
self._graphml.__enter__()
|
742 |
+
self.keys = {}
|
743 |
+
self.attribute_types = defaultdict(set)
|
744 |
+
|
745 |
+
if graph is not None:
|
746 |
+
self.add_graph_element(graph)
|
747 |
+
|
748 |
+
def add_graph_element(self, G):
|
749 |
+
"""
|
750 |
+
Serialize graph G in GraphML to the stream.
|
751 |
+
"""
|
752 |
+
if G.is_directed():
|
753 |
+
default_edge_type = "directed"
|
754 |
+
else:
|
755 |
+
default_edge_type = "undirected"
|
756 |
+
|
757 |
+
graphid = G.graph.pop("id", None)
|
758 |
+
if graphid is None:
|
759 |
+
graph_element = self._xml.element("graph", edgedefault=default_edge_type)
|
760 |
+
else:
|
761 |
+
graph_element = self._xml.element(
|
762 |
+
"graph", edgedefault=default_edge_type, id=graphid
|
763 |
+
)
|
764 |
+
|
765 |
+
# gather attributes types for the whole graph
|
766 |
+
# to find the most general numeric format needed.
|
767 |
+
# Then pass through attributes to create key_id for each.
|
768 |
+
graphdata = {
|
769 |
+
k: v
|
770 |
+
for k, v in G.graph.items()
|
771 |
+
if k not in ("node_default", "edge_default")
|
772 |
+
}
|
773 |
+
node_default = G.graph.get("node_default", {})
|
774 |
+
edge_default = G.graph.get("edge_default", {})
|
775 |
+
# Graph attributes
|
776 |
+
for k, v in graphdata.items():
|
777 |
+
self.attribute_types[(str(k), "graph")].add(type(v))
|
778 |
+
for k, v in graphdata.items():
|
779 |
+
element_type = self.get_xml_type(self.attr_type(k, "graph", v))
|
780 |
+
self.get_key(str(k), element_type, "graph", None)
|
781 |
+
# Nodes and data
|
782 |
+
for node, d in G.nodes(data=True):
|
783 |
+
for k, v in d.items():
|
784 |
+
self.attribute_types[(str(k), "node")].add(type(v))
|
785 |
+
for node, d in G.nodes(data=True):
|
786 |
+
for k, v in d.items():
|
787 |
+
T = self.get_xml_type(self.attr_type(k, "node", v))
|
788 |
+
self.get_key(str(k), T, "node", node_default.get(k))
|
789 |
+
# Edges and data
|
790 |
+
if G.is_multigraph():
|
791 |
+
for u, v, ekey, d in G.edges(keys=True, data=True):
|
792 |
+
for k, v in d.items():
|
793 |
+
self.attribute_types[(str(k), "edge")].add(type(v))
|
794 |
+
for u, v, ekey, d in G.edges(keys=True, data=True):
|
795 |
+
for k, v in d.items():
|
796 |
+
T = self.get_xml_type(self.attr_type(k, "edge", v))
|
797 |
+
self.get_key(str(k), T, "edge", edge_default.get(k))
|
798 |
+
else:
|
799 |
+
for u, v, d in G.edges(data=True):
|
800 |
+
for k, v in d.items():
|
801 |
+
self.attribute_types[(str(k), "edge")].add(type(v))
|
802 |
+
for u, v, d in G.edges(data=True):
|
803 |
+
for k, v in d.items():
|
804 |
+
T = self.get_xml_type(self.attr_type(k, "edge", v))
|
805 |
+
self.get_key(str(k), T, "edge", edge_default.get(k))
|
806 |
+
|
807 |
+
# Now add attribute keys to the xml file
|
808 |
+
for key in self.xml:
|
809 |
+
self._xml.write(key, pretty_print=self._prettyprint)
|
810 |
+
|
811 |
+
# The incremental_writer writes each node/edge as it is created
|
812 |
+
incremental_writer = IncrementalElement(self._xml, self._prettyprint)
|
813 |
+
with graph_element:
|
814 |
+
self.add_attributes("graph", incremental_writer, graphdata, {})
|
815 |
+
self.add_nodes(G, incremental_writer) # adds attributes too
|
816 |
+
self.add_edges(G, incremental_writer) # adds attributes too
|
817 |
+
|
818 |
+
def add_attributes(self, scope, xml_obj, data, default):
|
819 |
+
"""Appends attribute data."""
|
820 |
+
for k, v in data.items():
|
821 |
+
data_element = self.add_data(
|
822 |
+
str(k), self.attr_type(str(k), scope, v), str(v), scope, default.get(k)
|
823 |
+
)
|
824 |
+
xml_obj.append(data_element)
|
825 |
+
|
826 |
+
def __str__(self):
|
827 |
+
return object.__str__(self)
|
828 |
+
|
829 |
+
def dump(self, stream=None):
|
830 |
+
self._graphml.__exit__(None, None, None)
|
831 |
+
self._xml_base.__exit__(None, None, None)
|
832 |
+
|
833 |
+
|
834 |
+
# default is lxml is present.
|
835 |
+
write_graphml = write_graphml_lxml
|
836 |
+
|
837 |
+
|
838 |
+
class GraphMLReader(GraphML):
|
839 |
+
"""Read a GraphML document. Produces NetworkX graph objects."""
|
840 |
+
|
841 |
+
def __init__(self, node_type=str, edge_key_type=int, force_multigraph=False):
|
842 |
+
self.construct_types()
|
843 |
+
self.node_type = node_type
|
844 |
+
self.edge_key_type = edge_key_type
|
845 |
+
self.multigraph = force_multigraph # If False, test for multiedges
|
846 |
+
self.edge_ids = {} # dict mapping (u,v) tuples to edge id attributes
|
847 |
+
|
848 |
+
def __call__(self, path=None, string=None):
|
849 |
+
from xml.etree.ElementTree import ElementTree, fromstring
|
850 |
+
|
851 |
+
if path is not None:
|
852 |
+
self.xml = ElementTree(file=path)
|
853 |
+
elif string is not None:
|
854 |
+
self.xml = fromstring(string)
|
855 |
+
else:
|
856 |
+
raise ValueError("Must specify either 'path' or 'string' as kwarg")
|
857 |
+
(keys, defaults) = self.find_graphml_keys(self.xml)
|
858 |
+
for g in self.xml.findall(f"{{{self.NS_GRAPHML}}}graph"):
|
859 |
+
yield self.make_graph(g, keys, defaults)
|
860 |
+
|
861 |
+
def make_graph(self, graph_xml, graphml_keys, defaults, G=None):
|
862 |
+
# set default graph type
|
863 |
+
edgedefault = graph_xml.get("edgedefault", None)
|
864 |
+
if G is None:
|
865 |
+
if edgedefault == "directed":
|
866 |
+
G = nx.MultiDiGraph()
|
867 |
+
else:
|
868 |
+
G = nx.MultiGraph()
|
869 |
+
# set defaults for graph attributes
|
870 |
+
G.graph["node_default"] = {}
|
871 |
+
G.graph["edge_default"] = {}
|
872 |
+
for key_id, value in defaults.items():
|
873 |
+
key_for = graphml_keys[key_id]["for"]
|
874 |
+
name = graphml_keys[key_id]["name"]
|
875 |
+
python_type = graphml_keys[key_id]["type"]
|
876 |
+
if key_for == "node":
|
877 |
+
G.graph["node_default"].update({name: python_type(value)})
|
878 |
+
if key_for == "edge":
|
879 |
+
G.graph["edge_default"].update({name: python_type(value)})
|
880 |
+
# hyperedges are not supported
|
881 |
+
hyperedge = graph_xml.find(f"{{{self.NS_GRAPHML}}}hyperedge")
|
882 |
+
if hyperedge is not None:
|
883 |
+
raise nx.NetworkXError("GraphML reader doesn't support hyperedges")
|
884 |
+
# add nodes
|
885 |
+
for node_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}node"):
|
886 |
+
self.add_node(G, node_xml, graphml_keys, defaults)
|
887 |
+
# add edges
|
888 |
+
for edge_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}edge"):
|
889 |
+
self.add_edge(G, edge_xml, graphml_keys)
|
890 |
+
# add graph data
|
891 |
+
data = self.decode_data_elements(graphml_keys, graph_xml)
|
892 |
+
G.graph.update(data)
|
893 |
+
|
894 |
+
# switch to Graph or DiGraph if no parallel edges were found
|
895 |
+
if self.multigraph:
|
896 |
+
return G
|
897 |
+
|
898 |
+
G = nx.DiGraph(G) if G.is_directed() else nx.Graph(G)
|
899 |
+
# add explicit edge "id" from file as attribute in NX graph.
|
900 |
+
nx.set_edge_attributes(G, values=self.edge_ids, name="id")
|
901 |
+
return G
|
902 |
+
|
903 |
+
def add_node(self, G, node_xml, graphml_keys, defaults):
|
904 |
+
"""Add a node to the graph."""
|
905 |
+
# warn on finding unsupported ports tag
|
906 |
+
ports = node_xml.find(f"{{{self.NS_GRAPHML}}}port")
|
907 |
+
if ports is not None:
|
908 |
+
warnings.warn("GraphML port tag not supported.")
|
909 |
+
# find the node by id and cast it to the appropriate type
|
910 |
+
node_id = self.node_type(node_xml.get("id"))
|
911 |
+
# get data/attributes for node
|
912 |
+
data = self.decode_data_elements(graphml_keys, node_xml)
|
913 |
+
G.add_node(node_id, **data)
|
914 |
+
# get child nodes
|
915 |
+
if node_xml.attrib.get("yfiles.foldertype") == "group":
|
916 |
+
graph_xml = node_xml.find(f"{{{self.NS_GRAPHML}}}graph")
|
917 |
+
self.make_graph(graph_xml, graphml_keys, defaults, G)
|
918 |
+
|
919 |
+
def add_edge(self, G, edge_element, graphml_keys):
|
920 |
+
"""Add an edge to the graph."""
|
921 |
+
# warn on finding unsupported ports tag
|
922 |
+
ports = edge_element.find(f"{{{self.NS_GRAPHML}}}port")
|
923 |
+
if ports is not None:
|
924 |
+
warnings.warn("GraphML port tag not supported.")
|
925 |
+
|
926 |
+
# raise error if we find mixed directed and undirected edges
|
927 |
+
directed = edge_element.get("directed")
|
928 |
+
if G.is_directed() and directed == "false":
|
929 |
+
msg = "directed=false edge found in directed graph."
|
930 |
+
raise nx.NetworkXError(msg)
|
931 |
+
if (not G.is_directed()) and directed == "true":
|
932 |
+
msg = "directed=true edge found in undirected graph."
|
933 |
+
raise nx.NetworkXError(msg)
|
934 |
+
|
935 |
+
source = self.node_type(edge_element.get("source"))
|
936 |
+
target = self.node_type(edge_element.get("target"))
|
937 |
+
data = self.decode_data_elements(graphml_keys, edge_element)
|
938 |
+
# GraphML stores edge ids as an attribute
|
939 |
+
# NetworkX uses them as keys in multigraphs too if no key
|
940 |
+
# attribute is specified
|
941 |
+
edge_id = edge_element.get("id")
|
942 |
+
if edge_id:
|
943 |
+
# self.edge_ids is used by `make_graph` method for non-multigraphs
|
944 |
+
self.edge_ids[source, target] = edge_id
|
945 |
+
try:
|
946 |
+
edge_id = self.edge_key_type(edge_id)
|
947 |
+
except ValueError: # Could not convert.
|
948 |
+
pass
|
949 |
+
else:
|
950 |
+
edge_id = data.get("key")
|
951 |
+
|
952 |
+
if G.has_edge(source, target):
|
953 |
+
# mark this as a multigraph
|
954 |
+
self.multigraph = True
|
955 |
+
|
956 |
+
# Use add_edges_from to avoid error with add_edge when `'key' in data`
|
957 |
+
# Note there is only one edge here...
|
958 |
+
G.add_edges_from([(source, target, edge_id, data)])
|
959 |
+
|
960 |
+
def decode_data_elements(self, graphml_keys, obj_xml):
|
961 |
+
"""Use the key information to decode the data XML if present."""
|
962 |
+
data = {}
|
963 |
+
for data_element in obj_xml.findall(f"{{{self.NS_GRAPHML}}}data"):
|
964 |
+
key = data_element.get("key")
|
965 |
+
try:
|
966 |
+
data_name = graphml_keys[key]["name"]
|
967 |
+
data_type = graphml_keys[key]["type"]
|
968 |
+
except KeyError as err:
|
969 |
+
raise nx.NetworkXError(f"Bad GraphML data: no key {key}") from err
|
970 |
+
text = data_element.text
|
971 |
+
# assume anything with subelements is a yfiles extension
|
972 |
+
if text is not None and len(list(data_element)) == 0:
|
973 |
+
if data_type == bool:
|
974 |
+
# Ignore cases.
|
975 |
+
# http://docs.oracle.com/javase/6/docs/api/java/lang/
|
976 |
+
# Boolean.html#parseBoolean%28java.lang.String%29
|
977 |
+
data[data_name] = self.convert_bool[text.lower()]
|
978 |
+
else:
|
979 |
+
data[data_name] = data_type(text)
|
980 |
+
elif len(list(data_element)) > 0:
|
981 |
+
# Assume yfiles as subelements, try to extract node_label
|
982 |
+
node_label = None
|
983 |
+
# set GenericNode's configuration as shape type
|
984 |
+
gn = data_element.find(f"{{{self.NS_Y}}}GenericNode")
|
985 |
+
if gn is not None:
|
986 |
+
data["shape_type"] = gn.get("configuration")
|
987 |
+
for node_type in ["GenericNode", "ShapeNode", "SVGNode", "ImageNode"]:
|
988 |
+
pref = f"{{{self.NS_Y}}}{node_type}/{{{self.NS_Y}}}"
|
989 |
+
geometry = data_element.find(f"{pref}Geometry")
|
990 |
+
if geometry is not None:
|
991 |
+
data["x"] = geometry.get("x")
|
992 |
+
data["y"] = geometry.get("y")
|
993 |
+
if node_label is None:
|
994 |
+
node_label = data_element.find(f"{pref}NodeLabel")
|
995 |
+
shape = data_element.find(f"{pref}Shape")
|
996 |
+
if shape is not None:
|
997 |
+
data["shape_type"] = shape.get("type")
|
998 |
+
if node_label is not None:
|
999 |
+
data["label"] = node_label.text
|
1000 |
+
|
1001 |
+
# check all the different types of edges available in yEd.
|
1002 |
+
for edge_type in [
|
1003 |
+
"PolyLineEdge",
|
1004 |
+
"SplineEdge",
|
1005 |
+
"QuadCurveEdge",
|
1006 |
+
"BezierEdge",
|
1007 |
+
"ArcEdge",
|
1008 |
+
]:
|
1009 |
+
pref = f"{{{self.NS_Y}}}{edge_type}/{{{self.NS_Y}}}"
|
1010 |
+
edge_label = data_element.find(f"{pref}EdgeLabel")
|
1011 |
+
if edge_label is not None:
|
1012 |
+
break
|
1013 |
+
if edge_label is not None:
|
1014 |
+
data["label"] = edge_label.text
|
1015 |
+
elif text is None:
|
1016 |
+
data[data_name] = ""
|
1017 |
+
return data
|
1018 |
+
|
1019 |
+
def find_graphml_keys(self, graph_element):
|
1020 |
+
"""Extracts all the keys and key defaults from the xml."""
|
1021 |
+
graphml_keys = {}
|
1022 |
+
graphml_key_defaults = {}
|
1023 |
+
for k in graph_element.findall(f"{{{self.NS_GRAPHML}}}key"):
|
1024 |
+
attr_id = k.get("id")
|
1025 |
+
attr_type = k.get("attr.type")
|
1026 |
+
attr_name = k.get("attr.name")
|
1027 |
+
yfiles_type = k.get("yfiles.type")
|
1028 |
+
if yfiles_type is not None:
|
1029 |
+
attr_name = yfiles_type
|
1030 |
+
attr_type = "yfiles"
|
1031 |
+
if attr_type is None:
|
1032 |
+
attr_type = "string"
|
1033 |
+
warnings.warn(f"No key type for id {attr_id}. Using string")
|
1034 |
+
if attr_name is None:
|
1035 |
+
raise nx.NetworkXError(f"Unknown key for id {attr_id}.")
|
1036 |
+
graphml_keys[attr_id] = {
|
1037 |
+
"name": attr_name,
|
1038 |
+
"type": self.python_type[attr_type],
|
1039 |
+
"for": k.get("for"),
|
1040 |
+
}
|
1041 |
+
# check for "default" sub-element of key element
|
1042 |
+
default = k.find(f"{{{self.NS_GRAPHML}}}default")
|
1043 |
+
if default is not None:
|
1044 |
+
# Handle default values identically to data element values
|
1045 |
+
python_type = graphml_keys[attr_id]["type"]
|
1046 |
+
if python_type == bool:
|
1047 |
+
graphml_key_defaults[attr_id] = self.convert_bool[
|
1048 |
+
default.text.lower()
|
1049 |
+
]
|
1050 |
+
else:
|
1051 |
+
graphml_key_defaults[attr_id] = python_type(default.text)
|
1052 |
+
return graphml_keys, graphml_key_defaults
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/__init__.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
*********
|
3 |
+
JSON data
|
4 |
+
*********
|
5 |
+
Generate and parse JSON serializable data for NetworkX graphs.
|
6 |
+
|
7 |
+
These formats are suitable for use with the d3.js examples https://d3js.org/
|
8 |
+
|
9 |
+
The three formats that you can generate with NetworkX are:
|
10 |
+
|
11 |
+
- node-link like in the d3.js example https://bl.ocks.org/mbostock/4062045
|
12 |
+
- tree like in the d3.js example https://bl.ocks.org/mbostock/4063550
|
13 |
+
- adjacency like in the d3.js example https://bost.ocks.org/mike/miserables/
|
14 |
+
"""
|
15 |
+
from networkx.readwrite.json_graph.node_link import *
|
16 |
+
from networkx.readwrite.json_graph.adjacency import *
|
17 |
+
from networkx.readwrite.json_graph.tree import *
|
18 |
+
from networkx.readwrite.json_graph.cytoscape import *
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/adjacency.cpython-310.pyc
ADDED
Binary file (4.15 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/__pycache__/cytoscape.cpython-310.pyc
ADDED
Binary file (4.87 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/adjacency.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
|
3 |
+
__all__ = ["adjacency_data", "adjacency_graph"]
|
4 |
+
|
5 |
+
_attrs = {"id": "id", "key": "key"}
|
6 |
+
|
7 |
+
|
8 |
+
def adjacency_data(G, attrs=_attrs):
|
9 |
+
"""Returns data in adjacency format that is suitable for JSON serialization
|
10 |
+
and use in JavaScript documents.
|
11 |
+
|
12 |
+
Parameters
|
13 |
+
----------
|
14 |
+
G : NetworkX graph
|
15 |
+
|
16 |
+
attrs : dict
|
17 |
+
A dictionary that contains two keys 'id' and 'key'. The corresponding
|
18 |
+
values provide the attribute names for storing NetworkX-internal graph
|
19 |
+
data. The values should be unique. Default value:
|
20 |
+
:samp:`dict(id='id', key='key')`.
|
21 |
+
|
22 |
+
If some user-defined graph data use these attribute names as data keys,
|
23 |
+
they may be silently dropped.
|
24 |
+
|
25 |
+
Returns
|
26 |
+
-------
|
27 |
+
data : dict
|
28 |
+
A dictionary with adjacency formatted data.
|
29 |
+
|
30 |
+
Raises
|
31 |
+
------
|
32 |
+
NetworkXError
|
33 |
+
If values in attrs are not unique.
|
34 |
+
|
35 |
+
Examples
|
36 |
+
--------
|
37 |
+
>>> from networkx.readwrite import json_graph
|
38 |
+
>>> G = nx.Graph([(1, 2)])
|
39 |
+
>>> data = json_graph.adjacency_data(G)
|
40 |
+
|
41 |
+
To serialize with json
|
42 |
+
|
43 |
+
>>> import json
|
44 |
+
>>> s = json.dumps(data)
|
45 |
+
|
46 |
+
Notes
|
47 |
+
-----
|
48 |
+
Graph, node, and link attributes will be written when using this format
|
49 |
+
but attribute keys must be strings if you want to serialize the resulting
|
50 |
+
data with JSON.
|
51 |
+
|
52 |
+
The default value of attrs will be changed in a future release of NetworkX.
|
53 |
+
|
54 |
+
See Also
|
55 |
+
--------
|
56 |
+
adjacency_graph, node_link_data, tree_data
|
57 |
+
"""
|
58 |
+
multigraph = G.is_multigraph()
|
59 |
+
id_ = attrs["id"]
|
60 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
61 |
+
key = None if not multigraph else attrs["key"]
|
62 |
+
if id_ == key:
|
63 |
+
raise nx.NetworkXError("Attribute names are not unique.")
|
64 |
+
data = {}
|
65 |
+
data["directed"] = G.is_directed()
|
66 |
+
data["multigraph"] = multigraph
|
67 |
+
data["graph"] = list(G.graph.items())
|
68 |
+
data["nodes"] = []
|
69 |
+
data["adjacency"] = []
|
70 |
+
for n, nbrdict in G.adjacency():
|
71 |
+
data["nodes"].append({**G.nodes[n], id_: n})
|
72 |
+
adj = []
|
73 |
+
if multigraph:
|
74 |
+
for nbr, keys in nbrdict.items():
|
75 |
+
for k, d in keys.items():
|
76 |
+
adj.append({**d, id_: nbr, key: k})
|
77 |
+
else:
|
78 |
+
for nbr, d in nbrdict.items():
|
79 |
+
adj.append({**d, id_: nbr})
|
80 |
+
data["adjacency"].append(adj)
|
81 |
+
return data
|
82 |
+
|
83 |
+
|
84 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
85 |
+
def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
|
86 |
+
"""Returns graph from adjacency data format.
|
87 |
+
|
88 |
+
Parameters
|
89 |
+
----------
|
90 |
+
data : dict
|
91 |
+
Adjacency list formatted graph data
|
92 |
+
|
93 |
+
directed : bool
|
94 |
+
If True, and direction not specified in data, return a directed graph.
|
95 |
+
|
96 |
+
multigraph : bool
|
97 |
+
If True, and multigraph not specified in data, return a multigraph.
|
98 |
+
|
99 |
+
attrs : dict
|
100 |
+
A dictionary that contains two keys 'id' and 'key'. The corresponding
|
101 |
+
values provide the attribute names for storing NetworkX-internal graph
|
102 |
+
data. The values should be unique. Default value:
|
103 |
+
:samp:`dict(id='id', key='key')`.
|
104 |
+
|
105 |
+
Returns
|
106 |
+
-------
|
107 |
+
G : NetworkX graph
|
108 |
+
A NetworkX graph object
|
109 |
+
|
110 |
+
Examples
|
111 |
+
--------
|
112 |
+
>>> from networkx.readwrite import json_graph
|
113 |
+
>>> G = nx.Graph([(1, 2)])
|
114 |
+
>>> data = json_graph.adjacency_data(G)
|
115 |
+
>>> H = json_graph.adjacency_graph(data)
|
116 |
+
|
117 |
+
Notes
|
118 |
+
-----
|
119 |
+
The default value of attrs will be changed in a future release of NetworkX.
|
120 |
+
|
121 |
+
See Also
|
122 |
+
--------
|
123 |
+
adjacency_graph, node_link_data, tree_data
|
124 |
+
"""
|
125 |
+
multigraph = data.get("multigraph", multigraph)
|
126 |
+
directed = data.get("directed", directed)
|
127 |
+
if multigraph:
|
128 |
+
graph = nx.MultiGraph()
|
129 |
+
else:
|
130 |
+
graph = nx.Graph()
|
131 |
+
if directed:
|
132 |
+
graph = graph.to_directed()
|
133 |
+
id_ = attrs["id"]
|
134 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
135 |
+
key = None if not multigraph else attrs["key"]
|
136 |
+
graph.graph = dict(data.get("graph", []))
|
137 |
+
mapping = []
|
138 |
+
for d in data["nodes"]:
|
139 |
+
node_data = d.copy()
|
140 |
+
node = node_data.pop(id_)
|
141 |
+
mapping.append(node)
|
142 |
+
graph.add_node(node)
|
143 |
+
graph.nodes[node].update(node_data)
|
144 |
+
for i, d in enumerate(data["adjacency"]):
|
145 |
+
source = mapping[i]
|
146 |
+
for tdata in d:
|
147 |
+
target_data = tdata.copy()
|
148 |
+
target = target_data.pop(id_)
|
149 |
+
if not multigraph:
|
150 |
+
graph.add_edge(source, target)
|
151 |
+
graph[source][target].update(target_data)
|
152 |
+
else:
|
153 |
+
ky = target_data.pop(key, None)
|
154 |
+
graph.add_edge(source, target, key=ky)
|
155 |
+
graph[source][target][ky].update(target_data)
|
156 |
+
return graph
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/cytoscape.py
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
|
3 |
+
__all__ = ["cytoscape_data", "cytoscape_graph"]
|
4 |
+
|
5 |
+
|
6 |
+
def cytoscape_data(G, name="name", ident="id"):
|
7 |
+
"""Returns data in Cytoscape JSON format (cyjs).
|
8 |
+
|
9 |
+
Parameters
|
10 |
+
----------
|
11 |
+
G : NetworkX Graph
|
12 |
+
The graph to convert to cytoscape format
|
13 |
+
name : string
|
14 |
+
A string which is mapped to the 'name' node element in cyjs format.
|
15 |
+
Must not have the same value as `ident`.
|
16 |
+
ident : string
|
17 |
+
A string which is mapped to the 'id' node element in cyjs format.
|
18 |
+
Must not have the same value as `name`.
|
19 |
+
|
20 |
+
Returns
|
21 |
+
-------
|
22 |
+
data: dict
|
23 |
+
A dictionary with cyjs formatted data.
|
24 |
+
|
25 |
+
Raises
|
26 |
+
------
|
27 |
+
NetworkXError
|
28 |
+
If the values for `name` and `ident` are identical.
|
29 |
+
|
30 |
+
See Also
|
31 |
+
--------
|
32 |
+
cytoscape_graph: convert a dictionary in cyjs format to a graph
|
33 |
+
|
34 |
+
References
|
35 |
+
----------
|
36 |
+
.. [1] Cytoscape user's manual:
|
37 |
+
http://manual.cytoscape.org/en/stable/index.html
|
38 |
+
|
39 |
+
Examples
|
40 |
+
--------
|
41 |
+
>>> G = nx.path_graph(2)
|
42 |
+
>>> nx.cytoscape_data(G) # doctest: +SKIP
|
43 |
+
{'data': [],
|
44 |
+
'directed': False,
|
45 |
+
'multigraph': False,
|
46 |
+
'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
|
47 |
+
{'data': {'id': '1', 'value': 1, 'name': '1'}}],
|
48 |
+
'edges': [{'data': {'source': 0, 'target': 1}}]}}
|
49 |
+
"""
|
50 |
+
if name == ident:
|
51 |
+
raise nx.NetworkXError("name and ident must be different.")
|
52 |
+
|
53 |
+
jsondata = {"data": list(G.graph.items())}
|
54 |
+
jsondata["directed"] = G.is_directed()
|
55 |
+
jsondata["multigraph"] = G.is_multigraph()
|
56 |
+
jsondata["elements"] = {"nodes": [], "edges": []}
|
57 |
+
nodes = jsondata["elements"]["nodes"]
|
58 |
+
edges = jsondata["elements"]["edges"]
|
59 |
+
|
60 |
+
for i, j in G.nodes.items():
|
61 |
+
n = {"data": j.copy()}
|
62 |
+
n["data"]["id"] = j.get(ident) or str(i)
|
63 |
+
n["data"]["value"] = i
|
64 |
+
n["data"]["name"] = j.get(name) or str(i)
|
65 |
+
nodes.append(n)
|
66 |
+
|
67 |
+
if G.is_multigraph():
|
68 |
+
for e in G.edges(keys=True):
|
69 |
+
n = {"data": G.adj[e[0]][e[1]][e[2]].copy()}
|
70 |
+
n["data"]["source"] = e[0]
|
71 |
+
n["data"]["target"] = e[1]
|
72 |
+
n["data"]["key"] = e[2]
|
73 |
+
edges.append(n)
|
74 |
+
else:
|
75 |
+
for e in G.edges():
|
76 |
+
n = {"data": G.adj[e[0]][e[1]].copy()}
|
77 |
+
n["data"]["source"] = e[0]
|
78 |
+
n["data"]["target"] = e[1]
|
79 |
+
edges.append(n)
|
80 |
+
return jsondata
|
81 |
+
|
82 |
+
|
83 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
84 |
+
def cytoscape_graph(data, name="name", ident="id"):
|
85 |
+
"""
|
86 |
+
Create a NetworkX graph from a dictionary in cytoscape JSON format.
|
87 |
+
|
88 |
+
Parameters
|
89 |
+
----------
|
90 |
+
data : dict
|
91 |
+
A dictionary of data conforming to cytoscape JSON format.
|
92 |
+
name : string
|
93 |
+
A string which is mapped to the 'name' node element in cyjs format.
|
94 |
+
Must not have the same value as `ident`.
|
95 |
+
ident : string
|
96 |
+
A string which is mapped to the 'id' node element in cyjs format.
|
97 |
+
Must not have the same value as `name`.
|
98 |
+
|
99 |
+
Returns
|
100 |
+
-------
|
101 |
+
graph : a NetworkX graph instance
|
102 |
+
The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or
|
103 |
+
`MultiDiGraph` depending on the input data.
|
104 |
+
|
105 |
+
Raises
|
106 |
+
------
|
107 |
+
NetworkXError
|
108 |
+
If the `name` and `ident` attributes are identical.
|
109 |
+
|
110 |
+
See Also
|
111 |
+
--------
|
112 |
+
cytoscape_data: convert a NetworkX graph to a dict in cyjs format
|
113 |
+
|
114 |
+
References
|
115 |
+
----------
|
116 |
+
.. [1] Cytoscape user's manual:
|
117 |
+
http://manual.cytoscape.org/en/stable/index.html
|
118 |
+
|
119 |
+
Examples
|
120 |
+
--------
|
121 |
+
>>> data_dict = {
|
122 |
+
... "data": [],
|
123 |
+
... "directed": False,
|
124 |
+
... "multigraph": False,
|
125 |
+
... "elements": {
|
126 |
+
... "nodes": [
|
127 |
+
... {"data": {"id": "0", "value": 0, "name": "0"}},
|
128 |
+
... {"data": {"id": "1", "value": 1, "name": "1"}},
|
129 |
+
... ],
|
130 |
+
... "edges": [{"data": {"source": 0, "target": 1}}],
|
131 |
+
... },
|
132 |
+
... }
|
133 |
+
>>> G = nx.cytoscape_graph(data_dict)
|
134 |
+
>>> G.name
|
135 |
+
''
|
136 |
+
>>> G.nodes()
|
137 |
+
NodeView((0, 1))
|
138 |
+
>>> G.nodes(data=True)[0]
|
139 |
+
{'id': '0', 'value': 0, 'name': '0'}
|
140 |
+
>>> G.edges(data=True)
|
141 |
+
EdgeDataView([(0, 1, {'source': 0, 'target': 1})])
|
142 |
+
"""
|
143 |
+
if name == ident:
|
144 |
+
raise nx.NetworkXError("name and ident must be different.")
|
145 |
+
|
146 |
+
multigraph = data.get("multigraph")
|
147 |
+
directed = data.get("directed")
|
148 |
+
if multigraph:
|
149 |
+
graph = nx.MultiGraph()
|
150 |
+
else:
|
151 |
+
graph = nx.Graph()
|
152 |
+
if directed:
|
153 |
+
graph = graph.to_directed()
|
154 |
+
graph.graph = dict(data.get("data"))
|
155 |
+
for d in data["elements"]["nodes"]:
|
156 |
+
node_data = d["data"].copy()
|
157 |
+
node = d["data"]["value"]
|
158 |
+
|
159 |
+
if d["data"].get(name):
|
160 |
+
node_data[name] = d["data"].get(name)
|
161 |
+
if d["data"].get(ident):
|
162 |
+
node_data[ident] = d["data"].get(ident)
|
163 |
+
|
164 |
+
graph.add_node(node)
|
165 |
+
graph.nodes[node].update(node_data)
|
166 |
+
|
167 |
+
for d in data["elements"]["edges"]:
|
168 |
+
edge_data = d["data"].copy()
|
169 |
+
sour = d["data"]["source"]
|
170 |
+
targ = d["data"]["target"]
|
171 |
+
if multigraph:
|
172 |
+
key = d["data"].get("key", 0)
|
173 |
+
graph.add_edge(sour, targ, key=key)
|
174 |
+
graph.edges[sour, targ, key].update(edge_data)
|
175 |
+
else:
|
176 |
+
graph.add_edge(sour, targ)
|
177 |
+
graph.edges[sour, targ].update(edge_data)
|
178 |
+
return graph
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/node_link.py
ADDED
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import chain, count
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
__all__ = ["node_link_data", "node_link_graph"]
|
6 |
+
|
7 |
+
|
8 |
+
_attrs = {
|
9 |
+
"source": "source",
|
10 |
+
"target": "target",
|
11 |
+
"name": "id",
|
12 |
+
"key": "key",
|
13 |
+
"link": "links",
|
14 |
+
}
|
15 |
+
|
16 |
+
|
17 |
+
def _to_tuple(x):
|
18 |
+
"""Converts lists to tuples, including nested lists.
|
19 |
+
|
20 |
+
All other non-list inputs are passed through unmodified. This function is
|
21 |
+
intended to be used to convert potentially nested lists from json files
|
22 |
+
into valid nodes.
|
23 |
+
|
24 |
+
Examples
|
25 |
+
--------
|
26 |
+
>>> _to_tuple([1, 2, [3, 4]])
|
27 |
+
(1, 2, (3, 4))
|
28 |
+
"""
|
29 |
+
if not isinstance(x, tuple | list):
|
30 |
+
return x
|
31 |
+
return tuple(map(_to_tuple, x))
|
32 |
+
|
33 |
+
|
34 |
+
def node_link_data(
|
35 |
+
G,
|
36 |
+
*,
|
37 |
+
source="source",
|
38 |
+
target="target",
|
39 |
+
name="id",
|
40 |
+
key="key",
|
41 |
+
link="links",
|
42 |
+
):
|
43 |
+
"""Returns data in node-link format that is suitable for JSON serialization
|
44 |
+
and use in JavaScript documents.
|
45 |
+
|
46 |
+
Parameters
|
47 |
+
----------
|
48 |
+
G : NetworkX graph
|
49 |
+
source : string
|
50 |
+
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
|
51 |
+
target : string
|
52 |
+
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
|
53 |
+
name : string
|
54 |
+
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
|
55 |
+
key : string
|
56 |
+
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
|
57 |
+
link : string
|
58 |
+
A string that provides the 'link' attribute name for storing NetworkX-internal graph data.
|
59 |
+
|
60 |
+
Returns
|
61 |
+
-------
|
62 |
+
data : dict
|
63 |
+
A dictionary with node-link formatted data.
|
64 |
+
|
65 |
+
Raises
|
66 |
+
------
|
67 |
+
NetworkXError
|
68 |
+
If the values of 'source', 'target' and 'key' are not unique.
|
69 |
+
|
70 |
+
Examples
|
71 |
+
--------
|
72 |
+
>>> G = nx.Graph([("A", "B")])
|
73 |
+
>>> data1 = nx.node_link_data(G)
|
74 |
+
>>> data1
|
75 |
+
{'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]}
|
76 |
+
|
77 |
+
To serialize with JSON
|
78 |
+
|
79 |
+
>>> import json
|
80 |
+
>>> s1 = json.dumps(data1)
|
81 |
+
>>> s1
|
82 |
+
'{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
|
83 |
+
|
84 |
+
A graph can also be serialized by passing `node_link_data` as an encoder function. The two methods are equivalent.
|
85 |
+
|
86 |
+
>>> s1 = json.dumps(G, default=nx.node_link_data)
|
87 |
+
>>> s1
|
88 |
+
'{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
|
89 |
+
|
90 |
+
The attribute names for storing NetworkX-internal graph data can
|
91 |
+
be specified as keyword options.
|
92 |
+
|
93 |
+
>>> H = nx.gn_graph(2)
|
94 |
+
>>> data2 = nx.node_link_data(H, link="edges", source="from", target="to")
|
95 |
+
>>> data2
|
96 |
+
{'directed': True, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 0}, {'id': 1}], 'edges': [{'from': 1, 'to': 0}]}
|
97 |
+
|
98 |
+
Notes
|
99 |
+
-----
|
100 |
+
Graph, node, and link attributes are stored in this format. Note that
|
101 |
+
attribute keys will be converted to strings in order to comply with JSON.
|
102 |
+
|
103 |
+
Attribute 'key' is only used for multigraphs.
|
104 |
+
|
105 |
+
To use `node_link_data` in conjunction with `node_link_graph`,
|
106 |
+
the keyword names for the attributes must match.
|
107 |
+
|
108 |
+
|
109 |
+
See Also
|
110 |
+
--------
|
111 |
+
node_link_graph, adjacency_data, tree_data
|
112 |
+
"""
|
113 |
+
multigraph = G.is_multigraph()
|
114 |
+
|
115 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
116 |
+
key = None if not multigraph else key
|
117 |
+
if len({source, target, key}) < 3:
|
118 |
+
raise nx.NetworkXError("Attribute names are not unique.")
|
119 |
+
data = {
|
120 |
+
"directed": G.is_directed(),
|
121 |
+
"multigraph": multigraph,
|
122 |
+
"graph": G.graph,
|
123 |
+
"nodes": [{**G.nodes[n], name: n} for n in G],
|
124 |
+
}
|
125 |
+
if multigraph:
|
126 |
+
data[link] = [
|
127 |
+
{**d, source: u, target: v, key: k}
|
128 |
+
for u, v, k, d in G.edges(keys=True, data=True)
|
129 |
+
]
|
130 |
+
else:
|
131 |
+
data[link] = [{**d, source: u, target: v} for u, v, d in G.edges(data=True)]
|
132 |
+
return data
|
133 |
+
|
134 |
+
|
135 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
136 |
+
def node_link_graph(
|
137 |
+
data,
|
138 |
+
directed=False,
|
139 |
+
multigraph=True,
|
140 |
+
*,
|
141 |
+
source="source",
|
142 |
+
target="target",
|
143 |
+
name="id",
|
144 |
+
key="key",
|
145 |
+
link="links",
|
146 |
+
):
|
147 |
+
"""Returns graph from node-link data format.
|
148 |
+
Useful for de-serialization from JSON.
|
149 |
+
|
150 |
+
Parameters
|
151 |
+
----------
|
152 |
+
data : dict
|
153 |
+
node-link formatted graph data
|
154 |
+
|
155 |
+
directed : bool
|
156 |
+
If True, and direction not specified in data, return a directed graph.
|
157 |
+
|
158 |
+
multigraph : bool
|
159 |
+
If True, and multigraph not specified in data, return a multigraph.
|
160 |
+
|
161 |
+
source : string
|
162 |
+
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
|
163 |
+
target : string
|
164 |
+
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
|
165 |
+
name : string
|
166 |
+
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
|
167 |
+
key : string
|
168 |
+
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
|
169 |
+
link : string
|
170 |
+
A string that provides the 'link' attribute name for storing NetworkX-internal graph data.
|
171 |
+
|
172 |
+
Returns
|
173 |
+
-------
|
174 |
+
G : NetworkX graph
|
175 |
+
A NetworkX graph object
|
176 |
+
|
177 |
+
Examples
|
178 |
+
--------
|
179 |
+
|
180 |
+
Create data in node-link format by converting a graph.
|
181 |
+
|
182 |
+
>>> G = nx.Graph([("A", "B")])
|
183 |
+
>>> data = nx.node_link_data(G)
|
184 |
+
>>> data
|
185 |
+
{'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]}
|
186 |
+
|
187 |
+
Revert data in node-link format to a graph.
|
188 |
+
|
189 |
+
>>> H = nx.node_link_graph(data)
|
190 |
+
>>> print(H.edges)
|
191 |
+
[('A', 'B')]
|
192 |
+
|
193 |
+
To serialize and deserialize a graph with JSON,
|
194 |
+
|
195 |
+
>>> import json
|
196 |
+
>>> d = json.dumps(node_link_data(G))
|
197 |
+
>>> H = node_link_graph(json.loads(d))
|
198 |
+
>>> print(G.edges, H.edges)
|
199 |
+
[('A', 'B')] [('A', 'B')]
|
200 |
+
|
201 |
+
|
202 |
+
Notes
|
203 |
+
-----
|
204 |
+
Attribute 'key' is only used for multigraphs.
|
205 |
+
|
206 |
+
To use `node_link_data` in conjunction with `node_link_graph`,
|
207 |
+
the keyword names for the attributes must match.
|
208 |
+
|
209 |
+
See Also
|
210 |
+
--------
|
211 |
+
node_link_data, adjacency_data, tree_data
|
212 |
+
"""
|
213 |
+
multigraph = data.get("multigraph", multigraph)
|
214 |
+
directed = data.get("directed", directed)
|
215 |
+
if multigraph:
|
216 |
+
graph = nx.MultiGraph()
|
217 |
+
else:
|
218 |
+
graph = nx.Graph()
|
219 |
+
if directed:
|
220 |
+
graph = graph.to_directed()
|
221 |
+
|
222 |
+
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
|
223 |
+
key = None if not multigraph else key
|
224 |
+
graph.graph = data.get("graph", {})
|
225 |
+
c = count()
|
226 |
+
for d in data["nodes"]:
|
227 |
+
node = _to_tuple(d.get(name, next(c)))
|
228 |
+
nodedata = {str(k): v for k, v in d.items() if k != name}
|
229 |
+
graph.add_node(node, **nodedata)
|
230 |
+
for d in data[link]:
|
231 |
+
src = tuple(d[source]) if isinstance(d[source], list) else d[source]
|
232 |
+
tgt = tuple(d[target]) if isinstance(d[target], list) else d[target]
|
233 |
+
if not multigraph:
|
234 |
+
edgedata = {str(k): v for k, v in d.items() if k != source and k != target}
|
235 |
+
graph.add_edge(src, tgt, **edgedata)
|
236 |
+
else:
|
237 |
+
ky = d.get(key, None)
|
238 |
+
edgedata = {
|
239 |
+
str(k): v
|
240 |
+
for k, v in d.items()
|
241 |
+
if k != source and k != target and k != key
|
242 |
+
}
|
243 |
+
graph.add_edge(src, tgt, ky, **edgedata)
|
244 |
+
return graph
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/json_graph/tree.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import chain
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
__all__ = ["tree_data", "tree_graph"]
|
6 |
+
|
7 |
+
|
8 |
+
def tree_data(G, root, ident="id", children="children"):
|
9 |
+
"""Returns data in tree format that is suitable for JSON serialization
|
10 |
+
and use in JavaScript documents.
|
11 |
+
|
12 |
+
Parameters
|
13 |
+
----------
|
14 |
+
G : NetworkX graph
|
15 |
+
G must be an oriented tree
|
16 |
+
|
17 |
+
root : node
|
18 |
+
The root of the tree
|
19 |
+
|
20 |
+
ident : string
|
21 |
+
Attribute name for storing NetworkX-internal graph data. `ident` must
|
22 |
+
have a different value than `children`. The default is 'id'.
|
23 |
+
|
24 |
+
children : string
|
25 |
+
Attribute name for storing NetworkX-internal graph data. `children`
|
26 |
+
must have a different value than `ident`. The default is 'children'.
|
27 |
+
|
28 |
+
Returns
|
29 |
+
-------
|
30 |
+
data : dict
|
31 |
+
A dictionary with node-link formatted data.
|
32 |
+
|
33 |
+
Raises
|
34 |
+
------
|
35 |
+
NetworkXError
|
36 |
+
If `children` and `ident` attributes are identical.
|
37 |
+
|
38 |
+
Examples
|
39 |
+
--------
|
40 |
+
>>> from networkx.readwrite import json_graph
|
41 |
+
>>> G = nx.DiGraph([(1, 2)])
|
42 |
+
>>> data = json_graph.tree_data(G, root=1)
|
43 |
+
|
44 |
+
To serialize with json
|
45 |
+
|
46 |
+
>>> import json
|
47 |
+
>>> s = json.dumps(data)
|
48 |
+
|
49 |
+
Notes
|
50 |
+
-----
|
51 |
+
Node attributes are stored in this format but keys
|
52 |
+
for attributes must be strings if you want to serialize with JSON.
|
53 |
+
|
54 |
+
Graph and edge attributes are not stored.
|
55 |
+
|
56 |
+
See Also
|
57 |
+
--------
|
58 |
+
tree_graph, node_link_data, adjacency_data
|
59 |
+
"""
|
60 |
+
if G.number_of_nodes() != G.number_of_edges() + 1:
|
61 |
+
raise TypeError("G is not a tree.")
|
62 |
+
if not G.is_directed():
|
63 |
+
raise TypeError("G is not directed.")
|
64 |
+
if not nx.is_weakly_connected(G):
|
65 |
+
raise TypeError("G is not weakly connected.")
|
66 |
+
|
67 |
+
if ident == children:
|
68 |
+
raise nx.NetworkXError("The values for `id` and `children` must be different.")
|
69 |
+
|
70 |
+
def add_children(n, G):
|
71 |
+
nbrs = G[n]
|
72 |
+
if len(nbrs) == 0:
|
73 |
+
return []
|
74 |
+
children_ = []
|
75 |
+
for child in nbrs:
|
76 |
+
d = {**G.nodes[child], ident: child}
|
77 |
+
c = add_children(child, G)
|
78 |
+
if c:
|
79 |
+
d[children] = c
|
80 |
+
children_.append(d)
|
81 |
+
return children_
|
82 |
+
|
83 |
+
return {**G.nodes[root], ident: root, children: add_children(root, G)}
|
84 |
+
|
85 |
+
|
86 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
87 |
+
def tree_graph(data, ident="id", children="children"):
|
88 |
+
"""Returns graph from tree data format.
|
89 |
+
|
90 |
+
Parameters
|
91 |
+
----------
|
92 |
+
data : dict
|
93 |
+
Tree formatted graph data
|
94 |
+
|
95 |
+
ident : string
|
96 |
+
Attribute name for storing NetworkX-internal graph data. `ident` must
|
97 |
+
have a different value than `children`. The default is 'id'.
|
98 |
+
|
99 |
+
children : string
|
100 |
+
Attribute name for storing NetworkX-internal graph data. `children`
|
101 |
+
must have a different value than `ident`. The default is 'children'.
|
102 |
+
|
103 |
+
Returns
|
104 |
+
-------
|
105 |
+
G : NetworkX DiGraph
|
106 |
+
|
107 |
+
Examples
|
108 |
+
--------
|
109 |
+
>>> from networkx.readwrite import json_graph
|
110 |
+
>>> G = nx.DiGraph([(1, 2)])
|
111 |
+
>>> data = json_graph.tree_data(G, root=1)
|
112 |
+
>>> H = json_graph.tree_graph(data)
|
113 |
+
|
114 |
+
See Also
|
115 |
+
--------
|
116 |
+
tree_data, node_link_data, adjacency_data
|
117 |
+
"""
|
118 |
+
graph = nx.DiGraph()
|
119 |
+
|
120 |
+
def add_children(parent, children_):
|
121 |
+
for data in children_:
|
122 |
+
child = data[ident]
|
123 |
+
graph.add_edge(parent, child)
|
124 |
+
grandchildren = data.get(children, [])
|
125 |
+
if grandchildren:
|
126 |
+
add_children(child, grandchildren)
|
127 |
+
nodedata = {
|
128 |
+
str(k): v for k, v in data.items() if k != ident and k != children
|
129 |
+
}
|
130 |
+
graph.add_node(child, **nodedata)
|
131 |
+
|
132 |
+
root = data[ident]
|
133 |
+
children_ = data.get(children, [])
|
134 |
+
nodedata = {str(k): v for k, v in data.items() if k != ident and k != children}
|
135 |
+
graph.add_node(root, **nodedata)
|
136 |
+
add_children(root, children_)
|
137 |
+
return graph
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/multiline_adjlist.py
ADDED
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
*************************
|
3 |
+
Multi-line Adjacency List
|
4 |
+
*************************
|
5 |
+
Read and write NetworkX graphs as multi-line adjacency lists.
|
6 |
+
|
7 |
+
The multi-line adjacency list format is useful for graphs with
|
8 |
+
nodes that can be meaningfully represented as strings. With this format
|
9 |
+
simple edge data can be stored but node or graph data is not.
|
10 |
+
|
11 |
+
Format
|
12 |
+
------
|
13 |
+
The first label in a line is the source node label followed by the node degree
|
14 |
+
d. The next d lines are target node labels and optional edge data.
|
15 |
+
That pattern repeats for all nodes in the graph.
|
16 |
+
|
17 |
+
The graph with edges a-b, a-c, d-e can be represented as the following
|
18 |
+
adjacency list (anything following the # in a line is a comment)::
|
19 |
+
|
20 |
+
# example.multiline-adjlist
|
21 |
+
a 2
|
22 |
+
b
|
23 |
+
c
|
24 |
+
d 1
|
25 |
+
e
|
26 |
+
"""
|
27 |
+
|
28 |
+
__all__ = [
|
29 |
+
"generate_multiline_adjlist",
|
30 |
+
"write_multiline_adjlist",
|
31 |
+
"parse_multiline_adjlist",
|
32 |
+
"read_multiline_adjlist",
|
33 |
+
]
|
34 |
+
|
35 |
+
import networkx as nx
|
36 |
+
from networkx.utils import open_file
|
37 |
+
|
38 |
+
|
39 |
+
def generate_multiline_adjlist(G, delimiter=" "):
|
40 |
+
"""Generate a single line of the graph G in multiline adjacency list format.
|
41 |
+
|
42 |
+
Parameters
|
43 |
+
----------
|
44 |
+
G : NetworkX graph
|
45 |
+
|
46 |
+
delimiter : string, optional
|
47 |
+
Separator for node labels
|
48 |
+
|
49 |
+
Returns
|
50 |
+
-------
|
51 |
+
lines : string
|
52 |
+
Lines of data in multiline adjlist format.
|
53 |
+
|
54 |
+
Examples
|
55 |
+
--------
|
56 |
+
>>> G = nx.lollipop_graph(4, 3)
|
57 |
+
>>> for line in nx.generate_multiline_adjlist(G):
|
58 |
+
... print(line)
|
59 |
+
0 3
|
60 |
+
1 {}
|
61 |
+
2 {}
|
62 |
+
3 {}
|
63 |
+
1 2
|
64 |
+
2 {}
|
65 |
+
3 {}
|
66 |
+
2 1
|
67 |
+
3 {}
|
68 |
+
3 1
|
69 |
+
4 {}
|
70 |
+
4 1
|
71 |
+
5 {}
|
72 |
+
5 1
|
73 |
+
6 {}
|
74 |
+
6 0
|
75 |
+
|
76 |
+
See Also
|
77 |
+
--------
|
78 |
+
write_multiline_adjlist, read_multiline_adjlist
|
79 |
+
"""
|
80 |
+
if G.is_directed():
|
81 |
+
if G.is_multigraph():
|
82 |
+
for s, nbrs in G.adjacency():
|
83 |
+
nbr_edges = [
|
84 |
+
(u, data)
|
85 |
+
for u, datadict in nbrs.items()
|
86 |
+
for key, data in datadict.items()
|
87 |
+
]
|
88 |
+
deg = len(nbr_edges)
|
89 |
+
yield str(s) + delimiter + str(deg)
|
90 |
+
for u, d in nbr_edges:
|
91 |
+
if d is None:
|
92 |
+
yield str(u)
|
93 |
+
else:
|
94 |
+
yield str(u) + delimiter + str(d)
|
95 |
+
else: # directed single edges
|
96 |
+
for s, nbrs in G.adjacency():
|
97 |
+
deg = len(nbrs)
|
98 |
+
yield str(s) + delimiter + str(deg)
|
99 |
+
for u, d in nbrs.items():
|
100 |
+
if d is None:
|
101 |
+
yield str(u)
|
102 |
+
else:
|
103 |
+
yield str(u) + delimiter + str(d)
|
104 |
+
else: # undirected
|
105 |
+
if G.is_multigraph():
|
106 |
+
seen = set() # helper dict used to avoid duplicate edges
|
107 |
+
for s, nbrs in G.adjacency():
|
108 |
+
nbr_edges = [
|
109 |
+
(u, data)
|
110 |
+
for u, datadict in nbrs.items()
|
111 |
+
if u not in seen
|
112 |
+
for key, data in datadict.items()
|
113 |
+
]
|
114 |
+
deg = len(nbr_edges)
|
115 |
+
yield str(s) + delimiter + str(deg)
|
116 |
+
for u, d in nbr_edges:
|
117 |
+
if d is None:
|
118 |
+
yield str(u)
|
119 |
+
else:
|
120 |
+
yield str(u) + delimiter + str(d)
|
121 |
+
seen.add(s)
|
122 |
+
else: # undirected single edges
|
123 |
+
seen = set() # helper dict used to avoid duplicate edges
|
124 |
+
for s, nbrs in G.adjacency():
|
125 |
+
nbr_edges = [(u, d) for u, d in nbrs.items() if u not in seen]
|
126 |
+
deg = len(nbr_edges)
|
127 |
+
yield str(s) + delimiter + str(deg)
|
128 |
+
for u, d in nbr_edges:
|
129 |
+
if d is None:
|
130 |
+
yield str(u)
|
131 |
+
else:
|
132 |
+
yield str(u) + delimiter + str(d)
|
133 |
+
seen.add(s)
|
134 |
+
|
135 |
+
|
136 |
+
@open_file(1, mode="wb")
|
137 |
+
def write_multiline_adjlist(G, path, delimiter=" ", comments="#", encoding="utf-8"):
|
138 |
+
"""Write the graph G in multiline adjacency list format to path
|
139 |
+
|
140 |
+
Parameters
|
141 |
+
----------
|
142 |
+
G : NetworkX graph
|
143 |
+
|
144 |
+
path : string or file
|
145 |
+
Filename or file handle to write to.
|
146 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
147 |
+
|
148 |
+
comments : string, optional
|
149 |
+
Marker for comment lines
|
150 |
+
|
151 |
+
delimiter : string, optional
|
152 |
+
Separator for node labels
|
153 |
+
|
154 |
+
encoding : string, optional
|
155 |
+
Text encoding.
|
156 |
+
|
157 |
+
Examples
|
158 |
+
--------
|
159 |
+
>>> G = nx.path_graph(4)
|
160 |
+
>>> nx.write_multiline_adjlist(G, "test.adjlist")
|
161 |
+
|
162 |
+
The path can be a file handle or a string with the name of the file. If a
|
163 |
+
file handle is provided, it has to be opened in 'wb' mode.
|
164 |
+
|
165 |
+
>>> fh = open("test.adjlist", "wb")
|
166 |
+
>>> nx.write_multiline_adjlist(G, fh)
|
167 |
+
|
168 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
169 |
+
|
170 |
+
>>> nx.write_multiline_adjlist(G, "test.adjlist.gz")
|
171 |
+
|
172 |
+
See Also
|
173 |
+
--------
|
174 |
+
read_multiline_adjlist
|
175 |
+
"""
|
176 |
+
import sys
|
177 |
+
import time
|
178 |
+
|
179 |
+
pargs = comments + " ".join(sys.argv)
|
180 |
+
header = (
|
181 |
+
f"{pargs}\n"
|
182 |
+
+ comments
|
183 |
+
+ f" GMT {time.asctime(time.gmtime())}\n"
|
184 |
+
+ comments
|
185 |
+
+ f" {G.name}\n"
|
186 |
+
)
|
187 |
+
path.write(header.encode(encoding))
|
188 |
+
|
189 |
+
for multiline in generate_multiline_adjlist(G, delimiter):
|
190 |
+
multiline += "\n"
|
191 |
+
path.write(multiline.encode(encoding))
|
192 |
+
|
193 |
+
|
194 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
195 |
+
def parse_multiline_adjlist(
|
196 |
+
lines, comments="#", delimiter=None, create_using=None, nodetype=None, edgetype=None
|
197 |
+
):
|
198 |
+
"""Parse lines of a multiline adjacency list representation of a graph.
|
199 |
+
|
200 |
+
Parameters
|
201 |
+
----------
|
202 |
+
lines : list or iterator of strings
|
203 |
+
Input data in multiline adjlist format
|
204 |
+
|
205 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
206 |
+
Graph type to create. If graph instance, then cleared before populated.
|
207 |
+
|
208 |
+
nodetype : Python type, optional
|
209 |
+
Convert nodes to this type.
|
210 |
+
|
211 |
+
edgetype : Python type, optional
|
212 |
+
Convert edges to this type.
|
213 |
+
|
214 |
+
comments : string, optional
|
215 |
+
Marker for comment lines
|
216 |
+
|
217 |
+
delimiter : string, optional
|
218 |
+
Separator for node labels. The default is whitespace.
|
219 |
+
|
220 |
+
Returns
|
221 |
+
-------
|
222 |
+
G: NetworkX graph
|
223 |
+
The graph corresponding to the lines in multiline adjacency list format.
|
224 |
+
|
225 |
+
Examples
|
226 |
+
--------
|
227 |
+
>>> lines = [
|
228 |
+
... "1 2",
|
229 |
+
... "2 {'weight':3, 'name': 'Frodo'}",
|
230 |
+
... "3 {}",
|
231 |
+
... "2 1",
|
232 |
+
... "5 {'weight':6, 'name': 'Saruman'}",
|
233 |
+
... ]
|
234 |
+
>>> G = nx.parse_multiline_adjlist(iter(lines), nodetype=int)
|
235 |
+
>>> list(G)
|
236 |
+
[1, 2, 3, 5]
|
237 |
+
|
238 |
+
"""
|
239 |
+
from ast import literal_eval
|
240 |
+
|
241 |
+
G = nx.empty_graph(0, create_using)
|
242 |
+
for line in lines:
|
243 |
+
p = line.find(comments)
|
244 |
+
if p >= 0:
|
245 |
+
line = line[:p]
|
246 |
+
if not line:
|
247 |
+
continue
|
248 |
+
try:
|
249 |
+
(u, deg) = line.strip().split(delimiter)
|
250 |
+
deg = int(deg)
|
251 |
+
except BaseException as err:
|
252 |
+
raise TypeError(f"Failed to read node and degree on line ({line})") from err
|
253 |
+
if nodetype is not None:
|
254 |
+
try:
|
255 |
+
u = nodetype(u)
|
256 |
+
except BaseException as err:
|
257 |
+
raise TypeError(
|
258 |
+
f"Failed to convert node ({u}) to type {nodetype}"
|
259 |
+
) from err
|
260 |
+
G.add_node(u)
|
261 |
+
for i in range(deg):
|
262 |
+
while True:
|
263 |
+
try:
|
264 |
+
line = next(lines)
|
265 |
+
except StopIteration as err:
|
266 |
+
msg = f"Failed to find neighbor for node ({u})"
|
267 |
+
raise TypeError(msg) from err
|
268 |
+
p = line.find(comments)
|
269 |
+
if p >= 0:
|
270 |
+
line = line[:p]
|
271 |
+
if line:
|
272 |
+
break
|
273 |
+
vlist = line.strip().split(delimiter)
|
274 |
+
numb = len(vlist)
|
275 |
+
if numb < 1:
|
276 |
+
continue # isolated node
|
277 |
+
v = vlist.pop(0)
|
278 |
+
data = "".join(vlist)
|
279 |
+
if nodetype is not None:
|
280 |
+
try:
|
281 |
+
v = nodetype(v)
|
282 |
+
except BaseException as err:
|
283 |
+
raise TypeError(
|
284 |
+
f"Failed to convert node ({v}) to type {nodetype}"
|
285 |
+
) from err
|
286 |
+
if edgetype is not None:
|
287 |
+
try:
|
288 |
+
edgedata = {"weight": edgetype(data)}
|
289 |
+
except BaseException as err:
|
290 |
+
raise TypeError(
|
291 |
+
f"Failed to convert edge data ({data}) to type {edgetype}"
|
292 |
+
) from err
|
293 |
+
else:
|
294 |
+
try: # try to evaluate
|
295 |
+
edgedata = literal_eval(data)
|
296 |
+
except:
|
297 |
+
edgedata = {}
|
298 |
+
G.add_edge(u, v, **edgedata)
|
299 |
+
|
300 |
+
return G
|
301 |
+
|
302 |
+
|
303 |
+
@open_file(0, mode="rb")
|
304 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
305 |
+
def read_multiline_adjlist(
|
306 |
+
path,
|
307 |
+
comments="#",
|
308 |
+
delimiter=None,
|
309 |
+
create_using=None,
|
310 |
+
nodetype=None,
|
311 |
+
edgetype=None,
|
312 |
+
encoding="utf-8",
|
313 |
+
):
|
314 |
+
"""Read graph in multi-line adjacency list format from path.
|
315 |
+
|
316 |
+
Parameters
|
317 |
+
----------
|
318 |
+
path : string or file
|
319 |
+
Filename or file handle to read.
|
320 |
+
Filenames ending in .gz or .bz2 will be uncompressed.
|
321 |
+
|
322 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
323 |
+
Graph type to create. If graph instance, then cleared before populated.
|
324 |
+
|
325 |
+
nodetype : Python type, optional
|
326 |
+
Convert nodes to this type.
|
327 |
+
|
328 |
+
edgetype : Python type, optional
|
329 |
+
Convert edge data to this type.
|
330 |
+
|
331 |
+
comments : string, optional
|
332 |
+
Marker for comment lines
|
333 |
+
|
334 |
+
delimiter : string, optional
|
335 |
+
Separator for node labels. The default is whitespace.
|
336 |
+
|
337 |
+
Returns
|
338 |
+
-------
|
339 |
+
G: NetworkX graph
|
340 |
+
|
341 |
+
Examples
|
342 |
+
--------
|
343 |
+
>>> G = nx.path_graph(4)
|
344 |
+
>>> nx.write_multiline_adjlist(G, "test.adjlist")
|
345 |
+
>>> G = nx.read_multiline_adjlist("test.adjlist")
|
346 |
+
|
347 |
+
The path can be a file or a string with the name of the file. If a
|
348 |
+
file s provided, it has to be opened in 'rb' mode.
|
349 |
+
|
350 |
+
>>> fh = open("test.adjlist", "rb")
|
351 |
+
>>> G = nx.read_multiline_adjlist(fh)
|
352 |
+
|
353 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
354 |
+
|
355 |
+
>>> nx.write_multiline_adjlist(G, "test.adjlist.gz")
|
356 |
+
>>> G = nx.read_multiline_adjlist("test.adjlist.gz")
|
357 |
+
|
358 |
+
The optional nodetype is a function to convert node strings to nodetype.
|
359 |
+
|
360 |
+
For example
|
361 |
+
|
362 |
+
>>> G = nx.read_multiline_adjlist("test.adjlist", nodetype=int)
|
363 |
+
|
364 |
+
will attempt to convert all nodes to integer type.
|
365 |
+
|
366 |
+
The optional edgetype is a function to convert edge data strings to
|
367 |
+
edgetype.
|
368 |
+
|
369 |
+
>>> G = nx.read_multiline_adjlist("test.adjlist")
|
370 |
+
|
371 |
+
The optional create_using parameter is a NetworkX graph container.
|
372 |
+
The default is Graph(), an undirected graph. To read the data as
|
373 |
+
a directed graph use
|
374 |
+
|
375 |
+
>>> G = nx.read_multiline_adjlist("test.adjlist", create_using=nx.DiGraph)
|
376 |
+
|
377 |
+
Notes
|
378 |
+
-----
|
379 |
+
This format does not store graph, node, or edge data.
|
380 |
+
|
381 |
+
See Also
|
382 |
+
--------
|
383 |
+
write_multiline_adjlist
|
384 |
+
"""
|
385 |
+
lines = (line.decode(encoding) for line in path)
|
386 |
+
return parse_multiline_adjlist(
|
387 |
+
lines,
|
388 |
+
comments=comments,
|
389 |
+
delimiter=delimiter,
|
390 |
+
create_using=create_using,
|
391 |
+
nodetype=nodetype,
|
392 |
+
edgetype=edgetype,
|
393 |
+
)
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/pajek.py
ADDED
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
*****
|
3 |
+
Pajek
|
4 |
+
*****
|
5 |
+
Read graphs in Pajek format.
|
6 |
+
|
7 |
+
This implementation handles directed and undirected graphs including
|
8 |
+
those with self loops and parallel edges.
|
9 |
+
|
10 |
+
Format
|
11 |
+
------
|
12 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
13 |
+
for format information.
|
14 |
+
|
15 |
+
"""
|
16 |
+
|
17 |
+
import warnings
|
18 |
+
|
19 |
+
import networkx as nx
|
20 |
+
from networkx.utils import open_file
|
21 |
+
|
22 |
+
__all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"]
|
23 |
+
|
24 |
+
|
25 |
+
def generate_pajek(G):
|
26 |
+
"""Generate lines in Pajek graph format.
|
27 |
+
|
28 |
+
Parameters
|
29 |
+
----------
|
30 |
+
G : graph
|
31 |
+
A Networkx graph
|
32 |
+
|
33 |
+
References
|
34 |
+
----------
|
35 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
36 |
+
for format information.
|
37 |
+
"""
|
38 |
+
if G.name == "":
|
39 |
+
name = "NetworkX"
|
40 |
+
else:
|
41 |
+
name = G.name
|
42 |
+
# Apparently many Pajek format readers can't process this line
|
43 |
+
# So we'll leave it out for now.
|
44 |
+
# yield '*network %s'%name
|
45 |
+
|
46 |
+
# write nodes with attributes
|
47 |
+
yield f"*vertices {G.order()}"
|
48 |
+
nodes = list(G)
|
49 |
+
# make dictionary mapping nodes to integers
|
50 |
+
nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
|
51 |
+
for n in nodes:
|
52 |
+
# copy node attributes and pop mandatory attributes
|
53 |
+
# to avoid duplication.
|
54 |
+
na = G.nodes.get(n, {}).copy()
|
55 |
+
x = na.pop("x", 0.0)
|
56 |
+
y = na.pop("y", 0.0)
|
57 |
+
try:
|
58 |
+
id = int(na.pop("id", nodenumber[n]))
|
59 |
+
except ValueError as err:
|
60 |
+
err.args += (
|
61 |
+
(
|
62 |
+
"Pajek format requires 'id' to be an int()."
|
63 |
+
" Refer to the 'Relabeling nodes' section."
|
64 |
+
),
|
65 |
+
)
|
66 |
+
raise
|
67 |
+
nodenumber[n] = id
|
68 |
+
shape = na.pop("shape", "ellipse")
|
69 |
+
s = " ".join(map(make_qstr, (id, n, x, y, shape)))
|
70 |
+
# only optional attributes are left in na.
|
71 |
+
for k, v in na.items():
|
72 |
+
if isinstance(v, str) and v.strip() != "":
|
73 |
+
s += f" {make_qstr(k)} {make_qstr(v)}"
|
74 |
+
else:
|
75 |
+
warnings.warn(
|
76 |
+
f"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
|
77 |
+
)
|
78 |
+
yield s
|
79 |
+
|
80 |
+
# write edges with attributes
|
81 |
+
if G.is_directed():
|
82 |
+
yield "*arcs"
|
83 |
+
else:
|
84 |
+
yield "*edges"
|
85 |
+
for u, v, edgedata in G.edges(data=True):
|
86 |
+
d = edgedata.copy()
|
87 |
+
value = d.pop("weight", 1.0) # use 1 as default edge value
|
88 |
+
s = " ".join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
|
89 |
+
for k, v in d.items():
|
90 |
+
if isinstance(v, str) and v.strip() != "":
|
91 |
+
s += f" {make_qstr(k)} {make_qstr(v)}"
|
92 |
+
else:
|
93 |
+
warnings.warn(
|
94 |
+
f"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}."
|
95 |
+
)
|
96 |
+
yield s
|
97 |
+
|
98 |
+
|
99 |
+
@open_file(1, mode="wb")
|
100 |
+
def write_pajek(G, path, encoding="UTF-8"):
|
101 |
+
"""Write graph in Pajek format to path.
|
102 |
+
|
103 |
+
Parameters
|
104 |
+
----------
|
105 |
+
G : graph
|
106 |
+
A Networkx graph
|
107 |
+
path : file or string
|
108 |
+
File or filename to write.
|
109 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
110 |
+
|
111 |
+
Examples
|
112 |
+
--------
|
113 |
+
>>> G = nx.path_graph(4)
|
114 |
+
>>> nx.write_pajek(G, "test.net")
|
115 |
+
|
116 |
+
Warnings
|
117 |
+
--------
|
118 |
+
Optional node attributes and edge attributes must be non-empty strings.
|
119 |
+
Otherwise it will not be written into the file. You will need to
|
120 |
+
convert those attributes to strings if you want to keep them.
|
121 |
+
|
122 |
+
References
|
123 |
+
----------
|
124 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
125 |
+
for format information.
|
126 |
+
"""
|
127 |
+
for line in generate_pajek(G):
|
128 |
+
line += "\n"
|
129 |
+
path.write(line.encode(encoding))
|
130 |
+
|
131 |
+
|
132 |
+
@open_file(0, mode="rb")
|
133 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
134 |
+
def read_pajek(path, encoding="UTF-8"):
|
135 |
+
"""Read graph in Pajek format from path.
|
136 |
+
|
137 |
+
Parameters
|
138 |
+
----------
|
139 |
+
path : file or string
|
140 |
+
File or filename to write.
|
141 |
+
Filenames ending in .gz or .bz2 will be uncompressed.
|
142 |
+
|
143 |
+
Returns
|
144 |
+
-------
|
145 |
+
G : NetworkX MultiGraph or MultiDiGraph.
|
146 |
+
|
147 |
+
Examples
|
148 |
+
--------
|
149 |
+
>>> G = nx.path_graph(4)
|
150 |
+
>>> nx.write_pajek(G, "test.net")
|
151 |
+
>>> G = nx.read_pajek("test.net")
|
152 |
+
|
153 |
+
To create a Graph instead of a MultiGraph use
|
154 |
+
|
155 |
+
>>> G1 = nx.Graph(G)
|
156 |
+
|
157 |
+
References
|
158 |
+
----------
|
159 |
+
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
|
160 |
+
for format information.
|
161 |
+
"""
|
162 |
+
lines = (line.decode(encoding) for line in path)
|
163 |
+
return parse_pajek(lines)
|
164 |
+
|
165 |
+
|
166 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
167 |
+
def parse_pajek(lines):
|
168 |
+
"""Parse Pajek format graph from string or iterable.
|
169 |
+
|
170 |
+
Parameters
|
171 |
+
----------
|
172 |
+
lines : string or iterable
|
173 |
+
Data in Pajek format.
|
174 |
+
|
175 |
+
Returns
|
176 |
+
-------
|
177 |
+
G : NetworkX graph
|
178 |
+
|
179 |
+
See Also
|
180 |
+
--------
|
181 |
+
read_pajek
|
182 |
+
|
183 |
+
"""
|
184 |
+
import shlex
|
185 |
+
|
186 |
+
# multigraph=False
|
187 |
+
if isinstance(lines, str):
|
188 |
+
lines = iter(lines.split("\n"))
|
189 |
+
lines = iter([line.rstrip("\n") for line in lines])
|
190 |
+
G = nx.MultiDiGraph() # are multiedges allowed in Pajek? assume yes
|
191 |
+
labels = [] # in the order of the file, needed for matrix
|
192 |
+
while lines:
|
193 |
+
try:
|
194 |
+
l = next(lines)
|
195 |
+
except: # EOF
|
196 |
+
break
|
197 |
+
if l.lower().startswith("*network"):
|
198 |
+
try:
|
199 |
+
label, name = l.split(None, 1)
|
200 |
+
except ValueError:
|
201 |
+
# Line was not of the form: *network NAME
|
202 |
+
pass
|
203 |
+
else:
|
204 |
+
G.graph["name"] = name
|
205 |
+
elif l.lower().startswith("*vertices"):
|
206 |
+
nodelabels = {}
|
207 |
+
l, nnodes = l.split()
|
208 |
+
for i in range(int(nnodes)):
|
209 |
+
l = next(lines)
|
210 |
+
try:
|
211 |
+
splitline = [
|
212 |
+
x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
|
213 |
+
]
|
214 |
+
except AttributeError:
|
215 |
+
splitline = shlex.split(str(l))
|
216 |
+
id, label = splitline[0:2]
|
217 |
+
labels.append(label)
|
218 |
+
G.add_node(label)
|
219 |
+
nodelabels[id] = label
|
220 |
+
G.nodes[label]["id"] = id
|
221 |
+
try:
|
222 |
+
x, y, shape = splitline[2:5]
|
223 |
+
G.nodes[label].update(
|
224 |
+
{"x": float(x), "y": float(y), "shape": shape}
|
225 |
+
)
|
226 |
+
except:
|
227 |
+
pass
|
228 |
+
extra_attr = zip(splitline[5::2], splitline[6::2])
|
229 |
+
G.nodes[label].update(extra_attr)
|
230 |
+
elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
|
231 |
+
if l.lower().startswith("*edge"):
|
232 |
+
# switch from multidigraph to multigraph
|
233 |
+
G = nx.MultiGraph(G)
|
234 |
+
if l.lower().startswith("*arcs"):
|
235 |
+
# switch to directed with multiple arcs for each existing edge
|
236 |
+
G = G.to_directed()
|
237 |
+
for l in lines:
|
238 |
+
try:
|
239 |
+
splitline = [
|
240 |
+
x.decode("utf-8") for x in shlex.split(str(l).encode("utf-8"))
|
241 |
+
]
|
242 |
+
except AttributeError:
|
243 |
+
splitline = shlex.split(str(l))
|
244 |
+
|
245 |
+
if len(splitline) < 2:
|
246 |
+
continue
|
247 |
+
ui, vi = splitline[0:2]
|
248 |
+
u = nodelabels.get(ui, ui)
|
249 |
+
v = nodelabels.get(vi, vi)
|
250 |
+
# parse the data attached to this edge and put in a dictionary
|
251 |
+
edge_data = {}
|
252 |
+
try:
|
253 |
+
# there should always be a single value on the edge?
|
254 |
+
w = splitline[2:3]
|
255 |
+
edge_data.update({"weight": float(w[0])})
|
256 |
+
except:
|
257 |
+
pass
|
258 |
+
# if there isn't, just assign a 1
|
259 |
+
# edge_data.update({'value':1})
|
260 |
+
extra_attr = zip(splitline[3::2], splitline[4::2])
|
261 |
+
edge_data.update(extra_attr)
|
262 |
+
# if G.has_edge(u,v):
|
263 |
+
# multigraph=True
|
264 |
+
G.add_edge(u, v, **edge_data)
|
265 |
+
elif l.lower().startswith("*matrix"):
|
266 |
+
G = nx.DiGraph(G)
|
267 |
+
adj_list = (
|
268 |
+
(labels[row], labels[col], {"weight": int(data)})
|
269 |
+
for (row, line) in enumerate(lines)
|
270 |
+
for (col, data) in enumerate(line.split())
|
271 |
+
if int(data) != 0
|
272 |
+
)
|
273 |
+
G.add_edges_from(adj_list)
|
274 |
+
|
275 |
+
return G
|
276 |
+
|
277 |
+
|
278 |
+
def make_qstr(t):
|
279 |
+
"""Returns the string representation of t.
|
280 |
+
Add outer double-quotes if the string has a space.
|
281 |
+
"""
|
282 |
+
if not isinstance(t, str):
|
283 |
+
t = str(t)
|
284 |
+
if " " in t:
|
285 |
+
t = f'"{t}"'
|
286 |
+
return t
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/sparse6.py
ADDED
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Original author: D. Eppstein, UC Irvine, August 12, 2003.
|
2 |
+
# The original code at https://www.ics.uci.edu/~eppstein/PADS/ is public domain.
|
3 |
+
"""Functions for reading and writing graphs in the *sparse6* format.
|
4 |
+
|
5 |
+
The *sparse6* file format is a space-efficient format for large sparse
|
6 |
+
graphs. For small graphs or large dense graphs, use the *graph6* file
|
7 |
+
format.
|
8 |
+
|
9 |
+
For more information, see the `sparse6`_ homepage.
|
10 |
+
|
11 |
+
.. _sparse6: https://users.cecs.anu.edu.au/~bdm/data/formats.html
|
12 |
+
|
13 |
+
"""
|
14 |
+
import networkx as nx
|
15 |
+
from networkx.exception import NetworkXError
|
16 |
+
from networkx.readwrite.graph6 import data_to_n, n_to_data
|
17 |
+
from networkx.utils import not_implemented_for, open_file
|
18 |
+
|
19 |
+
__all__ = ["from_sparse6_bytes", "read_sparse6", "to_sparse6_bytes", "write_sparse6"]
|
20 |
+
|
21 |
+
|
22 |
+
def _generate_sparse6_bytes(G, nodes, header):
|
23 |
+
"""Yield bytes in the sparse6 encoding of a graph.
|
24 |
+
|
25 |
+
`G` is an undirected simple graph. `nodes` is the list of nodes for
|
26 |
+
which the node-induced subgraph will be encoded; if `nodes` is the
|
27 |
+
list of all nodes in the graph, the entire graph will be
|
28 |
+
encoded. `header` is a Boolean that specifies whether to generate
|
29 |
+
the header ``b'>>sparse6<<'`` before the remaining data.
|
30 |
+
|
31 |
+
This function generates `bytes` objects in the following order:
|
32 |
+
|
33 |
+
1. the header (if requested),
|
34 |
+
2. the encoding of the number of nodes,
|
35 |
+
3. each character, one-at-a-time, in the encoding of the requested
|
36 |
+
node-induced subgraph,
|
37 |
+
4. a newline character.
|
38 |
+
|
39 |
+
This function raises :exc:`ValueError` if the graph is too large for
|
40 |
+
the graph6 format (that is, greater than ``2 ** 36`` nodes).
|
41 |
+
|
42 |
+
"""
|
43 |
+
n = len(G)
|
44 |
+
if n >= 2**36:
|
45 |
+
raise ValueError(
|
46 |
+
"sparse6 is only defined if number of nodes is less than 2 ** 36"
|
47 |
+
)
|
48 |
+
if header:
|
49 |
+
yield b">>sparse6<<"
|
50 |
+
yield b":"
|
51 |
+
for d in n_to_data(n):
|
52 |
+
yield str.encode(chr(d + 63))
|
53 |
+
|
54 |
+
k = 1
|
55 |
+
while 1 << k < n:
|
56 |
+
k += 1
|
57 |
+
|
58 |
+
def enc(x):
|
59 |
+
"""Big endian k-bit encoding of x"""
|
60 |
+
return [1 if (x & 1 << (k - 1 - i)) else 0 for i in range(k)]
|
61 |
+
|
62 |
+
edges = sorted((max(u, v), min(u, v)) for u, v in G.edges())
|
63 |
+
bits = []
|
64 |
+
curv = 0
|
65 |
+
for v, u in edges:
|
66 |
+
if v == curv: # current vertex edge
|
67 |
+
bits.append(0)
|
68 |
+
bits.extend(enc(u))
|
69 |
+
elif v == curv + 1: # next vertex edge
|
70 |
+
curv += 1
|
71 |
+
bits.append(1)
|
72 |
+
bits.extend(enc(u))
|
73 |
+
else: # skip to vertex v and then add edge to u
|
74 |
+
curv = v
|
75 |
+
bits.append(1)
|
76 |
+
bits.extend(enc(v))
|
77 |
+
bits.append(0)
|
78 |
+
bits.extend(enc(u))
|
79 |
+
if k < 6 and n == (1 << k) and ((-len(bits)) % 6) >= k and curv < (n - 1):
|
80 |
+
# Padding special case: small k, n=2^k,
|
81 |
+
# more than k bits of padding needed,
|
82 |
+
# current vertex is not (n-1) --
|
83 |
+
# appending 1111... would add a loop on (n-1)
|
84 |
+
bits.append(0)
|
85 |
+
bits.extend([1] * ((-len(bits)) % 6))
|
86 |
+
else:
|
87 |
+
bits.extend([1] * ((-len(bits)) % 6))
|
88 |
+
|
89 |
+
data = [
|
90 |
+
(bits[i + 0] << 5)
|
91 |
+
+ (bits[i + 1] << 4)
|
92 |
+
+ (bits[i + 2] << 3)
|
93 |
+
+ (bits[i + 3] << 2)
|
94 |
+
+ (bits[i + 4] << 1)
|
95 |
+
+ (bits[i + 5] << 0)
|
96 |
+
for i in range(0, len(bits), 6)
|
97 |
+
]
|
98 |
+
|
99 |
+
for d in data:
|
100 |
+
yield str.encode(chr(d + 63))
|
101 |
+
yield b"\n"
|
102 |
+
|
103 |
+
|
104 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
105 |
+
def from_sparse6_bytes(string):
|
106 |
+
"""Read an undirected graph in sparse6 format from string.
|
107 |
+
|
108 |
+
Parameters
|
109 |
+
----------
|
110 |
+
string : string
|
111 |
+
Data in sparse6 format
|
112 |
+
|
113 |
+
Returns
|
114 |
+
-------
|
115 |
+
G : Graph
|
116 |
+
|
117 |
+
Raises
|
118 |
+
------
|
119 |
+
NetworkXError
|
120 |
+
If the string is unable to be parsed in sparse6 format
|
121 |
+
|
122 |
+
Examples
|
123 |
+
--------
|
124 |
+
>>> G = nx.from_sparse6_bytes(b":A_")
|
125 |
+
>>> sorted(G.edges())
|
126 |
+
[(0, 1), (0, 1), (0, 1)]
|
127 |
+
|
128 |
+
See Also
|
129 |
+
--------
|
130 |
+
read_sparse6, write_sparse6
|
131 |
+
|
132 |
+
References
|
133 |
+
----------
|
134 |
+
.. [1] Sparse6 specification
|
135 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
136 |
+
|
137 |
+
"""
|
138 |
+
if string.startswith(b">>sparse6<<"):
|
139 |
+
string = string[11:]
|
140 |
+
if not string.startswith(b":"):
|
141 |
+
raise NetworkXError("Expected leading colon in sparse6")
|
142 |
+
|
143 |
+
chars = [c - 63 for c in string[1:]]
|
144 |
+
n, data = data_to_n(chars)
|
145 |
+
k = 1
|
146 |
+
while 1 << k < n:
|
147 |
+
k += 1
|
148 |
+
|
149 |
+
def parseData():
|
150 |
+
"""Returns stream of pairs b[i], x[i] for sparse6 format."""
|
151 |
+
chunks = iter(data)
|
152 |
+
d = None # partial data word
|
153 |
+
dLen = 0 # how many unparsed bits are left in d
|
154 |
+
|
155 |
+
while 1:
|
156 |
+
if dLen < 1:
|
157 |
+
try:
|
158 |
+
d = next(chunks)
|
159 |
+
except StopIteration:
|
160 |
+
return
|
161 |
+
dLen = 6
|
162 |
+
dLen -= 1
|
163 |
+
b = (d >> dLen) & 1 # grab top remaining bit
|
164 |
+
|
165 |
+
x = d & ((1 << dLen) - 1) # partially built up value of x
|
166 |
+
xLen = dLen # how many bits included so far in x
|
167 |
+
while xLen < k: # now grab full chunks until we have enough
|
168 |
+
try:
|
169 |
+
d = next(chunks)
|
170 |
+
except StopIteration:
|
171 |
+
return
|
172 |
+
dLen = 6
|
173 |
+
x = (x << 6) + d
|
174 |
+
xLen += 6
|
175 |
+
x = x >> (xLen - k) # shift back the extra bits
|
176 |
+
dLen = xLen - k
|
177 |
+
yield b, x
|
178 |
+
|
179 |
+
v = 0
|
180 |
+
|
181 |
+
G = nx.MultiGraph()
|
182 |
+
G.add_nodes_from(range(n))
|
183 |
+
|
184 |
+
multigraph = False
|
185 |
+
for b, x in parseData():
|
186 |
+
if b == 1:
|
187 |
+
v += 1
|
188 |
+
# padding with ones can cause overlarge number here
|
189 |
+
if x >= n or v >= n:
|
190 |
+
break
|
191 |
+
elif x > v:
|
192 |
+
v = x
|
193 |
+
else:
|
194 |
+
if G.has_edge(x, v):
|
195 |
+
multigraph = True
|
196 |
+
G.add_edge(x, v)
|
197 |
+
if not multigraph:
|
198 |
+
G = nx.Graph(G)
|
199 |
+
return G
|
200 |
+
|
201 |
+
|
202 |
+
def to_sparse6_bytes(G, nodes=None, header=True):
|
203 |
+
"""Convert an undirected graph to bytes in sparse6 format.
|
204 |
+
|
205 |
+
Parameters
|
206 |
+
----------
|
207 |
+
G : Graph (undirected)
|
208 |
+
|
209 |
+
nodes: list or iterable
|
210 |
+
Nodes are labeled 0...n-1 in the order provided. If None the ordering
|
211 |
+
given by ``G.nodes()`` is used.
|
212 |
+
|
213 |
+
header: bool
|
214 |
+
If True add '>>sparse6<<' bytes to head of data.
|
215 |
+
|
216 |
+
Raises
|
217 |
+
------
|
218 |
+
NetworkXNotImplemented
|
219 |
+
If the graph is directed.
|
220 |
+
|
221 |
+
ValueError
|
222 |
+
If the graph has at least ``2 ** 36`` nodes; the sparse6 format
|
223 |
+
is only defined for graphs of order less than ``2 ** 36``.
|
224 |
+
|
225 |
+
Examples
|
226 |
+
--------
|
227 |
+
>>> nx.to_sparse6_bytes(nx.path_graph(2))
|
228 |
+
b'>>sparse6<<:An\\n'
|
229 |
+
|
230 |
+
See Also
|
231 |
+
--------
|
232 |
+
to_sparse6_bytes, read_sparse6, write_sparse6_bytes
|
233 |
+
|
234 |
+
Notes
|
235 |
+
-----
|
236 |
+
The returned bytes end with a newline character.
|
237 |
+
|
238 |
+
The format does not support edge or node labels.
|
239 |
+
|
240 |
+
References
|
241 |
+
----------
|
242 |
+
.. [1] Graph6 specification
|
243 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
244 |
+
|
245 |
+
"""
|
246 |
+
if nodes is not None:
|
247 |
+
G = G.subgraph(nodes)
|
248 |
+
G = nx.convert_node_labels_to_integers(G, ordering="sorted")
|
249 |
+
return b"".join(_generate_sparse6_bytes(G, nodes, header))
|
250 |
+
|
251 |
+
|
252 |
+
@open_file(0, mode="rb")
|
253 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
254 |
+
def read_sparse6(path):
|
255 |
+
"""Read an undirected graph in sparse6 format from path.
|
256 |
+
|
257 |
+
Parameters
|
258 |
+
----------
|
259 |
+
path : file or string
|
260 |
+
File or filename to write.
|
261 |
+
|
262 |
+
Returns
|
263 |
+
-------
|
264 |
+
G : Graph/Multigraph or list of Graphs/MultiGraphs
|
265 |
+
If the file contains multiple lines then a list of graphs is returned
|
266 |
+
|
267 |
+
Raises
|
268 |
+
------
|
269 |
+
NetworkXError
|
270 |
+
If the string is unable to be parsed in sparse6 format
|
271 |
+
|
272 |
+
Examples
|
273 |
+
--------
|
274 |
+
You can read a sparse6 file by giving the path to the file::
|
275 |
+
|
276 |
+
>>> import tempfile
|
277 |
+
>>> with tempfile.NamedTemporaryFile(delete=False) as f:
|
278 |
+
... _ = f.write(b">>sparse6<<:An\\n")
|
279 |
+
... _ = f.seek(0)
|
280 |
+
... G = nx.read_sparse6(f.name)
|
281 |
+
>>> list(G.edges())
|
282 |
+
[(0, 1)]
|
283 |
+
|
284 |
+
You can also read a sparse6 file by giving an open file-like object::
|
285 |
+
|
286 |
+
>>> import tempfile
|
287 |
+
>>> with tempfile.NamedTemporaryFile() as f:
|
288 |
+
... _ = f.write(b">>sparse6<<:An\\n")
|
289 |
+
... _ = f.seek(0)
|
290 |
+
... G = nx.read_sparse6(f)
|
291 |
+
>>> list(G.edges())
|
292 |
+
[(0, 1)]
|
293 |
+
|
294 |
+
See Also
|
295 |
+
--------
|
296 |
+
read_sparse6, from_sparse6_bytes
|
297 |
+
|
298 |
+
References
|
299 |
+
----------
|
300 |
+
.. [1] Sparse6 specification
|
301 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
302 |
+
|
303 |
+
"""
|
304 |
+
glist = []
|
305 |
+
for line in path:
|
306 |
+
line = line.strip()
|
307 |
+
if not len(line):
|
308 |
+
continue
|
309 |
+
glist.append(from_sparse6_bytes(line))
|
310 |
+
if len(glist) == 1:
|
311 |
+
return glist[0]
|
312 |
+
else:
|
313 |
+
return glist
|
314 |
+
|
315 |
+
|
316 |
+
@not_implemented_for("directed")
|
317 |
+
@open_file(1, mode="wb")
|
318 |
+
def write_sparse6(G, path, nodes=None, header=True):
|
319 |
+
"""Write graph G to given path in sparse6 format.
|
320 |
+
|
321 |
+
Parameters
|
322 |
+
----------
|
323 |
+
G : Graph (undirected)
|
324 |
+
|
325 |
+
path : file or string
|
326 |
+
File or filename to write
|
327 |
+
|
328 |
+
nodes: list or iterable
|
329 |
+
Nodes are labeled 0...n-1 in the order provided. If None the ordering
|
330 |
+
given by G.nodes() is used.
|
331 |
+
|
332 |
+
header: bool
|
333 |
+
If True add '>>sparse6<<' string to head of data
|
334 |
+
|
335 |
+
Raises
|
336 |
+
------
|
337 |
+
NetworkXError
|
338 |
+
If the graph is directed
|
339 |
+
|
340 |
+
Examples
|
341 |
+
--------
|
342 |
+
You can write a sparse6 file by giving the path to the file::
|
343 |
+
|
344 |
+
>>> import tempfile
|
345 |
+
>>> with tempfile.NamedTemporaryFile(delete=False) as f:
|
346 |
+
... nx.write_sparse6(nx.path_graph(2), f.name)
|
347 |
+
... print(f.read())
|
348 |
+
b'>>sparse6<<:An\\n'
|
349 |
+
|
350 |
+
You can also write a sparse6 file by giving an open file-like object::
|
351 |
+
|
352 |
+
>>> with tempfile.NamedTemporaryFile() as f:
|
353 |
+
... nx.write_sparse6(nx.path_graph(2), f)
|
354 |
+
... _ = f.seek(0)
|
355 |
+
... print(f.read())
|
356 |
+
b'>>sparse6<<:An\\n'
|
357 |
+
|
358 |
+
See Also
|
359 |
+
--------
|
360 |
+
read_sparse6, from_sparse6_bytes
|
361 |
+
|
362 |
+
Notes
|
363 |
+
-----
|
364 |
+
The format does not support edge or node labels.
|
365 |
+
|
366 |
+
References
|
367 |
+
----------
|
368 |
+
.. [1] Sparse6 specification
|
369 |
+
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
|
370 |
+
|
371 |
+
"""
|
372 |
+
if nodes is not None:
|
373 |
+
G = G.subgraph(nodes)
|
374 |
+
G = nx.convert_node_labels_to_integers(G, ordering="sorted")
|
375 |
+
for b in _generate_sparse6_bytes(G, nodes, header):
|
376 |
+
path.write(b)
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (189 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/networkx/readwrite/tests/__pycache__/test_adjlist.cpython-310.pyc
ADDED
Binary file (7.78 kB). View file
|
|