Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/17.input_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/17.input_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/17.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/25.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/8.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/8.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__init__.py +7 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/layout.py +1358 -0
- venv/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py +465 -0
- venv/lib/python3.10/site-packages/networkx/drawing/nx_latex.py +571 -0
- venv/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py +411 -0
- venv/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py +1871 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py +240 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py +292 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py +515 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py +180 -0
- venv/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py +879 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__init__.py +13 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/bethehessianmatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/graphmatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py +656 -0
- venv/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py +464 -0
- venv/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py +78 -0
- venv/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py +166 -0
- venv/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py +616 -0
- venv/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py +166 -0
- venv/lib/python3.10/site-packages/networkx/linalg/spectrum.py +185 -0
- venv/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/17.input_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:24a36c56bfccf20ae765db6915e85e57ae9216274eb3a1dd7d3f6534810f72b3
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/17.input_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e1cbeb05456b310bc3cf0a9076f45515fbf3e5b585f7e862ad2506aa117f4ff9
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/17.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f71f33d8072fdb3239e04a28fa73fb19641a41fced5dd1d53e223d0a85a07326
|
3 |
+
size 9293
|
ckpts/universal/global_step80/zero/25.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:af6359aebc201ea9fab097d6a46dfdd8904fe7386b2d1ec85fb3b15f886c957f
|
3 |
+
size 9293
|
ckpts/universal/global_step80/zero/8.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d2e48a38fd243eadf017efea94429edf11c3400d1acd94d387b15a8e662c19b9
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/8.mlp.dense_h_to_4h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:87365d4962e0bf8fae0544e01245a1bd6b213ad993a17a297cc7773454594482
|
3 |
+
size 33555627
|
venv/lib/python3.10/site-packages/networkx/drawing/__init__.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# graph drawing and interface to graphviz
|
2 |
+
|
3 |
+
from .layout import *
|
4 |
+
from .nx_latex import *
|
5 |
+
from .nx_pylab import *
|
6 |
+
from . import nx_agraph
|
7 |
+
from . import nx_pydot
|
venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (312 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc
ADDED
Binary file (33.7 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc
ADDED
Binary file (12.5 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc
ADDED
Binary file (22.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc
ADDED
Binary file (10 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc
ADDED
Binary file (51.6 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/layout.py
ADDED
@@ -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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
******
|
3 |
+
Layout
|
4 |
+
******
|
5 |
+
|
6 |
+
Node positioning algorithms for graph drawing.
|
7 |
+
|
8 |
+
For `random_layout()` the possible resulting shape
|
9 |
+
is a square of side [0, scale] (default: [0, 1])
|
10 |
+
Changing `center` shifts the layout by that amount.
|
11 |
+
|
12 |
+
For the other layout routines, the extent is
|
13 |
+
[center - scale, center + scale] (default: [-1, 1]).
|
14 |
+
|
15 |
+
Warning: Most layout routines have only been tested in 2-dimensions.
|
16 |
+
|
17 |
+
"""
|
18 |
+
import networkx as nx
|
19 |
+
from networkx.utils import np_random_state
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
"bipartite_layout",
|
23 |
+
"circular_layout",
|
24 |
+
"kamada_kawai_layout",
|
25 |
+
"random_layout",
|
26 |
+
"rescale_layout",
|
27 |
+
"rescale_layout_dict",
|
28 |
+
"shell_layout",
|
29 |
+
"spring_layout",
|
30 |
+
"spectral_layout",
|
31 |
+
"planar_layout",
|
32 |
+
"fruchterman_reingold_layout",
|
33 |
+
"spiral_layout",
|
34 |
+
"multipartite_layout",
|
35 |
+
"bfs_layout",
|
36 |
+
"arf_layout",
|
37 |
+
]
|
38 |
+
|
39 |
+
|
40 |
+
def _process_params(G, center, dim):
|
41 |
+
# Some boilerplate code.
|
42 |
+
import numpy as np
|
43 |
+
|
44 |
+
if not isinstance(G, nx.Graph):
|
45 |
+
empty_graph = nx.Graph()
|
46 |
+
empty_graph.add_nodes_from(G)
|
47 |
+
G = empty_graph
|
48 |
+
|
49 |
+
if center is None:
|
50 |
+
center = np.zeros(dim)
|
51 |
+
else:
|
52 |
+
center = np.asarray(center)
|
53 |
+
|
54 |
+
if len(center) != dim:
|
55 |
+
msg = "length of center coordinates must match dimension of layout"
|
56 |
+
raise ValueError(msg)
|
57 |
+
|
58 |
+
return G, center
|
59 |
+
|
60 |
+
|
61 |
+
@np_random_state(3)
|
62 |
+
def random_layout(G, center=None, dim=2, seed=None):
|
63 |
+
"""Position nodes uniformly at random in the unit square.
|
64 |
+
|
65 |
+
For every node, a position is generated by choosing each of dim
|
66 |
+
coordinates uniformly at random on the interval [0.0, 1.0).
|
67 |
+
|
68 |
+
NumPy (http://scipy.org) is required for this function.
|
69 |
+
|
70 |
+
Parameters
|
71 |
+
----------
|
72 |
+
G : NetworkX graph or list of nodes
|
73 |
+
A position will be assigned to every node in G.
|
74 |
+
|
75 |
+
center : array-like or None
|
76 |
+
Coordinate pair around which to center the layout.
|
77 |
+
|
78 |
+
dim : int
|
79 |
+
Dimension of layout.
|
80 |
+
|
81 |
+
seed : int, RandomState instance or None optional (default=None)
|
82 |
+
Set the random state for deterministic node layouts.
|
83 |
+
If int, `seed` is the seed used by the random number generator,
|
84 |
+
if numpy.random.RandomState instance, `seed` is the random
|
85 |
+
number generator,
|
86 |
+
if None, the random number generator is the RandomState instance used
|
87 |
+
by numpy.random.
|
88 |
+
|
89 |
+
Returns
|
90 |
+
-------
|
91 |
+
pos : dict
|
92 |
+
A dictionary of positions keyed by node
|
93 |
+
|
94 |
+
Examples
|
95 |
+
--------
|
96 |
+
>>> G = nx.lollipop_graph(4, 3)
|
97 |
+
>>> pos = nx.random_layout(G)
|
98 |
+
|
99 |
+
"""
|
100 |
+
import numpy as np
|
101 |
+
|
102 |
+
G, center = _process_params(G, center, dim)
|
103 |
+
pos = seed.rand(len(G), dim) + center
|
104 |
+
pos = pos.astype(np.float32)
|
105 |
+
pos = dict(zip(G, pos))
|
106 |
+
|
107 |
+
return pos
|
108 |
+
|
109 |
+
|
110 |
+
def circular_layout(G, scale=1, center=None, dim=2):
|
111 |
+
# dim=2 only
|
112 |
+
"""Position nodes on a circle.
|
113 |
+
|
114 |
+
Parameters
|
115 |
+
----------
|
116 |
+
G : NetworkX graph or list of nodes
|
117 |
+
A position will be assigned to every node in G.
|
118 |
+
|
119 |
+
scale : number (default: 1)
|
120 |
+
Scale factor for positions.
|
121 |
+
|
122 |
+
center : array-like or None
|
123 |
+
Coordinate pair around which to center the layout.
|
124 |
+
|
125 |
+
dim : int
|
126 |
+
Dimension of layout.
|
127 |
+
If dim>2, the remaining dimensions are set to zero
|
128 |
+
in the returned positions.
|
129 |
+
If dim<2, a ValueError is raised.
|
130 |
+
|
131 |
+
Returns
|
132 |
+
-------
|
133 |
+
pos : dict
|
134 |
+
A dictionary of positions keyed by node
|
135 |
+
|
136 |
+
Raises
|
137 |
+
------
|
138 |
+
ValueError
|
139 |
+
If dim < 2
|
140 |
+
|
141 |
+
Examples
|
142 |
+
--------
|
143 |
+
>>> G = nx.path_graph(4)
|
144 |
+
>>> pos = nx.circular_layout(G)
|
145 |
+
|
146 |
+
Notes
|
147 |
+
-----
|
148 |
+
This algorithm currently only works in two dimensions and does not
|
149 |
+
try to minimize edge crossings.
|
150 |
+
|
151 |
+
"""
|
152 |
+
import numpy as np
|
153 |
+
|
154 |
+
if dim < 2:
|
155 |
+
raise ValueError("cannot handle dimensions < 2")
|
156 |
+
|
157 |
+
G, center = _process_params(G, center, dim)
|
158 |
+
|
159 |
+
paddims = max(0, (dim - 2))
|
160 |
+
|
161 |
+
if len(G) == 0:
|
162 |
+
pos = {}
|
163 |
+
elif len(G) == 1:
|
164 |
+
pos = {nx.utils.arbitrary_element(G): center}
|
165 |
+
else:
|
166 |
+
# Discard the extra angle since it matches 0 radians.
|
167 |
+
theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
|
168 |
+
theta = theta.astype(np.float32)
|
169 |
+
pos = np.column_stack(
|
170 |
+
[np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
|
171 |
+
)
|
172 |
+
pos = rescale_layout(pos, scale=scale) + center
|
173 |
+
pos = dict(zip(G, pos))
|
174 |
+
|
175 |
+
return pos
|
176 |
+
|
177 |
+
|
178 |
+
def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2):
|
179 |
+
"""Position nodes in concentric circles.
|
180 |
+
|
181 |
+
Parameters
|
182 |
+
----------
|
183 |
+
G : NetworkX graph or list of nodes
|
184 |
+
A position will be assigned to every node in G.
|
185 |
+
|
186 |
+
nlist : list of lists
|
187 |
+
List of node lists for each shell.
|
188 |
+
|
189 |
+
rotate : angle in radians (default=pi/len(nlist))
|
190 |
+
Angle by which to rotate the starting position of each shell
|
191 |
+
relative to the starting position of the previous shell.
|
192 |
+
To recreate behavior before v2.5 use rotate=0.
|
193 |
+
|
194 |
+
scale : number (default: 1)
|
195 |
+
Scale factor for positions.
|
196 |
+
|
197 |
+
center : array-like or None
|
198 |
+
Coordinate pair around which to center the layout.
|
199 |
+
|
200 |
+
dim : int
|
201 |
+
Dimension of layout, currently only dim=2 is supported.
|
202 |
+
Other dimension values result in a ValueError.
|
203 |
+
|
204 |
+
Returns
|
205 |
+
-------
|
206 |
+
pos : dict
|
207 |
+
A dictionary of positions keyed by node
|
208 |
+
|
209 |
+
Raises
|
210 |
+
------
|
211 |
+
ValueError
|
212 |
+
If dim != 2
|
213 |
+
|
214 |
+
Examples
|
215 |
+
--------
|
216 |
+
>>> G = nx.path_graph(4)
|
217 |
+
>>> shells = [[0], [1, 2, 3]]
|
218 |
+
>>> pos = nx.shell_layout(G, shells)
|
219 |
+
|
220 |
+
Notes
|
221 |
+
-----
|
222 |
+
This algorithm currently only works in two dimensions and does not
|
223 |
+
try to minimize edge crossings.
|
224 |
+
|
225 |
+
"""
|
226 |
+
import numpy as np
|
227 |
+
|
228 |
+
if dim != 2:
|
229 |
+
raise ValueError("can only handle 2 dimensions")
|
230 |
+
|
231 |
+
G, center = _process_params(G, center, dim)
|
232 |
+
|
233 |
+
if len(G) == 0:
|
234 |
+
return {}
|
235 |
+
if len(G) == 1:
|
236 |
+
return {nx.utils.arbitrary_element(G): center}
|
237 |
+
|
238 |
+
if nlist is None:
|
239 |
+
# draw the whole graph in one shell
|
240 |
+
nlist = [list(G)]
|
241 |
+
|
242 |
+
radius_bump = scale / len(nlist)
|
243 |
+
|
244 |
+
if len(nlist[0]) == 1:
|
245 |
+
# single node at center
|
246 |
+
radius = 0.0
|
247 |
+
else:
|
248 |
+
# else start at r=1
|
249 |
+
radius = radius_bump
|
250 |
+
|
251 |
+
if rotate is None:
|
252 |
+
rotate = np.pi / len(nlist)
|
253 |
+
first_theta = rotate
|
254 |
+
npos = {}
|
255 |
+
for nodes in nlist:
|
256 |
+
# Discard the last angle (endpoint=False) since 2*pi matches 0 radians
|
257 |
+
theta = (
|
258 |
+
np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
|
259 |
+
+ first_theta
|
260 |
+
)
|
261 |
+
pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
|
262 |
+
npos.update(zip(nodes, pos))
|
263 |
+
radius += radius_bump
|
264 |
+
first_theta += rotate
|
265 |
+
|
266 |
+
return npos
|
267 |
+
|
268 |
+
|
269 |
+
def bipartite_layout(
|
270 |
+
G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3
|
271 |
+
):
|
272 |
+
"""Position nodes in two straight lines.
|
273 |
+
|
274 |
+
Parameters
|
275 |
+
----------
|
276 |
+
G : NetworkX graph or list of nodes
|
277 |
+
A position will be assigned to every node in G.
|
278 |
+
|
279 |
+
nodes : list or container
|
280 |
+
Nodes in one node set of the bipartite graph.
|
281 |
+
This set will be placed on left or top.
|
282 |
+
|
283 |
+
align : string (default='vertical')
|
284 |
+
The alignment of nodes. Vertical or horizontal.
|
285 |
+
|
286 |
+
scale : number (default: 1)
|
287 |
+
Scale factor for positions.
|
288 |
+
|
289 |
+
center : array-like or None
|
290 |
+
Coordinate pair around which to center the layout.
|
291 |
+
|
292 |
+
aspect_ratio : number (default=4/3):
|
293 |
+
The ratio of the width to the height of the layout.
|
294 |
+
|
295 |
+
Returns
|
296 |
+
-------
|
297 |
+
pos : dict
|
298 |
+
A dictionary of positions keyed by node.
|
299 |
+
|
300 |
+
Examples
|
301 |
+
--------
|
302 |
+
>>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
|
303 |
+
>>> top = nx.bipartite.sets(G)[0]
|
304 |
+
>>> pos = nx.bipartite_layout(G, top)
|
305 |
+
|
306 |
+
Notes
|
307 |
+
-----
|
308 |
+
This algorithm currently only works in two dimensions and does not
|
309 |
+
try to minimize edge crossings.
|
310 |
+
|
311 |
+
"""
|
312 |
+
|
313 |
+
import numpy as np
|
314 |
+
|
315 |
+
if align not in ("vertical", "horizontal"):
|
316 |
+
msg = "align must be either vertical or horizontal."
|
317 |
+
raise ValueError(msg)
|
318 |
+
|
319 |
+
G, center = _process_params(G, center=center, dim=2)
|
320 |
+
if len(G) == 0:
|
321 |
+
return {}
|
322 |
+
|
323 |
+
height = 1
|
324 |
+
width = aspect_ratio * height
|
325 |
+
offset = (width / 2, height / 2)
|
326 |
+
|
327 |
+
top = dict.fromkeys(nodes)
|
328 |
+
bottom = [v for v in G if v not in top]
|
329 |
+
nodes = list(top) + bottom
|
330 |
+
|
331 |
+
left_xs = np.repeat(0, len(top))
|
332 |
+
right_xs = np.repeat(width, len(bottom))
|
333 |
+
left_ys = np.linspace(0, height, len(top))
|
334 |
+
right_ys = np.linspace(0, height, len(bottom))
|
335 |
+
|
336 |
+
top_pos = np.column_stack([left_xs, left_ys]) - offset
|
337 |
+
bottom_pos = np.column_stack([right_xs, right_ys]) - offset
|
338 |
+
|
339 |
+
pos = np.concatenate([top_pos, bottom_pos])
|
340 |
+
pos = rescale_layout(pos, scale=scale) + center
|
341 |
+
if align == "horizontal":
|
342 |
+
pos = pos[:, ::-1] # swap x and y coords
|
343 |
+
pos = dict(zip(nodes, pos))
|
344 |
+
return pos
|
345 |
+
|
346 |
+
|
347 |
+
@np_random_state(10)
|
348 |
+
def spring_layout(
|
349 |
+
G,
|
350 |
+
k=None,
|
351 |
+
pos=None,
|
352 |
+
fixed=None,
|
353 |
+
iterations=50,
|
354 |
+
threshold=1e-4,
|
355 |
+
weight="weight",
|
356 |
+
scale=1,
|
357 |
+
center=None,
|
358 |
+
dim=2,
|
359 |
+
seed=None,
|
360 |
+
):
|
361 |
+
"""Position nodes using Fruchterman-Reingold force-directed algorithm.
|
362 |
+
|
363 |
+
The algorithm simulates a force-directed representation of the network
|
364 |
+
treating edges as springs holding nodes close, while treating nodes
|
365 |
+
as repelling objects, sometimes called an anti-gravity force.
|
366 |
+
Simulation continues until the positions are close to an equilibrium.
|
367 |
+
|
368 |
+
There are some hard-coded values: minimal distance between
|
369 |
+
nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
|
370 |
+
During the simulation, `k` helps determine the distance between nodes,
|
371 |
+
though `scale` and `center` determine the size and place after
|
372 |
+
rescaling occurs at the end of the simulation.
|
373 |
+
|
374 |
+
Fixing some nodes doesn't allow them to move in the simulation.
|
375 |
+
It also turns off the rescaling feature at the simulation's end.
|
376 |
+
In addition, setting `scale` to `None` turns off rescaling.
|
377 |
+
|
378 |
+
Parameters
|
379 |
+
----------
|
380 |
+
G : NetworkX graph or list of nodes
|
381 |
+
A position will be assigned to every node in G.
|
382 |
+
|
383 |
+
k : float (default=None)
|
384 |
+
Optimal distance between nodes. If None the distance is set to
|
385 |
+
1/sqrt(n) where n is the number of nodes. Increase this value
|
386 |
+
to move nodes farther apart.
|
387 |
+
|
388 |
+
pos : dict or None optional (default=None)
|
389 |
+
Initial positions for nodes as a dictionary with node as keys
|
390 |
+
and values as a coordinate list or tuple. If None, then use
|
391 |
+
random initial positions.
|
392 |
+
|
393 |
+
fixed : list or None optional (default=None)
|
394 |
+
Nodes to keep fixed at initial position.
|
395 |
+
Nodes not in ``G.nodes`` are ignored.
|
396 |
+
ValueError raised if `fixed` specified and `pos` not.
|
397 |
+
|
398 |
+
iterations : int optional (default=50)
|
399 |
+
Maximum number of iterations taken
|
400 |
+
|
401 |
+
threshold: float optional (default = 1e-4)
|
402 |
+
Threshold for relative error in node position changes.
|
403 |
+
The iteration stops if the error is below this threshold.
|
404 |
+
|
405 |
+
weight : string or None optional (default='weight')
|
406 |
+
The edge attribute that holds the numerical value used for
|
407 |
+
the edge weight. Larger means a stronger attractive force.
|
408 |
+
If None, then all edge weights are 1.
|
409 |
+
|
410 |
+
scale : number or None (default: 1)
|
411 |
+
Scale factor for positions. Not used unless `fixed is None`.
|
412 |
+
If scale is None, no rescaling is performed.
|
413 |
+
|
414 |
+
center : array-like or None
|
415 |
+
Coordinate pair around which to center the layout.
|
416 |
+
Not used unless `fixed is None`.
|
417 |
+
|
418 |
+
dim : int
|
419 |
+
Dimension of layout.
|
420 |
+
|
421 |
+
seed : int, RandomState instance or None optional (default=None)
|
422 |
+
Set the random state for deterministic node layouts.
|
423 |
+
If int, `seed` is the seed used by the random number generator,
|
424 |
+
if numpy.random.RandomState instance, `seed` is the random
|
425 |
+
number generator,
|
426 |
+
if None, the random number generator is the RandomState instance used
|
427 |
+
by numpy.random.
|
428 |
+
|
429 |
+
Returns
|
430 |
+
-------
|
431 |
+
pos : dict
|
432 |
+
A dictionary of positions keyed by node
|
433 |
+
|
434 |
+
Examples
|
435 |
+
--------
|
436 |
+
>>> G = nx.path_graph(4)
|
437 |
+
>>> pos = nx.spring_layout(G)
|
438 |
+
|
439 |
+
# The same using longer but equivalent function name
|
440 |
+
>>> pos = nx.fruchterman_reingold_layout(G)
|
441 |
+
"""
|
442 |
+
import numpy as np
|
443 |
+
|
444 |
+
G, center = _process_params(G, center, dim)
|
445 |
+
|
446 |
+
if fixed is not None:
|
447 |
+
if pos is None:
|
448 |
+
raise ValueError("nodes are fixed without positions given")
|
449 |
+
for node in fixed:
|
450 |
+
if node not in pos:
|
451 |
+
raise ValueError("nodes are fixed without positions given")
|
452 |
+
nfixed = {node: i for i, node in enumerate(G)}
|
453 |
+
fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
|
454 |
+
|
455 |
+
if pos is not None:
|
456 |
+
# Determine size of existing domain to adjust initial positions
|
457 |
+
dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
|
458 |
+
if dom_size == 0:
|
459 |
+
dom_size = 1
|
460 |
+
pos_arr = seed.rand(len(G), dim) * dom_size + center
|
461 |
+
|
462 |
+
for i, n in enumerate(G):
|
463 |
+
if n in pos:
|
464 |
+
pos_arr[i] = np.asarray(pos[n])
|
465 |
+
else:
|
466 |
+
pos_arr = None
|
467 |
+
dom_size = 1
|
468 |
+
|
469 |
+
if len(G) == 0:
|
470 |
+
return {}
|
471 |
+
if len(G) == 1:
|
472 |
+
return {nx.utils.arbitrary_element(G.nodes()): center}
|
473 |
+
|
474 |
+
try:
|
475 |
+
# Sparse matrix
|
476 |
+
if len(G) < 500: # sparse solver for large graphs
|
477 |
+
raise ValueError
|
478 |
+
A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
|
479 |
+
if k is None and fixed is not None:
|
480 |
+
# We must adjust k by domain size for layouts not near 1x1
|
481 |
+
nnodes, _ = A.shape
|
482 |
+
k = dom_size / np.sqrt(nnodes)
|
483 |
+
pos = _sparse_fruchterman_reingold(
|
484 |
+
A, k, pos_arr, fixed, iterations, threshold, dim, seed
|
485 |
+
)
|
486 |
+
except ValueError:
|
487 |
+
A = nx.to_numpy_array(G, weight=weight)
|
488 |
+
if k is None and fixed is not None:
|
489 |
+
# We must adjust k by domain size for layouts not near 1x1
|
490 |
+
nnodes, _ = A.shape
|
491 |
+
k = dom_size / np.sqrt(nnodes)
|
492 |
+
pos = _fruchterman_reingold(
|
493 |
+
A, k, pos_arr, fixed, iterations, threshold, dim, seed
|
494 |
+
)
|
495 |
+
if fixed is None and scale is not None:
|
496 |
+
pos = rescale_layout(pos, scale=scale) + center
|
497 |
+
pos = dict(zip(G, pos))
|
498 |
+
return pos
|
499 |
+
|
500 |
+
|
501 |
+
fruchterman_reingold_layout = spring_layout
|
502 |
+
|
503 |
+
|
504 |
+
@np_random_state(7)
|
505 |
+
def _fruchterman_reingold(
|
506 |
+
A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
|
507 |
+
):
|
508 |
+
# Position nodes in adjacency matrix A using Fruchterman-Reingold
|
509 |
+
# Entry point for NetworkX graph is fruchterman_reingold_layout()
|
510 |
+
import numpy as np
|
511 |
+
|
512 |
+
try:
|
513 |
+
nnodes, _ = A.shape
|
514 |
+
except AttributeError as err:
|
515 |
+
msg = "fruchterman_reingold() takes an adjacency matrix as input"
|
516 |
+
raise nx.NetworkXError(msg) from err
|
517 |
+
|
518 |
+
if pos is None:
|
519 |
+
# random initial positions
|
520 |
+
pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
|
521 |
+
else:
|
522 |
+
# make sure positions are of same type as matrix
|
523 |
+
pos = pos.astype(A.dtype)
|
524 |
+
|
525 |
+
# optimal distance between nodes
|
526 |
+
if k is None:
|
527 |
+
k = np.sqrt(1.0 / nnodes)
|
528 |
+
# the initial "temperature" is about .1 of domain area (=1x1)
|
529 |
+
# this is the largest step allowed in the dynamics.
|
530 |
+
# We need to calculate this in case our fixed positions force our domain
|
531 |
+
# to be much bigger than 1x1
|
532 |
+
t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
|
533 |
+
# simple cooling scheme.
|
534 |
+
# linearly step down by dt on each iteration so last iteration is size dt.
|
535 |
+
dt = t / (iterations + 1)
|
536 |
+
delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
|
537 |
+
# the inscrutable (but fast) version
|
538 |
+
# this is still O(V^2)
|
539 |
+
# could use multilevel methods to speed this up significantly
|
540 |
+
for iteration in range(iterations):
|
541 |
+
# matrix of difference between points
|
542 |
+
delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
|
543 |
+
# distance between points
|
544 |
+
distance = np.linalg.norm(delta, axis=-1)
|
545 |
+
# enforce minimum distance of 0.01
|
546 |
+
np.clip(distance, 0.01, None, out=distance)
|
547 |
+
# displacement "force"
|
548 |
+
displacement = np.einsum(
|
549 |
+
"ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
|
550 |
+
)
|
551 |
+
# update positions
|
552 |
+
length = np.linalg.norm(displacement, axis=-1)
|
553 |
+
length = np.where(length < 0.01, 0.1, length)
|
554 |
+
delta_pos = np.einsum("ij,i->ij", displacement, t / length)
|
555 |
+
if fixed is not None:
|
556 |
+
# don't change positions of fixed nodes
|
557 |
+
delta_pos[fixed] = 0.0
|
558 |
+
pos += delta_pos
|
559 |
+
# cool temperature
|
560 |
+
t -= dt
|
561 |
+
if (np.linalg.norm(delta_pos) / nnodes) < threshold:
|
562 |
+
break
|
563 |
+
return pos
|
564 |
+
|
565 |
+
|
566 |
+
@np_random_state(7)
|
567 |
+
def _sparse_fruchterman_reingold(
|
568 |
+
A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
|
569 |
+
):
|
570 |
+
# Position nodes in adjacency matrix A using Fruchterman-Reingold
|
571 |
+
# Entry point for NetworkX graph is fruchterman_reingold_layout()
|
572 |
+
# Sparse version
|
573 |
+
import numpy as np
|
574 |
+
import scipy as sp
|
575 |
+
|
576 |
+
try:
|
577 |
+
nnodes, _ = A.shape
|
578 |
+
except AttributeError as err:
|
579 |
+
msg = "fruchterman_reingold() takes an adjacency matrix as input"
|
580 |
+
raise nx.NetworkXError(msg) from err
|
581 |
+
# make sure we have a LIst of Lists representation
|
582 |
+
try:
|
583 |
+
A = A.tolil()
|
584 |
+
except AttributeError:
|
585 |
+
A = (sp.sparse.coo_array(A)).tolil()
|
586 |
+
|
587 |
+
if pos is None:
|
588 |
+
# random initial positions
|
589 |
+
pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
|
590 |
+
else:
|
591 |
+
# make sure positions are of same type as matrix
|
592 |
+
pos = pos.astype(A.dtype)
|
593 |
+
|
594 |
+
# no fixed nodes
|
595 |
+
if fixed is None:
|
596 |
+
fixed = []
|
597 |
+
|
598 |
+
# optimal distance between nodes
|
599 |
+
if k is None:
|
600 |
+
k = np.sqrt(1.0 / nnodes)
|
601 |
+
# the initial "temperature" is about .1 of domain area (=1x1)
|
602 |
+
# this is the largest step allowed in the dynamics.
|
603 |
+
t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
|
604 |
+
# simple cooling scheme.
|
605 |
+
# linearly step down by dt on each iteration so last iteration is size dt.
|
606 |
+
dt = t / (iterations + 1)
|
607 |
+
|
608 |
+
displacement = np.zeros((dim, nnodes))
|
609 |
+
for iteration in range(iterations):
|
610 |
+
displacement *= 0
|
611 |
+
# loop over rows
|
612 |
+
for i in range(A.shape[0]):
|
613 |
+
if i in fixed:
|
614 |
+
continue
|
615 |
+
# difference between this row's node position and all others
|
616 |
+
delta = (pos[i] - pos).T
|
617 |
+
# distance between points
|
618 |
+
distance = np.sqrt((delta**2).sum(axis=0))
|
619 |
+
# enforce minimum distance of 0.01
|
620 |
+
distance = np.where(distance < 0.01, 0.01, distance)
|
621 |
+
# the adjacency matrix row
|
622 |
+
Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
|
623 |
+
# displacement "force"
|
624 |
+
displacement[:, i] += (
|
625 |
+
delta * (k * k / distance**2 - Ai * distance / k)
|
626 |
+
).sum(axis=1)
|
627 |
+
# update positions
|
628 |
+
length = np.sqrt((displacement**2).sum(axis=0))
|
629 |
+
length = np.where(length < 0.01, 0.1, length)
|
630 |
+
delta_pos = (displacement * t / length).T
|
631 |
+
pos += delta_pos
|
632 |
+
# cool temperature
|
633 |
+
t -= dt
|
634 |
+
if (np.linalg.norm(delta_pos) / nnodes) < threshold:
|
635 |
+
break
|
636 |
+
return pos
|
637 |
+
|
638 |
+
|
639 |
+
def kamada_kawai_layout(
|
640 |
+
G, dist=None, pos=None, weight="weight", scale=1, center=None, dim=2
|
641 |
+
):
|
642 |
+
"""Position nodes using Kamada-Kawai path-length cost-function.
|
643 |
+
|
644 |
+
Parameters
|
645 |
+
----------
|
646 |
+
G : NetworkX graph or list of nodes
|
647 |
+
A position will be assigned to every node in G.
|
648 |
+
|
649 |
+
dist : dict (default=None)
|
650 |
+
A two-level dictionary of optimal distances between nodes,
|
651 |
+
indexed by source and destination node.
|
652 |
+
If None, the distance is computed using shortest_path_length().
|
653 |
+
|
654 |
+
pos : dict or None optional (default=None)
|
655 |
+
Initial positions for nodes as a dictionary with node as keys
|
656 |
+
and values as a coordinate list or tuple. If None, then use
|
657 |
+
circular_layout() for dim >= 2 and a linear layout for dim == 1.
|
658 |
+
|
659 |
+
weight : string or None optional (default='weight')
|
660 |
+
The edge attribute that holds the numerical value used for
|
661 |
+
the edge weight. If None, then all edge weights are 1.
|
662 |
+
|
663 |
+
scale : number (default: 1)
|
664 |
+
Scale factor for positions.
|
665 |
+
|
666 |
+
center : array-like or None
|
667 |
+
Coordinate pair around which to center the layout.
|
668 |
+
|
669 |
+
dim : int
|
670 |
+
Dimension of layout.
|
671 |
+
|
672 |
+
Returns
|
673 |
+
-------
|
674 |
+
pos : dict
|
675 |
+
A dictionary of positions keyed by node
|
676 |
+
|
677 |
+
Examples
|
678 |
+
--------
|
679 |
+
>>> G = nx.path_graph(4)
|
680 |
+
>>> pos = nx.kamada_kawai_layout(G)
|
681 |
+
"""
|
682 |
+
import numpy as np
|
683 |
+
|
684 |
+
G, center = _process_params(G, center, dim)
|
685 |
+
nNodes = len(G)
|
686 |
+
if nNodes == 0:
|
687 |
+
return {}
|
688 |
+
|
689 |
+
if dist is None:
|
690 |
+
dist = dict(nx.shortest_path_length(G, weight=weight))
|
691 |
+
dist_mtx = 1e6 * np.ones((nNodes, nNodes))
|
692 |
+
for row, nr in enumerate(G):
|
693 |
+
if nr not in dist:
|
694 |
+
continue
|
695 |
+
rdist = dist[nr]
|
696 |
+
for col, nc in enumerate(G):
|
697 |
+
if nc not in rdist:
|
698 |
+
continue
|
699 |
+
dist_mtx[row][col] = rdist[nc]
|
700 |
+
|
701 |
+
if pos is None:
|
702 |
+
if dim >= 3:
|
703 |
+
pos = random_layout(G, dim=dim)
|
704 |
+
elif dim == 2:
|
705 |
+
pos = circular_layout(G, dim=dim)
|
706 |
+
else:
|
707 |
+
pos = dict(zip(G, np.linspace(0, 1, len(G))))
|
708 |
+
pos_arr = np.array([pos[n] for n in G])
|
709 |
+
|
710 |
+
pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
|
711 |
+
|
712 |
+
pos = rescale_layout(pos, scale=scale) + center
|
713 |
+
return dict(zip(G, pos))
|
714 |
+
|
715 |
+
|
716 |
+
def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
|
717 |
+
# Anneal node locations based on the Kamada-Kawai cost-function,
|
718 |
+
# using the supplied matrix of preferred inter-node distances,
|
719 |
+
# and starting locations.
|
720 |
+
|
721 |
+
import numpy as np
|
722 |
+
import scipy as sp
|
723 |
+
|
724 |
+
meanwt = 1e-3
|
725 |
+
costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
|
726 |
+
|
727 |
+
optresult = sp.optimize.minimize(
|
728 |
+
_kamada_kawai_costfn,
|
729 |
+
pos_arr.ravel(),
|
730 |
+
method="L-BFGS-B",
|
731 |
+
args=costargs,
|
732 |
+
jac=True,
|
733 |
+
)
|
734 |
+
|
735 |
+
return optresult.x.reshape((-1, dim))
|
736 |
+
|
737 |
+
|
738 |
+
def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
|
739 |
+
# Cost-function and gradient for Kamada-Kawai layout algorithm
|
740 |
+
nNodes = invdist.shape[0]
|
741 |
+
pos_arr = pos_vec.reshape((nNodes, dim))
|
742 |
+
|
743 |
+
delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
|
744 |
+
nodesep = np.linalg.norm(delta, axis=-1)
|
745 |
+
direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
|
746 |
+
|
747 |
+
offset = nodesep * invdist - 1.0
|
748 |
+
offset[np.diag_indices(nNodes)] = 0
|
749 |
+
|
750 |
+
cost = 0.5 * np.sum(offset**2)
|
751 |
+
grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
|
752 |
+
"ij,ij,ijk->jk", invdist, offset, direction
|
753 |
+
)
|
754 |
+
|
755 |
+
# Additional parabolic term to encourage mean position to be near origin:
|
756 |
+
sumpos = np.sum(pos_arr, axis=0)
|
757 |
+
cost += 0.5 * meanweight * np.sum(sumpos**2)
|
758 |
+
grad += meanweight * sumpos
|
759 |
+
|
760 |
+
return (cost, grad.ravel())
|
761 |
+
|
762 |
+
|
763 |
+
def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
|
764 |
+
"""Position nodes using the eigenvectors of the graph Laplacian.
|
765 |
+
|
766 |
+
Using the unnormalized Laplacian, the layout shows possible clusters of
|
767 |
+
nodes which are an approximation of the ratio cut. If dim is the number of
|
768 |
+
dimensions then the positions are the entries of the dim eigenvectors
|
769 |
+
corresponding to the ascending eigenvalues starting from the second one.
|
770 |
+
|
771 |
+
Parameters
|
772 |
+
----------
|
773 |
+
G : NetworkX graph or list of nodes
|
774 |
+
A position will be assigned to every node in G.
|
775 |
+
|
776 |
+
weight : string or None optional (default='weight')
|
777 |
+
The edge attribute that holds the numerical value used for
|
778 |
+
the edge weight. If None, then all edge weights are 1.
|
779 |
+
|
780 |
+
scale : number (default: 1)
|
781 |
+
Scale factor for positions.
|
782 |
+
|
783 |
+
center : array-like or None
|
784 |
+
Coordinate pair around which to center the layout.
|
785 |
+
|
786 |
+
dim : int
|
787 |
+
Dimension of layout.
|
788 |
+
|
789 |
+
Returns
|
790 |
+
-------
|
791 |
+
pos : dict
|
792 |
+
A dictionary of positions keyed by node
|
793 |
+
|
794 |
+
Examples
|
795 |
+
--------
|
796 |
+
>>> G = nx.path_graph(4)
|
797 |
+
>>> pos = nx.spectral_layout(G)
|
798 |
+
|
799 |
+
Notes
|
800 |
+
-----
|
801 |
+
Directed graphs will be considered as undirected graphs when
|
802 |
+
positioning the nodes.
|
803 |
+
|
804 |
+
For larger graphs (>500 nodes) this will use the SciPy sparse
|
805 |
+
eigenvalue solver (ARPACK).
|
806 |
+
"""
|
807 |
+
# handle some special cases that break the eigensolvers
|
808 |
+
import numpy as np
|
809 |
+
|
810 |
+
G, center = _process_params(G, center, dim)
|
811 |
+
|
812 |
+
if len(G) <= 2:
|
813 |
+
if len(G) == 0:
|
814 |
+
pos = np.array([])
|
815 |
+
elif len(G) == 1:
|
816 |
+
pos = np.array([center])
|
817 |
+
else:
|
818 |
+
pos = np.array([np.zeros(dim), np.array(center) * 2.0])
|
819 |
+
return dict(zip(G, pos))
|
820 |
+
try:
|
821 |
+
# Sparse matrix
|
822 |
+
if len(G) < 500: # dense solver is faster for small graphs
|
823 |
+
raise ValueError
|
824 |
+
A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
|
825 |
+
# Symmetrize directed graphs
|
826 |
+
if G.is_directed():
|
827 |
+
A = A + np.transpose(A)
|
828 |
+
pos = _sparse_spectral(A, dim)
|
829 |
+
except (ImportError, ValueError):
|
830 |
+
# Dense matrix
|
831 |
+
A = nx.to_numpy_array(G, weight=weight)
|
832 |
+
# Symmetrize directed graphs
|
833 |
+
if G.is_directed():
|
834 |
+
A += A.T
|
835 |
+
pos = _spectral(A, dim)
|
836 |
+
|
837 |
+
pos = rescale_layout(pos, scale=scale) + center
|
838 |
+
pos = dict(zip(G, pos))
|
839 |
+
return pos
|
840 |
+
|
841 |
+
|
842 |
+
def _spectral(A, dim=2):
|
843 |
+
# Input adjacency matrix A
|
844 |
+
# Uses dense eigenvalue solver from numpy
|
845 |
+
import numpy as np
|
846 |
+
|
847 |
+
try:
|
848 |
+
nnodes, _ = A.shape
|
849 |
+
except AttributeError as err:
|
850 |
+
msg = "spectral() takes an adjacency matrix as input"
|
851 |
+
raise nx.NetworkXError(msg) from err
|
852 |
+
|
853 |
+
# form Laplacian matrix where D is diagonal of degrees
|
854 |
+
D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
|
855 |
+
L = D - A
|
856 |
+
|
857 |
+
eigenvalues, eigenvectors = np.linalg.eig(L)
|
858 |
+
# sort and keep smallest nonzero
|
859 |
+
index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
|
860 |
+
return np.real(eigenvectors[:, index])
|
861 |
+
|
862 |
+
|
863 |
+
def _sparse_spectral(A, dim=2):
|
864 |
+
# Input adjacency matrix A
|
865 |
+
# Uses sparse eigenvalue solver from scipy
|
866 |
+
# Could use multilevel methods here, see Koren "On spectral graph drawing"
|
867 |
+
import numpy as np
|
868 |
+
import scipy as sp
|
869 |
+
|
870 |
+
try:
|
871 |
+
nnodes, _ = A.shape
|
872 |
+
except AttributeError as err:
|
873 |
+
msg = "sparse_spectral() takes an adjacency matrix as input"
|
874 |
+
raise nx.NetworkXError(msg) from err
|
875 |
+
|
876 |
+
# form Laplacian matrix
|
877 |
+
# TODO: Rm csr_array wrapper in favor of spdiags array constructor when available
|
878 |
+
D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, nnodes, nnodes))
|
879 |
+
L = D - A
|
880 |
+
|
881 |
+
k = dim + 1
|
882 |
+
# number of Lanczos vectors for ARPACK solver.What is the right scaling?
|
883 |
+
ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
|
884 |
+
# return smallest k eigenvalues and eigenvectors
|
885 |
+
eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
|
886 |
+
index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
|
887 |
+
return np.real(eigenvectors[:, index])
|
888 |
+
|
889 |
+
|
890 |
+
def planar_layout(G, scale=1, center=None, dim=2):
|
891 |
+
"""Position nodes without edge intersections.
|
892 |
+
|
893 |
+
Parameters
|
894 |
+
----------
|
895 |
+
G : NetworkX graph or list of nodes
|
896 |
+
A position will be assigned to every node in G. If G is of type
|
897 |
+
nx.PlanarEmbedding, the positions are selected accordingly.
|
898 |
+
|
899 |
+
scale : number (default: 1)
|
900 |
+
Scale factor for positions.
|
901 |
+
|
902 |
+
center : array-like or None
|
903 |
+
Coordinate pair around which to center the layout.
|
904 |
+
|
905 |
+
dim : int
|
906 |
+
Dimension of layout.
|
907 |
+
|
908 |
+
Returns
|
909 |
+
-------
|
910 |
+
pos : dict
|
911 |
+
A dictionary of positions keyed by node
|
912 |
+
|
913 |
+
Raises
|
914 |
+
------
|
915 |
+
NetworkXException
|
916 |
+
If G is not planar
|
917 |
+
|
918 |
+
Examples
|
919 |
+
--------
|
920 |
+
>>> G = nx.path_graph(4)
|
921 |
+
>>> pos = nx.planar_layout(G)
|
922 |
+
"""
|
923 |
+
import numpy as np
|
924 |
+
|
925 |
+
if dim != 2:
|
926 |
+
raise ValueError("can only handle 2 dimensions")
|
927 |
+
|
928 |
+
G, center = _process_params(G, center, dim)
|
929 |
+
|
930 |
+
if len(G) == 0:
|
931 |
+
return {}
|
932 |
+
|
933 |
+
if isinstance(G, nx.PlanarEmbedding):
|
934 |
+
embedding = G
|
935 |
+
else:
|
936 |
+
is_planar, embedding = nx.check_planarity(G)
|
937 |
+
if not is_planar:
|
938 |
+
raise nx.NetworkXException("G is not planar.")
|
939 |
+
pos = nx.combinatorial_embedding_to_pos(embedding)
|
940 |
+
node_list = list(embedding)
|
941 |
+
pos = np.vstack([pos[x] for x in node_list])
|
942 |
+
pos = pos.astype(np.float64)
|
943 |
+
pos = rescale_layout(pos, scale=scale) + center
|
944 |
+
return dict(zip(node_list, pos))
|
945 |
+
|
946 |
+
|
947 |
+
def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False):
|
948 |
+
"""Position nodes in a spiral layout.
|
949 |
+
|
950 |
+
Parameters
|
951 |
+
----------
|
952 |
+
G : NetworkX graph or list of nodes
|
953 |
+
A position will be assigned to every node in G.
|
954 |
+
scale : number (default: 1)
|
955 |
+
Scale factor for positions.
|
956 |
+
center : array-like or None
|
957 |
+
Coordinate pair around which to center the layout.
|
958 |
+
dim : int, default=2
|
959 |
+
Dimension of layout, currently only dim=2 is supported.
|
960 |
+
Other dimension values result in a ValueError.
|
961 |
+
resolution : float, default=0.35
|
962 |
+
The compactness of the spiral layout returned.
|
963 |
+
Lower values result in more compressed spiral layouts.
|
964 |
+
equidistant : bool, default=False
|
965 |
+
If True, nodes will be positioned equidistant from each other
|
966 |
+
by decreasing angle further from center.
|
967 |
+
If False, nodes will be positioned at equal angles
|
968 |
+
from each other by increasing separation further from center.
|
969 |
+
|
970 |
+
Returns
|
971 |
+
-------
|
972 |
+
pos : dict
|
973 |
+
A dictionary of positions keyed by node
|
974 |
+
|
975 |
+
Raises
|
976 |
+
------
|
977 |
+
ValueError
|
978 |
+
If dim != 2
|
979 |
+
|
980 |
+
Examples
|
981 |
+
--------
|
982 |
+
>>> G = nx.path_graph(4)
|
983 |
+
>>> pos = nx.spiral_layout(G)
|
984 |
+
>>> nx.draw(G, pos=pos)
|
985 |
+
|
986 |
+
Notes
|
987 |
+
-----
|
988 |
+
This algorithm currently only works in two dimensions.
|
989 |
+
|
990 |
+
"""
|
991 |
+
import numpy as np
|
992 |
+
|
993 |
+
if dim != 2:
|
994 |
+
raise ValueError("can only handle 2 dimensions")
|
995 |
+
|
996 |
+
G, center = _process_params(G, center, dim)
|
997 |
+
|
998 |
+
if len(G) == 0:
|
999 |
+
return {}
|
1000 |
+
if len(G) == 1:
|
1001 |
+
return {nx.utils.arbitrary_element(G): center}
|
1002 |
+
|
1003 |
+
pos = []
|
1004 |
+
if equidistant:
|
1005 |
+
chord = 1
|
1006 |
+
step = 0.5
|
1007 |
+
theta = resolution
|
1008 |
+
theta += chord / (step * theta)
|
1009 |
+
for _ in range(len(G)):
|
1010 |
+
r = step * theta
|
1011 |
+
theta += chord / r
|
1012 |
+
pos.append([np.cos(theta) * r, np.sin(theta) * r])
|
1013 |
+
|
1014 |
+
else:
|
1015 |
+
dist = np.arange(len(G), dtype=float)
|
1016 |
+
angle = resolution * dist
|
1017 |
+
pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
|
1018 |
+
|
1019 |
+
pos = rescale_layout(np.array(pos), scale=scale) + center
|
1020 |
+
|
1021 |
+
pos = dict(zip(G, pos))
|
1022 |
+
|
1023 |
+
return pos
|
1024 |
+
|
1025 |
+
|
1026 |
+
def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
|
1027 |
+
"""Position nodes in layers of straight lines.
|
1028 |
+
|
1029 |
+
Parameters
|
1030 |
+
----------
|
1031 |
+
G : NetworkX graph or list of nodes
|
1032 |
+
A position will be assigned to every node in G.
|
1033 |
+
|
1034 |
+
subset_key : string or dict (default='subset')
|
1035 |
+
If a string, the key of node data in G that holds the node subset.
|
1036 |
+
If a dict, keyed by layer number to the nodes in that layer/subset.
|
1037 |
+
|
1038 |
+
align : string (default='vertical')
|
1039 |
+
The alignment of nodes. Vertical or horizontal.
|
1040 |
+
|
1041 |
+
scale : number (default: 1)
|
1042 |
+
Scale factor for positions.
|
1043 |
+
|
1044 |
+
center : array-like or None
|
1045 |
+
Coordinate pair around which to center the layout.
|
1046 |
+
|
1047 |
+
Returns
|
1048 |
+
-------
|
1049 |
+
pos : dict
|
1050 |
+
A dictionary of positions keyed by node.
|
1051 |
+
|
1052 |
+
Examples
|
1053 |
+
--------
|
1054 |
+
>>> G = nx.complete_multipartite_graph(28, 16, 10)
|
1055 |
+
>>> pos = nx.multipartite_layout(G)
|
1056 |
+
|
1057 |
+
or use a dict to provide the layers of the layout
|
1058 |
+
|
1059 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
|
1060 |
+
>>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
|
1061 |
+
>>> pos = nx.multipartite_layout(G, subset_key=layers)
|
1062 |
+
|
1063 |
+
Notes
|
1064 |
+
-----
|
1065 |
+
This algorithm currently only works in two dimensions and does not
|
1066 |
+
try to minimize edge crossings.
|
1067 |
+
|
1068 |
+
Network does not need to be a complete multipartite graph. As long as nodes
|
1069 |
+
have subset_key data, they will be placed in the corresponding layers.
|
1070 |
+
|
1071 |
+
"""
|
1072 |
+
import numpy as np
|
1073 |
+
|
1074 |
+
if align not in ("vertical", "horizontal"):
|
1075 |
+
msg = "align must be either vertical or horizontal."
|
1076 |
+
raise ValueError(msg)
|
1077 |
+
|
1078 |
+
G, center = _process_params(G, center=center, dim=2)
|
1079 |
+
if len(G) == 0:
|
1080 |
+
return {}
|
1081 |
+
|
1082 |
+
try:
|
1083 |
+
# check if subset_key is dict-like
|
1084 |
+
if len(G) != sum(len(nodes) for nodes in subset_key.values()):
|
1085 |
+
raise nx.NetworkXError(
|
1086 |
+
"all nodes must be in one subset of `subset_key` dict"
|
1087 |
+
)
|
1088 |
+
except AttributeError:
|
1089 |
+
# subset_key is not a dict, hence a string
|
1090 |
+
node_to_subset = nx.get_node_attributes(G, subset_key)
|
1091 |
+
if len(node_to_subset) != len(G):
|
1092 |
+
raise nx.NetworkXError(
|
1093 |
+
f"all nodes need a subset_key attribute: {subset_key}"
|
1094 |
+
)
|
1095 |
+
subset_key = nx.utils.groups(node_to_subset)
|
1096 |
+
|
1097 |
+
# Sort by layer, if possible
|
1098 |
+
try:
|
1099 |
+
layers = dict(sorted(subset_key.items()))
|
1100 |
+
except TypeError:
|
1101 |
+
layers = subset_key
|
1102 |
+
|
1103 |
+
pos = None
|
1104 |
+
nodes = []
|
1105 |
+
width = len(layers)
|
1106 |
+
for i, layer in enumerate(layers.values()):
|
1107 |
+
height = len(layer)
|
1108 |
+
xs = np.repeat(i, height)
|
1109 |
+
ys = np.arange(0, height, dtype=float)
|
1110 |
+
offset = ((width - 1) / 2, (height - 1) / 2)
|
1111 |
+
layer_pos = np.column_stack([xs, ys]) - offset
|
1112 |
+
if pos is None:
|
1113 |
+
pos = layer_pos
|
1114 |
+
else:
|
1115 |
+
pos = np.concatenate([pos, layer_pos])
|
1116 |
+
nodes.extend(layer)
|
1117 |
+
pos = rescale_layout(pos, scale=scale) + center
|
1118 |
+
if align == "horizontal":
|
1119 |
+
pos = pos[:, ::-1] # swap x and y coords
|
1120 |
+
pos = dict(zip(nodes, pos))
|
1121 |
+
return pos
|
1122 |
+
|
1123 |
+
|
1124 |
+
def arf_layout(
|
1125 |
+
G,
|
1126 |
+
pos=None,
|
1127 |
+
scaling=1,
|
1128 |
+
a=1.1,
|
1129 |
+
etol=1e-6,
|
1130 |
+
dt=1e-3,
|
1131 |
+
max_iter=1000,
|
1132 |
+
):
|
1133 |
+
"""Arf layout for networkx
|
1134 |
+
|
1135 |
+
The attractive and repulsive forces (arf) layout [1]
|
1136 |
+
improves the spring layout in three ways. First, it
|
1137 |
+
prevents congestion of highly connected nodes due to
|
1138 |
+
strong forcing between nodes. Second, it utilizes the
|
1139 |
+
layout space more effectively by preventing large gaps
|
1140 |
+
that spring layout tends to create. Lastly, the arf
|
1141 |
+
layout represents symmetries in the layout better than
|
1142 |
+
the default spring layout.
|
1143 |
+
|
1144 |
+
Parameters
|
1145 |
+
----------
|
1146 |
+
G : nx.Graph or nx.DiGraph
|
1147 |
+
Networkx graph.
|
1148 |
+
pos : dict
|
1149 |
+
Initial position of the nodes. If set to None a
|
1150 |
+
random layout will be used.
|
1151 |
+
scaling : float
|
1152 |
+
Scales the radius of the circular layout space.
|
1153 |
+
a : float
|
1154 |
+
Strength of springs between connected nodes. Should be larger than 1. The greater a, the clearer the separation ofunconnected sub clusters.
|
1155 |
+
etol : float
|
1156 |
+
Gradient sum of spring forces must be larger than `etol` before successful termination.
|
1157 |
+
dt : float
|
1158 |
+
Time step for force differential equation simulations.
|
1159 |
+
max_iter : int
|
1160 |
+
Max iterations before termination of the algorithm.
|
1161 |
+
|
1162 |
+
References
|
1163 |
+
.. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
|
1164 |
+
International Journal of Modern Physics C, 2007, Vol 18, No 10, pp. 1537-1549.
|
1165 |
+
https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
|
1166 |
+
|
1167 |
+
Returns
|
1168 |
+
-------
|
1169 |
+
pos : dict
|
1170 |
+
A dictionary of positions keyed by node.
|
1171 |
+
|
1172 |
+
Examples
|
1173 |
+
--------
|
1174 |
+
>>> G = nx.grid_graph((5, 5))
|
1175 |
+
>>> pos = nx.arf_layout(G)
|
1176 |
+
|
1177 |
+
"""
|
1178 |
+
import warnings
|
1179 |
+
|
1180 |
+
import numpy as np
|
1181 |
+
|
1182 |
+
if a <= 1:
|
1183 |
+
msg = "The parameter a should be larger than 1"
|
1184 |
+
raise ValueError(msg)
|
1185 |
+
|
1186 |
+
pos_tmp = nx.random_layout(G)
|
1187 |
+
if pos is None:
|
1188 |
+
pos = pos_tmp
|
1189 |
+
else:
|
1190 |
+
for node in G.nodes():
|
1191 |
+
if node not in pos:
|
1192 |
+
pos[node] = pos_tmp[node].copy()
|
1193 |
+
|
1194 |
+
# Initialize spring constant matrix
|
1195 |
+
N = len(G)
|
1196 |
+
# No nodes no computation
|
1197 |
+
if N == 0:
|
1198 |
+
return pos
|
1199 |
+
|
1200 |
+
# init force of springs
|
1201 |
+
K = np.ones((N, N)) - np.eye(N)
|
1202 |
+
node_order = {node: i for i, node in enumerate(G)}
|
1203 |
+
for x, y in G.edges():
|
1204 |
+
if x != y:
|
1205 |
+
idx, jdx = (node_order[i] for i in (x, y))
|
1206 |
+
K[idx, jdx] = a
|
1207 |
+
|
1208 |
+
# vectorize values
|
1209 |
+
p = np.asarray(list(pos.values()))
|
1210 |
+
|
1211 |
+
# equation 10 in [1]
|
1212 |
+
rho = scaling * np.sqrt(N)
|
1213 |
+
|
1214 |
+
# looping variables
|
1215 |
+
error = etol + 1
|
1216 |
+
n_iter = 0
|
1217 |
+
while error > etol:
|
1218 |
+
diff = p[:, np.newaxis] - p[np.newaxis]
|
1219 |
+
A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
|
1220 |
+
# attraction_force - repulsions force
|
1221 |
+
# suppress nans due to division; caused by diagonal set to zero.
|
1222 |
+
# Does not affect the computation due to nansum
|
1223 |
+
with warnings.catch_warnings():
|
1224 |
+
warnings.simplefilter("ignore")
|
1225 |
+
change = K[..., np.newaxis] * diff - rho / A * diff
|
1226 |
+
change = np.nansum(change, axis=0)
|
1227 |
+
p += change * dt
|
1228 |
+
|
1229 |
+
error = np.linalg.norm(change, axis=-1).sum()
|
1230 |
+
if n_iter > max_iter:
|
1231 |
+
break
|
1232 |
+
n_iter += 1
|
1233 |
+
return dict(zip(G.nodes(), p))
|
1234 |
+
|
1235 |
+
|
1236 |
+
def rescale_layout(pos, scale=1):
|
1237 |
+
"""Returns scaled position array to (-scale, scale) in all axes.
|
1238 |
+
|
1239 |
+
The function acts on NumPy arrays which hold position information.
|
1240 |
+
Each position is one row of the array. The dimension of the space
|
1241 |
+
equals the number of columns. Each coordinate in one column.
|
1242 |
+
|
1243 |
+
To rescale, the mean (center) is subtracted from each axis separately.
|
1244 |
+
Then all values are scaled so that the largest magnitude value
|
1245 |
+
from all axes equals `scale` (thus, the aspect ratio is preserved).
|
1246 |
+
The resulting NumPy Array is returned (order of rows unchanged).
|
1247 |
+
|
1248 |
+
Parameters
|
1249 |
+
----------
|
1250 |
+
pos : numpy array
|
1251 |
+
positions to be scaled. Each row is a position.
|
1252 |
+
|
1253 |
+
scale : number (default: 1)
|
1254 |
+
The size of the resulting extent in all directions.
|
1255 |
+
|
1256 |
+
Returns
|
1257 |
+
-------
|
1258 |
+
pos : numpy array
|
1259 |
+
scaled positions. Each row is a position.
|
1260 |
+
|
1261 |
+
See Also
|
1262 |
+
--------
|
1263 |
+
rescale_layout_dict
|
1264 |
+
"""
|
1265 |
+
import numpy as np
|
1266 |
+
|
1267 |
+
# Find max length over all dimensions
|
1268 |
+
pos -= pos.mean(axis=0)
|
1269 |
+
lim = np.abs(pos).max() # max coordinate for all axes
|
1270 |
+
# rescale to (-scale, scale) in all directions, preserves aspect
|
1271 |
+
if lim > 0:
|
1272 |
+
pos *= scale / lim
|
1273 |
+
return pos
|
1274 |
+
|
1275 |
+
|
1276 |
+
def rescale_layout_dict(pos, scale=1):
|
1277 |
+
"""Return a dictionary of scaled positions keyed by node
|
1278 |
+
|
1279 |
+
Parameters
|
1280 |
+
----------
|
1281 |
+
pos : A dictionary of positions keyed by node
|
1282 |
+
|
1283 |
+
scale : number (default: 1)
|
1284 |
+
The size of the resulting extent in all directions.
|
1285 |
+
|
1286 |
+
Returns
|
1287 |
+
-------
|
1288 |
+
pos : A dictionary of positions keyed by node
|
1289 |
+
|
1290 |
+
Examples
|
1291 |
+
--------
|
1292 |
+
>>> import numpy as np
|
1293 |
+
>>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
|
1294 |
+
>>> nx.rescale_layout_dict(pos)
|
1295 |
+
{0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
|
1296 |
+
|
1297 |
+
>>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
|
1298 |
+
>>> nx.rescale_layout_dict(pos, scale=2)
|
1299 |
+
{0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
|
1300 |
+
|
1301 |
+
See Also
|
1302 |
+
--------
|
1303 |
+
rescale_layout
|
1304 |
+
"""
|
1305 |
+
import numpy as np
|
1306 |
+
|
1307 |
+
if not pos: # empty_graph
|
1308 |
+
return {}
|
1309 |
+
pos_v = np.array(list(pos.values()))
|
1310 |
+
pos_v = rescale_layout(pos_v, scale=scale)
|
1311 |
+
return dict(zip(pos, pos_v))
|
1312 |
+
|
1313 |
+
|
1314 |
+
def bfs_layout(G, start, *, align="vertical", scale=1, center=None):
|
1315 |
+
"""Position nodes according to breadth-first search algorithm.
|
1316 |
+
|
1317 |
+
Parameters
|
1318 |
+
----------
|
1319 |
+
G : NetworkX graph
|
1320 |
+
A position will be assigned to every node in G.
|
1321 |
+
|
1322 |
+
start : node in `G`
|
1323 |
+
Starting node for bfs
|
1324 |
+
|
1325 |
+
center : array-like or None
|
1326 |
+
Coordinate pair around which to center the layout.
|
1327 |
+
|
1328 |
+
Returns
|
1329 |
+
-------
|
1330 |
+
pos : dict
|
1331 |
+
A dictionary of positions keyed by node.
|
1332 |
+
|
1333 |
+
Examples
|
1334 |
+
--------
|
1335 |
+
>>> G = nx.path_graph(4)
|
1336 |
+
>>> pos = nx.bfs_layout(G, 0)
|
1337 |
+
|
1338 |
+
Notes
|
1339 |
+
-----
|
1340 |
+
This algorithm currently only works in two dimensions and does not
|
1341 |
+
try to minimize edge crossings.
|
1342 |
+
|
1343 |
+
"""
|
1344 |
+
G, center = _process_params(G, center, 2)
|
1345 |
+
|
1346 |
+
# Compute layers with BFS
|
1347 |
+
layers = dict(enumerate(nx.bfs_layers(G, start)))
|
1348 |
+
|
1349 |
+
if len(G) != sum(len(nodes) for nodes in layers.values()):
|
1350 |
+
raise nx.NetworkXError(
|
1351 |
+
"bfs_layout didn't include all nodes. Perhaps use input graph:\n"
|
1352 |
+
" G.subgraph(nx.node_connected_component(G, start))"
|
1353 |
+
)
|
1354 |
+
|
1355 |
+
# Compute node positions with multipartite_layout
|
1356 |
+
return multipartite_layout(
|
1357 |
+
G, subset_key=layers, align=align, scale=scale, center=center
|
1358 |
+
)
|
venv/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py
ADDED
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
***************
|
3 |
+
Graphviz AGraph
|
4 |
+
***************
|
5 |
+
|
6 |
+
Interface to pygraphviz AGraph class.
|
7 |
+
|
8 |
+
Examples
|
9 |
+
--------
|
10 |
+
>>> G = nx.complete_graph(5)
|
11 |
+
>>> A = nx.nx_agraph.to_agraph(G)
|
12 |
+
>>> H = nx.nx_agraph.from_agraph(A)
|
13 |
+
|
14 |
+
See Also
|
15 |
+
--------
|
16 |
+
- Pygraphviz: http://pygraphviz.github.io/
|
17 |
+
- Graphviz: https://www.graphviz.org
|
18 |
+
- DOT Language: http://www.graphviz.org/doc/info/lang.html
|
19 |
+
"""
|
20 |
+
import os
|
21 |
+
import tempfile
|
22 |
+
|
23 |
+
import networkx as nx
|
24 |
+
|
25 |
+
__all__ = [
|
26 |
+
"from_agraph",
|
27 |
+
"to_agraph",
|
28 |
+
"write_dot",
|
29 |
+
"read_dot",
|
30 |
+
"graphviz_layout",
|
31 |
+
"pygraphviz_layout",
|
32 |
+
"view_pygraphviz",
|
33 |
+
]
|
34 |
+
|
35 |
+
|
36 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
37 |
+
def from_agraph(A, create_using=None):
|
38 |
+
"""Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
|
39 |
+
|
40 |
+
Parameters
|
41 |
+
----------
|
42 |
+
A : PyGraphviz AGraph
|
43 |
+
A graph created with PyGraphviz
|
44 |
+
|
45 |
+
create_using : NetworkX graph constructor, optional (default=None)
|
46 |
+
Graph type to create. If graph instance, then cleared before populated.
|
47 |
+
If `None`, then the appropriate Graph type is inferred from `A`.
|
48 |
+
|
49 |
+
Examples
|
50 |
+
--------
|
51 |
+
>>> K5 = nx.complete_graph(5)
|
52 |
+
>>> A = nx.nx_agraph.to_agraph(K5)
|
53 |
+
>>> G = nx.nx_agraph.from_agraph(A)
|
54 |
+
|
55 |
+
Notes
|
56 |
+
-----
|
57 |
+
The Graph G will have a dictionary G.graph_attr containing
|
58 |
+
the default graphviz attributes for graphs, nodes and edges.
|
59 |
+
|
60 |
+
Default node attributes will be in the dictionary G.node_attr
|
61 |
+
which is keyed by node.
|
62 |
+
|
63 |
+
Edge attributes will be returned as edge data in G. With
|
64 |
+
edge_attr=False the edge data will be the Graphviz edge weight
|
65 |
+
attribute or the value 1 if no edge weight attribute is found.
|
66 |
+
|
67 |
+
"""
|
68 |
+
if create_using is None:
|
69 |
+
if A.is_directed():
|
70 |
+
if A.is_strict():
|
71 |
+
create_using = nx.DiGraph
|
72 |
+
else:
|
73 |
+
create_using = nx.MultiDiGraph
|
74 |
+
else:
|
75 |
+
if A.is_strict():
|
76 |
+
create_using = nx.Graph
|
77 |
+
else:
|
78 |
+
create_using = nx.MultiGraph
|
79 |
+
|
80 |
+
# assign defaults
|
81 |
+
N = nx.empty_graph(0, create_using)
|
82 |
+
if A.name is not None:
|
83 |
+
N.name = A.name
|
84 |
+
|
85 |
+
# add graph attributes
|
86 |
+
N.graph.update(A.graph_attr)
|
87 |
+
|
88 |
+
# add nodes, attributes to N.node_attr
|
89 |
+
for n in A.nodes():
|
90 |
+
str_attr = {str(k): v for k, v in n.attr.items()}
|
91 |
+
N.add_node(str(n), **str_attr)
|
92 |
+
|
93 |
+
# add edges, assign edge data as dictionary of attributes
|
94 |
+
for e in A.edges():
|
95 |
+
u, v = str(e[0]), str(e[1])
|
96 |
+
attr = dict(e.attr)
|
97 |
+
str_attr = {str(k): v for k, v in attr.items()}
|
98 |
+
if not N.is_multigraph():
|
99 |
+
if e.name is not None:
|
100 |
+
str_attr["key"] = e.name
|
101 |
+
N.add_edge(u, v, **str_attr)
|
102 |
+
else:
|
103 |
+
N.add_edge(u, v, key=e.name, **str_attr)
|
104 |
+
|
105 |
+
# add default attributes for graph, nodes, and edges
|
106 |
+
# hang them on N.graph_attr
|
107 |
+
N.graph["graph"] = dict(A.graph_attr)
|
108 |
+
N.graph["node"] = dict(A.node_attr)
|
109 |
+
N.graph["edge"] = dict(A.edge_attr)
|
110 |
+
return N
|
111 |
+
|
112 |
+
|
113 |
+
def to_agraph(N):
|
114 |
+
"""Returns a pygraphviz graph from a NetworkX graph N.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
----------
|
118 |
+
N : NetworkX graph
|
119 |
+
A graph created with NetworkX
|
120 |
+
|
121 |
+
Examples
|
122 |
+
--------
|
123 |
+
>>> K5 = nx.complete_graph(5)
|
124 |
+
>>> A = nx.nx_agraph.to_agraph(K5)
|
125 |
+
|
126 |
+
Notes
|
127 |
+
-----
|
128 |
+
If N has an dict N.graph_attr an attempt will be made first
|
129 |
+
to copy properties attached to the graph (see from_agraph)
|
130 |
+
and then updated with the calling arguments if any.
|
131 |
+
|
132 |
+
"""
|
133 |
+
try:
|
134 |
+
import pygraphviz
|
135 |
+
except ImportError as err:
|
136 |
+
raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
|
137 |
+
directed = N.is_directed()
|
138 |
+
strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
|
139 |
+
|
140 |
+
for node in N:
|
141 |
+
if "pos" in N.nodes[node]:
|
142 |
+
N.nodes[node]["pos"] = "{},{}!".format(
|
143 |
+
N.nodes[node]["pos"][0], N.nodes[node]["pos"][1]
|
144 |
+
)
|
145 |
+
|
146 |
+
A = pygraphviz.AGraph(name=N.name, strict=strict, directed=directed)
|
147 |
+
|
148 |
+
# default graph attributes
|
149 |
+
A.graph_attr.update(N.graph.get("graph", {}))
|
150 |
+
A.node_attr.update(N.graph.get("node", {}))
|
151 |
+
A.edge_attr.update(N.graph.get("edge", {}))
|
152 |
+
|
153 |
+
A.graph_attr.update(
|
154 |
+
(k, v) for k, v in N.graph.items() if k not in ("graph", "node", "edge")
|
155 |
+
)
|
156 |
+
|
157 |
+
# add nodes
|
158 |
+
for n, nodedata in N.nodes(data=True):
|
159 |
+
A.add_node(n)
|
160 |
+
# Add node data
|
161 |
+
a = A.get_node(n)
|
162 |
+
a.attr.update({k: str(v) for k, v in nodedata.items()})
|
163 |
+
|
164 |
+
# loop over edges
|
165 |
+
if N.is_multigraph():
|
166 |
+
for u, v, key, edgedata in N.edges(data=True, keys=True):
|
167 |
+
str_edgedata = {k: str(v) for k, v in edgedata.items() if k != "key"}
|
168 |
+
A.add_edge(u, v, key=str(key))
|
169 |
+
# Add edge data
|
170 |
+
a = A.get_edge(u, v)
|
171 |
+
a.attr.update(str_edgedata)
|
172 |
+
|
173 |
+
else:
|
174 |
+
for u, v, edgedata in N.edges(data=True):
|
175 |
+
str_edgedata = {k: str(v) for k, v in edgedata.items()}
|
176 |
+
A.add_edge(u, v)
|
177 |
+
# Add edge data
|
178 |
+
a = A.get_edge(u, v)
|
179 |
+
a.attr.update(str_edgedata)
|
180 |
+
|
181 |
+
return A
|
182 |
+
|
183 |
+
|
184 |
+
def write_dot(G, path):
|
185 |
+
"""Write NetworkX graph G to Graphviz dot format on path.
|
186 |
+
|
187 |
+
Parameters
|
188 |
+
----------
|
189 |
+
G : graph
|
190 |
+
A networkx graph
|
191 |
+
path : filename
|
192 |
+
Filename or file handle to write
|
193 |
+
|
194 |
+
Notes
|
195 |
+
-----
|
196 |
+
To use a specific graph layout, call ``A.layout`` prior to `write_dot`.
|
197 |
+
Note that some graphviz layouts are not guaranteed to be deterministic,
|
198 |
+
see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
|
199 |
+
"""
|
200 |
+
A = to_agraph(G)
|
201 |
+
A.write(path)
|
202 |
+
A.clear()
|
203 |
+
return
|
204 |
+
|
205 |
+
|
206 |
+
@nx._dispatchable(name="agraph_read_dot", graphs=None, returns_graph=True)
|
207 |
+
def read_dot(path):
|
208 |
+
"""Returns a NetworkX graph from a dot file on path.
|
209 |
+
|
210 |
+
Parameters
|
211 |
+
----------
|
212 |
+
path : file or string
|
213 |
+
File name or file handle to read.
|
214 |
+
"""
|
215 |
+
try:
|
216 |
+
import pygraphviz
|
217 |
+
except ImportError as err:
|
218 |
+
raise ImportError(
|
219 |
+
"read_dot() requires pygraphviz http://pygraphviz.github.io/"
|
220 |
+
) from err
|
221 |
+
A = pygraphviz.AGraph(file=path)
|
222 |
+
gr = from_agraph(A)
|
223 |
+
A.clear()
|
224 |
+
return gr
|
225 |
+
|
226 |
+
|
227 |
+
def graphviz_layout(G, prog="neato", root=None, args=""):
|
228 |
+
"""Create node positions for G using Graphviz.
|
229 |
+
|
230 |
+
Parameters
|
231 |
+
----------
|
232 |
+
G : NetworkX graph
|
233 |
+
A graph created with NetworkX
|
234 |
+
prog : string
|
235 |
+
Name of Graphviz layout program
|
236 |
+
root : string, optional
|
237 |
+
Root node for twopi layout
|
238 |
+
args : string, optional
|
239 |
+
Extra arguments to Graphviz layout program
|
240 |
+
|
241 |
+
Returns
|
242 |
+
-------
|
243 |
+
Dictionary of x, y, positions keyed by node.
|
244 |
+
|
245 |
+
Examples
|
246 |
+
--------
|
247 |
+
>>> G = nx.petersen_graph()
|
248 |
+
>>> pos = nx.nx_agraph.graphviz_layout(G)
|
249 |
+
>>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
|
250 |
+
|
251 |
+
Notes
|
252 |
+
-----
|
253 |
+
This is a wrapper for pygraphviz_layout.
|
254 |
+
|
255 |
+
Note that some graphviz layouts are not guaranteed to be deterministic,
|
256 |
+
see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
|
257 |
+
"""
|
258 |
+
return pygraphviz_layout(G, prog=prog, root=root, args=args)
|
259 |
+
|
260 |
+
|
261 |
+
def pygraphviz_layout(G, prog="neato", root=None, args=""):
|
262 |
+
"""Create node positions for G using Graphviz.
|
263 |
+
|
264 |
+
Parameters
|
265 |
+
----------
|
266 |
+
G : NetworkX graph
|
267 |
+
A graph created with NetworkX
|
268 |
+
prog : string
|
269 |
+
Name of Graphviz layout program
|
270 |
+
root : string, optional
|
271 |
+
Root node for twopi layout
|
272 |
+
args : string, optional
|
273 |
+
Extra arguments to Graphviz layout program
|
274 |
+
|
275 |
+
Returns
|
276 |
+
-------
|
277 |
+
node_pos : dict
|
278 |
+
Dictionary of x, y, positions keyed by node.
|
279 |
+
|
280 |
+
Examples
|
281 |
+
--------
|
282 |
+
>>> G = nx.petersen_graph()
|
283 |
+
>>> pos = nx.nx_agraph.graphviz_layout(G)
|
284 |
+
>>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
|
285 |
+
|
286 |
+
Notes
|
287 |
+
-----
|
288 |
+
If you use complex node objects, they may have the same string
|
289 |
+
representation and GraphViz could treat them as the same node.
|
290 |
+
The layout may assign both nodes a single location. See Issue #1568
|
291 |
+
If this occurs in your case, consider relabeling the nodes just
|
292 |
+
for the layout computation using something similar to::
|
293 |
+
|
294 |
+
>>> H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
|
295 |
+
>>> H_layout = nx.nx_agraph.pygraphviz_layout(G, prog="dot")
|
296 |
+
>>> G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
|
297 |
+
|
298 |
+
Note that some graphviz layouts are not guaranteed to be deterministic,
|
299 |
+
see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
|
300 |
+
"""
|
301 |
+
try:
|
302 |
+
import pygraphviz
|
303 |
+
except ImportError as err:
|
304 |
+
raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
|
305 |
+
if root is not None:
|
306 |
+
args += f"-Groot={root}"
|
307 |
+
A = to_agraph(G)
|
308 |
+
A.layout(prog=prog, args=args)
|
309 |
+
node_pos = {}
|
310 |
+
for n in G:
|
311 |
+
node = pygraphviz.Node(A, n)
|
312 |
+
try:
|
313 |
+
xs = node.attr["pos"].split(",")
|
314 |
+
node_pos[n] = tuple(float(x) for x in xs)
|
315 |
+
except:
|
316 |
+
print("no position for node", n)
|
317 |
+
node_pos[n] = (0.0, 0.0)
|
318 |
+
return node_pos
|
319 |
+
|
320 |
+
|
321 |
+
@nx.utils.open_file(5, "w+b")
|
322 |
+
def view_pygraphviz(
|
323 |
+
G, edgelabel=None, prog="dot", args="", suffix="", path=None, show=True
|
324 |
+
):
|
325 |
+
"""Views the graph G using the specified layout algorithm.
|
326 |
+
|
327 |
+
Parameters
|
328 |
+
----------
|
329 |
+
G : NetworkX graph
|
330 |
+
The machine to draw.
|
331 |
+
edgelabel : str, callable, None
|
332 |
+
If a string, then it specifies the edge attribute to be displayed
|
333 |
+
on the edge labels. If a callable, then it is called for each
|
334 |
+
edge and it should return the string to be displayed on the edges.
|
335 |
+
The function signature of `edgelabel` should be edgelabel(data),
|
336 |
+
where `data` is the edge attribute dictionary.
|
337 |
+
prog : string
|
338 |
+
Name of Graphviz layout program.
|
339 |
+
args : str
|
340 |
+
Additional arguments to pass to the Graphviz layout program.
|
341 |
+
suffix : str
|
342 |
+
If `filename` is None, we save to a temporary file. The value of
|
343 |
+
`suffix` will appear at the tail end of the temporary filename.
|
344 |
+
path : str, None
|
345 |
+
The filename used to save the image. If None, save to a temporary
|
346 |
+
file. File formats are the same as those from pygraphviz.agraph.draw.
|
347 |
+
show : bool, default = True
|
348 |
+
Whether to display the graph with :mod:`PIL.Image.show`,
|
349 |
+
default is `True`. If `False`, the rendered graph is still available
|
350 |
+
at `path`.
|
351 |
+
|
352 |
+
Returns
|
353 |
+
-------
|
354 |
+
path : str
|
355 |
+
The filename of the generated image.
|
356 |
+
A : PyGraphviz graph
|
357 |
+
The PyGraphviz graph instance used to generate the image.
|
358 |
+
|
359 |
+
Notes
|
360 |
+
-----
|
361 |
+
If this function is called in succession too quickly, sometimes the
|
362 |
+
image is not displayed. So you might consider time.sleep(.5) between
|
363 |
+
calls if you experience problems.
|
364 |
+
|
365 |
+
Note that some graphviz layouts are not guaranteed to be deterministic,
|
366 |
+
see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
|
367 |
+
|
368 |
+
"""
|
369 |
+
if not len(G):
|
370 |
+
raise nx.NetworkXException("An empty graph cannot be drawn.")
|
371 |
+
|
372 |
+
# If we are providing default values for graphviz, these must be set
|
373 |
+
# before any nodes or edges are added to the PyGraphviz graph object.
|
374 |
+
# The reason for this is that default values only affect incoming objects.
|
375 |
+
# If you change the default values after the objects have been added,
|
376 |
+
# then they inherit no value and are set only if explicitly set.
|
377 |
+
|
378 |
+
# to_agraph() uses these values.
|
379 |
+
attrs = ["edge", "node", "graph"]
|
380 |
+
for attr in attrs:
|
381 |
+
if attr not in G.graph:
|
382 |
+
G.graph[attr] = {}
|
383 |
+
|
384 |
+
# These are the default values.
|
385 |
+
edge_attrs = {"fontsize": "10"}
|
386 |
+
node_attrs = {
|
387 |
+
"style": "filled",
|
388 |
+
"fillcolor": "#0000FF40",
|
389 |
+
"height": "0.75",
|
390 |
+
"width": "0.75",
|
391 |
+
"shape": "circle",
|
392 |
+
}
|
393 |
+
graph_attrs = {}
|
394 |
+
|
395 |
+
def update_attrs(which, attrs):
|
396 |
+
# Update graph attributes. Return list of those which were added.
|
397 |
+
added = []
|
398 |
+
for k, v in attrs.items():
|
399 |
+
if k not in G.graph[which]:
|
400 |
+
G.graph[which][k] = v
|
401 |
+
added.append(k)
|
402 |
+
|
403 |
+
def clean_attrs(which, added):
|
404 |
+
# Remove added attributes
|
405 |
+
for attr in added:
|
406 |
+
del G.graph[which][attr]
|
407 |
+
if not G.graph[which]:
|
408 |
+
del G.graph[which]
|
409 |
+
|
410 |
+
# Update all default values
|
411 |
+
update_attrs("edge", edge_attrs)
|
412 |
+
update_attrs("node", node_attrs)
|
413 |
+
update_attrs("graph", graph_attrs)
|
414 |
+
|
415 |
+
# Convert to agraph, so we inherit default values
|
416 |
+
A = to_agraph(G)
|
417 |
+
|
418 |
+
# Remove the default values we added to the original graph.
|
419 |
+
clean_attrs("edge", edge_attrs)
|
420 |
+
clean_attrs("node", node_attrs)
|
421 |
+
clean_attrs("graph", graph_attrs)
|
422 |
+
|
423 |
+
# If the user passed in an edgelabel, we update the labels for all edges.
|
424 |
+
if edgelabel is not None:
|
425 |
+
if not callable(edgelabel):
|
426 |
+
|
427 |
+
def func(data):
|
428 |
+
return "".join([" ", str(data[edgelabel]), " "])
|
429 |
+
|
430 |
+
else:
|
431 |
+
func = edgelabel
|
432 |
+
|
433 |
+
# update all the edge labels
|
434 |
+
if G.is_multigraph():
|
435 |
+
for u, v, key, data in G.edges(keys=True, data=True):
|
436 |
+
# PyGraphviz doesn't convert the key to a string. See #339
|
437 |
+
edge = A.get_edge(u, v, str(key))
|
438 |
+
edge.attr["label"] = str(func(data))
|
439 |
+
else:
|
440 |
+
for u, v, data in G.edges(data=True):
|
441 |
+
edge = A.get_edge(u, v)
|
442 |
+
edge.attr["label"] = str(func(data))
|
443 |
+
|
444 |
+
if path is None:
|
445 |
+
ext = "png"
|
446 |
+
if suffix:
|
447 |
+
suffix = f"_{suffix}.{ext}"
|
448 |
+
else:
|
449 |
+
suffix = f".{ext}"
|
450 |
+
path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
|
451 |
+
else:
|
452 |
+
# Assume the decorator worked and it is a file-object.
|
453 |
+
pass
|
454 |
+
|
455 |
+
# Write graph to file
|
456 |
+
A.draw(path=path, format=None, prog=prog, args=args)
|
457 |
+
path.close()
|
458 |
+
|
459 |
+
# Show graph in a new window (depends on platform configuration)
|
460 |
+
if show:
|
461 |
+
from PIL import Image
|
462 |
+
|
463 |
+
Image.open(path.name).show()
|
464 |
+
|
465 |
+
return path.name, A
|
venv/lib/python3.10/site-packages/networkx/drawing/nx_latex.py
ADDED
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
r"""
|
2 |
+
*****
|
3 |
+
LaTeX
|
4 |
+
*****
|
5 |
+
|
6 |
+
Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
|
7 |
+
Usually, you will want the drawing to appear in a figure environment so
|
8 |
+
you use ``to_latex(G, caption="A caption")``. If you want the raw
|
9 |
+
drawing commands without a figure environment use :func:`to_latex_raw`.
|
10 |
+
And if you want to write to a file instead of just returning the latex
|
11 |
+
code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
|
12 |
+
|
13 |
+
To construct a figure with subfigures for each graph to be shown, provide
|
14 |
+
``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
|
15 |
+
and a number of rows of subfigures inside the figure.
|
16 |
+
|
17 |
+
To be able to refer to the figures or subfigures in latex using ``\\ref``,
|
18 |
+
the keyword ``latex_label`` is available for figures and `sub_labels` for
|
19 |
+
a list of labels, one for each subfigure.
|
20 |
+
|
21 |
+
We intend to eventually provide an interface to the TikZ Graph
|
22 |
+
features which include e.g. layout algorithms.
|
23 |
+
|
24 |
+
Let us know via github what you'd like to see available, or better yet
|
25 |
+
give us some code to do it, or even better make a github pull request
|
26 |
+
to add the feature.
|
27 |
+
|
28 |
+
The TikZ approach
|
29 |
+
=================
|
30 |
+
Drawing options can be stored on the graph as node/edge attributes, or
|
31 |
+
can be provided as dicts keyed by node/edge to a string of the options
|
32 |
+
for that node/edge. Similarly a label can be shown for each node/edge
|
33 |
+
by specifying the labels as graph node/edge attributes or by providing
|
34 |
+
a dict keyed by node/edge to the text to be written for that node/edge.
|
35 |
+
|
36 |
+
Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
|
37 |
+
via a keyword argument. Similarly default node and edge options can be
|
38 |
+
provided through keywords arguments. The default node options are applied
|
39 |
+
to the single TikZ "path" that draws all nodes (and no edges). The default edge
|
40 |
+
options are applied to a TikZ "scope" which contains a path for each edge.
|
41 |
+
|
42 |
+
Examples
|
43 |
+
========
|
44 |
+
>>> G = nx.path_graph(3)
|
45 |
+
>>> nx.write_latex(G, "just_my_figure.tex", as_document=True)
|
46 |
+
>>> nx.write_latex(G, "my_figure.tex", caption="A path graph", latex_label="fig1")
|
47 |
+
>>> latex_code = nx.to_latex(G) # a string rather than a file
|
48 |
+
|
49 |
+
You can change many features of the nodes and edges.
|
50 |
+
|
51 |
+
>>> G = nx.path_graph(4, create_using=nx.DiGraph)
|
52 |
+
>>> pos = {n: (n, n) for n in G} # nodes set on a line
|
53 |
+
|
54 |
+
>>> G.nodes[0]["style"] = "blue"
|
55 |
+
>>> G.nodes[2]["style"] = "line width=3,draw"
|
56 |
+
>>> G.nodes[3]["label"] = "Stop"
|
57 |
+
>>> G.edges[(0, 1)]["label"] = "1st Step"
|
58 |
+
>>> G.edges[(0, 1)]["label_opts"] = "near start"
|
59 |
+
>>> G.edges[(1, 2)]["style"] = "line width=3"
|
60 |
+
>>> G.edges[(1, 2)]["label"] = "2nd Step"
|
61 |
+
>>> G.edges[(2, 3)]["style"] = "green"
|
62 |
+
>>> G.edges[(2, 3)]["label"] = "3rd Step"
|
63 |
+
>>> G.edges[(2, 3)]["label_opts"] = "near end"
|
64 |
+
|
65 |
+
>>> nx.write_latex(G, "latex_graph.tex", pos=pos, as_document=True)
|
66 |
+
|
67 |
+
Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
|
68 |
+
and view the pdf file created: ``latex_graph.pdf``.
|
69 |
+
|
70 |
+
If you want **subfigures** each containing one graph, you can input a list of graphs.
|
71 |
+
|
72 |
+
>>> H1 = nx.path_graph(4)
|
73 |
+
>>> H2 = nx.complete_graph(4)
|
74 |
+
>>> H3 = nx.path_graph(8)
|
75 |
+
>>> H4 = nx.complete_graph(8)
|
76 |
+
>>> graphs = [H1, H2, H3, H4]
|
77 |
+
>>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
|
78 |
+
>>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
|
79 |
+
>>> nx.write_latex(graphs, "subfigs.tex", n_rows=2, sub_captions=caps, sub_labels=lbls)
|
80 |
+
>>> latex_code = nx.to_latex(graphs, n_rows=2, sub_captions=caps, sub_labels=lbls)
|
81 |
+
|
82 |
+
>>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
|
83 |
+
>>> edge_width = {e: "line width=1.5" for e in H3.edges}
|
84 |
+
>>> pos = nx.circular_layout(H3)
|
85 |
+
>>> latex_code = nx.to_latex(H3, pos, node_options=node_color, edge_options=edge_width)
|
86 |
+
>>> print(latex_code)
|
87 |
+
\documentclass{report}
|
88 |
+
\usepackage{tikz}
|
89 |
+
\usepackage{subcaption}
|
90 |
+
<BLANKLINE>
|
91 |
+
\begin{document}
|
92 |
+
\begin{figure}
|
93 |
+
\begin{tikzpicture}
|
94 |
+
\draw
|
95 |
+
(1.0, 0.0) node[red] (0){0}
|
96 |
+
(0.707, 0.707) node[orange] (1){1}
|
97 |
+
(-0.0, 1.0) node[blue] (2){2}
|
98 |
+
(-0.707, 0.707) node[gray!90] (3){3}
|
99 |
+
(-1.0, -0.0) node (4){4}
|
100 |
+
(-0.707, -0.707) node (5){5}
|
101 |
+
(0.0, -1.0) node (6){6}
|
102 |
+
(0.707, -0.707) node (7){7};
|
103 |
+
\begin{scope}[-]
|
104 |
+
\draw[line width=1.5] (0) to (1);
|
105 |
+
\draw[line width=1.5] (1) to (2);
|
106 |
+
\draw[line width=1.5] (2) to (3);
|
107 |
+
\draw[line width=1.5] (3) to (4);
|
108 |
+
\draw[line width=1.5] (4) to (5);
|
109 |
+
\draw[line width=1.5] (5) to (6);
|
110 |
+
\draw[line width=1.5] (6) to (7);
|
111 |
+
\end{scope}
|
112 |
+
\end{tikzpicture}
|
113 |
+
\end{figure}
|
114 |
+
\end{document}
|
115 |
+
|
116 |
+
Notes
|
117 |
+
-----
|
118 |
+
If you want to change the preamble/postamble of the figure/document/subfigure
|
119 |
+
environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
|
120 |
+
`subfigure_wrapper`. The default values are stored in private variables
|
121 |
+
e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
|
122 |
+
|
123 |
+
References
|
124 |
+
----------
|
125 |
+
TikZ: https://tikz.dev/
|
126 |
+
|
127 |
+
TikZ options details: https://tikz.dev/tikz-actions
|
128 |
+
"""
|
129 |
+
import numbers
|
130 |
+
import os
|
131 |
+
|
132 |
+
import networkx as nx
|
133 |
+
|
134 |
+
__all__ = [
|
135 |
+
"to_latex_raw",
|
136 |
+
"to_latex",
|
137 |
+
"write_latex",
|
138 |
+
]
|
139 |
+
|
140 |
+
|
141 |
+
@nx.utils.not_implemented_for("multigraph")
|
142 |
+
def to_latex_raw(
|
143 |
+
G,
|
144 |
+
pos="pos",
|
145 |
+
tikz_options="",
|
146 |
+
default_node_options="",
|
147 |
+
node_options="node_options",
|
148 |
+
node_label="label",
|
149 |
+
default_edge_options="",
|
150 |
+
edge_options="edge_options",
|
151 |
+
edge_label="label",
|
152 |
+
edge_label_options="edge_label_options",
|
153 |
+
):
|
154 |
+
"""Return a string of the LaTeX/TikZ code to draw `G`
|
155 |
+
|
156 |
+
This function produces just the code for the tikzpicture
|
157 |
+
without any enclosing environment.
|
158 |
+
|
159 |
+
Parameters
|
160 |
+
==========
|
161 |
+
G : NetworkX graph
|
162 |
+
The NetworkX graph to be drawn
|
163 |
+
pos : string or dict (default "pos")
|
164 |
+
The name of the node attribute on `G` that holds the position of each node.
|
165 |
+
Positions can be sequences of length 2 with numbers for (x,y) coordinates.
|
166 |
+
They can also be strings to denote positions in TikZ style, such as (x, y)
|
167 |
+
or (angle:radius).
|
168 |
+
If a dict, it should be keyed by node to a position.
|
169 |
+
If an empty dict, a circular layout is computed by TikZ.
|
170 |
+
tikz_options : string
|
171 |
+
The tikzpicture options description defining the options for the picture.
|
172 |
+
Often large scale options like `[scale=2]`.
|
173 |
+
default_node_options : string
|
174 |
+
The draw options for a path of nodes. Individual node options override these.
|
175 |
+
node_options : string or dict
|
176 |
+
The name of the node attribute on `G` that holds the options for each node.
|
177 |
+
Or a dict keyed by node to a string holding the options for that node.
|
178 |
+
node_label : string or dict
|
179 |
+
The name of the node attribute on `G` that holds the node label (text)
|
180 |
+
displayed for each node. If the attribute is "" or not present, the node
|
181 |
+
itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
|
182 |
+
Or a dict keyed by node to a string holding the label for that node.
|
183 |
+
default_edge_options : string
|
184 |
+
The options for the scope drawing all edges. The default is "[-]" for
|
185 |
+
undirected graphs and "[->]" for directed graphs.
|
186 |
+
edge_options : string or dict
|
187 |
+
The name of the edge attribute on `G` that holds the options for each edge.
|
188 |
+
If the edge is a self-loop and ``"loop" not in edge_options`` the option
|
189 |
+
"loop," is added to the options for the self-loop edge. Hence you can
|
190 |
+
use "[loop above]" explicitly, but the default is "[loop]".
|
191 |
+
Or a dict keyed by edge to a string holding the options for that edge.
|
192 |
+
edge_label : string or dict
|
193 |
+
The name of the edge attribute on `G` that holds the edge label (text)
|
194 |
+
displayed for each edge. If the attribute is "" or not present, no edge
|
195 |
+
label is drawn.
|
196 |
+
Or a dict keyed by edge to a string holding the label for that edge.
|
197 |
+
edge_label_options : string or dict
|
198 |
+
The name of the edge attribute on `G` that holds the label options for
|
199 |
+
each edge. For example, "[sloped,above,blue]". The default is no options.
|
200 |
+
Or a dict keyed by edge to a string holding the label options for that edge.
|
201 |
+
|
202 |
+
Returns
|
203 |
+
=======
|
204 |
+
latex_code : string
|
205 |
+
The text string which draws the desired graph(s) when compiled by LaTeX.
|
206 |
+
|
207 |
+
See Also
|
208 |
+
========
|
209 |
+
to_latex
|
210 |
+
write_latex
|
211 |
+
"""
|
212 |
+
i4 = "\n "
|
213 |
+
i8 = "\n "
|
214 |
+
|
215 |
+
# set up position dict
|
216 |
+
# TODO allow pos to be None and use a nice TikZ default
|
217 |
+
if not isinstance(pos, dict):
|
218 |
+
pos = nx.get_node_attributes(G, pos)
|
219 |
+
if not pos:
|
220 |
+
# circular layout with radius 2
|
221 |
+
pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
|
222 |
+
for node in G:
|
223 |
+
if node not in pos:
|
224 |
+
raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
|
225 |
+
posnode = pos[node]
|
226 |
+
if not isinstance(posnode, str):
|
227 |
+
try:
|
228 |
+
posx, posy = posnode
|
229 |
+
pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
|
230 |
+
except (TypeError, ValueError):
|
231 |
+
msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
|
232 |
+
raise nx.NetworkXError(msg)
|
233 |
+
|
234 |
+
# set up all the dicts
|
235 |
+
if not isinstance(node_options, dict):
|
236 |
+
node_options = nx.get_node_attributes(G, node_options)
|
237 |
+
if not isinstance(node_label, dict):
|
238 |
+
node_label = nx.get_node_attributes(G, node_label)
|
239 |
+
if not isinstance(edge_options, dict):
|
240 |
+
edge_options = nx.get_edge_attributes(G, edge_options)
|
241 |
+
if not isinstance(edge_label, dict):
|
242 |
+
edge_label = nx.get_edge_attributes(G, edge_label)
|
243 |
+
if not isinstance(edge_label_options, dict):
|
244 |
+
edge_label_options = nx.get_edge_attributes(G, edge_label_options)
|
245 |
+
|
246 |
+
# process default options (add brackets or not)
|
247 |
+
topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
|
248 |
+
defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
|
249 |
+
linestyle = f"{'->' if G.is_directed() else '-'}"
|
250 |
+
if default_edge_options == "":
|
251 |
+
defe = "[" + linestyle + "]"
|
252 |
+
elif "-" in default_edge_options:
|
253 |
+
defe = default_edge_options
|
254 |
+
else:
|
255 |
+
defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
|
256 |
+
|
257 |
+
# Construct the string line by line
|
258 |
+
result = " \\begin{tikzpicture}" + topts
|
259 |
+
result += i4 + " \\draw" + defn
|
260 |
+
# load the nodes
|
261 |
+
for n in G:
|
262 |
+
# node options goes inside square brackets
|
263 |
+
nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
|
264 |
+
# node text goes inside curly brackets {}
|
265 |
+
ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
|
266 |
+
|
267 |
+
result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
|
268 |
+
result += ";\n"
|
269 |
+
|
270 |
+
# load the edges
|
271 |
+
result += " \\begin{scope}" + defe
|
272 |
+
for edge in G.edges:
|
273 |
+
u, v = edge[:2]
|
274 |
+
e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
|
275 |
+
# add loop options for selfloops if not present
|
276 |
+
if u == v and "loop" not in e_opts:
|
277 |
+
e_opts = "loop," + e_opts
|
278 |
+
e_opts = f"[{e_opts}]" if e_opts != "" else ""
|
279 |
+
# TODO -- handle bending of multiedges
|
280 |
+
|
281 |
+
els = edge_label_options[edge] if edge in edge_label_options else ""
|
282 |
+
# edge label options goes inside square brackets []
|
283 |
+
els = f"[{els.strip('[]')}]"
|
284 |
+
# edge text is drawn using the TikZ node command inside curly brackets {}
|
285 |
+
e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
|
286 |
+
|
287 |
+
result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
|
288 |
+
|
289 |
+
result += "\n \\end{scope}\n \\end{tikzpicture}\n"
|
290 |
+
return result
|
291 |
+
|
292 |
+
|
293 |
+
_DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
|
294 |
+
\usepackage{{tikz}}
|
295 |
+
\usepackage{{subcaption}}
|
296 |
+
|
297 |
+
\begin{{document}}
|
298 |
+
{content}
|
299 |
+
\end{{document}}"""
|
300 |
+
|
301 |
+
|
302 |
+
_FIG_WRAPPER = r"""\begin{{figure}}
|
303 |
+
{content}{caption}{label}
|
304 |
+
\end{{figure}}"""
|
305 |
+
|
306 |
+
|
307 |
+
_SUBFIG_WRAPPER = r""" \begin{{subfigure}}{{{size}\textwidth}}
|
308 |
+
{content}{caption}{label}
|
309 |
+
\end{{subfigure}}"""
|
310 |
+
|
311 |
+
|
312 |
+
def to_latex(
|
313 |
+
Gbunch,
|
314 |
+
pos="pos",
|
315 |
+
tikz_options="",
|
316 |
+
default_node_options="",
|
317 |
+
node_options="node_options",
|
318 |
+
node_label="node_label",
|
319 |
+
default_edge_options="",
|
320 |
+
edge_options="edge_options",
|
321 |
+
edge_label="edge_label",
|
322 |
+
edge_label_options="edge_label_options",
|
323 |
+
caption="",
|
324 |
+
latex_label="",
|
325 |
+
sub_captions=None,
|
326 |
+
sub_labels=None,
|
327 |
+
n_rows=1,
|
328 |
+
as_document=True,
|
329 |
+
document_wrapper=_DOC_WRAPPER_TIKZ,
|
330 |
+
figure_wrapper=_FIG_WRAPPER,
|
331 |
+
subfigure_wrapper=_SUBFIG_WRAPPER,
|
332 |
+
):
|
333 |
+
"""Return latex code to draw the graph(s) in `Gbunch`
|
334 |
+
|
335 |
+
The TikZ drawing utility in LaTeX is used to draw the graph(s).
|
336 |
+
If `Gbunch` is a graph, it is drawn in a figure environment.
|
337 |
+
If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
|
338 |
+
within a single figure environment.
|
339 |
+
|
340 |
+
If `as_document` is True, the figure is wrapped inside a document environment
|
341 |
+
so that the resulting string is ready to be compiled by LaTeX. Otherwise,
|
342 |
+
the string is ready for inclusion in a larger tex document using ``\\include``
|
343 |
+
or ``\\input`` statements.
|
344 |
+
|
345 |
+
Parameters
|
346 |
+
==========
|
347 |
+
Gbunch : NetworkX graph or iterable of NetworkX graphs
|
348 |
+
The NetworkX graph to be drawn or an iterable of graphs
|
349 |
+
to be drawn inside subfigures of a single figure.
|
350 |
+
pos : string or list of strings
|
351 |
+
The name of the node attribute on `G` that holds the position of each node.
|
352 |
+
Positions can be sequences of length 2 with numbers for (x,y) coordinates.
|
353 |
+
They can also be strings to denote positions in TikZ style, such as (x, y)
|
354 |
+
or (angle:radius).
|
355 |
+
If a dict, it should be keyed by node to a position.
|
356 |
+
If an empty dict, a circular layout is computed by TikZ.
|
357 |
+
If you are drawing many graphs in subfigures, use a list of position dicts.
|
358 |
+
tikz_options : string
|
359 |
+
The tikzpicture options description defining the options for the picture.
|
360 |
+
Often large scale options like `[scale=2]`.
|
361 |
+
default_node_options : string
|
362 |
+
The draw options for a path of nodes. Individual node options override these.
|
363 |
+
node_options : string or dict
|
364 |
+
The name of the node attribute on `G` that holds the options for each node.
|
365 |
+
Or a dict keyed by node to a string holding the options for that node.
|
366 |
+
node_label : string or dict
|
367 |
+
The name of the node attribute on `G` that holds the node label (text)
|
368 |
+
displayed for each node. If the attribute is "" or not present, the node
|
369 |
+
itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
|
370 |
+
Or a dict keyed by node to a string holding the label for that node.
|
371 |
+
default_edge_options : string
|
372 |
+
The options for the scope drawing all edges. The default is "[-]" for
|
373 |
+
undirected graphs and "[->]" for directed graphs.
|
374 |
+
edge_options : string or dict
|
375 |
+
The name of the edge attribute on `G` that holds the options for each edge.
|
376 |
+
If the edge is a self-loop and ``"loop" not in edge_options`` the option
|
377 |
+
"loop," is added to the options for the self-loop edge. Hence you can
|
378 |
+
use "[loop above]" explicitly, but the default is "[loop]".
|
379 |
+
Or a dict keyed by edge to a string holding the options for that edge.
|
380 |
+
edge_label : string or dict
|
381 |
+
The name of the edge attribute on `G` that holds the edge label (text)
|
382 |
+
displayed for each edge. If the attribute is "" or not present, no edge
|
383 |
+
label is drawn.
|
384 |
+
Or a dict keyed by edge to a string holding the label for that edge.
|
385 |
+
edge_label_options : string or dict
|
386 |
+
The name of the edge attribute on `G` that holds the label options for
|
387 |
+
each edge. For example, "[sloped,above,blue]". The default is no options.
|
388 |
+
Or a dict keyed by edge to a string holding the label options for that edge.
|
389 |
+
caption : string
|
390 |
+
The caption string for the figure environment
|
391 |
+
latex_label : string
|
392 |
+
The latex label used for the figure for easy referral from the main text
|
393 |
+
sub_captions : list of strings
|
394 |
+
The sub_caption string for each subfigure in the figure
|
395 |
+
sub_latex_labels : list of strings
|
396 |
+
The latex label for each subfigure in the figure
|
397 |
+
n_rows : int
|
398 |
+
The number of rows of subfigures to arrange for multiple graphs
|
399 |
+
as_document : bool
|
400 |
+
Whether to wrap the latex code in a document environment for compiling
|
401 |
+
document_wrapper : formatted text string with variable ``content``.
|
402 |
+
This text is called to evaluate the content embedded in a document
|
403 |
+
environment with a preamble setting up TikZ.
|
404 |
+
figure_wrapper : formatted text string
|
405 |
+
This text is evaluated with variables ``content``, ``caption`` and ``label``.
|
406 |
+
It wraps the content and if a caption is provided, adds the latex code for
|
407 |
+
that caption, and if a label is provided, adds the latex code for a label.
|
408 |
+
subfigure_wrapper : formatted text string
|
409 |
+
This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
|
410 |
+
It wraps the content and if a caption is provided, adds the latex code for
|
411 |
+
that caption, and if a label is provided, adds the latex code for a label.
|
412 |
+
The size is the vertical size of each row of subfigures as a fraction.
|
413 |
+
|
414 |
+
Returns
|
415 |
+
=======
|
416 |
+
latex_code : string
|
417 |
+
The text string which draws the desired graph(s) when compiled by LaTeX.
|
418 |
+
|
419 |
+
See Also
|
420 |
+
========
|
421 |
+
write_latex
|
422 |
+
to_latex_raw
|
423 |
+
"""
|
424 |
+
if hasattr(Gbunch, "adj"):
|
425 |
+
raw = to_latex_raw(
|
426 |
+
Gbunch,
|
427 |
+
pos,
|
428 |
+
tikz_options,
|
429 |
+
default_node_options,
|
430 |
+
node_options,
|
431 |
+
node_label,
|
432 |
+
default_edge_options,
|
433 |
+
edge_options,
|
434 |
+
edge_label,
|
435 |
+
edge_label_options,
|
436 |
+
)
|
437 |
+
else: # iterator of graphs
|
438 |
+
sbf = subfigure_wrapper
|
439 |
+
size = 1 / n_rows
|
440 |
+
|
441 |
+
N = len(Gbunch)
|
442 |
+
if isinstance(pos, str | dict):
|
443 |
+
pos = [pos] * N
|
444 |
+
if sub_captions is None:
|
445 |
+
sub_captions = [""] * N
|
446 |
+
if sub_labels is None:
|
447 |
+
sub_labels = [""] * N
|
448 |
+
if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
|
449 |
+
raise nx.NetworkXError(
|
450 |
+
"length of Gbunch, sub_captions and sub_figures must agree"
|
451 |
+
)
|
452 |
+
|
453 |
+
raw = ""
|
454 |
+
for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
|
455 |
+
subraw = to_latex_raw(
|
456 |
+
G,
|
457 |
+
pos,
|
458 |
+
tikz_options,
|
459 |
+
default_node_options,
|
460 |
+
node_options,
|
461 |
+
node_label,
|
462 |
+
default_edge_options,
|
463 |
+
edge_options,
|
464 |
+
edge_label,
|
465 |
+
edge_label_options,
|
466 |
+
)
|
467 |
+
cap = f" \\caption{{{subcap}}}" if subcap else ""
|
468 |
+
lbl = f"\\label{{{sublbl}}}" if sublbl else ""
|
469 |
+
raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
|
470 |
+
raw += "\n"
|
471 |
+
|
472 |
+
# put raw latex code into a figure environment and optionally into a document
|
473 |
+
raw = raw[:-1]
|
474 |
+
cap = f"\n \\caption{{{caption}}}" if caption else ""
|
475 |
+
lbl = f"\\label{{{latex_label}}}" if latex_label else ""
|
476 |
+
fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
|
477 |
+
if as_document:
|
478 |
+
return document_wrapper.format(content=fig)
|
479 |
+
return fig
|
480 |
+
|
481 |
+
|
482 |
+
@nx.utils.open_file(1, mode="w")
|
483 |
+
def write_latex(Gbunch, path, **options):
|
484 |
+
"""Write the latex code to draw the graph(s) onto `path`.
|
485 |
+
|
486 |
+
This convenience function creates the latex drawing code as a string
|
487 |
+
and writes that to a file ready to be compiled when `as_document` is True
|
488 |
+
or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
|
489 |
+
|
490 |
+
The `path` argument can be a string filename or a file handle to write to.
|
491 |
+
|
492 |
+
Parameters
|
493 |
+
----------
|
494 |
+
Gbunch : NetworkX graph or iterable of NetworkX graphs
|
495 |
+
If Gbunch is a graph, it is drawn in a figure environment.
|
496 |
+
If Gbunch is an iterable of graphs, each is drawn in a subfigure
|
497 |
+
environment within a single figure environment.
|
498 |
+
path : filename
|
499 |
+
Filename or file handle to write to
|
500 |
+
options : dict
|
501 |
+
By default, TikZ is used with options: (others are ignored)::
|
502 |
+
|
503 |
+
pos : string or dict or list
|
504 |
+
The name of the node attribute on `G` that holds the position of each node.
|
505 |
+
Positions can be sequences of length 2 with numbers for (x,y) coordinates.
|
506 |
+
They can also be strings to denote positions in TikZ style, such as (x, y)
|
507 |
+
or (angle:radius).
|
508 |
+
If a dict, it should be keyed by node to a position.
|
509 |
+
If an empty dict, a circular layout is computed by TikZ.
|
510 |
+
If you are drawing many graphs in subfigures, use a list of position dicts.
|
511 |
+
tikz_options : string
|
512 |
+
The tikzpicture options description defining the options for the picture.
|
513 |
+
Often large scale options like `[scale=2]`.
|
514 |
+
default_node_options : string
|
515 |
+
The draw options for a path of nodes. Individual node options override these.
|
516 |
+
node_options : string or dict
|
517 |
+
The name of the node attribute on `G` that holds the options for each node.
|
518 |
+
Or a dict keyed by node to a string holding the options for that node.
|
519 |
+
node_label : string or dict
|
520 |
+
The name of the node attribute on `G` that holds the node label (text)
|
521 |
+
displayed for each node. If the attribute is "" or not present, the node
|
522 |
+
itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
|
523 |
+
Or a dict keyed by node to a string holding the label for that node.
|
524 |
+
default_edge_options : string
|
525 |
+
The options for the scope drawing all edges. The default is "[-]" for
|
526 |
+
undirected graphs and "[->]" for directed graphs.
|
527 |
+
edge_options : string or dict
|
528 |
+
The name of the edge attribute on `G` that holds the options for each edge.
|
529 |
+
If the edge is a self-loop and ``"loop" not in edge_options`` the option
|
530 |
+
"loop," is added to the options for the self-loop edge. Hence you can
|
531 |
+
use "[loop above]" explicitly, but the default is "[loop]".
|
532 |
+
Or a dict keyed by edge to a string holding the options for that edge.
|
533 |
+
edge_label : string or dict
|
534 |
+
The name of the edge attribute on `G` that holds the edge label (text)
|
535 |
+
displayed for each edge. If the attribute is "" or not present, no edge
|
536 |
+
label is drawn.
|
537 |
+
Or a dict keyed by edge to a string holding the label for that edge.
|
538 |
+
edge_label_options : string or dict
|
539 |
+
The name of the edge attribute on `G` that holds the label options for
|
540 |
+
each edge. For example, "[sloped,above,blue]". The default is no options.
|
541 |
+
Or a dict keyed by edge to a string holding the label options for that edge.
|
542 |
+
caption : string
|
543 |
+
The caption string for the figure environment
|
544 |
+
latex_label : string
|
545 |
+
The latex label used for the figure for easy referral from the main text
|
546 |
+
sub_captions : list of strings
|
547 |
+
The sub_caption string for each subfigure in the figure
|
548 |
+
sub_latex_labels : list of strings
|
549 |
+
The latex label for each subfigure in the figure
|
550 |
+
n_rows : int
|
551 |
+
The number of rows of subfigures to arrange for multiple graphs
|
552 |
+
as_document : bool
|
553 |
+
Whether to wrap the latex code in a document environment for compiling
|
554 |
+
document_wrapper : formatted text string with variable ``content``.
|
555 |
+
This text is called to evaluate the content embedded in a document
|
556 |
+
environment with a preamble setting up the TikZ syntax.
|
557 |
+
figure_wrapper : formatted text string
|
558 |
+
This text is evaluated with variables ``content``, ``caption`` and ``label``.
|
559 |
+
It wraps the content and if a caption is provided, adds the latex code for
|
560 |
+
that caption, and if a label is provided, adds the latex code for a label.
|
561 |
+
subfigure_wrapper : formatted text string
|
562 |
+
This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
|
563 |
+
It wraps the content and if a caption is provided, adds the latex code for
|
564 |
+
that caption, and if a label is provided, adds the latex code for a label.
|
565 |
+
The size is the vertical size of each row of subfigures as a fraction.
|
566 |
+
|
567 |
+
See Also
|
568 |
+
========
|
569 |
+
to_latex
|
570 |
+
"""
|
571 |
+
path.write(to_latex(Gbunch, **options))
|
venv/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py
ADDED
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
*****
|
3 |
+
Pydot
|
4 |
+
*****
|
5 |
+
|
6 |
+
Import and export NetworkX graphs in Graphviz dot format using pydot.
|
7 |
+
|
8 |
+
Either this module or nx_agraph can be used to interface with graphviz.
|
9 |
+
|
10 |
+
Examples
|
11 |
+
--------
|
12 |
+
>>> G = nx.complete_graph(5)
|
13 |
+
>>> PG = nx.nx_pydot.to_pydot(G)
|
14 |
+
>>> H = nx.nx_pydot.from_pydot(PG)
|
15 |
+
|
16 |
+
See Also
|
17 |
+
--------
|
18 |
+
- pydot: https://github.com/erocarrera/pydot
|
19 |
+
- Graphviz: https://www.graphviz.org
|
20 |
+
- DOT Language: http://www.graphviz.org/doc/info/lang.html
|
21 |
+
"""
|
22 |
+
from locale import getpreferredencoding
|
23 |
+
|
24 |
+
import networkx as nx
|
25 |
+
from networkx.utils import open_file
|
26 |
+
|
27 |
+
__all__ = [
|
28 |
+
"write_dot",
|
29 |
+
"read_dot",
|
30 |
+
"graphviz_layout",
|
31 |
+
"pydot_layout",
|
32 |
+
"to_pydot",
|
33 |
+
"from_pydot",
|
34 |
+
]
|
35 |
+
|
36 |
+
|
37 |
+
@open_file(1, mode="w")
|
38 |
+
def write_dot(G, path):
|
39 |
+
"""Write NetworkX graph G to Graphviz dot format on path.
|
40 |
+
|
41 |
+
Path can be a string or a file handle.
|
42 |
+
"""
|
43 |
+
P = to_pydot(G)
|
44 |
+
path.write(P.to_string())
|
45 |
+
return
|
46 |
+
|
47 |
+
|
48 |
+
@open_file(0, mode="r")
|
49 |
+
@nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
|
50 |
+
def read_dot(path):
|
51 |
+
"""Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
|
52 |
+
dot file with the passed path.
|
53 |
+
|
54 |
+
If this file contains multiple graphs, only the first such graph is
|
55 |
+
returned. All graphs _except_ the first are silently ignored.
|
56 |
+
|
57 |
+
Parameters
|
58 |
+
----------
|
59 |
+
path : str or file
|
60 |
+
Filename or file handle.
|
61 |
+
|
62 |
+
Returns
|
63 |
+
-------
|
64 |
+
G : MultiGraph or MultiDiGraph
|
65 |
+
A :class:`MultiGraph` or :class:`MultiDiGraph`.
|
66 |
+
|
67 |
+
Notes
|
68 |
+
-----
|
69 |
+
Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
|
70 |
+
:class:`MultiGraph`.
|
71 |
+
"""
|
72 |
+
import pydot
|
73 |
+
|
74 |
+
data = path.read()
|
75 |
+
|
76 |
+
# List of one or more "pydot.Dot" instances deserialized from this file.
|
77 |
+
P_list = pydot.graph_from_dot_data(data)
|
78 |
+
|
79 |
+
# Convert only the first such instance into a NetworkX graph.
|
80 |
+
return from_pydot(P_list[0])
|
81 |
+
|
82 |
+
|
83 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
84 |
+
def from_pydot(P):
|
85 |
+
"""Returns a NetworkX graph from a Pydot graph.
|
86 |
+
|
87 |
+
Parameters
|
88 |
+
----------
|
89 |
+
P : Pydot graph
|
90 |
+
A graph created with Pydot
|
91 |
+
|
92 |
+
Returns
|
93 |
+
-------
|
94 |
+
G : NetworkX multigraph
|
95 |
+
A MultiGraph or MultiDiGraph.
|
96 |
+
|
97 |
+
Examples
|
98 |
+
--------
|
99 |
+
>>> K5 = nx.complete_graph(5)
|
100 |
+
>>> A = nx.nx_pydot.to_pydot(K5)
|
101 |
+
>>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
|
102 |
+
|
103 |
+
# make a Graph instead of MultiGraph
|
104 |
+
>>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
|
105 |
+
|
106 |
+
"""
|
107 |
+
|
108 |
+
if P.get_strict(None): # pydot bug: get_strict() shouldn't take argument
|
109 |
+
multiedges = False
|
110 |
+
else:
|
111 |
+
multiedges = True
|
112 |
+
|
113 |
+
if P.get_type() == "graph": # undirected
|
114 |
+
if multiedges:
|
115 |
+
N = nx.MultiGraph()
|
116 |
+
else:
|
117 |
+
N = nx.Graph()
|
118 |
+
else:
|
119 |
+
if multiedges:
|
120 |
+
N = nx.MultiDiGraph()
|
121 |
+
else:
|
122 |
+
N = nx.DiGraph()
|
123 |
+
|
124 |
+
# assign defaults
|
125 |
+
name = P.get_name().strip('"')
|
126 |
+
if name != "":
|
127 |
+
N.name = name
|
128 |
+
|
129 |
+
# add nodes, attributes to N.node_attr
|
130 |
+
for p in P.get_node_list():
|
131 |
+
n = p.get_name().strip('"')
|
132 |
+
if n in ("node", "graph", "edge"):
|
133 |
+
continue
|
134 |
+
N.add_node(n, **p.get_attributes())
|
135 |
+
|
136 |
+
# add edges
|
137 |
+
for e in P.get_edge_list():
|
138 |
+
u = e.get_source()
|
139 |
+
v = e.get_destination()
|
140 |
+
attr = e.get_attributes()
|
141 |
+
s = []
|
142 |
+
d = []
|
143 |
+
|
144 |
+
if isinstance(u, str):
|
145 |
+
s.append(u.strip('"'))
|
146 |
+
else:
|
147 |
+
for unodes in u["nodes"]:
|
148 |
+
s.append(unodes.strip('"'))
|
149 |
+
|
150 |
+
if isinstance(v, str):
|
151 |
+
d.append(v.strip('"'))
|
152 |
+
else:
|
153 |
+
for vnodes in v["nodes"]:
|
154 |
+
d.append(vnodes.strip('"'))
|
155 |
+
|
156 |
+
for source_node in s:
|
157 |
+
for destination_node in d:
|
158 |
+
N.add_edge(source_node, destination_node, **attr)
|
159 |
+
|
160 |
+
# add default attributes for graph, nodes, edges
|
161 |
+
pattr = P.get_attributes()
|
162 |
+
if pattr:
|
163 |
+
N.graph["graph"] = pattr
|
164 |
+
try:
|
165 |
+
N.graph["node"] = P.get_node_defaults()[0]
|
166 |
+
except (IndexError, TypeError):
|
167 |
+
pass # N.graph['node']={}
|
168 |
+
try:
|
169 |
+
N.graph["edge"] = P.get_edge_defaults()[0]
|
170 |
+
except (IndexError, TypeError):
|
171 |
+
pass # N.graph['edge']={}
|
172 |
+
return N
|
173 |
+
|
174 |
+
|
175 |
+
def _check_colon_quotes(s):
|
176 |
+
# A quick helper function to check if a string has a colon in it
|
177 |
+
# and if it is quoted properly with double quotes.
|
178 |
+
# refer https://github.com/pydot/pydot/issues/258
|
179 |
+
return ":" in s and (s[0] != '"' or s[-1] != '"')
|
180 |
+
|
181 |
+
|
182 |
+
def to_pydot(N):
|
183 |
+
"""Returns a pydot graph from a NetworkX graph N.
|
184 |
+
|
185 |
+
Parameters
|
186 |
+
----------
|
187 |
+
N : NetworkX graph
|
188 |
+
A graph created with NetworkX
|
189 |
+
|
190 |
+
Examples
|
191 |
+
--------
|
192 |
+
>>> K5 = nx.complete_graph(5)
|
193 |
+
>>> P = nx.nx_pydot.to_pydot(K5)
|
194 |
+
|
195 |
+
Notes
|
196 |
+
-----
|
197 |
+
|
198 |
+
"""
|
199 |
+
import pydot
|
200 |
+
|
201 |
+
# set Graphviz graph type
|
202 |
+
if N.is_directed():
|
203 |
+
graph_type = "digraph"
|
204 |
+
else:
|
205 |
+
graph_type = "graph"
|
206 |
+
strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
|
207 |
+
|
208 |
+
name = N.name
|
209 |
+
graph_defaults = N.graph.get("graph", {})
|
210 |
+
if name == "":
|
211 |
+
P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
|
212 |
+
else:
|
213 |
+
P = pydot.Dot(
|
214 |
+
f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
|
215 |
+
)
|
216 |
+
try:
|
217 |
+
P.set_node_defaults(**N.graph["node"])
|
218 |
+
except KeyError:
|
219 |
+
pass
|
220 |
+
try:
|
221 |
+
P.set_edge_defaults(**N.graph["edge"])
|
222 |
+
except KeyError:
|
223 |
+
pass
|
224 |
+
|
225 |
+
for n, nodedata in N.nodes(data=True):
|
226 |
+
str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
|
227 |
+
# Explicitly catch nodes with ":" in node names or nodedata.
|
228 |
+
n = str(n)
|
229 |
+
raise_error = _check_colon_quotes(n) or (
|
230 |
+
any(
|
231 |
+
(_check_colon_quotes(k) or _check_colon_quotes(v))
|
232 |
+
for k, v in str_nodedata.items()
|
233 |
+
)
|
234 |
+
)
|
235 |
+
if raise_error:
|
236 |
+
raise ValueError(
|
237 |
+
f'Node names and attributes should not contain ":" unless they are quoted with "".\
|
238 |
+
For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
|
239 |
+
Please refer https://github.com/pydot/pydot/issues/258'
|
240 |
+
)
|
241 |
+
p = pydot.Node(n, **str_nodedata)
|
242 |
+
P.add_node(p)
|
243 |
+
|
244 |
+
if N.is_multigraph():
|
245 |
+
for u, v, key, edgedata in N.edges(data=True, keys=True):
|
246 |
+
str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
|
247 |
+
u, v = str(u), str(v)
|
248 |
+
raise_error = (
|
249 |
+
_check_colon_quotes(u)
|
250 |
+
or _check_colon_quotes(v)
|
251 |
+
or (
|
252 |
+
any(
|
253 |
+
(_check_colon_quotes(k) or _check_colon_quotes(val))
|
254 |
+
for k, val in str_edgedata.items()
|
255 |
+
)
|
256 |
+
)
|
257 |
+
)
|
258 |
+
if raise_error:
|
259 |
+
raise ValueError(
|
260 |
+
f'Node names and attributes should not contain ":" unless they are quoted with "".\
|
261 |
+
For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
|
262 |
+
Please refer https://github.com/pydot/pydot/issues/258'
|
263 |
+
)
|
264 |
+
edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
|
265 |
+
P.add_edge(edge)
|
266 |
+
|
267 |
+
else:
|
268 |
+
for u, v, edgedata in N.edges(data=True):
|
269 |
+
str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
|
270 |
+
u, v = str(u), str(v)
|
271 |
+
raise_error = (
|
272 |
+
_check_colon_quotes(u)
|
273 |
+
or _check_colon_quotes(v)
|
274 |
+
or (
|
275 |
+
any(
|
276 |
+
(_check_colon_quotes(k) or _check_colon_quotes(val))
|
277 |
+
for k, val in str_edgedata.items()
|
278 |
+
)
|
279 |
+
)
|
280 |
+
)
|
281 |
+
if raise_error:
|
282 |
+
raise ValueError(
|
283 |
+
f'Node names and attributes should not contain ":" unless they are quoted with "".\
|
284 |
+
For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
|
285 |
+
Please refer https://github.com/pydot/pydot/issues/258'
|
286 |
+
)
|
287 |
+
edge = pydot.Edge(u, v, **str_edgedata)
|
288 |
+
P.add_edge(edge)
|
289 |
+
return P
|
290 |
+
|
291 |
+
|
292 |
+
def graphviz_layout(G, prog="neato", root=None):
|
293 |
+
"""Create node positions using Pydot and Graphviz.
|
294 |
+
|
295 |
+
Returns a dictionary of positions keyed by node.
|
296 |
+
|
297 |
+
Parameters
|
298 |
+
----------
|
299 |
+
G : NetworkX Graph
|
300 |
+
The graph for which the layout is computed.
|
301 |
+
prog : string (default: 'neato')
|
302 |
+
The name of the GraphViz program to use for layout.
|
303 |
+
Options depend on GraphViz version but may include:
|
304 |
+
'dot', 'twopi', 'fdp', 'sfdp', 'circo'
|
305 |
+
root : Node from G or None (default: None)
|
306 |
+
The node of G from which to start some layout algorithms.
|
307 |
+
|
308 |
+
Returns
|
309 |
+
-------
|
310 |
+
Dictionary of (x, y) positions keyed by node.
|
311 |
+
|
312 |
+
Examples
|
313 |
+
--------
|
314 |
+
>>> G = nx.complete_graph(4)
|
315 |
+
>>> pos = nx.nx_pydot.graphviz_layout(G)
|
316 |
+
>>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
|
317 |
+
|
318 |
+
Notes
|
319 |
+
-----
|
320 |
+
This is a wrapper for pydot_layout.
|
321 |
+
"""
|
322 |
+
return pydot_layout(G=G, prog=prog, root=root)
|
323 |
+
|
324 |
+
|
325 |
+
def pydot_layout(G, prog="neato", root=None):
|
326 |
+
"""Create node positions using :mod:`pydot` and Graphviz.
|
327 |
+
|
328 |
+
Parameters
|
329 |
+
----------
|
330 |
+
G : Graph
|
331 |
+
NetworkX graph to be laid out.
|
332 |
+
prog : string (default: 'neato')
|
333 |
+
Name of the GraphViz command to use for layout.
|
334 |
+
Options depend on GraphViz version but may include:
|
335 |
+
'dot', 'twopi', 'fdp', 'sfdp', 'circo'
|
336 |
+
root : Node from G or None (default: None)
|
337 |
+
The node of G from which to start some layout algorithms.
|
338 |
+
|
339 |
+
Returns
|
340 |
+
-------
|
341 |
+
dict
|
342 |
+
Dictionary of positions keyed by node.
|
343 |
+
|
344 |
+
Examples
|
345 |
+
--------
|
346 |
+
>>> G = nx.complete_graph(4)
|
347 |
+
>>> pos = nx.nx_pydot.pydot_layout(G)
|
348 |
+
>>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
|
349 |
+
|
350 |
+
Notes
|
351 |
+
-----
|
352 |
+
If you use complex node objects, they may have the same string
|
353 |
+
representation and GraphViz could treat them as the same node.
|
354 |
+
The layout may assign both nodes a single location. See Issue #1568
|
355 |
+
If this occurs in your case, consider relabeling the nodes just
|
356 |
+
for the layout computation using something similar to::
|
357 |
+
|
358 |
+
H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
|
359 |
+
H_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
|
360 |
+
G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
|
361 |
+
|
362 |
+
"""
|
363 |
+
import pydot
|
364 |
+
|
365 |
+
P = to_pydot(G)
|
366 |
+
if root is not None:
|
367 |
+
P.set("root", str(root))
|
368 |
+
|
369 |
+
# List of low-level bytes comprising a string in the dot language converted
|
370 |
+
# from the passed graph with the passed external GraphViz command.
|
371 |
+
D_bytes = P.create_dot(prog=prog)
|
372 |
+
|
373 |
+
# Unique string decoded from these bytes with the preferred locale encoding
|
374 |
+
D = str(D_bytes, encoding=getpreferredencoding())
|
375 |
+
|
376 |
+
if D == "": # no data returned
|
377 |
+
print(f"Graphviz layout with {prog} failed")
|
378 |
+
print()
|
379 |
+
print("To debug what happened try:")
|
380 |
+
print("P = nx.nx_pydot.to_pydot(G)")
|
381 |
+
print('P.write_dot("file.dot")')
|
382 |
+
print(f"And then run {prog} on file.dot")
|
383 |
+
return
|
384 |
+
|
385 |
+
# List of one or more "pydot.Dot" instances deserialized from this string.
|
386 |
+
Q_list = pydot.graph_from_dot_data(D)
|
387 |
+
assert len(Q_list) == 1
|
388 |
+
|
389 |
+
# The first and only such instance, as guaranteed by the above assertion.
|
390 |
+
Q = Q_list[0]
|
391 |
+
|
392 |
+
node_pos = {}
|
393 |
+
for n in G.nodes():
|
394 |
+
str_n = str(n)
|
395 |
+
# Explicitly catch nodes with ":" in node names or nodedata.
|
396 |
+
if _check_colon_quotes(str_n):
|
397 |
+
raise ValueError(
|
398 |
+
f'Node names and node attributes should not contain ":" unless they are quoted with "".\
|
399 |
+
For example the string \'attribute:data1\' should be written as \'"attribute:data1"\'.\
|
400 |
+
Please refer https://github.com/pydot/pydot/issues/258'
|
401 |
+
)
|
402 |
+
pydot_node = pydot.Node(str_n).get_name()
|
403 |
+
node = Q.get_node(pydot_node)
|
404 |
+
|
405 |
+
if isinstance(node, list):
|
406 |
+
node = node[0]
|
407 |
+
pos = node.get_pos()[1:-1] # strip leading and trailing double quotes
|
408 |
+
if pos is not None:
|
409 |
+
xx, yy = pos.split(",")
|
410 |
+
node_pos[n] = (float(xx), float(yy))
|
411 |
+
return node_pos
|
venv/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py
ADDED
@@ -0,0 +1,1871 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
**********
|
3 |
+
Matplotlib
|
4 |
+
**********
|
5 |
+
|
6 |
+
Draw networks with matplotlib.
|
7 |
+
|
8 |
+
Examples
|
9 |
+
--------
|
10 |
+
>>> G = nx.complete_graph(5)
|
11 |
+
>>> nx.draw(G)
|
12 |
+
|
13 |
+
See Also
|
14 |
+
--------
|
15 |
+
- :doc:`matplotlib <matplotlib:index>`
|
16 |
+
- :func:`matplotlib.pyplot.scatter`
|
17 |
+
- :obj:`matplotlib.patches.FancyArrowPatch`
|
18 |
+
"""
|
19 |
+
import collections
|
20 |
+
import itertools
|
21 |
+
from numbers import Number
|
22 |
+
|
23 |
+
import networkx as nx
|
24 |
+
from networkx.drawing.layout import (
|
25 |
+
circular_layout,
|
26 |
+
kamada_kawai_layout,
|
27 |
+
planar_layout,
|
28 |
+
random_layout,
|
29 |
+
shell_layout,
|
30 |
+
spectral_layout,
|
31 |
+
spring_layout,
|
32 |
+
)
|
33 |
+
|
34 |
+
__all__ = [
|
35 |
+
"draw",
|
36 |
+
"draw_networkx",
|
37 |
+
"draw_networkx_nodes",
|
38 |
+
"draw_networkx_edges",
|
39 |
+
"draw_networkx_labels",
|
40 |
+
"draw_networkx_edge_labels",
|
41 |
+
"draw_circular",
|
42 |
+
"draw_kamada_kawai",
|
43 |
+
"draw_random",
|
44 |
+
"draw_spectral",
|
45 |
+
"draw_spring",
|
46 |
+
"draw_planar",
|
47 |
+
"draw_shell",
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
def draw(G, pos=None, ax=None, **kwds):
|
52 |
+
"""Draw the graph G with Matplotlib.
|
53 |
+
|
54 |
+
Draw the graph as a simple representation with no node
|
55 |
+
labels or edge labels and using the full Matplotlib figure area
|
56 |
+
and no axis labels by default. See draw_networkx() for more
|
57 |
+
full-featured drawing that allows title, axis labels etc.
|
58 |
+
|
59 |
+
Parameters
|
60 |
+
----------
|
61 |
+
G : graph
|
62 |
+
A networkx graph
|
63 |
+
|
64 |
+
pos : dictionary, optional
|
65 |
+
A dictionary with nodes as keys and positions as values.
|
66 |
+
If not specified a spring layout positioning will be computed.
|
67 |
+
See :py:mod:`networkx.drawing.layout` for functions that
|
68 |
+
compute node positions.
|
69 |
+
|
70 |
+
ax : Matplotlib Axes object, optional
|
71 |
+
Draw the graph in specified Matplotlib axes.
|
72 |
+
|
73 |
+
kwds : optional keywords
|
74 |
+
See networkx.draw_networkx() for a description of optional keywords.
|
75 |
+
|
76 |
+
Examples
|
77 |
+
--------
|
78 |
+
>>> G = nx.dodecahedral_graph()
|
79 |
+
>>> nx.draw(G)
|
80 |
+
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
|
81 |
+
|
82 |
+
See Also
|
83 |
+
--------
|
84 |
+
draw_networkx
|
85 |
+
draw_networkx_nodes
|
86 |
+
draw_networkx_edges
|
87 |
+
draw_networkx_labels
|
88 |
+
draw_networkx_edge_labels
|
89 |
+
|
90 |
+
Notes
|
91 |
+
-----
|
92 |
+
This function has the same name as pylab.draw and pyplot.draw
|
93 |
+
so beware when using `from networkx import *`
|
94 |
+
|
95 |
+
since you might overwrite the pylab.draw function.
|
96 |
+
|
97 |
+
With pyplot use
|
98 |
+
|
99 |
+
>>> import matplotlib.pyplot as plt
|
100 |
+
>>> G = nx.dodecahedral_graph()
|
101 |
+
>>> nx.draw(G) # networkx draw()
|
102 |
+
>>> plt.draw() # pyplot draw()
|
103 |
+
|
104 |
+
Also see the NetworkX drawing examples at
|
105 |
+
https://networkx.org/documentation/latest/auto_examples/index.html
|
106 |
+
"""
|
107 |
+
import matplotlib.pyplot as plt
|
108 |
+
|
109 |
+
if ax is None:
|
110 |
+
cf = plt.gcf()
|
111 |
+
else:
|
112 |
+
cf = ax.get_figure()
|
113 |
+
cf.set_facecolor("w")
|
114 |
+
if ax is None:
|
115 |
+
if cf.axes:
|
116 |
+
ax = cf.gca()
|
117 |
+
else:
|
118 |
+
ax = cf.add_axes((0, 0, 1, 1))
|
119 |
+
|
120 |
+
if "with_labels" not in kwds:
|
121 |
+
kwds["with_labels"] = "labels" in kwds
|
122 |
+
|
123 |
+
draw_networkx(G, pos=pos, ax=ax, **kwds)
|
124 |
+
ax.set_axis_off()
|
125 |
+
plt.draw_if_interactive()
|
126 |
+
return
|
127 |
+
|
128 |
+
|
129 |
+
def draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds):
|
130 |
+
r"""Draw the graph G using Matplotlib.
|
131 |
+
|
132 |
+
Draw the graph with Matplotlib with options for node positions,
|
133 |
+
labeling, titles, and many other drawing features.
|
134 |
+
See draw() for simple drawing without labels or axes.
|
135 |
+
|
136 |
+
Parameters
|
137 |
+
----------
|
138 |
+
G : graph
|
139 |
+
A networkx graph
|
140 |
+
|
141 |
+
pos : dictionary, optional
|
142 |
+
A dictionary with nodes as keys and positions as values.
|
143 |
+
If not specified a spring layout positioning will be computed.
|
144 |
+
See :py:mod:`networkx.drawing.layout` for functions that
|
145 |
+
compute node positions.
|
146 |
+
|
147 |
+
arrows : bool or None, optional (default=None)
|
148 |
+
If `None`, directed graphs draw arrowheads with
|
149 |
+
`~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
|
150 |
+
via `~matplotlib.collections.LineCollection` for speed.
|
151 |
+
If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
|
152 |
+
If `False`, draw edges using LineCollection (linear and fast).
|
153 |
+
For directed graphs, if True draw arrowheads.
|
154 |
+
Note: Arrows will be the same color as edges.
|
155 |
+
|
156 |
+
arrowstyle : str (default='-\|>' for directed graphs)
|
157 |
+
For directed graphs, choose the style of the arrowsheads.
|
158 |
+
For undirected graphs default to '-'
|
159 |
+
|
160 |
+
See `matplotlib.patches.ArrowStyle` for more options.
|
161 |
+
|
162 |
+
arrowsize : int or list (default=10)
|
163 |
+
For directed graphs, choose the size of the arrow head's length and
|
164 |
+
width. A list of values can be passed in to assign a different size for arrow head's length and width.
|
165 |
+
See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
|
166 |
+
for more info.
|
167 |
+
|
168 |
+
with_labels : bool (default=True)
|
169 |
+
Set to True to draw labels on the nodes.
|
170 |
+
|
171 |
+
ax : Matplotlib Axes object, optional
|
172 |
+
Draw the graph in the specified Matplotlib axes.
|
173 |
+
|
174 |
+
nodelist : list (default=list(G))
|
175 |
+
Draw only specified nodes
|
176 |
+
|
177 |
+
edgelist : list (default=list(G.edges()))
|
178 |
+
Draw only specified edges
|
179 |
+
|
180 |
+
node_size : scalar or array (default=300)
|
181 |
+
Size of nodes. If an array is specified it must be the
|
182 |
+
same length as nodelist.
|
183 |
+
|
184 |
+
node_color : color or array of colors (default='#1f78b4')
|
185 |
+
Node color. Can be a single color or a sequence of colors with the same
|
186 |
+
length as nodelist. Color can be string or rgb (or rgba) tuple of
|
187 |
+
floats from 0-1. If numeric values are specified they will be
|
188 |
+
mapped to colors using the cmap and vmin,vmax parameters. See
|
189 |
+
matplotlib.scatter for more details.
|
190 |
+
|
191 |
+
node_shape : string (default='o')
|
192 |
+
The shape of the node. Specification is as matplotlib.scatter
|
193 |
+
marker, one of 'so^>v<dph8'.
|
194 |
+
|
195 |
+
alpha : float or None (default=None)
|
196 |
+
The node and edge transparency
|
197 |
+
|
198 |
+
cmap : Matplotlib colormap, optional
|
199 |
+
Colormap for mapping intensities of nodes
|
200 |
+
|
201 |
+
vmin,vmax : float, optional
|
202 |
+
Minimum and maximum for node colormap scaling
|
203 |
+
|
204 |
+
linewidths : scalar or sequence (default=1.0)
|
205 |
+
Line width of symbol border
|
206 |
+
|
207 |
+
width : float or array of floats (default=1.0)
|
208 |
+
Line width of edges
|
209 |
+
|
210 |
+
edge_color : color or array of colors (default='k')
|
211 |
+
Edge color. Can be a single color or a sequence of colors with the same
|
212 |
+
length as edgelist. Color can be string or rgb (or rgba) tuple of
|
213 |
+
floats from 0-1. If numeric values are specified they will be
|
214 |
+
mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
|
215 |
+
|
216 |
+
edge_cmap : Matplotlib colormap, optional
|
217 |
+
Colormap for mapping intensities of edges
|
218 |
+
|
219 |
+
edge_vmin,edge_vmax : floats, optional
|
220 |
+
Minimum and maximum for edge colormap scaling
|
221 |
+
|
222 |
+
style : string (default=solid line)
|
223 |
+
Edge line style e.g.: '-', '--', '-.', ':'
|
224 |
+
or words like 'solid' or 'dashed'.
|
225 |
+
(See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
|
226 |
+
|
227 |
+
labels : dictionary (default=None)
|
228 |
+
Node labels in a dictionary of text labels keyed by node
|
229 |
+
|
230 |
+
font_size : int (default=12 for nodes, 10 for edges)
|
231 |
+
Font size for text labels
|
232 |
+
|
233 |
+
font_color : color (default='k' black)
|
234 |
+
Font color string. Color can be string or rgb (or rgba) tuple of
|
235 |
+
floats from 0-1.
|
236 |
+
|
237 |
+
font_weight : string (default='normal')
|
238 |
+
Font weight
|
239 |
+
|
240 |
+
font_family : string (default='sans-serif')
|
241 |
+
Font family
|
242 |
+
|
243 |
+
label : string, optional
|
244 |
+
Label for graph legend
|
245 |
+
|
246 |
+
hide_ticks : bool, optional
|
247 |
+
Hide ticks of axes. When `True` (the default), ticks and ticklabels
|
248 |
+
are removed from the axes. To set ticks and tick labels to the pyplot default,
|
249 |
+
use ``hide_ticks=False``.
|
250 |
+
|
251 |
+
kwds : optional keywords
|
252 |
+
See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
|
253 |
+
networkx.draw_networkx_labels() for a description of optional keywords.
|
254 |
+
|
255 |
+
Notes
|
256 |
+
-----
|
257 |
+
For directed graphs, arrows are drawn at the head end. Arrows can be
|
258 |
+
turned off with keyword arrows=False.
|
259 |
+
|
260 |
+
Examples
|
261 |
+
--------
|
262 |
+
>>> G = nx.dodecahedral_graph()
|
263 |
+
>>> nx.draw(G)
|
264 |
+
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
|
265 |
+
|
266 |
+
>>> import matplotlib.pyplot as plt
|
267 |
+
>>> limits = plt.axis("off") # turn off axis
|
268 |
+
|
269 |
+
Also see the NetworkX drawing examples at
|
270 |
+
https://networkx.org/documentation/latest/auto_examples/index.html
|
271 |
+
|
272 |
+
See Also
|
273 |
+
--------
|
274 |
+
draw
|
275 |
+
draw_networkx_nodes
|
276 |
+
draw_networkx_edges
|
277 |
+
draw_networkx_labels
|
278 |
+
draw_networkx_edge_labels
|
279 |
+
"""
|
280 |
+
from inspect import signature
|
281 |
+
|
282 |
+
import matplotlib.pyplot as plt
|
283 |
+
|
284 |
+
# Get all valid keywords by inspecting the signatures of draw_networkx_nodes,
|
285 |
+
# draw_networkx_edges, draw_networkx_labels
|
286 |
+
|
287 |
+
valid_node_kwds = signature(draw_networkx_nodes).parameters.keys()
|
288 |
+
valid_edge_kwds = signature(draw_networkx_edges).parameters.keys()
|
289 |
+
valid_label_kwds = signature(draw_networkx_labels).parameters.keys()
|
290 |
+
|
291 |
+
# Create a set with all valid keywords across the three functions and
|
292 |
+
# remove the arguments of this function (draw_networkx)
|
293 |
+
valid_kwds = (valid_node_kwds | valid_edge_kwds | valid_label_kwds) - {
|
294 |
+
"G",
|
295 |
+
"pos",
|
296 |
+
"arrows",
|
297 |
+
"with_labels",
|
298 |
+
}
|
299 |
+
|
300 |
+
if any(k not in valid_kwds for k in kwds):
|
301 |
+
invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
|
302 |
+
raise ValueError(f"Received invalid argument(s): {invalid_args}")
|
303 |
+
|
304 |
+
node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
|
305 |
+
edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
|
306 |
+
label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
|
307 |
+
|
308 |
+
if pos is None:
|
309 |
+
pos = nx.drawing.spring_layout(G) # default to spring layout
|
310 |
+
|
311 |
+
draw_networkx_nodes(G, pos, **node_kwds)
|
312 |
+
draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
|
313 |
+
if with_labels:
|
314 |
+
draw_networkx_labels(G, pos, **label_kwds)
|
315 |
+
plt.draw_if_interactive()
|
316 |
+
|
317 |
+
|
318 |
+
def draw_networkx_nodes(
|
319 |
+
G,
|
320 |
+
pos,
|
321 |
+
nodelist=None,
|
322 |
+
node_size=300,
|
323 |
+
node_color="#1f78b4",
|
324 |
+
node_shape="o",
|
325 |
+
alpha=None,
|
326 |
+
cmap=None,
|
327 |
+
vmin=None,
|
328 |
+
vmax=None,
|
329 |
+
ax=None,
|
330 |
+
linewidths=None,
|
331 |
+
edgecolors=None,
|
332 |
+
label=None,
|
333 |
+
margins=None,
|
334 |
+
hide_ticks=True,
|
335 |
+
):
|
336 |
+
"""Draw the nodes of the graph G.
|
337 |
+
|
338 |
+
This draws only the nodes of the graph G.
|
339 |
+
|
340 |
+
Parameters
|
341 |
+
----------
|
342 |
+
G : graph
|
343 |
+
A networkx graph
|
344 |
+
|
345 |
+
pos : dictionary
|
346 |
+
A dictionary with nodes as keys and positions as values.
|
347 |
+
Positions should be sequences of length 2.
|
348 |
+
|
349 |
+
ax : Matplotlib Axes object, optional
|
350 |
+
Draw the graph in the specified Matplotlib axes.
|
351 |
+
|
352 |
+
nodelist : list (default list(G))
|
353 |
+
Draw only specified nodes
|
354 |
+
|
355 |
+
node_size : scalar or array (default=300)
|
356 |
+
Size of nodes. If an array it must be the same length as nodelist.
|
357 |
+
|
358 |
+
node_color : color or array of colors (default='#1f78b4')
|
359 |
+
Node color. Can be a single color or a sequence of colors with the same
|
360 |
+
length as nodelist. Color can be string or rgb (or rgba) tuple of
|
361 |
+
floats from 0-1. If numeric values are specified they will be
|
362 |
+
mapped to colors using the cmap and vmin,vmax parameters. See
|
363 |
+
matplotlib.scatter for more details.
|
364 |
+
|
365 |
+
node_shape : string (default='o')
|
366 |
+
The shape of the node. Specification is as matplotlib.scatter
|
367 |
+
marker, one of 'so^>v<dph8'.
|
368 |
+
|
369 |
+
alpha : float or array of floats (default=None)
|
370 |
+
The node transparency. This can be a single alpha value,
|
371 |
+
in which case it will be applied to all the nodes of color. Otherwise,
|
372 |
+
if it is an array, the elements of alpha will be applied to the colors
|
373 |
+
in order (cycling through alpha multiple times if necessary).
|
374 |
+
|
375 |
+
cmap : Matplotlib colormap (default=None)
|
376 |
+
Colormap for mapping intensities of nodes
|
377 |
+
|
378 |
+
vmin,vmax : floats or None (default=None)
|
379 |
+
Minimum and maximum for node colormap scaling
|
380 |
+
|
381 |
+
linewidths : [None | scalar | sequence] (default=1.0)
|
382 |
+
Line width of symbol border
|
383 |
+
|
384 |
+
edgecolors : [None | scalar | sequence] (default = node_color)
|
385 |
+
Colors of node borders. Can be a single color or a sequence of colors with the
|
386 |
+
same length as nodelist. Color can be string or rgb (or rgba) tuple of floats
|
387 |
+
from 0-1. If numeric values are specified they will be mapped to colors
|
388 |
+
using the cmap and vmin,vmax parameters. See `~matplotlib.pyplot.scatter` for more details.
|
389 |
+
|
390 |
+
label : [None | string]
|
391 |
+
Label for legend
|
392 |
+
|
393 |
+
margins : float or 2-tuple, optional
|
394 |
+
Sets the padding for axis autoscaling. Increase margin to prevent
|
395 |
+
clipping for nodes that are near the edges of an image. Values should
|
396 |
+
be in the range ``[0, 1]``. See :meth:`matplotlib.axes.Axes.margins`
|
397 |
+
for details. The default is `None`, which uses the Matplotlib default.
|
398 |
+
|
399 |
+
hide_ticks : bool, optional
|
400 |
+
Hide ticks of axes. When `True` (the default), ticks and ticklabels
|
401 |
+
are removed from the axes. To set ticks and tick labels to the pyplot default,
|
402 |
+
use ``hide_ticks=False``.
|
403 |
+
|
404 |
+
Returns
|
405 |
+
-------
|
406 |
+
matplotlib.collections.PathCollection
|
407 |
+
`PathCollection` of the nodes.
|
408 |
+
|
409 |
+
Examples
|
410 |
+
--------
|
411 |
+
>>> G = nx.dodecahedral_graph()
|
412 |
+
>>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
|
413 |
+
|
414 |
+
Also see the NetworkX drawing examples at
|
415 |
+
https://networkx.org/documentation/latest/auto_examples/index.html
|
416 |
+
|
417 |
+
See Also
|
418 |
+
--------
|
419 |
+
draw
|
420 |
+
draw_networkx
|
421 |
+
draw_networkx_edges
|
422 |
+
draw_networkx_labels
|
423 |
+
draw_networkx_edge_labels
|
424 |
+
"""
|
425 |
+
from collections.abc import Iterable
|
426 |
+
|
427 |
+
import matplotlib as mpl
|
428 |
+
import matplotlib.collections # call as mpl.collections
|
429 |
+
import matplotlib.pyplot as plt
|
430 |
+
import numpy as np
|
431 |
+
|
432 |
+
if ax is None:
|
433 |
+
ax = plt.gca()
|
434 |
+
|
435 |
+
if nodelist is None:
|
436 |
+
nodelist = list(G)
|
437 |
+
|
438 |
+
if len(nodelist) == 0: # empty nodelist, no drawing
|
439 |
+
return mpl.collections.PathCollection(None)
|
440 |
+
|
441 |
+
try:
|
442 |
+
xy = np.asarray([pos[v] for v in nodelist])
|
443 |
+
except KeyError as err:
|
444 |
+
raise nx.NetworkXError(f"Node {err} has no position.") from err
|
445 |
+
|
446 |
+
if isinstance(alpha, Iterable):
|
447 |
+
node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
|
448 |
+
alpha = None
|
449 |
+
|
450 |
+
node_collection = ax.scatter(
|
451 |
+
xy[:, 0],
|
452 |
+
xy[:, 1],
|
453 |
+
s=node_size,
|
454 |
+
c=node_color,
|
455 |
+
marker=node_shape,
|
456 |
+
cmap=cmap,
|
457 |
+
vmin=vmin,
|
458 |
+
vmax=vmax,
|
459 |
+
alpha=alpha,
|
460 |
+
linewidths=linewidths,
|
461 |
+
edgecolors=edgecolors,
|
462 |
+
label=label,
|
463 |
+
)
|
464 |
+
if hide_ticks:
|
465 |
+
ax.tick_params(
|
466 |
+
axis="both",
|
467 |
+
which="both",
|
468 |
+
bottom=False,
|
469 |
+
left=False,
|
470 |
+
labelbottom=False,
|
471 |
+
labelleft=False,
|
472 |
+
)
|
473 |
+
|
474 |
+
if margins is not None:
|
475 |
+
if isinstance(margins, Iterable):
|
476 |
+
ax.margins(*margins)
|
477 |
+
else:
|
478 |
+
ax.margins(margins)
|
479 |
+
|
480 |
+
node_collection.set_zorder(2)
|
481 |
+
return node_collection
|
482 |
+
|
483 |
+
|
484 |
+
class FancyArrowFactory:
|
485 |
+
"""Draw arrows with `matplotlib.patches.FancyarrowPatch`"""
|
486 |
+
|
487 |
+
class ConnectionStyleFactory:
|
488 |
+
def __init__(self, connectionstyles, selfloop_height, ax=None):
|
489 |
+
import matplotlib as mpl
|
490 |
+
import matplotlib.path # call as mpl.path
|
491 |
+
import numpy as np
|
492 |
+
|
493 |
+
self.ax = ax
|
494 |
+
self.mpl = mpl
|
495 |
+
self.np = np
|
496 |
+
self.base_connection_styles = [
|
497 |
+
mpl.patches.ConnectionStyle(cs) for cs in connectionstyles
|
498 |
+
]
|
499 |
+
self.n = len(self.base_connection_styles)
|
500 |
+
self.selfloop_height = selfloop_height
|
501 |
+
|
502 |
+
def curved(self, edge_index):
|
503 |
+
return self.base_connection_styles[edge_index % self.n]
|
504 |
+
|
505 |
+
def self_loop(self, edge_index):
|
506 |
+
def self_loop_connection(posA, posB, *args, **kwargs):
|
507 |
+
if not self.np.all(posA == posB):
|
508 |
+
raise nx.NetworkXError(
|
509 |
+
"`self_loop` connection style method"
|
510 |
+
"is only to be used for self-loops"
|
511 |
+
)
|
512 |
+
# this is called with _screen space_ values
|
513 |
+
# so convert back to data space
|
514 |
+
data_loc = self.ax.transData.inverted().transform(posA)
|
515 |
+
v_shift = 0.1 * self.selfloop_height
|
516 |
+
h_shift = v_shift * 0.5
|
517 |
+
# put the top of the loop first so arrow is not hidden by node
|
518 |
+
path = self.np.asarray(
|
519 |
+
[
|
520 |
+
# 1
|
521 |
+
[0, v_shift],
|
522 |
+
# 4 4 4
|
523 |
+
[h_shift, v_shift],
|
524 |
+
[h_shift, 0],
|
525 |
+
[0, 0],
|
526 |
+
# 4 4 4
|
527 |
+
[-h_shift, 0],
|
528 |
+
[-h_shift, v_shift],
|
529 |
+
[0, v_shift],
|
530 |
+
]
|
531 |
+
)
|
532 |
+
# Rotate self loop 90 deg. if more than 1
|
533 |
+
# This will allow for maximum of 4 visible self loops
|
534 |
+
if edge_index % 4:
|
535 |
+
x, y = path.T
|
536 |
+
for _ in range(edge_index % 4):
|
537 |
+
x, y = y, -x
|
538 |
+
path = self.np.array([x, y]).T
|
539 |
+
return self.mpl.path.Path(
|
540 |
+
self.ax.transData.transform(data_loc + path), [1, 4, 4, 4, 4, 4, 4]
|
541 |
+
)
|
542 |
+
|
543 |
+
return self_loop_connection
|
544 |
+
|
545 |
+
def __init__(
|
546 |
+
self,
|
547 |
+
edge_pos,
|
548 |
+
edgelist,
|
549 |
+
nodelist,
|
550 |
+
edge_indices,
|
551 |
+
node_size,
|
552 |
+
selfloop_height,
|
553 |
+
connectionstyle="arc3",
|
554 |
+
node_shape="o",
|
555 |
+
arrowstyle="-",
|
556 |
+
arrowsize=10,
|
557 |
+
edge_color="k",
|
558 |
+
alpha=None,
|
559 |
+
linewidth=1.0,
|
560 |
+
style="solid",
|
561 |
+
min_source_margin=0,
|
562 |
+
min_target_margin=0,
|
563 |
+
ax=None,
|
564 |
+
):
|
565 |
+
import matplotlib as mpl
|
566 |
+
import matplotlib.patches # call as mpl.patches
|
567 |
+
import matplotlib.pyplot as plt
|
568 |
+
import numpy as np
|
569 |
+
|
570 |
+
if isinstance(connectionstyle, str):
|
571 |
+
connectionstyle = [connectionstyle]
|
572 |
+
elif np.iterable(connectionstyle):
|
573 |
+
connectionstyle = list(connectionstyle)
|
574 |
+
else:
|
575 |
+
msg = "ConnectionStyleFactory arg `connectionstyle` must be str or iterable"
|
576 |
+
raise nx.NetworkXError(msg)
|
577 |
+
self.ax = ax
|
578 |
+
self.mpl = mpl
|
579 |
+
self.np = np
|
580 |
+
self.edge_pos = edge_pos
|
581 |
+
self.edgelist = edgelist
|
582 |
+
self.nodelist = nodelist
|
583 |
+
self.node_shape = node_shape
|
584 |
+
self.min_source_margin = min_source_margin
|
585 |
+
self.min_target_margin = min_target_margin
|
586 |
+
self.edge_indices = edge_indices
|
587 |
+
self.node_size = node_size
|
588 |
+
self.connectionstyle_factory = self.ConnectionStyleFactory(
|
589 |
+
connectionstyle, selfloop_height, ax
|
590 |
+
)
|
591 |
+
self.arrowstyle = arrowstyle
|
592 |
+
self.arrowsize = arrowsize
|
593 |
+
self.arrow_colors = mpl.colors.colorConverter.to_rgba_array(edge_color, alpha)
|
594 |
+
self.linewidth = linewidth
|
595 |
+
self.style = style
|
596 |
+
if isinstance(arrowsize, list) and len(arrowsize) != len(edge_pos):
|
597 |
+
raise ValueError("arrowsize should have the same length as edgelist")
|
598 |
+
|
599 |
+
def __call__(self, i):
|
600 |
+
(x1, y1), (x2, y2) = self.edge_pos[i]
|
601 |
+
shrink_source = 0 # space from source to tail
|
602 |
+
shrink_target = 0 # space from head to target
|
603 |
+
if self.np.iterable(self.node_size): # many node sizes
|
604 |
+
source, target = self.edgelist[i][:2]
|
605 |
+
source_node_size = self.node_size[self.nodelist.index(source)]
|
606 |
+
target_node_size = self.node_size[self.nodelist.index(target)]
|
607 |
+
shrink_source = self.to_marker_edge(source_node_size, self.node_shape)
|
608 |
+
shrink_target = self.to_marker_edge(target_node_size, self.node_shape)
|
609 |
+
else:
|
610 |
+
shrink_source = self.to_marker_edge(self.node_size, self.node_shape)
|
611 |
+
shrink_target = shrink_source
|
612 |
+
shrink_source = max(shrink_source, self.min_source_margin)
|
613 |
+
shrink_target = max(shrink_target, self.min_target_margin)
|
614 |
+
|
615 |
+
# scale factor of arrow head
|
616 |
+
if isinstance(self.arrowsize, list):
|
617 |
+
mutation_scale = self.arrowsize[i]
|
618 |
+
else:
|
619 |
+
mutation_scale = self.arrowsize
|
620 |
+
|
621 |
+
if len(self.arrow_colors) > i:
|
622 |
+
arrow_color = self.arrow_colors[i]
|
623 |
+
elif len(self.arrow_colors) == 1:
|
624 |
+
arrow_color = self.arrow_colors[0]
|
625 |
+
else: # Cycle through colors
|
626 |
+
arrow_color = self.arrow_colors[i % len(self.arrow_colors)]
|
627 |
+
|
628 |
+
if self.np.iterable(self.linewidth):
|
629 |
+
if len(self.linewidth) > i:
|
630 |
+
linewidth = self.linewidth[i]
|
631 |
+
else:
|
632 |
+
linewidth = self.linewidth[i % len(self.linewidth)]
|
633 |
+
else:
|
634 |
+
linewidth = self.linewidth
|
635 |
+
|
636 |
+
if (
|
637 |
+
self.np.iterable(self.style)
|
638 |
+
and not isinstance(self.style, str)
|
639 |
+
and not isinstance(self.style, tuple)
|
640 |
+
):
|
641 |
+
if len(self.style) > i:
|
642 |
+
linestyle = self.style[i]
|
643 |
+
else: # Cycle through styles
|
644 |
+
linestyle = self.style[i % len(self.style)]
|
645 |
+
else:
|
646 |
+
linestyle = self.style
|
647 |
+
|
648 |
+
if x1 == x2 and y1 == y2:
|
649 |
+
connectionstyle = self.connectionstyle_factory.self_loop(
|
650 |
+
self.edge_indices[i]
|
651 |
+
)
|
652 |
+
else:
|
653 |
+
connectionstyle = self.connectionstyle_factory.curved(self.edge_indices[i])
|
654 |
+
return self.mpl.patches.FancyArrowPatch(
|
655 |
+
(x1, y1),
|
656 |
+
(x2, y2),
|
657 |
+
arrowstyle=self.arrowstyle,
|
658 |
+
shrinkA=shrink_source,
|
659 |
+
shrinkB=shrink_target,
|
660 |
+
mutation_scale=mutation_scale,
|
661 |
+
color=arrow_color,
|
662 |
+
linewidth=linewidth,
|
663 |
+
connectionstyle=connectionstyle,
|
664 |
+
linestyle=linestyle,
|
665 |
+
zorder=1, # arrows go behind nodes
|
666 |
+
)
|
667 |
+
|
668 |
+
def to_marker_edge(self, marker_size, marker):
|
669 |
+
if marker in "s^>v<d": # `large` markers need extra space
|
670 |
+
return self.np.sqrt(2 * marker_size) / 2
|
671 |
+
else:
|
672 |
+
return self.np.sqrt(marker_size) / 2
|
673 |
+
|
674 |
+
|
675 |
+
def draw_networkx_edges(
|
676 |
+
G,
|
677 |
+
pos,
|
678 |
+
edgelist=None,
|
679 |
+
width=1.0,
|
680 |
+
edge_color="k",
|
681 |
+
style="solid",
|
682 |
+
alpha=None,
|
683 |
+
arrowstyle=None,
|
684 |
+
arrowsize=10,
|
685 |
+
edge_cmap=None,
|
686 |
+
edge_vmin=None,
|
687 |
+
edge_vmax=None,
|
688 |
+
ax=None,
|
689 |
+
arrows=None,
|
690 |
+
label=None,
|
691 |
+
node_size=300,
|
692 |
+
nodelist=None,
|
693 |
+
node_shape="o",
|
694 |
+
connectionstyle="arc3",
|
695 |
+
min_source_margin=0,
|
696 |
+
min_target_margin=0,
|
697 |
+
hide_ticks=True,
|
698 |
+
):
|
699 |
+
r"""Draw the edges of the graph G.
|
700 |
+
|
701 |
+
This draws only the edges of the graph G.
|
702 |
+
|
703 |
+
Parameters
|
704 |
+
----------
|
705 |
+
G : graph
|
706 |
+
A networkx graph
|
707 |
+
|
708 |
+
pos : dictionary
|
709 |
+
A dictionary with nodes as keys and positions as values.
|
710 |
+
Positions should be sequences of length 2.
|
711 |
+
|
712 |
+
edgelist : collection of edge tuples (default=G.edges())
|
713 |
+
Draw only specified edges
|
714 |
+
|
715 |
+
width : float or array of floats (default=1.0)
|
716 |
+
Line width of edges
|
717 |
+
|
718 |
+
edge_color : color or array of colors (default='k')
|
719 |
+
Edge color. Can be a single color or a sequence of colors with the same
|
720 |
+
length as edgelist. Color can be string or rgb (or rgba) tuple of
|
721 |
+
floats from 0-1. If numeric values are specified they will be
|
722 |
+
mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
|
723 |
+
|
724 |
+
style : string or array of strings (default='solid')
|
725 |
+
Edge line style e.g.: '-', '--', '-.', ':'
|
726 |
+
or words like 'solid' or 'dashed'.
|
727 |
+
Can be a single style or a sequence of styles with the same
|
728 |
+
length as the edge list.
|
729 |
+
If less styles than edges are given the styles will cycle.
|
730 |
+
If more styles than edges are given the styles will be used sequentially
|
731 |
+
and not be exhausted.
|
732 |
+
Also, `(offset, onoffseq)` tuples can be used as style instead of a strings.
|
733 |
+
(See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
|
734 |
+
|
735 |
+
alpha : float or array of floats (default=None)
|
736 |
+
The edge transparency. This can be a single alpha value,
|
737 |
+
in which case it will be applied to all specified edges. Otherwise,
|
738 |
+
if it is an array, the elements of alpha will be applied to the colors
|
739 |
+
in order (cycling through alpha multiple times if necessary).
|
740 |
+
|
741 |
+
edge_cmap : Matplotlib colormap, optional
|
742 |
+
Colormap for mapping intensities of edges
|
743 |
+
|
744 |
+
edge_vmin,edge_vmax : floats, optional
|
745 |
+
Minimum and maximum for edge colormap scaling
|
746 |
+
|
747 |
+
ax : Matplotlib Axes object, optional
|
748 |
+
Draw the graph in the specified Matplotlib axes.
|
749 |
+
|
750 |
+
arrows : bool or None, optional (default=None)
|
751 |
+
If `None`, directed graphs draw arrowheads with
|
752 |
+
`~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
|
753 |
+
via `~matplotlib.collections.LineCollection` for speed.
|
754 |
+
If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
|
755 |
+
If `False`, draw edges using LineCollection (linear and fast).
|
756 |
+
|
757 |
+
Note: Arrowheads will be the same color as edges.
|
758 |
+
|
759 |
+
arrowstyle : str (default='-\|>' for directed graphs)
|
760 |
+
For directed graphs and `arrows==True` defaults to '-\|>',
|
761 |
+
For undirected graphs default to '-'.
|
762 |
+
|
763 |
+
See `matplotlib.patches.ArrowStyle` for more options.
|
764 |
+
|
765 |
+
arrowsize : int (default=10)
|
766 |
+
For directed graphs, choose the size of the arrow head's length and
|
767 |
+
width. See `matplotlib.patches.FancyArrowPatch` for attribute
|
768 |
+
`mutation_scale` for more info.
|
769 |
+
|
770 |
+
connectionstyle : string or iterable of strings (default="arc3")
|
771 |
+
Pass the connectionstyle parameter to create curved arc of rounding
|
772 |
+
radius rad. For example, connectionstyle='arc3,rad=0.2'.
|
773 |
+
See `matplotlib.patches.ConnectionStyle` and
|
774 |
+
`matplotlib.patches.FancyArrowPatch` for more info.
|
775 |
+
If Iterable, index indicates i'th edge key of MultiGraph
|
776 |
+
|
777 |
+
node_size : scalar or array (default=300)
|
778 |
+
Size of nodes. Though the nodes are not drawn with this function, the
|
779 |
+
node size is used in determining edge positioning.
|
780 |
+
|
781 |
+
nodelist : list, optional (default=G.nodes())
|
782 |
+
This provides the node order for the `node_size` array (if it is an array).
|
783 |
+
|
784 |
+
node_shape : string (default='o')
|
785 |
+
The marker used for nodes, used in determining edge positioning.
|
786 |
+
Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v<dph8'.
|
787 |
+
|
788 |
+
label : None or string
|
789 |
+
Label for legend
|
790 |
+
|
791 |
+
min_source_margin : int (default=0)
|
792 |
+
The minimum margin (gap) at the beginning of the edge at the source.
|
793 |
+
|
794 |
+
min_target_margin : int (default=0)
|
795 |
+
The minimum margin (gap) at the end of the edge at the target.
|
796 |
+
|
797 |
+
hide_ticks : bool, optional
|
798 |
+
Hide ticks of axes. When `True` (the default), ticks and ticklabels
|
799 |
+
are removed from the axes. To set ticks and tick labels to the pyplot default,
|
800 |
+
use ``hide_ticks=False``.
|
801 |
+
|
802 |
+
Returns
|
803 |
+
-------
|
804 |
+
matplotlib.collections.LineCollection or a list of matplotlib.patches.FancyArrowPatch
|
805 |
+
If ``arrows=True``, a list of FancyArrowPatches is returned.
|
806 |
+
If ``arrows=False``, a LineCollection is returned.
|
807 |
+
If ``arrows=None`` (the default), then a LineCollection is returned if
|
808 |
+
`G` is undirected, otherwise returns a list of FancyArrowPatches.
|
809 |
+
|
810 |
+
Notes
|
811 |
+
-----
|
812 |
+
For directed graphs, arrows are drawn at the head end. Arrows can be
|
813 |
+
turned off with keyword arrows=False or by passing an arrowstyle without
|
814 |
+
an arrow on the end.
|
815 |
+
|
816 |
+
Be sure to include `node_size` as a keyword argument; arrows are
|
817 |
+
drawn considering the size of nodes.
|
818 |
+
|
819 |
+
Self-loops are always drawn with `~matplotlib.patches.FancyArrowPatch`
|
820 |
+
regardless of the value of `arrows` or whether `G` is directed.
|
821 |
+
When ``arrows=False`` or ``arrows=None`` and `G` is undirected, the
|
822 |
+
FancyArrowPatches corresponding to the self-loops are not explicitly
|
823 |
+
returned. They should instead be accessed via the ``Axes.patches``
|
824 |
+
attribute (see examples).
|
825 |
+
|
826 |
+
Examples
|
827 |
+
--------
|
828 |
+
>>> G = nx.dodecahedral_graph()
|
829 |
+
>>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
|
830 |
+
|
831 |
+
>>> G = nx.DiGraph()
|
832 |
+
>>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
|
833 |
+
>>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
|
834 |
+
>>> alphas = [0.3, 0.4, 0.5]
|
835 |
+
>>> for i, arc in enumerate(arcs): # change alpha values of arcs
|
836 |
+
... arc.set_alpha(alphas[i])
|
837 |
+
|
838 |
+
The FancyArrowPatches corresponding to self-loops are not always
|
839 |
+
returned, but can always be accessed via the ``patches`` attribute of the
|
840 |
+
`matplotlib.Axes` object.
|
841 |
+
|
842 |
+
>>> import matplotlib.pyplot as plt
|
843 |
+
>>> fig, ax = plt.subplots()
|
844 |
+
>>> G = nx.Graph([(0, 1), (0, 0)]) # Self-loop at node 0
|
845 |
+
>>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
|
846 |
+
>>> self_loop_fap = ax.patches[0]
|
847 |
+
|
848 |
+
Also see the NetworkX drawing examples at
|
849 |
+
https://networkx.org/documentation/latest/auto_examples/index.html
|
850 |
+
|
851 |
+
See Also
|
852 |
+
--------
|
853 |
+
draw
|
854 |
+
draw_networkx
|
855 |
+
draw_networkx_nodes
|
856 |
+
draw_networkx_labels
|
857 |
+
draw_networkx_edge_labels
|
858 |
+
|
859 |
+
"""
|
860 |
+
import warnings
|
861 |
+
|
862 |
+
import matplotlib as mpl
|
863 |
+
import matplotlib.collections # call as mpl.collections
|
864 |
+
import matplotlib.colors # call as mpl.colors
|
865 |
+
import matplotlib.pyplot as plt
|
866 |
+
import numpy as np
|
867 |
+
|
868 |
+
# The default behavior is to use LineCollection to draw edges for
|
869 |
+
# undirected graphs (for performance reasons) and use FancyArrowPatches
|
870 |
+
# for directed graphs.
|
871 |
+
# The `arrows` keyword can be used to override the default behavior
|
872 |
+
if arrows is None:
|
873 |
+
use_linecollection = not (G.is_directed() or G.is_multigraph())
|
874 |
+
else:
|
875 |
+
if not isinstance(arrows, bool):
|
876 |
+
raise TypeError("Argument `arrows` must be of type bool or None")
|
877 |
+
use_linecollection = not arrows
|
878 |
+
|
879 |
+
if isinstance(connectionstyle, str):
|
880 |
+
connectionstyle = [connectionstyle]
|
881 |
+
elif np.iterable(connectionstyle):
|
882 |
+
connectionstyle = list(connectionstyle)
|
883 |
+
else:
|
884 |
+
msg = "draw_networkx_edges arg `connectionstyle` must be str or iterable"
|
885 |
+
raise nx.NetworkXError(msg)
|
886 |
+
|
887 |
+
# Some kwargs only apply to FancyArrowPatches. Warn users when they use
|
888 |
+
# non-default values for these kwargs when LineCollection is being used
|
889 |
+
# instead of silently ignoring the specified option
|
890 |
+
if use_linecollection:
|
891 |
+
msg = (
|
892 |
+
"\n\nThe {0} keyword argument is not applicable when drawing edges\n"
|
893 |
+
"with LineCollection.\n\n"
|
894 |
+
"To make this warning go away, either specify `arrows=True` to\n"
|
895 |
+
"force FancyArrowPatches or use the default values.\n"
|
896 |
+
"Note that using FancyArrowPatches may be slow for large graphs.\n"
|
897 |
+
)
|
898 |
+
if arrowstyle is not None:
|
899 |
+
warnings.warn(msg.format("arrowstyle"), category=UserWarning, stacklevel=2)
|
900 |
+
if arrowsize != 10:
|
901 |
+
warnings.warn(msg.format("arrowsize"), category=UserWarning, stacklevel=2)
|
902 |
+
if min_source_margin != 0:
|
903 |
+
warnings.warn(
|
904 |
+
msg.format("min_source_margin"), category=UserWarning, stacklevel=2
|
905 |
+
)
|
906 |
+
if min_target_margin != 0:
|
907 |
+
warnings.warn(
|
908 |
+
msg.format("min_target_margin"), category=UserWarning, stacklevel=2
|
909 |
+
)
|
910 |
+
if any(cs != "arc3" for cs in connectionstyle):
|
911 |
+
warnings.warn(
|
912 |
+
msg.format("connectionstyle"), category=UserWarning, stacklevel=2
|
913 |
+
)
|
914 |
+
|
915 |
+
# NOTE: Arrowstyle modification must occur after the warnings section
|
916 |
+
if arrowstyle is None:
|
917 |
+
arrowstyle = "-|>" if G.is_directed() else "-"
|
918 |
+
|
919 |
+
if ax is None:
|
920 |
+
ax = plt.gca()
|
921 |
+
|
922 |
+
if edgelist is None:
|
923 |
+
edgelist = list(G.edges) # (u, v, k) for multigraph (u, v) otherwise
|
924 |
+
|
925 |
+
if len(edgelist):
|
926 |
+
if G.is_multigraph():
|
927 |
+
key_count = collections.defaultdict(lambda: itertools.count(0))
|
928 |
+
edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
|
929 |
+
else:
|
930 |
+
edge_indices = [0] * len(edgelist)
|
931 |
+
else: # no edges!
|
932 |
+
return []
|
933 |
+
|
934 |
+
if nodelist is None:
|
935 |
+
nodelist = list(G.nodes())
|
936 |
+
|
937 |
+
# FancyArrowPatch handles color=None different from LineCollection
|
938 |
+
if edge_color is None:
|
939 |
+
edge_color = "k"
|
940 |
+
|
941 |
+
# set edge positions
|
942 |
+
edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
|
943 |
+
|
944 |
+
# Check if edge_color is an array of floats and map to edge_cmap.
|
945 |
+
# This is the only case handled differently from matplotlib
|
946 |
+
if (
|
947 |
+
np.iterable(edge_color)
|
948 |
+
and (len(edge_color) == len(edge_pos))
|
949 |
+
and np.all([isinstance(c, Number) for c in edge_color])
|
950 |
+
):
|
951 |
+
if edge_cmap is not None:
|
952 |
+
assert isinstance(edge_cmap, mpl.colors.Colormap)
|
953 |
+
else:
|
954 |
+
edge_cmap = plt.get_cmap()
|
955 |
+
if edge_vmin is None:
|
956 |
+
edge_vmin = min(edge_color)
|
957 |
+
if edge_vmax is None:
|
958 |
+
edge_vmax = max(edge_color)
|
959 |
+
color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax)
|
960 |
+
edge_color = [edge_cmap(color_normal(e)) for e in edge_color]
|
961 |
+
|
962 |
+
# compute initial view
|
963 |
+
minx = np.amin(np.ravel(edge_pos[:, :, 0]))
|
964 |
+
maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
|
965 |
+
miny = np.amin(np.ravel(edge_pos[:, :, 1]))
|
966 |
+
maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
|
967 |
+
w = maxx - minx
|
968 |
+
h = maxy - miny
|
969 |
+
|
970 |
+
# Self-loops are scaled by view extent, except in cases the extent
|
971 |
+
# is 0, e.g. for a single node. In this case, fall back to scaling
|
972 |
+
# by the maximum node size
|
973 |
+
selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
|
974 |
+
fancy_arrow_factory = FancyArrowFactory(
|
975 |
+
edge_pos,
|
976 |
+
edgelist,
|
977 |
+
nodelist,
|
978 |
+
edge_indices,
|
979 |
+
node_size,
|
980 |
+
selfloop_height,
|
981 |
+
connectionstyle,
|
982 |
+
node_shape,
|
983 |
+
arrowstyle,
|
984 |
+
arrowsize,
|
985 |
+
edge_color,
|
986 |
+
alpha,
|
987 |
+
width,
|
988 |
+
style,
|
989 |
+
min_source_margin,
|
990 |
+
min_target_margin,
|
991 |
+
ax=ax,
|
992 |
+
)
|
993 |
+
|
994 |
+
# Draw the edges
|
995 |
+
if use_linecollection:
|
996 |
+
edge_collection = mpl.collections.LineCollection(
|
997 |
+
edge_pos,
|
998 |
+
colors=edge_color,
|
999 |
+
linewidths=width,
|
1000 |
+
antialiaseds=(1,),
|
1001 |
+
linestyle=style,
|
1002 |
+
alpha=alpha,
|
1003 |
+
)
|
1004 |
+
edge_collection.set_cmap(edge_cmap)
|
1005 |
+
edge_collection.set_clim(edge_vmin, edge_vmax)
|
1006 |
+
edge_collection.set_zorder(1) # edges go behind nodes
|
1007 |
+
edge_collection.set_label(label)
|
1008 |
+
ax.add_collection(edge_collection)
|
1009 |
+
edge_viz_obj = edge_collection
|
1010 |
+
|
1011 |
+
# Make sure selfloop edges are also drawn
|
1012 |
+
# ---------------------------------------
|
1013 |
+
selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
|
1014 |
+
if selfloops_to_draw:
|
1015 |
+
edgelist_tuple = list(map(tuple, edgelist))
|
1016 |
+
arrow_collection = []
|
1017 |
+
for loop in selfloops_to_draw:
|
1018 |
+
i = edgelist_tuple.index(loop)
|
1019 |
+
arrow = fancy_arrow_factory(i)
|
1020 |
+
arrow_collection.append(arrow)
|
1021 |
+
ax.add_patch(arrow)
|
1022 |
+
else:
|
1023 |
+
edge_viz_obj = []
|
1024 |
+
for i in range(len(edgelist)):
|
1025 |
+
arrow = fancy_arrow_factory(i)
|
1026 |
+
ax.add_patch(arrow)
|
1027 |
+
edge_viz_obj.append(arrow)
|
1028 |
+
|
1029 |
+
# update view after drawing
|
1030 |
+
padx, pady = 0.05 * w, 0.05 * h
|
1031 |
+
corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
|
1032 |
+
ax.update_datalim(corners)
|
1033 |
+
ax.autoscale_view()
|
1034 |
+
|
1035 |
+
if hide_ticks:
|
1036 |
+
ax.tick_params(
|
1037 |
+
axis="both",
|
1038 |
+
which="both",
|
1039 |
+
bottom=False,
|
1040 |
+
left=False,
|
1041 |
+
labelbottom=False,
|
1042 |
+
labelleft=False,
|
1043 |
+
)
|
1044 |
+
|
1045 |
+
return edge_viz_obj
|
1046 |
+
|
1047 |
+
|
1048 |
+
def draw_networkx_labels(
|
1049 |
+
G,
|
1050 |
+
pos,
|
1051 |
+
labels=None,
|
1052 |
+
font_size=12,
|
1053 |
+
font_color="k",
|
1054 |
+
font_family="sans-serif",
|
1055 |
+
font_weight="normal",
|
1056 |
+
alpha=None,
|
1057 |
+
bbox=None,
|
1058 |
+
horizontalalignment="center",
|
1059 |
+
verticalalignment="center",
|
1060 |
+
ax=None,
|
1061 |
+
clip_on=True,
|
1062 |
+
hide_ticks=True,
|
1063 |
+
):
|
1064 |
+
"""Draw node labels on the graph G.
|
1065 |
+
|
1066 |
+
Parameters
|
1067 |
+
----------
|
1068 |
+
G : graph
|
1069 |
+
A networkx graph
|
1070 |
+
|
1071 |
+
pos : dictionary
|
1072 |
+
A dictionary with nodes as keys and positions as values.
|
1073 |
+
Positions should be sequences of length 2.
|
1074 |
+
|
1075 |
+
labels : dictionary (default={n: n for n in G})
|
1076 |
+
Node labels in a dictionary of text labels keyed by node.
|
1077 |
+
Node-keys in labels should appear as keys in `pos`.
|
1078 |
+
If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
|
1079 |
+
|
1080 |
+
font_size : int (default=12)
|
1081 |
+
Font size for text labels
|
1082 |
+
|
1083 |
+
font_color : color (default='k' black)
|
1084 |
+
Font color string. Color can be string or rgb (or rgba) tuple of
|
1085 |
+
floats from 0-1.
|
1086 |
+
|
1087 |
+
font_weight : string (default='normal')
|
1088 |
+
Font weight
|
1089 |
+
|
1090 |
+
font_family : string (default='sans-serif')
|
1091 |
+
Font family
|
1092 |
+
|
1093 |
+
alpha : float or None (default=None)
|
1094 |
+
The text transparency
|
1095 |
+
|
1096 |
+
bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
|
1097 |
+
Specify text box properties (e.g. shape, color etc.) for node labels.
|
1098 |
+
|
1099 |
+
horizontalalignment : string (default='center')
|
1100 |
+
Horizontal alignment {'center', 'right', 'left'}
|
1101 |
+
|
1102 |
+
verticalalignment : string (default='center')
|
1103 |
+
Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
|
1104 |
+
|
1105 |
+
ax : Matplotlib Axes object, optional
|
1106 |
+
Draw the graph in the specified Matplotlib axes.
|
1107 |
+
|
1108 |
+
clip_on : bool (default=True)
|
1109 |
+
Turn on clipping of node labels at axis boundaries
|
1110 |
+
|
1111 |
+
hide_ticks : bool, optional
|
1112 |
+
Hide ticks of axes. When `True` (the default), ticks and ticklabels
|
1113 |
+
are removed from the axes. To set ticks and tick labels to the pyplot default,
|
1114 |
+
use ``hide_ticks=False``.
|
1115 |
+
|
1116 |
+
Returns
|
1117 |
+
-------
|
1118 |
+
dict
|
1119 |
+
`dict` of labels keyed on the nodes
|
1120 |
+
|
1121 |
+
Examples
|
1122 |
+
--------
|
1123 |
+
>>> G = nx.dodecahedral_graph()
|
1124 |
+
>>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
|
1125 |
+
|
1126 |
+
Also see the NetworkX drawing examples at
|
1127 |
+
https://networkx.org/documentation/latest/auto_examples/index.html
|
1128 |
+
|
1129 |
+
See Also
|
1130 |
+
--------
|
1131 |
+
draw
|
1132 |
+
draw_networkx
|
1133 |
+
draw_networkx_nodes
|
1134 |
+
draw_networkx_edges
|
1135 |
+
draw_networkx_edge_labels
|
1136 |
+
"""
|
1137 |
+
import matplotlib.pyplot as plt
|
1138 |
+
|
1139 |
+
if ax is None:
|
1140 |
+
ax = plt.gca()
|
1141 |
+
|
1142 |
+
if labels is None:
|
1143 |
+
labels = {n: n for n in G.nodes()}
|
1144 |
+
|
1145 |
+
text_items = {} # there is no text collection so we'll fake one
|
1146 |
+
for n, label in labels.items():
|
1147 |
+
(x, y) = pos[n]
|
1148 |
+
if not isinstance(label, str):
|
1149 |
+
label = str(label) # this makes "1" and 1 labeled the same
|
1150 |
+
t = ax.text(
|
1151 |
+
x,
|
1152 |
+
y,
|
1153 |
+
label,
|
1154 |
+
size=font_size,
|
1155 |
+
color=font_color,
|
1156 |
+
family=font_family,
|
1157 |
+
weight=font_weight,
|
1158 |
+
alpha=alpha,
|
1159 |
+
horizontalalignment=horizontalalignment,
|
1160 |
+
verticalalignment=verticalalignment,
|
1161 |
+
transform=ax.transData,
|
1162 |
+
bbox=bbox,
|
1163 |
+
clip_on=clip_on,
|
1164 |
+
)
|
1165 |
+
text_items[n] = t
|
1166 |
+
|
1167 |
+
if hide_ticks:
|
1168 |
+
ax.tick_params(
|
1169 |
+
axis="both",
|
1170 |
+
which="both",
|
1171 |
+
bottom=False,
|
1172 |
+
left=False,
|
1173 |
+
labelbottom=False,
|
1174 |
+
labelleft=False,
|
1175 |
+
)
|
1176 |
+
|
1177 |
+
return text_items
|
1178 |
+
|
1179 |
+
|
1180 |
+
def draw_networkx_edge_labels(
|
1181 |
+
G,
|
1182 |
+
pos,
|
1183 |
+
edge_labels=None,
|
1184 |
+
label_pos=0.5,
|
1185 |
+
font_size=10,
|
1186 |
+
font_color="k",
|
1187 |
+
font_family="sans-serif",
|
1188 |
+
font_weight="normal",
|
1189 |
+
alpha=None,
|
1190 |
+
bbox=None,
|
1191 |
+
horizontalalignment="center",
|
1192 |
+
verticalalignment="center",
|
1193 |
+
ax=None,
|
1194 |
+
rotate=True,
|
1195 |
+
clip_on=True,
|
1196 |
+
node_size=300,
|
1197 |
+
nodelist=None,
|
1198 |
+
connectionstyle="arc3",
|
1199 |
+
hide_ticks=True,
|
1200 |
+
):
|
1201 |
+
"""Draw edge labels.
|
1202 |
+
|
1203 |
+
Parameters
|
1204 |
+
----------
|
1205 |
+
G : graph
|
1206 |
+
A networkx graph
|
1207 |
+
|
1208 |
+
pos : dictionary
|
1209 |
+
A dictionary with nodes as keys and positions as values.
|
1210 |
+
Positions should be sequences of length 2.
|
1211 |
+
|
1212 |
+
edge_labels : dictionary (default=None)
|
1213 |
+
Edge labels in a dictionary of labels keyed by edge two-tuple.
|
1214 |
+
Only labels for the keys in the dictionary are drawn.
|
1215 |
+
|
1216 |
+
label_pos : float (default=0.5)
|
1217 |
+
Position of edge label along edge (0=head, 0.5=center, 1=tail)
|
1218 |
+
|
1219 |
+
font_size : int (default=10)
|
1220 |
+
Font size for text labels
|
1221 |
+
|
1222 |
+
font_color : color (default='k' black)
|
1223 |
+
Font color string. Color can be string or rgb (or rgba) tuple of
|
1224 |
+
floats from 0-1.
|
1225 |
+
|
1226 |
+
font_weight : string (default='normal')
|
1227 |
+
Font weight
|
1228 |
+
|
1229 |
+
font_family : string (default='sans-serif')
|
1230 |
+
Font family
|
1231 |
+
|
1232 |
+
alpha : float or None (default=None)
|
1233 |
+
The text transparency
|
1234 |
+
|
1235 |
+
bbox : Matplotlib bbox, optional
|
1236 |
+
Specify text box properties (e.g. shape, color etc.) for edge labels.
|
1237 |
+
Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
|
1238 |
+
|
1239 |
+
horizontalalignment : string (default='center')
|
1240 |
+
Horizontal alignment {'center', 'right', 'left'}
|
1241 |
+
|
1242 |
+
verticalalignment : string (default='center')
|
1243 |
+
Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
|
1244 |
+
|
1245 |
+
ax : Matplotlib Axes object, optional
|
1246 |
+
Draw the graph in the specified Matplotlib axes.
|
1247 |
+
|
1248 |
+
rotate : bool (default=True)
|
1249 |
+
Rotate edge labels to lie parallel to edges
|
1250 |
+
|
1251 |
+
clip_on : bool (default=True)
|
1252 |
+
Turn on clipping of edge labels at axis boundaries
|
1253 |
+
|
1254 |
+
node_size : scalar or array (default=300)
|
1255 |
+
Size of nodes. If an array it must be the same length as nodelist.
|
1256 |
+
|
1257 |
+
nodelist : list, optional (default=G.nodes())
|
1258 |
+
This provides the node order for the `node_size` array (if it is an array).
|
1259 |
+
|
1260 |
+
connectionstyle : string or iterable of strings (default="arc3")
|
1261 |
+
Pass the connectionstyle parameter to create curved arc of rounding
|
1262 |
+
radius rad. For example, connectionstyle='arc3,rad=0.2'.
|
1263 |
+
See `matplotlib.patches.ConnectionStyle` and
|
1264 |
+
`matplotlib.patches.FancyArrowPatch` for more info.
|
1265 |
+
If Iterable, index indicates i'th edge key of MultiGraph
|
1266 |
+
|
1267 |
+
hide_ticks : bool, optional
|
1268 |
+
Hide ticks of axes. When `True` (the default), ticks and ticklabels
|
1269 |
+
are removed from the axes. To set ticks and tick labels to the pyplot default,
|
1270 |
+
use ``hide_ticks=False``.
|
1271 |
+
|
1272 |
+
Returns
|
1273 |
+
-------
|
1274 |
+
dict
|
1275 |
+
`dict` of labels keyed by edge
|
1276 |
+
|
1277 |
+
Examples
|
1278 |
+
--------
|
1279 |
+
>>> G = nx.dodecahedral_graph()
|
1280 |
+
>>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
|
1281 |
+
|
1282 |
+
Also see the NetworkX drawing examples at
|
1283 |
+
https://networkx.org/documentation/latest/auto_examples/index.html
|
1284 |
+
|
1285 |
+
See Also
|
1286 |
+
--------
|
1287 |
+
draw
|
1288 |
+
draw_networkx
|
1289 |
+
draw_networkx_nodes
|
1290 |
+
draw_networkx_edges
|
1291 |
+
draw_networkx_labels
|
1292 |
+
"""
|
1293 |
+
import matplotlib as mpl
|
1294 |
+
import matplotlib.pyplot as plt
|
1295 |
+
import numpy as np
|
1296 |
+
|
1297 |
+
class CurvedArrowText(mpl.text.Text):
|
1298 |
+
def __init__(
|
1299 |
+
self,
|
1300 |
+
arrow,
|
1301 |
+
*args,
|
1302 |
+
label_pos=0.5,
|
1303 |
+
labels_horizontal=False,
|
1304 |
+
ax=None,
|
1305 |
+
**kwargs,
|
1306 |
+
):
|
1307 |
+
# Bind to FancyArrowPatch
|
1308 |
+
self.arrow = arrow
|
1309 |
+
# how far along the text should be on the curve,
|
1310 |
+
# 0 is at start, 1 is at end etc.
|
1311 |
+
self.label_pos = label_pos
|
1312 |
+
self.labels_horizontal = labels_horizontal
|
1313 |
+
if ax is None:
|
1314 |
+
ax = plt.gca()
|
1315 |
+
self.ax = ax
|
1316 |
+
self.x, self.y, self.angle = self._update_text_pos_angle(arrow)
|
1317 |
+
|
1318 |
+
# Create text object
|
1319 |
+
super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
|
1320 |
+
# Bind to axis
|
1321 |
+
self.ax.add_artist(self)
|
1322 |
+
|
1323 |
+
def _get_arrow_path_disp(self, arrow):
|
1324 |
+
"""
|
1325 |
+
This is part of FancyArrowPatch._get_path_in_displaycoord
|
1326 |
+
It omits the second part of the method where path is converted
|
1327 |
+
to polygon based on width
|
1328 |
+
The transform is taken from ax, not the object, as the object
|
1329 |
+
has not been added yet, and doesn't have transform
|
1330 |
+
"""
|
1331 |
+
dpi_cor = arrow._dpi_cor
|
1332 |
+
# trans_data = arrow.get_transform()
|
1333 |
+
trans_data = self.ax.transData
|
1334 |
+
if arrow._posA_posB is not None:
|
1335 |
+
posA = arrow._convert_xy_units(arrow._posA_posB[0])
|
1336 |
+
posB = arrow._convert_xy_units(arrow._posA_posB[1])
|
1337 |
+
(posA, posB) = trans_data.transform((posA, posB))
|
1338 |
+
_path = arrow.get_connectionstyle()(
|
1339 |
+
posA,
|
1340 |
+
posB,
|
1341 |
+
patchA=arrow.patchA,
|
1342 |
+
patchB=arrow.patchB,
|
1343 |
+
shrinkA=arrow.shrinkA * dpi_cor,
|
1344 |
+
shrinkB=arrow.shrinkB * dpi_cor,
|
1345 |
+
)
|
1346 |
+
else:
|
1347 |
+
_path = trans_data.transform_path(arrow._path_original)
|
1348 |
+
# Return is in display coordinates
|
1349 |
+
return _path
|
1350 |
+
|
1351 |
+
def _update_text_pos_angle(self, arrow):
|
1352 |
+
# Fractional label position
|
1353 |
+
path_disp = self._get_arrow_path_disp(arrow)
|
1354 |
+
(x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
|
1355 |
+
# Text position at a proportion t along the line in display coords
|
1356 |
+
# default is 0.5 so text appears at the halfway point
|
1357 |
+
t = self.label_pos
|
1358 |
+
tt = 1 - t
|
1359 |
+
x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
|
1360 |
+
y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
|
1361 |
+
if self.labels_horizontal:
|
1362 |
+
# Horizontal text labels
|
1363 |
+
angle = 0
|
1364 |
+
else:
|
1365 |
+
# Labels parallel to curve
|
1366 |
+
change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
|
1367 |
+
change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
|
1368 |
+
angle = (np.arctan2(change_y, change_x) / (2 * np.pi)) * 360
|
1369 |
+
# Text is "right way up"
|
1370 |
+
if angle > 90:
|
1371 |
+
angle -= 180
|
1372 |
+
if angle < -90:
|
1373 |
+
angle += 180
|
1374 |
+
(x, y) = self.ax.transData.inverted().transform((x, y))
|
1375 |
+
return x, y, angle
|
1376 |
+
|
1377 |
+
def draw(self, renderer):
|
1378 |
+
# recalculate the text position and angle
|
1379 |
+
self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
|
1380 |
+
self.set_position((self.x, self.y))
|
1381 |
+
self.set_rotation(self.angle)
|
1382 |
+
# redraw text
|
1383 |
+
super().draw(renderer)
|
1384 |
+
|
1385 |
+
# use default box of white with white border
|
1386 |
+
if bbox is None:
|
1387 |
+
bbox = {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
|
1388 |
+
|
1389 |
+
if isinstance(connectionstyle, str):
|
1390 |
+
connectionstyle = [connectionstyle]
|
1391 |
+
elif np.iterable(connectionstyle):
|
1392 |
+
connectionstyle = list(connectionstyle)
|
1393 |
+
else:
|
1394 |
+
raise nx.NetworkXError(
|
1395 |
+
"draw_networkx_edges arg `connectionstyle` must be"
|
1396 |
+
"string or iterable of strings"
|
1397 |
+
)
|
1398 |
+
|
1399 |
+
if ax is None:
|
1400 |
+
ax = plt.gca()
|
1401 |
+
|
1402 |
+
if edge_labels is None:
|
1403 |
+
kwds = {"keys": True} if G.is_multigraph() else {}
|
1404 |
+
edge_labels = {tuple(edge): d for *edge, d in G.edges(data=True, **kwds)}
|
1405 |
+
# NOTHING TO PLOT
|
1406 |
+
if not edge_labels:
|
1407 |
+
return {}
|
1408 |
+
edgelist, labels = zip(*edge_labels.items())
|
1409 |
+
|
1410 |
+
if nodelist is None:
|
1411 |
+
nodelist = list(G.nodes())
|
1412 |
+
|
1413 |
+
# set edge positions
|
1414 |
+
edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
|
1415 |
+
|
1416 |
+
if G.is_multigraph():
|
1417 |
+
key_count = collections.defaultdict(lambda: itertools.count(0))
|
1418 |
+
edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
|
1419 |
+
else:
|
1420 |
+
edge_indices = [0] * len(edgelist)
|
1421 |
+
|
1422 |
+
# Used to determine self loop mid-point
|
1423 |
+
# Note, that this will not be accurate,
|
1424 |
+
# if not drawing edge_labels for all edges drawn
|
1425 |
+
h = 0
|
1426 |
+
if edge_labels:
|
1427 |
+
miny = np.amin(np.ravel(edge_pos[:, :, 1]))
|
1428 |
+
maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
|
1429 |
+
h = maxy - miny
|
1430 |
+
selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
|
1431 |
+
fancy_arrow_factory = FancyArrowFactory(
|
1432 |
+
edge_pos,
|
1433 |
+
edgelist,
|
1434 |
+
nodelist,
|
1435 |
+
edge_indices,
|
1436 |
+
node_size,
|
1437 |
+
selfloop_height,
|
1438 |
+
connectionstyle,
|
1439 |
+
ax=ax,
|
1440 |
+
)
|
1441 |
+
|
1442 |
+
text_items = {}
|
1443 |
+
for i, (edge, label) in enumerate(zip(edgelist, labels)):
|
1444 |
+
if not isinstance(label, str):
|
1445 |
+
label = str(label) # this makes "1" and 1 labeled the same
|
1446 |
+
|
1447 |
+
n1, n2 = edge[:2]
|
1448 |
+
arrow = fancy_arrow_factory(i)
|
1449 |
+
if n1 == n2:
|
1450 |
+
connectionstyle_obj = arrow.get_connectionstyle()
|
1451 |
+
posA = ax.transData.transform(pos[n1])
|
1452 |
+
path_disp = connectionstyle_obj(posA, posA)
|
1453 |
+
path_data = ax.transData.inverted().transform_path(path_disp)
|
1454 |
+
x, y = path_data.vertices[0]
|
1455 |
+
text_items[edge] = ax.text(
|
1456 |
+
x,
|
1457 |
+
y,
|
1458 |
+
label,
|
1459 |
+
size=font_size,
|
1460 |
+
color=font_color,
|
1461 |
+
family=font_family,
|
1462 |
+
weight=font_weight,
|
1463 |
+
alpha=alpha,
|
1464 |
+
horizontalalignment=horizontalalignment,
|
1465 |
+
verticalalignment=verticalalignment,
|
1466 |
+
rotation=0,
|
1467 |
+
transform=ax.transData,
|
1468 |
+
bbox=bbox,
|
1469 |
+
zorder=1,
|
1470 |
+
clip_on=clip_on,
|
1471 |
+
)
|
1472 |
+
else:
|
1473 |
+
text_items[edge] = CurvedArrowText(
|
1474 |
+
arrow,
|
1475 |
+
label,
|
1476 |
+
size=font_size,
|
1477 |
+
color=font_color,
|
1478 |
+
family=font_family,
|
1479 |
+
weight=font_weight,
|
1480 |
+
alpha=alpha,
|
1481 |
+
horizontalalignment=horizontalalignment,
|
1482 |
+
verticalalignment=verticalalignment,
|
1483 |
+
transform=ax.transData,
|
1484 |
+
bbox=bbox,
|
1485 |
+
zorder=1,
|
1486 |
+
clip_on=clip_on,
|
1487 |
+
label_pos=label_pos,
|
1488 |
+
labels_horizontal=not rotate,
|
1489 |
+
ax=ax,
|
1490 |
+
)
|
1491 |
+
|
1492 |
+
if hide_ticks:
|
1493 |
+
ax.tick_params(
|
1494 |
+
axis="both",
|
1495 |
+
which="both",
|
1496 |
+
bottom=False,
|
1497 |
+
left=False,
|
1498 |
+
labelbottom=False,
|
1499 |
+
labelleft=False,
|
1500 |
+
)
|
1501 |
+
|
1502 |
+
return text_items
|
1503 |
+
|
1504 |
+
|
1505 |
+
def draw_circular(G, **kwargs):
|
1506 |
+
"""Draw the graph `G` with a circular layout.
|
1507 |
+
|
1508 |
+
This is a convenience function equivalent to::
|
1509 |
+
|
1510 |
+
nx.draw(G, pos=nx.circular_layout(G), **kwargs)
|
1511 |
+
|
1512 |
+
Parameters
|
1513 |
+
----------
|
1514 |
+
G : graph
|
1515 |
+
A networkx graph
|
1516 |
+
|
1517 |
+
kwargs : optional keywords
|
1518 |
+
See `draw_networkx` for a description of optional keywords.
|
1519 |
+
|
1520 |
+
Notes
|
1521 |
+
-----
|
1522 |
+
The layout is computed each time this function is called. For
|
1523 |
+
repeated drawing it is much more efficient to call
|
1524 |
+
`~networkx.drawing.layout.circular_layout` directly and reuse the result::
|
1525 |
+
|
1526 |
+
>>> G = nx.complete_graph(5)
|
1527 |
+
>>> pos = nx.circular_layout(G)
|
1528 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1529 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1530 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1531 |
+
|
1532 |
+
Examples
|
1533 |
+
--------
|
1534 |
+
>>> G = nx.path_graph(5)
|
1535 |
+
>>> nx.draw_circular(G)
|
1536 |
+
|
1537 |
+
See Also
|
1538 |
+
--------
|
1539 |
+
:func:`~networkx.drawing.layout.circular_layout`
|
1540 |
+
"""
|
1541 |
+
draw(G, circular_layout(G), **kwargs)
|
1542 |
+
|
1543 |
+
|
1544 |
+
def draw_kamada_kawai(G, **kwargs):
|
1545 |
+
"""Draw the graph `G` with a Kamada-Kawai force-directed layout.
|
1546 |
+
|
1547 |
+
This is a convenience function equivalent to::
|
1548 |
+
|
1549 |
+
nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
|
1550 |
+
|
1551 |
+
Parameters
|
1552 |
+
----------
|
1553 |
+
G : graph
|
1554 |
+
A networkx graph
|
1555 |
+
|
1556 |
+
kwargs : optional keywords
|
1557 |
+
See `draw_networkx` for a description of optional keywords.
|
1558 |
+
|
1559 |
+
Notes
|
1560 |
+
-----
|
1561 |
+
The layout is computed each time this function is called.
|
1562 |
+
For repeated drawing it is much more efficient to call
|
1563 |
+
`~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
|
1564 |
+
result::
|
1565 |
+
|
1566 |
+
>>> G = nx.complete_graph(5)
|
1567 |
+
>>> pos = nx.kamada_kawai_layout(G)
|
1568 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1569 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1570 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1571 |
+
|
1572 |
+
Examples
|
1573 |
+
--------
|
1574 |
+
>>> G = nx.path_graph(5)
|
1575 |
+
>>> nx.draw_kamada_kawai(G)
|
1576 |
+
|
1577 |
+
See Also
|
1578 |
+
--------
|
1579 |
+
:func:`~networkx.drawing.layout.kamada_kawai_layout`
|
1580 |
+
"""
|
1581 |
+
draw(G, kamada_kawai_layout(G), **kwargs)
|
1582 |
+
|
1583 |
+
|
1584 |
+
def draw_random(G, **kwargs):
|
1585 |
+
"""Draw the graph `G` with a random layout.
|
1586 |
+
|
1587 |
+
This is a convenience function equivalent to::
|
1588 |
+
|
1589 |
+
nx.draw(G, pos=nx.random_layout(G), **kwargs)
|
1590 |
+
|
1591 |
+
Parameters
|
1592 |
+
----------
|
1593 |
+
G : graph
|
1594 |
+
A networkx graph
|
1595 |
+
|
1596 |
+
kwargs : optional keywords
|
1597 |
+
See `draw_networkx` for a description of optional keywords.
|
1598 |
+
|
1599 |
+
Notes
|
1600 |
+
-----
|
1601 |
+
The layout is computed each time this function is called.
|
1602 |
+
For repeated drawing it is much more efficient to call
|
1603 |
+
`~networkx.drawing.layout.random_layout` directly and reuse the result::
|
1604 |
+
|
1605 |
+
>>> G = nx.complete_graph(5)
|
1606 |
+
>>> pos = nx.random_layout(G)
|
1607 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1608 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1609 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1610 |
+
|
1611 |
+
Examples
|
1612 |
+
--------
|
1613 |
+
>>> G = nx.lollipop_graph(4, 3)
|
1614 |
+
>>> nx.draw_random(G)
|
1615 |
+
|
1616 |
+
See Also
|
1617 |
+
--------
|
1618 |
+
:func:`~networkx.drawing.layout.random_layout`
|
1619 |
+
"""
|
1620 |
+
draw(G, random_layout(G), **kwargs)
|
1621 |
+
|
1622 |
+
|
1623 |
+
def draw_spectral(G, **kwargs):
|
1624 |
+
"""Draw the graph `G` with a spectral 2D layout.
|
1625 |
+
|
1626 |
+
This is a convenience function equivalent to::
|
1627 |
+
|
1628 |
+
nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
|
1629 |
+
|
1630 |
+
For more information about how node positions are determined, see
|
1631 |
+
`~networkx.drawing.layout.spectral_layout`.
|
1632 |
+
|
1633 |
+
Parameters
|
1634 |
+
----------
|
1635 |
+
G : graph
|
1636 |
+
A networkx graph
|
1637 |
+
|
1638 |
+
kwargs : optional keywords
|
1639 |
+
See `draw_networkx` for a description of optional keywords.
|
1640 |
+
|
1641 |
+
Notes
|
1642 |
+
-----
|
1643 |
+
The layout is computed each time this function is called.
|
1644 |
+
For repeated drawing it is much more efficient to call
|
1645 |
+
`~networkx.drawing.layout.spectral_layout` directly and reuse the result::
|
1646 |
+
|
1647 |
+
>>> G = nx.complete_graph(5)
|
1648 |
+
>>> pos = nx.spectral_layout(G)
|
1649 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1650 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1651 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1652 |
+
|
1653 |
+
Examples
|
1654 |
+
--------
|
1655 |
+
>>> G = nx.path_graph(5)
|
1656 |
+
>>> nx.draw_spectral(G)
|
1657 |
+
|
1658 |
+
See Also
|
1659 |
+
--------
|
1660 |
+
:func:`~networkx.drawing.layout.spectral_layout`
|
1661 |
+
"""
|
1662 |
+
draw(G, spectral_layout(G), **kwargs)
|
1663 |
+
|
1664 |
+
|
1665 |
+
def draw_spring(G, **kwargs):
|
1666 |
+
"""Draw the graph `G` with a spring layout.
|
1667 |
+
|
1668 |
+
This is a convenience function equivalent to::
|
1669 |
+
|
1670 |
+
nx.draw(G, pos=nx.spring_layout(G), **kwargs)
|
1671 |
+
|
1672 |
+
Parameters
|
1673 |
+
----------
|
1674 |
+
G : graph
|
1675 |
+
A networkx graph
|
1676 |
+
|
1677 |
+
kwargs : optional keywords
|
1678 |
+
See `draw_networkx` for a description of optional keywords.
|
1679 |
+
|
1680 |
+
Notes
|
1681 |
+
-----
|
1682 |
+
`~networkx.drawing.layout.spring_layout` is also the default layout for
|
1683 |
+
`draw`, so this function is equivalent to `draw`.
|
1684 |
+
|
1685 |
+
The layout is computed each time this function is called.
|
1686 |
+
For repeated drawing it is much more efficient to call
|
1687 |
+
`~networkx.drawing.layout.spring_layout` directly and reuse the result::
|
1688 |
+
|
1689 |
+
>>> G = nx.complete_graph(5)
|
1690 |
+
>>> pos = nx.spring_layout(G)
|
1691 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1692 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1693 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1694 |
+
|
1695 |
+
Examples
|
1696 |
+
--------
|
1697 |
+
>>> G = nx.path_graph(20)
|
1698 |
+
>>> nx.draw_spring(G)
|
1699 |
+
|
1700 |
+
See Also
|
1701 |
+
--------
|
1702 |
+
draw
|
1703 |
+
:func:`~networkx.drawing.layout.spring_layout`
|
1704 |
+
"""
|
1705 |
+
draw(G, spring_layout(G), **kwargs)
|
1706 |
+
|
1707 |
+
|
1708 |
+
def draw_shell(G, nlist=None, **kwargs):
|
1709 |
+
"""Draw networkx graph `G` with shell layout.
|
1710 |
+
|
1711 |
+
This is a convenience function equivalent to::
|
1712 |
+
|
1713 |
+
nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
|
1714 |
+
|
1715 |
+
Parameters
|
1716 |
+
----------
|
1717 |
+
G : graph
|
1718 |
+
A networkx graph
|
1719 |
+
|
1720 |
+
nlist : list of list of nodes, optional
|
1721 |
+
A list containing lists of nodes representing the shells.
|
1722 |
+
Default is `None`, meaning all nodes are in a single shell.
|
1723 |
+
See `~networkx.drawing.layout.shell_layout` for details.
|
1724 |
+
|
1725 |
+
kwargs : optional keywords
|
1726 |
+
See `draw_networkx` for a description of optional keywords.
|
1727 |
+
|
1728 |
+
Notes
|
1729 |
+
-----
|
1730 |
+
The layout is computed each time this function is called.
|
1731 |
+
For repeated drawing it is much more efficient to call
|
1732 |
+
`~networkx.drawing.layout.shell_layout` directly and reuse the result::
|
1733 |
+
|
1734 |
+
>>> G = nx.complete_graph(5)
|
1735 |
+
>>> pos = nx.shell_layout(G)
|
1736 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1737 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1738 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1739 |
+
|
1740 |
+
Examples
|
1741 |
+
--------
|
1742 |
+
>>> G = nx.path_graph(4)
|
1743 |
+
>>> shells = [[0], [1, 2, 3]]
|
1744 |
+
>>> nx.draw_shell(G, nlist=shells)
|
1745 |
+
|
1746 |
+
See Also
|
1747 |
+
--------
|
1748 |
+
:func:`~networkx.drawing.layout.shell_layout`
|
1749 |
+
"""
|
1750 |
+
draw(G, shell_layout(G, nlist=nlist), **kwargs)
|
1751 |
+
|
1752 |
+
|
1753 |
+
def draw_planar(G, **kwargs):
|
1754 |
+
"""Draw a planar networkx graph `G` with planar layout.
|
1755 |
+
|
1756 |
+
This is a convenience function equivalent to::
|
1757 |
+
|
1758 |
+
nx.draw(G, pos=nx.planar_layout(G), **kwargs)
|
1759 |
+
|
1760 |
+
Parameters
|
1761 |
+
----------
|
1762 |
+
G : graph
|
1763 |
+
A planar networkx graph
|
1764 |
+
|
1765 |
+
kwargs : optional keywords
|
1766 |
+
See `draw_networkx` for a description of optional keywords.
|
1767 |
+
|
1768 |
+
Raises
|
1769 |
+
------
|
1770 |
+
NetworkXException
|
1771 |
+
When `G` is not planar
|
1772 |
+
|
1773 |
+
Notes
|
1774 |
+
-----
|
1775 |
+
The layout is computed each time this function is called.
|
1776 |
+
For repeated drawing it is much more efficient to call
|
1777 |
+
`~networkx.drawing.layout.planar_layout` directly and reuse the result::
|
1778 |
+
|
1779 |
+
>>> G = nx.path_graph(5)
|
1780 |
+
>>> pos = nx.planar_layout(G)
|
1781 |
+
>>> nx.draw(G, pos=pos) # Draw the original graph
|
1782 |
+
>>> # Draw a subgraph, reusing the same node positions
|
1783 |
+
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
|
1784 |
+
|
1785 |
+
Examples
|
1786 |
+
--------
|
1787 |
+
>>> G = nx.path_graph(4)
|
1788 |
+
>>> nx.draw_planar(G)
|
1789 |
+
|
1790 |
+
See Also
|
1791 |
+
--------
|
1792 |
+
:func:`~networkx.drawing.layout.planar_layout`
|
1793 |
+
"""
|
1794 |
+
draw(G, planar_layout(G), **kwargs)
|
1795 |
+
|
1796 |
+
|
1797 |
+
def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
|
1798 |
+
"""Apply an alpha (or list of alphas) to the colors provided.
|
1799 |
+
|
1800 |
+
Parameters
|
1801 |
+
----------
|
1802 |
+
|
1803 |
+
colors : color string or array of floats (default='r')
|
1804 |
+
Color of element. Can be a single color format string,
|
1805 |
+
or a sequence of colors with the same length as nodelist.
|
1806 |
+
If numeric values are specified they will be mapped to
|
1807 |
+
colors using the cmap and vmin,vmax parameters. See
|
1808 |
+
matplotlib.scatter for more details.
|
1809 |
+
|
1810 |
+
alpha : float or array of floats
|
1811 |
+
Alpha values for elements. This can be a single alpha value, in
|
1812 |
+
which case it will be applied to all the elements of color. Otherwise,
|
1813 |
+
if it is an array, the elements of alpha will be applied to the colors
|
1814 |
+
in order (cycling through alpha multiple times if necessary).
|
1815 |
+
|
1816 |
+
elem_list : array of networkx objects
|
1817 |
+
The list of elements which are being colored. These could be nodes,
|
1818 |
+
edges or labels.
|
1819 |
+
|
1820 |
+
cmap : matplotlib colormap
|
1821 |
+
Color map for use if colors is a list of floats corresponding to points
|
1822 |
+
on a color mapping.
|
1823 |
+
|
1824 |
+
vmin, vmax : float
|
1825 |
+
Minimum and maximum values for normalizing colors if a colormap is used
|
1826 |
+
|
1827 |
+
Returns
|
1828 |
+
-------
|
1829 |
+
|
1830 |
+
rgba_colors : numpy ndarray
|
1831 |
+
Array containing RGBA format values for each of the node colours.
|
1832 |
+
|
1833 |
+
"""
|
1834 |
+
from itertools import cycle, islice
|
1835 |
+
|
1836 |
+
import matplotlib as mpl
|
1837 |
+
import matplotlib.cm # call as mpl.cm
|
1838 |
+
import matplotlib.colors # call as mpl.colors
|
1839 |
+
import numpy as np
|
1840 |
+
|
1841 |
+
# If we have been provided with a list of numbers as long as elem_list,
|
1842 |
+
# apply the color mapping.
|
1843 |
+
if len(colors) == len(elem_list) and isinstance(colors[0], Number):
|
1844 |
+
mapper = mpl.cm.ScalarMappable(cmap=cmap)
|
1845 |
+
mapper.set_clim(vmin, vmax)
|
1846 |
+
rgba_colors = mapper.to_rgba(colors)
|
1847 |
+
# Otherwise, convert colors to matplotlib's RGB using the colorConverter
|
1848 |
+
# object. These are converted to numpy ndarrays to be consistent with the
|
1849 |
+
# to_rgba method of ScalarMappable.
|
1850 |
+
else:
|
1851 |
+
try:
|
1852 |
+
rgba_colors = np.array([mpl.colors.colorConverter.to_rgba(colors)])
|
1853 |
+
except ValueError:
|
1854 |
+
rgba_colors = np.array(
|
1855 |
+
[mpl.colors.colorConverter.to_rgba(color) for color in colors]
|
1856 |
+
)
|
1857 |
+
# Set the final column of the rgba_colors to have the relevant alpha values
|
1858 |
+
try:
|
1859 |
+
# If alpha is longer than the number of colors, resize to the number of
|
1860 |
+
# elements. Also, if rgba_colors.size (the number of elements of
|
1861 |
+
# rgba_colors) is the same as the number of elements, resize the array,
|
1862 |
+
# to avoid it being interpreted as a colormap by scatter()
|
1863 |
+
if len(alpha) > len(rgba_colors) or rgba_colors.size == len(elem_list):
|
1864 |
+
rgba_colors = np.resize(rgba_colors, (len(elem_list), 4))
|
1865 |
+
rgba_colors[1:, 0] = rgba_colors[0, 0]
|
1866 |
+
rgba_colors[1:, 1] = rgba_colors[0, 1]
|
1867 |
+
rgba_colors[1:, 2] = rgba_colors[0, 2]
|
1868 |
+
rgba_colors[:, 3] = list(islice(cycle(alpha), len(rgba_colors)))
|
1869 |
+
except TypeError:
|
1870 |
+
rgba_colors[:, -1] = alpha
|
1871 |
+
return rgba_colors
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (190 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc
ADDED
Binary file (9.75 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc
ADDED
Binary file (7.38 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc
ADDED
Binary file (18 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc
ADDED
Binary file (5.28 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc
ADDED
Binary file (26.3 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for PyGraphviz interface."""
|
2 |
+
import warnings
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
pygraphviz = pytest.importorskip("pygraphviz")
|
7 |
+
|
8 |
+
|
9 |
+
import networkx as nx
|
10 |
+
from networkx.utils import edges_equal, graphs_equal, nodes_equal
|
11 |
+
|
12 |
+
|
13 |
+
class TestAGraph:
|
14 |
+
def build_graph(self, G):
|
15 |
+
edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")]
|
16 |
+
G.add_edges_from(edges)
|
17 |
+
G.add_node("E")
|
18 |
+
G.graph["metal"] = "bronze"
|
19 |
+
return G
|
20 |
+
|
21 |
+
def assert_equal(self, G1, G2):
|
22 |
+
assert nodes_equal(G1.nodes(), G2.nodes())
|
23 |
+
assert edges_equal(G1.edges(), G2.edges())
|
24 |
+
assert G1.graph["metal"] == G2.graph["metal"]
|
25 |
+
|
26 |
+
@pytest.mark.parametrize(
|
27 |
+
"G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
|
28 |
+
)
|
29 |
+
def test_agraph_roundtripping(self, G, tmp_path):
|
30 |
+
G = self.build_graph(G)
|
31 |
+
A = nx.nx_agraph.to_agraph(G)
|
32 |
+
H = nx.nx_agraph.from_agraph(A)
|
33 |
+
self.assert_equal(G, H)
|
34 |
+
|
35 |
+
fname = tmp_path / "test.dot"
|
36 |
+
nx.drawing.nx_agraph.write_dot(H, fname)
|
37 |
+
Hin = nx.nx_agraph.read_dot(fname)
|
38 |
+
self.assert_equal(H, Hin)
|
39 |
+
|
40 |
+
fname = tmp_path / "fh_test.dot"
|
41 |
+
with open(fname, "w") as fh:
|
42 |
+
nx.drawing.nx_agraph.write_dot(H, fh)
|
43 |
+
|
44 |
+
with open(fname) as fh:
|
45 |
+
Hin = nx.nx_agraph.read_dot(fh)
|
46 |
+
self.assert_equal(H, Hin)
|
47 |
+
|
48 |
+
def test_from_agraph_name(self):
|
49 |
+
G = nx.Graph(name="test")
|
50 |
+
A = nx.nx_agraph.to_agraph(G)
|
51 |
+
H = nx.nx_agraph.from_agraph(A)
|
52 |
+
assert G.name == "test"
|
53 |
+
|
54 |
+
@pytest.mark.parametrize(
|
55 |
+
"graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
|
56 |
+
)
|
57 |
+
def test_from_agraph_create_using(self, graph_class):
|
58 |
+
G = nx.path_graph(3)
|
59 |
+
A = nx.nx_agraph.to_agraph(G)
|
60 |
+
H = nx.nx_agraph.from_agraph(A, create_using=graph_class)
|
61 |
+
assert isinstance(H, graph_class)
|
62 |
+
|
63 |
+
def test_from_agraph_named_edges(self):
|
64 |
+
# Create an AGraph from an existing (non-multi) Graph
|
65 |
+
G = nx.Graph()
|
66 |
+
G.add_nodes_from([0, 1])
|
67 |
+
A = nx.nx_agraph.to_agraph(G)
|
68 |
+
# Add edge (+ name, given by key) to the AGraph
|
69 |
+
A.add_edge(0, 1, key="foo")
|
70 |
+
# Verify a.name roundtrips out to 'key' in from_agraph
|
71 |
+
H = nx.nx_agraph.from_agraph(A)
|
72 |
+
assert isinstance(H, nx.Graph)
|
73 |
+
assert ("0", "1", {"key": "foo"}) in H.edges(data=True)
|
74 |
+
|
75 |
+
def test_to_agraph_with_nodedata(self):
|
76 |
+
G = nx.Graph()
|
77 |
+
G.add_node(1, color="red")
|
78 |
+
A = nx.nx_agraph.to_agraph(G)
|
79 |
+
assert dict(A.nodes()[0].attr) == {"color": "red"}
|
80 |
+
|
81 |
+
@pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph))
|
82 |
+
def test_to_agraph_with_edgedata(self, graph_class):
|
83 |
+
G = graph_class()
|
84 |
+
G.add_nodes_from([0, 1])
|
85 |
+
G.add_edge(0, 1, color="yellow")
|
86 |
+
A = nx.nx_agraph.to_agraph(G)
|
87 |
+
assert dict(A.edges()[0].attr) == {"color": "yellow"}
|
88 |
+
|
89 |
+
def test_view_pygraphviz_path(self, tmp_path):
|
90 |
+
G = nx.complete_graph(3)
|
91 |
+
input_path = str(tmp_path / "graph.png")
|
92 |
+
out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False)
|
93 |
+
assert out_path == input_path
|
94 |
+
# Ensure file is not empty
|
95 |
+
with open(input_path, "rb") as fh:
|
96 |
+
data = fh.read()
|
97 |
+
assert len(data) > 0
|
98 |
+
|
99 |
+
def test_view_pygraphviz_file_suffix(self, tmp_path):
|
100 |
+
G = nx.complete_graph(3)
|
101 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False)
|
102 |
+
assert path[-6:] == "_1.png"
|
103 |
+
|
104 |
+
def test_view_pygraphviz(self):
|
105 |
+
G = nx.Graph() # "An empty graph cannot be drawn."
|
106 |
+
pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
|
107 |
+
G = nx.barbell_graph(4, 6)
|
108 |
+
nx.nx_agraph.view_pygraphviz(G, show=False)
|
109 |
+
|
110 |
+
def test_view_pygraphviz_edgelabel(self):
|
111 |
+
G = nx.Graph()
|
112 |
+
G.add_edge(1, 2, weight=7)
|
113 |
+
G.add_edge(2, 3, weight=8)
|
114 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False)
|
115 |
+
for edge in A.edges():
|
116 |
+
assert edge.attr["weight"] in ("7", "8")
|
117 |
+
|
118 |
+
def test_view_pygraphviz_callable_edgelabel(self):
|
119 |
+
G = nx.complete_graph(3)
|
120 |
+
|
121 |
+
def foo_label(data):
|
122 |
+
return "foo"
|
123 |
+
|
124 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False)
|
125 |
+
for edge in A.edges():
|
126 |
+
assert edge.attr["label"] == "foo"
|
127 |
+
|
128 |
+
def test_view_pygraphviz_multigraph_edgelabels(self):
|
129 |
+
G = nx.MultiGraph()
|
130 |
+
G.add_edge(0, 1, key=0, name="left_fork")
|
131 |
+
G.add_edge(0, 1, key=1, name="right_fork")
|
132 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False)
|
133 |
+
edges = A.edges()
|
134 |
+
assert len(edges) == 2
|
135 |
+
for edge in edges:
|
136 |
+
assert edge.attr["label"].strip() in ("left_fork", "right_fork")
|
137 |
+
|
138 |
+
def test_graph_with_reserved_keywords(self):
|
139 |
+
# test attribute/keyword clash case for #1582
|
140 |
+
# node: n
|
141 |
+
# edges: u,v
|
142 |
+
G = nx.Graph()
|
143 |
+
G = self.build_graph(G)
|
144 |
+
G.nodes["E"]["n"] = "keyword"
|
145 |
+
G.edges[("A", "B")]["u"] = "keyword"
|
146 |
+
G.edges[("A", "B")]["v"] = "keyword"
|
147 |
+
A = nx.nx_agraph.to_agraph(G)
|
148 |
+
|
149 |
+
def test_view_pygraphviz_no_added_attrs_to_input(self):
|
150 |
+
G = nx.complete_graph(2)
|
151 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
|
152 |
+
assert G.graph == {}
|
153 |
+
|
154 |
+
@pytest.mark.xfail(reason="known bug in clean_attrs")
|
155 |
+
def test_view_pygraphviz_leaves_input_graph_unmodified(self):
|
156 |
+
G = nx.complete_graph(2)
|
157 |
+
# Add entries to graph dict that to_agraph handles specially
|
158 |
+
G.graph["node"] = {"width": "0.80"}
|
159 |
+
G.graph["edge"] = {"fontsize": "14"}
|
160 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
|
161 |
+
assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}}
|
162 |
+
|
163 |
+
def test_graph_with_AGraph_attrs(self):
|
164 |
+
G = nx.complete_graph(2)
|
165 |
+
# Add entries to graph dict that to_agraph handles specially
|
166 |
+
G.graph["node"] = {"width": "0.80"}
|
167 |
+
G.graph["edge"] = {"fontsize": "14"}
|
168 |
+
path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
|
169 |
+
# Ensure user-specified values are not lost
|
170 |
+
assert dict(A.node_attr)["width"] == "0.80"
|
171 |
+
assert dict(A.edge_attr)["fontsize"] == "14"
|
172 |
+
|
173 |
+
def test_round_trip_empty_graph(self):
|
174 |
+
G = nx.Graph()
|
175 |
+
A = nx.nx_agraph.to_agraph(G)
|
176 |
+
H = nx.nx_agraph.from_agraph(A)
|
177 |
+
# assert graphs_equal(G, H)
|
178 |
+
AA = nx.nx_agraph.to_agraph(H)
|
179 |
+
HH = nx.nx_agraph.from_agraph(AA)
|
180 |
+
assert graphs_equal(H, HH)
|
181 |
+
G.graph["graph"] = {}
|
182 |
+
G.graph["node"] = {}
|
183 |
+
G.graph["edge"] = {}
|
184 |
+
assert graphs_equal(G, HH)
|
185 |
+
|
186 |
+
@pytest.mark.xfail(reason="integer->string node conversion in round trip")
|
187 |
+
def test_round_trip_integer_nodes(self):
|
188 |
+
G = nx.complete_graph(3)
|
189 |
+
A = nx.nx_agraph.to_agraph(G)
|
190 |
+
H = nx.nx_agraph.from_agraph(A)
|
191 |
+
assert graphs_equal(G, H)
|
192 |
+
|
193 |
+
def test_graphviz_alias(self):
|
194 |
+
G = self.build_graph(nx.Graph())
|
195 |
+
pos_graphviz = nx.nx_agraph.graphviz_layout(G)
|
196 |
+
pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G)
|
197 |
+
assert pos_graphviz == pos_pygraphviz
|
198 |
+
|
199 |
+
@pytest.mark.parametrize("root", range(5))
|
200 |
+
def test_pygraphviz_layout_root(self, root):
|
201 |
+
# NOTE: test depends on layout prog being deterministic
|
202 |
+
G = nx.complete_graph(5)
|
203 |
+
A = nx.nx_agraph.to_agraph(G)
|
204 |
+
# Get layout with root arg is not None
|
205 |
+
pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root)
|
206 |
+
# Equivalent layout directly on AGraph
|
207 |
+
A.layout(args=f"-Groot={root}", prog="circo")
|
208 |
+
# Parse AGraph layout
|
209 |
+
a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(","))
|
210 |
+
assert pygv_layout[1] == a1_pos
|
211 |
+
|
212 |
+
def test_2d_layout(self):
|
213 |
+
G = nx.Graph()
|
214 |
+
G = self.build_graph(G)
|
215 |
+
G.graph["dimen"] = 2
|
216 |
+
pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
|
217 |
+
pos = list(pos.values())
|
218 |
+
assert len(pos) == 5
|
219 |
+
assert len(pos[0]) == 2
|
220 |
+
|
221 |
+
def test_3d_layout(self):
|
222 |
+
G = nx.Graph()
|
223 |
+
G = self.build_graph(G)
|
224 |
+
G.graph["dimen"] = 3
|
225 |
+
pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
|
226 |
+
pos = list(pos.values())
|
227 |
+
assert len(pos) == 5
|
228 |
+
assert len(pos[0]) == 3
|
229 |
+
|
230 |
+
def test_no_warnings_raised(self):
|
231 |
+
# Test that no warnings are raised when Networkx graph
|
232 |
+
# is converted to Pygraphviz graph and 'pos'
|
233 |
+
# attribute is given
|
234 |
+
G = nx.Graph()
|
235 |
+
G.add_node(0, pos=(0, 0))
|
236 |
+
G.add_node(1, pos=(1, 1))
|
237 |
+
A = nx.nx_agraph.to_agraph(G)
|
238 |
+
with warnings.catch_warnings(record=True) as record:
|
239 |
+
A.layout()
|
240 |
+
assert len(record) == 0
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
def test_tikz_attributes():
|
7 |
+
G = nx.path_graph(4, create_using=nx.DiGraph)
|
8 |
+
pos = {n: (n, n) for n in G}
|
9 |
+
|
10 |
+
G.add_edge(0, 0)
|
11 |
+
G.edges[(0, 0)]["label"] = "Loop"
|
12 |
+
G.edges[(0, 0)]["label_options"] = "midway"
|
13 |
+
|
14 |
+
G.nodes[0]["style"] = "blue"
|
15 |
+
G.nodes[1]["style"] = "line width=3,draw"
|
16 |
+
G.nodes[2]["style"] = "circle,draw,blue!50"
|
17 |
+
G.nodes[3]["label"] = "Stop"
|
18 |
+
G.edges[(0, 1)]["label"] = "1st Step"
|
19 |
+
G.edges[(0, 1)]["label_options"] = "near end"
|
20 |
+
G.edges[(2, 3)]["label"] = "3rd Step"
|
21 |
+
G.edges[(2, 3)]["label_options"] = "near start"
|
22 |
+
G.edges[(2, 3)]["style"] = "bend left,green"
|
23 |
+
G.edges[(1, 2)]["label"] = "2nd"
|
24 |
+
G.edges[(1, 2)]["label_options"] = "pos=0.5"
|
25 |
+
G.edges[(1, 2)]["style"] = ">->,bend right,line width=3,green!90"
|
26 |
+
|
27 |
+
output_tex = nx.to_latex(
|
28 |
+
G,
|
29 |
+
pos=pos,
|
30 |
+
as_document=False,
|
31 |
+
tikz_options="[scale=3]",
|
32 |
+
node_options="style",
|
33 |
+
edge_options="style",
|
34 |
+
node_label="label",
|
35 |
+
edge_label="label",
|
36 |
+
edge_label_options="label_options",
|
37 |
+
)
|
38 |
+
expected_tex = r"""\begin{figure}
|
39 |
+
\begin{tikzpicture}[scale=3]
|
40 |
+
\draw
|
41 |
+
(0, 0) node[blue] (0){0}
|
42 |
+
(1, 1) node[line width=3,draw] (1){1}
|
43 |
+
(2, 2) node[circle,draw,blue!50] (2){2}
|
44 |
+
(3, 3) node (3){Stop};
|
45 |
+
\begin{scope}[->]
|
46 |
+
\draw (0) to node[near end] {1st Step} (1);
|
47 |
+
\draw[loop,] (0) to node[midway] {Loop} (0);
|
48 |
+
\draw[>->,bend right,line width=3,green!90] (1) to node[pos=0.5] {2nd} (2);
|
49 |
+
\draw[bend left,green] (2) to node[near start] {3rd Step} (3);
|
50 |
+
\end{scope}
|
51 |
+
\end{tikzpicture}
|
52 |
+
\end{figure}"""
|
53 |
+
|
54 |
+
assert output_tex == expected_tex
|
55 |
+
# print(output_tex)
|
56 |
+
# # Pretty way to assert that A.to_document() == expected_tex
|
57 |
+
# content_same = True
|
58 |
+
# for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
|
59 |
+
# if aa != bb:
|
60 |
+
# content_same = False
|
61 |
+
# print(f"-{aa}|\n+{bb}|")
|
62 |
+
# assert content_same
|
63 |
+
|
64 |
+
|
65 |
+
def test_basic_multiple_graphs():
|
66 |
+
H1 = nx.path_graph(4)
|
67 |
+
H2 = nx.complete_graph(4)
|
68 |
+
H3 = nx.path_graph(8)
|
69 |
+
H4 = nx.complete_graph(8)
|
70 |
+
captions = [
|
71 |
+
"Path on 4 nodes",
|
72 |
+
"Complete graph on 4 nodes",
|
73 |
+
"Path on 8 nodes",
|
74 |
+
"Complete graph on 8 nodes",
|
75 |
+
]
|
76 |
+
labels = ["fig2a", "fig2b", "fig2c", "fig2d"]
|
77 |
+
latex_code = nx.to_latex(
|
78 |
+
[H1, H2, H3, H4],
|
79 |
+
n_rows=2,
|
80 |
+
sub_captions=captions,
|
81 |
+
sub_labels=labels,
|
82 |
+
)
|
83 |
+
# print(latex_code)
|
84 |
+
assert "begin{document}" in latex_code
|
85 |
+
assert "begin{figure}" in latex_code
|
86 |
+
assert latex_code.count("begin{subfigure}") == 4
|
87 |
+
assert latex_code.count("tikzpicture") == 8
|
88 |
+
assert latex_code.count("[-]") == 4
|
89 |
+
|
90 |
+
|
91 |
+
def test_basic_tikz():
|
92 |
+
expected_tex = r"""\documentclass{report}
|
93 |
+
\usepackage{tikz}
|
94 |
+
\usepackage{subcaption}
|
95 |
+
|
96 |
+
\begin{document}
|
97 |
+
\begin{figure}
|
98 |
+
\begin{subfigure}{0.5\textwidth}
|
99 |
+
\begin{tikzpicture}[scale=2]
|
100 |
+
\draw[gray!90]
|
101 |
+
(0.749, 0.702) node[red!90] (0){0}
|
102 |
+
(1.0, -0.014) node[red!90] (1){1}
|
103 |
+
(-0.777, -0.705) node (2){2}
|
104 |
+
(-0.984, 0.042) node (3){3}
|
105 |
+
(-0.028, 0.375) node[cyan!90] (4){4}
|
106 |
+
(-0.412, 0.888) node (5){5}
|
107 |
+
(0.448, -0.856) node (6){6}
|
108 |
+
(0.003, -0.431) node[cyan!90] (7){7};
|
109 |
+
\begin{scope}[->,gray!90]
|
110 |
+
\draw (0) to (4);
|
111 |
+
\draw (0) to (5);
|
112 |
+
\draw (0) to (6);
|
113 |
+
\draw (0) to (7);
|
114 |
+
\draw (1) to (4);
|
115 |
+
\draw (1) to (5);
|
116 |
+
\draw (1) to (6);
|
117 |
+
\draw (1) to (7);
|
118 |
+
\draw (2) to (4);
|
119 |
+
\draw (2) to (5);
|
120 |
+
\draw (2) to (6);
|
121 |
+
\draw (2) to (7);
|
122 |
+
\draw (3) to (4);
|
123 |
+
\draw (3) to (5);
|
124 |
+
\draw (3) to (6);
|
125 |
+
\draw (3) to (7);
|
126 |
+
\end{scope}
|
127 |
+
\end{tikzpicture}
|
128 |
+
\caption{My tikz number 1 of 2}\label{tikz_1_2}
|
129 |
+
\end{subfigure}
|
130 |
+
\begin{subfigure}{0.5\textwidth}
|
131 |
+
\begin{tikzpicture}[scale=2]
|
132 |
+
\draw[gray!90]
|
133 |
+
(0.749, 0.702) node[green!90] (0){0}
|
134 |
+
(1.0, -0.014) node[green!90] (1){1}
|
135 |
+
(-0.777, -0.705) node (2){2}
|
136 |
+
(-0.984, 0.042) node (3){3}
|
137 |
+
(-0.028, 0.375) node[purple!90] (4){4}
|
138 |
+
(-0.412, 0.888) node (5){5}
|
139 |
+
(0.448, -0.856) node (6){6}
|
140 |
+
(0.003, -0.431) node[purple!90] (7){7};
|
141 |
+
\begin{scope}[->,gray!90]
|
142 |
+
\draw (0) to (4);
|
143 |
+
\draw (0) to (5);
|
144 |
+
\draw (0) to (6);
|
145 |
+
\draw (0) to (7);
|
146 |
+
\draw (1) to (4);
|
147 |
+
\draw (1) to (5);
|
148 |
+
\draw (1) to (6);
|
149 |
+
\draw (1) to (7);
|
150 |
+
\draw (2) to (4);
|
151 |
+
\draw (2) to (5);
|
152 |
+
\draw (2) to (6);
|
153 |
+
\draw (2) to (7);
|
154 |
+
\draw (3) to (4);
|
155 |
+
\draw (3) to (5);
|
156 |
+
\draw (3) to (6);
|
157 |
+
\draw (3) to (7);
|
158 |
+
\end{scope}
|
159 |
+
\end{tikzpicture}
|
160 |
+
\caption{My tikz number 2 of 2}\label{tikz_2_2}
|
161 |
+
\end{subfigure}
|
162 |
+
\caption{A graph generated with python and latex.}
|
163 |
+
\end{figure}
|
164 |
+
\end{document}"""
|
165 |
+
|
166 |
+
edges = [
|
167 |
+
(0, 4),
|
168 |
+
(0, 5),
|
169 |
+
(0, 6),
|
170 |
+
(0, 7),
|
171 |
+
(1, 4),
|
172 |
+
(1, 5),
|
173 |
+
(1, 6),
|
174 |
+
(1, 7),
|
175 |
+
(2, 4),
|
176 |
+
(2, 5),
|
177 |
+
(2, 6),
|
178 |
+
(2, 7),
|
179 |
+
(3, 4),
|
180 |
+
(3, 5),
|
181 |
+
(3, 6),
|
182 |
+
(3, 7),
|
183 |
+
]
|
184 |
+
G = nx.DiGraph()
|
185 |
+
G.add_nodes_from(range(8))
|
186 |
+
G.add_edges_from(edges)
|
187 |
+
pos = {
|
188 |
+
0: (0.7490296171687696, 0.702353520257394),
|
189 |
+
1: (1.0, -0.014221357723796535),
|
190 |
+
2: (-0.7765783344161441, -0.7054170966808919),
|
191 |
+
3: (-0.9842690223417624, 0.04177547602465483),
|
192 |
+
4: (-0.02768523817180917, 0.3745724439551441),
|
193 |
+
5: (-0.41154855146767433, 0.8880106515525136),
|
194 |
+
6: (0.44780153389148264, -0.8561492709269164),
|
195 |
+
7: (0.0032499953371383505, -0.43092436645809945),
|
196 |
+
}
|
197 |
+
|
198 |
+
rc_node_color = {0: "red!90", 1: "red!90", 4: "cyan!90", 7: "cyan!90"}
|
199 |
+
gp_node_color = {0: "green!90", 1: "green!90", 4: "purple!90", 7: "purple!90"}
|
200 |
+
|
201 |
+
H = G.copy()
|
202 |
+
nx.set_node_attributes(G, rc_node_color, "color")
|
203 |
+
nx.set_node_attributes(H, gp_node_color, "color")
|
204 |
+
|
205 |
+
sub_captions = ["My tikz number 1 of 2", "My tikz number 2 of 2"]
|
206 |
+
sub_labels = ["tikz_1_2", "tikz_2_2"]
|
207 |
+
|
208 |
+
output_tex = nx.to_latex(
|
209 |
+
[G, H],
|
210 |
+
[pos, pos],
|
211 |
+
tikz_options="[scale=2]",
|
212 |
+
default_node_options="gray!90",
|
213 |
+
default_edge_options="gray!90",
|
214 |
+
node_options="color",
|
215 |
+
sub_captions=sub_captions,
|
216 |
+
sub_labels=sub_labels,
|
217 |
+
caption="A graph generated with python and latex.",
|
218 |
+
n_rows=2,
|
219 |
+
as_document=True,
|
220 |
+
)
|
221 |
+
|
222 |
+
assert output_tex == expected_tex
|
223 |
+
# print(output_tex)
|
224 |
+
# # Pretty way to assert that A.to_document() == expected_tex
|
225 |
+
# content_same = True
|
226 |
+
# for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
|
227 |
+
# if aa != bb:
|
228 |
+
# content_same = False
|
229 |
+
# print(f"-{aa}|\n+{bb}|")
|
230 |
+
# assert content_same
|
231 |
+
|
232 |
+
|
233 |
+
def test_exception_pos_single_graph(to_latex=nx.to_latex):
|
234 |
+
# smoke test that pos can be a string
|
235 |
+
G = nx.path_graph(4)
|
236 |
+
to_latex(G, pos="pos")
|
237 |
+
|
238 |
+
# must include all nodes
|
239 |
+
pos = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
|
240 |
+
with pytest.raises(nx.NetworkXError):
|
241 |
+
to_latex(G, pos)
|
242 |
+
|
243 |
+
# must have 2 values
|
244 |
+
pos[3] = (1, 2, 3)
|
245 |
+
with pytest.raises(nx.NetworkXError):
|
246 |
+
to_latex(G, pos)
|
247 |
+
pos[3] = 2
|
248 |
+
with pytest.raises(nx.NetworkXError):
|
249 |
+
to_latex(G, pos)
|
250 |
+
|
251 |
+
# check that passes with 2 values
|
252 |
+
pos[3] = (3, 2)
|
253 |
+
to_latex(G, pos)
|
254 |
+
|
255 |
+
|
256 |
+
def test_exception_multiple_graphs(to_latex=nx.to_latex):
|
257 |
+
G = nx.path_graph(3)
|
258 |
+
pos_bad = {0: (1, 2), 1: (0, 1)}
|
259 |
+
pos_OK = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
|
260 |
+
fourG = [G, G, G, G]
|
261 |
+
fourpos = [pos_OK, pos_OK, pos_OK, pos_OK]
|
262 |
+
|
263 |
+
# input single dict to use for all graphs
|
264 |
+
to_latex(fourG, pos_OK)
|
265 |
+
with pytest.raises(nx.NetworkXError):
|
266 |
+
to_latex(fourG, pos_bad)
|
267 |
+
|
268 |
+
# input list of dicts to use for all graphs
|
269 |
+
to_latex(fourG, fourpos)
|
270 |
+
with pytest.raises(nx.NetworkXError):
|
271 |
+
to_latex(fourG, [pos_bad, pos_bad, pos_bad, pos_bad])
|
272 |
+
|
273 |
+
# every pos dict must include all nodes
|
274 |
+
with pytest.raises(nx.NetworkXError):
|
275 |
+
to_latex(fourG, [pos_OK, pos_OK, pos_bad, pos_OK])
|
276 |
+
|
277 |
+
# test sub_captions and sub_labels (len must match Gbunch)
|
278 |
+
with pytest.raises(nx.NetworkXError):
|
279 |
+
to_latex(fourG, fourpos, sub_captions=["hi", "hi"])
|
280 |
+
|
281 |
+
with pytest.raises(nx.NetworkXError):
|
282 |
+
to_latex(fourG, fourpos, sub_labels=["hi", "hi"])
|
283 |
+
|
284 |
+
# all pass
|
285 |
+
to_latex(fourG, fourpos, sub_captions=["hi"] * 4, sub_labels=["lbl"] * 4)
|
286 |
+
|
287 |
+
|
288 |
+
def test_exception_multigraph():
|
289 |
+
G = nx.path_graph(4, create_using=nx.MultiGraph)
|
290 |
+
G.add_edge(1, 2)
|
291 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
292 |
+
nx.to_latex(G)
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py
ADDED
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for layout functions."""
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
np = pytest.importorskip("numpy")
|
7 |
+
pytest.importorskip("scipy")
|
8 |
+
|
9 |
+
|
10 |
+
class TestLayout:
|
11 |
+
@classmethod
|
12 |
+
def setup_class(cls):
|
13 |
+
cls.Gi = nx.grid_2d_graph(5, 5)
|
14 |
+
cls.Gs = nx.Graph()
|
15 |
+
nx.add_path(cls.Gs, "abcdef")
|
16 |
+
cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse
|
17 |
+
|
18 |
+
def test_spring_fixed_without_pos(self):
|
19 |
+
G = nx.path_graph(4)
|
20 |
+
pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
|
21 |
+
pos = {0: (1, 1), 2: (0, 0)}
|
22 |
+
pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
|
23 |
+
nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError
|
24 |
+
|
25 |
+
def test_spring_init_pos(self):
|
26 |
+
# Tests GH #2448
|
27 |
+
import math
|
28 |
+
|
29 |
+
G = nx.Graph()
|
30 |
+
G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)])
|
31 |
+
|
32 |
+
init_pos = {0: (0.0, 0.0)}
|
33 |
+
fixed_pos = [0]
|
34 |
+
pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos)
|
35 |
+
has_nan = any(math.isnan(c) for coords in pos.values() for c in coords)
|
36 |
+
assert not has_nan, "values should not be nan"
|
37 |
+
|
38 |
+
def test_smoke_empty_graph(self):
|
39 |
+
G = []
|
40 |
+
nx.random_layout(G)
|
41 |
+
nx.circular_layout(G)
|
42 |
+
nx.planar_layout(G)
|
43 |
+
nx.spring_layout(G)
|
44 |
+
nx.fruchterman_reingold_layout(G)
|
45 |
+
nx.spectral_layout(G)
|
46 |
+
nx.shell_layout(G)
|
47 |
+
nx.bipartite_layout(G, G)
|
48 |
+
nx.spiral_layout(G)
|
49 |
+
nx.multipartite_layout(G)
|
50 |
+
nx.kamada_kawai_layout(G)
|
51 |
+
|
52 |
+
def test_smoke_int(self):
|
53 |
+
G = self.Gi
|
54 |
+
nx.random_layout(G)
|
55 |
+
nx.circular_layout(G)
|
56 |
+
nx.planar_layout(G)
|
57 |
+
nx.spring_layout(G)
|
58 |
+
nx.fruchterman_reingold_layout(G)
|
59 |
+
nx.fruchterman_reingold_layout(self.bigG)
|
60 |
+
nx.spectral_layout(G)
|
61 |
+
nx.spectral_layout(G.to_directed())
|
62 |
+
nx.spectral_layout(self.bigG)
|
63 |
+
nx.spectral_layout(self.bigG.to_directed())
|
64 |
+
nx.shell_layout(G)
|
65 |
+
nx.spiral_layout(G)
|
66 |
+
nx.kamada_kawai_layout(G)
|
67 |
+
nx.kamada_kawai_layout(G, dim=1)
|
68 |
+
nx.kamada_kawai_layout(G, dim=3)
|
69 |
+
nx.arf_layout(G)
|
70 |
+
|
71 |
+
def test_smoke_string(self):
|
72 |
+
G = self.Gs
|
73 |
+
nx.random_layout(G)
|
74 |
+
nx.circular_layout(G)
|
75 |
+
nx.planar_layout(G)
|
76 |
+
nx.spring_layout(G)
|
77 |
+
nx.fruchterman_reingold_layout(G)
|
78 |
+
nx.spectral_layout(G)
|
79 |
+
nx.shell_layout(G)
|
80 |
+
nx.spiral_layout(G)
|
81 |
+
nx.kamada_kawai_layout(G)
|
82 |
+
nx.kamada_kawai_layout(G, dim=1)
|
83 |
+
nx.kamada_kawai_layout(G, dim=3)
|
84 |
+
nx.arf_layout(G)
|
85 |
+
|
86 |
+
def check_scale_and_center(self, pos, scale, center):
|
87 |
+
center = np.array(center)
|
88 |
+
low = center - scale
|
89 |
+
hi = center + scale
|
90 |
+
vpos = np.array(list(pos.values()))
|
91 |
+
length = vpos.max(0) - vpos.min(0)
|
92 |
+
assert (length <= 2 * scale).all()
|
93 |
+
assert (vpos >= low).all()
|
94 |
+
assert (vpos <= hi).all()
|
95 |
+
|
96 |
+
def test_scale_and_center_arg(self):
|
97 |
+
sc = self.check_scale_and_center
|
98 |
+
c = (4, 5)
|
99 |
+
G = nx.complete_graph(9)
|
100 |
+
G.add_node(9)
|
101 |
+
sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
|
102 |
+
# rest can have 2*scale length: [-scale, scale]
|
103 |
+
sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
|
104 |
+
sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
|
105 |
+
sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
|
106 |
+
sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
|
107 |
+
sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
|
108 |
+
sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
|
109 |
+
|
110 |
+
c = (2, 3, 5)
|
111 |
+
sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c)
|
112 |
+
|
113 |
+
def test_planar_layout_non_planar_input(self):
|
114 |
+
G = nx.complete_graph(9)
|
115 |
+
pytest.raises(nx.NetworkXException, nx.planar_layout, G)
|
116 |
+
|
117 |
+
def test_smoke_planar_layout_embedding_input(self):
|
118 |
+
embedding = nx.PlanarEmbedding()
|
119 |
+
embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]})
|
120 |
+
nx.planar_layout(embedding)
|
121 |
+
|
122 |
+
def test_default_scale_and_center(self):
|
123 |
+
sc = self.check_scale_and_center
|
124 |
+
c = (0, 0)
|
125 |
+
G = nx.complete_graph(9)
|
126 |
+
G.add_node(9)
|
127 |
+
sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
|
128 |
+
sc(nx.spring_layout(G), scale=1, center=c)
|
129 |
+
sc(nx.spectral_layout(G), scale=1, center=c)
|
130 |
+
sc(nx.circular_layout(G), scale=1, center=c)
|
131 |
+
sc(nx.shell_layout(G), scale=1, center=c)
|
132 |
+
sc(nx.spiral_layout(G), scale=1, center=c)
|
133 |
+
sc(nx.kamada_kawai_layout(G), scale=1, center=c)
|
134 |
+
|
135 |
+
c = (0, 0, 0)
|
136 |
+
sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c)
|
137 |
+
|
138 |
+
def test_circular_planar_and_shell_dim_error(self):
|
139 |
+
G = nx.path_graph(4)
|
140 |
+
pytest.raises(ValueError, nx.circular_layout, G, dim=1)
|
141 |
+
pytest.raises(ValueError, nx.shell_layout, G, dim=1)
|
142 |
+
pytest.raises(ValueError, nx.shell_layout, G, dim=3)
|
143 |
+
pytest.raises(ValueError, nx.planar_layout, G, dim=1)
|
144 |
+
pytest.raises(ValueError, nx.planar_layout, G, dim=3)
|
145 |
+
|
146 |
+
def test_adjacency_interface_numpy(self):
|
147 |
+
A = nx.to_numpy_array(self.Gs)
|
148 |
+
pos = nx.drawing.layout._fruchterman_reingold(A)
|
149 |
+
assert pos.shape == (6, 2)
|
150 |
+
pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
|
151 |
+
assert pos.shape == (6, 3)
|
152 |
+
pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
|
153 |
+
assert pos.shape == (6, 2)
|
154 |
+
|
155 |
+
def test_adjacency_interface_scipy(self):
|
156 |
+
A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
|
157 |
+
pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
|
158 |
+
assert pos.shape == (6, 2)
|
159 |
+
pos = nx.drawing.layout._sparse_spectral(A)
|
160 |
+
assert pos.shape == (6, 2)
|
161 |
+
pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
|
162 |
+
assert pos.shape == (6, 3)
|
163 |
+
|
164 |
+
def test_single_nodes(self):
|
165 |
+
G = nx.path_graph(1)
|
166 |
+
vpos = nx.shell_layout(G)
|
167 |
+
assert not vpos[0].any()
|
168 |
+
G = nx.path_graph(4)
|
169 |
+
vpos = nx.shell_layout(G, [[0], [1, 2], [3]])
|
170 |
+
assert not vpos[0].any()
|
171 |
+
assert vpos[3].any() # ensure node 3 not at origin (#3188)
|
172 |
+
assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
|
173 |
+
vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0)
|
174 |
+
assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
|
175 |
+
|
176 |
+
def test_smoke_initial_pos_fruchterman_reingold(self):
|
177 |
+
pos = nx.circular_layout(self.Gi)
|
178 |
+
npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
|
179 |
+
|
180 |
+
def test_smoke_initial_pos_arf(self):
|
181 |
+
pos = nx.circular_layout(self.Gi)
|
182 |
+
npos = nx.arf_layout(self.Gi, pos=pos)
|
183 |
+
|
184 |
+
def test_fixed_node_fruchterman_reingold(self):
|
185 |
+
# Dense version (numpy based)
|
186 |
+
pos = nx.circular_layout(self.Gi)
|
187 |
+
npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)])
|
188 |
+
assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)])
|
189 |
+
# Sparse version (scipy based)
|
190 |
+
pos = nx.circular_layout(self.bigG)
|
191 |
+
npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)])
|
192 |
+
for axis in range(2):
|
193 |
+
assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7)
|
194 |
+
|
195 |
+
def test_center_parameter(self):
|
196 |
+
G = nx.path_graph(1)
|
197 |
+
nx.random_layout(G, center=(1, 1))
|
198 |
+
vpos = nx.circular_layout(G, center=(1, 1))
|
199 |
+
assert tuple(vpos[0]) == (1, 1)
|
200 |
+
vpos = nx.planar_layout(G, center=(1, 1))
|
201 |
+
assert tuple(vpos[0]) == (1, 1)
|
202 |
+
vpos = nx.spring_layout(G, center=(1, 1))
|
203 |
+
assert tuple(vpos[0]) == (1, 1)
|
204 |
+
vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
|
205 |
+
assert tuple(vpos[0]) == (1, 1)
|
206 |
+
vpos = nx.spectral_layout(G, center=(1, 1))
|
207 |
+
assert tuple(vpos[0]) == (1, 1)
|
208 |
+
vpos = nx.shell_layout(G, center=(1, 1))
|
209 |
+
assert tuple(vpos[0]) == (1, 1)
|
210 |
+
vpos = nx.spiral_layout(G, center=(1, 1))
|
211 |
+
assert tuple(vpos[0]) == (1, 1)
|
212 |
+
|
213 |
+
def test_center_wrong_dimensions(self):
|
214 |
+
G = nx.path_graph(1)
|
215 |
+
assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout)
|
216 |
+
pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1))
|
217 |
+
pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1))
|
218 |
+
pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1))
|
219 |
+
pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1))
|
220 |
+
pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1))
|
221 |
+
pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1))
|
222 |
+
pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1))
|
223 |
+
pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
|
224 |
+
pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1))
|
225 |
+
pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1))
|
226 |
+
|
227 |
+
def test_empty_graph(self):
|
228 |
+
G = nx.empty_graph()
|
229 |
+
vpos = nx.random_layout(G, center=(1, 1))
|
230 |
+
assert vpos == {}
|
231 |
+
vpos = nx.circular_layout(G, center=(1, 1))
|
232 |
+
assert vpos == {}
|
233 |
+
vpos = nx.planar_layout(G, center=(1, 1))
|
234 |
+
assert vpos == {}
|
235 |
+
vpos = nx.bipartite_layout(G, G)
|
236 |
+
assert vpos == {}
|
237 |
+
vpos = nx.spring_layout(G, center=(1, 1))
|
238 |
+
assert vpos == {}
|
239 |
+
vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
|
240 |
+
assert vpos == {}
|
241 |
+
vpos = nx.spectral_layout(G, center=(1, 1))
|
242 |
+
assert vpos == {}
|
243 |
+
vpos = nx.shell_layout(G, center=(1, 1))
|
244 |
+
assert vpos == {}
|
245 |
+
vpos = nx.spiral_layout(G, center=(1, 1))
|
246 |
+
assert vpos == {}
|
247 |
+
vpos = nx.multipartite_layout(G, center=(1, 1))
|
248 |
+
assert vpos == {}
|
249 |
+
vpos = nx.kamada_kawai_layout(G, center=(1, 1))
|
250 |
+
assert vpos == {}
|
251 |
+
vpos = nx.arf_layout(G)
|
252 |
+
assert vpos == {}
|
253 |
+
|
254 |
+
def test_bipartite_layout(self):
|
255 |
+
G = nx.complete_bipartite_graph(3, 5)
|
256 |
+
top, bottom = nx.bipartite.sets(G)
|
257 |
+
|
258 |
+
vpos = nx.bipartite_layout(G, top)
|
259 |
+
assert len(vpos) == len(G)
|
260 |
+
|
261 |
+
top_x = vpos[list(top)[0]][0]
|
262 |
+
bottom_x = vpos[list(bottom)[0]][0]
|
263 |
+
for node in top:
|
264 |
+
assert vpos[node][0] == top_x
|
265 |
+
for node in bottom:
|
266 |
+
assert vpos[node][0] == bottom_x
|
267 |
+
|
268 |
+
vpos = nx.bipartite_layout(
|
269 |
+
G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1
|
270 |
+
)
|
271 |
+
assert len(vpos) == len(G)
|
272 |
+
|
273 |
+
top_y = vpos[list(top)[0]][1]
|
274 |
+
bottom_y = vpos[list(bottom)[0]][1]
|
275 |
+
for node in top:
|
276 |
+
assert vpos[node][1] == top_y
|
277 |
+
for node in bottom:
|
278 |
+
assert vpos[node][1] == bottom_y
|
279 |
+
|
280 |
+
pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo")
|
281 |
+
|
282 |
+
def test_multipartite_layout(self):
|
283 |
+
sizes = (0, 5, 7, 2, 8)
|
284 |
+
G = nx.complete_multipartite_graph(*sizes)
|
285 |
+
|
286 |
+
vpos = nx.multipartite_layout(G)
|
287 |
+
assert len(vpos) == len(G)
|
288 |
+
|
289 |
+
start = 0
|
290 |
+
for n in sizes:
|
291 |
+
end = start + n
|
292 |
+
assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end))
|
293 |
+
start += n
|
294 |
+
|
295 |
+
vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2))
|
296 |
+
assert len(vpos) == len(G)
|
297 |
+
|
298 |
+
start = 0
|
299 |
+
for n in sizes:
|
300 |
+
end = start + n
|
301 |
+
assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end))
|
302 |
+
start += n
|
303 |
+
|
304 |
+
pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
|
305 |
+
|
306 |
+
def test_kamada_kawai_costfn_1d(self):
|
307 |
+
costfn = nx.drawing.layout._kamada_kawai_costfn
|
308 |
+
|
309 |
+
pos = np.array([4.0, 7.0])
|
310 |
+
invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]])
|
311 |
+
|
312 |
+
cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1)
|
313 |
+
|
314 |
+
assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7)
|
315 |
+
assert grad[0] == pytest.approx((-0.5), abs=1e-7)
|
316 |
+
assert grad[1] == pytest.approx(0.5, abs=1e-7)
|
317 |
+
|
318 |
+
def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim):
|
319 |
+
costfn = nx.drawing.layout._kamada_kawai_costfn
|
320 |
+
|
321 |
+
cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim)
|
322 |
+
|
323 |
+
expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2)
|
324 |
+
for i in range(pos.shape[0]):
|
325 |
+
for j in range(i + 1, pos.shape[0]):
|
326 |
+
diff = np.linalg.norm(pos[i] - pos[j])
|
327 |
+
expected_cost += (diff * invdist[i][j] - 1.0) ** 2
|
328 |
+
|
329 |
+
assert cost == pytest.approx(expected_cost, abs=1e-7)
|
330 |
+
|
331 |
+
dx = 1e-4
|
332 |
+
for nd in range(pos.shape[0]):
|
333 |
+
for dm in range(pos.shape[1]):
|
334 |
+
idx = nd * pos.shape[1] + dm
|
335 |
+
ps = pos.flatten()
|
336 |
+
|
337 |
+
ps[idx] += dx
|
338 |
+
cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
|
339 |
+
|
340 |
+
ps[idx] -= 2 * dx
|
341 |
+
cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
|
342 |
+
|
343 |
+
assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5)
|
344 |
+
|
345 |
+
def test_kamada_kawai_costfn(self):
|
346 |
+
invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]])
|
347 |
+
meanwt = 0.3
|
348 |
+
|
349 |
+
# 2d
|
350 |
+
pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]])
|
351 |
+
|
352 |
+
self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2)
|
353 |
+
|
354 |
+
# 3d
|
355 |
+
pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]])
|
356 |
+
|
357 |
+
self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3)
|
358 |
+
|
359 |
+
def test_spiral_layout(self):
|
360 |
+
G = self.Gs
|
361 |
+
|
362 |
+
# a lower value of resolution should result in a more compact layout
|
363 |
+
# intuitively, the total distance from the start and end nodes
|
364 |
+
# via each node in between (transiting through each) will be less,
|
365 |
+
# assuming rescaling does not occur on the computed node positions
|
366 |
+
pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values()))
|
367 |
+
pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values()))
|
368 |
+
distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1)
|
369 |
+
distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1)
|
370 |
+
assert sum(distances) > sum(distances_tighter)
|
371 |
+
|
372 |
+
# return near-equidistant points after the first value if set to true
|
373 |
+
pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values()))
|
374 |
+
distances_equidistant = np.linalg.norm(
|
375 |
+
pos_equidistant[:-1] - pos_equidistant[1:], axis=1
|
376 |
+
)
|
377 |
+
assert np.allclose(
|
378 |
+
distances_equidistant[1:], distances_equidistant[-1], atol=0.01
|
379 |
+
)
|
380 |
+
|
381 |
+
def test_spiral_layout_equidistant(self):
|
382 |
+
G = nx.path_graph(10)
|
383 |
+
pos = nx.spiral_layout(G, equidistant=True)
|
384 |
+
# Extract individual node positions as an array
|
385 |
+
p = np.array(list(pos.values()))
|
386 |
+
# Elementwise-distance between node positions
|
387 |
+
dist = np.linalg.norm(p[1:] - p[:-1], axis=1)
|
388 |
+
assert np.allclose(np.diff(dist), 0, atol=1e-3)
|
389 |
+
|
390 |
+
def test_rescale_layout_dict(self):
|
391 |
+
G = nx.empty_graph()
|
392 |
+
vpos = nx.random_layout(G, center=(1, 1))
|
393 |
+
assert nx.rescale_layout_dict(vpos) == {}
|
394 |
+
|
395 |
+
G = nx.empty_graph(2)
|
396 |
+
vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)}
|
397 |
+
s_vpos = nx.rescale_layout_dict(vpos)
|
398 |
+
assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6
|
399 |
+
|
400 |
+
G = nx.empty_graph(3)
|
401 |
+
vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)}
|
402 |
+
s_vpos = nx.rescale_layout_dict(vpos)
|
403 |
+
|
404 |
+
expectation = {
|
405 |
+
0: np.array((-1, -1)),
|
406 |
+
1: np.array((1, 1)),
|
407 |
+
2: np.array((0, 0)),
|
408 |
+
}
|
409 |
+
for k, v in expectation.items():
|
410 |
+
assert (s_vpos[k] == v).all()
|
411 |
+
s_vpos = nx.rescale_layout_dict(vpos, scale=2)
|
412 |
+
expectation = {
|
413 |
+
0: np.array((-2, -2)),
|
414 |
+
1: np.array((2, 2)),
|
415 |
+
2: np.array((0, 0)),
|
416 |
+
}
|
417 |
+
for k, v in expectation.items():
|
418 |
+
assert (s_vpos[k] == v).all()
|
419 |
+
|
420 |
+
def test_arf_layout_partial_input_test(self):
|
421 |
+
"""
|
422 |
+
Checks whether partial pos input still returns a proper position.
|
423 |
+
"""
|
424 |
+
G = self.Gs
|
425 |
+
node = nx.utils.arbitrary_element(G)
|
426 |
+
pos = nx.circular_layout(G)
|
427 |
+
del pos[node]
|
428 |
+
pos = nx.arf_layout(G, pos=pos)
|
429 |
+
assert len(pos) == len(G)
|
430 |
+
|
431 |
+
def test_arf_layout_negative_a_check(self):
|
432 |
+
"""
|
433 |
+
Checks input parameters correctly raises errors. For example, `a` should be larger than 1
|
434 |
+
"""
|
435 |
+
G = self.Gs
|
436 |
+
pytest.raises(ValueError, nx.arf_layout, G=G, a=-1)
|
437 |
+
|
438 |
+
|
439 |
+
def test_multipartite_layout_nonnumeric_partition_labels():
|
440 |
+
"""See gh-5123."""
|
441 |
+
G = nx.Graph()
|
442 |
+
G.add_node(0, subset="s0")
|
443 |
+
G.add_node(1, subset="s0")
|
444 |
+
G.add_node(2, subset="s1")
|
445 |
+
G.add_node(3, subset="s1")
|
446 |
+
G.add_edges_from([(0, 2), (0, 3), (1, 2)])
|
447 |
+
pos = nx.multipartite_layout(G)
|
448 |
+
assert len(pos) == len(G)
|
449 |
+
|
450 |
+
|
451 |
+
def test_multipartite_layout_layer_order():
|
452 |
+
"""Return the layers in sorted order if the layers of the multipartite
|
453 |
+
graph are sortable. See gh-5691"""
|
454 |
+
G = nx.Graph()
|
455 |
+
node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4)))
|
456 |
+
for node, layer in node_group.items():
|
457 |
+
G.add_node(node, subset=layer)
|
458 |
+
|
459 |
+
# Horizontal alignment, therefore y-coord determines layers
|
460 |
+
pos = nx.multipartite_layout(G, align="horizontal")
|
461 |
+
|
462 |
+
layers = nx.utils.groups(node_group)
|
463 |
+
pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers)
|
464 |
+
for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()):
|
465 |
+
assert n1 == n2 and (p1 == p2).all()
|
466 |
+
|
467 |
+
# Nodes "a" and "d" are in the same layer
|
468 |
+
assert pos["a"][-1] == pos["d"][-1]
|
469 |
+
# positions should be sorted according to layer
|
470 |
+
assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1]
|
471 |
+
|
472 |
+
# Make sure that multipartite_layout still works when layers are not sortable
|
473 |
+
G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints
|
474 |
+
pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise
|
475 |
+
assert pos_nosort.keys() == pos.keys()
|
476 |
+
|
477 |
+
|
478 |
+
def _num_nodes_per_bfs_layer(pos):
|
479 |
+
"""Helper function to extract the number of nodes in each layer of bfs_layout"""
|
480 |
+
x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension
|
481 |
+
_, layer_count = np.unique(x, return_counts=True)
|
482 |
+
return layer_count
|
483 |
+
|
484 |
+
|
485 |
+
@pytest.mark.parametrize("n", range(2, 7))
|
486 |
+
def test_bfs_layout_complete_graph(n):
|
487 |
+
"""The complete graph should result in two layers: the starting node and
|
488 |
+
a second layer containing all neighbors."""
|
489 |
+
G = nx.complete_graph(n)
|
490 |
+
pos = nx.bfs_layout(G, start=0)
|
491 |
+
assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1])
|
492 |
+
|
493 |
+
|
494 |
+
def test_bfs_layout_barbell():
|
495 |
+
G = nx.barbell_graph(5, 3)
|
496 |
+
# Start in one of the "bells"
|
497 |
+
pos = nx.bfs_layout(G, start=0)
|
498 |
+
# start, bell-1, [1] * len(bar)+1, bell-1
|
499 |
+
expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4]
|
500 |
+
assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
|
501 |
+
# Start in the other "bell" - expect same layer pattern
|
502 |
+
pos = nx.bfs_layout(G, start=12)
|
503 |
+
assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
|
504 |
+
# Starting in the center of the bar, expect layers to be symmetric
|
505 |
+
pos = nx.bfs_layout(G, start=6)
|
506 |
+
# Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells}
|
507 |
+
expected_nodes_per_layer = [1, 2, 2, 8]
|
508 |
+
assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
|
509 |
+
|
510 |
+
|
511 |
+
def test_bfs_layout_disconnected():
|
512 |
+
G = nx.complete_graph(5)
|
513 |
+
G.add_edges_from([(10, 11), (11, 12)])
|
514 |
+
with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"):
|
515 |
+
nx.bfs_layout(G, start=0)
|
venv/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for pydot drawing functions."""
|
2 |
+
from io import StringIO
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
from networkx.utils import graphs_equal
|
8 |
+
|
9 |
+
pydot = pytest.importorskip("pydot")
|
10 |
+
|
11 |
+
|
12 |
+
class TestPydot:
|
13 |
+
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
|
14 |
+
@pytest.mark.parametrize("prog", ("neato", "dot"))
|
15 |
+
def test_pydot(self, G, prog, tmp_path):
|
16 |
+
"""
|
17 |
+
Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
|
18 |
+
passed basename of an external GraphViz command (e.g., `dot`, `neato`).
|
19 |
+
"""
|
20 |
+
|
21 |
+
# Set the name of this graph to... "G". Failing to do so will
|
22 |
+
# subsequently trip an assertion expecting this name.
|
23 |
+
G.graph["name"] = "G"
|
24 |
+
|
25 |
+
# Add arbitrary nodes and edges to the passed empty graph.
|
26 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
|
27 |
+
G.add_node("E")
|
28 |
+
|
29 |
+
# Validate layout of this graph with the passed GraphViz command.
|
30 |
+
graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
|
31 |
+
assert isinstance(graph_layout, dict)
|
32 |
+
|
33 |
+
# Convert this graph into a "pydot.Dot" instance.
|
34 |
+
P = nx.nx_pydot.to_pydot(G)
|
35 |
+
|
36 |
+
# Convert this "pydot.Dot" instance back into a graph of the same type.
|
37 |
+
G2 = G.__class__(nx.nx_pydot.from_pydot(P))
|
38 |
+
|
39 |
+
# Validate the original and resulting graphs to be the same.
|
40 |
+
assert graphs_equal(G, G2)
|
41 |
+
|
42 |
+
fname = tmp_path / "out.dot"
|
43 |
+
|
44 |
+
# Serialize this "pydot.Dot" instance to a temporary file in dot format
|
45 |
+
P.write_raw(fname)
|
46 |
+
|
47 |
+
# Deserialize a list of new "pydot.Dot" instances back from this file.
|
48 |
+
Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")
|
49 |
+
|
50 |
+
# Validate this file to contain only one graph.
|
51 |
+
assert len(Pin_list) == 1
|
52 |
+
|
53 |
+
# The single "pydot.Dot" instance deserialized from this file.
|
54 |
+
Pin = Pin_list[0]
|
55 |
+
|
56 |
+
# Sorted list of all nodes in the original "pydot.Dot" instance.
|
57 |
+
n1 = sorted(p.get_name() for p in P.get_node_list())
|
58 |
+
|
59 |
+
# Sorted list of all nodes in the deserialized "pydot.Dot" instance.
|
60 |
+
n2 = sorted(p.get_name() for p in Pin.get_node_list())
|
61 |
+
|
62 |
+
# Validate these instances to contain the same nodes.
|
63 |
+
assert n1 == n2
|
64 |
+
|
65 |
+
# Sorted list of all edges in the original "pydot.Dot" instance.
|
66 |
+
e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list())
|
67 |
+
|
68 |
+
# Sorted list of all edges in the original "pydot.Dot" instance.
|
69 |
+
e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list())
|
70 |
+
|
71 |
+
# Validate these instances to contain the same edges.
|
72 |
+
assert e1 == e2
|
73 |
+
|
74 |
+
# Deserialize a new graph of the same type back from this file.
|
75 |
+
Hin = nx.nx_pydot.read_dot(fname)
|
76 |
+
Hin = G.__class__(Hin)
|
77 |
+
|
78 |
+
# Validate the original and resulting graphs to be the same.
|
79 |
+
assert graphs_equal(G, Hin)
|
80 |
+
|
81 |
+
def test_read_write(self):
|
82 |
+
G = nx.MultiGraph()
|
83 |
+
G.graph["name"] = "G"
|
84 |
+
G.add_edge("1", "2", key="0") # read assumes strings
|
85 |
+
fh = StringIO()
|
86 |
+
nx.nx_pydot.write_dot(G, fh)
|
87 |
+
fh.seek(0)
|
88 |
+
H = nx.nx_pydot.read_dot(fh)
|
89 |
+
assert graphs_equal(G, H)
|
90 |
+
|
91 |
+
|
92 |
+
def test_pydot_issue_258():
|
93 |
+
G = nx.Graph([("Example:A", 1)])
|
94 |
+
with pytest.raises(ValueError):
|
95 |
+
nx.nx_pydot.to_pydot(G)
|
96 |
+
with pytest.raises(ValueError):
|
97 |
+
nx.nx_pydot.pydot_layout(G)
|
98 |
+
|
99 |
+
G = nx.Graph()
|
100 |
+
G.add_node("1.2", style="filled", fillcolor="red:yellow")
|
101 |
+
with pytest.raises(ValueError):
|
102 |
+
nx.nx_pydot.to_pydot(G)
|
103 |
+
G.remove_node("1.2")
|
104 |
+
G.add_node("1.2", style="filled", fillcolor='"red:yellow"')
|
105 |
+
assert (
|
106 |
+
G.nodes.data() == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes.data()
|
107 |
+
)
|
108 |
+
|
109 |
+
G = nx.DiGraph()
|
110 |
+
G.add_edge("1", "2", foo="bar:1")
|
111 |
+
with pytest.raises(ValueError):
|
112 |
+
nx.nx_pydot.to_pydot(G)
|
113 |
+
G = nx.DiGraph()
|
114 |
+
G.add_edge("1", "2", foo='"bar:1"')
|
115 |
+
assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"]
|
116 |
+
|
117 |
+
G = nx.MultiGraph()
|
118 |
+
G.add_edge("1", "2", foo="b:1")
|
119 |
+
G.add_edge("1", "2", bar="foo:foo")
|
120 |
+
with pytest.raises(ValueError):
|
121 |
+
nx.nx_pydot.to_pydot(G)
|
122 |
+
G = nx.MultiGraph()
|
123 |
+
G.add_edge("1", "2", foo='"b:1"')
|
124 |
+
G.add_edge("1", "2", bar='"foo:foo"')
|
125 |
+
# Keys as integers aren't preserved in the conversion. They are read as strings.
|
126 |
+
assert [attr for _, _, attr in G.edges.data()] == [
|
127 |
+
attr
|
128 |
+
for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
|
129 |
+
]
|
130 |
+
|
131 |
+
G = nx.Graph()
|
132 |
+
G.add_edge("1", "2")
|
133 |
+
G["1"]["2"]["f:oo"] = "bar"
|
134 |
+
with pytest.raises(ValueError):
|
135 |
+
nx.nx_pydot.to_pydot(G)
|
136 |
+
G = nx.Graph()
|
137 |
+
G.add_edge("1", "2")
|
138 |
+
G["1"]["2"]['"f:oo"'] = "bar"
|
139 |
+
assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"]
|
140 |
+
|
141 |
+
G = nx.Graph([('"Example:A"', 1)])
|
142 |
+
layout = nx.nx_pydot.pydot_layout(G)
|
143 |
+
assert isinstance(layout, dict)
|
144 |
+
|
145 |
+
|
146 |
+
@pytest.mark.parametrize(
|
147 |
+
"graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
|
148 |
+
)
|
149 |
+
def test_hashable_pydot(graph_type):
|
150 |
+
# gh-5790
|
151 |
+
G = graph_type()
|
152 |
+
G.add_edge("5", frozenset([1]), t='"Example:A"', l=False)
|
153 |
+
G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"]))
|
154 |
+
G.add_edge("node", (3, 3), w="string")
|
155 |
+
|
156 |
+
assert [
|
157 |
+
{"t": '"Example:A"', "l": "False"},
|
158 |
+
{"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"},
|
159 |
+
{"w": "string"},
|
160 |
+
] == [
|
161 |
+
attr
|
162 |
+
for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
|
163 |
+
]
|
164 |
+
|
165 |
+
assert {str(i) for i in G.nodes()} == set(
|
166 |
+
nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes
|
167 |
+
)
|
168 |
+
|
169 |
+
|
170 |
+
def test_pydot_numerical_name():
|
171 |
+
G = nx.Graph()
|
172 |
+
G.add_edges_from([("A", "B"), (0, 1)])
|
173 |
+
graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
|
174 |
+
assert isinstance(graph_layout, dict)
|
175 |
+
assert "0" not in graph_layout
|
176 |
+
assert 0 in graph_layout
|
177 |
+
assert "1" not in graph_layout
|
178 |
+
assert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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Unit tests for matplotlib drawing functions."""
|
2 |
+
import itertools
|
3 |
+
import os
|
4 |
+
import warnings
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
mpl = pytest.importorskip("matplotlib")
|
9 |
+
np = pytest.importorskip("numpy")
|
10 |
+
mpl.use("PS")
|
11 |
+
plt = pytest.importorskip("matplotlib.pyplot")
|
12 |
+
plt.rcParams["text.usetex"] = False
|
13 |
+
|
14 |
+
|
15 |
+
import networkx as nx
|
16 |
+
|
17 |
+
barbell = nx.barbell_graph(4, 6)
|
18 |
+
|
19 |
+
|
20 |
+
def test_draw():
|
21 |
+
try:
|
22 |
+
functions = [
|
23 |
+
nx.draw_circular,
|
24 |
+
nx.draw_kamada_kawai,
|
25 |
+
nx.draw_planar,
|
26 |
+
nx.draw_random,
|
27 |
+
nx.draw_spectral,
|
28 |
+
nx.draw_spring,
|
29 |
+
nx.draw_shell,
|
30 |
+
]
|
31 |
+
options = [{"node_color": "black", "node_size": 100, "width": 3}]
|
32 |
+
for function, option in itertools.product(functions, options):
|
33 |
+
function(barbell, **option)
|
34 |
+
plt.savefig("test.ps")
|
35 |
+
except ModuleNotFoundError: # draw_kamada_kawai requires scipy
|
36 |
+
pass
|
37 |
+
finally:
|
38 |
+
try:
|
39 |
+
os.unlink("test.ps")
|
40 |
+
except OSError:
|
41 |
+
pass
|
42 |
+
|
43 |
+
|
44 |
+
def test_draw_shell_nlist():
|
45 |
+
try:
|
46 |
+
nlist = [list(range(4)), list(range(4, 10)), list(range(10, 14))]
|
47 |
+
nx.draw_shell(barbell, nlist=nlist)
|
48 |
+
plt.savefig("test.ps")
|
49 |
+
finally:
|
50 |
+
try:
|
51 |
+
os.unlink("test.ps")
|
52 |
+
except OSError:
|
53 |
+
pass
|
54 |
+
|
55 |
+
|
56 |
+
def test_edge_colormap():
|
57 |
+
colors = range(barbell.number_of_edges())
|
58 |
+
nx.draw_spring(
|
59 |
+
barbell, edge_color=colors, width=4, edge_cmap=plt.cm.Blues, with_labels=True
|
60 |
+
)
|
61 |
+
# plt.show()
|
62 |
+
|
63 |
+
|
64 |
+
def test_arrows():
|
65 |
+
nx.draw_spring(barbell.to_directed())
|
66 |
+
# plt.show()
|
67 |
+
|
68 |
+
|
69 |
+
@pytest.mark.parametrize(
|
70 |
+
("edge_color", "expected"),
|
71 |
+
(
|
72 |
+
(None, "black"), # Default
|
73 |
+
("r", "red"), # Non-default color string
|
74 |
+
(["r"], "red"), # Single non-default color in a list
|
75 |
+
((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
|
76 |
+
([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
|
77 |
+
((0, 1, 0, 1), "lime"), # single color as rgba tuple
|
78 |
+
([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
|
79 |
+
("#0000ff", "blue"), # single color hex code
|
80 |
+
(["#0000ff"], "blue"), # hex code in list
|
81 |
+
),
|
82 |
+
)
|
83 |
+
@pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
|
84 |
+
def test_single_edge_color_undirected(edge_color, expected, edgelist):
|
85 |
+
"""Tests ways of specifying all edges have a single color for edges
|
86 |
+
drawn with a LineCollection"""
|
87 |
+
|
88 |
+
G = nx.path_graph(3)
|
89 |
+
drawn_edges = nx.draw_networkx_edges(
|
90 |
+
G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
|
91 |
+
)
|
92 |
+
assert mpl.colors.same_color(drawn_edges.get_color(), expected)
|
93 |
+
|
94 |
+
|
95 |
+
@pytest.mark.parametrize(
|
96 |
+
("edge_color", "expected"),
|
97 |
+
(
|
98 |
+
(None, "black"), # Default
|
99 |
+
("r", "red"), # Non-default color string
|
100 |
+
(["r"], "red"), # Single non-default color in a list
|
101 |
+
((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
|
102 |
+
([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
|
103 |
+
((0, 1, 0, 1), "lime"), # single color as rgba tuple
|
104 |
+
([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
|
105 |
+
("#0000ff", "blue"), # single color hex code
|
106 |
+
(["#0000ff"], "blue"), # hex code in list
|
107 |
+
),
|
108 |
+
)
|
109 |
+
@pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
|
110 |
+
def test_single_edge_color_directed(edge_color, expected, edgelist):
|
111 |
+
"""Tests ways of specifying all edges have a single color for edges drawn
|
112 |
+
with FancyArrowPatches"""
|
113 |
+
|
114 |
+
G = nx.path_graph(3, create_using=nx.DiGraph)
|
115 |
+
drawn_edges = nx.draw_networkx_edges(
|
116 |
+
G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
|
117 |
+
)
|
118 |
+
for fap in drawn_edges:
|
119 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), expected)
|
120 |
+
|
121 |
+
|
122 |
+
def test_edge_color_tuple_interpretation():
|
123 |
+
"""If edge_color is a sequence with the same length as edgelist, then each
|
124 |
+
value in edge_color is mapped onto each edge via colormap."""
|
125 |
+
G = nx.path_graph(6, create_using=nx.DiGraph)
|
126 |
+
pos = {n: (n, n) for n in range(len(G))}
|
127 |
+
|
128 |
+
# num edges != 3 or 4 --> edge_color interpreted as rgb(a)
|
129 |
+
for ec in ((0, 0, 1), (0, 0, 1, 1)):
|
130 |
+
# More than 4 edges
|
131 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=ec)
|
132 |
+
for fap in drawn_edges:
|
133 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), ec)
|
134 |
+
# Fewer than 3 edges
|
135 |
+
drawn_edges = nx.draw_networkx_edges(
|
136 |
+
G, pos, edgelist=[(0, 1), (1, 2)], edge_color=ec
|
137 |
+
)
|
138 |
+
for fap in drawn_edges:
|
139 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), ec)
|
140 |
+
|
141 |
+
# num edges == 3, len(edge_color) == 4: interpreted as rgba
|
142 |
+
drawn_edges = nx.draw_networkx_edges(
|
143 |
+
G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1, 1)
|
144 |
+
)
|
145 |
+
for fap in drawn_edges:
|
146 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
|
147 |
+
|
148 |
+
# num edges == 4, len(edge_color) == 3: interpreted as rgb
|
149 |
+
drawn_edges = nx.draw_networkx_edges(
|
150 |
+
G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1)
|
151 |
+
)
|
152 |
+
for fap in drawn_edges:
|
153 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
|
154 |
+
|
155 |
+
# num edges == len(edge_color) == 3: interpreted with cmap, *not* as rgb
|
156 |
+
drawn_edges = nx.draw_networkx_edges(
|
157 |
+
G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1)
|
158 |
+
)
|
159 |
+
assert mpl.colors.same_color(
|
160 |
+
drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
|
161 |
+
)
|
162 |
+
for fap in drawn_edges:
|
163 |
+
assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
|
164 |
+
|
165 |
+
# num edges == len(edge_color) == 4: interpreted with cmap, *not* as rgba
|
166 |
+
drawn_edges = nx.draw_networkx_edges(
|
167 |
+
G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1, 1)
|
168 |
+
)
|
169 |
+
assert mpl.colors.same_color(
|
170 |
+
drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
|
171 |
+
)
|
172 |
+
assert mpl.colors.same_color(
|
173 |
+
drawn_edges[2].get_edgecolor(), drawn_edges[3].get_edgecolor()
|
174 |
+
)
|
175 |
+
for fap in drawn_edges:
|
176 |
+
assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
|
177 |
+
|
178 |
+
|
179 |
+
def test_fewer_edge_colors_than_num_edges_directed():
|
180 |
+
"""Test that the edge colors are cycled when there are fewer specified
|
181 |
+
colors than edges."""
|
182 |
+
G = barbell.to_directed()
|
183 |
+
pos = nx.random_layout(barbell)
|
184 |
+
edgecolors = ("r", "g", "b")
|
185 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
|
186 |
+
for fap, expected in zip(drawn_edges, itertools.cycle(edgecolors)):
|
187 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), expected)
|
188 |
+
|
189 |
+
|
190 |
+
def test_more_edge_colors_than_num_edges_directed():
|
191 |
+
"""Test that extra edge colors are ignored when there are more specified
|
192 |
+
colors than edges."""
|
193 |
+
G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges
|
194 |
+
pos = nx.random_layout(barbell)
|
195 |
+
edgecolors = ("r", "g", "b", "c") # 4 edge colors
|
196 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
|
197 |
+
for fap, expected in zip(drawn_edges, edgecolors[:-1]):
|
198 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), expected)
|
199 |
+
|
200 |
+
|
201 |
+
def test_edge_color_string_with_global_alpha_undirected():
|
202 |
+
edge_collection = nx.draw_networkx_edges(
|
203 |
+
barbell,
|
204 |
+
pos=nx.random_layout(barbell),
|
205 |
+
edgelist=[(0, 1), (1, 2)],
|
206 |
+
edge_color="purple",
|
207 |
+
alpha=0.2,
|
208 |
+
)
|
209 |
+
ec = edge_collection.get_color().squeeze() # as rgba tuple
|
210 |
+
assert len(edge_collection.get_paths()) == 2
|
211 |
+
assert mpl.colors.same_color(ec[:-1], "purple")
|
212 |
+
assert ec[-1] == 0.2
|
213 |
+
|
214 |
+
|
215 |
+
def test_edge_color_string_with_global_alpha_directed():
|
216 |
+
drawn_edges = nx.draw_networkx_edges(
|
217 |
+
barbell.to_directed(),
|
218 |
+
pos=nx.random_layout(barbell),
|
219 |
+
edgelist=[(0, 1), (1, 2)],
|
220 |
+
edge_color="purple",
|
221 |
+
alpha=0.2,
|
222 |
+
)
|
223 |
+
assert len(drawn_edges) == 2
|
224 |
+
for fap in drawn_edges:
|
225 |
+
ec = fap.get_edgecolor() # As rgba tuple
|
226 |
+
assert mpl.colors.same_color(ec[:-1], "purple")
|
227 |
+
assert ec[-1] == 0.2
|
228 |
+
|
229 |
+
|
230 |
+
@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
|
231 |
+
def test_edge_width_default_value(graph_type):
|
232 |
+
"""Test the default linewidth for edges drawn either via LineCollection or
|
233 |
+
FancyArrowPatches."""
|
234 |
+
G = nx.path_graph(2, create_using=graph_type)
|
235 |
+
pos = {n: (n, n) for n in range(len(G))}
|
236 |
+
drawn_edges = nx.draw_networkx_edges(G, pos)
|
237 |
+
if isinstance(drawn_edges, list): # directed case: list of FancyArrowPatch
|
238 |
+
drawn_edges = drawn_edges[0]
|
239 |
+
assert drawn_edges.get_linewidth() == 1
|
240 |
+
|
241 |
+
|
242 |
+
@pytest.mark.parametrize(
|
243 |
+
("edgewidth", "expected"),
|
244 |
+
(
|
245 |
+
(3, 3), # single-value, non-default
|
246 |
+
([3], 3), # Single value as a list
|
247 |
+
),
|
248 |
+
)
|
249 |
+
def test_edge_width_single_value_undirected(edgewidth, expected):
|
250 |
+
G = nx.path_graph(4)
|
251 |
+
pos = {n: (n, n) for n in range(len(G))}
|
252 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
|
253 |
+
assert len(drawn_edges.get_paths()) == 3
|
254 |
+
assert drawn_edges.get_linewidth() == expected
|
255 |
+
|
256 |
+
|
257 |
+
@pytest.mark.parametrize(
|
258 |
+
("edgewidth", "expected"),
|
259 |
+
(
|
260 |
+
(3, 3), # single-value, non-default
|
261 |
+
([3], 3), # Single value as a list
|
262 |
+
),
|
263 |
+
)
|
264 |
+
def test_edge_width_single_value_directed(edgewidth, expected):
|
265 |
+
G = nx.path_graph(4, create_using=nx.DiGraph)
|
266 |
+
pos = {n: (n, n) for n in range(len(G))}
|
267 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
|
268 |
+
assert len(drawn_edges) == 3
|
269 |
+
for fap in drawn_edges:
|
270 |
+
assert fap.get_linewidth() == expected
|
271 |
+
|
272 |
+
|
273 |
+
@pytest.mark.parametrize(
|
274 |
+
"edgelist",
|
275 |
+
(
|
276 |
+
[(0, 1), (1, 2), (2, 3)], # one width specification per edge
|
277 |
+
None, # fewer widths than edges - widths cycle
|
278 |
+
[(0, 1), (1, 2)], # More widths than edges - unused widths ignored
|
279 |
+
),
|
280 |
+
)
|
281 |
+
def test_edge_width_sequence(edgelist):
|
282 |
+
G = barbell.to_directed()
|
283 |
+
pos = nx.random_layout(G)
|
284 |
+
widths = (0.5, 2.0, 12.0)
|
285 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, width=widths)
|
286 |
+
for fap, expected_width in zip(drawn_edges, itertools.cycle(widths)):
|
287 |
+
assert fap.get_linewidth() == expected_width
|
288 |
+
|
289 |
+
|
290 |
+
def test_edge_color_with_edge_vmin_vmax():
|
291 |
+
"""Test that edge_vmin and edge_vmax properly set the dynamic range of the
|
292 |
+
color map when num edges == len(edge_colors)."""
|
293 |
+
G = nx.path_graph(3, create_using=nx.DiGraph)
|
294 |
+
pos = nx.random_layout(G)
|
295 |
+
# Extract colors from the original (unscaled) colormap
|
296 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=[0, 1.0])
|
297 |
+
orig_colors = [e.get_edgecolor() for e in drawn_edges]
|
298 |
+
# Colors from scaled colormap
|
299 |
+
drawn_edges = nx.draw_networkx_edges(
|
300 |
+
G, pos, edge_color=[0.2, 0.8], edge_vmin=0.2, edge_vmax=0.8
|
301 |
+
)
|
302 |
+
scaled_colors = [e.get_edgecolor() for e in drawn_edges]
|
303 |
+
assert mpl.colors.same_color(orig_colors, scaled_colors)
|
304 |
+
|
305 |
+
|
306 |
+
def test_directed_edges_linestyle_default():
|
307 |
+
"""Test default linestyle for edges drawn with FancyArrowPatches."""
|
308 |
+
G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
|
309 |
+
pos = {n: (n, n) for n in range(len(G))}
|
310 |
+
|
311 |
+
# edge with default style
|
312 |
+
drawn_edges = nx.draw_networkx_edges(G, pos)
|
313 |
+
assert len(drawn_edges) == 3
|
314 |
+
for fap in drawn_edges:
|
315 |
+
assert fap.get_linestyle() == "solid"
|
316 |
+
|
317 |
+
|
318 |
+
@pytest.mark.parametrize(
|
319 |
+
"style",
|
320 |
+
(
|
321 |
+
"dashed", # edge with string style
|
322 |
+
"--", # edge with simplified string style
|
323 |
+
(1, (1, 1)), # edge with (offset, onoffseq) style
|
324 |
+
),
|
325 |
+
)
|
326 |
+
def test_directed_edges_linestyle_single_value(style):
|
327 |
+
"""Tests support for specifying linestyles with a single value to be applied to
|
328 |
+
all edges in ``draw_networkx_edges`` for FancyArrowPatch outputs
|
329 |
+
(e.g. directed edges)."""
|
330 |
+
|
331 |
+
G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
|
332 |
+
pos = {n: (n, n) for n in range(len(G))}
|
333 |
+
|
334 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, style=style)
|
335 |
+
assert len(drawn_edges) == 3
|
336 |
+
for fap in drawn_edges:
|
337 |
+
assert fap.get_linestyle() == style
|
338 |
+
|
339 |
+
|
340 |
+
@pytest.mark.parametrize(
|
341 |
+
"style_seq",
|
342 |
+
(
|
343 |
+
["dashed"], # edge with string style in list
|
344 |
+
["--"], # edge with simplified string style in list
|
345 |
+
[(1, (1, 1))], # edge with (offset, onoffseq) style in list
|
346 |
+
["--", "-", ":"], # edges with styles for each edge
|
347 |
+
["--", "-"], # edges with fewer styles than edges (styles cycle)
|
348 |
+
["--", "-", ":", "-."], # edges with more styles than edges (extra unused)
|
349 |
+
),
|
350 |
+
)
|
351 |
+
def test_directed_edges_linestyle_sequence(style_seq):
|
352 |
+
"""Tests support for specifying linestyles with sequences in
|
353 |
+
``draw_networkx_edges`` for FancyArrowPatch outputs (e.g. directed edges)."""
|
354 |
+
|
355 |
+
G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
|
356 |
+
pos = {n: (n, n) for n in range(len(G))}
|
357 |
+
|
358 |
+
drawn_edges = nx.draw_networkx_edges(G, pos, style=style_seq)
|
359 |
+
assert len(drawn_edges) == 3
|
360 |
+
for fap, style in zip(drawn_edges, itertools.cycle(style_seq)):
|
361 |
+
assert fap.get_linestyle() == style
|
362 |
+
|
363 |
+
|
364 |
+
def test_labels_and_colors():
|
365 |
+
G = nx.cubical_graph()
|
366 |
+
pos = nx.spring_layout(G) # positions for all nodes
|
367 |
+
# nodes
|
368 |
+
nx.draw_networkx_nodes(
|
369 |
+
G, pos, nodelist=[0, 1, 2, 3], node_color="r", node_size=500, alpha=0.75
|
370 |
+
)
|
371 |
+
nx.draw_networkx_nodes(
|
372 |
+
G,
|
373 |
+
pos,
|
374 |
+
nodelist=[4, 5, 6, 7],
|
375 |
+
node_color="b",
|
376 |
+
node_size=500,
|
377 |
+
alpha=[0.25, 0.5, 0.75, 1.0],
|
378 |
+
)
|
379 |
+
# edges
|
380 |
+
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
|
381 |
+
nx.draw_networkx_edges(
|
382 |
+
G,
|
383 |
+
pos,
|
384 |
+
edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
|
385 |
+
width=8,
|
386 |
+
alpha=0.5,
|
387 |
+
edge_color="r",
|
388 |
+
)
|
389 |
+
nx.draw_networkx_edges(
|
390 |
+
G,
|
391 |
+
pos,
|
392 |
+
edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
|
393 |
+
width=8,
|
394 |
+
alpha=0.5,
|
395 |
+
edge_color="b",
|
396 |
+
)
|
397 |
+
nx.draw_networkx_edges(
|
398 |
+
G,
|
399 |
+
pos,
|
400 |
+
edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
|
401 |
+
arrows=True,
|
402 |
+
min_source_margin=0.5,
|
403 |
+
min_target_margin=0.75,
|
404 |
+
width=8,
|
405 |
+
edge_color="b",
|
406 |
+
)
|
407 |
+
# some math labels
|
408 |
+
labels = {}
|
409 |
+
labels[0] = r"$a$"
|
410 |
+
labels[1] = r"$b$"
|
411 |
+
labels[2] = r"$c$"
|
412 |
+
labels[3] = r"$d$"
|
413 |
+
labels[4] = r"$\alpha$"
|
414 |
+
labels[5] = r"$\beta$"
|
415 |
+
labels[6] = r"$\gamma$"
|
416 |
+
labels[7] = r"$\delta$"
|
417 |
+
nx.draw_networkx_labels(G, pos, labels, font_size=16)
|
418 |
+
nx.draw_networkx_edge_labels(G, pos, edge_labels=None, rotate=False)
|
419 |
+
nx.draw_networkx_edge_labels(G, pos, edge_labels={(4, 5): "4-5"})
|
420 |
+
# plt.show()
|
421 |
+
|
422 |
+
|
423 |
+
@pytest.mark.mpl_image_compare
|
424 |
+
def test_house_with_colors():
|
425 |
+
G = nx.house_graph()
|
426 |
+
# explicitly set positions
|
427 |
+
fig, ax = plt.subplots()
|
428 |
+
pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
|
429 |
+
|
430 |
+
# Plot nodes with different properties for the "wall" and "roof" nodes
|
431 |
+
nx.draw_networkx_nodes(
|
432 |
+
G,
|
433 |
+
pos,
|
434 |
+
node_size=3000,
|
435 |
+
nodelist=[0, 1, 2, 3],
|
436 |
+
node_color="tab:blue",
|
437 |
+
)
|
438 |
+
nx.draw_networkx_nodes(
|
439 |
+
G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
|
440 |
+
)
|
441 |
+
nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
|
442 |
+
# Customize axes
|
443 |
+
ax.margins(0.11)
|
444 |
+
plt.tight_layout()
|
445 |
+
plt.axis("off")
|
446 |
+
return fig
|
447 |
+
|
448 |
+
|
449 |
+
def test_axes():
|
450 |
+
fig, ax = plt.subplots()
|
451 |
+
nx.draw(barbell, ax=ax)
|
452 |
+
nx.draw_networkx_edge_labels(barbell, nx.circular_layout(barbell), ax=ax)
|
453 |
+
|
454 |
+
|
455 |
+
def test_empty_graph():
|
456 |
+
G = nx.Graph()
|
457 |
+
nx.draw(G)
|
458 |
+
|
459 |
+
|
460 |
+
def test_draw_empty_nodes_return_values():
|
461 |
+
# See Issue #3833
|
462 |
+
import matplotlib.collections # call as mpl.collections
|
463 |
+
|
464 |
+
G = nx.Graph([(1, 2), (2, 3)])
|
465 |
+
DG = nx.DiGraph([(1, 2), (2, 3)])
|
466 |
+
pos = nx.circular_layout(G)
|
467 |
+
assert isinstance(
|
468 |
+
nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection
|
469 |
+
)
|
470 |
+
assert isinstance(
|
471 |
+
nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection
|
472 |
+
)
|
473 |
+
|
474 |
+
# drawing empty edges used to return an empty LineCollection or empty list.
|
475 |
+
# Now it is always an empty list (because edges are now lists of FancyArrows)
|
476 |
+
assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=True) == []
|
477 |
+
assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=False) == []
|
478 |
+
assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=False) == []
|
479 |
+
assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=True) == []
|
480 |
+
|
481 |
+
|
482 |
+
def test_multigraph_edgelist_tuples():
|
483 |
+
# See Issue #3295
|
484 |
+
G = nx.path_graph(3, create_using=nx.MultiDiGraph)
|
485 |
+
nx.draw_networkx(G, edgelist=[(0, 1, 0)])
|
486 |
+
nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20, 0])
|
487 |
+
|
488 |
+
|
489 |
+
def test_alpha_iter():
|
490 |
+
pos = nx.random_layout(barbell)
|
491 |
+
fig = plt.figure()
|
492 |
+
# with fewer alpha elements than nodes
|
493 |
+
fig.add_subplot(131) # Each test in a new axis object
|
494 |
+
nx.draw_networkx_nodes(barbell, pos, alpha=[0.1, 0.2])
|
495 |
+
# with equal alpha elements and nodes
|
496 |
+
num_nodes = len(barbell.nodes)
|
497 |
+
alpha = [x / num_nodes for x in range(num_nodes)]
|
498 |
+
colors = range(num_nodes)
|
499 |
+
fig.add_subplot(132)
|
500 |
+
nx.draw_networkx_nodes(barbell, pos, node_color=colors, alpha=alpha)
|
501 |
+
# with more alpha elements than nodes
|
502 |
+
alpha.append(1)
|
503 |
+
fig.add_subplot(133)
|
504 |
+
nx.draw_networkx_nodes(barbell, pos, alpha=alpha)
|
505 |
+
|
506 |
+
|
507 |
+
def test_error_invalid_kwds():
|
508 |
+
with pytest.raises(ValueError, match="Received invalid argument"):
|
509 |
+
nx.draw(barbell, foo="bar")
|
510 |
+
|
511 |
+
|
512 |
+
def test_draw_networkx_arrowsize_incorrect_size():
|
513 |
+
G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 3)])
|
514 |
+
arrowsize = [1, 2, 3]
|
515 |
+
with pytest.raises(
|
516 |
+
ValueError, match="arrowsize should have the same length as edgelist"
|
517 |
+
):
|
518 |
+
nx.draw(G, arrowsize=arrowsize)
|
519 |
+
|
520 |
+
|
521 |
+
@pytest.mark.parametrize("arrowsize", (30, [10, 20, 30]))
|
522 |
+
def test_draw_edges_arrowsize(arrowsize):
|
523 |
+
G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
|
524 |
+
pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
|
525 |
+
edges = nx.draw_networkx_edges(G, pos=pos, arrowsize=arrowsize)
|
526 |
+
|
527 |
+
arrowsize = itertools.repeat(arrowsize) if isinstance(arrowsize, int) else arrowsize
|
528 |
+
|
529 |
+
for fap, expected in zip(edges, arrowsize):
|
530 |
+
assert isinstance(fap, mpl.patches.FancyArrowPatch)
|
531 |
+
assert fap.get_mutation_scale() == expected
|
532 |
+
|
533 |
+
|
534 |
+
def test_np_edgelist():
|
535 |
+
# see issue #4129
|
536 |
+
nx.draw_networkx(barbell, edgelist=np.array([(0, 2), (0, 3)]))
|
537 |
+
|
538 |
+
|
539 |
+
def test_draw_nodes_missing_node_from_position():
|
540 |
+
G = nx.path_graph(3)
|
541 |
+
pos = {0: (0, 0), 1: (1, 1)} # No position for node 2
|
542 |
+
with pytest.raises(nx.NetworkXError, match="has no position"):
|
543 |
+
nx.draw_networkx_nodes(G, pos)
|
544 |
+
|
545 |
+
|
546 |
+
# NOTE: parametrizing on marker to test both branches of internal
|
547 |
+
# nx.draw_networkx_edges.to_marker_edge function
|
548 |
+
@pytest.mark.parametrize("node_shape", ("o", "s"))
|
549 |
+
def test_draw_edges_min_source_target_margins(node_shape):
|
550 |
+
"""Test that there is a wider gap between the node and the start of an
|
551 |
+
incident edge when min_source_margin is specified.
|
552 |
+
|
553 |
+
This test checks that the use of min_{source/target}_margin kwargs result
|
554 |
+
in shorter (more padding) between the edges and source and target nodes.
|
555 |
+
As a crude visual example, let 's' and 't' represent source and target
|
556 |
+
nodes, respectively:
|
557 |
+
|
558 |
+
Default:
|
559 |
+
s-----------------------------t
|
560 |
+
|
561 |
+
With margins:
|
562 |
+
s ----------------------- t
|
563 |
+
|
564 |
+
"""
|
565 |
+
# Create a single axis object to get consistent pixel coords across
|
566 |
+
# multiple draws
|
567 |
+
fig, ax = plt.subplots()
|
568 |
+
G = nx.DiGraph([(0, 1)])
|
569 |
+
pos = {0: (0, 0), 1: (1, 0)} # horizontal layout
|
570 |
+
# Get leftmost and rightmost points of the FancyArrowPatch object
|
571 |
+
# representing the edge between nodes 0 and 1 (in pixel coordinates)
|
572 |
+
default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)[0]
|
573 |
+
default_extent = default_patch.get_extents().corners()[::2, 0]
|
574 |
+
# Now, do the same but with "padding" for the source and target via the
|
575 |
+
# min_{source/target}_margin kwargs
|
576 |
+
padded_patch = nx.draw_networkx_edges(
|
577 |
+
G,
|
578 |
+
pos,
|
579 |
+
ax=ax,
|
580 |
+
node_shape=node_shape,
|
581 |
+
min_source_margin=100,
|
582 |
+
min_target_margin=100,
|
583 |
+
)[0]
|
584 |
+
padded_extent = padded_patch.get_extents().corners()[::2, 0]
|
585 |
+
|
586 |
+
# With padding, the left-most extent of the edge should be further to the
|
587 |
+
# right
|
588 |
+
assert padded_extent[0] > default_extent[0]
|
589 |
+
# And the rightmost extent of the edge, further to the left
|
590 |
+
assert padded_extent[1] < default_extent[1]
|
591 |
+
|
592 |
+
|
593 |
+
def test_nonzero_selfloop_with_single_node():
|
594 |
+
"""Ensure that selfloop extent is non-zero when there is only one node."""
|
595 |
+
# Create explicit axis object for test
|
596 |
+
fig, ax = plt.subplots()
|
597 |
+
# Graph with single node + self loop
|
598 |
+
G = nx.DiGraph()
|
599 |
+
G.add_node(0)
|
600 |
+
G.add_edge(0, 0)
|
601 |
+
# Draw
|
602 |
+
patch = nx.draw_networkx_edges(G, {0: (0, 0)})[0]
|
603 |
+
# The resulting patch must have non-zero extent
|
604 |
+
bbox = patch.get_extents()
|
605 |
+
assert bbox.width > 0 and bbox.height > 0
|
606 |
+
# Cleanup
|
607 |
+
plt.delaxes(ax)
|
608 |
+
plt.close()
|
609 |
+
|
610 |
+
|
611 |
+
def test_nonzero_selfloop_with_single_edge_in_edgelist():
|
612 |
+
"""Ensure that selfloop extent is non-zero when only a single edge is
|
613 |
+
specified in the edgelist.
|
614 |
+
"""
|
615 |
+
# Create explicit axis object for test
|
616 |
+
fig, ax = plt.subplots()
|
617 |
+
# Graph with selfloop
|
618 |
+
G = nx.path_graph(2, create_using=nx.DiGraph)
|
619 |
+
G.add_edge(1, 1)
|
620 |
+
pos = {n: (n, n) for n in G.nodes}
|
621 |
+
# Draw only the selfloop edge via the `edgelist` kwarg
|
622 |
+
patch = nx.draw_networkx_edges(G, pos, edgelist=[(1, 1)])[0]
|
623 |
+
# The resulting patch must have non-zero extent
|
624 |
+
bbox = patch.get_extents()
|
625 |
+
assert bbox.width > 0 and bbox.height > 0
|
626 |
+
# Cleanup
|
627 |
+
plt.delaxes(ax)
|
628 |
+
plt.close()
|
629 |
+
|
630 |
+
|
631 |
+
def test_apply_alpha():
|
632 |
+
"""Test apply_alpha when there is a mismatch between the number of
|
633 |
+
supplied colors and elements.
|
634 |
+
"""
|
635 |
+
nodelist = [0, 1, 2]
|
636 |
+
colorlist = ["r", "g", "b"]
|
637 |
+
alpha = 0.5
|
638 |
+
rgba_colors = nx.drawing.nx_pylab.apply_alpha(colorlist, alpha, nodelist)
|
639 |
+
assert all(rgba_colors[:, -1] == alpha)
|
640 |
+
|
641 |
+
|
642 |
+
def test_draw_edges_toggling_with_arrows_kwarg():
|
643 |
+
"""
|
644 |
+
The `arrows` keyword argument is used as a 3-way switch to select which
|
645 |
+
type of object to use for drawing edges:
|
646 |
+
- ``arrows=None`` -> default (FancyArrowPatches for directed, else LineCollection)
|
647 |
+
- ``arrows=True`` -> FancyArrowPatches
|
648 |
+
- ``arrows=False`` -> LineCollection
|
649 |
+
"""
|
650 |
+
import matplotlib.collections
|
651 |
+
import matplotlib.patches
|
652 |
+
|
653 |
+
UG = nx.path_graph(3)
|
654 |
+
DG = nx.path_graph(3, create_using=nx.DiGraph)
|
655 |
+
pos = {n: (n, n) for n in UG}
|
656 |
+
|
657 |
+
# Use FancyArrowPatches when arrows=True, regardless of graph type
|
658 |
+
for G in (UG, DG):
|
659 |
+
edges = nx.draw_networkx_edges(G, pos, arrows=True)
|
660 |
+
assert len(edges) == len(G.edges)
|
661 |
+
assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
|
662 |
+
|
663 |
+
# Use LineCollection when arrows=False, regardless of graph type
|
664 |
+
for G in (UG, DG):
|
665 |
+
edges = nx.draw_networkx_edges(G, pos, arrows=False)
|
666 |
+
assert isinstance(edges, mpl.collections.LineCollection)
|
667 |
+
|
668 |
+
# Default behavior when arrows=None: FAPs for directed, LC's for undirected
|
669 |
+
edges = nx.draw_networkx_edges(UG, pos)
|
670 |
+
assert isinstance(edges, mpl.collections.LineCollection)
|
671 |
+
edges = nx.draw_networkx_edges(DG, pos)
|
672 |
+
assert len(edges) == len(G.edges)
|
673 |
+
assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
|
674 |
+
|
675 |
+
|
676 |
+
@pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
|
677 |
+
def test_draw_networkx_arrows_default_undirected(drawing_func):
|
678 |
+
import matplotlib.collections
|
679 |
+
|
680 |
+
G = nx.path_graph(3)
|
681 |
+
fig, ax = plt.subplots()
|
682 |
+
drawing_func(G, ax=ax)
|
683 |
+
assert any(isinstance(c, mpl.collections.LineCollection) for c in ax.collections)
|
684 |
+
assert not ax.patches
|
685 |
+
plt.delaxes(ax)
|
686 |
+
plt.close()
|
687 |
+
|
688 |
+
|
689 |
+
@pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
|
690 |
+
def test_draw_networkx_arrows_default_directed(drawing_func):
|
691 |
+
import matplotlib.collections
|
692 |
+
|
693 |
+
G = nx.path_graph(3, create_using=nx.DiGraph)
|
694 |
+
fig, ax = plt.subplots()
|
695 |
+
drawing_func(G, ax=ax)
|
696 |
+
assert not any(
|
697 |
+
isinstance(c, mpl.collections.LineCollection) for c in ax.collections
|
698 |
+
)
|
699 |
+
assert ax.patches
|
700 |
+
plt.delaxes(ax)
|
701 |
+
plt.close()
|
702 |
+
|
703 |
+
|
704 |
+
def test_edgelist_kwarg_not_ignored():
|
705 |
+
# See gh-4994
|
706 |
+
G = nx.path_graph(3)
|
707 |
+
G.add_edge(0, 0)
|
708 |
+
fig, ax = plt.subplots()
|
709 |
+
nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax) # Exclude self-loop from edgelist
|
710 |
+
assert not ax.patches
|
711 |
+
plt.delaxes(ax)
|
712 |
+
plt.close()
|
713 |
+
|
714 |
+
|
715 |
+
@pytest.mark.parametrize(
|
716 |
+
("G", "expected_n_edges"),
|
717 |
+
([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
|
718 |
+
)
|
719 |
+
def test_draw_networkx_edges_multiedge_connectionstyle(G, expected_n_edges):
|
720 |
+
"""Draws edges correctly for 3 types of graphs and checks for valid length"""
|
721 |
+
for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
|
722 |
+
G.add_edge(u, v, weight=round(i / 3, 2))
|
723 |
+
pos = {n: (n, n) for n in G}
|
724 |
+
# Raises on insuficient connectionstyle length
|
725 |
+
for conn_style in [
|
726 |
+
"arc3,rad=0.1",
|
727 |
+
["arc3,rad=0.1", "arc3,rad=0.1"],
|
728 |
+
["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.2"],
|
729 |
+
]:
|
730 |
+
nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
|
731 |
+
arrows = nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
|
732 |
+
assert len(arrows) == expected_n_edges
|
733 |
+
|
734 |
+
|
735 |
+
@pytest.mark.parametrize(
|
736 |
+
("G", "expected_n_edges"),
|
737 |
+
([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
|
738 |
+
)
|
739 |
+
def test_draw_networkx_edge_labels_multiedge_connectionstyle(G, expected_n_edges):
|
740 |
+
"""Draws labels correctly for 3 types of graphs and checks for valid length and class names"""
|
741 |
+
for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
|
742 |
+
G.add_edge(u, v, weight=round(i / 3, 2))
|
743 |
+
pos = {n: (n, n) for n in G}
|
744 |
+
# Raises on insuficient connectionstyle length
|
745 |
+
arrows = nx.draw_networkx_edges(
|
746 |
+
G, pos, connectionstyle=["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"]
|
747 |
+
)
|
748 |
+
for conn_style in [
|
749 |
+
"arc3,rad=0.1",
|
750 |
+
["arc3,rad=0.1", "arc3,rad=0.2"],
|
751 |
+
["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"],
|
752 |
+
]:
|
753 |
+
text_items = nx.draw_networkx_edge_labels(G, pos, connectionstyle=conn_style)
|
754 |
+
assert len(text_items) == expected_n_edges
|
755 |
+
for ti in text_items.values():
|
756 |
+
assert ti.__class__.__name__ == "CurvedArrowText"
|
757 |
+
|
758 |
+
|
759 |
+
def test_draw_networkx_edge_label_multiedge():
|
760 |
+
G = nx.MultiGraph()
|
761 |
+
G.add_edge(0, 1, weight=10)
|
762 |
+
G.add_edge(0, 1, weight=20)
|
763 |
+
edge_labels = nx.get_edge_attributes(G, "weight") # Includes edge keys
|
764 |
+
pos = {n: (n, n) for n in G}
|
765 |
+
text_items = nx.draw_networkx_edge_labels(
|
766 |
+
G,
|
767 |
+
pos,
|
768 |
+
edge_labels=edge_labels,
|
769 |
+
connectionstyle=["arc3,rad=0.1", "arc3,rad=0.2"],
|
770 |
+
)
|
771 |
+
assert len(text_items) == 2
|
772 |
+
|
773 |
+
|
774 |
+
def test_draw_networkx_edge_label_empty_dict():
|
775 |
+
"""Regression test for draw_networkx_edge_labels with empty dict. See
|
776 |
+
gh-5372."""
|
777 |
+
G = nx.path_graph(3)
|
778 |
+
pos = {n: (n, n) for n in G.nodes}
|
779 |
+
assert nx.draw_networkx_edge_labels(G, pos, edge_labels={}) == {}
|
780 |
+
|
781 |
+
|
782 |
+
def test_draw_networkx_edges_undirected_selfloop_colors():
|
783 |
+
"""When an edgelist is supplied along with a sequence of colors, check that
|
784 |
+
the self-loops have the correct colors."""
|
785 |
+
fig, ax = plt.subplots()
|
786 |
+
# Edge list and corresponding colors
|
787 |
+
edgelist = [(1, 3), (1, 2), (2, 3), (1, 1), (3, 3), (2, 2)]
|
788 |
+
edge_colors = ["pink", "cyan", "black", "red", "blue", "green"]
|
789 |
+
|
790 |
+
G = nx.Graph(edgelist)
|
791 |
+
pos = {n: (n, n) for n in G.nodes}
|
792 |
+
nx.draw_networkx_edges(G, pos, ax=ax, edgelist=edgelist, edge_color=edge_colors)
|
793 |
+
|
794 |
+
# Verify that there are three fancy arrow patches (1 per self loop)
|
795 |
+
assert len(ax.patches) == 3
|
796 |
+
|
797 |
+
# These are points that should be contained in the self loops. For example,
|
798 |
+
# sl_points[0] will be (1, 1.1), which is inside the "path" of the first
|
799 |
+
# self-loop but outside the others
|
800 |
+
sl_points = np.array(edgelist[-3:]) + np.array([0, 0.1])
|
801 |
+
|
802 |
+
# Check that the mapping between self-loop locations and their colors is
|
803 |
+
# correct
|
804 |
+
for fap, clr, slp in zip(ax.patches, edge_colors[-3:], sl_points):
|
805 |
+
assert fap.get_path().contains_point(slp)
|
806 |
+
assert mpl.colors.same_color(fap.get_edgecolor(), clr)
|
807 |
+
plt.delaxes(ax)
|
808 |
+
plt.close()
|
809 |
+
|
810 |
+
|
811 |
+
@pytest.mark.parametrize(
|
812 |
+
"fap_only_kwarg", # Non-default values for kwargs that only apply to FAPs
|
813 |
+
(
|
814 |
+
{"arrowstyle": "-"},
|
815 |
+
{"arrowsize": 20},
|
816 |
+
{"connectionstyle": "arc3,rad=0.2"},
|
817 |
+
{"min_source_margin": 10},
|
818 |
+
{"min_target_margin": 10},
|
819 |
+
),
|
820 |
+
)
|
821 |
+
def test_user_warnings_for_unused_edge_drawing_kwargs(fap_only_kwarg):
|
822 |
+
"""Users should get a warning when they specify a non-default value for
|
823 |
+
one of the kwargs that applies only to edges drawn with FancyArrowPatches,
|
824 |
+
but FancyArrowPatches aren't being used under the hood."""
|
825 |
+
G = nx.path_graph(3)
|
826 |
+
pos = {n: (n, n) for n in G}
|
827 |
+
fig, ax = plt.subplots()
|
828 |
+
# By default, an undirected graph will use LineCollection to represent
|
829 |
+
# the edges
|
830 |
+
kwarg_name = list(fap_only_kwarg.keys())[0]
|
831 |
+
with pytest.warns(
|
832 |
+
UserWarning, match=f"\n\nThe {kwarg_name} keyword argument is not applicable"
|
833 |
+
):
|
834 |
+
nx.draw_networkx_edges(G, pos, ax=ax, **fap_only_kwarg)
|
835 |
+
# FancyArrowPatches are always used when `arrows=True` is specified.
|
836 |
+
# Check that warnings are *not* raised in this case
|
837 |
+
with warnings.catch_warnings():
|
838 |
+
# Escalate warnings -> errors so tests fail if warnings are raised
|
839 |
+
warnings.simplefilter("error")
|
840 |
+
nx.draw_networkx_edges(G, pos, ax=ax, arrows=True, **fap_only_kwarg)
|
841 |
+
|
842 |
+
plt.delaxes(ax)
|
843 |
+
plt.close()
|
844 |
+
|
845 |
+
|
846 |
+
@pytest.mark.parametrize("draw_fn", (nx.draw, nx.draw_circular))
|
847 |
+
def test_no_warning_on_default_draw_arrowstyle(draw_fn):
|
848 |
+
# See gh-7284
|
849 |
+
fig, ax = plt.subplots()
|
850 |
+
G = nx.cycle_graph(5)
|
851 |
+
with warnings.catch_warnings(record=True) as w:
|
852 |
+
draw_fn(G, ax=ax)
|
853 |
+
assert len(w) == 0
|
854 |
+
|
855 |
+
plt.delaxes(ax)
|
856 |
+
plt.close()
|
857 |
+
|
858 |
+
|
859 |
+
@pytest.mark.parametrize("hide_ticks", [False, True])
|
860 |
+
@pytest.mark.parametrize(
|
861 |
+
"method",
|
862 |
+
[
|
863 |
+
nx.draw_networkx,
|
864 |
+
nx.draw_networkx_edge_labels,
|
865 |
+
nx.draw_networkx_edges,
|
866 |
+
nx.draw_networkx_labels,
|
867 |
+
nx.draw_networkx_nodes,
|
868 |
+
],
|
869 |
+
)
|
870 |
+
def test_hide_ticks(method, hide_ticks):
|
871 |
+
G = nx.path_graph(3)
|
872 |
+
pos = {n: (n, n) for n in G.nodes}
|
873 |
+
_, ax = plt.subplots()
|
874 |
+
method(G, pos=pos, ax=ax, hide_ticks=hide_ticks)
|
875 |
+
for axis in [ax.xaxis, ax.yaxis]:
|
876 |
+
assert bool(axis.get_ticklabels()) != hide_ticks
|
877 |
+
|
878 |
+
plt.delaxes(ax)
|
879 |
+
plt.close()
|
venv/lib/python3.10/site-packages/networkx/linalg/__init__.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from networkx.linalg.attrmatrix import *
|
2 |
+
from networkx.linalg import attrmatrix
|
3 |
+
from networkx.linalg.spectrum import *
|
4 |
+
from networkx.linalg import spectrum
|
5 |
+
from networkx.linalg.graphmatrix import *
|
6 |
+
from networkx.linalg import graphmatrix
|
7 |
+
from networkx.linalg.laplacianmatrix import *
|
8 |
+
from networkx.linalg import laplacianmatrix
|
9 |
+
from networkx.linalg.algebraicconnectivity import *
|
10 |
+
from networkx.linalg.modularitymatrix import *
|
11 |
+
from networkx.linalg import modularitymatrix
|
12 |
+
from networkx.linalg.bethehessianmatrix import *
|
13 |
+
from networkx.linalg import bethehessianmatrix
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (716 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/algebraicconnectivity.cpython-310.pyc
ADDED
Binary file (20 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/bethehessianmatrix.cpython-310.pyc
ADDED
Binary file (2.98 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/graphmatrix.cpython-310.pyc
ADDED
Binary file (5.48 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/laplacianmatrix.cpython-310.pyc
ADDED
Binary file (18.9 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/modularitymatrix.cpython-310.pyc
ADDED
Binary file (4.73 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/__pycache__/spectrum.cpython-310.pyc
ADDED
Binary file (4.43 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/algebraicconnectivity.py
ADDED
@@ -0,0 +1,656 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Algebraic connectivity and Fiedler vectors of undirected graphs.
|
3 |
+
"""
|
4 |
+
from functools import partial
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
from networkx.utils import (
|
8 |
+
not_implemented_for,
|
9 |
+
np_random_state,
|
10 |
+
reverse_cuthill_mckee_ordering,
|
11 |
+
)
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
"algebraic_connectivity",
|
15 |
+
"fiedler_vector",
|
16 |
+
"spectral_ordering",
|
17 |
+
"spectral_bisection",
|
18 |
+
]
|
19 |
+
|
20 |
+
|
21 |
+
class _PCGSolver:
|
22 |
+
"""Preconditioned conjugate gradient method.
|
23 |
+
|
24 |
+
To solve Ax = b:
|
25 |
+
M = A.diagonal() # or some other preconditioner
|
26 |
+
solver = _PCGSolver(lambda x: A * x, lambda x: M * x)
|
27 |
+
x = solver.solve(b)
|
28 |
+
|
29 |
+
The inputs A and M are functions which compute
|
30 |
+
matrix multiplication on the argument.
|
31 |
+
A - multiply by the matrix A in Ax=b
|
32 |
+
M - multiply by M, the preconditioner surrogate for A
|
33 |
+
|
34 |
+
Warning: There is no limit on number of iterations.
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __init__(self, A, M):
|
38 |
+
self._A = A
|
39 |
+
self._M = M
|
40 |
+
|
41 |
+
def solve(self, B, tol):
|
42 |
+
import numpy as np
|
43 |
+
|
44 |
+
# Densifying step - can this be kept sparse?
|
45 |
+
B = np.asarray(B)
|
46 |
+
X = np.ndarray(B.shape, order="F")
|
47 |
+
for j in range(B.shape[1]):
|
48 |
+
X[:, j] = self._solve(B[:, j], tol)
|
49 |
+
return X
|
50 |
+
|
51 |
+
def _solve(self, b, tol):
|
52 |
+
import numpy as np
|
53 |
+
import scipy as sp
|
54 |
+
|
55 |
+
A = self._A
|
56 |
+
M = self._M
|
57 |
+
tol *= sp.linalg.blas.dasum(b)
|
58 |
+
# Initialize.
|
59 |
+
x = np.zeros(b.shape)
|
60 |
+
r = b.copy()
|
61 |
+
z = M(r)
|
62 |
+
rz = sp.linalg.blas.ddot(r, z)
|
63 |
+
p = z.copy()
|
64 |
+
# Iterate.
|
65 |
+
while True:
|
66 |
+
Ap = A(p)
|
67 |
+
alpha = rz / sp.linalg.blas.ddot(p, Ap)
|
68 |
+
x = sp.linalg.blas.daxpy(p, x, a=alpha)
|
69 |
+
r = sp.linalg.blas.daxpy(Ap, r, a=-alpha)
|
70 |
+
if sp.linalg.blas.dasum(r) < tol:
|
71 |
+
return x
|
72 |
+
z = M(r)
|
73 |
+
beta = sp.linalg.blas.ddot(r, z)
|
74 |
+
beta, rz = beta / rz, beta
|
75 |
+
p = sp.linalg.blas.daxpy(p, z, a=beta)
|
76 |
+
|
77 |
+
|
78 |
+
class _LUSolver:
|
79 |
+
"""LU factorization.
|
80 |
+
|
81 |
+
To solve Ax = b:
|
82 |
+
solver = _LUSolver(A)
|
83 |
+
x = solver.solve(b)
|
84 |
+
|
85 |
+
optional argument `tol` on solve method is ignored but included
|
86 |
+
to match _PCGsolver API.
|
87 |
+
"""
|
88 |
+
|
89 |
+
def __init__(self, A):
|
90 |
+
import scipy as sp
|
91 |
+
|
92 |
+
self._LU = sp.sparse.linalg.splu(
|
93 |
+
A,
|
94 |
+
permc_spec="MMD_AT_PLUS_A",
|
95 |
+
diag_pivot_thresh=0.0,
|
96 |
+
options={"Equil": True, "SymmetricMode": True},
|
97 |
+
)
|
98 |
+
|
99 |
+
def solve(self, B, tol=None):
|
100 |
+
import numpy as np
|
101 |
+
|
102 |
+
B = np.asarray(B)
|
103 |
+
X = np.ndarray(B.shape, order="F")
|
104 |
+
for j in range(B.shape[1]):
|
105 |
+
X[:, j] = self._LU.solve(B[:, j])
|
106 |
+
return X
|
107 |
+
|
108 |
+
|
109 |
+
def _preprocess_graph(G, weight):
|
110 |
+
"""Compute edge weights and eliminate zero-weight edges."""
|
111 |
+
if G.is_directed():
|
112 |
+
H = nx.MultiGraph()
|
113 |
+
H.add_nodes_from(G)
|
114 |
+
H.add_weighted_edges_from(
|
115 |
+
((u, v, e.get(weight, 1.0)) for u, v, e in G.edges(data=True) if u != v),
|
116 |
+
weight=weight,
|
117 |
+
)
|
118 |
+
G = H
|
119 |
+
if not G.is_multigraph():
|
120 |
+
edges = (
|
121 |
+
(u, v, abs(e.get(weight, 1.0))) for u, v, e in G.edges(data=True) if u != v
|
122 |
+
)
|
123 |
+
else:
|
124 |
+
edges = (
|
125 |
+
(u, v, sum(abs(e.get(weight, 1.0)) for e in G[u][v].values()))
|
126 |
+
for u, v in G.edges()
|
127 |
+
if u != v
|
128 |
+
)
|
129 |
+
H = nx.Graph()
|
130 |
+
H.add_nodes_from(G)
|
131 |
+
H.add_weighted_edges_from((u, v, e) for u, v, e in edges if e != 0)
|
132 |
+
return H
|
133 |
+
|
134 |
+
|
135 |
+
def _rcm_estimate(G, nodelist):
|
136 |
+
"""Estimate the Fiedler vector using the reverse Cuthill-McKee ordering."""
|
137 |
+
import numpy as np
|
138 |
+
|
139 |
+
G = G.subgraph(nodelist)
|
140 |
+
order = reverse_cuthill_mckee_ordering(G)
|
141 |
+
n = len(nodelist)
|
142 |
+
index = dict(zip(nodelist, range(n)))
|
143 |
+
x = np.ndarray(n, dtype=float)
|
144 |
+
for i, u in enumerate(order):
|
145 |
+
x[index[u]] = i
|
146 |
+
x -= (n - 1) / 2.0
|
147 |
+
return x
|
148 |
+
|
149 |
+
|
150 |
+
def _tracemin_fiedler(L, X, normalized, tol, method):
|
151 |
+
"""Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
|
152 |
+
|
153 |
+
The Fiedler vector of a connected undirected graph is the eigenvector
|
154 |
+
corresponding to the second smallest eigenvalue of the Laplacian matrix
|
155 |
+
of the graph. This function starts with the Laplacian L, not the Graph.
|
156 |
+
|
157 |
+
Parameters
|
158 |
+
----------
|
159 |
+
L : Laplacian of a possibly weighted or normalized, but undirected graph
|
160 |
+
|
161 |
+
X : Initial guess for a solution. Usually a matrix of random numbers.
|
162 |
+
This function allows more than one column in X to identify more than
|
163 |
+
one eigenvector if desired.
|
164 |
+
|
165 |
+
normalized : bool
|
166 |
+
Whether the normalized Laplacian matrix is used.
|
167 |
+
|
168 |
+
tol : float
|
169 |
+
Tolerance of relative residual in eigenvalue computation.
|
170 |
+
Warning: There is no limit on number of iterations.
|
171 |
+
|
172 |
+
method : string
|
173 |
+
Should be 'tracemin_pcg' or 'tracemin_lu'.
|
174 |
+
Otherwise exception is raised.
|
175 |
+
|
176 |
+
Returns
|
177 |
+
-------
|
178 |
+
sigma, X : Two NumPy arrays of floats.
|
179 |
+
The lowest eigenvalues and corresponding eigenvectors of L.
|
180 |
+
The size of input X determines the size of these outputs.
|
181 |
+
As this is for Fiedler vectors, the zero eigenvalue (and
|
182 |
+
constant eigenvector) are avoided.
|
183 |
+
"""
|
184 |
+
import numpy as np
|
185 |
+
import scipy as sp
|
186 |
+
|
187 |
+
n = X.shape[0]
|
188 |
+
|
189 |
+
if normalized:
|
190 |
+
# Form the normalized Laplacian matrix and determine the eigenvector of
|
191 |
+
# its nullspace.
|
192 |
+
e = np.sqrt(L.diagonal())
|
193 |
+
# TODO: rm csr_array wrapper when spdiags array creation becomes available
|
194 |
+
D = sp.sparse.csr_array(sp.sparse.spdiags(1 / e, 0, n, n, format="csr"))
|
195 |
+
L = D @ L @ D
|
196 |
+
e *= 1.0 / np.linalg.norm(e, 2)
|
197 |
+
|
198 |
+
if normalized:
|
199 |
+
|
200 |
+
def project(X):
|
201 |
+
"""Make X orthogonal to the nullspace of L."""
|
202 |
+
X = np.asarray(X)
|
203 |
+
for j in range(X.shape[1]):
|
204 |
+
X[:, j] -= (X[:, j] @ e) * e
|
205 |
+
|
206 |
+
else:
|
207 |
+
|
208 |
+
def project(X):
|
209 |
+
"""Make X orthogonal to the nullspace of L."""
|
210 |
+
X = np.asarray(X)
|
211 |
+
for j in range(X.shape[1]):
|
212 |
+
X[:, j] -= X[:, j].sum() / n
|
213 |
+
|
214 |
+
if method == "tracemin_pcg":
|
215 |
+
D = L.diagonal().astype(float)
|
216 |
+
solver = _PCGSolver(lambda x: L @ x, lambda x: D * x)
|
217 |
+
elif method == "tracemin_lu":
|
218 |
+
# Convert A to CSC to suppress SparseEfficiencyWarning.
|
219 |
+
A = sp.sparse.csc_array(L, dtype=float, copy=True)
|
220 |
+
# Force A to be nonsingular. Since A is the Laplacian matrix of a
|
221 |
+
# connected graph, its rank deficiency is one, and thus one diagonal
|
222 |
+
# element needs to modified. Changing to infinity forces a zero in the
|
223 |
+
# corresponding element in the solution.
|
224 |
+
i = (A.indptr[1:] - A.indptr[:-1]).argmax()
|
225 |
+
A[i, i] = np.inf
|
226 |
+
solver = _LUSolver(A)
|
227 |
+
else:
|
228 |
+
raise nx.NetworkXError(f"Unknown linear system solver: {method}")
|
229 |
+
|
230 |
+
# Initialize.
|
231 |
+
Lnorm = abs(L).sum(axis=1).flatten().max()
|
232 |
+
project(X)
|
233 |
+
W = np.ndarray(X.shape, order="F")
|
234 |
+
|
235 |
+
while True:
|
236 |
+
# Orthonormalize X.
|
237 |
+
X = np.linalg.qr(X)[0]
|
238 |
+
# Compute iteration matrix H.
|
239 |
+
W[:, :] = L @ X
|
240 |
+
H = X.T @ W
|
241 |
+
sigma, Y = sp.linalg.eigh(H, overwrite_a=True)
|
242 |
+
# Compute the Ritz vectors.
|
243 |
+
X = X @ Y
|
244 |
+
# Test for convergence exploiting the fact that L * X == W * Y.
|
245 |
+
res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm
|
246 |
+
if res < tol:
|
247 |
+
break
|
248 |
+
# Compute X = L \ X / (X' * (L \ X)).
|
249 |
+
# L \ X can have an arbitrary projection on the nullspace of L,
|
250 |
+
# which will be eliminated.
|
251 |
+
W[:, :] = solver.solve(X, tol)
|
252 |
+
X = (sp.linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order.
|
253 |
+
project(X)
|
254 |
+
|
255 |
+
return sigma, np.asarray(X)
|
256 |
+
|
257 |
+
|
258 |
+
def _get_fiedler_func(method):
|
259 |
+
"""Returns a function that solves the Fiedler eigenvalue problem."""
|
260 |
+
import numpy as np
|
261 |
+
|
262 |
+
if method == "tracemin": # old style keyword <v2.1
|
263 |
+
method = "tracemin_pcg"
|
264 |
+
if method in ("tracemin_pcg", "tracemin_lu"):
|
265 |
+
|
266 |
+
def find_fiedler(L, x, normalized, tol, seed):
|
267 |
+
q = 1 if method == "tracemin_pcg" else min(4, L.shape[0] - 1)
|
268 |
+
X = np.asarray(seed.normal(size=(q, L.shape[0]))).T
|
269 |
+
sigma, X = _tracemin_fiedler(L, X, normalized, tol, method)
|
270 |
+
return sigma[0], X[:, 0]
|
271 |
+
|
272 |
+
elif method == "lanczos" or method == "lobpcg":
|
273 |
+
|
274 |
+
def find_fiedler(L, x, normalized, tol, seed):
|
275 |
+
import scipy as sp
|
276 |
+
|
277 |
+
L = sp.sparse.csc_array(L, dtype=float)
|
278 |
+
n = L.shape[0]
|
279 |
+
if normalized:
|
280 |
+
# TODO: rm csc_array wrapping when spdiags array becomes available
|
281 |
+
D = sp.sparse.csc_array(
|
282 |
+
sp.sparse.spdiags(
|
283 |
+
1.0 / np.sqrt(L.diagonal()), [0], n, n, format="csc"
|
284 |
+
)
|
285 |
+
)
|
286 |
+
L = D @ L @ D
|
287 |
+
if method == "lanczos" or n < 10:
|
288 |
+
# Avoid LOBPCG when n < 10 due to
|
289 |
+
# https://github.com/scipy/scipy/issues/3592
|
290 |
+
# https://github.com/scipy/scipy/pull/3594
|
291 |
+
sigma, X = sp.sparse.linalg.eigsh(
|
292 |
+
L, 2, which="SM", tol=tol, return_eigenvectors=True
|
293 |
+
)
|
294 |
+
return sigma[1], X[:, 1]
|
295 |
+
else:
|
296 |
+
X = np.asarray(np.atleast_2d(x).T)
|
297 |
+
# TODO: rm csr_array wrapping when spdiags array becomes available
|
298 |
+
M = sp.sparse.csr_array(sp.sparse.spdiags(1.0 / L.diagonal(), 0, n, n))
|
299 |
+
Y = np.ones(n)
|
300 |
+
if normalized:
|
301 |
+
Y /= D.diagonal()
|
302 |
+
sigma, X = sp.sparse.linalg.lobpcg(
|
303 |
+
L, X, M=M, Y=np.atleast_2d(Y).T, tol=tol, maxiter=n, largest=False
|
304 |
+
)
|
305 |
+
return sigma[0], X[:, 0]
|
306 |
+
|
307 |
+
else:
|
308 |
+
raise nx.NetworkXError(f"unknown method {method!r}.")
|
309 |
+
|
310 |
+
return find_fiedler
|
311 |
+
|
312 |
+
|
313 |
+
@not_implemented_for("directed")
|
314 |
+
@np_random_state(5)
|
315 |
+
@nx._dispatchable(edge_attrs="weight")
|
316 |
+
def algebraic_connectivity(
|
317 |
+
G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
|
318 |
+
):
|
319 |
+
r"""Returns the algebraic connectivity of an undirected graph.
|
320 |
+
|
321 |
+
The algebraic connectivity of a connected undirected graph is the second
|
322 |
+
smallest eigenvalue of its Laplacian matrix.
|
323 |
+
|
324 |
+
Parameters
|
325 |
+
----------
|
326 |
+
G : NetworkX graph
|
327 |
+
An undirected graph.
|
328 |
+
|
329 |
+
weight : object, optional (default: None)
|
330 |
+
The data key used to determine the weight of each edge. If None, then
|
331 |
+
each edge has unit weight.
|
332 |
+
|
333 |
+
normalized : bool, optional (default: False)
|
334 |
+
Whether the normalized Laplacian matrix is used.
|
335 |
+
|
336 |
+
tol : float, optional (default: 1e-8)
|
337 |
+
Tolerance of relative residual in eigenvalue computation.
|
338 |
+
|
339 |
+
method : string, optional (default: 'tracemin_pcg')
|
340 |
+
Method of eigenvalue computation. It must be one of the tracemin
|
341 |
+
options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
|
342 |
+
or 'lobpcg' (LOBPCG).
|
343 |
+
|
344 |
+
The TraceMIN algorithm uses a linear system solver. The following
|
345 |
+
values allow specifying the solver to be used.
|
346 |
+
|
347 |
+
=============== ========================================
|
348 |
+
Value Solver
|
349 |
+
=============== ========================================
|
350 |
+
'tracemin_pcg' Preconditioned conjugate gradient method
|
351 |
+
'tracemin_lu' LU factorization
|
352 |
+
=============== ========================================
|
353 |
+
|
354 |
+
seed : integer, random_state, or None (default)
|
355 |
+
Indicator of random number generation state.
|
356 |
+
See :ref:`Randomness<randomness>`.
|
357 |
+
|
358 |
+
Returns
|
359 |
+
-------
|
360 |
+
algebraic_connectivity : float
|
361 |
+
Algebraic connectivity.
|
362 |
+
|
363 |
+
Raises
|
364 |
+
------
|
365 |
+
NetworkXNotImplemented
|
366 |
+
If G is directed.
|
367 |
+
|
368 |
+
NetworkXError
|
369 |
+
If G has less than two nodes.
|
370 |
+
|
371 |
+
Notes
|
372 |
+
-----
|
373 |
+
Edge weights are interpreted by their absolute values. For MultiGraph's,
|
374 |
+
weights of parallel edges are summed. Zero-weighted edges are ignored.
|
375 |
+
|
376 |
+
See Also
|
377 |
+
--------
|
378 |
+
laplacian_matrix
|
379 |
+
|
380 |
+
Examples
|
381 |
+
--------
|
382 |
+
For undirected graphs algebraic connectivity can tell us if a graph is connected or not
|
383 |
+
`G` is connected iff ``algebraic_connectivity(G) > 0``:
|
384 |
+
|
385 |
+
>>> G = nx.complete_graph(5)
|
386 |
+
>>> nx.algebraic_connectivity(G) > 0
|
387 |
+
True
|
388 |
+
>>> G.add_node(10) # G is no longer connected
|
389 |
+
>>> nx.algebraic_connectivity(G) > 0
|
390 |
+
False
|
391 |
+
|
392 |
+
"""
|
393 |
+
if len(G) < 2:
|
394 |
+
raise nx.NetworkXError("graph has less than two nodes.")
|
395 |
+
G = _preprocess_graph(G, weight)
|
396 |
+
if not nx.is_connected(G):
|
397 |
+
return 0.0
|
398 |
+
|
399 |
+
L = nx.laplacian_matrix(G)
|
400 |
+
if L.shape[0] == 2:
|
401 |
+
return 2.0 * float(L[0, 0]) if not normalized else 2.0
|
402 |
+
|
403 |
+
find_fiedler = _get_fiedler_func(method)
|
404 |
+
x = None if method != "lobpcg" else _rcm_estimate(G, G)
|
405 |
+
sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
|
406 |
+
return float(sigma)
|
407 |
+
|
408 |
+
|
409 |
+
@not_implemented_for("directed")
|
410 |
+
@np_random_state(5)
|
411 |
+
@nx._dispatchable(edge_attrs="weight")
|
412 |
+
def fiedler_vector(
|
413 |
+
G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
|
414 |
+
):
|
415 |
+
"""Returns the Fiedler vector of a connected undirected graph.
|
416 |
+
|
417 |
+
The Fiedler vector of a connected undirected graph is the eigenvector
|
418 |
+
corresponding to the second smallest eigenvalue of the Laplacian matrix
|
419 |
+
of the graph.
|
420 |
+
|
421 |
+
Parameters
|
422 |
+
----------
|
423 |
+
G : NetworkX graph
|
424 |
+
An undirected graph.
|
425 |
+
|
426 |
+
weight : object, optional (default: None)
|
427 |
+
The data key used to determine the weight of each edge. If None, then
|
428 |
+
each edge has unit weight.
|
429 |
+
|
430 |
+
normalized : bool, optional (default: False)
|
431 |
+
Whether the normalized Laplacian matrix is used.
|
432 |
+
|
433 |
+
tol : float, optional (default: 1e-8)
|
434 |
+
Tolerance of relative residual in eigenvalue computation.
|
435 |
+
|
436 |
+
method : string, optional (default: 'tracemin_pcg')
|
437 |
+
Method of eigenvalue computation. It must be one of the tracemin
|
438 |
+
options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
|
439 |
+
or 'lobpcg' (LOBPCG).
|
440 |
+
|
441 |
+
The TraceMIN algorithm uses a linear system solver. The following
|
442 |
+
values allow specifying the solver to be used.
|
443 |
+
|
444 |
+
=============== ========================================
|
445 |
+
Value Solver
|
446 |
+
=============== ========================================
|
447 |
+
'tracemin_pcg' Preconditioned conjugate gradient method
|
448 |
+
'tracemin_lu' LU factorization
|
449 |
+
=============== ========================================
|
450 |
+
|
451 |
+
seed : integer, random_state, or None (default)
|
452 |
+
Indicator of random number generation state.
|
453 |
+
See :ref:`Randomness<randomness>`.
|
454 |
+
|
455 |
+
Returns
|
456 |
+
-------
|
457 |
+
fiedler_vector : NumPy array of floats.
|
458 |
+
Fiedler vector.
|
459 |
+
|
460 |
+
Raises
|
461 |
+
------
|
462 |
+
NetworkXNotImplemented
|
463 |
+
If G is directed.
|
464 |
+
|
465 |
+
NetworkXError
|
466 |
+
If G has less than two nodes or is not connected.
|
467 |
+
|
468 |
+
Notes
|
469 |
+
-----
|
470 |
+
Edge weights are interpreted by their absolute values. For MultiGraph's,
|
471 |
+
weights of parallel edges are summed. Zero-weighted edges are ignored.
|
472 |
+
|
473 |
+
See Also
|
474 |
+
--------
|
475 |
+
laplacian_matrix
|
476 |
+
|
477 |
+
Examples
|
478 |
+
--------
|
479 |
+
Given a connected graph the signs of the values in the Fiedler vector can be
|
480 |
+
used to partition the graph into two components.
|
481 |
+
|
482 |
+
>>> G = nx.barbell_graph(5, 0)
|
483 |
+
>>> nx.fiedler_vector(G, normalized=True, seed=1)
|
484 |
+
array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899,
|
485 |
+
0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129])
|
486 |
+
|
487 |
+
The connected components are the two 5-node cliques of the barbell graph.
|
488 |
+
"""
|
489 |
+
import numpy as np
|
490 |
+
|
491 |
+
if len(G) < 2:
|
492 |
+
raise nx.NetworkXError("graph has less than two nodes.")
|
493 |
+
G = _preprocess_graph(G, weight)
|
494 |
+
if not nx.is_connected(G):
|
495 |
+
raise nx.NetworkXError("graph is not connected.")
|
496 |
+
|
497 |
+
if len(G) == 2:
|
498 |
+
return np.array([1.0, -1.0])
|
499 |
+
|
500 |
+
find_fiedler = _get_fiedler_func(method)
|
501 |
+
L = nx.laplacian_matrix(G)
|
502 |
+
x = None if method != "lobpcg" else _rcm_estimate(G, G)
|
503 |
+
sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
|
504 |
+
return fiedler
|
505 |
+
|
506 |
+
|
507 |
+
@np_random_state(5)
|
508 |
+
@nx._dispatchable(edge_attrs="weight")
|
509 |
+
def spectral_ordering(
|
510 |
+
G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
|
511 |
+
):
|
512 |
+
"""Compute the spectral_ordering of a graph.
|
513 |
+
|
514 |
+
The spectral ordering of a graph is an ordering of its nodes where nodes
|
515 |
+
in the same weakly connected components appear contiguous and ordered by
|
516 |
+
their corresponding elements in the Fiedler vector of the component.
|
517 |
+
|
518 |
+
Parameters
|
519 |
+
----------
|
520 |
+
G : NetworkX graph
|
521 |
+
A graph.
|
522 |
+
|
523 |
+
weight : object, optional (default: None)
|
524 |
+
The data key used to determine the weight of each edge. If None, then
|
525 |
+
each edge has unit weight.
|
526 |
+
|
527 |
+
normalized : bool, optional (default: False)
|
528 |
+
Whether the normalized Laplacian matrix is used.
|
529 |
+
|
530 |
+
tol : float, optional (default: 1e-8)
|
531 |
+
Tolerance of relative residual in eigenvalue computation.
|
532 |
+
|
533 |
+
method : string, optional (default: 'tracemin_pcg')
|
534 |
+
Method of eigenvalue computation. It must be one of the tracemin
|
535 |
+
options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
|
536 |
+
or 'lobpcg' (LOBPCG).
|
537 |
+
|
538 |
+
The TraceMIN algorithm uses a linear system solver. The following
|
539 |
+
values allow specifying the solver to be used.
|
540 |
+
|
541 |
+
=============== ========================================
|
542 |
+
Value Solver
|
543 |
+
=============== ========================================
|
544 |
+
'tracemin_pcg' Preconditioned conjugate gradient method
|
545 |
+
'tracemin_lu' LU factorization
|
546 |
+
=============== ========================================
|
547 |
+
|
548 |
+
seed : integer, random_state, or None (default)
|
549 |
+
Indicator of random number generation state.
|
550 |
+
See :ref:`Randomness<randomness>`.
|
551 |
+
|
552 |
+
Returns
|
553 |
+
-------
|
554 |
+
spectral_ordering : NumPy array of floats.
|
555 |
+
Spectral ordering of nodes.
|
556 |
+
|
557 |
+
Raises
|
558 |
+
------
|
559 |
+
NetworkXError
|
560 |
+
If G is empty.
|
561 |
+
|
562 |
+
Notes
|
563 |
+
-----
|
564 |
+
Edge weights are interpreted by their absolute values. For MultiGraph's,
|
565 |
+
weights of parallel edges are summed. Zero-weighted edges are ignored.
|
566 |
+
|
567 |
+
See Also
|
568 |
+
--------
|
569 |
+
laplacian_matrix
|
570 |
+
"""
|
571 |
+
if len(G) == 0:
|
572 |
+
raise nx.NetworkXError("graph is empty.")
|
573 |
+
G = _preprocess_graph(G, weight)
|
574 |
+
|
575 |
+
find_fiedler = _get_fiedler_func(method)
|
576 |
+
order = []
|
577 |
+
for component in nx.connected_components(G):
|
578 |
+
size = len(component)
|
579 |
+
if size > 2:
|
580 |
+
L = nx.laplacian_matrix(G, component)
|
581 |
+
x = None if method != "lobpcg" else _rcm_estimate(G, component)
|
582 |
+
sigma, fiedler = find_fiedler(L, x, normalized, tol, seed)
|
583 |
+
sort_info = zip(fiedler, range(size), component)
|
584 |
+
order.extend(u for x, c, u in sorted(sort_info))
|
585 |
+
else:
|
586 |
+
order.extend(component)
|
587 |
+
|
588 |
+
return order
|
589 |
+
|
590 |
+
|
591 |
+
@nx._dispatchable(edge_attrs="weight")
|
592 |
+
def spectral_bisection(
|
593 |
+
G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None
|
594 |
+
):
|
595 |
+
"""Bisect the graph using the Fiedler vector.
|
596 |
+
|
597 |
+
This method uses the Fiedler vector to bisect a graph.
|
598 |
+
The partition is defined by the nodes which are associated with
|
599 |
+
either positive or negative values in the vector.
|
600 |
+
|
601 |
+
Parameters
|
602 |
+
----------
|
603 |
+
G : NetworkX Graph
|
604 |
+
|
605 |
+
weight : str, optional (default: weight)
|
606 |
+
The data key used to determine the weight of each edge. If None, then
|
607 |
+
each edge has unit weight.
|
608 |
+
|
609 |
+
normalized : bool, optional (default: False)
|
610 |
+
Whether the normalized Laplacian matrix is used.
|
611 |
+
|
612 |
+
tol : float, optional (default: 1e-8)
|
613 |
+
Tolerance of relative residual in eigenvalue computation.
|
614 |
+
|
615 |
+
method : string, optional (default: 'tracemin_pcg')
|
616 |
+
Method of eigenvalue computation. It must be one of the tracemin
|
617 |
+
options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
|
618 |
+
or 'lobpcg' (LOBPCG).
|
619 |
+
|
620 |
+
The TraceMIN algorithm uses a linear system solver. The following
|
621 |
+
values allow specifying the solver to be used.
|
622 |
+
|
623 |
+
=============== ========================================
|
624 |
+
Value Solver
|
625 |
+
=============== ========================================
|
626 |
+
'tracemin_pcg' Preconditioned conjugate gradient method
|
627 |
+
'tracemin_lu' LU factorization
|
628 |
+
=============== ========================================
|
629 |
+
|
630 |
+
seed : integer, random_state, or None (default)
|
631 |
+
Indicator of random number generation state.
|
632 |
+
See :ref:`Randomness<randomness>`.
|
633 |
+
|
634 |
+
Returns
|
635 |
+
-------
|
636 |
+
bisection : tuple of sets
|
637 |
+
Sets with the bisection of nodes
|
638 |
+
|
639 |
+
Examples
|
640 |
+
--------
|
641 |
+
>>> G = nx.barbell_graph(3, 0)
|
642 |
+
>>> nx.spectral_bisection(G)
|
643 |
+
({0, 1, 2}, {3, 4, 5})
|
644 |
+
|
645 |
+
References
|
646 |
+
----------
|
647 |
+
.. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370
|
648 |
+
Oxford University Press 2011.
|
649 |
+
"""
|
650 |
+
import numpy as np
|
651 |
+
|
652 |
+
v = nx.fiedler_vector(G, weight, normalized, tol, method, seed)
|
653 |
+
nodes = np.array(list(G))
|
654 |
+
pos_vals = v >= 0
|
655 |
+
|
656 |
+
return set(nodes[~pos_vals].tolist()), set(nodes[pos_vals].tolist())
|
venv/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py
ADDED
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Functions for constructing matrix-like objects from graph attributes.
|
3 |
+
"""
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
__all__ = ["attr_matrix", "attr_sparse_matrix"]
|
7 |
+
|
8 |
+
|
9 |
+
def _node_value(G, node_attr):
|
10 |
+
"""Returns a function that returns a value from G.nodes[u].
|
11 |
+
|
12 |
+
We return a function expecting a node as its sole argument. Then, in the
|
13 |
+
simplest scenario, the returned function will return G.nodes[u][node_attr].
|
14 |
+
However, we also handle the case when `node_attr` is None or when it is a
|
15 |
+
function itself.
|
16 |
+
|
17 |
+
Parameters
|
18 |
+
----------
|
19 |
+
G : graph
|
20 |
+
A NetworkX graph
|
21 |
+
|
22 |
+
node_attr : {None, str, callable}
|
23 |
+
Specification of how the value of the node attribute should be obtained
|
24 |
+
from the node attribute dictionary.
|
25 |
+
|
26 |
+
Returns
|
27 |
+
-------
|
28 |
+
value : function
|
29 |
+
A function expecting a node as its sole argument. The function will
|
30 |
+
returns a value from G.nodes[u] that depends on `edge_attr`.
|
31 |
+
|
32 |
+
"""
|
33 |
+
if node_attr is None:
|
34 |
+
|
35 |
+
def value(u):
|
36 |
+
return u
|
37 |
+
|
38 |
+
elif not callable(node_attr):
|
39 |
+
# assume it is a key for the node attribute dictionary
|
40 |
+
def value(u):
|
41 |
+
return G.nodes[u][node_attr]
|
42 |
+
|
43 |
+
else:
|
44 |
+
# Advanced: Allow users to specify something else.
|
45 |
+
#
|
46 |
+
# For example,
|
47 |
+
# node_attr = lambda u: G.nodes[u].get('size', .5) * 3
|
48 |
+
#
|
49 |
+
value = node_attr
|
50 |
+
|
51 |
+
return value
|
52 |
+
|
53 |
+
|
54 |
+
def _edge_value(G, edge_attr):
|
55 |
+
"""Returns a function that returns a value from G[u][v].
|
56 |
+
|
57 |
+
Suppose there exists an edge between u and v. Then we return a function
|
58 |
+
expecting u and v as arguments. For Graph and DiGraph, G[u][v] is
|
59 |
+
the edge attribute dictionary, and the function (essentially) returns
|
60 |
+
G[u][v][edge_attr]. However, we also handle cases when `edge_attr` is None
|
61 |
+
and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v]
|
62 |
+
is a dictionary of all edges between u and v. In this case, the returned
|
63 |
+
function sums the value of `edge_attr` for every edge between u and v.
|
64 |
+
|
65 |
+
Parameters
|
66 |
+
----------
|
67 |
+
G : graph
|
68 |
+
A NetworkX graph
|
69 |
+
|
70 |
+
edge_attr : {None, str, callable}
|
71 |
+
Specification of how the value of the edge attribute should be obtained
|
72 |
+
from the edge attribute dictionary, G[u][v]. For multigraphs, G[u][v]
|
73 |
+
is a dictionary of all the edges between u and v. This allows for
|
74 |
+
special treatment of multiedges.
|
75 |
+
|
76 |
+
Returns
|
77 |
+
-------
|
78 |
+
value : function
|
79 |
+
A function expecting two nodes as parameters. The nodes should
|
80 |
+
represent the from- and to- node of an edge. The function will
|
81 |
+
return a value from G[u][v] that depends on `edge_attr`.
|
82 |
+
|
83 |
+
"""
|
84 |
+
|
85 |
+
if edge_attr is None:
|
86 |
+
# topological count of edges
|
87 |
+
|
88 |
+
if G.is_multigraph():
|
89 |
+
|
90 |
+
def value(u, v):
|
91 |
+
return len(G[u][v])
|
92 |
+
|
93 |
+
else:
|
94 |
+
|
95 |
+
def value(u, v):
|
96 |
+
return 1
|
97 |
+
|
98 |
+
elif not callable(edge_attr):
|
99 |
+
# assume it is a key for the edge attribute dictionary
|
100 |
+
|
101 |
+
if edge_attr == "weight":
|
102 |
+
# provide a default value
|
103 |
+
if G.is_multigraph():
|
104 |
+
|
105 |
+
def value(u, v):
|
106 |
+
return sum(d.get(edge_attr, 1) for d in G[u][v].values())
|
107 |
+
|
108 |
+
else:
|
109 |
+
|
110 |
+
def value(u, v):
|
111 |
+
return G[u][v].get(edge_attr, 1)
|
112 |
+
|
113 |
+
else:
|
114 |
+
# otherwise, the edge attribute MUST exist for each edge
|
115 |
+
if G.is_multigraph():
|
116 |
+
|
117 |
+
def value(u, v):
|
118 |
+
return sum(d[edge_attr] for d in G[u][v].values())
|
119 |
+
|
120 |
+
else:
|
121 |
+
|
122 |
+
def value(u, v):
|
123 |
+
return G[u][v][edge_attr]
|
124 |
+
|
125 |
+
else:
|
126 |
+
# Advanced: Allow users to specify something else.
|
127 |
+
#
|
128 |
+
# Alternative default value:
|
129 |
+
# edge_attr = lambda u,v: G[u][v].get('thickness', .5)
|
130 |
+
#
|
131 |
+
# Function on an attribute:
|
132 |
+
# edge_attr = lambda u,v: abs(G[u][v]['weight'])
|
133 |
+
#
|
134 |
+
# Handle Multi(Di)Graphs differently:
|
135 |
+
# edge_attr = lambda u,v: numpy.prod([d['size'] for d in G[u][v].values()])
|
136 |
+
#
|
137 |
+
# Ignore multiple edges
|
138 |
+
# edge_attr = lambda u,v: 1 if len(G[u][v]) else 0
|
139 |
+
#
|
140 |
+
value = edge_attr
|
141 |
+
|
142 |
+
return value
|
143 |
+
|
144 |
+
|
145 |
+
@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
|
146 |
+
def attr_matrix(
|
147 |
+
G,
|
148 |
+
edge_attr=None,
|
149 |
+
node_attr=None,
|
150 |
+
normalized=False,
|
151 |
+
rc_order=None,
|
152 |
+
dtype=None,
|
153 |
+
order=None,
|
154 |
+
):
|
155 |
+
"""Returns the attribute matrix using attributes from `G` as a numpy array.
|
156 |
+
|
157 |
+
If only `G` is passed in, then the adjacency matrix is constructed.
|
158 |
+
|
159 |
+
Let A be a discrete set of values for the node attribute `node_attr`. Then
|
160 |
+
the elements of A represent the rows and columns of the constructed matrix.
|
161 |
+
Now, iterate through every edge e=(u,v) in `G` and consider the value
|
162 |
+
of the edge attribute `edge_attr`. If ua and va are the values of the
|
163 |
+
node attribute `node_attr` for u and v, respectively, then the value of
|
164 |
+
the edge attribute is added to the matrix element at (ua, va).
|
165 |
+
|
166 |
+
Parameters
|
167 |
+
----------
|
168 |
+
G : graph
|
169 |
+
The NetworkX graph used to construct the attribute matrix.
|
170 |
+
|
171 |
+
edge_attr : str, optional
|
172 |
+
Each element of the matrix represents a running total of the
|
173 |
+
specified edge attribute for edges whose node attributes correspond
|
174 |
+
to the rows/cols of the matrix. The attribute must be present for
|
175 |
+
all edges in the graph. If no attribute is specified, then we
|
176 |
+
just count the number of edges whose node attributes correspond
|
177 |
+
to the matrix element.
|
178 |
+
|
179 |
+
node_attr : str, optional
|
180 |
+
Each row and column in the matrix represents a particular value
|
181 |
+
of the node attribute. The attribute must be present for all nodes
|
182 |
+
in the graph. Note, the values of this attribute should be reliably
|
183 |
+
hashable. So, float values are not recommended. If no attribute is
|
184 |
+
specified, then the rows and columns will be the nodes of the graph.
|
185 |
+
|
186 |
+
normalized : bool, optional
|
187 |
+
If True, then each row is normalized by the summation of its values.
|
188 |
+
|
189 |
+
rc_order : list, optional
|
190 |
+
A list of the node attribute values. This list specifies the ordering
|
191 |
+
of rows and columns of the array. If no ordering is provided, then
|
192 |
+
the ordering will be random (and also, a return value).
|
193 |
+
|
194 |
+
Other Parameters
|
195 |
+
----------------
|
196 |
+
dtype : NumPy data-type, optional
|
197 |
+
A valid NumPy dtype used to initialize the array. Keep in mind certain
|
198 |
+
dtypes can yield unexpected results if the array is to be normalized.
|
199 |
+
The parameter is passed to numpy.zeros(). If unspecified, the NumPy
|
200 |
+
default is used.
|
201 |
+
|
202 |
+
order : {'C', 'F'}, optional
|
203 |
+
Whether to store multidimensional data in C- or Fortran-contiguous
|
204 |
+
(row- or column-wise) order in memory. This parameter is passed to
|
205 |
+
numpy.zeros(). If unspecified, the NumPy default is used.
|
206 |
+
|
207 |
+
Returns
|
208 |
+
-------
|
209 |
+
M : 2D NumPy ndarray
|
210 |
+
The attribute matrix.
|
211 |
+
|
212 |
+
ordering : list
|
213 |
+
If `rc_order` was specified, then only the attribute matrix is returned.
|
214 |
+
However, if `rc_order` was None, then the ordering used to construct
|
215 |
+
the matrix is returned as well.
|
216 |
+
|
217 |
+
Examples
|
218 |
+
--------
|
219 |
+
Construct an adjacency matrix:
|
220 |
+
|
221 |
+
>>> G = nx.Graph()
|
222 |
+
>>> G.add_edge(0, 1, thickness=1, weight=3)
|
223 |
+
>>> G.add_edge(0, 2, thickness=2)
|
224 |
+
>>> G.add_edge(1, 2, thickness=3)
|
225 |
+
>>> nx.attr_matrix(G, rc_order=[0, 1, 2])
|
226 |
+
array([[0., 1., 1.],
|
227 |
+
[1., 0., 1.],
|
228 |
+
[1., 1., 0.]])
|
229 |
+
|
230 |
+
Alternatively, we can obtain the matrix describing edge thickness.
|
231 |
+
|
232 |
+
>>> nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
|
233 |
+
array([[0., 1., 2.],
|
234 |
+
[1., 0., 3.],
|
235 |
+
[2., 3., 0.]])
|
236 |
+
|
237 |
+
We can also color the nodes and ask for the probability distribution over
|
238 |
+
all edges (u,v) describing:
|
239 |
+
|
240 |
+
Pr(v has color Y | u has color X)
|
241 |
+
|
242 |
+
>>> G.nodes[0]["color"] = "red"
|
243 |
+
>>> G.nodes[1]["color"] = "red"
|
244 |
+
>>> G.nodes[2]["color"] = "blue"
|
245 |
+
>>> rc = ["red", "blue"]
|
246 |
+
>>> nx.attr_matrix(G, node_attr="color", normalized=True, rc_order=rc)
|
247 |
+
array([[0.33333333, 0.66666667],
|
248 |
+
[1. , 0. ]])
|
249 |
+
|
250 |
+
For example, the above tells us that for all edges (u,v):
|
251 |
+
|
252 |
+
Pr( v is red | u is red) = 1/3
|
253 |
+
Pr( v is blue | u is red) = 2/3
|
254 |
+
|
255 |
+
Pr( v is red | u is blue) = 1
|
256 |
+
Pr( v is blue | u is blue) = 0
|
257 |
+
|
258 |
+
Finally, we can obtain the total weights listed by the node colors.
|
259 |
+
|
260 |
+
>>> nx.attr_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
|
261 |
+
array([[3., 2.],
|
262 |
+
[2., 0.]])
|
263 |
+
|
264 |
+
Thus, the total weight over all edges (u,v) with u and v having colors:
|
265 |
+
|
266 |
+
(red, red) is 3 # the sole contribution is from edge (0,1)
|
267 |
+
(red, blue) is 2 # contributions from edges (0,2) and (1,2)
|
268 |
+
(blue, red) is 2 # same as (red, blue) since graph is undirected
|
269 |
+
(blue, blue) is 0 # there are no edges with blue endpoints
|
270 |
+
|
271 |
+
"""
|
272 |
+
import numpy as np
|
273 |
+
|
274 |
+
edge_value = _edge_value(G, edge_attr)
|
275 |
+
node_value = _node_value(G, node_attr)
|
276 |
+
|
277 |
+
if rc_order is None:
|
278 |
+
ordering = list({node_value(n) for n in G})
|
279 |
+
else:
|
280 |
+
ordering = rc_order
|
281 |
+
|
282 |
+
N = len(ordering)
|
283 |
+
undirected = not G.is_directed()
|
284 |
+
index = dict(zip(ordering, range(N)))
|
285 |
+
M = np.zeros((N, N), dtype=dtype, order=order)
|
286 |
+
|
287 |
+
seen = set()
|
288 |
+
for u, nbrdict in G.adjacency():
|
289 |
+
for v in nbrdict:
|
290 |
+
# Obtain the node attribute values.
|
291 |
+
i, j = index[node_value(u)], index[node_value(v)]
|
292 |
+
if v not in seen:
|
293 |
+
M[i, j] += edge_value(u, v)
|
294 |
+
if undirected:
|
295 |
+
M[j, i] = M[i, j]
|
296 |
+
|
297 |
+
if undirected:
|
298 |
+
seen.add(u)
|
299 |
+
|
300 |
+
if normalized:
|
301 |
+
M /= M.sum(axis=1).reshape((N, 1))
|
302 |
+
|
303 |
+
if rc_order is None:
|
304 |
+
return M, ordering
|
305 |
+
else:
|
306 |
+
return M
|
307 |
+
|
308 |
+
|
309 |
+
@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
|
310 |
+
def attr_sparse_matrix(
|
311 |
+
G, edge_attr=None, node_attr=None, normalized=False, rc_order=None, dtype=None
|
312 |
+
):
|
313 |
+
"""Returns a SciPy sparse array using attributes from G.
|
314 |
+
|
315 |
+
If only `G` is passed in, then the adjacency matrix is constructed.
|
316 |
+
|
317 |
+
Let A be a discrete set of values for the node attribute `node_attr`. Then
|
318 |
+
the elements of A represent the rows and columns of the constructed matrix.
|
319 |
+
Now, iterate through every edge e=(u,v) in `G` and consider the value
|
320 |
+
of the edge attribute `edge_attr`. If ua and va are the values of the
|
321 |
+
node attribute `node_attr` for u and v, respectively, then the value of
|
322 |
+
the edge attribute is added to the matrix element at (ua, va).
|
323 |
+
|
324 |
+
Parameters
|
325 |
+
----------
|
326 |
+
G : graph
|
327 |
+
The NetworkX graph used to construct the NumPy matrix.
|
328 |
+
|
329 |
+
edge_attr : str, optional
|
330 |
+
Each element of the matrix represents a running total of the
|
331 |
+
specified edge attribute for edges whose node attributes correspond
|
332 |
+
to the rows/cols of the matrix. The attribute must be present for
|
333 |
+
all edges in the graph. If no attribute is specified, then we
|
334 |
+
just count the number of edges whose node attributes correspond
|
335 |
+
to the matrix element.
|
336 |
+
|
337 |
+
node_attr : str, optional
|
338 |
+
Each row and column in the matrix represents a particular value
|
339 |
+
of the node attribute. The attribute must be present for all nodes
|
340 |
+
in the graph. Note, the values of this attribute should be reliably
|
341 |
+
hashable. So, float values are not recommended. If no attribute is
|
342 |
+
specified, then the rows and columns will be the nodes of the graph.
|
343 |
+
|
344 |
+
normalized : bool, optional
|
345 |
+
If True, then each row is normalized by the summation of its values.
|
346 |
+
|
347 |
+
rc_order : list, optional
|
348 |
+
A list of the node attribute values. This list specifies the ordering
|
349 |
+
of rows and columns of the array. If no ordering is provided, then
|
350 |
+
the ordering will be random (and also, a return value).
|
351 |
+
|
352 |
+
Other Parameters
|
353 |
+
----------------
|
354 |
+
dtype : NumPy data-type, optional
|
355 |
+
A valid NumPy dtype used to initialize the array. Keep in mind certain
|
356 |
+
dtypes can yield unexpected results if the array is to be normalized.
|
357 |
+
The parameter is passed to numpy.zeros(). If unspecified, the NumPy
|
358 |
+
default is used.
|
359 |
+
|
360 |
+
Returns
|
361 |
+
-------
|
362 |
+
M : SciPy sparse array
|
363 |
+
The attribute matrix.
|
364 |
+
|
365 |
+
ordering : list
|
366 |
+
If `rc_order` was specified, then only the matrix is returned.
|
367 |
+
However, if `rc_order` was None, then the ordering used to construct
|
368 |
+
the matrix is returned as well.
|
369 |
+
|
370 |
+
Examples
|
371 |
+
--------
|
372 |
+
Construct an adjacency matrix:
|
373 |
+
|
374 |
+
>>> G = nx.Graph()
|
375 |
+
>>> G.add_edge(0, 1, thickness=1, weight=3)
|
376 |
+
>>> G.add_edge(0, 2, thickness=2)
|
377 |
+
>>> G.add_edge(1, 2, thickness=3)
|
378 |
+
>>> M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2])
|
379 |
+
>>> M.toarray()
|
380 |
+
array([[0., 1., 1.],
|
381 |
+
[1., 0., 1.],
|
382 |
+
[1., 1., 0.]])
|
383 |
+
|
384 |
+
Alternatively, we can obtain the matrix describing edge thickness.
|
385 |
+
|
386 |
+
>>> M = nx.attr_sparse_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
|
387 |
+
>>> M.toarray()
|
388 |
+
array([[0., 1., 2.],
|
389 |
+
[1., 0., 3.],
|
390 |
+
[2., 3., 0.]])
|
391 |
+
|
392 |
+
We can also color the nodes and ask for the probability distribution over
|
393 |
+
all edges (u,v) describing:
|
394 |
+
|
395 |
+
Pr(v has color Y | u has color X)
|
396 |
+
|
397 |
+
>>> G.nodes[0]["color"] = "red"
|
398 |
+
>>> G.nodes[1]["color"] = "red"
|
399 |
+
>>> G.nodes[2]["color"] = "blue"
|
400 |
+
>>> rc = ["red", "blue"]
|
401 |
+
>>> M = nx.attr_sparse_matrix(G, node_attr="color", normalized=True, rc_order=rc)
|
402 |
+
>>> M.toarray()
|
403 |
+
array([[0.33333333, 0.66666667],
|
404 |
+
[1. , 0. ]])
|
405 |
+
|
406 |
+
For example, the above tells us that for all edges (u,v):
|
407 |
+
|
408 |
+
Pr( v is red | u is red) = 1/3
|
409 |
+
Pr( v is blue | u is red) = 2/3
|
410 |
+
|
411 |
+
Pr( v is red | u is blue) = 1
|
412 |
+
Pr( v is blue | u is blue) = 0
|
413 |
+
|
414 |
+
Finally, we can obtain the total weights listed by the node colors.
|
415 |
+
|
416 |
+
>>> M = nx.attr_sparse_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
|
417 |
+
>>> M.toarray()
|
418 |
+
array([[3., 2.],
|
419 |
+
[2., 0.]])
|
420 |
+
|
421 |
+
Thus, the total weight over all edges (u,v) with u and v having colors:
|
422 |
+
|
423 |
+
(red, red) is 3 # the sole contribution is from edge (0,1)
|
424 |
+
(red, blue) is 2 # contributions from edges (0,2) and (1,2)
|
425 |
+
(blue, red) is 2 # same as (red, blue) since graph is undirected
|
426 |
+
(blue, blue) is 0 # there are no edges with blue endpoints
|
427 |
+
|
428 |
+
"""
|
429 |
+
import numpy as np
|
430 |
+
import scipy as sp
|
431 |
+
|
432 |
+
edge_value = _edge_value(G, edge_attr)
|
433 |
+
node_value = _node_value(G, node_attr)
|
434 |
+
|
435 |
+
if rc_order is None:
|
436 |
+
ordering = list({node_value(n) for n in G})
|
437 |
+
else:
|
438 |
+
ordering = rc_order
|
439 |
+
|
440 |
+
N = len(ordering)
|
441 |
+
undirected = not G.is_directed()
|
442 |
+
index = dict(zip(ordering, range(N)))
|
443 |
+
M = sp.sparse.lil_array((N, N), dtype=dtype)
|
444 |
+
|
445 |
+
seen = set()
|
446 |
+
for u, nbrdict in G.adjacency():
|
447 |
+
for v in nbrdict:
|
448 |
+
# Obtain the node attribute values.
|
449 |
+
i, j = index[node_value(u)], index[node_value(v)]
|
450 |
+
if v not in seen:
|
451 |
+
M[i, j] += edge_value(u, v)
|
452 |
+
if undirected:
|
453 |
+
M[j, i] = M[i, j]
|
454 |
+
|
455 |
+
if undirected:
|
456 |
+
seen.add(u)
|
457 |
+
|
458 |
+
if normalized:
|
459 |
+
M *= 1 / M.sum(axis=1)[:, np.newaxis] # in-place mult preserves sparse
|
460 |
+
|
461 |
+
if rc_order is None:
|
462 |
+
return M, ordering
|
463 |
+
else:
|
464 |
+
return M
|
venv/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Bethe Hessian or deformed Laplacian matrix of graphs."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.utils import not_implemented_for
|
4 |
+
|
5 |
+
__all__ = ["bethe_hessian_matrix"]
|
6 |
+
|
7 |
+
|
8 |
+
@not_implemented_for("directed")
|
9 |
+
@not_implemented_for("multigraph")
|
10 |
+
@nx._dispatchable
|
11 |
+
def bethe_hessian_matrix(G, r=None, nodelist=None):
|
12 |
+
r"""Returns the Bethe Hessian matrix of G.
|
13 |
+
|
14 |
+
The Bethe Hessian is a family of matrices parametrized by r, defined as
|
15 |
+
H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the
|
16 |
+
diagonal matrix of node degrees, and I is the identify matrix. It is equal
|
17 |
+
to the graph laplacian when the regularizer r = 1.
|
18 |
+
|
19 |
+
The default choice of regularizer should be the ratio [2]_
|
20 |
+
|
21 |
+
.. math::
|
22 |
+
r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1
|
23 |
+
|
24 |
+
Parameters
|
25 |
+
----------
|
26 |
+
G : Graph
|
27 |
+
A NetworkX graph
|
28 |
+
r : float
|
29 |
+
Regularizer parameter
|
30 |
+
nodelist : list, optional
|
31 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
32 |
+
If nodelist is None, then the ordering is produced by ``G.nodes()``.
|
33 |
+
|
34 |
+
Returns
|
35 |
+
-------
|
36 |
+
H : scipy.sparse.csr_array
|
37 |
+
The Bethe Hessian matrix of `G`, with parameter `r`.
|
38 |
+
|
39 |
+
Examples
|
40 |
+
--------
|
41 |
+
>>> k = [3, 2, 2, 1, 0]
|
42 |
+
>>> G = nx.havel_hakimi_graph(k)
|
43 |
+
>>> H = nx.bethe_hessian_matrix(G)
|
44 |
+
>>> H.toarray()
|
45 |
+
array([[ 3.5625, -1.25 , -1.25 , -1.25 , 0. ],
|
46 |
+
[-1.25 , 2.5625, -1.25 , 0. , 0. ],
|
47 |
+
[-1.25 , -1.25 , 2.5625, 0. , 0. ],
|
48 |
+
[-1.25 , 0. , 0. , 1.5625, 0. ],
|
49 |
+
[ 0. , 0. , 0. , 0. , 0.5625]])
|
50 |
+
|
51 |
+
See Also
|
52 |
+
--------
|
53 |
+
bethe_hessian_spectrum
|
54 |
+
adjacency_matrix
|
55 |
+
laplacian_matrix
|
56 |
+
|
57 |
+
References
|
58 |
+
----------
|
59 |
+
.. [1] A. Saade, F. Krzakala and L. Zdeborová
|
60 |
+
"Spectral Clustering of Graphs with the Bethe Hessian",
|
61 |
+
Advances in Neural Information Processing Systems, 2014.
|
62 |
+
.. [2] C. M. Le, E. Levina
|
63 |
+
"Estimating the number of communities in networks by spectral methods"
|
64 |
+
arXiv:1507.00827, 2015.
|
65 |
+
"""
|
66 |
+
import scipy as sp
|
67 |
+
|
68 |
+
if nodelist is None:
|
69 |
+
nodelist = list(G)
|
70 |
+
if r is None:
|
71 |
+
r = sum(d**2 for v, d in nx.degree(G)) / sum(d for v, d in nx.degree(G)) - 1
|
72 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, format="csr")
|
73 |
+
n, m = A.shape
|
74 |
+
# TODO: Rm csr_array wrapper when spdiags array creation becomes available
|
75 |
+
D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, m, n, format="csr"))
|
76 |
+
# TODO: Rm csr_array wrapper when eye array creation becomes available
|
77 |
+
I = sp.sparse.csr_array(sp.sparse.eye(m, n, format="csr"))
|
78 |
+
return (r**2 - 1) * I - r * A + D
|
venv/lib/python3.10/site-packages/networkx/linalg/graphmatrix.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Adjacency matrix and incidence matrix of graphs.
|
3 |
+
"""
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
__all__ = ["incidence_matrix", "adjacency_matrix"]
|
7 |
+
|
8 |
+
|
9 |
+
@nx._dispatchable(edge_attrs="weight")
|
10 |
+
def incidence_matrix(
|
11 |
+
G, nodelist=None, edgelist=None, oriented=False, weight=None, *, dtype=None
|
12 |
+
):
|
13 |
+
"""Returns incidence matrix of G.
|
14 |
+
|
15 |
+
The incidence matrix assigns each row to a node and each column to an edge.
|
16 |
+
For a standard incidence matrix a 1 appears wherever a row's node is
|
17 |
+
incident on the column's edge. For an oriented incidence matrix each
|
18 |
+
edge is assigned an orientation (arbitrarily for undirected and aligning to
|
19 |
+
direction for directed). A -1 appears for the source (tail) of an edge and
|
20 |
+
1 for the destination (head) of the edge. The elements are zero otherwise.
|
21 |
+
|
22 |
+
Parameters
|
23 |
+
----------
|
24 |
+
G : graph
|
25 |
+
A NetworkX graph
|
26 |
+
|
27 |
+
nodelist : list, optional (default= all nodes in G)
|
28 |
+
The rows are ordered according to the nodes in nodelist.
|
29 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
30 |
+
|
31 |
+
edgelist : list, optional (default= all edges in G)
|
32 |
+
The columns are ordered according to the edges in edgelist.
|
33 |
+
If edgelist is None, then the ordering is produced by G.edges().
|
34 |
+
|
35 |
+
oriented: bool, optional (default=False)
|
36 |
+
If True, matrix elements are +1 or -1 for the head or tail node
|
37 |
+
respectively of each edge. If False, +1 occurs at both nodes.
|
38 |
+
|
39 |
+
weight : string or None, optional (default=None)
|
40 |
+
The edge data key used to provide each value in the matrix.
|
41 |
+
If None, then each edge has weight 1. Edge weights, if used,
|
42 |
+
should be positive so that the orientation can provide the sign.
|
43 |
+
|
44 |
+
dtype : a NumPy dtype or None (default=None)
|
45 |
+
The dtype of the output sparse array. This type should be a compatible
|
46 |
+
type of the weight argument, eg. if weight would return a float this
|
47 |
+
argument should also be a float.
|
48 |
+
If None, then the default for SciPy is used.
|
49 |
+
|
50 |
+
Returns
|
51 |
+
-------
|
52 |
+
A : SciPy sparse array
|
53 |
+
The incidence matrix of G.
|
54 |
+
|
55 |
+
Notes
|
56 |
+
-----
|
57 |
+
For MultiGraph/MultiDiGraph, the edges in edgelist should be
|
58 |
+
(u,v,key) 3-tuples.
|
59 |
+
|
60 |
+
"Networks are the best discrete model for so many problems in
|
61 |
+
applied mathematics" [1]_.
|
62 |
+
|
63 |
+
References
|
64 |
+
----------
|
65 |
+
.. [1] Gil Strang, Network applications: A = incidence matrix,
|
66 |
+
http://videolectures.net/mit18085f07_strang_lec03/
|
67 |
+
"""
|
68 |
+
import scipy as sp
|
69 |
+
|
70 |
+
if nodelist is None:
|
71 |
+
nodelist = list(G)
|
72 |
+
if edgelist is None:
|
73 |
+
if G.is_multigraph():
|
74 |
+
edgelist = list(G.edges(keys=True))
|
75 |
+
else:
|
76 |
+
edgelist = list(G.edges())
|
77 |
+
A = sp.sparse.lil_array((len(nodelist), len(edgelist)), dtype=dtype)
|
78 |
+
node_index = {node: i for i, node in enumerate(nodelist)}
|
79 |
+
for ei, e in enumerate(edgelist):
|
80 |
+
(u, v) = e[:2]
|
81 |
+
if u == v:
|
82 |
+
continue # self loops give zero column
|
83 |
+
try:
|
84 |
+
ui = node_index[u]
|
85 |
+
vi = node_index[v]
|
86 |
+
except KeyError as err:
|
87 |
+
raise nx.NetworkXError(
|
88 |
+
f"node {u} or {v} in edgelist but not in nodelist"
|
89 |
+
) from err
|
90 |
+
if weight is None:
|
91 |
+
wt = 1
|
92 |
+
else:
|
93 |
+
if G.is_multigraph():
|
94 |
+
ekey = e[2]
|
95 |
+
wt = G[u][v][ekey].get(weight, 1)
|
96 |
+
else:
|
97 |
+
wt = G[u][v].get(weight, 1)
|
98 |
+
if oriented:
|
99 |
+
A[ui, ei] = -wt
|
100 |
+
A[vi, ei] = wt
|
101 |
+
else:
|
102 |
+
A[ui, ei] = wt
|
103 |
+
A[vi, ei] = wt
|
104 |
+
return A.asformat("csc")
|
105 |
+
|
106 |
+
|
107 |
+
@nx._dispatchable(edge_attrs="weight")
|
108 |
+
def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"):
|
109 |
+
"""Returns adjacency matrix of G.
|
110 |
+
|
111 |
+
Parameters
|
112 |
+
----------
|
113 |
+
G : graph
|
114 |
+
A NetworkX graph
|
115 |
+
|
116 |
+
nodelist : list, optional
|
117 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
118 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
119 |
+
|
120 |
+
dtype : NumPy data-type, optional
|
121 |
+
The desired data-type for the array.
|
122 |
+
If None, then the NumPy default is used.
|
123 |
+
|
124 |
+
weight : string or None, optional (default='weight')
|
125 |
+
The edge data key used to provide each value in the matrix.
|
126 |
+
If None, then each edge has weight 1.
|
127 |
+
|
128 |
+
Returns
|
129 |
+
-------
|
130 |
+
A : SciPy sparse array
|
131 |
+
Adjacency matrix representation of G.
|
132 |
+
|
133 |
+
Notes
|
134 |
+
-----
|
135 |
+
For directed graphs, entry i,j corresponds to an edge from i to j.
|
136 |
+
|
137 |
+
If you want a pure Python adjacency matrix representation try
|
138 |
+
networkx.convert.to_dict_of_dicts which will return a
|
139 |
+
dictionary-of-dictionaries format that can be addressed as a
|
140 |
+
sparse matrix.
|
141 |
+
|
142 |
+
For MultiGraph/MultiDiGraph with parallel edges the weights are summed.
|
143 |
+
See `to_numpy_array` for other options.
|
144 |
+
|
145 |
+
The convention used for self-loop edges in graphs is to assign the
|
146 |
+
diagonal matrix entry value to the edge weight attribute
|
147 |
+
(or the number 1 if the edge has no weight attribute). If the
|
148 |
+
alternate convention of doubling the edge weight is desired the
|
149 |
+
resulting SciPy sparse array can be modified as follows:
|
150 |
+
|
151 |
+
>>> G = nx.Graph([(1, 1)])
|
152 |
+
>>> A = nx.adjacency_matrix(G)
|
153 |
+
>>> print(A.todense())
|
154 |
+
[[1]]
|
155 |
+
>>> A.setdiag(A.diagonal() * 2)
|
156 |
+
>>> print(A.todense())
|
157 |
+
[[2]]
|
158 |
+
|
159 |
+
See Also
|
160 |
+
--------
|
161 |
+
to_numpy_array
|
162 |
+
to_scipy_sparse_array
|
163 |
+
to_dict_of_dicts
|
164 |
+
adjacency_spectrum
|
165 |
+
"""
|
166 |
+
return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight)
|
venv/lib/python3.10/site-packages/networkx/linalg/laplacianmatrix.py
ADDED
@@ -0,0 +1,616 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Laplacian matrix of graphs.
|
2 |
+
|
3 |
+
All calculations here are done using the out-degree. For Laplacians using
|
4 |
+
in-degree, use `G.reverse(copy=False)` instead of `G` and take the transpose.
|
5 |
+
|
6 |
+
The `laplacian_matrix` function provides an unnormalized matrix,
|
7 |
+
while `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
|
8 |
+
and `directed_combinatorial_laplacian_matrix` are all normalized.
|
9 |
+
"""
|
10 |
+
import networkx as nx
|
11 |
+
from networkx.utils import not_implemented_for
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
"laplacian_matrix",
|
15 |
+
"normalized_laplacian_matrix",
|
16 |
+
"total_spanning_tree_weight",
|
17 |
+
"directed_laplacian_matrix",
|
18 |
+
"directed_combinatorial_laplacian_matrix",
|
19 |
+
]
|
20 |
+
|
21 |
+
|
22 |
+
@nx._dispatchable(edge_attrs="weight")
|
23 |
+
def laplacian_matrix(G, nodelist=None, weight="weight"):
|
24 |
+
"""Returns the Laplacian matrix of G.
|
25 |
+
|
26 |
+
The graph Laplacian is the matrix L = D - A, where
|
27 |
+
A is the adjacency matrix and D is the diagonal matrix of node degrees.
|
28 |
+
|
29 |
+
Parameters
|
30 |
+
----------
|
31 |
+
G : graph
|
32 |
+
A NetworkX graph
|
33 |
+
|
34 |
+
nodelist : list, optional
|
35 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
36 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
37 |
+
|
38 |
+
weight : string or None, optional (default='weight')
|
39 |
+
The edge data key used to compute each value in the matrix.
|
40 |
+
If None, then each edge has weight 1.
|
41 |
+
|
42 |
+
Returns
|
43 |
+
-------
|
44 |
+
L : SciPy sparse array
|
45 |
+
The Laplacian matrix of G.
|
46 |
+
|
47 |
+
Notes
|
48 |
+
-----
|
49 |
+
For MultiGraph, the edges weights are summed.
|
50 |
+
|
51 |
+
This returns an unnormalized matrix. For a normalized output,
|
52 |
+
use `normalized_laplacian_matrix`, `directed_laplacian_matrix`,
|
53 |
+
or `directed_combinatorial_laplacian_matrix`.
|
54 |
+
|
55 |
+
This calculation uses the out-degree of the graph `G`. To use the
|
56 |
+
in-degree for calculations instead, use `G.reverse(copy=False)` and
|
57 |
+
take the transpose.
|
58 |
+
|
59 |
+
See Also
|
60 |
+
--------
|
61 |
+
:func:`~networkx.convert_matrix.to_numpy_array`
|
62 |
+
normalized_laplacian_matrix
|
63 |
+
directed_laplacian_matrix
|
64 |
+
directed_combinatorial_laplacian_matrix
|
65 |
+
:func:`~networkx.linalg.spectrum.laplacian_spectrum`
|
66 |
+
|
67 |
+
Examples
|
68 |
+
--------
|
69 |
+
For graphs with multiple connected components, L is permutation-similar
|
70 |
+
to a block diagonal matrix where each block is the respective Laplacian
|
71 |
+
matrix for each component.
|
72 |
+
|
73 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
|
74 |
+
>>> print(nx.laplacian_matrix(G).toarray())
|
75 |
+
[[ 1 -1 0 0 0]
|
76 |
+
[-1 2 -1 0 0]
|
77 |
+
[ 0 -1 1 0 0]
|
78 |
+
[ 0 0 0 1 -1]
|
79 |
+
[ 0 0 0 -1 1]]
|
80 |
+
|
81 |
+
>>> edges = [
|
82 |
+
... (1, 2),
|
83 |
+
... (2, 1),
|
84 |
+
... (2, 4),
|
85 |
+
... (4, 3),
|
86 |
+
... (3, 4),
|
87 |
+
... ]
|
88 |
+
>>> DiG = nx.DiGraph(edges)
|
89 |
+
>>> print(nx.laplacian_matrix(DiG).toarray())
|
90 |
+
[[ 1 -1 0 0]
|
91 |
+
[-1 2 -1 0]
|
92 |
+
[ 0 0 1 -1]
|
93 |
+
[ 0 0 -1 1]]
|
94 |
+
|
95 |
+
Notice that node 4 is represented by the third column and row. This is because
|
96 |
+
by default the row/column order is the order of `G.nodes` (i.e. the node added
|
97 |
+
order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
|
98 |
+
To control the node order of the matrix, use the `nodelist` argument.
|
99 |
+
|
100 |
+
>>> print(nx.laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
|
101 |
+
[[ 1 -1 0 0]
|
102 |
+
[-1 2 0 -1]
|
103 |
+
[ 0 0 1 -1]
|
104 |
+
[ 0 0 -1 1]]
|
105 |
+
|
106 |
+
This calculation uses the out-degree of the graph `G`. To use the
|
107 |
+
in-degree for calculations instead, use `G.reverse(copy=False)` and
|
108 |
+
take the transpose.
|
109 |
+
|
110 |
+
>>> print(nx.laplacian_matrix(DiG.reverse(copy=False)).toarray().T)
|
111 |
+
[[ 1 -1 0 0]
|
112 |
+
[-1 1 -1 0]
|
113 |
+
[ 0 0 2 -1]
|
114 |
+
[ 0 0 -1 1]]
|
115 |
+
|
116 |
+
References
|
117 |
+
----------
|
118 |
+
.. [1] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
|
119 |
+
The Science of Search Engine Rankings. Princeton University Press, 2006.
|
120 |
+
|
121 |
+
"""
|
122 |
+
import scipy as sp
|
123 |
+
|
124 |
+
if nodelist is None:
|
125 |
+
nodelist = list(G)
|
126 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
|
127 |
+
n, m = A.shape
|
128 |
+
# TODO: rm csr_array wrapper when spdiags can produce arrays
|
129 |
+
D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, m, n, format="csr"))
|
130 |
+
return D - A
|
131 |
+
|
132 |
+
|
133 |
+
@nx._dispatchable(edge_attrs="weight")
|
134 |
+
def normalized_laplacian_matrix(G, nodelist=None, weight="weight"):
|
135 |
+
r"""Returns the normalized Laplacian matrix of G.
|
136 |
+
|
137 |
+
The normalized graph Laplacian is the matrix
|
138 |
+
|
139 |
+
.. math::
|
140 |
+
|
141 |
+
N = D^{-1/2} L D^{-1/2}
|
142 |
+
|
143 |
+
where `L` is the graph Laplacian and `D` is the diagonal matrix of
|
144 |
+
node degrees [1]_.
|
145 |
+
|
146 |
+
Parameters
|
147 |
+
----------
|
148 |
+
G : graph
|
149 |
+
A NetworkX graph
|
150 |
+
|
151 |
+
nodelist : list, optional
|
152 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
153 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
154 |
+
|
155 |
+
weight : string or None, optional (default='weight')
|
156 |
+
The edge data key used to compute each value in the matrix.
|
157 |
+
If None, then each edge has weight 1.
|
158 |
+
|
159 |
+
Returns
|
160 |
+
-------
|
161 |
+
N : SciPy sparse array
|
162 |
+
The normalized Laplacian matrix of G.
|
163 |
+
|
164 |
+
Notes
|
165 |
+
-----
|
166 |
+
For MultiGraph, the edges weights are summed.
|
167 |
+
See :func:`to_numpy_array` for other options.
|
168 |
+
|
169 |
+
If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is
|
170 |
+
the adjacency matrix [2]_.
|
171 |
+
|
172 |
+
This calculation uses the out-degree of the graph `G`. To use the
|
173 |
+
in-degree for calculations instead, use `G.reverse(copy=False)` and
|
174 |
+
take the transpose.
|
175 |
+
|
176 |
+
For an unnormalized output, use `laplacian_matrix`.
|
177 |
+
|
178 |
+
Examples
|
179 |
+
--------
|
180 |
+
|
181 |
+
>>> import numpy as np
|
182 |
+
>>> edges = [
|
183 |
+
... (1, 2),
|
184 |
+
... (2, 1),
|
185 |
+
... (2, 4),
|
186 |
+
... (4, 3),
|
187 |
+
... (3, 4),
|
188 |
+
... ]
|
189 |
+
>>> DiG = nx.DiGraph(edges)
|
190 |
+
>>> print(nx.normalized_laplacian_matrix(DiG).toarray())
|
191 |
+
[[ 1. -0.70710678 0. 0. ]
|
192 |
+
[-0.70710678 1. -0.70710678 0. ]
|
193 |
+
[ 0. 0. 1. -1. ]
|
194 |
+
[ 0. 0. -1. 1. ]]
|
195 |
+
|
196 |
+
Notice that node 4 is represented by the third column and row. This is because
|
197 |
+
by default the row/column order is the order of `G.nodes` (i.e. the node added
|
198 |
+
order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
|
199 |
+
To control the node order of the matrix, use the `nodelist` argument.
|
200 |
+
|
201 |
+
>>> print(nx.normalized_laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
|
202 |
+
[[ 1. -0.70710678 0. 0. ]
|
203 |
+
[-0.70710678 1. 0. -0.70710678]
|
204 |
+
[ 0. 0. 1. -1. ]
|
205 |
+
[ 0. 0. -1. 1. ]]
|
206 |
+
>>> G = nx.Graph(edges)
|
207 |
+
>>> print(nx.normalized_laplacian_matrix(G).toarray())
|
208 |
+
[[ 1. -0.70710678 0. 0. ]
|
209 |
+
[-0.70710678 1. -0.5 0. ]
|
210 |
+
[ 0. -0.5 1. -0.70710678]
|
211 |
+
[ 0. 0. -0.70710678 1. ]]
|
212 |
+
|
213 |
+
See Also
|
214 |
+
--------
|
215 |
+
laplacian_matrix
|
216 |
+
normalized_laplacian_spectrum
|
217 |
+
directed_laplacian_matrix
|
218 |
+
directed_combinatorial_laplacian_matrix
|
219 |
+
|
220 |
+
References
|
221 |
+
----------
|
222 |
+
.. [1] Fan Chung-Graham, Spectral Graph Theory,
|
223 |
+
CBMS Regional Conference Series in Mathematics, Number 92, 1997.
|
224 |
+
.. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized
|
225 |
+
Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98,
|
226 |
+
March 2007.
|
227 |
+
.. [3] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
|
228 |
+
The Science of Search Engine Rankings. Princeton University Press, 2006.
|
229 |
+
"""
|
230 |
+
import numpy as np
|
231 |
+
import scipy as sp
|
232 |
+
|
233 |
+
if nodelist is None:
|
234 |
+
nodelist = list(G)
|
235 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
|
236 |
+
n, _ = A.shape
|
237 |
+
diags = A.sum(axis=1)
|
238 |
+
# TODO: rm csr_array wrapper when spdiags can produce arrays
|
239 |
+
D = sp.sparse.csr_array(sp.sparse.spdiags(diags, 0, n, n, format="csr"))
|
240 |
+
L = D - A
|
241 |
+
with np.errstate(divide="ignore"):
|
242 |
+
diags_sqrt = 1.0 / np.sqrt(diags)
|
243 |
+
diags_sqrt[np.isinf(diags_sqrt)] = 0
|
244 |
+
# TODO: rm csr_array wrapper when spdiags can produce arrays
|
245 |
+
DH = sp.sparse.csr_array(sp.sparse.spdiags(diags_sqrt, 0, n, n, format="csr"))
|
246 |
+
return DH @ (L @ DH)
|
247 |
+
|
248 |
+
|
249 |
+
@nx._dispatchable(edge_attrs="weight")
|
250 |
+
def total_spanning_tree_weight(G, weight=None, root=None):
|
251 |
+
"""
|
252 |
+
Returns the total weight of all spanning trees of `G`.
|
253 |
+
|
254 |
+
Kirchoff's Tree Matrix Theorem [1]_, [2]_ states that the determinant of any
|
255 |
+
cofactor of the Laplacian matrix of a graph is the number of spanning trees
|
256 |
+
in the graph. For a weighted Laplacian matrix, it is the sum across all
|
257 |
+
spanning trees of the multiplicative weight of each tree. That is, the
|
258 |
+
weight of each tree is the product of its edge weights.
|
259 |
+
|
260 |
+
For unweighted graphs, the total weight equals the number of spanning trees in `G`.
|
261 |
+
|
262 |
+
For directed graphs, the total weight follows by summing over all directed
|
263 |
+
spanning trees in `G` that start in the `root` node [3]_.
|
264 |
+
|
265 |
+
.. deprecated:: 3.3
|
266 |
+
|
267 |
+
``total_spanning_tree_weight`` is deprecated and will be removed in v3.5.
|
268 |
+
Use ``nx.number_of_spanning_trees(G)`` instead.
|
269 |
+
|
270 |
+
Parameters
|
271 |
+
----------
|
272 |
+
G : NetworkX Graph
|
273 |
+
|
274 |
+
weight : string or None, optional (default=None)
|
275 |
+
The key for the edge attribute holding the edge weight.
|
276 |
+
If None, then each edge has weight 1.
|
277 |
+
|
278 |
+
root : node (only required for directed graphs)
|
279 |
+
A node in the directed graph `G`.
|
280 |
+
|
281 |
+
Returns
|
282 |
+
-------
|
283 |
+
total_weight : float
|
284 |
+
Undirected graphs:
|
285 |
+
The sum of the total multiplicative weights for all spanning trees in `G`.
|
286 |
+
Directed graphs:
|
287 |
+
The sum of the total multiplicative weights for all spanning trees of `G`,
|
288 |
+
rooted at node `root`.
|
289 |
+
|
290 |
+
Raises
|
291 |
+
------
|
292 |
+
NetworkXPointlessConcept
|
293 |
+
If `G` does not contain any nodes.
|
294 |
+
|
295 |
+
NetworkXError
|
296 |
+
If the graph `G` is not (weakly) connected,
|
297 |
+
or if `G` is directed and the root node is not specified or not in G.
|
298 |
+
|
299 |
+
Examples
|
300 |
+
--------
|
301 |
+
>>> G = nx.complete_graph(5)
|
302 |
+
>>> round(nx.total_spanning_tree_weight(G))
|
303 |
+
125
|
304 |
+
|
305 |
+
>>> G = nx.Graph()
|
306 |
+
>>> G.add_edge(1, 2, weight=2)
|
307 |
+
>>> G.add_edge(1, 3, weight=1)
|
308 |
+
>>> G.add_edge(2, 3, weight=1)
|
309 |
+
>>> round(nx.total_spanning_tree_weight(G, "weight"))
|
310 |
+
5
|
311 |
+
|
312 |
+
Notes
|
313 |
+
-----
|
314 |
+
Self-loops are excluded. Multi-edges are contracted in one edge
|
315 |
+
equal to the sum of the weights.
|
316 |
+
|
317 |
+
References
|
318 |
+
----------
|
319 |
+
.. [1] Wikipedia
|
320 |
+
"Kirchhoff's theorem."
|
321 |
+
https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem
|
322 |
+
.. [2] Kirchhoff, G. R.
|
323 |
+
Über die Auflösung der Gleichungen, auf welche man
|
324 |
+
bei der Untersuchung der linearen Vertheilung
|
325 |
+
Galvanischer Ströme geführt wird
|
326 |
+
Annalen der Physik und Chemie, vol. 72, pp. 497-508, 1847.
|
327 |
+
.. [3] Margoliash, J.
|
328 |
+
"Matrix-Tree Theorem for Directed Graphs"
|
329 |
+
https://www.math.uchicago.edu/~may/VIGRE/VIGRE2010/REUPapers/Margoliash.pdf
|
330 |
+
"""
|
331 |
+
import warnings
|
332 |
+
|
333 |
+
warnings.warn(
|
334 |
+
(
|
335 |
+
"\n\ntotal_spanning_tree_weight is deprecated and will be removed in v3.5.\n"
|
336 |
+
"Use `nx.number_of_spanning_trees(G)` instead."
|
337 |
+
),
|
338 |
+
category=DeprecationWarning,
|
339 |
+
stacklevel=3,
|
340 |
+
)
|
341 |
+
|
342 |
+
return nx.number_of_spanning_trees(G, weight=weight, root=root)
|
343 |
+
|
344 |
+
|
345 |
+
###############################################################################
|
346 |
+
# Code based on work from https://github.com/bjedwards
|
347 |
+
|
348 |
+
|
349 |
+
@not_implemented_for("undirected")
|
350 |
+
@not_implemented_for("multigraph")
|
351 |
+
@nx._dispatchable(edge_attrs="weight")
|
352 |
+
def directed_laplacian_matrix(
|
353 |
+
G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
|
354 |
+
):
|
355 |
+
r"""Returns the directed Laplacian matrix of G.
|
356 |
+
|
357 |
+
The graph directed Laplacian is the matrix
|
358 |
+
|
359 |
+
.. math::
|
360 |
+
|
361 |
+
L = I - \frac{1}{2} \left (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} \right )
|
362 |
+
|
363 |
+
where `I` is the identity matrix, `P` is the transition matrix of the
|
364 |
+
graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
|
365 |
+
zeros elsewhere [1]_.
|
366 |
+
|
367 |
+
Depending on the value of walk_type, `P` can be the transition matrix
|
368 |
+
induced by a random walk, a lazy random walk, or a random walk with
|
369 |
+
teleportation (PageRank).
|
370 |
+
|
371 |
+
Parameters
|
372 |
+
----------
|
373 |
+
G : DiGraph
|
374 |
+
A NetworkX graph
|
375 |
+
|
376 |
+
nodelist : list, optional
|
377 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
378 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
379 |
+
|
380 |
+
weight : string or None, optional (default='weight')
|
381 |
+
The edge data key used to compute each value in the matrix.
|
382 |
+
If None, then each edge has weight 1.
|
383 |
+
|
384 |
+
walk_type : string or None, optional (default=None)
|
385 |
+
One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
|
386 |
+
(the default), then a value is selected according to the properties of `G`:
|
387 |
+
- ``walk_type="random"`` if `G` is strongly connected and aperiodic
|
388 |
+
- ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
|
389 |
+
- ``walk_type="pagerank"`` for all other cases.
|
390 |
+
|
391 |
+
alpha : real
|
392 |
+
(1 - alpha) is the teleportation probability used with pagerank
|
393 |
+
|
394 |
+
Returns
|
395 |
+
-------
|
396 |
+
L : NumPy matrix
|
397 |
+
Normalized Laplacian of G.
|
398 |
+
|
399 |
+
Notes
|
400 |
+
-----
|
401 |
+
Only implemented for DiGraphs
|
402 |
+
|
403 |
+
The result is always a symmetric matrix.
|
404 |
+
|
405 |
+
This calculation uses the out-degree of the graph `G`. To use the
|
406 |
+
in-degree for calculations instead, use `G.reverse(copy=False)` and
|
407 |
+
take the transpose.
|
408 |
+
|
409 |
+
See Also
|
410 |
+
--------
|
411 |
+
laplacian_matrix
|
412 |
+
normalized_laplacian_matrix
|
413 |
+
directed_combinatorial_laplacian_matrix
|
414 |
+
|
415 |
+
References
|
416 |
+
----------
|
417 |
+
.. [1] Fan Chung (2005).
|
418 |
+
Laplacians and the Cheeger inequality for directed graphs.
|
419 |
+
Annals of Combinatorics, 9(1), 2005
|
420 |
+
"""
|
421 |
+
import numpy as np
|
422 |
+
import scipy as sp
|
423 |
+
|
424 |
+
# NOTE: P has type ndarray if walk_type=="pagerank", else csr_array
|
425 |
+
P = _transition_matrix(
|
426 |
+
G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
|
427 |
+
)
|
428 |
+
|
429 |
+
n, m = P.shape
|
430 |
+
|
431 |
+
evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
|
432 |
+
v = evecs.flatten().real
|
433 |
+
p = v / v.sum()
|
434 |
+
# p>=0 by Perron-Frobenius Thm. Use abs() to fix roundoff across zero gh-6865
|
435 |
+
sqrtp = np.sqrt(np.abs(p))
|
436 |
+
Q = (
|
437 |
+
# TODO: rm csr_array wrapper when spdiags creates arrays
|
438 |
+
sp.sparse.csr_array(sp.sparse.spdiags(sqrtp, 0, n, n))
|
439 |
+
@ P
|
440 |
+
# TODO: rm csr_array wrapper when spdiags creates arrays
|
441 |
+
@ sp.sparse.csr_array(sp.sparse.spdiags(1.0 / sqrtp, 0, n, n))
|
442 |
+
)
|
443 |
+
# NOTE: This could be sparsified for the non-pagerank cases
|
444 |
+
I = np.identity(len(G))
|
445 |
+
|
446 |
+
return I - (Q + Q.T) / 2.0
|
447 |
+
|
448 |
+
|
449 |
+
@not_implemented_for("undirected")
|
450 |
+
@not_implemented_for("multigraph")
|
451 |
+
@nx._dispatchable(edge_attrs="weight")
|
452 |
+
def directed_combinatorial_laplacian_matrix(
|
453 |
+
G, nodelist=None, weight="weight", walk_type=None, alpha=0.95
|
454 |
+
):
|
455 |
+
r"""Return the directed combinatorial Laplacian matrix of G.
|
456 |
+
|
457 |
+
The graph directed combinatorial Laplacian is the matrix
|
458 |
+
|
459 |
+
.. math::
|
460 |
+
|
461 |
+
L = \Phi - \frac{1}{2} \left (\Phi P + P^T \Phi \right)
|
462 |
+
|
463 |
+
where `P` is the transition matrix of the graph and `\Phi` a matrix
|
464 |
+
with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
|
465 |
+
|
466 |
+
Depending on the value of walk_type, `P` can be the transition matrix
|
467 |
+
induced by a random walk, a lazy random walk, or a random walk with
|
468 |
+
teleportation (PageRank).
|
469 |
+
|
470 |
+
Parameters
|
471 |
+
----------
|
472 |
+
G : DiGraph
|
473 |
+
A NetworkX graph
|
474 |
+
|
475 |
+
nodelist : list, optional
|
476 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
477 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
478 |
+
|
479 |
+
weight : string or None, optional (default='weight')
|
480 |
+
The edge data key used to compute each value in the matrix.
|
481 |
+
If None, then each edge has weight 1.
|
482 |
+
|
483 |
+
walk_type : string or None, optional (default=None)
|
484 |
+
One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
|
485 |
+
(the default), then a value is selected according to the properties of `G`:
|
486 |
+
- ``walk_type="random"`` if `G` is strongly connected and aperiodic
|
487 |
+
- ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
|
488 |
+
- ``walk_type="pagerank"`` for all other cases.
|
489 |
+
|
490 |
+
alpha : real
|
491 |
+
(1 - alpha) is the teleportation probability used with pagerank
|
492 |
+
|
493 |
+
Returns
|
494 |
+
-------
|
495 |
+
L : NumPy matrix
|
496 |
+
Combinatorial Laplacian of G.
|
497 |
+
|
498 |
+
Notes
|
499 |
+
-----
|
500 |
+
Only implemented for DiGraphs
|
501 |
+
|
502 |
+
The result is always a symmetric matrix.
|
503 |
+
|
504 |
+
This calculation uses the out-degree of the graph `G`. To use the
|
505 |
+
in-degree for calculations instead, use `G.reverse(copy=False)` and
|
506 |
+
take the transpose.
|
507 |
+
|
508 |
+
See Also
|
509 |
+
--------
|
510 |
+
laplacian_matrix
|
511 |
+
normalized_laplacian_matrix
|
512 |
+
directed_laplacian_matrix
|
513 |
+
|
514 |
+
References
|
515 |
+
----------
|
516 |
+
.. [1] Fan Chung (2005).
|
517 |
+
Laplacians and the Cheeger inequality for directed graphs.
|
518 |
+
Annals of Combinatorics, 9(1), 2005
|
519 |
+
"""
|
520 |
+
import scipy as sp
|
521 |
+
|
522 |
+
P = _transition_matrix(
|
523 |
+
G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha
|
524 |
+
)
|
525 |
+
|
526 |
+
n, m = P.shape
|
527 |
+
|
528 |
+
evals, evecs = sp.sparse.linalg.eigs(P.T, k=1)
|
529 |
+
v = evecs.flatten().real
|
530 |
+
p = v / v.sum()
|
531 |
+
# NOTE: could be improved by not densifying
|
532 |
+
# TODO: Rm csr_array wrapper when spdiags array creation becomes available
|
533 |
+
Phi = sp.sparse.csr_array(sp.sparse.spdiags(p, 0, n, n)).toarray()
|
534 |
+
|
535 |
+
return Phi - (Phi @ P + P.T @ Phi) / 2.0
|
536 |
+
|
537 |
+
|
538 |
+
def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha=0.95):
|
539 |
+
"""Returns the transition matrix of G.
|
540 |
+
|
541 |
+
This is a row stochastic giving the transition probabilities while
|
542 |
+
performing a random walk on the graph. Depending on the value of walk_type,
|
543 |
+
P can be the transition matrix induced by a random walk, a lazy random walk,
|
544 |
+
or a random walk with teleportation (PageRank).
|
545 |
+
|
546 |
+
Parameters
|
547 |
+
----------
|
548 |
+
G : DiGraph
|
549 |
+
A NetworkX graph
|
550 |
+
|
551 |
+
nodelist : list, optional
|
552 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
553 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
554 |
+
|
555 |
+
weight : string or None, optional (default='weight')
|
556 |
+
The edge data key used to compute each value in the matrix.
|
557 |
+
If None, then each edge has weight 1.
|
558 |
+
|
559 |
+
walk_type : string or None, optional (default=None)
|
560 |
+
One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
|
561 |
+
(the default), then a value is selected according to the properties of `G`:
|
562 |
+
- ``walk_type="random"`` if `G` is strongly connected and aperiodic
|
563 |
+
- ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
|
564 |
+
- ``walk_type="pagerank"`` for all other cases.
|
565 |
+
|
566 |
+
alpha : real
|
567 |
+
(1 - alpha) is the teleportation probability used with pagerank
|
568 |
+
|
569 |
+
Returns
|
570 |
+
-------
|
571 |
+
P : numpy.ndarray
|
572 |
+
transition matrix of G.
|
573 |
+
|
574 |
+
Raises
|
575 |
+
------
|
576 |
+
NetworkXError
|
577 |
+
If walk_type not specified or alpha not in valid range
|
578 |
+
"""
|
579 |
+
import numpy as np
|
580 |
+
import scipy as sp
|
581 |
+
|
582 |
+
if walk_type is None:
|
583 |
+
if nx.is_strongly_connected(G):
|
584 |
+
if nx.is_aperiodic(G):
|
585 |
+
walk_type = "random"
|
586 |
+
else:
|
587 |
+
walk_type = "lazy"
|
588 |
+
else:
|
589 |
+
walk_type = "pagerank"
|
590 |
+
|
591 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
|
592 |
+
n, m = A.shape
|
593 |
+
if walk_type in ["random", "lazy"]:
|
594 |
+
# TODO: Rm csr_array wrapper when spdiags array creation becomes available
|
595 |
+
DI = sp.sparse.csr_array(sp.sparse.spdiags(1.0 / A.sum(axis=1), 0, n, n))
|
596 |
+
if walk_type == "random":
|
597 |
+
P = DI @ A
|
598 |
+
else:
|
599 |
+
# TODO: Rm csr_array wrapper when identity array creation becomes available
|
600 |
+
I = sp.sparse.csr_array(sp.sparse.identity(n))
|
601 |
+
P = (I + DI @ A) / 2.0
|
602 |
+
|
603 |
+
elif walk_type == "pagerank":
|
604 |
+
if not (0 < alpha < 1):
|
605 |
+
raise nx.NetworkXError("alpha must be between 0 and 1")
|
606 |
+
# this is using a dense representation. NOTE: This should be sparsified!
|
607 |
+
A = A.toarray()
|
608 |
+
# add constant to dangling nodes' row
|
609 |
+
A[A.sum(axis=1) == 0, :] = 1 / n
|
610 |
+
# normalize
|
611 |
+
A = A / A.sum(axis=1)[np.newaxis, :].T
|
612 |
+
P = alpha * A + (1 - alpha) / n
|
613 |
+
else:
|
614 |
+
raise nx.NetworkXError("walk_type must be random, lazy, or pagerank")
|
615 |
+
|
616 |
+
return P
|
venv/lib/python3.10/site-packages/networkx/linalg/modularitymatrix.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Modularity matrix of graphs.
|
2 |
+
"""
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.utils import not_implemented_for
|
5 |
+
|
6 |
+
__all__ = ["modularity_matrix", "directed_modularity_matrix"]
|
7 |
+
|
8 |
+
|
9 |
+
@not_implemented_for("directed")
|
10 |
+
@not_implemented_for("multigraph")
|
11 |
+
@nx._dispatchable(edge_attrs="weight")
|
12 |
+
def modularity_matrix(G, nodelist=None, weight=None):
|
13 |
+
r"""Returns the modularity matrix of G.
|
14 |
+
|
15 |
+
The modularity matrix is the matrix B = A - <A>, where A is the adjacency
|
16 |
+
matrix and <A> is the average adjacency matrix, assuming that the graph
|
17 |
+
is described by the configuration model.
|
18 |
+
|
19 |
+
More specifically, the element B_ij of B is defined as
|
20 |
+
|
21 |
+
.. math::
|
22 |
+
A_{ij} - {k_i k_j \over 2 m}
|
23 |
+
|
24 |
+
where k_i is the degree of node i, and where m is the number of edges
|
25 |
+
in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
|
26 |
+
k_j and m are computed using its value.
|
27 |
+
|
28 |
+
Parameters
|
29 |
+
----------
|
30 |
+
G : Graph
|
31 |
+
A NetworkX graph
|
32 |
+
|
33 |
+
nodelist : list, optional
|
34 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
35 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
36 |
+
|
37 |
+
weight : string or None, optional (default=None)
|
38 |
+
The edge attribute that holds the numerical value used for
|
39 |
+
the edge weight. If None then all edge weights are 1.
|
40 |
+
|
41 |
+
Returns
|
42 |
+
-------
|
43 |
+
B : Numpy array
|
44 |
+
The modularity matrix of G.
|
45 |
+
|
46 |
+
Examples
|
47 |
+
--------
|
48 |
+
>>> k = [3, 2, 2, 1, 0]
|
49 |
+
>>> G = nx.havel_hakimi_graph(k)
|
50 |
+
>>> B = nx.modularity_matrix(G)
|
51 |
+
|
52 |
+
|
53 |
+
See Also
|
54 |
+
--------
|
55 |
+
to_numpy_array
|
56 |
+
modularity_spectrum
|
57 |
+
adjacency_matrix
|
58 |
+
directed_modularity_matrix
|
59 |
+
|
60 |
+
References
|
61 |
+
----------
|
62 |
+
.. [1] M. E. J. Newman, "Modularity and community structure in networks",
|
63 |
+
Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
|
64 |
+
"""
|
65 |
+
import numpy as np
|
66 |
+
|
67 |
+
if nodelist is None:
|
68 |
+
nodelist = list(G)
|
69 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
|
70 |
+
k = A.sum(axis=1)
|
71 |
+
m = k.sum() * 0.5
|
72 |
+
# Expected adjacency matrix
|
73 |
+
X = np.outer(k, k) / (2 * m)
|
74 |
+
|
75 |
+
return A - X
|
76 |
+
|
77 |
+
|
78 |
+
@not_implemented_for("undirected")
|
79 |
+
@not_implemented_for("multigraph")
|
80 |
+
@nx._dispatchable(edge_attrs="weight")
|
81 |
+
def directed_modularity_matrix(G, nodelist=None, weight=None):
|
82 |
+
"""Returns the directed modularity matrix of G.
|
83 |
+
|
84 |
+
The modularity matrix is the matrix B = A - <A>, where A is the adjacency
|
85 |
+
matrix and <A> is the expected adjacency matrix, assuming that the graph
|
86 |
+
is described by the configuration model.
|
87 |
+
|
88 |
+
More specifically, the element B_ij of B is defined as
|
89 |
+
|
90 |
+
.. math::
|
91 |
+
B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
|
92 |
+
|
93 |
+
where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree
|
94 |
+
of node j, with m the number of edges in the graph. When weight is set
|
95 |
+
to a name of an attribute edge, Aij, k_i, k_j and m are computed using
|
96 |
+
its value.
|
97 |
+
|
98 |
+
Parameters
|
99 |
+
----------
|
100 |
+
G : DiGraph
|
101 |
+
A NetworkX DiGraph
|
102 |
+
|
103 |
+
nodelist : list, optional
|
104 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
105 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
106 |
+
|
107 |
+
weight : string or None, optional (default=None)
|
108 |
+
The edge attribute that holds the numerical value used for
|
109 |
+
the edge weight. If None then all edge weights are 1.
|
110 |
+
|
111 |
+
Returns
|
112 |
+
-------
|
113 |
+
B : Numpy array
|
114 |
+
The modularity matrix of G.
|
115 |
+
|
116 |
+
Examples
|
117 |
+
--------
|
118 |
+
>>> G = nx.DiGraph()
|
119 |
+
>>> G.add_edges_from(
|
120 |
+
... (
|
121 |
+
... (1, 2),
|
122 |
+
... (1, 3),
|
123 |
+
... (3, 1),
|
124 |
+
... (3, 2),
|
125 |
+
... (3, 5),
|
126 |
+
... (4, 5),
|
127 |
+
... (4, 6),
|
128 |
+
... (5, 4),
|
129 |
+
... (5, 6),
|
130 |
+
... (6, 4),
|
131 |
+
... )
|
132 |
+
... )
|
133 |
+
>>> B = nx.directed_modularity_matrix(G)
|
134 |
+
|
135 |
+
|
136 |
+
Notes
|
137 |
+
-----
|
138 |
+
NetworkX defines the element A_ij of the adjacency matrix as 1 if there
|
139 |
+
is a link going from node i to node j. Leicht and Newman use the opposite
|
140 |
+
definition. This explains the different expression for B_ij.
|
141 |
+
|
142 |
+
See Also
|
143 |
+
--------
|
144 |
+
to_numpy_array
|
145 |
+
modularity_spectrum
|
146 |
+
adjacency_matrix
|
147 |
+
modularity_matrix
|
148 |
+
|
149 |
+
References
|
150 |
+
----------
|
151 |
+
.. [1] E. A. Leicht, M. E. J. Newman,
|
152 |
+
"Community structure in directed networks",
|
153 |
+
Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
|
154 |
+
"""
|
155 |
+
import numpy as np
|
156 |
+
|
157 |
+
if nodelist is None:
|
158 |
+
nodelist = list(G)
|
159 |
+
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr")
|
160 |
+
k_in = A.sum(axis=0)
|
161 |
+
k_out = A.sum(axis=1)
|
162 |
+
m = k_in.sum()
|
163 |
+
# Expected adjacency matrix
|
164 |
+
X = np.outer(k_out, k_in) / m
|
165 |
+
|
166 |
+
return A - X
|
venv/lib/python3.10/site-packages/networkx/linalg/spectrum.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Eigenvalue spectrum of graphs.
|
3 |
+
"""
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
__all__ = [
|
7 |
+
"laplacian_spectrum",
|
8 |
+
"adjacency_spectrum",
|
9 |
+
"modularity_spectrum",
|
10 |
+
"normalized_laplacian_spectrum",
|
11 |
+
"bethe_hessian_spectrum",
|
12 |
+
]
|
13 |
+
|
14 |
+
|
15 |
+
@nx._dispatchable(edge_attrs="weight")
|
16 |
+
def laplacian_spectrum(G, weight="weight"):
|
17 |
+
"""Returns eigenvalues of the Laplacian of G
|
18 |
+
|
19 |
+
Parameters
|
20 |
+
----------
|
21 |
+
G : graph
|
22 |
+
A NetworkX graph
|
23 |
+
|
24 |
+
weight : string or None, optional (default='weight')
|
25 |
+
The edge data key used to compute each value in the matrix.
|
26 |
+
If None, then each edge has weight 1.
|
27 |
+
|
28 |
+
Returns
|
29 |
+
-------
|
30 |
+
evals : NumPy array
|
31 |
+
Eigenvalues
|
32 |
+
|
33 |
+
Notes
|
34 |
+
-----
|
35 |
+
For MultiGraph/MultiDiGraph, the edges weights are summed.
|
36 |
+
See :func:`~networkx.convert_matrix.to_numpy_array` for other options.
|
37 |
+
|
38 |
+
See Also
|
39 |
+
--------
|
40 |
+
laplacian_matrix
|
41 |
+
|
42 |
+
Examples
|
43 |
+
--------
|
44 |
+
The multiplicity of 0 as an eigenvalue of the laplacian matrix is equal
|
45 |
+
to the number of connected components of G.
|
46 |
+
|
47 |
+
>>> G = nx.Graph() # Create a graph with 5 nodes and 3 connected components
|
48 |
+
>>> G.add_nodes_from(range(5))
|
49 |
+
>>> G.add_edges_from([(0, 2), (3, 4)])
|
50 |
+
>>> nx.laplacian_spectrum(G)
|
51 |
+
array([0., 0., 0., 2., 2.])
|
52 |
+
|
53 |
+
"""
|
54 |
+
import scipy as sp
|
55 |
+
|
56 |
+
return sp.linalg.eigvalsh(nx.laplacian_matrix(G, weight=weight).todense())
|
57 |
+
|
58 |
+
|
59 |
+
@nx._dispatchable(edge_attrs="weight")
|
60 |
+
def normalized_laplacian_spectrum(G, weight="weight"):
|
61 |
+
"""Return eigenvalues of the normalized Laplacian of G
|
62 |
+
|
63 |
+
Parameters
|
64 |
+
----------
|
65 |
+
G : graph
|
66 |
+
A NetworkX graph
|
67 |
+
|
68 |
+
weight : string or None, optional (default='weight')
|
69 |
+
The edge data key used to compute each value in the matrix.
|
70 |
+
If None, then each edge has weight 1.
|
71 |
+
|
72 |
+
Returns
|
73 |
+
-------
|
74 |
+
evals : NumPy array
|
75 |
+
Eigenvalues
|
76 |
+
|
77 |
+
Notes
|
78 |
+
-----
|
79 |
+
For MultiGraph/MultiDiGraph, the edges weights are summed.
|
80 |
+
See to_numpy_array for other options.
|
81 |
+
|
82 |
+
See Also
|
83 |
+
--------
|
84 |
+
normalized_laplacian_matrix
|
85 |
+
"""
|
86 |
+
import scipy as sp
|
87 |
+
|
88 |
+
return sp.linalg.eigvalsh(
|
89 |
+
nx.normalized_laplacian_matrix(G, weight=weight).todense()
|
90 |
+
)
|
91 |
+
|
92 |
+
|
93 |
+
@nx._dispatchable(edge_attrs="weight")
|
94 |
+
def adjacency_spectrum(G, weight="weight"):
|
95 |
+
"""Returns eigenvalues of the adjacency matrix of G.
|
96 |
+
|
97 |
+
Parameters
|
98 |
+
----------
|
99 |
+
G : graph
|
100 |
+
A NetworkX graph
|
101 |
+
|
102 |
+
weight : string or None, optional (default='weight')
|
103 |
+
The edge data key used to compute each value in the matrix.
|
104 |
+
If None, then each edge has weight 1.
|
105 |
+
|
106 |
+
Returns
|
107 |
+
-------
|
108 |
+
evals : NumPy array
|
109 |
+
Eigenvalues
|
110 |
+
|
111 |
+
Notes
|
112 |
+
-----
|
113 |
+
For MultiGraph/MultiDiGraph, the edges weights are summed.
|
114 |
+
See to_numpy_array for other options.
|
115 |
+
|
116 |
+
See Also
|
117 |
+
--------
|
118 |
+
adjacency_matrix
|
119 |
+
"""
|
120 |
+
import scipy as sp
|
121 |
+
|
122 |
+
return sp.linalg.eigvals(nx.adjacency_matrix(G, weight=weight).todense())
|
123 |
+
|
124 |
+
|
125 |
+
@nx._dispatchable
|
126 |
+
def modularity_spectrum(G):
|
127 |
+
"""Returns eigenvalues of the modularity matrix of G.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
----------
|
131 |
+
G : Graph
|
132 |
+
A NetworkX Graph or DiGraph
|
133 |
+
|
134 |
+
Returns
|
135 |
+
-------
|
136 |
+
evals : NumPy array
|
137 |
+
Eigenvalues
|
138 |
+
|
139 |
+
See Also
|
140 |
+
--------
|
141 |
+
modularity_matrix
|
142 |
+
|
143 |
+
References
|
144 |
+
----------
|
145 |
+
.. [1] M. E. J. Newman, "Modularity and community structure in networks",
|
146 |
+
Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
|
147 |
+
"""
|
148 |
+
import scipy as sp
|
149 |
+
|
150 |
+
if G.is_directed():
|
151 |
+
return sp.linalg.eigvals(nx.directed_modularity_matrix(G))
|
152 |
+
else:
|
153 |
+
return sp.linalg.eigvals(nx.modularity_matrix(G))
|
154 |
+
|
155 |
+
|
156 |
+
@nx._dispatchable
|
157 |
+
def bethe_hessian_spectrum(G, r=None):
|
158 |
+
"""Returns eigenvalues of the Bethe Hessian matrix of G.
|
159 |
+
|
160 |
+
Parameters
|
161 |
+
----------
|
162 |
+
G : Graph
|
163 |
+
A NetworkX Graph or DiGraph
|
164 |
+
|
165 |
+
r : float
|
166 |
+
Regularizer parameter
|
167 |
+
|
168 |
+
Returns
|
169 |
+
-------
|
170 |
+
evals : NumPy array
|
171 |
+
Eigenvalues
|
172 |
+
|
173 |
+
See Also
|
174 |
+
--------
|
175 |
+
bethe_hessian_matrix
|
176 |
+
|
177 |
+
References
|
178 |
+
----------
|
179 |
+
.. [1] A. Saade, F. Krzakala and L. Zdeborová
|
180 |
+
"Spectral clustering of graphs with the bethe hessian",
|
181 |
+
Advances in Neural Information Processing Systems. 2014.
|
182 |
+
"""
|
183 |
+
import scipy as sp
|
184 |
+
|
185 |
+
return sp.linalg.eigvalsh(nx.bethe_hessian_matrix(G, r).todense())
|
venv/lib/python3.10/site-packages/networkx/linalg/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (189 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_algebraic_connectivity.cpython-310.pyc
ADDED
Binary file (12.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/test_attrmatrix.cpython-310.pyc
ADDED
Binary file (3.11 kB). View file
|
|