Skip to content

Commit 0b2496f

Browse files
authored
MAINT: stats.wilcoxon: fix attempt to access np.AxisError (scipy#22056)
* MAINT: stats.wilcoxon: fix attempt to access np.AxisError
1 parent 2af8108 commit 0b2496f

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

scipy/stats/_wilcoxon.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ def _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis):
5757
raise ValueError(message)
5858

5959
message = '`axis` must be compatible with the shape(s) of `x` (and `y`)'
60+
AxisError = getattr(np, 'AxisError', None) or np.exceptions.AxisError
6061
try:
6162
if y is None:
6263
x = np.asarray(x)
@@ -65,8 +66,8 @@ def _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis):
6566
x, y = _broadcast_arrays((x, y), axis=axis)
6667
d = x - y
6768
d = np.moveaxis(d, axis, -1)
68-
except np.AxisError as e:
69-
raise ValueError(message) from e
69+
except AxisError as e:
70+
raise AxisError(message) from e
7071

7172
message = "`x` and `y` must have the same length along `axis`."
7273
if y is not None and x.shape[axis] != y.shape[axis]:

scipy/stats/tests/test_morestats.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1768,6 +1768,27 @@ def test_all_zeros_exact(self, method):
17681768
res = stats.wilcoxon(np.zeros(5), method=method)
17691769
assert_allclose(res, [0, 1])
17701770

1771+
def test_wilcoxon_axis_broadcasting_errors_gh22051(self):
1772+
# In previous versions of SciPy, `wilcoxon` gave an incorrect error
1773+
# message when `AxisError` was not found in the base NumPy namespace.
1774+
# Check that this is resolved with and without the ANP decorator.
1775+
message = "Array shapes are incompatible for broadcasting."
1776+
with pytest.raises(ValueError, match=message):
1777+
stats.wilcoxon([1, 2, 3], [4, 5])
1778+
1779+
message = "operands could not be broadcast together with..."
1780+
with pytest.raises(ValueError, match=message):
1781+
stats.wilcoxon([1, 2, 3], [4, 5], _no_deco=True)
1782+
1783+
AxisError = getattr(np, 'AxisError', None) or np.exceptions.AxisError
1784+
message = "source: axis 3 is out of bounds for array of dimension 1"
1785+
with pytest.raises(AxisError, match=message):
1786+
stats.wilcoxon([1, 2, 3], [4, 5, 6], axis=3)
1787+
1788+
message = "`axis` must be compatible with the shape..."
1789+
with pytest.raises(AxisError, match=message):
1790+
stats.wilcoxon([1, 2, 3], [4, 5, 6], axis=3, _no_deco=True)
1791+
17711792

17721793
# data for k-statistics tests from
17731794
# https://cran.r-project.org/web/packages/kStatistics/kStatistics.pdf

0 commit comments

Comments
 (0)