diff options
67 files changed, 496 insertions, 416 deletions
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 31dbf844..70ed6d47 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -246,6 +246,22 @@ Guidelines import pandas as pd import networkx as nx + After importing `sp`` for ``scipy``:: + + import scipy as sp + + use the following imports:: + + import scipy.linalg # call as sp.linalg + import scipy.sparse # call as sp.sparse + import scipy.sparse.linalg # call as sp.sparse.linalg + import scipy.stats # call as sp.stats + import scipy.optimize # call as sp.optimize + + For example, many libraries have a ``linalg`` subpackage: ``nx.linalg``, + ``np.linalg``, ``sp.linalg``, ``sp.sparse.linalg``. The above import + pattern makes the origin of any particular instance of ``linalg`` explicit. + * Use the decorator ``not_implemented_for`` in ``networkx/utils/decorators.py`` to designate that a function doesn't accept 'directed', 'undirected', 'multigraph' or 'graph'. The first argument of the decorated function should diff --git a/networkx/algorithms/assortativity/correlation.py b/networkx/algorithms/assortativity/correlation.py index 5f43845a..7136f2bd 100644 --- a/networkx/algorithms/assortativity/correlation.py +++ b/networkx/algorithms/assortativity/correlation.py @@ -129,11 +129,12 @@ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, node .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS 107, 10815-20 (2010). """ - from scipy import stats + import scipy as sp + import scipy.stats # call as sp.stats xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight) x, y = zip(*xy) - return stats.pearsonr(x, y)[0] + return sp.stats.pearsonr(x, y)[0] def attribute_assortativity_coefficient(G, attribute, nodes=None): diff --git a/networkx/algorithms/assortativity/tests/test_correlation.py b/networkx/algorithms/assortativity/tests/test_correlation.py index 42aa1d00..548ed82f 100644 --- a/networkx/algorithms/assortativity/tests/test_correlation.py +++ b/networkx/algorithms/assortativity/tests/test_correlation.py @@ -1,8 +1,7 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") -scipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") import networkx as nx @@ -13,27 +12,27 @@ from networkx.algorithms.assortativity.correlation import attribute_ac class TestDegreeMixingCorrelation(BaseTestDegreeMixing): def test_degree_assortativity_undirected(self): r = nx.degree_assortativity_coefficient(self.P4) - npt.assert_almost_equal(r, -1.0 / 2, decimal=4) + np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4) def test_degree_assortativity_directed(self): r = nx.degree_assortativity_coefficient(self.D) - npt.assert_almost_equal(r, -0.57735, decimal=4) + np.testing.assert_almost_equal(r, -0.57735, decimal=4) def test_degree_assortativity_multigraph(self): r = nx.degree_assortativity_coefficient(self.M) - npt.assert_almost_equal(r, -1.0 / 7.0, decimal=4) + np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4) def test_degree_pearson_assortativity_undirected(self): r = nx.degree_pearson_correlation_coefficient(self.P4) - npt.assert_almost_equal(r, -1.0 / 2, decimal=4) + np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4) def test_degree_pearson_assortativity_directed(self): r = nx.degree_pearson_correlation_coefficient(self.D) - npt.assert_almost_equal(r, -0.57735, decimal=4) + np.testing.assert_almost_equal(r, -0.57735, decimal=4) def test_degree_pearson_assortativity_multigraph(self): r = nx.degree_pearson_correlation_coefficient(self.M) - npt.assert_almost_equal(r, -1.0 / 7.0, decimal=4) + np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4) class TestAttributeMixingCorrelation(BaseTestAttributeMixing): @@ -58,7 +57,7 @@ class TestAttributeMixingCorrelation(BaseTestAttributeMixing): [0.005, 0.007, 0.024, 0.016]]) # fmt: on r = attribute_ac(a) - npt.assert_almost_equal(r, 0.623, decimal=3) + np.testing.assert_almost_equal(r, 0.623, decimal=3) def test_attribute_assortativity_coefficient2(self): # fmt: off @@ -68,9 +67,9 @@ class TestAttributeMixingCorrelation(BaseTestAttributeMixing): [0.03, 0.02, 0.01, 0.22]]) # fmt: on r = attribute_ac(a) - npt.assert_almost_equal(r, 0.68, decimal=2) + np.testing.assert_almost_equal(r, 0.68, decimal=2) def test_attribute_assortativity(self): a = np.array([[50, 50, 0], [50, 50, 0], [0, 0, 2]]) r = attribute_ac(a) - npt.assert_almost_equal(r, 0.029, decimal=3) + np.testing.assert_almost_equal(r, 0.029, decimal=3) diff --git a/networkx/algorithms/assortativity/tests/test_mixing.py b/networkx/algorithms/assortativity/tests/test_mixing.py index 1b21eebd..f1a1b4e2 100644 --- a/networkx/algorithms/assortativity/tests/test_mixing.py +++ b/networkx/algorithms/assortativity/tests/test_mixing.py @@ -1,7 +1,6 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") import networkx as nx @@ -40,9 +39,9 @@ class TestDegreeMixingMatrix(BaseTestDegreeMixing): ) # fmt: on a = nx.degree_mixing_matrix(self.P4, normalized=False) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.P4) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) def test_degree_mixing_matrix_directed(self): # fmt: off @@ -53,9 +52,9 @@ class TestDegreeMixingMatrix(BaseTestDegreeMixing): ) # fmt: on a = nx.degree_mixing_matrix(self.D, normalized=False) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.D) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) def test_degree_mixing_matrix_multigraph(self): # fmt: off @@ -66,9 +65,9 @@ class TestDegreeMixingMatrix(BaseTestDegreeMixing): ) # fmt: on a = nx.degree_mixing_matrix(self.M, normalized=False) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.M) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) def test_degree_mixing_matrix_selfloop(self): # fmt: off @@ -78,9 +77,9 @@ class TestDegreeMixingMatrix(BaseTestDegreeMixing): ) # fmt: on a = nx.degree_mixing_matrix(self.S, normalized=False) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.S) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) class TestAttributeMixingDict(BaseTestAttributeMixing): @@ -117,9 +116,9 @@ class TestAttributeMixingMatrix(BaseTestAttributeMixing): a = nx.attribute_mixing_matrix( self.G, "fish", mapping=mapping, normalized=False ) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) def test_attribute_mixing_matrix_directed(self): mapping = {"one": 0, "two": 1, "red": 2, "blue": 3} @@ -127,9 +126,9 @@ class TestAttributeMixingMatrix(BaseTestAttributeMixing): a = nx.attribute_mixing_matrix( self.D, "fish", mapping=mapping, normalized=False ) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) def test_attribute_mixing_matrix_multigraph(self): mapping = {"one": 0, "two": 1, "red": 2, "blue": 3} @@ -137,6 +136,6 @@ class TestAttributeMixingMatrix(BaseTestAttributeMixing): a = nx.attribute_mixing_matrix( self.M, "fish", mapping=mapping, normalized=False ) - npt.assert_equal(a, a_result) + np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping) - npt.assert_equal(a, a_result / float(a_result.sum())) + np.testing.assert_equal(a, a_result / float(a_result.sum())) diff --git a/networkx/algorithms/bipartite/matching.py b/networkx/algorithms/bipartite/matching.py index b89d89bd..279e0160 100644 --- a/networkx/algorithms/bipartite/matching.py +++ b/networkx/algorithms/bipartite/matching.py @@ -557,7 +557,8 @@ def minimum_weight_full_matching(G, top_nodes=None, weight="weight"): """ import numpy as np - import scipy.optimize + import scipy as sp + import scipy.optimize # call as sp.optimize left, right = nx.bipartite.sets(G, top_nodes) U = list(left) @@ -570,7 +571,7 @@ def minimum_weight_full_matching(G, top_nodes=None, weight="weight"): ) weights = np.full(weights_sparse.shape, np.inf) weights[weights_sparse.row, weights_sparse.col] = weights_sparse.data - left_matches = scipy.optimize.linear_sum_assignment(weights) + left_matches = sp.optimize.linear_sum_assignment(weights) d = {U[u]: V[v] for u, v in zip(*left_matches)} # d will contain the matching from edges in left to right; we need to # add the ones from right to left as well. diff --git a/networkx/algorithms/bipartite/matrix.py b/networkx/algorithms/bipartite/matrix.py index 5261a911..9d7ee4e3 100644 --- a/networkx/algorithms/bipartite/matrix.py +++ b/networkx/algorithms/bipartite/matrix.py @@ -73,7 +73,8 @@ def biadjacency_matrix( .. [2] Scipy Dev. References, "Sparse Matrices", https://docs.scipy.org/doc/scipy/reference/sparse.html """ - from scipy import sparse + import scipy as sp + import scipy.sparse # call as sp.sparse nlen = len(row_order) if nlen == 0: @@ -101,12 +102,10 @@ def biadjacency_matrix( if u in row_index and v in col_index ) ) - M = sparse.coo_matrix((data, (row, col)), shape=(nlen, mlen), dtype=dtype) + M = sp.sparse.coo_matrix((data, (row, col)), shape=(nlen, mlen), dtype=dtype) try: return M.asformat(format) - # From Scipy 1.1.0, asformat will throw a ValueError instead of an - # AttributeError if the format if not recognized. - except (AttributeError, ValueError) as e: + except ValueError as e: raise nx.NetworkXError(f"Unknown sparse matrix format: {format}") from e diff --git a/networkx/algorithms/bipartite/spectral.py b/networkx/algorithms/bipartite/spectral.py index 79d8ded5..290893f6 100644 --- a/networkx/algorithms/bipartite/spectral.py +++ b/networkx/algorithms/bipartite/spectral.py @@ -47,12 +47,13 @@ def spectral_bipartivity(G, nodes=None, weight="weight"): .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of bipartivity in complex networks", PhysRev E 72, 046105 (2005) """ - import scipy.linalg + import scipy as sp + import scipy.linalg # call as sp.linalg nodelist = list(G) # ordering of nodes in matrix A = nx.to_numpy_array(G, nodelist, weight=weight) - expA = scipy.linalg.expm(A) - expmA = scipy.linalg.expm(-A) + expA = sp.linalg.expm(A) + expmA = sp.linalg.expm(-A) coshA = 0.5 * (expA + expmA) if nodes is None: # return single number for entire graph diff --git a/networkx/algorithms/bipartite/tests/test_basic.py b/networkx/algorithms/bipartite/tests/test_basic.py index 1df1f070..cb42bb9a 100644 --- a/networkx/algorithms/bipartite/tests/test_basic.py +++ b/networkx/algorithms/bipartite/tests/test_basic.py @@ -90,7 +90,7 @@ class TestBipartiteBasic: assert dict(d) == {0: 0.2, 2: 2, 4: 1} def test_biadjacency_matrix_weight(self): - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") G = nx.path_graph(5) G.add_edge(0, 1, weight=2, other=4) X = [1, 3] @@ -101,7 +101,7 @@ class TestBipartiteBasic: assert M[0, 0] == 4 def test_biadjacency_matrix(self): - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") tops = [2, 5, 10] bots = [5, 10, 15] for i in range(len(tops)): @@ -112,7 +112,7 @@ class TestBipartiteBasic: assert M.shape[1] == bots[i] def test_biadjacency_matrix_order(self): - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") G = nx.path_graph(5) G.add_edge(0, 1, weight=2) X = [3, 1] diff --git a/networkx/algorithms/bipartite/tests/test_matching.py b/networkx/algorithms/bipartite/tests/test_matching.py index 2c6c84df..d4fcd980 100644 --- a/networkx/algorithms/bipartite/tests/test_matching.py +++ b/networkx/algorithms/bipartite/tests/test_matching.py @@ -207,8 +207,7 @@ def test_eppstein_matching(): class TestMinimumWeightFullMatching: @classmethod def setup_class(cls): - global scipy - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") def test_minimum_weight_full_matching_incomplete_graph(self): B = nx.Graph() diff --git a/networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py b/networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py index 3c85e187..16bab3c0 100644 --- a/networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py +++ b/networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py @@ -1,5 +1,7 @@ import pytest +pytest.importorskip("scipy") + import networkx as nx from networkx.algorithms.bipartite import spectral_bipartivity as sb from networkx.testing import almost_equal @@ -10,11 +12,6 @@ from networkx.testing import almost_equal class TestSpectralBipartivity: - @classmethod - def setup_class(cls): - global scipy - scipy = pytest.importorskip("scipy") - def test_star_like(self): # star-like diff --git a/networkx/algorithms/centrality/eigenvector.py b/networkx/algorithms/centrality/eigenvector.py index 611cf407..3fc43e2a 100644 --- a/networkx/algorithms/centrality/eigenvector.py +++ b/networkx/algorithms/centrality/eigenvector.py @@ -214,14 +214,14 @@ def eigenvector_centrality_numpy(G, weight=None, max_iter=50, tol=0): """ import numpy as np import scipy as sp - from scipy.sparse import linalg + import scipy.sparse.linalg # call as sp.sparse.linalg if len(G) == 0: raise nx.NetworkXPointlessConcept( "cannot compute centrality for the null graph" ) M = nx.to_scipy_sparse_matrix(G, nodelist=list(G), weight=weight, dtype=float) - eigenvalue, eigenvector = linalg.eigs( + eigenvalue, eigenvector = sp.sparse.linalg.eigs( M.T, k=1, which="LR", maxiter=max_iter, tol=tol ) largest = eigenvector.flatten().real diff --git a/networkx/algorithms/centrality/flow_matrix.py b/networkx/algorithms/centrality/flow_matrix.py index 382eaf8c..ad78fad8 100644 --- a/networkx/algorithms/centrality/flow_matrix.py +++ b/networkx/algorithms/centrality/flow_matrix.py @@ -95,9 +95,10 @@ class FullInverseLaplacian(InverseLaplacian): class SuperLUInverseLaplacian(InverseLaplacian): def init_solver(self, L): - from scipy.sparse import linalg + import scipy as sp + import scipy.sparse.linalg # call as sp.sparse.linalg - self.lusolve = linalg.factorized(self.L1.tocsc()) + self.lusolve = sp.sparse.linalg.factorized(self.L1.tocsc()) def solve_inverse(self, r): rhs = np.zeros(self.n, dtype=self.dtype) @@ -112,33 +113,35 @@ class SuperLUInverseLaplacian(InverseLaplacian): class CGInverseLaplacian(InverseLaplacian): def init_solver(self, L): - global linalg - from scipy.sparse import linalg + global sp + import scipy as sp + import scipy.sparse.linalg # call as sp.sparse.linalg - ilu = linalg.spilu(self.L1.tocsc()) + ilu = sp.sparse.linalg.spilu(self.L1.tocsc()) n = self.n - 1 - self.M = linalg.LinearOperator(shape=(n, n), matvec=ilu.solve) + self.M = sp.sparse.linalg.LinearOperator(shape=(n, n), matvec=ilu.solve) def solve(self, rhs): s = np.zeros(rhs.shape, dtype=self.dtype) - s[1:] = linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0] + s[1:] = sp.sparse.linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0] return s def solve_inverse(self, r): rhs = np.zeros(self.n, self.dtype) rhs[r] = 1 - return linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0] + return sp.sparse.linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0] # graph laplacian, sparse version, will move to linalg/laplacianmatrix.py def laplacian_sparse_matrix(G, nodelist=None, weight=None, dtype=None, format="csr"): import numpy as np - import scipy.sparse + import scipy as sp + import scipy.sparse # call as sp.sparse A = nx.to_scipy_sparse_matrix( G, nodelist=nodelist, weight=weight, dtype=dtype, format=format ) (n, n) = A.shape data = np.asarray(A.sum(axis=1).T) - D = scipy.sparse.spdiags(data, 0, n, n, format=format) + D = sp.sparse.spdiags(data, 0, n, n, format=format) return D - A diff --git a/networkx/algorithms/centrality/subgraph_alg.py b/networkx/algorithms/centrality/subgraph_alg.py index 56c1e6a2..a792dd93 100644 --- a/networkx/algorithms/centrality/subgraph_alg.py +++ b/networkx/algorithms/centrality/subgraph_alg.py @@ -83,13 +83,14 @@ def subgraph_centrality_exp(G): ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90'] """ # alternative implementation that calculates the matrix exponential - import scipy.linalg + import scipy as sp + import scipy.linalg # call as sp.linalg nodelist = list(G) # ordering of nodes in matrix A = nx.to_numpy_array(G, nodelist) # convert to 0-1 matrix A[A != 0.0] = 1 - expA = scipy.linalg.expm(A) + expA = sp.linalg.expm(A) # convert diagonal to dictionary keyed by node sc = dict(zip(nodelist, map(float, expA.diagonal()))) return sc @@ -253,14 +254,15 @@ def communicability_betweenness_centrality(G, normalized=True): ['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03'] """ import numpy as np - import scipy.linalg + import scipy as sp + import scipy.linalg # call as sp.linalg nodelist = list(G) # ordering of nodes in matrix n = len(nodelist) A = nx.to_numpy_array(G, nodelist) # convert to 0-1 matrix A[np.nonzero(A)] = 1 - expA = scipy.linalg.expm(A) + expA = sp.linalg.expm(A) mapping = dict(zip(nodelist, range(n))) cbc = {} for v in G: @@ -270,7 +272,7 @@ def communicability_betweenness_centrality(G, normalized=True): col = A[:, i].copy() A[i, :] = 0 A[:, i] = 0 - B = (expA - scipy.linalg.expm(A)) / expA + B = (expA - sp.linalg.expm(A)) / expA # sum with row/col of node v and diag set to zero B[i, :] = 0 B[:, i] = 0 diff --git a/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py b/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py index d3dde1ec..166df59a 100644 --- a/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py +++ b/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py @@ -7,8 +7,7 @@ from networkx import approximate_current_flow_betweenness_centrality as approxim np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") -scipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") class TestFlowBetweennessCentrality: @@ -88,7 +87,7 @@ class TestApproximateFlowBetweennessCentrality: epsilon = 0.1 ba = approximate_cfbc(G, normalized=True, epsilon=0.5 * epsilon) for n in sorted(G): - npt.assert_allclose(b[n], ba[n], atol=epsilon) + np.testing.assert_allclose(b[n], ba[n], atol=epsilon) def test_K4(self): "Approximate current-flow betweenness centrality: K4" @@ -97,7 +96,7 @@ class TestApproximateFlowBetweennessCentrality: epsilon = 0.1 ba = approximate_cfbc(G, normalized=False, epsilon=0.5 * epsilon) for n in sorted(G): - npt.assert_allclose(b[n], ba[n], atol=epsilon * len(G) ** 2) + np.testing.assert_allclose(b[n], ba[n], atol=epsilon * len(G) ** 2) def test_star(self): "Approximate current-flow betweenness centrality: star" @@ -107,7 +106,7 @@ class TestApproximateFlowBetweennessCentrality: epsilon = 0.1 ba = approximate_cfbc(G, normalized=True, epsilon=0.5 * epsilon) for n in sorted(G): - npt.assert_allclose(b[n], ba[n], atol=epsilon) + np.testing.assert_allclose(b[n], ba[n], atol=epsilon) def test_grid(self): "Approximate current-flow betweenness centrality: 2d grid" @@ -116,14 +115,14 @@ class TestApproximateFlowBetweennessCentrality: epsilon = 0.1 ba = approximate_cfbc(G, normalized=True, epsilon=0.5 * epsilon) for n in sorted(G): - npt.assert_allclose(b[n], ba[n], atol=epsilon) + np.testing.assert_allclose(b[n], ba[n], atol=epsilon) def test_seed(self): G = nx.complete_graph(4) b = approximate_cfbc(G, normalized=False, epsilon=0.05, seed=1) b_answer = {0: 0.75, 1: 0.75, 2: 0.75, 3: 0.75} for n in sorted(G): - npt.assert_allclose(b[n], b_answer[n], atol=0.1) + np.testing.assert_allclose(b[n], b_answer[n], atol=0.1) def test_solvers(self): "Approximate current-flow betweenness centrality: solvers" @@ -135,7 +134,7 @@ class TestApproximateFlowBetweennessCentrality: ) b_answer = {0: 0.75, 1: 0.75, 2: 0.75, 3: 0.75} for n in sorted(G): - npt.assert_allclose(b[n], b_answer[n], atol=epsilon) + np.testing.assert_allclose(b[n], b_answer[n], atol=epsilon) class TestWeightedFlowBetweennessCentrality: diff --git a/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py b/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py index 1ec1b080..15b0773b 100644 --- a/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py +++ b/networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py @@ -1,7 +1,7 @@ import pytest -np = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.testing import almost_equal diff --git a/networkx/algorithms/centrality/tests/test_current_flow_closeness.py b/networkx/algorithms/centrality/tests/test_current_flow_closeness.py index e6a38949..338c9613 100644 --- a/networkx/algorithms/centrality/tests/test_current_flow_closeness.py +++ b/networkx/algorithms/centrality/tests/test_current_flow_closeness.py @@ -1,7 +1,7 @@ import pytest -np = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.testing import almost_equal diff --git a/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py b/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py index a2f72ecd..133f4ffd 100644 --- a/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py +++ b/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py @@ -2,7 +2,7 @@ import math import pytest np = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") import networkx as nx diff --git a/networkx/algorithms/centrality/tests/test_katz_centrality.py b/networkx/algorithms/centrality/tests/test_katz_centrality.py index 7810f519..4d270d22 100644 --- a/networkx/algorithms/centrality/tests/test_katz_centrality.py +++ b/networkx/algorithms/centrality/tests/test_katz_centrality.py @@ -123,7 +123,7 @@ class TestKatzCentralityNumpy: def setup_class(cls): global np np = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") def test_K5(self): """Katz centrality: K5""" @@ -320,7 +320,7 @@ class TestKatzCentralityDirectedNumpy(TestKatzCentralityDirected): def setup_class(cls): global np np = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") def test_katz_centrality_weighted(self): G = self.G @@ -341,14 +341,12 @@ class TestKatzEigenvectorVKatz: @classmethod def setup_class(cls): global np - global eigvals np = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") - from numpy.linalg import eigvals + pytest.importorskip("scipy") def test_eigenvector_v_katz_random(self): G = nx.gnp_random_graph(10, 0.5, seed=1234) - l = float(max(eigvals(nx.adjacency_matrix(G).todense()))) + l = float(max(np.linalg.eigvals(nx.adjacency_matrix(G).todense()))) e = nx.eigenvector_centrality_numpy(G) k = nx.katz_centrality_numpy(G, 1.0 / l) for n in G: diff --git a/networkx/algorithms/centrality/tests/test_second_order_centrality.py b/networkx/algorithms/centrality/tests/test_second_order_centrality.py index 58eee18c..385593b6 100644 --- a/networkx/algorithms/centrality/tests/test_second_order_centrality.py +++ b/networkx/algorithms/centrality/tests/test_second_order_centrality.py @@ -4,8 +4,8 @@ Tests for second order centrality. import pytest -np = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.testing import almost_equal diff --git a/networkx/algorithms/centrality/tests/test_subgraph.py b/networkx/algorithms/centrality/tests/test_subgraph.py index 1a5f5c0c..e5e0210a 100644 --- a/networkx/algorithms/centrality/tests/test_subgraph.py +++ b/networkx/algorithms/centrality/tests/test_subgraph.py @@ -1,7 +1,7 @@ import pytest -numpy = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.algorithms.centrality.subgraph_alg import ( diff --git a/networkx/algorithms/centrality/tests/test_trophic.py b/networkx/algorithms/centrality/tests/test_trophic.py index 91a79aee..18e2d74a 100644 --- a/networkx/algorithms/centrality/tests/test_trophic.py +++ b/networkx/algorithms/centrality/tests/test_trophic.py @@ -3,6 +3,7 @@ import pytest np = pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.testing import almost_equal diff --git a/networkx/algorithms/communicability_alg.py b/networkx/algorithms/communicability_alg.py index a9acad6b..ba4b4abe 100644 --- a/networkx/algorithms/communicability_alg.py +++ b/networkx/algorithms/communicability_alg.py @@ -143,14 +143,15 @@ def communicability_exp(G): >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) >>> c = nx.communicability_exp(G) """ - import scipy.linalg + import scipy as sp + import scipy.linalg # call as sp.linalg nodelist = list(G) # ordering of nodes in matrix A = nx.to_numpy_array(G, nodelist) # convert to 0-1 matrix A[A != 0.0] = 1 # communicability matrix - expA = scipy.linalg.expm(A) + expA = sp.linalg.expm(A) mapping = dict(zip(nodelist, range(len(nodelist)))) c = {} for u in G: diff --git a/networkx/algorithms/distance_measures.py b/networkx/algorithms/distance_measures.py index 4cb0c812..6a51d77b 100644 --- a/networkx/algorithms/distance_measures.py +++ b/networkx/algorithms/distance_measures.py @@ -545,7 +545,8 @@ def resistance_distance(G, nodeA, nodeB, weight=None, invert_weight=True): Available: `Link to thesis <https://www.universiteitleiden.nl/binaries/content/assets/science/mi/scripties/master/vos_vaya_master.pdf>`_ """ import numpy as np - import scipy.sparse + import scipy as sp + import scipy.sparse.linalg # call as sp.sparse.linalg if not nx.is_connected(G): msg = "Graph G must be strongly connected." @@ -582,7 +583,7 @@ def resistance_distance(G, nodeA, nodeB, weight=None, invert_weight=True): # Factorize Laplacian submatrixes and extract diagonals # Order the diagonals to minimize the likelihood over overflows # during computing the determinant - lu_a = scipy.sparse.linalg.splu(Lsub_a, options=dict(SymmetricMode=True)) + lu_a = sp.sparse.linalg.splu(Lsub_a, options=dict(SymmetricMode=True)) LdiagA = lu_a.U.diagonal() LdiagA_s = np.product(np.sign(LdiagA)) * np.product(lu_a.L.diagonal()) LdiagA_s *= (-1) ** _count_lu_permutations(lu_a.perm_r) @@ -590,7 +591,7 @@ def resistance_distance(G, nodeA, nodeB, weight=None, invert_weight=True): LdiagA = np.absolute(LdiagA) LdiagA = np.sort(LdiagA) - lu_ab = scipy.sparse.linalg.splu(Lsub_ab, options=dict(SymmetricMode=True)) + lu_ab = sp.sparse.linalg.splu(Lsub_ab, options=dict(SymmetricMode=True)) LdiagAB = lu_ab.U.diagonal() LdiagAB_s = np.product(np.sign(LdiagAB)) * np.product(lu_ab.L.diagonal()) LdiagAB_s *= (-1) ** _count_lu_permutations(lu_ab.perm_r) diff --git a/networkx/algorithms/link_analysis/pagerank_alg.py b/networkx/algorithms/link_analysis/pagerank_alg.py index f28085ee..f564b910 100644 --- a/networkx/algorithms/link_analysis/pagerank_alg.py +++ b/networkx/algorithms/link_analysis/pagerank_alg.py @@ -449,7 +449,8 @@ def pagerank_scipy( msg = "networkx.pagerank_scipy is deprecated and will be removed in NetworkX 3.0, use networkx.pagerank instead." warn(msg, DeprecationWarning, stacklevel=2) import numpy as np - import scipy.sparse + import scipy as sp + import scipy.sparse # call as sp.sparse N = len(G) if N == 0: @@ -459,7 +460,7 @@ def pagerank_scipy( M = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight, dtype=float) S = np.array(M.sum(axis=1)).flatten() S[S != 0] = 1.0 / S[S != 0] - Q = scipy.sparse.spdiags(S.T, 0, *M.shape, format="csr") + Q = sp.sparse.spdiags(S.T, 0, *M.shape, format="csr") M = Q * M # initial vector diff --git a/networkx/algorithms/link_analysis/tests/test_hits.py b/networkx/algorithms/link_analysis/tests/test_hits.py index e9522065..e306d541 100644 --- a/networkx/algorithms/link_analysis/tests/test_hits.py +++ b/networkx/algorithms/link_analysis/tests/test_hits.py @@ -40,7 +40,7 @@ class TestHITS: h, a = networkx.hits(G, nstart=nstart) def test_hits_numpy(self): - numpy = pytest.importorskip("numpy") + pytest.importorskip("numpy") G = self.G h, a = networkx.hits_numpy(G) for n in G: @@ -49,7 +49,7 @@ class TestHITS: assert almost_equal(a[n], G.a[n], places=4) def test_hits_scipy(self): - sp = pytest.importorskip("scipy") + pytest.importorskip("scipy") G = self.G h, a = networkx.hits_scipy(G, tol=1.0e-08) for n in G: @@ -58,7 +58,7 @@ class TestHITS: assert almost_equal(a[n], G.a[n], places=4) def test_empty(self): - numpy = pytest.importorskip("numpy") + pytest.importorskip("numpy") G = networkx.Graph() assert networkx.hits(G) == ({}, {}) assert networkx.hits_numpy(G) == ({}, {}) @@ -66,7 +66,7 @@ class TestHITS: assert networkx.hub_matrix(G).shape == (0, 0) def test_empty_scipy(self): - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") G = networkx.Graph() assert networkx.hits_scipy(G) == ({}, {}) diff --git a/networkx/algorithms/link_analysis/tests/test_pagerank.py b/networkx/algorithms/link_analysis/tests/test_pagerank.py index ef59caaf..e655db0a 100644 --- a/networkx/algorithms/link_analysis/tests/test_pagerank.py +++ b/networkx/algorithms/link_analysis/tests/test_pagerank.py @@ -3,8 +3,8 @@ import random import networkx as nx import pytest -numpy = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +np = pytest.importorskip("numpy") +pytest.importorskip("scipy") from networkx.testing import almost_equal from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_python @@ -81,8 +81,8 @@ class TestPageRank: def test_google_matrix(self): G = self.G M = nx.google_matrix(G, alpha=0.9, nodelist=sorted(G)) - e, ev = numpy.linalg.eig(M.T) - p = numpy.array(ev[:, 0] / ev[:, 0].sum())[:, 0] + e, ev = np.linalg.eig(M.T) + p = np.array(ev[:, 0] / ev[:, 0].sum())[:, 0] for (a, b) in zip(p, self.G.pagerank.values()): assert almost_equal(a, b) diff --git a/networkx/algorithms/node_classification/hmn.py b/networkx/algorithms/node_classification/hmn.py index 01432959..a4e1ace3 100644 --- a/networkx/algorithms/node_classification/hmn.py +++ b/networkx/algorithms/node_classification/hmn.py @@ -62,7 +62,8 @@ def harmonic_function(G, max_iter=30, label_name="label"): In ICML (Vol. 3, pp. 912-919). """ import numpy as np - from scipy import sparse + import scipy as sp + import scipy.sparse # call as sp.sparse def _build_propagation_matrix(X, labels): """Build propagation matrix of Harmonic function @@ -82,7 +83,7 @@ def harmonic_function(G, max_iter=30, label_name="label"): """ degrees = X.sum(axis=0).A[0] degrees[degrees == 0] = 1 # Avoid division by 0 - D = sparse.diags((1.0 / degrees), offsets=0) + D = sp.sparse.diags((1.0 / degrees), offsets=0) P = (D @ X).tolil() P[labels[:, 0]] = 0 # labels[:, 0] indicates IDs of labeled nodes return P diff --git a/networkx/algorithms/node_classification/lgc.py b/networkx/algorithms/node_classification/lgc.py index c9ee7df1..dda73502 100644 --- a/networkx/algorithms/node_classification/lgc.py +++ b/networkx/algorithms/node_classification/lgc.py @@ -65,7 +65,8 @@ def local_and_global_consistency(G, alpha=0.99, max_iter=30, label_name="label") Advances in neural information processing systems, 16(16), 321-328. """ import numpy as np - from scipy import sparse + import scipy as sp + import scipy.sparse # call as sp.sparse def _build_propagation_matrix(X, labels, alpha): """Build propagation matrix of Local and global consistency @@ -87,7 +88,7 @@ def local_and_global_consistency(G, alpha=0.99, max_iter=30, label_name="label") """ degrees = X.sum(axis=0).A[0] degrees[degrees == 0] = 1 # Avoid division by 0 - D2 = np.sqrt(sparse.diags((1.0 / degrees), offsets=0)) + D2 = np.sqrt(sp.sparse.diags((1.0 / degrees), offsets=0)) S = alpha * ((D2 @ X) @ D2) return S diff --git a/networkx/algorithms/node_classification/tests/test_harmonic_function.py b/networkx/algorithms/node_classification/tests/test_harmonic_function.py index c8379262..cb7f7d9f 100644 --- a/networkx/algorithms/node_classification/tests/test_harmonic_function.py +++ b/networkx/algorithms/node_classification/tests/test_harmonic_function.py @@ -1,7 +1,7 @@ import pytest -numpy = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.algorithms import node_classification diff --git a/networkx/algorithms/node_classification/tests/test_local_and_global_consistency.py b/networkx/algorithms/node_classification/tests/test_local_and_global_consistency.py index 163c0218..029f2405 100644 --- a/networkx/algorithms/node_classification/tests/test_local_and_global_consistency.py +++ b/networkx/algorithms/node_classification/tests/test_local_and_global_consistency.py @@ -1,7 +1,7 @@ import pytest -numpy = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx diff --git a/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py b/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py index bee06968..13df927f 100644 --- a/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py +++ b/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py @@ -1,7 +1,6 @@ import pytest -numpy = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") +np = pytest.importorskip("numpy") import networkx as nx @@ -60,17 +59,17 @@ class TestFloydNumpy: nx.add_cycle(G, [0, 1, 2, 3]) pred, dist = nx.floyd_warshall_predecessor_and_distance(G) D = nx.utils.dict_to_numpy_array(dist) - npt.assert_equal(nx.floyd_warshall_numpy(G), D) + np.testing.assert_equal(nx.floyd_warshall_numpy(G), D) def test_zero_weight(self): G = nx.DiGraph() edges = [(1, 2, -2), (2, 3, -4), (1, 5, 1), (5, 4, 0), (4, 3, -5), (2, 5, -7)] G.add_weighted_edges_from(edges) dist = nx.floyd_warshall_numpy(G) - assert int(numpy.min(dist)) == -14 + assert int(np.min(dist)) == -14 G = nx.MultiDiGraph() edges.append((2, 5, -7)) G.add_weighted_edges_from(edges) dist = nx.floyd_warshall_numpy(G) - assert int(numpy.min(dist)) == -14 + assert int(np.min(dist)) == -14 diff --git a/networkx/algorithms/shortest_paths/tests/test_generic.py b/networkx/algorithms/shortest_paths/tests/test_generic.py index 251db317..2a7b15ff 100644 --- a/networkx/algorithms/shortest_paths/tests/test_generic.py +++ b/networkx/algorithms/shortest_paths/tests/test_generic.py @@ -358,12 +358,10 @@ class TestAverageShortestPathLength: class TestAverageShortestPathLengthNumpy: @classmethod def setup_class(cls): - global numpy - global npt + global np import pytest - numpy = pytest.importorskip("numpy") - npt = pytest.importorskip("numpy.testing") + np = pytest.importorskip("numpy") def test_specified_methods_numpy(self): G = nx.Graph() @@ -371,11 +369,11 @@ class TestAverageShortestPathLengthNumpy: ans = nx.average_shortest_path_length( G, weight="weight", method="floyd-warshall-numpy" ) - npt.assert_almost_equal(ans, 4) + np.testing.assert_almost_equal(ans, 4) G = nx.Graph() nx.add_path(G, range(5), weight=2) ans = nx.average_shortest_path_length( G, weight="weight", method="floyd-warshall-numpy" ) - npt.assert_almost_equal(ans, 4) + np.testing.assert_almost_equal(ans, 4) diff --git a/networkx/algorithms/similarity.py b/networkx/algorithms/similarity.py index 08e63b46..607cd7f5 100644 --- a/networkx/algorithms/similarity.py +++ b/networkx/algorithms/similarity.py @@ -669,7 +669,8 @@ def optimize_edit_paths( # TODO: support DiGraph import numpy as np - from scipy.optimize import linear_sum_assignment + import scipy as sp + import scipy.optimize # call as sp.optimize class CostMatrix: def __init__(self, C, lsa_row_ind, lsa_col_ind, ls): @@ -686,7 +687,7 @@ def optimize_edit_paths( def make_CostMatrix(C, m, n): # assert(C.shape == (m + n, m + n)) - lsa_row_ind, lsa_col_ind = linear_sum_assignment(C) + lsa_row_ind, lsa_col_ind = sp.optimize.linear_sum_assignment(C) # Fixup dummy assignments: # each substitution i<->j should have dummy assignment m+j<->n+i @@ -1306,13 +1307,13 @@ def simrank_similarity( If the nodes of the graph are numbered from zero to *n - 1*, where *n* is the number of nodes in the graph, you can create a SimRank matrix from the return value of this function where the node numbers are - the row and column indices of the matrix:: + the row and column indices of the matrix: - >>> from numpy import array - >>> G = nx.cycle_graph(4) - >>> sim = nx.simrank_similarity(G) - >>> lol = [[sim[u][v] for v in sorted(sim[u])] for u in sorted(sim)] - >>> sim_array = array(lol) + >>> import numpy as np + >>> G = nx.cycle_graph(4) + >>> sim = nx.simrank_similarity(G) + >>> lol = [[sim[u][v] for v in sorted(sim[u])] for u in sorted(sim)] + >>> sim_array = np.array(lol) References ---------- @@ -1408,9 +1409,8 @@ def simrank_similarity_numpy( Examples -------- - >>> from numpy import array - >>> G = nx.cycle_graph(4) - >>> sim = nx.simrank_similarity_numpy(G) + >>> G = nx.cycle_graph(4) + >>> sim = nx.simrank_similarity_numpy(G) References ---------- diff --git a/networkx/algorithms/tests/test_communicability.py b/networkx/algorithms/tests/test_communicability.py index c35cd33d..00d30136 100644 --- a/networkx/algorithms/tests/test_communicability.py +++ b/networkx/algorithms/tests/test_communicability.py @@ -2,8 +2,8 @@ from collections import defaultdict import pytest -numpy = pytest.importorskip("numpy") -scipy = pytest.importorskip("scipy") +pytest.importorskip("numpy") +pytest.importorskip("scipy") import networkx as nx from networkx.testing import almost_equal diff --git a/networkx/algorithms/tests/test_distance_measures.py b/networkx/algorithms/tests/test_distance_measures.py index 142deaad..e18b7341 100644 --- a/networkx/algorithms/tests/test_distance_measures.py +++ b/networkx/algorithms/tests/test_distance_measures.py @@ -95,10 +95,9 @@ class TestResistanceDistance: @classmethod def setup_class(cls): global np - global sp_sparse + global sp np = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") - sp_sparse = pytest.importorskip("scipy.sparse") + sp = pytest.importorskip("scipy") def setup_method(self): G = nx.Graph() @@ -111,8 +110,8 @@ class TestResistanceDistance: def test_laplacian_submatrix(self): from networkx.algorithms.distance_measures import _laplacian_submatrix - M = sp_sparse.csr_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32) - N = sp_sparse.csr_matrix([[5, 6], [8, 9]], dtype=np.float32) + M = sp.sparse.csr_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32) + N = sp.sparse.csr_matrix([[5, 6], [8, 9]], dtype=np.float32) Mn, Mn_nodelist = _laplacian_submatrix(1, M, [1, 2, 3]) assert Mn_nodelist == [2, 3] assert np.allclose(Mn.toarray(), N.toarray()) @@ -121,14 +120,14 @@ class TestResistanceDistance: with pytest.raises(nx.NetworkXError): from networkx.algorithms.distance_measures import _laplacian_submatrix - M = sp_sparse.csr_matrix([[1, 2], [4, 5], [7, 8]], dtype=np.float32) + M = sp.sparse.csr_matrix([[1, 2], [4, 5], [7, 8]], dtype=np.float32) _laplacian_submatrix(1, M, [1, 2, 3]) def test_laplacian_submatrix_matrix_node_dim(self): with pytest.raises(nx.NetworkXError): from networkx.algorithms.distance_measures import _laplacian_submatrix - M = sp_sparse.csr_matrix( + M = sp.sparse.csr_matrix( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32 ) _laplacian_submatrix(1, M, [1, 2, 3, 4]) diff --git a/networkx/algorithms/tests/test_graphical.py b/networkx/algorithms/tests/test_graphical.py index 3e244bbf..3bb93cf1 100644 --- a/networkx/algorithms/tests/test_graphical.py +++ b/networkx/algorithms/tests/test_graphical.py @@ -150,13 +150,13 @@ def test_pseudo_sequence(): def test_numpy_degree_sequence(): - numpy = pytest.importorskip("numpy") - ds = numpy.array([1, 2, 2, 2, 1], dtype=numpy.int64) + np = pytest.importorskip("numpy") + ds = np.array([1, 2, 2, 2, 1], dtype=np.int64) assert nx.is_graphical(ds, "eg") assert nx.is_graphical(ds, "hh") - ds = numpy.array([1, 2, 2, 2, 1], dtype=numpy.float64) + ds = np.array([1, 2, 2, 2, 1], dtype=np.float64) assert nx.is_graphical(ds, "eg") assert nx.is_graphical(ds, "hh") - ds = numpy.array([1.1, 2, 2, 2, 1], dtype=numpy.float64) + ds = np.array([1.1, 2, 2, 2, 1], dtype=np.float64) pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "eg") pytest.raises(nx.NetworkXException, nx.is_graphical, ds, "hh") diff --git a/networkx/algorithms/tests/test_non_randomness.py b/networkx/algorithms/tests/test_non_randomness.py index 17925eb7..30ec6c50 100644 --- a/networkx/algorithms/tests/test_non_randomness.py +++ b/networkx/algorithms/tests/test_non_randomness.py @@ -2,13 +2,12 @@ import networkx as nx import pytest -numpy = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") +np = pytest.importorskip("numpy") def test_non_randomness(): G = nx.karate_club_graph() - npt.assert_almost_equal(nx.non_randomness(G, 2)[0], 11.7, decimal=2) - npt.assert_almost_equal( + np.testing.assert_almost_equal(nx.non_randomness(G, 2)[0], 11.7, decimal=2) + np.testing.assert_almost_equal( nx.non_randomness(G)[0], 7.21, decimal=2 ) # infers 3 communities diff --git a/networkx/algorithms/tests/test_similarity.py b/networkx/algorithms/tests/test_similarity.py index 442f85cd..88022f5f 100644 --- a/networkx/algorithms/tests/test_similarity.py +++ b/networkx/algorithms/tests/test_similarity.py @@ -38,10 +38,9 @@ def getCanonical(): class TestSimilarity: @classmethod def setup_class(cls): - global numpy - global scipy - numpy = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") + global np + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") def test_graph_edit_distance_roots_and_timeout(self): G0 = nx.star_graph(5) @@ -653,7 +652,7 @@ class TestSimilarity: def test_simrank_numpy_no_source_no_target(self): G = nx.cycle_graph(5) - expected = numpy.array( + expected = np.array( [ [ 1.0, @@ -693,11 +692,11 @@ class TestSimilarity: ] ) actual = nx.simrank_similarity_numpy(G) - numpy.testing.assert_allclose(expected, actual, atol=1e-7) + np.testing.assert_allclose(expected, actual, atol=1e-7) def test_simrank_numpy_source_no_target(self): G = nx.cycle_graph(5) - expected = numpy.array( + expected = np.array( [ 1.0, 0.3947180735764555, @@ -707,13 +706,13 @@ class TestSimilarity: ] ) actual = nx.simrank_similarity_numpy(G, source=0) - numpy.testing.assert_allclose(expected, actual, atol=1e-7) + np.testing.assert_allclose(expected, actual, atol=1e-7) def test_simrank_numpy_source_and_target(self): G = nx.cycle_graph(5) expected = 1.0 actual = nx.simrank_similarity_numpy(G, source=0, target=0) - numpy.testing.assert_allclose(expected, actual, atol=1e-7) + np.testing.assert_allclose(expected, actual, atol=1e-7) def test_n_choose_k_small_k(self): assert _n_choose_k(10, 4) == 210 @@ -728,7 +727,7 @@ class TestSimilarity: assert _n_choose_k(5, 10) == 0 def test_panther_similarity_unweighted(self): - numpy.random.seed(42) + np.random.seed(42) G = nx.Graph() G.add_edge(0, 1) @@ -741,7 +740,7 @@ class TestSimilarity: assert sim == expected def test_panther_similarity_weighted(self): - numpy.random.seed(42) + np.random.seed(42) G = nx.Graph() G.add_edge("v1", "v2", weight=5) @@ -754,7 +753,7 @@ class TestSimilarity: assert sim == expected def test_generate_random_paths_unweighted(self): - numpy.random.seed(42) + np.random.seed(42) index_map = {} num_paths = 10 @@ -792,7 +791,7 @@ class TestSimilarity: assert expected_map == index_map def test_generate_random_paths_weighted(self): - numpy.random.seed(42) + np.random.seed(42) index_map = {} num_paths = 10 diff --git a/networkx/algorithms/tests/test_smallworld.py b/networkx/algorithms/tests/test_smallworld.py index 8b1b5377..6291f7d0 100644 --- a/networkx/algorithms/tests/test_smallworld.py +++ b/networkx/algorithms/tests/test_smallworld.py @@ -1,6 +1,6 @@ import pytest -numpy = pytest.importorskip("numpy") +pytest.importorskip("numpy") import random diff --git a/networkx/algorithms/tests/test_threshold.py b/networkx/algorithms/tests/test_threshold.py index fe8e1b9f..f6edb564 100644 --- a/networkx/algorithms/tests/test_threshold.py +++ b/networkx/algorithms/tests/test_threshold.py @@ -249,7 +249,7 @@ class TestGeneratorThreshold: def test_eigenvectors(self): np = pytest.importorskip("numpy") eigenval = np.linalg.eigvals - scipy = pytest.importorskip("scipy") + pytest.importorskip("scipy") cs = "ddiiddid" G = nxt.threshold_graph(cs) diff --git a/networkx/convert_matrix.py b/networkx/convert_matrix.py index 98ed6ea7..8db6ad63 100644 --- a/networkx/convert_matrix.py +++ b/networkx/convert_matrix.py @@ -818,7 +818,6 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight="weight", format alternate convention of doubling the edge weight is desired the resulting Scipy sparse matrix can be modified as follows: - >>> import scipy as sp >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_scipy_sparse_matrix(G) >>> print(A.todense()) @@ -849,7 +848,8 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight="weight", format .. [1] Scipy Dev. References, "Sparse Matrices", https://docs.scipy.org/doc/scipy/reference/sparse.html """ - from scipy import sparse + import scipy as sp + import scipy.sparse # call as sp.sparse if len(G) == 0: raise nx.NetworkXError("Graph has no nodes or edges") @@ -881,7 +881,7 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight="weight", format row, col, data = [], [], [] if G.is_directed(): - M = sparse.coo_matrix((data, (row, col)), shape=(nlen, nlen), dtype=dtype) + M = sp.sparse.coo_matrix((data, (row, col)), shape=(nlen, nlen), dtype=dtype) else: # symmetrize matrix d = data + data @@ -895,7 +895,7 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight="weight", format d += diag_data r += diag_index c += diag_index - M = sparse.coo_matrix((d, (r, c)), shape=(nlen, nlen), dtype=dtype) + M = sp.sparse.coo_matrix((d, (r, c)), shape=(nlen, nlen), dtype=dtype) try: return M.asformat(format) # From Scipy 1.1.0, asformat will throw a ValueError instead of an @@ -1006,6 +1006,7 @@ def from_scipy_sparse_matrix( Examples -------- >>> import scipy as sp + >>> import scipy.sparse # call as sp.sparse >>> A = sp.sparse.eye(2, 2, 1) >>> G = nx.from_scipy_sparse_matrix(A) diff --git a/networkx/drawing/layout.py b/networkx/drawing/layout.py index 3c379182..7bab044a 100644 --- a/networkx/drawing/layout.py +++ b/networkx/drawing/layout.py @@ -580,7 +580,8 @@ def _sparse_fruchterman_reingold( # Entry point for NetworkX graph is fruchterman_reingold_layout() # Sparse version import numpy as np - from scipy.sparse import coo_matrix + import scipy as sp + import scipy.sparse # call as sp.sparse try: nnodes, _ = A.shape @@ -591,7 +592,7 @@ def _sparse_fruchterman_reingold( try: A = A.tolil() except AttributeError: - A = (coo_matrix(A)).tolil() + A = (sp.sparse.coo_matrix(A)).tolil() if pos is None: # random initial positions @@ -729,12 +730,13 @@ def _kamada_kawai_solve(dist_mtx, pos_arr, dim): # and starting locations. import numpy as np - from scipy.optimize import minimize + import scipy as sp + import scipy.optimize # call as sp.optimize meanwt = 1e-3 costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim) - optresult = minimize( + optresult = sp.optimize.minimize( _kamada_kawai_costfn, pos_arr.ravel(), method="L-BFGS-B", @@ -875,8 +877,9 @@ def _sparse_spectral(A, dim=2): # Uses sparse eigenvalue solver from scipy # Could use multilevel methods here, see Koren "On spectral graph drawing" import numpy as np - from scipy.sparse import spdiags - from scipy.sparse.linalg.eigen import eigsh + import scipy as sp + import scipy.sparse # call as sp.sparse + import scipy.sparse.linalg # call as sp.sparse.linalg try: nnodes, _ = A.shape @@ -886,14 +889,14 @@ def _sparse_spectral(A, dim=2): # form Laplacian matrix data = np.asarray(A.sum(axis=1).T) - D = spdiags(data, 0, nnodes, nnodes) + D = sp.sparse.spdiags(data, 0, nnodes, nnodes) L = D - A k = dim + 1 # number of Lanczos vectors for ARPACK solver.What is the right scaling? ncv = max(2 * k + 1, int(np.sqrt(nnodes))) # return smallest k eigenvalues and eigenvectors - eigenvalues, eigenvectors = eigsh(L, k, which="SM", ncv=ncv) + eigenvalues, eigenvectors = sp.sparse.linalg.eigen.eigsh(L, k, which="SM", ncv=ncv) index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue return np.real(eigenvectors[:, index]) diff --git a/networkx/drawing/nx_pylab.py b/networkx/drawing/nx_pylab.py index 6a2c4e17..5dc84157 100644 --- a/networkx/drawing/nx_pylab.py +++ b/networkx/drawing/nx_pylab.py @@ -421,9 +421,10 @@ def draw_networkx_nodes( draw_networkx_edge_labels() """ from collections.abc import Iterable - import matplotlib.pyplot as plt - from matplotlib.collections import PathCollection import numpy as np + import matplotlib as mpl + import matplotlib.collections # call as mpl.collections + import matplotlib.pyplot as plt if ax is None: ax = plt.gca() @@ -432,7 +433,7 @@ def draw_networkx_nodes( nodelist = list(G) if len(nodelist) == 0: # empty nodelist, no drawing - return PathCollection(None) + return mpl.collections.PathCollection(None) try: xy = np.asarray([pos[v] for v in nodelist]) @@ -616,11 +617,12 @@ def draw_networkx_edges( draw_networkx_edge_labels() """ - import matplotlib.pyplot as plt - from matplotlib.colors import colorConverter, Colormap, Normalize - from matplotlib.patches import FancyArrowPatch, ConnectionStyle - from matplotlib.path import Path import numpy as np + import matplotlib as mpl + import matplotlib.colors # call as mpl.colors + import matplotlib.patches # call as mpl.patches + import matplotlib.path # call as mpl.path + import matplotlib.pyplot as plt if arrowstyle is not None and arrows is not None: warnings.warn( @@ -666,14 +668,14 @@ def draw_networkx_edges( and np.alltrue([isinstance(c, Number) for c in edge_color]) ): if edge_cmap is not None: - assert isinstance(edge_cmap, Colormap) + assert isinstance(edge_cmap, mpl.colors.Colormap) else: edge_cmap = plt.get_cmap() if edge_vmin is None: edge_vmin = min(edge_color) if edge_vmax is None: edge_vmax = max(edge_color) - color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax) + color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax) edge_color = [edge_cmap(color_normal(e)) for e in edge_color] # Note: Waiting for someone to implement arrow to intersection with @@ -698,7 +700,7 @@ def draw_networkx_edges( w = maxx - minx h = maxy - miny - base_connection_style = ConnectionStyle(connectionstyle) + base_connection_style = mpl.patches.ConnectionStyle(connectionstyle) def _connectionstyle(posA, posB, *args, **kwargs): # check if we need to do a self-loop @@ -722,7 +724,7 @@ def draw_networkx_edges( data_loc + np.asarray([0, v_shift]), ] - ret = Path(ax.transData.transform(path), [1, 4, 4, 4, 4, 4, 4]) + ret = mpl.path.Path(ax.transData.transform(path), [1, 4, 4, 4, 4, 4, 4]) # if not, fall back to the user specified behavior else: ret = base_connection_style(posA, posB, *args, **kwargs) @@ -730,7 +732,7 @@ def draw_networkx_edges( return ret # FancyArrowPatch doesn't handle color strings - arrow_colors = colorConverter.to_rgba_array(edge_color, alpha) + arrow_colors = mpl.colors.colorConverter.to_rgba_array(edge_color, alpha) for i, (src, dst) in enumerate(edge_pos): x1, y1 = src x2, y2 = dst @@ -766,7 +768,7 @@ def draw_networkx_edges( else: line_width = width - arrow = FancyArrowPatch( + arrow = mpl.patches.FancyArrowPatch( (x1, y1), (x2, y2), arrowstyle=arrowstyle, @@ -1248,13 +1250,14 @@ def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None): """ from itertools import islice, cycle import numpy as np - from matplotlib.colors import colorConverter - import matplotlib.cm as cm + import matplotlib as mpl + import matplotlib.colors # call as mpl.colors + import matplotlib.cm # call as mpl.cm # If we have been provided with a list of numbers as long as elem_list, # apply the color mapping. if len(colors) == len(elem_list) and isinstance(colors[0], Number): - mapper = cm.ScalarMappable(cmap=cmap) + mapper = mpl.cm.ScalarMappable(cmap=cmap) mapper.set_clim(vmin, vmax) rgba_colors = mapper.to_rgba(colors) # Otherwise, convert colors to matplotlib's RGB using the colorConverter @@ -1262,9 +1265,11 @@ def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None): # to_rgba method of ScalarMappable. else: try: - rgba_colors = np.array([colorConverter.to_rgba(colors)]) + rgba_colors = np.array([mpl.colors.colorConverter.to_rgba(colors)]) except ValueError: - rgba_colors = np.array([colorConverter.to_rgba(color) for color in colors]) + rgba_colors = np.array( + [mpl.colors.colorConverter.to_rgba(color) for color in colors] + ) # Set the final column of the rgba_colors to have the relevant alpha values try: # If alpha is longer than the number of colors, resize to the number of diff --git a/networkx/drawing/tests/test_layout.py b/networkx/drawing/tests/test_layout.py index 9527f363..c232ace9 100644 --- a/networkx/drawing/tests/test_layout.py +++ b/networkx/drawing/tests/test_layout.py @@ -5,7 +5,7 @@ from networkx.testing import almost_equal import pytest np = pytest.importorskip("numpy") -test_smoke_empty_graphscipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") class TestLayout: diff --git a/networkx/drawing/tests/test_pylab.py b/networkx/drawing/tests/test_pylab.py index fac1b467..868652cf 100644 --- a/networkx/drawing/tests/test_pylab.py +++ b/networkx/drawing/tests/test_pylab.py @@ -206,13 +206,17 @@ class TestPylab: def test_draw_empty_nodes_return_values(self): # See Issue #3833 - from matplotlib.collections import PathCollection + import matplotlib.collections # call as mpl.collections G = nx.Graph([(1, 2), (2, 3)]) DG = nx.DiGraph([(1, 2), (2, 3)]) pos = nx.circular_layout(G) - assert isinstance(nx.draw_networkx_nodes(G, pos, nodelist=[]), PathCollection) - assert isinstance(nx.draw_networkx_nodes(DG, pos, nodelist=[]), PathCollection) + assert isinstance( + nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection + ) + assert isinstance( + nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection + ) # drawing empty edges used to return an empty LineCollection or empty list. # Now it is always an empty list (because edges are now lists of FancyArrows) diff --git a/networkx/generators/geometric.py b/networkx/generators/geometric.py index 8a8eb841..ed72cafc 100644 --- a/networkx/generators/geometric.py +++ b/networkx/generators/geometric.py @@ -33,11 +33,12 @@ def geometric_edges(G, radius, p): """Returns edge list of node pairs within `radius` of each other Radius uses Minkowski distance metric `p`. - If scipy available, use scipy KDTree to speed computation. + If scipy available, use scipy cKDTree to speed computation. """ nodes_pos = G.nodes(data="pos") try: - from scipy.spatial import cKDTree as KDTree + import scipy as sp + import scipy.spatial # call as sp.spatial except ImportError: # no scipy KDTree so compute by for-loop radius_p = radius ** p @@ -49,7 +50,7 @@ def geometric_edges(G, radius, p): return edges # scipy KDTree is available nodes, coords = list(zip(*nodes_pos)) - kdtree = KDTree(coords) # Cannot provide generator. + kdtree = sp.spatial.cKDTree(coords) # Cannot provide generator. edge_indexes = kdtree.query_pairs(radius, p) edges = [(nodes[u], nodes[v]) for u, v in edge_indexes] return edges diff --git a/networkx/generators/random_graphs.py b/networkx/generators/random_graphs.py index 0cb18c49..25871224 100644 --- a/networkx/generators/random_graphs.py +++ b/networkx/generators/random_graphs.py @@ -1274,13 +1274,14 @@ def random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None): PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177 """ if kernel_root is None: - from scipy import optimize + import scipy as sp + import scipy.optimize # call as sp.optimize def kernel_root(y, a, r): def my_function(b): return kernel_integral(y, a, b) - r - return optimize.brentq(my_function, a, 1) + return sp.optimize.brentq(my_function, a, 1) graph = nx.Graph() graph.add_nodes_from(range(n)) diff --git a/networkx/generators/spectral_graph_forge.py b/networkx/generators/spectral_graph_forge.py index e59e9111..3a63bddb 100644 --- a/networkx/generators/spectral_graph_forge.py +++ b/networkx/generators/spectral_graph_forge.py @@ -44,7 +44,6 @@ def _mat_spect_approx(A, level, sorteigs=True, reverse=False, absolute=True): .. [2] L. Mirsky, Symmetric gauge functions and unitarily invariant norms """ - import numpy as np d, V = np.linalg.eigh(A) @@ -141,9 +140,9 @@ def spectral_graph_forge(G, alpha, transformation="identity", seed=None): >>> H = nx.spectral_graph_forge(G, 0.3) >>> """ - import numpy as np - from scipy import stats + import scipy as sp + import scipy.stats # call as sp.stats available_transformations = ["identity", "modularity"] alpha = np.clip(alpha, 0, 1) @@ -171,7 +170,7 @@ def spectral_graph_forge(G, alpha, transformation="identity", seed=None): np.fill_diagonal(B, 0) for i in range(n - 1): - B[i, i + 1 :] = stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed) + B[i, i + 1 :] = sp.stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed) B[i + 1 :, i] = np.transpose(B[i, i + 1 :]) H = nx.from_numpy_array(B) diff --git a/networkx/generators/tests/test_expanders.py b/networkx/generators/tests/test_expanders.py index a822e041..7b540f5a 100644 --- a/networkx/generators/tests/test_expanders.py +++ b/networkx/generators/tests/test_expanders.py @@ -24,11 +24,10 @@ def test_margulis_gabber_galil_graph(): assert 0 <= i < n np = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") - scipy.linalg = pytest.importorskip("scipy.linalg") + sp = pytest.importorskip("scipy") # Eigenvalues are already sorted using the scipy eigvalsh, # but the implementation in numpy does not guarantee order. - w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A)) + w = sorted(sp.linalg.eigvalsh(adjacency_matrix(g).A)) assert w[-2] < 5 * np.sqrt(2) @@ -41,7 +40,7 @@ def test_chordal_cycle_graph(): # TODO The second largest eigenvalue should be smaller than a constant, # independent of the number of nodes in the graph: # - # eigs = sorted(scipy.linalg.eigvalsh(adjacency_matrix(G).A)) + # eigs = sorted(sp.linalg.eigvalsh(adjacency_matrix(G).A)) # assert_less(eigs[-2], ...) # diff --git a/networkx/generators/tests/test_spectral_graph_forge.py b/networkx/generators/tests/test_spectral_graph_forge.py index 3f27a17d..b260f72e 100644 --- a/networkx/generators/tests/test_spectral_graph_forge.py +++ b/networkx/generators/tests/test_spectral_graph_forge.py @@ -1,5 +1,9 @@ import pytest +pytest.importorskip("numpy") +pytest.importorskip("scipy") + + from networkx import is_isomorphic from networkx.exception import NetworkXError from networkx.testing import assert_nodes_equal @@ -8,9 +12,6 @@ from networkx.generators import karate_club_graph def test_spectral_graph_forge(): - numpy = pytest.importorskip("numpy") - scipy = pytest.importorskip("scipy") - G = karate_club_graph() seed = 54321 diff --git a/networkx/linalg/algebraicconnectivity.py b/networkx/linalg/algebraicconnectivity.py index 1dc3a3ff..14dbfc8f 100644 --- a/networkx/linalg/algebraicconnectivity.py +++ b/networkx/linalg/algebraicconnectivity.py @@ -41,29 +41,30 @@ class _PCGSolver: def _solve(self, b, tol): import numpy as np - from scipy.linalg.blas import dasum, daxpy, ddot + import scipy as sp + import scipy.linalg.blas # call as sp.linalg.blas A = self._A M = self._M - tol *= dasum(b) + tol *= sp.linalg.blas.dasum(b) # Initialize. x = np.zeros(b.shape) r = b.copy() z = M(r) - rz = ddot(r, z) + rz = sp.linalg.blas.ddot(r, z) p = z.copy() # Iterate. while True: Ap = A(p) - alpha = rz / ddot(p, Ap) - x = daxpy(p, x, a=alpha) - r = daxpy(Ap, r, a=-alpha) - if dasum(r) < tol: + alpha = rz / sp.linalg.blas.ddot(p, Ap) + x = sp.linalg.blas.daxpy(p, x, a=alpha) + r = sp.linalg.blas.daxpy(Ap, r, a=-alpha) + if sp.linalg.blas.dasum(r) < tol: return x z = M(r) - beta = ddot(r, z) + beta = sp.linalg.blas.ddot(r, z) beta, rz = beta / rz, beta - p = daxpy(p, z, a=beta) + p = sp.linalg.blas.daxpy(p, z, a=beta) class _CholeskySolver: @@ -93,9 +94,10 @@ class _LUSolver: """ def __init__(self, A): - from scipy.sparse.linalg import splu + import scipy as sp + import scipy.sparse.linalg # call as sp.sparse.linalg - self._LU = splu( + self._LU = sp.sparse.linalg.splu( A, permc_spec="MMD_AT_PLUS_A", diag_pivot_thresh=0.0, @@ -188,8 +190,10 @@ def _tracemin_fiedler(L, X, normalized, tol, method): constant eigenvector) are avoided. """ import numpy as np - from scipy import linalg, sparse - from scipy.linalg.blas import dasum, daxpy + import scipy as sp + import scipy.linalg # call as sp.linalg + import scipy.linalg.blas # call as sp.linalg.blas + import scipy.sparse # call as sp.sparse n = X.shape[0] @@ -197,7 +201,7 @@ def _tracemin_fiedler(L, X, normalized, tol, method): # Form the normalized Laplacian matrix and determine the eigenvector of # its nullspace. e = np.sqrt(L.diagonal()) - D = sparse.spdiags(1.0 / e, [0], n, n, format="csr") + D = sp.sparse.spdiags(1.0 / e, [0], n, n, format="csr") L = D * L * D e *= 1.0 / np.linalg.norm(e, 2) @@ -222,7 +226,7 @@ def _tracemin_fiedler(L, X, normalized, tol, method): solver = _PCGSolver(lambda x: L * x, lambda x: D * x) elif method == "tracemin_lu" or method == "tracemin_chol": # Convert A to CSC to suppress SparseEfficiencyWarning. - A = sparse.csc_matrix(L, dtype=float, copy=True) + A = sp.sparse.csc_matrix(L, dtype=float, copy=True) # Force A to be nonsingular. Since A is the Laplacian matrix of a # connected graph, its rank deficiency is one, and thus one diagonal # element needs to modified. Changing to infinity forces a zero in the @@ -247,18 +251,18 @@ def _tracemin_fiedler(L, X, normalized, tol, method): # Compute iteration matrix H. W[:, :] = L @ X H = X.T @ W - sigma, Y = linalg.eigh(H, overwrite_a=True) + sigma, Y = sp.linalg.eigh(H, overwrite_a=True) # Compute the Ritz vectors. X = X @ Y # Test for convergence exploiting the fact that L * X == W * Y. - res = dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm + res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm if res < tol: break # Compute X = L \ X / (X' * (L \ X)). # L \ X can have an arbitrary projection on the nullspace of L, # which will be eliminated. W[:, :] = solver.solve(X, tol) - X = (linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order. + X = (sp.linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order. project(X) return sigma, np.asarray(X) @@ -281,27 +285,32 @@ def _get_fiedler_func(method): elif method == "lanczos" or method == "lobpcg": def find_fiedler(L, x, normalized, tol, seed): - from scipy import sparse - from scipy.sparse.linalg import eigsh, lobpcg + import scipy as sp + import scipy.sparse # call as sp.sparse + import scipy.sparse.linalg # call as sp.sparse.linalg - L = sparse.csc_matrix(L, dtype=float) + L = sp.sparse.csc_matrix(L, dtype=float) n = L.shape[0] if normalized: - D = sparse.spdiags(1.0 / np.sqrt(L.diagonal()), [0], n, n, format="csc") + D = sp.sparse.spdiags( + 1.0 / np.sqrt(L.diagonal()), [0], n, n, format="csc" + ) L = D * L * D if method == "lanczos" or n < 10: # Avoid LOBPCG when n < 10 due to # https://github.com/scipy/scipy/issues/3592 # https://github.com/scipy/scipy/pull/3594 - sigma, X = eigsh(L, 2, which="SM", tol=tol, return_eigenvectors=True) + sigma, X = sp.sparse.linalg.eigsh( + L, 2, which="SM", tol=tol, return_eigenvectors=True + ) return sigma[1], X[:, 1] else: X = np.asarray(np.atleast_2d(x).T) - M = sparse.spdiags(1.0 / L.diagonal(), [0], n, n) + M = sp.sparse.spdiags(1.0 / L.diagonal(), [0], n, n) Y = np.ones(n) if normalized: Y /= D.diagonal() - sigma, X = lobpcg( + sigma, X = sp.sparse.linalg.lobpcg( L, X, M=M, Y=np.atleast_2d(Y).T, tol=tol, maxiter=n, largest=False ) return sigma[0], X[:, 0] diff --git a/networkx/linalg/attrmatrix.py b/networkx/linalg/attrmatrix.py index 24443565..ffa6fa5b 100644 --- a/networkx/linalg/attrmatrix.py +++ b/networkx/linalg/attrmatrix.py @@ -426,7 +426,8 @@ def attr_sparse_matrix( """ import numpy as np - from scipy import sparse + import scipy as sp + import scipy.sparse # call as sp.sparse edge_value = _edge_value(G, edge_attr) node_value = _node_value(G, node_attr) @@ -439,7 +440,7 @@ def attr_sparse_matrix( N = len(ordering) undirected = not G.is_directed() index = dict(zip(ordering, range(N))) - M = sparse.lil_matrix((N, N), dtype=dtype) + M = sp.sparse.lil_matrix((N, N), dtype=dtype) seen = set() for u, nbrdict in G.adjacency(): diff --git a/networkx/linalg/bethehessianmatrix.py b/networkx/linalg/bethehessianmatrix.py index 5f9dc76b..a38ca86e 100644 --- a/networkx/linalg/bethehessianmatrix.py +++ b/networkx/linalg/bethehessianmatrix.py @@ -61,7 +61,8 @@ def bethe_hessian_matrix(G, r=None, nodelist=None): "Estimating the number of communities in networks by spectral methods" arXiv:1507.00827, 2015. """ - import scipy.sparse + import scipy as sp + import scipy.sparse # call as sp.sparse if nodelist is None: nodelist = list(G) @@ -73,6 +74,6 @@ def bethe_hessian_matrix(G, r=None, nodelist=None): A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, format="csr") n, m = A.shape diags = A.sum(axis=1) - D = scipy.sparse.spdiags(diags.flatten(), [0], m, n, format="csr") - I = scipy.sparse.eye(m, n, format="csr") + D = sp.sparse.spdiags(diags.flatten(), [0], m, n, format="csr") + I = sp.sparse.eye(m, n, format="csr") return (r ** 2 - 1) * I - r * A + D diff --git a/networkx/linalg/graphmatrix.py b/networkx/linalg/graphmatrix.py index a2fb48d7..73147857 100644 --- a/networkx/linalg/graphmatrix.py +++ b/networkx/linalg/graphmatrix.py @@ -56,7 +56,8 @@ def incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=Non .. [1] Gil Strang, Network applications: A = incidence matrix, http://academicearth.org/lectures/network-applications-incidence-matrix """ - import scipy.sparse + import scipy as sp + import scipy.sparse # call as sp.sparse if nodelist is None: nodelist = list(G) @@ -65,7 +66,7 @@ def incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=Non edgelist = list(G.edges(keys=True)) else: edgelist = list(G.edges()) - A = scipy.sparse.lil_matrix((len(nodelist), len(edgelist))) + A = sp.sparse.lil_matrix((len(nodelist), len(edgelist))) node_index = {node: i for i, node in enumerate(nodelist)} for ei, e in enumerate(edgelist): (u, v) = e[:2] @@ -134,7 +135,6 @@ def adjacency_matrix(G, nodelist=None, weight="weight"): alternate convention of doubling the edge weight is desired the resulting Scipy sparse matrix can be modified as follows: - >>> import scipy as sp >>> G = nx.Graph([(1, 1)]) >>> A = nx.adjacency_matrix(G) >>> print(A.todense()) diff --git a/networkx/linalg/laplacianmatrix.py b/networkx/linalg/laplacianmatrix.py index a13b2391..77623f81 100644 --- a/networkx/linalg/laplacianmatrix.py +++ b/networkx/linalg/laplacianmatrix.py @@ -46,14 +46,15 @@ def laplacian_matrix(G, nodelist=None, weight="weight"): normalized_laplacian_matrix laplacian_spectrum """ - from scipy.sparse import spdiags + import scipy as sp + import scipy.sparse # call as sp.sparse if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight, format="csr") n, m = A.shape diags = A.sum(axis=1) - D = spdiags(diags.flatten(), [0], m, n, format="csr") + D = sp.sparse.spdiags(diags.flatten(), [0], m, n, format="csr") return D - A @@ -111,19 +112,19 @@ def normalized_laplacian_matrix(G, nodelist=None, weight="weight"): """ import numpy as np import scipy as sp - from scipy.sparse import spdiags + import scipy.sparse # call as sp.sparse if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight, format="csr") n, m = A.shape diags = A.sum(axis=1).flatten() - D = spdiags(diags, [0], m, n, format="csr") + D = sp.sparse.spdiags(diags, [0], m, n, format="csr") L = D - A with sp.errstate(divide="ignore"): diags_sqrt = 1.0 / np.sqrt(diags) diags_sqrt[np.isinf(diags_sqrt)] = 0 - DH = spdiags(diags_sqrt, [0], m, n, format="csr") + DH = sp.sparse.spdiags(diags_sqrt, [0], m, n, format="csr") return DH @ (L @ DH) @@ -193,7 +194,8 @@ def directed_laplacian_matrix( Annals of Combinatorics, 9(1), 2005 """ import numpy as np - from scipy.sparse import spdiags, linalg + import scipy as sp + import scipy.sparse # call as sp.sparse P = _transition_matrix( G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha @@ -201,11 +203,15 @@ def directed_laplacian_matrix( n, m = P.shape - evals, evecs = linalg.eigs(P.T, k=1) + evals, evecs = sp.sparse.linalg.eigs(P.T, k=1) v = evecs.flatten().real p = v / v.sum() sqrtp = np.sqrt(p) - Q = spdiags(sqrtp, [0], n, n) * P * spdiags(1.0 / sqrtp, [0], n, n) + Q = ( + sp.sparse.spdiags(sqrtp, [0], n, n) + * P + * sp.sparse.spdiags(1.0 / sqrtp, [0], n, n) + ) I = np.identity(len(G)) return I - (Q + Q.T) / 2.0 @@ -270,7 +276,8 @@ def directed_combinatorial_laplacian_matrix( Laplacians and the Cheeger inequality for directed graphs. Annals of Combinatorics, 9(1), 2005 """ - from scipy.sparse import spdiags, linalg + import scipy as sp + import scipy.sparse # call as sp.sparse P = _transition_matrix( G, nodelist=nodelist, weight=weight, walk_type=walk_type, alpha=alpha @@ -278,10 +285,10 @@ def directed_combinatorial_laplacian_matrix( n, m = P.shape - evals, evecs = linalg.eigs(P.T, k=1) + evals, evecs = sp.sparse.linalg.eigs(P.T, k=1) v = evecs.flatten().real p = v / v.sum() - Phi = spdiags(p, [0], n, n) + Phi = sp.sparse.spdiags(p, [0], n, n) Phi = Phi.todense() @@ -327,7 +334,8 @@ def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha= If walk_type not specified or alpha not in valid range """ import numpy as np - from scipy.sparse import identity, spdiags + import scipy as sp + import scipy.sparse # call as sp.sparse if walk_type is None: if nx.is_strongly_connected(G): @@ -341,11 +349,11 @@ def _transition_matrix(G, nodelist=None, weight="weight", walk_type=None, alpha= M = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight, dtype=float) n, m = M.shape if walk_type in ["random", "lazy"]: - DI = spdiags(1.0 / np.array(M.sum(axis=1).flat), [0], n, n) + DI = sp.sparse.spdiags(1.0 / np.array(M.sum(axis=1).flat), [0], n, n) if walk_type == "random": P = DI * M else: - I = identity(n) + I = sp.sparse.identity(n) P = (I + DI * M) / 2.0 elif walk_type == "pagerank": diff --git a/networkx/linalg/spectrum.py b/networkx/linalg/spectrum.py index 2855b045..caa95fc5 100644 --- a/networkx/linalg/spectrum.py +++ b/networkx/linalg/spectrum.py @@ -38,9 +38,10 @@ def laplacian_spectrum(G, weight="weight"): -------- laplacian_matrix """ - from scipy.linalg import eigvalsh + import scipy as sp + import scipy.linalg # call as sp.linalg - return eigvalsh(nx.laplacian_matrix(G, weight=weight).todense()) + return sp.linalg.eigvalsh(nx.laplacian_matrix(G, weight=weight).todense()) def normalized_laplacian_spectrum(G, weight="weight"): @@ -69,9 +70,12 @@ def normalized_laplacian_spectrum(G, weight="weight"): -------- normalized_laplacian_matrix """ - from scipy.linalg import eigvalsh + import scipy as sp + import scipy.linalg # call as sp.linalg - return eigvalsh(nx.normalized_laplacian_matrix(G, weight=weight).todense()) + return sp.linalg.eigvalsh( + nx.normalized_laplacian_matrix(G, weight=weight).todense() + ) def adjacency_spectrum(G, weight="weight"): @@ -100,9 +104,10 @@ def adjacency_spectrum(G, weight="weight"): -------- adjacency_matrix """ - from scipy.linalg import eigvals + import scipy as sp + import scipy.linalg # call as sp.linalg - return eigvals(nx.adjacency_matrix(G, weight=weight).todense()) + return sp.linalg.eigvals(nx.adjacency_matrix(G, weight=weight).todense()) def modularity_spectrum(G): @@ -127,12 +132,13 @@ def modularity_spectrum(G): .. [1] M. E. J. Newman, "Modularity and community structure in networks", Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006. """ - from scipy.linalg import eigvals + import scipy as sp + import scipy.linalg # call as sp.linalg if G.is_directed(): - return eigvals(nx.directed_modularity_matrix(G)) + return sp.linalg.eigvals(nx.directed_modularity_matrix(G)) else: - return eigvals(nx.modularity_matrix(G)) + return sp.linalg.eigvals(nx.modularity_matrix(G)) def bethe_hessian_spectrum(G, r=None): @@ -161,6 +167,7 @@ def bethe_hessian_spectrum(G, r=None): "Spectral clustering of graphs with the bethe hessian", Advances in Neural Information Processing Systems. 2014. """ - from scipy.linalg import eigvalsh + import scipy as sp + import scipy.linalg # call as sp.linalg - return eigvalsh(nx.bethe_hessian_matrix(G, r).todense()) + return sp.linalg.eigvalsh(nx.bethe_hessian_matrix(G, r).todense()) diff --git a/networkx/linalg/tests/test_algebraic_connectivity.py b/networkx/linalg/tests/test_algebraic_connectivity.py index 9c784321..e95d0cff 100644 --- a/networkx/linalg/tests/test_algebraic_connectivity.py +++ b/networkx/linalg/tests/test_algebraic_connectivity.py @@ -13,6 +13,7 @@ methods = ("tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg") def test_algebraic_connectivity_tracemin_chol(): """Test that "tracemin_chol" raises an exception.""" + pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) with pytest.raises(nx.NetworkXError): nx.algebraic_connectivity(G, method="tracemin_chol") @@ -20,6 +21,7 @@ def test_algebraic_connectivity_tracemin_chol(): def test_fiedler_vector_tracemin_chol(): """Test that "tracemin_chol" raises an exception.""" + pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) with pytest.raises(nx.NetworkXError): nx.fiedler_vector(G, method="tracemin_chol") @@ -27,6 +29,7 @@ def test_fiedler_vector_tracemin_chol(): def test_spectral_ordering_tracemin_chol(): """Test that "tracemin_chol" raises an exception.""" + pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) with pytest.raises(nx.NetworkXError): nx.spectral_ordering(G, method="tracemin_chol") @@ -34,6 +37,7 @@ def test_spectral_ordering_tracemin_chol(): def test_fiedler_vector_tracemin_unknown(): """Test that "tracemin_unknown" raises an exception.""" + pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) L = nx.laplacian_matrix(G) X = np.asarray(np.random.normal(size=(1, L.shape[0]))).T @@ -84,12 +88,14 @@ class TestAlgebraicConnectivity: pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method) def test_unrecognized_method(self): + pytest.importorskip("scipy") G = nx.path_graph(4) pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method="unknown") pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method="unknown") @pytest.mark.parametrize("method", methods) def test_two_nodes(self, method): + pytest.importorskip("scipy") G = nx.Graph() G.add_edge(0, 1, weight=1) A = nx.laplacian_matrix(G) @@ -99,6 +105,7 @@ class TestAlgebraicConnectivity: @pytest.mark.parametrize("method", methods) def test_two_nodes_multigraph(self, method): + pytest.importorskip("scipy") G = nx.MultiGraph() G.add_edge(0, 0, spam=1e8) G.add_edge(0, 1, spam=1) @@ -111,6 +118,7 @@ class TestAlgebraicConnectivity: check_eigenvector(A, 6, x) def test_abbreviation_of_method(self): + pytest.importorskip("scipy") G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) @@ -121,6 +129,7 @@ class TestAlgebraicConnectivity: @pytest.mark.parametrize("method", methods) def test_path(self, method): + pytest.importorskip("scipy") G = nx.path_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2 + sqrt(2)) @@ -131,6 +140,7 @@ class TestAlgebraicConnectivity: @pytest.mark.parametrize("method", methods) def test_problematic_graph_issue_2381(self, method): + pytest.importorskip("scipy") G = nx.path_graph(4) G.add_edges_from([(4, 2), (5, 1)]) A = nx.laplacian_matrix(G) @@ -142,6 +152,7 @@ class TestAlgebraicConnectivity: @pytest.mark.parametrize("method", methods) def test_cycle(self, method): + pytest.importorskip("scipy") G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) @@ -152,6 +163,7 @@ class TestAlgebraicConnectivity: @pytest.mark.parametrize("method", methods) def test_seed_argument(self, method): + pytest.importorskip("scipy") G = nx.cycle_graph(8) A = nx.laplacian_matrix(G) sigma = 2 - sqrt(2) @@ -169,6 +181,7 @@ class TestAlgebraicConnectivity: ) @pytest.mark.parametrize("method", methods) def test_buckminsterfullerene(self, normalized, sigma, laplacian_fn, method): + pytest.importorskip("scipy") G = nx.Graph( [ (1, 10), @@ -304,6 +317,7 @@ class TestSpectralOrdering: @pytest.mark.parametrize("method", methods) def test_three_nodes(self, method): + pytest.importorskip("scipy") G = nx.Graph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1)], weight="spam") order = nx.spectral_ordering(G, weight="spam", method=method) @@ -312,6 +326,7 @@ class TestSpectralOrdering: @pytest.mark.parametrize("method", methods) def test_three_nodes_multigraph(self, method): + pytest.importorskip("scipy") G = nx.MultiDiGraph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1), (2, 3, 2)]) order = nx.spectral_ordering(G, method=method) @@ -320,6 +335,7 @@ class TestSpectralOrdering: @pytest.mark.parametrize("method", methods) def test_path(self, method): + pytest.importorskip("scipy") path = list(range(10)) np.random.shuffle(path) G = nx.Graph() @@ -329,6 +345,7 @@ class TestSpectralOrdering: @pytest.mark.parametrize("method", methods) def test_seed_argument(self, method): + pytest.importorskip("scipy") path = list(range(10)) np.random.shuffle(path) G = nx.Graph() @@ -338,6 +355,7 @@ class TestSpectralOrdering: @pytest.mark.parametrize("method", methods) def test_disconnected(self, method): + pytest.importorskip("scipy") G = nx.Graph() nx.add_path(G, range(0, 10, 2)) nx.add_path(G, range(1, 10, 2)) @@ -361,6 +379,7 @@ class TestSpectralOrdering: ) @pytest.mark.parametrize("method", methods) def test_cycle(self, normalized, expected_order, method): + pytest.importorskip("scipy") path = list(range(10)) G = nx.Graph() nx.add_path(G, path, weight=5) diff --git a/networkx/linalg/tests/test_attrmatrix.py b/networkx/linalg/tests/test_attrmatrix.py index fb1ea479..01574bb3 100644 --- a/networkx/linalg/tests/test_attrmatrix.py +++ b/networkx/linalg/tests/test_attrmatrix.py @@ -1,7 +1,6 @@ import pytest np = pytest.importorskip("numpy") -import numpy.testing as npt import networkx as nx @@ -20,7 +19,7 @@ def test_attr_matrix(): return G[u][v].get("thickness", 0.5) M = nx.attr_matrix(G, edge_attr=edge_attr, node_attr=node_attr) - npt.assert_equal(M[0], np.array([[6.0]])) + np.testing.assert_equal(M[0], np.array([[6.0]])) assert M[1] == [1.5] @@ -38,7 +37,7 @@ def test_attr_matrix_directed(): [0., 0., 0.]] ) # fmt: on - npt.assert_equal(M, np.array(data)) + np.testing.assert_equal(M, np.array(data)) def test_attr_matrix_multigraph(): @@ -56,7 +55,7 @@ def test_attr_matrix_multigraph(): [1., 1., 0.]] ) # fmt: on - npt.assert_equal(M, np.array(data)) + 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( @@ -65,7 +64,7 @@ def test_attr_matrix_multigraph(): [1., 1., 0.]] ) # fmt: on - npt.assert_equal(M, np.array(data)) + 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( @@ -74,7 +73,7 @@ def test_attr_matrix_multigraph(): [2., 3., 0.]] ) # fmt: on - npt.assert_equal(M, np.array(data)) + np.testing.assert_equal(M, np.array(data)) def test_attr_sparse_matrix(): @@ -87,11 +86,12 @@ def test_attr_sparse_matrix(): mtx = M[0] data = np.ones((3, 3), float) np.fill_diagonal(data, 0) - npt.assert_equal(mtx.todense(), np.array(data)) + 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) @@ -105,4 +105,4 @@ def test_attr_sparse_matrix_directed(): [0., 0., 0.]] ) # fmt: on - npt.assert_equal(M.todense(), np.array(data)) + np.testing.assert_equal(M.todense(), np.array(data)) diff --git a/networkx/linalg/tests/test_bethehessian.py b/networkx/linalg/tests/test_bethehessian.py index 64644ba4..339fe1be 100644 --- a/networkx/linalg/tests/test_bethehessian.py +++ b/networkx/linalg/tests/test_bethehessian.py @@ -1,8 +1,7 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") -sp = pytest.importorskip("scipy") +pytest.importorskip("scipy") import networkx as nx from networkx.generators.degree_seq import havel_hakimi_graph @@ -24,19 +23,19 @@ class TestBetheHessian: # fmt: on permutation = [2, 0, 1] # Bethe Hessian gives expected form - npt.assert_equal(nx.bethe_hessian_matrix(self.P, r=2).todense(), H) + np.testing.assert_equal(nx.bethe_hessian_matrix(self.P, r=2).todense(), H) # nodelist is correctly implemented - npt.assert_equal( + np.testing.assert_equal( nx.bethe_hessian_matrix(self.P, r=2, nodelist=permutation).todense(), H[np.ix_(permutation, permutation)], ) # Equal to Laplacian matrix when r=1 - npt.assert_equal( + np.testing.assert_equal( nx.bethe_hessian_matrix(self.G, r=1).todense(), nx.laplacian_matrix(self.G).todense(), ) # Correct default for the regularizer r - npt.assert_equal( + np.testing.assert_equal( nx.bethe_hessian_matrix(self.G).todense(), nx.bethe_hessian_matrix(self.G, r=1.25).todense(), ) diff --git a/networkx/linalg/tests/test_graphmatrix.py b/networkx/linalg/tests/test_graphmatrix.py index fdf3c640..5a9c70ca 100644 --- a/networkx/linalg/tests/test_graphmatrix.py +++ b/networkx/linalg/tests/test_graphmatrix.py @@ -1,8 +1,7 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") -scipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") import networkx as nx from networkx.generators.degree_seq import havel_hakimi_graph @@ -25,7 +24,7 @@ def test_incidence_matrix_simple(): [0, 0, 0, 0]] ) # fmt: on - npt.assert_equal(I, expected) + np.testing.assert_equal(I, expected) I = nx.incidence_matrix(MG).todense().astype(int) # fmt: off @@ -40,7 +39,7 @@ def test_incidence_matrix_simple(): [0, 0, 0, 0, 1, 0, 1]] ) # fmt: on - npt.assert_equal(I, expected) + np.testing.assert_equal(I, expected) with pytest.raises(NetworkXError): nx.incidence_matrix(G, nodelist=[0, 1]) @@ -114,7 +113,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, self.OI) + np.testing.assert_equal(I, self.OI) I = ( nx.incidence_matrix( @@ -126,7 +125,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, np.abs(self.OI)) + np.testing.assert_equal(I, np.abs(self.OI)) I = ( nx.incidence_matrix( @@ -138,7 +137,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, self.OI) + np.testing.assert_equal(I, self.OI) I = ( nx.incidence_matrix( @@ -150,7 +149,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, np.abs(self.OI)) + np.testing.assert_equal(I, np.abs(self.OI)) I = ( nx.incidence_matrix( @@ -162,7 +161,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, self.MGOI) + np.testing.assert_equal(I, self.MGOI) I = ( nx.incidence_matrix( @@ -174,7 +173,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, np.abs(self.MGOI)) + np.testing.assert_equal(I, np.abs(self.MGOI)) def test_weighted_incidence_matrix(self): I = ( @@ -187,7 +186,7 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, self.OI) + np.testing.assert_equal(I, self.OI) I = ( nx.incidence_matrix( @@ -199,13 +198,13 @@ class TestGraphMatrix: .todense() .astype(int) ) - npt.assert_equal(I, np.abs(self.OI)) + np.testing.assert_equal(I, np.abs(self.OI)) - # npt.assert_equal(nx.incidence_matrix(self.WG,oriented=True, + # np.testing.assert_equal(nx.incidence_matrix(self.WG,oriented=True, # weight='weight').todense(),0.5*self.OI) - # npt.assert_equal(nx.incidence_matrix(self.WG,weight='weight').todense(), + # np.testing.assert_equal(nx.incidence_matrix(self.WG,weight='weight').todense(), # np.abs(0.5*self.OI)) - # npt.assert_equal(nx.incidence_matrix(self.WG,oriented=True,weight='other').todense(), + # np.testing.assert_equal(nx.incidence_matrix(self.WG,oriented=True,weight='other').todense(), # 0.3*self.OI) I = nx.incidence_matrix( @@ -215,7 +214,7 @@ class TestGraphMatrix: oriented=True, weight="weight", ).todense() - npt.assert_equal(I, 0.5 * self.OI) + np.testing.assert_equal(I, 0.5 * self.OI) I = nx.incidence_matrix( self.WG, @@ -224,7 +223,7 @@ class TestGraphMatrix: oriented=False, weight="weight", ).todense() - npt.assert_equal(I, np.abs(0.5 * self.OI)) + np.testing.assert_equal(I, np.abs(0.5 * self.OI)) I = nx.incidence_matrix( self.WG, @@ -233,15 +232,15 @@ class TestGraphMatrix: oriented=True, weight="other", ).todense() - npt.assert_equal(I, 0.3 * self.OI) + np.testing.assert_equal(I, 0.3 * self.OI) # WMG=nx.MultiGraph(self.WG) # WMG.add_edge(0,1,weight=0.5,other=0.3) - # npt.assert_equal(nx.incidence_matrix(WMG,weight='weight').todense(), + # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='weight').todense(), # np.abs(0.5*self.MGOI)) - # npt.assert_equal(nx.incidence_matrix(WMG,weight='weight',oriented=True).todense(), + # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='weight',oriented=True).todense(), # 0.5*self.MGOI) - # npt.assert_equal(nx.incidence_matrix(WMG,weight='other',oriented=True).todense(), + # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='other',oriented=True).todense(), # 0.3*self.MGOI) WMG = nx.MultiGraph(self.WG) @@ -254,7 +253,7 @@ class TestGraphMatrix: oriented=True, weight="weight", ).todense() - npt.assert_equal(I, 0.5 * self.MGOI) + np.testing.assert_equal(I, 0.5 * self.MGOI) I = nx.incidence_matrix( WMG, @@ -263,7 +262,7 @@ class TestGraphMatrix: oriented=False, weight="weight", ).todense() - npt.assert_equal(I, np.abs(0.5 * self.MGOI)) + np.testing.assert_equal(I, np.abs(0.5 * self.MGOI)) I = nx.incidence_matrix( WMG, @@ -272,22 +271,24 @@ class TestGraphMatrix: oriented=True, weight="other", ).todense() - npt.assert_equal(I, 0.3 * self.MGOI) + np.testing.assert_equal(I, 0.3 * self.MGOI) def test_adjacency_matrix(self): "Conversion to adjacency matrix" - npt.assert_equal(nx.adj_matrix(self.G).todense(), self.A) - npt.assert_equal(nx.adj_matrix(self.MG).todense(), self.A) - npt.assert_equal(nx.adj_matrix(self.MG2).todense(), self.MG2A) - npt.assert_equal( + np.testing.assert_equal(nx.adj_matrix(self.G).todense(), self.A) + np.testing.assert_equal(nx.adj_matrix(self.MG).todense(), self.A) + np.testing.assert_equal(nx.adj_matrix(self.MG2).todense(), self.MG2A) + np.testing.assert_equal( nx.adj_matrix(self.G, nodelist=[0, 1]).todense(), self.A[:2, :2] ) - npt.assert_equal(nx.adj_matrix(self.WG).todense(), self.WA) - npt.assert_equal(nx.adj_matrix(self.WG, weight=None).todense(), self.A) - npt.assert_equal(nx.adj_matrix(self.MG2, weight=None).todense(), self.MG2A) - npt.assert_equal( + np.testing.assert_equal(nx.adj_matrix(self.WG).todense(), self.WA) + np.testing.assert_equal(nx.adj_matrix(self.WG, weight=None).todense(), self.A) + np.testing.assert_equal( + nx.adj_matrix(self.MG2, weight=None).todense(), self.MG2A + ) + np.testing.assert_equal( nx.adj_matrix(self.WG, weight="other").todense(), 0.6 * self.WA ) - npt.assert_equal( + np.testing.assert_equal( nx.adj_matrix(self.no_edges_G, nodelist=[1, 3]).todense(), self.no_edges_A ) diff --git a/networkx/linalg/tests/test_laplacian.py b/networkx/linalg/tests/test_laplacian.py index eeb3b6ea..3a825d5a 100644 --- a/networkx/linalg/tests/test_laplacian.py +++ b/networkx/linalg/tests/test_laplacian.py @@ -1,7 +1,6 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") pytest.importorskip("scipy") import networkx as nx @@ -36,15 +35,17 @@ class TestLaplacian: # fmt: on WL = 0.5 * NL OL = 0.3 * NL - npt.assert_equal(nx.laplacian_matrix(self.G).todense(), NL) - npt.assert_equal(nx.laplacian_matrix(self.MG).todense(), NL) - npt.assert_equal( + np.testing.assert_equal(nx.laplacian_matrix(self.G).todense(), NL) + np.testing.assert_equal(nx.laplacian_matrix(self.MG).todense(), NL) + np.testing.assert_equal( nx.laplacian_matrix(self.G, nodelist=[0, 1]).todense(), np.array([[1, -1], [-1, 1]]), ) - npt.assert_equal(nx.laplacian_matrix(self.WG).todense(), WL) - npt.assert_equal(nx.laplacian_matrix(self.WG, weight=None).todense(), NL) - npt.assert_equal(nx.laplacian_matrix(self.WG, weight="other").todense(), OL) + np.testing.assert_equal(nx.laplacian_matrix(self.WG).todense(), WL) + np.testing.assert_equal(nx.laplacian_matrix(self.WG, weight=None).todense(), NL) + np.testing.assert_equal( + nx.laplacian_matrix(self.WG, weight="other").todense(), OL + ) def test_normalized_laplacian(self): "Generalized Graph Laplacian" @@ -66,26 +67,26 @@ class TestLaplacian: [ 0. , 0. , 0. , 0. , 0. ]]) # fmt: on - npt.assert_almost_equal( + np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.G, nodelist=range(5)).todense(), G, decimal=3, ) - npt.assert_almost_equal( + np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.G).todense(), GL, decimal=3 ) - npt.assert_almost_equal( + np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.MG).todense(), GL, decimal=3 ) - npt.assert_almost_equal( + np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.WG).todense(), GL, decimal=3 ) - npt.assert_almost_equal( + np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.WG, weight="other").todense(), GL, decimal=3, ) - npt.assert_almost_equal( + np.testing.assert_almost_equal( nx.normalized_laplacian_matrix(self.Gsl).todense(), Lsl, decimal=3 ) @@ -118,7 +119,7 @@ class TestLaplacian: [-0.0261, -0.0554, -0.0251, -0.6675, -0.2078, 0.9833]]) # fmt: on L = nx.directed_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G)) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) # Make the graph strongly connected, so we can use a random and lazy walk G.add_edges_from(((2, 5), (6, 1))) @@ -133,7 +134,7 @@ class TestLaplacian: L = nx.directed_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="random" ) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) # fmt: off GL = np.array([[ 0.5 , -0.1531, -0.2357, 0. , 0. , -0.1614], @@ -146,7 +147,7 @@ class TestLaplacian: L = nx.directed_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="lazy" ) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) # Make a strongly connected periodic graph G = nx.DiGraph() @@ -166,7 +167,7 @@ class TestLaplacian: [-0.25 , -0.176, -0.176, 0.5 ]]) # fmt: on L = nx.directed_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G)) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) def test_directed_combinatorial_laplacian(self): "Directed combinatorial Laplacian" @@ -198,7 +199,7 @@ class TestLaplacian: # fmt: on L = nx.directed_combinatorial_laplacian_matrix(G, alpha=0.9, nodelist=sorted(G)) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) # Make the graph strongly connected, so we can use a random and lazy walk G.add_edges_from(((2, 5), (6, 1))) @@ -215,7 +216,7 @@ class TestLaplacian: L = nx.directed_combinatorial_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="random" ) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) # fmt: off GL = np.array([[ 0.0698, -0.0174, -0.0233, 0. , 0. , -0.0291], @@ -229,7 +230,7 @@ class TestLaplacian: L = nx.directed_combinatorial_laplacian_matrix( G, alpha=0.9, nodelist=sorted(G), walk_type="lazy" ) - npt.assert_almost_equal(L, GL, decimal=3) + np.testing.assert_almost_equal(L, GL, decimal=3) E = nx.DiGraph(margulis_gabber_galil_graph(2)) L = nx.directed_combinatorial_laplacian_matrix(E) @@ -241,7 +242,7 @@ class TestLaplacian: [ 0. , -0.08333333, -0.08333333, 0.16666667]] ) # fmt: on - npt.assert_almost_equal(L, expected, decimal=6) + np.testing.assert_almost_equal(L, expected, decimal=6) with pytest.raises(nx.NetworkXError): nx.directed_combinatorial_laplacian_matrix( diff --git a/networkx/linalg/tests/test_modularity.py b/networkx/linalg/tests/test_modularity.py index ccf730fe..9f94ff4d 100644 --- a/networkx/linalg/tests/test_modularity.py +++ b/networkx/linalg/tests/test_modularity.py @@ -1,8 +1,7 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") -scipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") import networkx as nx from networkx.generators.degree_seq import havel_hakimi_graph @@ -42,8 +41,8 @@ class TestModularity: # fmt: on permutation = [4, 0, 1, 2, 3] - npt.assert_equal(nx.modularity_matrix(self.G), B) - npt.assert_equal( + np.testing.assert_equal(nx.modularity_matrix(self.G), B) + np.testing.assert_equal( nx.modularity_matrix(self.G, nodelist=permutation), B[np.ix_(permutation, permutation)], ) @@ -62,9 +61,11 @@ class TestModularity: for n1, n2 in G_weighted.edges(): G_weighted.edges[n1, n2]["weight"] = 0.5 # The following test would fail in networkx 1.1 - npt.assert_equal(nx.modularity_matrix(G_weighted), B) + np.testing.assert_equal(nx.modularity_matrix(G_weighted), B) # The following test that the modularity matrix get rescaled accordingly - npt.assert_equal(nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B) + np.testing.assert_equal( + nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B + ) def test_directed_modularity(self): "Directed Modularity matrix" @@ -79,8 +80,8 @@ class TestModularity: node_permutation = [5, 1, 2, 3, 4, 6] idx_permutation = [4, 0, 1, 2, 3, 5] mm = nx.directed_modularity_matrix(self.DG, nodelist=sorted(self.DG)) - npt.assert_equal(mm, B) - npt.assert_equal( + np.testing.assert_equal(mm, B) + np.testing.assert_equal( nx.directed_modularity_matrix(self.DG, nodelist=node_permutation), B[np.ix_(idx_permutation, idx_permutation)], ) diff --git a/networkx/linalg/tests/test_spectrum.py b/networkx/linalg/tests/test_spectrum.py index 63e12d37..e9101303 100644 --- a/networkx/linalg/tests/test_spectrum.py +++ b/networkx/linalg/tests/test_spectrum.py @@ -1,8 +1,7 @@ import pytest np = pytest.importorskip("numpy") -npt = pytest.importorskip("numpy.testing") -scipy = pytest.importorskip("scipy") +pytest.importorskip("scipy") import networkx as nx from networkx.generators.degree_seq import havel_hakimi_graph @@ -25,48 +24,48 @@ class TestSpectrum: "Laplacian eigenvalues" evals = np.array([0, 0, 1, 3, 4]) e = sorted(nx.laplacian_spectrum(self.G)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) e = sorted(nx.laplacian_spectrum(self.WG, weight=None)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) e = sorted(nx.laplacian_spectrum(self.WG)) - npt.assert_almost_equal(e, 0.5 * evals) + np.testing.assert_almost_equal(e, 0.5 * evals) e = sorted(nx.laplacian_spectrum(self.WG, weight="other")) - npt.assert_almost_equal(e, 0.3 * evals) + np.testing.assert_almost_equal(e, 0.3 * evals) def test_normalized_laplacian_spectrum(self): "Normalized Laplacian eigenvalues" evals = np.array([0, 0, 0.7712864461218, 1.5, 1.7287135538781]) e = sorted(nx.normalized_laplacian_spectrum(self.G)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight=None)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) e = sorted(nx.normalized_laplacian_spectrum(self.WG)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight="other")) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) def test_adjacency_spectrum(self): "Adjacency eigenvalues" evals = np.array([-np.sqrt(2), 0, np.sqrt(2)]) e = sorted(nx.adjacency_spectrum(self.P)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) def test_modularity_spectrum(self): "Modularity eigenvalues" evals = np.array([-1.5, 0.0, 0.0]) e = sorted(nx.modularity_spectrum(self.P)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) # Directed modularity eigenvalues evals = np.array([-0.5, 0.0, 0.0]) e = sorted(nx.modularity_spectrum(self.DG)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) def test_bethe_hessian_spectrum(self): "Bethe Hessian eigenvalues" evals = np.array([0.5 * (9 - np.sqrt(33)), 4, 0.5 * (9 + np.sqrt(33))]) e = sorted(nx.bethe_hessian_spectrum(self.P, r=2)) - npt.assert_almost_equal(e, evals) + np.testing.assert_almost_equal(e, evals) # Collapses back to Laplacian: e1 = sorted(nx.bethe_hessian_spectrum(self.P, r=1)) e2 = sorted(nx.laplacian_spectrum(self.P)) - npt.assert_almost_equal(e1, e2) + np.testing.assert_almost_equal(e1, e2) diff --git a/networkx/tests/test_convert_numpy.py b/networkx/tests/test_convert_numpy.py index debd6d82..b62f823f 100644 --- a/networkx/tests/test_convert_numpy.py +++ b/networkx/tests/test_convert_numpy.py @@ -1,7 +1,6 @@ import pytest np = pytest.importorskip("numpy") -npt = np.testing import networkx as nx from networkx.generators.classic import barbell_graph, cycle_graph, path_graph @@ -121,11 +120,13 @@ class TestConvertNumpyMatrix: WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3)) for n in range(3)) P4 = path_graph(4) A = nx.to_numpy_matrix(P4) - npt.assert_equal(A, nx.to_numpy_matrix(WP4, weight=None)) - npt.assert_equal(0.5 * A, nx.to_numpy_matrix(WP4)) - npt.assert_equal(0.3 * A, nx.to_numpy_matrix(WP4, weight="other")) + np.testing.assert_equal(A, nx.to_numpy_matrix(WP4, weight=None)) + np.testing.assert_equal(0.5 * A, nx.to_numpy_matrix(WP4)) + np.testing.assert_equal(0.3 * A, nx.to_numpy_matrix(WP4, weight="other")) def test_from_numpy_matrix_type(self): + pytest.importorskip("scipy") + A = np.matrix([[1]]) G = nx.from_numpy_matrix(A) assert type(G[0][0]["weight"]) == int @@ -323,9 +324,9 @@ class TestConvertNumpyArray: WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3)) for n in range(3)) P4 = path_graph(4) A = nx.to_numpy_array(P4) - npt.assert_equal(A, nx.to_numpy_array(WP4, weight=None)) - npt.assert_equal(0.5 * A, nx.to_numpy_array(WP4)) - npt.assert_equal(0.3 * A, nx.to_numpy_array(WP4, weight="other")) + np.testing.assert_equal(A, nx.to_numpy_array(WP4, weight=None)) + np.testing.assert_equal(0.5 * A, nx.to_numpy_array(WP4)) + np.testing.assert_equal(0.3 * A, nx.to_numpy_array(WP4, weight="other")) def test_from_numpy_array_type(self): A = np.array([[1]]) @@ -461,8 +462,8 @@ def test_to_numpy_recarray_directed(recarray_test_graph): G = recarray_test_graph.to_directed() G.remove_edge(2, 1) A = nx.to_numpy_recarray(G, dtype=[("weight", float), ("cost", int)]) - npt.assert_array_equal(A.weight, np.array([[0, 7.0], [0, 0]])) - npt.assert_array_equal(A.cost, np.array([[0, 5], [0, 0]])) + np.testing.assert_array_equal(A.weight, np.array([[0, 7.0], [0, 0]])) + np.testing.assert_array_equal(A.cost, np.array([[0, 5], [0, 0]])) def test_to_numpy_recarray_default_dtype_no_weight(): @@ -489,7 +490,7 @@ def recarray_nodelist_test_graph(): def test_to_numpy_recarray_nodelist(recarray_nodelist_test_graph): A = nx.to_numpy_recarray(recarray_nodelist_test_graph, nodelist=[0, 1]) - npt.assert_array_equal(A.weight, np.array([[0, 1], [1, 0]])) + np.testing.assert_array_equal(A.weight, np.array([[0, 1], [1, 0]])) @pytest.mark.parametrize( diff --git a/networkx/tests/test_convert_scipy.py b/networkx/tests/test_convert_scipy.py index a1d558d8..c246152a 100644 --- a/networkx/tests/test_convert_scipy.py +++ b/networkx/tests/test_convert_scipy.py @@ -2,8 +2,7 @@ import pytest np = pytest.importorskip("numpy") sp = pytest.importorskip("scipy") -sp_sparse = sp.sparse -npt = np.testing +import scipy.sparse # call as sp.sparse import networkx as nx from networkx.testing import assert_graphs_equal @@ -115,11 +114,13 @@ class TestConvertScipy: WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3)) for n in range(3)) P4 = path_graph(4) A = nx.to_scipy_sparse_matrix(P4) - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) - npt.assert_equal(0.5 * A.todense(), nx.to_scipy_sparse_matrix(WP4).todense()) - npt.assert_equal( + np.testing.assert_equal( + 0.5 * A.todense(), nx.to_scipy_sparse_matrix(WP4).todense() + ) + np.testing.assert_equal( 0.3 * A.todense(), nx.to_scipy_sparse_matrix(WP4, weight="other").todense() ) @@ -128,37 +129,37 @@ class TestConvertScipy: WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3)) for n in range(3)) P4 = path_graph(4) A = nx.to_scipy_sparse_matrix(P4, format="csr") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) A = nx.to_scipy_sparse_matrix(P4, format="csc") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) A = nx.to_scipy_sparse_matrix(P4, format="coo") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) A = nx.to_scipy_sparse_matrix(P4, format="bsr") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) A = nx.to_scipy_sparse_matrix(P4, format="lil") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) A = nx.to_scipy_sparse_matrix(P4, format="dia") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) A = nx.to_scipy_sparse_matrix(P4, format="dok") - npt.assert_equal( + np.testing.assert_equal( A.todense(), nx.to_scipy_sparse_matrix(WP4, weight=None).todense() ) @@ -179,7 +180,7 @@ class TestConvertScipy: G = nx.Graph() G.add_node(1) M = nx.to_scipy_sparse_matrix(G) - npt.assert_equal(M.todense(), np.matrix([[0]])) + np.testing.assert_equal(M.todense(), np.matrix([[0]])) def test_ordering(self): G = nx.DiGraph() @@ -187,25 +188,31 @@ class TestConvertScipy: G.add_edge(2, 3) G.add_edge(3, 1) M = nx.to_scipy_sparse_matrix(G, nodelist=[3, 2, 1]) - npt.assert_equal(M.todense(), np.matrix([[0, 0, 1], [1, 0, 0], [0, 1, 0]])) + np.testing.assert_equal( + M.todense(), np.matrix([[0, 0, 1], [1, 0, 0], [0, 1, 0]]) + ) def test_selfloop_graph(self): G = nx.Graph([(1, 1)]) M = nx.to_scipy_sparse_matrix(G) - npt.assert_equal(M.todense(), np.matrix([[1]])) + np.testing.assert_equal(M.todense(), np.matrix([[1]])) G.add_edges_from([(2, 3), (3, 4)]) M = nx.to_scipy_sparse_matrix(G, nodelist=[2, 3, 4]) - npt.assert_equal(M.todense(), np.matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])) + np.testing.assert_equal( + M.todense(), np.matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) + ) def test_selfloop_digraph(self): G = nx.DiGraph([(1, 1)]) M = nx.to_scipy_sparse_matrix(G) - npt.assert_equal(M.todense(), np.matrix([[1]])) + np.testing.assert_equal(M.todense(), np.matrix([[1]])) G.add_edges_from([(2, 3), (3, 4)]) M = nx.to_scipy_sparse_matrix(G, nodelist=[2, 3, 4]) - npt.assert_equal(M.todense(), np.matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]])) + np.testing.assert_equal( + M.todense(), np.matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) + ) def test_from_scipy_sparse_matrix_parallel_edges(self): """Tests that the :func:`networkx.from_scipy_sparse_matrix` function @@ -213,7 +220,7 @@ class TestConvertScipy: creating a multigraph. """ - A = sp_sparse.csr_matrix([[1, 1], [1, 2]]) + A = sp.sparse.csr_matrix([[1, 1], [1, 2]]) # First, with a simple graph, each integer entry in the adjacency # matrix is interpreted as the weight of a single edge in the graph. expected = nx.DiGraph() @@ -253,7 +260,7 @@ class TestConvertScipy: :func:`networkx.from_scipy_sparse_matrix`. """ - A = sp_sparse.csr_matrix([[0, 1], [1, 0]]) + A = sp.sparse.csr_matrix([[0, 1], [1, 0]]) G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph) expected = nx.MultiGraph() expected.add_edge(0, 1, weight=1) @@ -275,5 +282,5 @@ def test_from_scipy_sparse_matrix_formats(sparse_format): (2, 1, {"weight": 1}), ] ) - A = sp_sparse.coo_matrix([[0, 3, 2], [3, 0, 1], [2, 1, 0]]).asformat(sparse_format) + A = sp.sparse.coo_matrix([[0, 3, 2], [3, 0, 1], [2, 1, 0]]).asformat(sparse_format) assert_graphs_equal(expected, nx.from_scipy_sparse_matrix(A)) diff --git a/networkx/utils/decorators.py b/networkx/utils/decorators.py index e73e8703..5c474298 100644 --- a/networkx/utils/decorators.py +++ b/networkx/utils/decorators.py @@ -332,19 +332,19 @@ def preserve_random_state(func): If numpy.random is not importable, the state is not saved or restored. """ try: - from numpy.random import get_state, seed, set_state + import numpy as np @contextmanager def save_random_state(): - state = get_state() + state = np.random.get_state() try: yield finally: - set_state(state) + np.random.set_state(state) def wrapper(*args, **kwargs): with save_random_state(): - seed(1234567890) + np.random.seed(1234567890) return func(*args, **kwargs) wrapper.__name__ = func.__name__ diff --git a/networkx/utils/tests/test_misc.py b/networkx/utils/tests/test_misc.py index b20648cb..4abb7ce6 100644 --- a/networkx/utils/tests/test_misc.py +++ b/networkx/utils/tests/test_misc.py @@ -127,15 +127,13 @@ def test_make_str_with_unicode(): class TestNumpyArray: @classmethod def setup_class(cls): - global numpy - global assert_allclose - numpy = pytest.importorskip("numpy") - assert_allclose = numpy.testing.assert_allclose + global np + np = pytest.importorskip("numpy") def test_numpy_to_list_of_ints(self): - a = numpy.array([1, 2, 3], dtype=numpy.int64) - b = numpy.array([1.0, 2, 3]) - c = numpy.array([1.1, 2, 3]) + a = np.array([1, 2, 3], dtype=np.int64) + b = np.array([1.0, 2, 3]) + c = np.array([1.1, 2, 3]) assert type(make_list_of_ints(a)) == list assert make_list_of_ints(b) == list(b) B = make_list_of_ints(b) @@ -145,46 +143,46 @@ class TestNumpyArray: def test_dict_to_numpy_array1(self): d = {"a": 1, "b": 2} a = dict_to_numpy_array1(d, mapping={"a": 0, "b": 1}) - assert_allclose(a, numpy.array([1, 2])) + np.testing.assert_allclose(a, np.array([1, 2])) a = dict_to_numpy_array1(d, mapping={"b": 0, "a": 1}) - assert_allclose(a, numpy.array([2, 1])) + np.testing.assert_allclose(a, np.array([2, 1])) a = dict_to_numpy_array1(d) - assert_allclose(a.sum(), 3) + np.testing.assert_allclose(a.sum(), 3) def test_dict_to_numpy_array2(self): d = {"a": {"a": 1, "b": 2}, "b": {"a": 10, "b": 20}} mapping = {"a": 1, "b": 0} a = dict_to_numpy_array2(d, mapping=mapping) - assert_allclose(a, numpy.array([[20, 10], [2, 1]])) + np.testing.assert_allclose(a, np.array([[20, 10], [2, 1]])) a = dict_to_numpy_array2(d) - assert_allclose(a.sum(), 33) + np.testing.assert_allclose(a.sum(), 33) def test_dict_to_numpy_array_a(self): d = {"a": {"a": 1, "b": 2}, "b": {"a": 10, "b": 20}} mapping = {"a": 0, "b": 1} a = dict_to_numpy_array(d, mapping=mapping) - assert_allclose(a, numpy.array([[1, 2], [10, 20]])) + np.testing.assert_allclose(a, np.array([[1, 2], [10, 20]])) mapping = {"a": 1, "b": 0} a = dict_to_numpy_array(d, mapping=mapping) - assert_allclose(a, numpy.array([[20, 10], [2, 1]])) + np.testing.assert_allclose(a, np.array([[20, 10], [2, 1]])) a = dict_to_numpy_array2(d) - assert_allclose(a.sum(), 33) + np.testing.assert_allclose(a.sum(), 33) def test_dict_to_numpy_array_b(self): d = {"a": 1, "b": 2} mapping = {"a": 0, "b": 1} a = dict_to_numpy_array(d, mapping=mapping) - assert_allclose(a, numpy.array([1, 2])) + np.testing.assert_allclose(a, np.array([1, 2])) a = dict_to_numpy_array1(d) - assert_allclose(a.sum(), 3) + np.testing.assert_allclose(a.sum(), 3) def test_pairwise(): |