Spaces:
Running
Running
File size: 2,833 Bytes
b200bda |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
import pytest
np = pytest.importorskip("numpy")
import networkx as nx
def test_attr_matrix():
G = nx.Graph()
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 2, thickness=2)
G.add_edge(1, 2, thickness=3)
def node_attr(u):
return G.nodes[u].get("size", 0.5) * 3
def edge_attr(u, v):
return G[u][v].get("thickness", 0.5)
M = nx.attr_matrix(G, edge_attr=edge_attr, node_attr=node_attr)
np.testing.assert_equal(M[0], np.array([[6.0]]))
assert M[1] == [1.5]
def test_attr_matrix_directed():
G = nx.DiGraph()
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 2, thickness=2)
G.add_edge(1, 2, thickness=3)
M = nx.attr_matrix(G, rc_order=[0, 1, 2])
# fmt: off
data = np.array(
[[0., 1., 1.],
[0., 0., 1.],
[0., 0., 0.]]
)
# fmt: on
np.testing.assert_equal(M, np.array(data))
def test_attr_matrix_multigraph():
G = nx.MultiGraph()
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 2, thickness=2)
G.add_edge(1, 2, thickness=3)
M = nx.attr_matrix(G, rc_order=[0, 1, 2])
# fmt: off
data = np.array(
[[0., 3., 1.],
[3., 0., 1.],
[1., 1., 0.]]
)
# fmt: on
np.testing.assert_equal(M, np.array(data))
M = nx.attr_matrix(G, edge_attr="weight", rc_order=[0, 1, 2])
# fmt: off
data = np.array(
[[0., 9., 1.],
[9., 0., 1.],
[1., 1., 0.]]
)
# fmt: on
np.testing.assert_equal(M, np.array(data))
M = nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
# fmt: off
data = np.array(
[[0., 3., 2.],
[3., 0., 3.],
[2., 3., 0.]]
)
# fmt: on
np.testing.assert_equal(M, np.array(data))
def test_attr_sparse_matrix():
pytest.importorskip("scipy")
G = nx.Graph()
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 2, thickness=2)
G.add_edge(1, 2, thickness=3)
M = nx.attr_sparse_matrix(G)
mtx = M[0]
data = np.ones((3, 3), float)
np.fill_diagonal(data, 0)
np.testing.assert_equal(mtx.todense(), np.array(data))
assert M[1] == [0, 1, 2]
def test_attr_sparse_matrix_directed():
pytest.importorskip("scipy")
G = nx.DiGraph()
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 1, thickness=1, weight=3)
G.add_edge(0, 2, thickness=2)
G.add_edge(1, 2, thickness=3)
M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2])
# fmt: off
data = np.array(
[[0., 1., 1.],
[0., 0., 1.],
[0., 0., 0.]]
)
# fmt: on
np.testing.assert_equal(M.todense(), np.array(data))
|