summaryrefslogtreecommitdiff
path: root/networkx/algorithms/centrality/tests/test_trophic.py
blob: 18e2d74a42e9d1996cac5d44e787c34a0a1adb80 (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""Test trophic levels, trophic differences and trophic coherence
"""
import pytest

np = pytest.importorskip("numpy")
pytest.importorskip("scipy")

import networkx as nx
from networkx.testing import almost_equal


def test_trophic_levels():
    """Trivial example"""
    G = nx.DiGraph()
    G.add_edge("a", "b")
    G.add_edge("b", "c")

    d = nx.trophic_levels(G)
    assert d == {"a": 1, "b": 2, "c": 3}


def test_trophic_levels_levine():
    """Example from Figure 5 in Stephen Levine (1980) J. theor. Biol. 83,
    195-207
    """
    S = nx.DiGraph()
    S.add_edge(1, 2, weight=1.0)
    S.add_edge(1, 3, weight=0.2)
    S.add_edge(1, 4, weight=0.8)
    S.add_edge(2, 3, weight=0.2)
    S.add_edge(2, 5, weight=0.3)
    S.add_edge(4, 3, weight=0.6)
    S.add_edge(4, 5, weight=0.7)
    S.add_edge(5, 4, weight=0.2)

    # save copy for later, test intermediate implementation details first
    S2 = S.copy()

    # drop nodes of in-degree zero
    z = [nid for nid, d in S.in_degree if d == 0]
    for nid in z:
        S.remove_node(nid)

    # find adjacency matrix
    q = nx.linalg.graphmatrix.adjacency_matrix(S).T

    # fmt: off
    expected_q = np.array([
        [0, 0, 0., 0],
        [0.2, 0, 0.6, 0],
        [0, 0, 0, 0.2],
        [0.3, 0, 0.7, 0]
    ])
    # fmt: on
    assert np.array_equal(q.todense(), expected_q)

    # must be square, size of number of nodes
    assert len(q.shape) == 2
    assert q.shape[0] == q.shape[1]
    assert q.shape[0] == len(S)

    nn = q.shape[0]

    i = np.eye(nn)
    n = np.linalg.inv(i - q)
    y = np.asarray(n) @ np.ones(nn)

    expected_y = np.array([1, 2.07906977, 1.46511628, 2.3255814])
    assert np.allclose(y, expected_y)

    expected_d = {1: 1, 2: 2, 3: 3.07906977, 4: 2.46511628, 5: 3.3255814}

    d = nx.trophic_levels(S2)

    for nid, level in d.items():
        expected_level = expected_d[nid]
        assert almost_equal(expected_level, level)


def test_trophic_levels_simple():
    matrix_a = np.array([[0, 0], [1, 0]])
    G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
    d = nx.trophic_levels(G)
    assert almost_equal(d[0], 2)
    assert almost_equal(d[1], 1)


def test_trophic_levels_more_complex():
    # fmt: off
    matrix = np.array([
        [0, 1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 1],
        [0, 0, 0, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
    d = nx.trophic_levels(G)
    expected_result = [1, 2, 3, 4]
    for ind in range(4):
        assert almost_equal(d[ind], expected_result[ind])

    # fmt: off
    matrix = np.array([
        [0, 1, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
    d = nx.trophic_levels(G)

    expected_result = [1, 2, 2.5, 3.25]
    print("Calculated result: ", d)
    print("Expected Result: ", expected_result)

    for ind in range(4):
        assert almost_equal(d[ind], expected_result[ind])


def test_trophic_levels_even_more_complex():
    # fmt: off
    # Another, bigger matrix
    matrix = np.array([
        [0, 0, 0, 0, 0],
        [0, 1, 0, 1, 0],
        [1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0]
    ])
    # Generated this linear system using pen and paper:
    K = np.array([
        [1, 0, -1, 0, 0],
        [0, 0.5, 0, -0.5, 0],
        [0, 0, 1, 0, 0],
        [0, -0.5, 0, 1, -0.5],
        [0, 0, 0, 0, 1],
    ])
    # fmt: on
    result_1 = np.ravel(np.linalg.inv(K) @ np.ones(5))
    G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
    result_2 = nx.trophic_levels(G)

    for ind in range(5):
        assert almost_equal(result_1[ind], result_2[ind])


def test_trophic_levels_singular_matrix():
    """Should raise an error with graphs with only non-basal nodes"""
    matrix = np.identity(4)
    G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
    with pytest.raises(nx.NetworkXError) as e:
        nx.trophic_levels(G)
    msg = (
        "Trophic levels are only defined for graphs where every node "
        + "has a path from a basal node (basal nodes are nodes with no "
        + "incoming edges)."
    )
    assert msg in str(e.value)


def test_trophic_levels_singular_with_basal():
    """Should fail to compute if there are any parts of the graph which are not
    reachable from any basal node (with in-degree zero).
    """
    G = nx.DiGraph()
    # a has in-degree zero
    G.add_edge("a", "b")

    # b is one level above a, c and d
    G.add_edge("c", "b")
    G.add_edge("d", "b")

    # c and d form a loop, neither are reachable from a
    G.add_edge("c", "d")
    G.add_edge("d", "c")

    with pytest.raises(nx.NetworkXError) as e:
        nx.trophic_levels(G)
    msg = (
        "Trophic levels are only defined for graphs where every node "
        + "has a path from a basal node (basal nodes are nodes with no "
        + "incoming edges)."
    )
    assert msg in str(e.value)

    # if self-loops are allowed, smaller example:
    G = nx.DiGraph()
    G.add_edge("a", "b")  # a has in-degree zero
    G.add_edge("c", "b")  # b is one level above a and c
    G.add_edge("c", "c")  # c has a self-loop
    with pytest.raises(nx.NetworkXError) as e:
        nx.trophic_levels(G)
    msg = (
        "Trophic levels are only defined for graphs where every node "
        + "has a path from a basal node (basal nodes are nodes with no "
        + "incoming edges)."
    )
    assert msg in str(e.value)


def test_trophic_differences():
    matrix_a = np.array([[0, 1], [0, 0]])
    G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
    diffs = nx.trophic_differences(G)
    assert almost_equal(diffs[(0, 1)], 1)

    # fmt: off
    matrix_b = np.array([
        [0, 1, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
    diffs = nx.trophic_differences(G)

    assert almost_equal(diffs[(0, 1)], 1)
    assert almost_equal(diffs[(0, 2)], 1.5)
    assert almost_equal(diffs[(1, 2)], 0.5)
    assert almost_equal(diffs[(1, 3)], 1.25)
    assert almost_equal(diffs[(2, 3)], 0.75)


def test_trophic_incoherence_parameter_no_cannibalism():
    matrix_a = np.array([[0, 1], [0, 0]])
    G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=False)
    assert almost_equal(q, 0)

    # fmt: off
    matrix_b = np.array([
        [0, 1, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=False)
    assert almost_equal(q, np.std([1, 1.5, 0.5, 0.75, 1.25]))

    # fmt: off
    matrix_c = np.array([
        [0, 1, 1, 0],
        [0, 1, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=False)
    # Ignore the -link
    assert almost_equal(q, np.std([1, 1.5, 0.5, 0.75, 1.25]))

    # no self-loops case
    # fmt: off
    matrix_d = np.array([
        [0, 1, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix_d, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=False)
    # Ignore the -link
    assert almost_equal(q, np.std([1, 1.5, 0.5, 0.75, 1.25]))


def test_trophic_incoherence_parameter_cannibalism():
    matrix_a = np.array([[0, 1], [0, 0]])
    G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=True)
    assert almost_equal(q, 0)

    # fmt: off
    matrix_b = np.array([
        [0, 0, 0, 0, 0],
        [0, 1, 0, 1, 0],
        [1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=True)
    assert almost_equal(q, 2)

    # fmt: off
    matrix_c = np.array([
        [0, 1, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0]
    ])
    # fmt: on
    G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
    q = nx.trophic_incoherence_parameter(G, cannibalism=True)
    # Ignore the -link
    assert almost_equal(q, np.std([1, 1.5, 0.5, 0.75, 1.25]))