summaryrefslogtreecommitdiff
path: root/networkx/algorithms/link_analysis/tests/test_hits.py
blob: be354086bab9889bcf4c7ec0e984b9252d861667 (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
import pytest
import networkx as nx

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

from networkx.testing import almost_equal

from networkx.algorithms.link_analysis.hits_alg import _hits_python

# Example from
# A. Langville and C. Meyer, "A survey of eigenvector methods of web
# information retrieval."  http://citeseer.ist.psu.edu/713792.html


class TestHITS:
    @classmethod
    def setup_class(cls):

        G = nx.DiGraph()

        edges = [(1, 3), (1, 5), (2, 1), (3, 5), (5, 4), (5, 3), (6, 5)]

        G.add_edges_from(edges, weight=1)
        cls.G = G
        cls.G.a = dict(
            zip(sorted(G), [0.000000, 0.000000, 0.366025, 0.133975, 0.500000, 0.000000])
        )
        cls.G.h = dict(
            zip(sorted(G), [0.366025, 0.000000, 0.211325, 0.000000, 0.211325, 0.211325])
        )

    def test_hits_numpy(self):
        G = self.G
        h, a = nx.hits_numpy(G)
        for n in G:
            assert almost_equal(h[n], G.h[n], places=4)
        for n in G:
            assert almost_equal(a[n], G.a[n], places=4)

    @pytest.mark.parametrize(
        "hits_alg",
        (nx.hits, nx.hits_scipy, _hits_python),
    )
    def test_hits(self, hits_alg):
        G = self.G
        h, a = hits_alg(G, tol=1.0e-08)
        for n in G:
            assert almost_equal(h[n], G.h[n], places=4)
        for n in G:
            assert almost_equal(a[n], G.a[n], places=4)
        nstart = {i: 1.0 / 2 for i in G}
        h, a = hits_alg(G, nstart=nstart)
        for n in G:
            assert almost_equal(h[n], G.h[n], places=4)
        for n in G:
            assert almost_equal(a[n], G.a[n], places=4)

    def test_empty(self):
        G = nx.Graph()
        assert nx.hits(G) == ({}, {})
        assert nx.hits_numpy(G) == ({}, {})
        assert _hits_python(G) == ({}, {})
        assert nx.hits_scipy(G) == ({}, {})
        assert nx.authority_matrix(G).shape == (0, 0)
        assert nx.hub_matrix(G).shape == (0, 0)

    def test_hits_not_convergent(self):
        with pytest.raises(nx.PowerIterationFailedConvergence):
            G = self.G
            nx.hits(G, max_iter=0)


@pytest.mark.parametrize(
    "hits_alg",
    (nx.hits_numpy, nx.hits_scipy),
)
def test_deprecation_warnings(hits_alg):
    """Make sure deprecation warnings are raised.

    To be removed when deprecations expire.
    """
    G = nx.DiGraph(nx.path_graph(4))
    with pytest.warns(DeprecationWarning):
        pr = hits_alg(G)