comparison env/lib/python3.9/site-packages/networkx/linalg/tests/test_modularity.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 import pytest
2
3 np = pytest.importorskip("numpy")
4 npt = pytest.importorskip("numpy.testing")
5 scipy = pytest.importorskip("scipy")
6
7 import networkx as nx
8 from networkx.generators.degree_seq import havel_hakimi_graph
9
10
11 class TestModularity:
12 @classmethod
13 def setup_class(cls):
14 deg = [3, 2, 2, 1, 0]
15 cls.G = havel_hakimi_graph(deg)
16 # Graph used as an example in Sec. 4.1 of Langville and Meyer,
17 # "Google's PageRank and Beyond". (Used for test_directed_laplacian)
18 cls.DG = nx.DiGraph()
19 cls.DG.add_edges_from(
20 (
21 (1, 2),
22 (1, 3),
23 (3, 1),
24 (3, 2),
25 (3, 5),
26 (4, 5),
27 (4, 6),
28 (5, 4),
29 (5, 6),
30 (6, 4),
31 )
32 )
33
34 def test_modularity(self):
35 "Modularity matrix"
36 # fmt: off
37 B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.],
38 [0.25, -0.5, 0.5, -0.25, 0.],
39 [0.25, 0.5, -0.5, -0.25, 0.],
40 [0.625, -0.25, -0.25, -0.125, 0.],
41 [0., 0., 0., 0., 0.]])
42 # fmt: on
43
44 permutation = [4, 0, 1, 2, 3]
45 npt.assert_equal(nx.modularity_matrix(self.G), B)
46 npt.assert_equal(
47 nx.modularity_matrix(self.G, nodelist=permutation),
48 B[np.ix_(permutation, permutation)],
49 )
50
51 def test_modularity_weight(self):
52 "Modularity matrix with weights"
53 # fmt: off
54 B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.],
55 [0.25, -0.5, 0.5, -0.25, 0.],
56 [0.25, 0.5, -0.5, -0.25, 0.],
57 [0.625, -0.25, -0.25, -0.125, 0.],
58 [0., 0., 0., 0., 0.]])
59 # fmt: on
60
61 G_weighted = self.G.copy()
62 for n1, n2 in G_weighted.edges():
63 G_weighted.edges[n1, n2]["weight"] = 0.5
64 # The following test would fail in networkx 1.1
65 npt.assert_equal(nx.modularity_matrix(G_weighted), B)
66 # The following test that the modularity matrix get rescaled accordingly
67 npt.assert_equal(nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B)
68
69 def test_directed_modularity(self):
70 "Directed Modularity matrix"
71 # fmt: off
72 B = np.array([[-0.2, 0.6, 0.8, -0.4, -0.4, -0.4],
73 [0., 0., 0., 0., 0., 0.],
74 [0.7, 0.4, -0.3, -0.6, 0.4, -0.6],
75 [-0.2, -0.4, -0.2, -0.4, 0.6, 0.6],
76 [-0.2, -0.4, -0.2, 0.6, -0.4, 0.6],
77 [-0.1, -0.2, -0.1, 0.8, -0.2, -0.2]])
78 # fmt: on
79 node_permutation = [5, 1, 2, 3, 4, 6]
80 idx_permutation = [4, 0, 1, 2, 3, 5]
81 mm = nx.directed_modularity_matrix(self.DG, nodelist=sorted(self.DG))
82 npt.assert_equal(mm, B)
83 npt.assert_equal(
84 nx.directed_modularity_matrix(self.DG, nodelist=node_permutation),
85 B[np.ix_(idx_permutation, idx_permutation)],
86 )