1import numpy as np
2from numpy.testing import assert_array_almost_equal
3from scipy.sparse import csr_matrix
4from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense
5
6
7def test_csgraph_from_dense():
8    np.random.seed(1234)
9    G = np.random.random((10, 10))
10    some_nulls = (G < 0.4)
11    all_nulls = (G < 0.8)
12
13    for null_value in [0, np.nan, np.inf]:
14        G[all_nulls] = null_value
15        with np.errstate(invalid="ignore"):
16            G_csr = csgraph_from_dense(G, null_value=0)
17
18        G[all_nulls] = 0
19        assert_array_almost_equal(G, G_csr.toarray())
20
21    for null_value in [np.nan, np.inf]:
22        G[all_nulls] = 0
23        G[some_nulls] = null_value
24        with np.errstate(invalid="ignore"):
25            G_csr = csgraph_from_dense(G, null_value=0)
26
27        G[all_nulls] = 0
28        assert_array_almost_equal(G, G_csr.toarray())
29
30
31def test_csgraph_to_dense():
32    np.random.seed(1234)
33    G = np.random.random((10, 10))
34    nulls = (G < 0.8)
35    G[nulls] = np.inf
36
37    G_csr = csgraph_from_dense(G)
38
39    for null_value in [0, 10, -np.inf, np.inf]:
40        G[nulls] = null_value
41        assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value))
42
43
44def test_multiple_edges():
45    # create a random sqare matrix with an even number of elements
46    np.random.seed(1234)
47    X = np.random.random((10, 10))
48    Xcsr = csr_matrix(X)
49
50    # now double-up every other column
51    Xcsr.indices[::2] = Xcsr.indices[1::2]
52
53    # normal sparse toarray() will sum the duplicated edges
54    Xdense = Xcsr.toarray()
55    assert_array_almost_equal(Xdense[:, 1::2],
56                              X[:, ::2] + X[:, 1::2])
57
58    # csgraph_to_dense chooses the minimum of each duplicated edge
59    Xdense = csgraph_to_dense(Xcsr)
60    assert_array_almost_equal(Xdense[:, 1::2],
61                              np.minimum(X[:, ::2], X[:, 1::2]))
62