From 979fa4e3bdeb3711aed188cfcbbd19d17cd52a71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= Date: Fri, 4 Aug 2023 10:52:37 +0200 Subject: [PATCH] API: Update numpy exceptions imports --- scipy/_lib/_util.py | 15 ++++++++++++--- scipy/interpolate/tests/test_bsplines.py | 5 +++-- scipy/interpolate/tests/test_rgi.py | 4 +++- scipy/io/matlab/tests/test_mio.py | 4 +++- scipy/linalg/_decomp_ldl.py | 3 ++- scipy/linalg/tests/test_decomp_ldl.py | 2 +- scipy/optimize/_milp.py | 3 ++- .../optimize/tests/test__linprog_clean_inputs.py | 5 +++-- scipy/optimize/tests/test_linprog.py | 3 ++- scipy/signal/tests/test_signaltools.py | 3 ++- scipy/sparse/_base.py | 5 +++-- .../sparse/linalg/_dsolve/tests/test_linsolve.py | 3 ++- scipy/sparse/tests/test_array_api.py | 6 ++++-- scipy/sparse/tests/test_base.py | 3 ++- scipy/stats/_axis_nan_policy.py | 10 +++++----- scipy/stats/_stats_py.py | 11 ++++++----- scipy/stats/tests/test_axis_nan_policy.py | 5 +++-- scipy/stats/tests/test_stats.py | 5 +++-- scipy/stats/tests/test_variation.py | 5 +++-- 19 files changed, 64 insertions(+), 36 deletions(-) diff --git a/scipy/_lib/_util.py b/scipy/_lib/_util.py index 032fdd980403..f3d58440845a 100644 --- a/scipy/_lib/_util.py +++ b/scipy/_lib/_util.py @@ -11,16 +11,25 @@ Optional, Union, TYPE_CHECKING, + Type, TypeVar, ) import numpy as np + +AxisError: Type[Exception] +ComplexWarning: Type[Warning] +VisibleDeprecationWarning: Type[Warning] + if np.lib.NumpyVersion(np.__version__) >= '1.25.0': - from numpy.exceptions import AxisError + from numpy.exceptions import ( + AxisError, ComplexWarning, VisibleDeprecationWarning # noqa: F401 + ) else: - from numpy import AxisError - + from numpy import ( + AxisError, ComplexWarning, VisibleDeprecationWarning # noqa: F401 + ) IntNumber = Union[int, np.integer] diff --git a/scipy/interpolate/tests/test_bsplines.py b/scipy/interpolate/tests/test_bsplines.py index d30102b84cf0..d89e75712e3c 100644 --- a/scipy/interpolate/tests/test_bsplines.py +++ b/scipy/interpolate/tests/test_bsplines.py @@ -1,3 +1,4 @@ +import os import operator import itertools @@ -17,7 +18,7 @@ _woodbury_algorithm, _periodic_knots, _make_interp_per_full_matr) import scipy.interpolate._fitpack_impl as _impl -import os +from scipy._lib._util import AxisError class TestBSpline: @@ -412,7 +413,7 @@ def test_axis(self, axis): # -c.ndim <= axis < c.ndim for ax in [-c.ndim - 1, c.ndim]: - assert_raises(np.AxisError, BSpline, + assert_raises(AxisError, BSpline, **dict(t=t, c=c, k=k, axis=ax)) # derivative, antiderivative keeps the axis diff --git a/scipy/interpolate/tests/test_rgi.py b/scipy/interpolate/tests/test_rgi.py index 25240666c1b9..b19113cb491d 100644 --- a/scipy/interpolate/tests/test_rgi.py +++ b/scipy/interpolate/tests/test_rgi.py @@ -12,6 +12,8 @@ NearestNDInterpolator, LinearNDInterpolator) from scipy.sparse._sputils import matrix +from scipy._lib._util import ComplexWarning + parametrize_rgi_interp_methods = pytest.mark.parametrize( "method", ['linear', 'nearest', 'slinear', 'cubic', 'quintic', 'pchip'] @@ -869,7 +871,7 @@ def test_complex_spline2fd(self): sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T - with assert_warns(np.ComplexWarning): + with assert_warns(ComplexWarning): interpn(points, values, sample, method='splinef2d') @pytest.mark.parametrize( diff --git a/scipy/io/matlab/tests/test_mio.py b/scipy/io/matlab/tests/test_mio.py index 9cc9ea226533..b52c851fc14a 100644 --- a/scipy/io/matlab/tests/test_mio.py +++ b/scipy/io/matlab/tests/test_mio.py @@ -34,6 +34,8 @@ MatFile5Writer, MatFile5Reader, varmats_from_mat, to_writeable, EmptyStructMarker) import scipy.io.matlab._mio5_params as mio5p +from scipy._lib._util import VisibleDeprecationWarning + test_data_path = pjoin(dirname(__file__), 'data') @@ -1315,7 +1317,7 @@ def test_gh_17992(tmp_path): list_of_arrays = [array_one, array_two] # warning suppression only needed for NumPy < 1.24.0 with np.testing.suppress_warnings() as sup: - sup.filter(np.VisibleDeprecationWarning) + sup.filter(VisibleDeprecationWarning) savemat(outfile, {'data': list_of_arrays}, long_field_names=True, diff --git a/scipy/linalg/_decomp_ldl.py b/scipy/linalg/_decomp_ldl.py index e484e11f6776..31c4b1931624 100644 --- a/scipy/linalg/_decomp_ldl.py +++ b/scipy/linalg/_decomp_ldl.py @@ -1,8 +1,9 @@ from warnings import warn import numpy as np -from numpy import (atleast_2d, ComplexWarning, arange, zeros_like, imag, diag, +from numpy import (atleast_2d, arange, zeros_like, imag, diag, iscomplexobj, tril, triu, argsort, empty_like) +from scipy._lib._util import ComplexWarning from ._decomp import _asarray_validated from .lapack import get_lapack_funcs, _compute_lwork diff --git a/scipy/linalg/tests/test_decomp_ldl.py b/scipy/linalg/tests/test_decomp_ldl.py index 28b030ee5807..ed844f6856fb 100644 --- a/scipy/linalg/tests/test_decomp_ldl.py +++ b/scipy/linalg/tests/test_decomp_ldl.py @@ -4,9 +4,9 @@ complex64, complex128) from numpy.random import rand, randint, seed from scipy.linalg import ldl +from scipy._lib._util import ComplexWarning import pytest from pytest import raises as assert_raises, warns -from numpy import ComplexWarning def test_args(): diff --git a/scipy/optimize/_milp.py b/scipy/optimize/_milp.py index ec515baa317f..00aac5173cb9 100644 --- a/scipy/optimize/_milp.py +++ b/scipy/optimize/_milp.py @@ -1,6 +1,7 @@ import warnings import numpy as np from scipy.sparse import csc_array, vstack, issparse +from scipy._lib._util import VisibleDeprecationWarning from ._highs._highs_wrapper import _highs_wrapper # type: ignore[import] from ._constraints import LinearConstraint, Bounds from ._optimize import OptimizeResult @@ -43,7 +44,7 @@ def _constraints_to_components(constraints): # argument could be a single tuple representing a LinearConstraint try: constraints = [LinearConstraint(*constraints)] - except (TypeError, ValueError, np.VisibleDeprecationWarning): + except (TypeError, ValueError, VisibleDeprecationWarning): # argument was not a tuple representing a LinearConstraint pass diff --git a/scipy/optimize/tests/test__linprog_clean_inputs.py b/scipy/optimize/tests/test__linprog_clean_inputs.py index 0ba8494d0688..f65ec7f06876 100644 --- a/scipy/optimize/tests/test__linprog_clean_inputs.py +++ b/scipy/optimize/tests/test__linprog_clean_inputs.py @@ -5,6 +5,7 @@ from numpy.testing import assert_, assert_allclose, assert_equal from pytest import raises as assert_raises from scipy.optimize._linprog_util import _clean_inputs, _LPProblem +from scipy._lib._util import VisibleDeprecationWarning from copy import deepcopy from datetime import date @@ -113,7 +114,7 @@ def test_inconsistent_dimensions(): assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Agood, b_eq=bbad)) assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, bounds=boundsbad)) with np.testing.suppress_warnings() as sup: - sup.filter(np.VisibleDeprecationWarning, "Creating an ndarray from ragged") + sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged") assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, bounds=[[1, 2], [2, 3], [3, 4], [4, 5, 6]])) @@ -245,7 +246,7 @@ def test_bad_bounds(): assert_raises(ValueError, _clean_inputs, lp._replace(bounds=(1, 2, 2))) assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2, 2)])) with np.testing.suppress_warnings() as sup: - sup.filter(np.VisibleDeprecationWarning, "Creating an ndarray from ragged") + sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged") assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2), (1, 2, 2)])) assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2), (1, 2), (1, 2)])) diff --git a/scipy/optimize/tests/test_linprog.py b/scipy/optimize/tests/test_linprog.py index fa4564388cad..8f55912fb8df 100644 --- a/scipy/optimize/tests/test_linprog.py +++ b/scipy/optimize/tests/test_linprog.py @@ -12,6 +12,7 @@ from scipy.optimize._numdiff import approx_derivative from scipy.sparse.linalg import MatrixRankWarning from scipy.linalg import LinAlgWarning +from scipy._lib._util import VisibleDeprecationWarning import scipy.sparse import pytest @@ -487,7 +488,7 @@ def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None): # Test ill-formatted bounds assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4)]) with np.testing.suppress_warnings() as sup: - sup.filter(np.VisibleDeprecationWarning, "Creating an ndarray from ragged") + sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged") assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4), (3, 4, 5)]) assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, -2), (1, 2)]) diff --git a/scipy/signal/tests/test_signaltools.py b/scipy/signal/tests/test_signaltools.py index d999c51e0566..f6594bd91600 100644 --- a/scipy/signal/tests/test_signaltools.py +++ b/scipy/signal/tests/test_signaltools.py @@ -31,6 +31,7 @@ _group_poles) from scipy.signal._upfirdn import _upfirdn_modes from scipy._lib import _testutils +from scipy._lib._util import ComplexWarning class _TestConvolve: @@ -297,7 +298,7 @@ def test_fillvalue(self): def test_fillvalue_errors(self): msg = "could not cast `fillvalue` directly to the output " with np.testing.suppress_warnings() as sup: - sup.filter(np.ComplexWarning, "Casting complex values") + sup.filter(ComplexWarning, "Casting complex values") with assert_raises(ValueError, match=msg): convolve2d([[1]], [[1, 2]], fillvalue=1j) diff --git a/scipy/sparse/_base.py b/scipy/sparse/_base.py index 26de3a56d625..86907dbbc795 100644 --- a/scipy/sparse/_base.py +++ b/scipy/sparse/_base.py @@ -2,6 +2,7 @@ from warnings import warn import numpy as np +from scipy._lib._util import VisibleDeprecationWarning from ._sputils import (asmatrix, check_reshape_kwargs, check_shape, get_sum_dtype, isdense, isscalarlike, @@ -714,7 +715,7 @@ def __pow__(self, *args, **kwargs): @property def A(self) -> np.ndarray: if isinstance(self, sparray): - warn(np.VisibleDeprecationWarning( + warn(VisibleDeprecationWarning( "`.A` is deprecated and will be removed in v1.13.0. " "Use `.toarray()` instead." )) @@ -727,7 +728,7 @@ def T(self): @property def H(self): if isinstance(self, sparray): - warn(np.VisibleDeprecationWarning( + warn(VisibleDeprecationWarning( "`.H` is deprecated and will be removed in v1.13.0. " "Please use `.T.conjugate()` instead." )) diff --git a/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py b/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py index 00e0d1886dcc..0f3cd6339bab 100644 --- a/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py +++ b/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py @@ -21,6 +21,7 @@ import scipy.sparse from scipy._lib._testutils import check_free_memory +from scipy._lib._util import ComplexWarning sup_sparse_efficiency = suppress_warnings() @@ -154,7 +155,7 @@ def test_call_with_cast_to_complex_with_umfpack(self): solve = factorized(self.A) b = random.rand(4) for t in [np.complex64, np.complex128]: - assert_warns(np.ComplexWarning, solve, b.astype(t)) + assert_warns(ComplexWarning, solve, b.astype(t)) @pytest.mark.skipif(not has_umfpack, reason="umfpack not available") def test_assume_sorted_indices_flag(self): diff --git a/scipy/sparse/tests/test_array_api.py b/scipy/sparse/tests/test_array_api.py index 65d851e5022d..d92924bb2d79 100644 --- a/scipy/sparse/tests/test_array_api.py +++ b/scipy/sparse/tests/test_array_api.py @@ -3,6 +3,8 @@ import numpy.testing as npt import scipy.sparse import scipy.sparse.linalg as spla +from scipy._lib._util import VisibleDeprecationWarning + sparray_types = ('bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil') @@ -160,13 +162,13 @@ def test_dense_divide(A): @parametrize_sparrays def test_no_A_attr(A): - with pytest.warns(np.VisibleDeprecationWarning): + with pytest.warns(VisibleDeprecationWarning): A.A @parametrize_sparrays def test_no_H_attr(A): - with pytest.warns(np.VisibleDeprecationWarning): + with pytest.warns(VisibleDeprecationWarning): A.H diff --git a/scipy/sparse/tests/test_base.py b/scipy/sparse/tests/test_base.py index ca38ff176fe7..bbc66cf1e6fc 100644 --- a/scipy/sparse/tests/test_base.py +++ b/scipy/sparse/tests/test_base.py @@ -20,7 +20,7 @@ class for generic tests" section. import numpy as np from numpy import (arange, zeros, array, dot, asarray, vstack, ndarray, transpose, diag, kron, inf, conjugate, - int8, ComplexWarning) + int8) import random from numpy.testing import (assert_equal, assert_array_equal, @@ -39,6 +39,7 @@ class for generic tests" section. from scipy.sparse.linalg import splu, expm, inv from scipy._lib.decorator import decorator +from scipy._lib._util import ComplexWarning import pytest diff --git a/scipy/stats/_axis_nan_policy.py b/scipy/stats/_axis_nan_policy.py index 89bcab331499..6d6cad1f25ec 100644 --- a/scipy/stats/_axis_nan_policy.py +++ b/scipy/stats/_axis_nan_policy.py @@ -7,7 +7,7 @@ import numpy as np from functools import wraps from scipy._lib._docscrape import FunctionDoc, Parameter -from scipy._lib._util import _contains_nan +from scipy._lib._util import _contains_nan, AxisError import inspect @@ -42,8 +42,8 @@ def _broadcast_shapes(shapes, axis=None): axis = np.atleast_1d(axis) axis_int = axis.astype(int) if not np.array_equal(axis_int, axis): - raise np.AxisError('`axis` must be an integer, a ' - 'tuple of integers, or `None`.') + raise AxisError('`axis` must be an integer, a ' + 'tuple of integers, or `None`.') axis = axis_int # First, ensure all shapes have same number of dimensions by prepending 1s. @@ -59,10 +59,10 @@ def _broadcast_shapes(shapes, axis=None): if axis[-1] >= n_dims or axis[0] < 0: message = (f"`axis` is out of bounds " f"for array of dimension {n_dims}") - raise np.AxisError(message) + raise AxisError(message) if len(np.unique(axis)) != len(axis): - raise np.AxisError("`axis` must contain only distinct elements") + raise AxisError("`axis` must contain only distinct elements") removed_shapes = new_shapes[:, axis] new_shapes = np.delete(new_shapes, axis, axis=1) diff --git a/scipy/stats/_stats_py.py b/scipy/stats/_stats_py.py index 9e73ea78e57b..865e83eb334a 100644 --- a/scipy/stats/_stats_py.py +++ b/scipy/stats/_stats_py.py @@ -43,7 +43,8 @@ from scipy.ndimage import _measurements from scipy.optimize import milp, LinearConstraint from scipy._lib._util import (check_random_state, MapWrapper, _get_nan, - rng_integers, _rename_parameter, _contains_nan) + rng_integers, _rename_parameter, _contains_nan, + AxisError) import scipy.special as special from scipy import linalg @@ -4124,9 +4125,9 @@ def f_oneway(*samples, axis=0): num_groups = len(samples) # We haven't explicitly validated axis, but if it is bad, this call of - # np.concatenate will raise np.AxisError. The call will raise ValueError - # if the dimensions of all the arrays, except the axis dimension, are not - # the same. + # np.concatenate will raise np.exceptions.AxisError. The call will raise + # ValueError if the dimensions of all the arrays, except the axis + # dimension, are not the same. alldata = np.concatenate(samples, axis=axis) bign = alldata.shape[axis] @@ -7676,7 +7677,7 @@ def _get_len(a, axis, msg): try: n = a.shape[axis] except IndexError: - raise np.AxisError(axis, a.ndim, msg) from None + raise AxisError(axis, a.ndim, msg) from None return n diff --git a/scipy/stats/tests/test_axis_nan_policy.py b/scipy/stats/tests/test_axis_nan_policy.py index 8811ec5da0d4..4ae3be5c190b 100644 --- a/scipy/stats/tests/test_axis_nan_policy.py +++ b/scipy/stats/tests/test_axis_nan_policy.py @@ -13,6 +13,7 @@ from numpy.testing import assert_allclose, assert_equal, suppress_warnings from scipy import stats from scipy.stats._axis_nan_policy import _masked_arrays_2_sentinel_arrays +from scipy._lib._util import AxisError def unpack_ttest_result(res): @@ -971,13 +972,13 @@ def test_other_axis_tuples(axis): if len(set(axis)) != len(axis): message = "`axis` must contain only distinct elements" - with pytest.raises(np.AxisError, match=re.escape(message)): + with pytest.raises(AxisError, match=re.escape(message)): stats.mannwhitneyu(x, y, axis=axis_original) return if axis[0] < 0 or axis[-1] > 2: message = "`axis` is out of bounds for array of dimension 3" - with pytest.raises(np.AxisError, match=re.escape(message)): + with pytest.raises(AxisError, match=re.escape(message)): stats.mannwhitneyu(x, y, axis=axis_original) return diff --git a/scipy/stats/tests/test_stats.py b/scipy/stats/tests/test_stats.py index 7b7ec27c26b7..79d6cdbf3483 100644 --- a/scipy/stats/tests/test_stats.py +++ b/scipy/stats/tests/test_stats.py @@ -35,6 +35,7 @@ from numpy.lib import NumpyVersion from scipy.stats._axis_nan_policy import _broadcast_concatenate from scipy.stats._stats_py import _permutation_distribution_t +from scipy._lib._util import AxisError """ Numbers in docstrings beginning with 'W' refer to the section numbers @@ -2891,7 +2892,7 @@ def test_axis(self): assert_equal(stats.iqr(d, axis=(1, 3))[2, 2], stats.iqr(d[2, :, 2,:].ravel())) - assert_raises(np.AxisError, stats.iqr, d, axis=4) + assert_raises(AxisError, stats.iqr, d, axis=4) assert_raises(ValueError, stats.iqr, d, axis=(0, 0)) def test_rng(self): @@ -7089,7 +7090,7 @@ def test_too_few_inputs(self, args): def test_axis_error(self): a = np.ones((3, 4)) b = np.ones((5, 4)) - with assert_raises(np.AxisError): + with assert_raises(AxisError): stats.f_oneway(a, b, axis=2) def test_bad_shapes(self): diff --git a/scipy/stats/tests/test_variation.py b/scipy/stats/tests/test_variation.py index 2a546b1f6e50..133978d681f0 100644 --- a/scipy/stats/tests/test_variation.py +++ b/scipy/stats/tests/test_variation.py @@ -2,6 +2,7 @@ from numpy.testing import assert_equal, assert_allclose import pytest from scipy.stats import variation +from scipy._lib._util import AxisError class TestVariation: @@ -77,9 +78,9 @@ def test_axis_none(self): assert_allclose(y, np.sqrt(5/4)/1.5) def test_bad_axis(self): - # Check that an invalid axis raises np.AxisError. + # Check that an invalid axis raises np.exceptions.AxisError. x = np.array([[1, 2, 3], [4, 5, 6]]) - with pytest.raises(np.AxisError): + with pytest.raises(AxisError): variation(x, axis=10) def test_mean_zero(self):