Skip to content

Commit

Permalink
API: Update numpy exceptions imports
Browse files Browse the repository at this point in the history
  • Loading branch information
mtsokol committed Aug 4, 2023
1 parent a4ed945 commit 979fa4e
Show file tree
Hide file tree
Showing 19 changed files with 64 additions and 36 deletions.
15 changes: 12 additions & 3 deletions scipy/_lib/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
5 changes: 3 additions & 2 deletions scipy/interpolate/tests/test_bsplines.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import operator
import itertools

Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion scipy/interpolate/tests/test_rgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
Expand Down Expand Up @@ -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(
Expand Down
4 changes: 3 additions & 1 deletion scipy/io/matlab/tests/test_mio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion scipy/linalg/_decomp_ldl.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down
2 changes: 1 addition & 1 deletion scipy/linalg/tests/test_decomp_ldl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
3 changes: 2 additions & 1 deletion scipy/optimize/_milp.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions scipy/optimize/tests/test__linprog_clean_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]]))

Expand Down Expand Up @@ -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)]))
Expand Down
3 changes: 2 additions & 1 deletion scipy/optimize/tests/test_linprog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)])

Expand Down
3 changes: 2 additions & 1 deletion scipy/signal/tests/test_signaltools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down
5 changes: 3 additions & 2 deletions scipy/sparse/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."
))
Expand All @@ -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."
))
Expand Down
3 changes: 2 additions & 1 deletion scipy/sparse/linalg/_dsolve/tests/test_linsolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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):
Expand Down
6 changes: 4 additions & 2 deletions scipy/sparse/tests/test_array_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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


Expand Down
3 changes: 2 additions & 1 deletion scipy/sparse/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand Down
10 changes: 5 additions & 5 deletions scipy/stats/_axis_nan_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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.
Expand All @@ -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)
Expand Down
11 changes: 6 additions & 5 deletions scipy/stats/_stats_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]

Expand Down Expand Up @@ -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


Expand Down
5 changes: 3 additions & 2 deletions scipy/stats/tests/test_axis_nan_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions scipy/stats/tests/test_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
Loading

0 comments on commit 979fa4e

Please sign in to comment.