diff options
author | Jarrod Millman <jarrod.millman@gmail.com> | 2020-09-09 17:56:24 -0700 |
---|---|---|
committer | Jarrod Millman <jarrod.millman@gmail.com> | 2020-09-15 20:00:19 -0700 |
commit | 79d6620a80427726aa9d540fbb75b5aa3b8c0b37 (patch) | |
tree | 3f476bfee816ebdf4df8c7b24daa501644abd118 /networkx | |
parent | 5f2445c1b5ff4db2dd0f943e006df1a107e8f00b (diff) | |
download | networkx-79d6620a80427726aa9d540fbb75b5aa3b8c0b37.tar.gz |
Simplify imports
Diffstat (limited to 'networkx')
-rw-r--r-- | networkx/algorithms/assortativity/correlation.py | 30 | ||||
-rw-r--r-- | networkx/algorithms/bipartite/matching.py | 16 | ||||
-rw-r--r-- | networkx/algorithms/bipartite/spectral.py | 8 | ||||
-rw-r--r-- | networkx/algorithms/centrality/current_flow_betweenness.py | 8 | ||||
-rw-r--r-- | networkx/algorithms/centrality/current_flow_betweenness_subset.py | 15 | ||||
-rw-r--r-- | networkx/algorithms/centrality/katz.py | 6 | ||||
-rw-r--r-- | networkx/algorithms/centrality/second_order.py | 6 | ||||
-rw-r--r-- | networkx/algorithms/centrality/trophic.py | 12 | ||||
-rw-r--r-- | networkx/algorithms/link_analysis/hits_alg.py | 15 | ||||
-rw-r--r-- | networkx/algorithms/node_classification/hmn.py | 14 | ||||
-rw-r--r-- | networkx/algorithms/node_classification/lgc.py | 14 | ||||
-rw-r--r-- | networkx/algorithms/non_randomness.py | 7 | ||||
-rw-r--r-- | networkx/algorithms/shortest_paths/dense.py | 5 | ||||
-rw-r--r-- | networkx/convert.py | 3 | ||||
-rw-r--r-- | networkx/drawing/layout.py | 6 | ||||
-rw-r--r-- | networkx/drawing/nx_pylab.py | 74 | ||||
-rw-r--r-- | networkx/linalg/algebraicconnectivity.py | 31 | ||||
-rw-r--r-- | networkx/linalg/attrmatrix.py | 14 |
18 files changed, 65 insertions, 219 deletions
diff --git a/networkx/algorithms/assortativity/correlation.py b/networkx/algorithms/assortativity/correlation.py index 17b3331c..4897af3b 100644 --- a/networkx/algorithms/assortativity/correlation.py +++ b/networkx/algorithms/assortativity/correlation.py @@ -129,10 +129,8 @@ 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). """ - try: - import scipy.stats as stats - except ImportError as e: - raise ImportError("Assortativity requires SciPy:" "http://scipy.org/ ") from e + import scipy.stats as stats + xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight) x, y = zip(*xy) return stats.pearsonr(x, y)[0] @@ -250,12 +248,6 @@ def attribute_ac(M): .. [1] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003 """ - try: - import numpy - except ImportError as e: - raise ImportError( - "attribute_assortativity requires " "NumPy: http://scipy.org/" - ) from e if M.sum() != 1.0: M = M / M.sum() s = (M @ M).sum() @@ -267,21 +259,17 @@ def attribute_ac(M): def numeric_ac(M): # M is a numpy matrix or array # numeric assortativity coefficient, pearsonr - try: - import numpy - except ImportError as e: - raise ImportError( - "numeric_assortativity requires " "NumPy: http://scipy.org/" - ) from e + import numpy as np + if M.sum() != 1.0: M = M / float(M.sum()) nx, ny = M.shape # nx=ny - x = numpy.arange(nx) - y = numpy.arange(ny) + x = np.arange(nx) + y = np.arange(ny) a = M.sum(axis=0) b = M.sum(axis=1) vara = (a * x ** 2).sum() - ((a * x).sum()) ** 2 varb = (b * x ** 2).sum() - ((b * x).sum()) ** 2 - xy = numpy.outer(x, y) - ab = numpy.outer(a, b) - return (xy * (M - ab)).sum() / numpy.sqrt(vara * varb) + xy = np.outer(x, y) + ab = np.outer(a, b) + return (xy * (M - ab)).sum() / np.sqrt(vara * varb) diff --git a/networkx/algorithms/bipartite/matching.py b/networkx/algorithms/bipartite/matching.py index e8a3e025..b89d89bd 100644 --- a/networkx/algorithms/bipartite/matching.py +++ b/networkx/algorithms/bipartite/matching.py @@ -57,13 +57,13 @@ INFINITY = float("inf") def hopcroft_karp_matching(G, top_nodes=None): """Returns the maximum cardinality matching of the bipartite graph `G`. - A matching is a set of edges that do not share any nodes. A maximum + A matching is a set of edges that do not share any nodes. A maximum cardinality matching is a matching with the most edges possible. It is not always unique. Finding a matching in a bipartite graph can be treated as a networkx flow problem. - + The functions ``hopcroft_karp_matching`` and ``maximum_matching`` - are aliases of the same function. + are aliases of the same function. Parameters ---------- @@ -556,13 +556,9 @@ def minimum_weight_full_matching(G, top_nodes=None, weight="weight"): Networks, 10(2):143–152, 1980. """ - try: - import numpy as np - import scipy.optimize - except ImportError as e: - raise ImportError( - "minimum_weight_full_matching requires SciPy: " + "https://scipy.org/" - ) from e + import numpy as np + import scipy.optimize + left, right = nx.bipartite.sets(G, top_nodes) U = list(left) V = list(right) diff --git a/networkx/algorithms/bipartite/spectral.py b/networkx/algorithms/bipartite/spectral.py index 57dea5a3..79d8ded5 100644 --- a/networkx/algorithms/bipartite/spectral.py +++ b/networkx/algorithms/bipartite/spectral.py @@ -47,12 +47,8 @@ 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) """ - try: - import scipy.linalg - except ImportError as e: - raise ImportError( - "spectral_bipartivity() requires SciPy: ", "http://scipy.org/" - ) from e + import scipy.linalg + nodelist = list(G) # ordering of nodes in matrix A = nx.to_numpy_array(G, nodelist, weight=weight) expA = scipy.linalg.expm(A) diff --git a/networkx/algorithms/centrality/current_flow_betweenness.py b/networkx/algorithms/centrality/current_flow_betweenness.py index 106ceb4a..3b086216 100644 --- a/networkx/algorithms/centrality/current_flow_betweenness.py +++ b/networkx/algorithms/centrality/current_flow_betweenness.py @@ -95,12 +95,8 @@ def approximate_current_flow_betweenness_centrality( LNCS 3404, pp. 533-544. Springer-Verlag, 2005. http://algo.uni-konstanz.de/publications/bf-cmbcf-05.pdf """ - try: - import numpy as np - except ImportError as e: - raise ImportError( - "current_flow_betweenness_centrality requires NumPy " "http://numpy.org/" - ) from e + import numpy as np + if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected.") solvername = { diff --git a/networkx/algorithms/centrality/current_flow_betweenness_subset.py b/networkx/algorithms/centrality/current_flow_betweenness_subset.py index a9286077..69ed32e3 100644 --- a/networkx/algorithms/centrality/current_flow_betweenness_subset.py +++ b/networkx/algorithms/centrality/current_flow_betweenness_subset.py @@ -88,13 +88,8 @@ def current_flow_betweenness_centrality_subset( M. E. J. Newman, Social Networks 27, 39-54 (2005). """ from networkx.utils import reverse_cuthill_mckee_ordering + import numpy as np - try: - import numpy as np - except ImportError as e: - raise ImportError( - "current_flow_betweenness_centrality requires NumPy ", "http://numpy.org/" - ) from e if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected.") n = G.number_of_nodes() @@ -198,12 +193,8 @@ def edge_current_flow_betweenness_centrality_subset( .. [2] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005). """ - try: - import numpy as np - except ImportError as e: - raise ImportError( - "current_flow_betweenness_centrality requires NumPy " "http://numpy.org/" - ) from e + import numpy as np + if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected.") n = G.number_of_nodes() diff --git a/networkx/algorithms/centrality/katz.py b/networkx/algorithms/centrality/katz.py index 8697750f..a7de6375 100644 --- a/networkx/algorithms/centrality/katz.py +++ b/networkx/algorithms/centrality/katz.py @@ -302,10 +302,8 @@ def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None): Psychometrika 18(1):39–43, 1953 http://phya.snu.ac.kr/~dkim/PRL87278701.pdf """ - try: - import numpy as np - except ImportError as e: - raise ImportError("Requires NumPy: http://numpy.org/") from e + import numpy as np + if len(G) == 0: return {} try: diff --git a/networkx/algorithms/centrality/second_order.py b/networkx/algorithms/centrality/second_order.py index cf86cb01..b1cb8b83 100644 --- a/networkx/algorithms/centrality/second_order.py +++ b/networkx/algorithms/centrality/second_order.py @@ -95,11 +95,7 @@ def second_order_centrality(G): "Second order centrality: Distributed assessment of nodes criticity in complex networks", Elsevier Computer Communications 34(5):619-628, 2011. """ - - try: - import numpy as np - except ImportError as e: - raise ImportError("Requires NumPy: http://numpy.org/") from e + import numpy as np n = len(G) diff --git a/networkx/algorithms/centrality/trophic.py b/networkx/algorithms/centrality/trophic.py index 76620096..c5af642f 100644 --- a/networkx/algorithms/centrality/trophic.py +++ b/networkx/algorithms/centrality/trophic.py @@ -40,10 +40,7 @@ def trophic_levels(G, weight="weight"): ---------- .. [1] Stephen Levine (1980) J. theor. Biol. 83, 195-207 """ - try: - import numpy as np - except ImportError as e: - raise ImportError("trophic_levels() requires NumPy: http://numpy.org/") from e + import numpy as np # find adjacency matrix a = nx.adjacency_matrix(G, weight=weight).T.toarray() @@ -145,12 +142,7 @@ def trophic_incoherence_parameter(G, weight="weight", cannibalism=False): .. [1] Samuel Johnson, Virginia Dominguez-Garcia, Luca Donetti, Miguel A. Munoz (2014) PNAS "Trophic coherence determines food-web stability" """ - try: - import numpy as np - except ImportError as e: - raise ImportError( - "trophic_incoherence_parameter() requires NumPy: " "http://scipy.org/" - ) from e + import numpy as np if cannibalism: diffs = trophic_differences(G, weight=weight) diff --git a/networkx/algorithms/link_analysis/hits_alg.py b/networkx/algorithms/link_analysis/hits_alg.py index f7b1174d..19fe9bb3 100644 --- a/networkx/algorithms/link_analysis/hits_alg.py +++ b/networkx/algorithms/link_analysis/hits_alg.py @@ -176,10 +176,8 @@ def hits_numpy(G, normalized=True): doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf. """ - try: - import numpy as np - except ImportError as e: - raise ImportError("hits_numpy() requires NumPy: " "http://numpy.org/") from e + import numpy as np + if len(G) == 0: return {}, {} H = nx.hub_matrix(G, list(G)) @@ -267,13 +265,8 @@ def hits_scipy(G, max_iter=100, tol=1.0e-6, normalized=True): doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf. """ - try: - import numpy as np - except ImportError as e: - raise ImportError( - "hits_scipy() requires SciPy and NumPy:" - "http://scipy.org/ http://numpy.org/" - ) from e + import numpy as np + if len(G) == 0: return {}, {} M = nx.to_scipy_sparse_matrix(G, nodelist=list(G)) diff --git a/networkx/algorithms/node_classification/hmn.py b/networkx/algorithms/node_classification/hmn.py index 56297de9..c9c53def 100644 --- a/networkx/algorithms/node_classification/hmn.py +++ b/networkx/algorithms/node_classification/hmn.py @@ -61,18 +61,8 @@ def harmonic_function(G, max_iter=30, label_name="label"): Semi-supervised learning using gaussian fields and harmonic functions. In ICML (Vol. 3, pp. 912-919). """ - try: - import numpy as np - except ImportError as e: - raise ImportError( - "harmonic_function() requires numpy: http://numpy.org/ " - ) from e - try: - from scipy import sparse - except ImportError as e: - raise ImportError( - "harmonic_function() requires scipy: http://scipy.org/ " - ) from e + import numpy as np + from scipy import sparse def _build_propagation_matrix(X, labels): """Build propagation matrix of Harmonic function diff --git a/networkx/algorithms/node_classification/lgc.py b/networkx/algorithms/node_classification/lgc.py index dd32c594..0610c0ba 100644 --- a/networkx/algorithms/node_classification/lgc.py +++ b/networkx/algorithms/node_classification/lgc.py @@ -64,18 +64,8 @@ def local_and_global_consistency(G, alpha=0.99, max_iter=30, label_name="label") Learning with local and global consistency. Advances in neural information processing systems, 16(16), 321-328. """ - try: - import numpy as np - except ImportError as e: - raise ImportError( - "local_and_global_consistency() requires numpy: ", "http://numpy.org/ " - ) from e - try: - from scipy import sparse - except ImportError as e: - raise ImportError( - "local_and_global_consistensy() requires scipy: ", "http://scipy.org/ " - ) from e + import numpy as np + from scipy import sparse def _build_propagation_matrix(X, labels, alpha): """Build propagation matrix of Local and global consistency diff --git a/networkx/algorithms/non_randomness.py b/networkx/algorithms/non_randomness.py index cab2e904..ca61c584 100644 --- a/networkx/algorithms/non_randomness.py +++ b/networkx/algorithms/non_randomness.py @@ -54,6 +54,7 @@ def non_randomness(G, k=None): On Randomness Measures for Social Networks, SIAM International Conference on Data Mining. 2009 """ + import numpy as np if not nx.is_connected(G): raise nx.NetworkXException("Non connected graph.") @@ -63,12 +64,6 @@ def non_randomness(G, k=None): if k is None: k = len(tuple(nx.community.label_propagation_communities(G))) - try: - import numpy as np - except ImportError as e: - msg = "non_randomness requires NumPy: http://numpy.org/" - raise ImportError(msg) from e - # eq. 4.4 nr = np.real(np.sum(np.linalg.eigvals(nx.to_numpy_array(G))[:k])) diff --git a/networkx/algorithms/shortest_paths/dense.py b/networkx/algorithms/shortest_paths/dense.py index 148a7189..c8d0df00 100644 --- a/networkx/algorithms/shortest_paths/dense.py +++ b/networkx/algorithms/shortest_paths/dense.py @@ -38,10 +38,7 @@ def floyd_warshall_numpy(G, nodelist=None, weight="weight"): algorithm fails. This algorithm can still fail if there are negative cycles. It has running time $O(n^3)$ with running space of $O(n^2)$. """ - try: - import numpy as np - except ImportError as e: - raise ImportError("to_numpy_array() requires numpy: http://numpy.org/ ") from e + import numpy as np # To handle cases when an edge has weight=0, we must make sure that # nonedges are not given the value 0 as well. diff --git a/networkx/convert.py b/networkx/convert.py index c9cef124..837cb089 100644 --- a/networkx/convert.py +++ b/networkx/convert.py @@ -129,8 +129,7 @@ def to_networkx_graph(data, create_using=None, multigraph_input=False): msg = "Input is not a correct Pandas DataFrame edge-list." raise nx.NetworkXError(msg) from e except ImportError: - msg = "pandas not found, skipping conversion test." - warnings.warn(msg, ImportWarning) + warnings.warn("pandas not found, skipping conversion test.", ImportWarning) # numpy matrix or ndarray try: diff --git a/networkx/drawing/layout.py b/networkx/drawing/layout.py index e02de9aa..3c379182 100644 --- a/networkx/drawing/layout.py +++ b/networkx/drawing/layout.py @@ -580,17 +580,13 @@ 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 try: nnodes, _ = A.shape except AttributeError as e: msg = "fruchterman_reingold() takes an adjacency matrix as input" raise nx.NetworkXError(msg) from e - try: - from scipy.sparse import coo_matrix - except ImportError as e: - msg = "_sparse_fruchterman_reingold() scipy numpy: http://scipy.org/ " - raise ImportError(msg) from e # make sure we have a LIst of Lists representation try: A = A.tolil() diff --git a/networkx/drawing/nx_pylab.py b/networkx/drawing/nx_pylab.py index c9af529b..b0150661 100644 --- a/networkx/drawing/nx_pylab.py +++ b/networkx/drawing/nx_pylab.py @@ -13,6 +13,7 @@ matplotlib: http://matplotlib.org/ pygraphviz: http://pygraphviz.github.io/ """ + from numbers import Number import networkx as nx from networkx.drawing.layout import ( @@ -98,13 +99,7 @@ def draw(G, pos=None, ax=None, **kwds): Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html """ - try: - import matplotlib.pyplot as plt - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e - except RuntimeError: - print("Matplotlib unable to open display") - raise + import matplotlib.pyplot as plt if ax is None: cf = plt.gcf() @@ -262,13 +257,7 @@ def draw_networkx(G, pos=None, arrows=True, with_labels=True, **kwds): draw_networkx_labels() draw_networkx_edge_labels() """ - try: - import matplotlib.pyplot as plt - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e - except RuntimeError: - print("Matplotlib unable to open display") - raise + import matplotlib.pyplot as plt valid_node_kwds = ( "nodelist", @@ -432,16 +421,9 @@ def draw_networkx_nodes( draw_networkx_edge_labels() """ from collections.abc import Iterable - - try: - import matplotlib.pyplot as plt - from matplotlib.collections import PathCollection - import numpy as np - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e - except RuntimeError: - print("Matplotlib unable to open display") - raise + import matplotlib.pyplot as plt + from matplotlib.collections import PathCollection + import numpy as np if ax is None: ax = plt.gca() @@ -621,17 +603,11 @@ def draw_networkx_edges( draw_networkx_labels() draw_networkx_edge_labels() """ - try: - import matplotlib.pyplot as plt - from matplotlib.colors import colorConverter, Colormap, Normalize - from matplotlib.collections import LineCollection - from matplotlib.patches import FancyArrowPatch - import numpy as np - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e - except RuntimeError: - print("Matplotlib unable to open display") - raise + import matplotlib.pyplot as plt + from matplotlib.colors import colorConverter, Colormap, Normalize + from matplotlib.collections import LineCollection + from matplotlib.patches import FancyArrowPatch + import numpy as np if ax is None: ax = plt.gca() @@ -875,13 +851,7 @@ def draw_networkx_labels( draw_networkx_edges() draw_networkx_edge_labels() """ - try: - import matplotlib.pyplot as plt - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e - except RuntimeError: - print("Matplotlib unable to open display") - raise + import matplotlib.pyplot as plt if ax is None: ax = plt.gca() @@ -1015,14 +985,8 @@ def draw_networkx_edge_labels( draw_networkx_edges() draw_networkx_labels() """ - try: - import matplotlib.pyplot as plt - import numpy as np - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e - except RuntimeError: - print("Matplotlib unable to open display") - raise + import matplotlib.pyplot as plt + import numpy as np if ax is None: ax = plt.gca() @@ -1250,13 +1214,9 @@ def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None): """ from itertools import islice, cycle - - try: - import numpy as np - from matplotlib.colors import colorConverter - import matplotlib.cm as cm - except ImportError as e: - raise ImportError("Matplotlib required for draw()") from e + import numpy as np + from matplotlib.colors import colorConverter + import matplotlib.cm as cm # If we have been provided with a list of numbers as long as elem_list, # apply the color mapping. diff --git a/networkx/linalg/algebraicconnectivity.py b/networkx/linalg/algebraicconnectivity.py index e4b3aabb..16bce858 100644 --- a/networkx/linalg/algebraicconnectivity.py +++ b/networkx/linalg/algebraicconnectivity.py @@ -11,6 +11,7 @@ try: from numpy import array, asarray, dot, ndarray, ones, sqrt, zeros, atleast_2d from numpy.linalg import norm, qr from scipy.linalg import eigh, inv + from scipy.linalg.blas import dasum, daxpy, ddot from scipy.sparse import csc_matrix, spdiags from scipy.sparse.linalg import eigsh, lobpcg @@ -18,19 +19,6 @@ try: except ImportError: __all__ = [] -try: - from scipy.linalg.blas import dasum, daxpy, ddot -except ImportError: - if __all__: - # Make sure the imports succeeded. - # Use minimal replacements if BLAS is unavailable from SciPy. - dasum = partial(norm, ord=1) - ddot = dot - - def daxpy(x, y, a): - y += a * x - return y - class _PCGSolver: """Preconditioned conjugate gradient method. @@ -122,8 +110,6 @@ class _LUSolver: """ def __init__(self, A): - if not self._splu: - raise nx.NetworkXError("LU solver unavailable.") self._LU = self._splu(A) def solve(self, B, tol=None): @@ -147,8 +133,7 @@ class _LUSolver: def _preprocess_graph(G, weight): - """Compute edge weights and eliminate zero-weight edges. - """ + """Compute edge weights and eliminate zero-weight edges.""" if G.is_directed(): H = nx.MultiGraph() H.add_nodes_from(G) @@ -174,8 +159,7 @@ def _preprocess_graph(G, weight): def _rcm_estimate(G, nodelist): - """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering. - """ + """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering.""" G = G.subgraph(nodelist) order = reverse_cuthill_mckee_ordering(G) n = len(nodelist) @@ -234,8 +218,7 @@ def _tracemin_fiedler(L, X, normalized, tol, method): if normalized: def project(X): - """Make X orthogonal to the nullspace of L. - """ + """Make X orthogonal to the nullspace of L.""" X = asarray(X) for j in range(X.shape[1]): X[:, j] -= dot(X[:, j], e) * e @@ -243,8 +226,7 @@ def _tracemin_fiedler(L, X, normalized, tol, method): else: def project(X): - """Make X orthogonal to the nullspace of L. - """ + """Make X orthogonal to the nullspace of L.""" X = asarray(X) for j in range(X.shape[1]): X[:, j] -= X[:, j].sum() / n @@ -297,8 +279,7 @@ def _tracemin_fiedler(L, X, normalized, tol, method): def _get_fiedler_func(method): - """Returns a function that solves the Fiedler eigenvalue problem. - """ + """Returns a function that solves the Fiedler eigenvalue problem.""" if method == "tracemin": # old style keyword <v2.1 method = "tracemin_pcg" if method in ("tracemin_pcg", "tracemin_chol", "tracemin_lu"): diff --git a/networkx/linalg/attrmatrix.py b/networkx/linalg/attrmatrix.py index 1d68fdc6..24443565 100644 --- a/networkx/linalg/attrmatrix.py +++ b/networkx/linalg/attrmatrix.py @@ -267,10 +267,7 @@ def attr_matrix( (blue, blue) is 0 # there are no edges with blue endpoints """ - try: - import numpy as np - except ImportError as e: - raise ImportError("attr_matrix() requires numpy: http://scipy.org/ ") from e + import numpy as np edge_value = _edge_value(G, edge_attr) node_value = _node_value(G, node_attr) @@ -428,13 +425,8 @@ def attr_sparse_matrix( (blue, blue) is 0 # there are no edges with blue endpoints """ - try: - import numpy as np - from scipy import sparse - except ImportError as e: - raise ImportError( - "attr_sparse_matrix() requires scipy: " "http://scipy.org/ " - ) from e + import numpy as np + from scipy import sparse edge_value = _edge_value(G, edge_attr) node_value = _node_value(G, node_attr) |