Skip to content

Commit c18d255

Browse files
committed
Finish up Numpy 2.0 port
1 parent 330866b commit c18d255

16 files changed

+84
-32
lines changed

nipy/algorithms/diagnostics/tsdiffplot.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import numpy as np
66

77
import nipy
8+
from ...utils import deprecate_with_doc
89

910
from .timediff import time_slice_diffs
1011

@@ -76,7 +77,7 @@ def xmax_labels(ax, val, xlabel, ylabel):
7677
return axes
7778

7879

79-
@np.deprecate_with_doc('Please see docstring for alternative code')
80+
@deprecate_with_doc('please see docstring for alternative code')
8081
def plot_tsdiffs_image(img, axes=None, show=True):
8182
''' Plot time series diagnostics for image
8283

nipy/algorithms/statistics/formula/formulae.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,14 @@
123123
from nipy.algorithms.utils.matrices import full_rank, matrix_rank
124124

125125
# Legacy repr printing from numpy.
126-
from nipy.utils import VisibleDeprecationWarning, _NoValue
126+
from nipy.utils import VisibleDeprecationWarning, _NoValue, deprecate_with_doc
127127

128128

129129
def _to_str(s):
130130
return s.decode('latin1') if isinstance(s, bytes) else str(s)
131131

132132

133-
@np.deprecate(message = "Please use sympy.Dummy instead of this function")
133+
@deprecate_with_doc("please use sympy.Dummy instead")
134134
def make_dummy(name):
135135
""" Make dummy variable of given name
136136

nipy/algorithms/statistics/tests/test_intrinsic_volumes.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pytest
99
from numpy.testing import assert_almost_equal, assert_array_equal
1010

11+
from nipy.utils import SCTYPES
1112
from .. import intvol
1213

1314

@@ -190,7 +191,7 @@ def test_ec():
190191
assert_almost_equal(f(box1), 1)
191192
# While we're here, test we can use different dtypes, and that values
192193
# other than 0 or 1 raise an error.
193-
for dtt in sum([np.sctypes[t] for t in ('int', 'uint', 'float')], []):
194+
for dtt in sum([SCTYPES[t] for t in ('int', 'uint', 'float')], []):
194195
box1_again = box1.copy().astype(dtt)
195196
assert_almost_equal(f(box1_again), 1)
196197
box1_again[(10,) * i] = 2

nipy/algorithms/statistics/tests/test_quantile.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1+
""" Test quartile functions
2+
"""
13

24
import numpy as np
35
from numpy import median as np_median
46
from numpy.testing import assert_array_almost_equal, assert_array_equal
57
from scipy.stats import scoreatpercentile as sp_percentile
68

9+
from nipy.utils import SCTYPES
710
from .._quantile import _median, _quantile
811

9-
NUMERIC_TYPES = sum([np.sctypes[t]
12+
NUMERIC_TYPES = sum([SCTYPES[t]
1013
for t in ('int', 'uint', 'float', 'complex')],
1114
[])
1215

nipy/algorithms/statistics/tests/test_utils.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
)
1010
from scipy.stats import norm
1111

12-
from ..utils import check_cast_bin8, multiple_fast_inv, multiple_mahalanobis, z_score
12+
from nipy.utils import SCTYPES
13+
from ..utils import (check_cast_bin8, multiple_fast_inv, multiple_mahalanobis,
14+
z_score)
1315

1416

1517
def test_z_score():
@@ -59,13 +61,13 @@ def assert_equal_bin8(actual, expected):
5961

6062
def test_check_cast_bin8():
6163
# Function to return np.uint8 array with check whether array is binary.
62-
for in_dtype in np.sctypes['int'] + np.sctypes['uint']:
64+
for in_dtype in SCTYPES['int'] + SCTYPES['uint']:
6365
assert_equal_bin8(np.array([0, 1, 1, 1], in_dtype), [0, 1, 1, 1])
6466
assert_equal_bin8(np.array([[0, 1], [1, 1]], in_dtype),
6567
[[0, 1], [1, 1]])
6668
pytest.raises(ValueError, check_cast_bin8,
6769
np.array([0, 1, 2], dtype=in_dtype))
68-
for in_dtype in np.sctypes['float']:
70+
for in_dtype in SCTYPES['float']:
6971
assert_equal_bin8(np.array([0, 1, 1, -0], np.float64), [0, 1, 1, 0])
7072
assert_equal_bin8(np.array([[0, 1], [1, -0]], np.float64),
7173
[[0, 1], [1, 0]])

nipy/algorithms/utils/pca.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import numpy as np
1818
import numpy.linalg as npl
1919

20+
from ...utils import SCTYPES
2021
from ...core.image.image import rollimg
2122
from ...core.reference.coordinate_map import (
2223
AxisError,
@@ -204,8 +205,8 @@ def _get_covariance(data, UX, rmse_scales_func, mask):
204205
C = np.zeros((rank, rank))
205206
# nan_to_num only for floating point masks
206207
if mask is not None:
207-
nan_to_num = mask.dtype.type in (np.sctypes['float'] +
208-
np.sctypes['complex'])
208+
nan_to_num = mask.dtype.type in (SCTYPES['float'] +
209+
SCTYPES['complex'])
209210
# loop over next dimension to save memory
210211
if data.ndim == 2:
211212
# If we have 2D data, just do the covariance all in one shot, by using

nipy/algorithms/utils/tests/test_pca.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import numpy as np
44
import pytest
55

6+
from nipy.utils import SCTYPES
67
from nipy.io.api import load_image
78
from nipy.testing import (
89
assert_almost_equal,
@@ -169,9 +170,9 @@ def test_PCAMask(data):
169170
assert_almost_equal(p['pcnt_var'].sum(), 100.)
170171
# Any reasonable datatype for mask
171172
for dt in ([np.bool_] +
172-
np.sctypes['int'] +
173-
np.sctypes['uint'] +
174-
np.sctypes['float']):
173+
SCTYPES['int'] +
174+
SCTYPES['uint'] +
175+
SCTYPES['float']):
175176
p = pca(arr4d, -1, mask3d.astype(dt), ncomp=ncomp)
176177
assert p['basis_vectors'].shape == (data['nimages'], ntotal)
177178
assert p['basis_projections'].shape == mask3d.shape + (ncomp,)

nipy/core/image/image.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
import numpy as np
1919
from nibabel.onetime import auto_attr
2020

21+
from ...utils import deprecate_with_doc
22+
2123
# Legacy repr printing from numpy.
2224
from ..reference.array_coords import ArrayCoordMap
2325

@@ -581,7 +583,7 @@ def fromarray(data, innames, outnames):
581583
return Image(data, coordmap)
582584

583585

584-
@np.deprecate_with_doc('Please use rollimg instead')
586+
@deprecate_with_doc('please use rollimg instead')
585587
def rollaxis(img, axis, inverse=False):
586588
""" Roll `axis` backwards, until it lies in the first position.
587589

nipy/core/reference/coordinate_system.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515

1616
import numpy as np
1717

18+
from ...utils import SCTYPES
19+
1820

1921
class CoordinateSystemError(Exception):
2022
pass
@@ -115,8 +117,8 @@ def __init__(self, coord_names, name='', coord_dtype=np.float64):
115117
if len(set(coord_names)) != len(coord_names):
116118
raise ValueError('coord_names must have distinct names')
117119
# verify that the dtype is coord_dtype for sanity
118-
sctypes = (np.sctypes['int'] + np.sctypes['float'] +
119-
np.sctypes['complex'] + np.sctypes['uint'] + [object])
120+
sctypes = (SCTYPES['int'] + SCTYPES['float'] +
121+
SCTYPES['complex'] + SCTYPES['uint'] + [object])
120122
coord_dtype = np.dtype(coord_dtype)
121123
if coord_dtype not in sctypes:
122124
raise ValueError(f'Coordinate dtype should be one of {sctypes}')

nipy/core/reference/tests/test_coordinate_map.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
import numpy as np
77

8+
from nipy.utils import SCTYPES
9+
810
# this import line is a little ridiculous...
911
from ..coordinate_map import (
1012
AffineTransform,
@@ -35,8 +37,8 @@
3537
from numpy.testing import assert_almost_equal, assert_array_equal
3638

3739
# Dtypes for testing coordinate map creation / processing
38-
_SYMPY_SAFE_DTYPES = (np.sctypes['int'] + np.sctypes['uint'] +
39-
np.sctypes['float'] + np.sctypes['complex'] +
40+
_SYMPY_SAFE_DTYPES = (SCTYPES['int'] + SCTYPES['uint'] +
41+
SCTYPES['float'] + SCTYPES['complex'] +
4042
[object])
4143
# Sympy <= 1.1 does not handle numpy longcomplex correctly. See:
4244
# https://github.com/sympy/sympy/pull/12901
@@ -965,7 +967,7 @@ def test_dtype_cmap_inverses():
965967
coord = np.array(in_list, dtype=dt)
966968
out_coord = np.array(out_list, dtype=dt)
967969
# Expected output type of inverse, not preserving
968-
if dt in np.sctypes['int'] + np.sctypes['uint']:
970+
if dt in SCTYPES['int'] + SCTYPES['uint']:
969971
exp_i_dt = np.float64
970972
else:
971973
exp_i_dt = dt
@@ -1000,7 +1002,7 @@ def test_dtype_cmap_inverses():
10001002
arr_p2 = arr_p1 * 2
10011003
arr_p2[-1, -1] = 1
10021004
out_list = [0, 4, 2]
1003-
for dt in np.sctypes['int'] + np.sctypes['uint']:
1005+
for dt in SCTYPES['int'] + SCTYPES['uint']:
10041006
in_cs = CoordinateSystem('ijk', coord_dtype=dt)
10051007
out_cs = CoordinateSystem('xyz', coord_dtype=dt)
10061008
cmap = AffineTransform(in_cs, out_cs, arr_p2.astype(dt))

nipy/core/reference/tests/test_coordinate_system.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import numpy as np
77
import pytest
88

9+
from nipy.utils import SCTYPES
10+
911
from ..coordinate_system import (
1012
CoordinateSystem,
1113
CoordinateSystemError,
@@ -60,15 +62,15 @@ def test_unique_coord_names():
6062

6163
def test_dtypes():
6264
# invalid dtypes
63-
dtypes = np.sctypes['others']
65+
dtypes = SCTYPES['others']
6466
dtypes.remove(object)
6567
for dt in dtypes:
6668
pytest.raises(ValueError, CoordinateSystem, 'ijk', 'test', dt)
6769
# compound dtype
6870
dtype = np.dtype([('field1', '<f8'), ('field2', '<i4')])
6971
pytest.raises(ValueError, CoordinateSystem, 'ijk', 'test', dtype)
7072
# valid dtypes
71-
dtypes = (np.sctypes['int'] + np.sctypes['float'] + np.sctypes['complex'] +
73+
dtypes = (SCTYPES['int'] + SCTYPES['float'] + SCTYPES['complex'] +
7274
[object])
7375
for dt in dtypes:
7476
cs = CoordinateSystem('ij', coord_dtype=dt)
@@ -184,10 +186,10 @@ def test_safe_dtype():
184186
pytest.raises(TypeError, safe_dtype, str, np.float64)
185187
pytest.raises(TypeError, safe_dtype, [('x', 'f8')])
186188
valid_dtypes = []
187-
valid_dtypes.extend(np.sctypes['complex'])
188-
valid_dtypes.extend(np.sctypes['float'])
189-
valid_dtypes.extend(np.sctypes['int'])
190-
valid_dtypes.extend(np.sctypes['uint'])
189+
valid_dtypes.extend(SCTYPES['complex'])
190+
valid_dtypes.extend(SCTYPES['float'])
191+
valid_dtypes.extend(SCTYPES['int'])
192+
valid_dtypes.extend(SCTYPES['uint'])
191193
for dt in valid_dtypes:
192194
sdt = safe_dtype(dt)
193195
assert sdt == dt

nipy/labs/bindings/tests/test_numpy.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import numpy as np
66
from numpy.testing import assert_almost_equal, assert_array_equal
77

8+
from nipy.utils import SCTYPES
9+
810
from .. import (
911
c_types,
1012
copy_vector,
@@ -35,12 +37,12 @@ def random_shape(size):
3537
#
3638

3739
def test_type_conversions_to_fff():
38-
# use np.sctypes for testing numpy types, np.typeDict.values
40+
# use SCTYPES for testing numpy types, np.typeDict.values
3941
# contains a lot of duplicates. There are 140 values in
4042
# np.typeDict, but only 21 unique numpy types. But only 11 fff
4143
# types in c_types.
42-
for type_key in np.sctypes:
43-
for npy_t in np.sctypes[type_key]:
44+
for type_key in SCTYPES:
45+
for npy_t in SCTYPES[type_key]:
4446
t, nbytes = fff_type(np.dtype(npy_t))
4547
if t != 'unknown type':
4648
assert nbytes == np.dtype(npy_t).itemsize

nipy/labs/bindings/wrapper.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ def copy_via_iterators(ndarray Y, int axis=0):
162162
cdef fffpy_multi_iterator* multi
163163

164164
# Allocate output array
165-
Z = np.zeros_like(Y, dtype=np.float_)
165+
Z = np.zeros_like(Y, dtype=np.float64)
166166

167167
# Create a new array iterator
168168
multi = fffpy_multi_iterator_new(2, axis, <void*>Y, <void*>Z)

nipy/labs/meson.build

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ python_sources = [
66
'mask.py',
77
'statistical_mapping.py',
88
'viz3d.py',
9-
'viz.py'
9+
'viz.py',
10+
'conftest.py'
1011
]
12+
1113
py.install_sources(
1214
python_sources,
1315
pure: false,

nipy/utils/__init__.py

+30
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@
77
wrote, that we ship, go in the nipy.externals tree.
88
"""
99

10+
import functools
11+
import warnings
12+
13+
import numpy as np
14+
1015
from nibabel.data import DataError, datasource_or_bomber, make_datasource
1116

1217
# Module level datasource instances for convenience
@@ -48,3 +53,28 @@ class _NoValue:
4853
This class may be used as the default value assigned to a deprecated
4954
keyword in order to check if it has been given a user defined value.
5055
"""
56+
57+
58+
# Numpy sctypes (np.sctypes removed in Numpy 2.0).
59+
SCTYPES = {'int': [np.int8, np.int16, np.int32, np.int64],
60+
'uint': [np.uint8, np.uint16, np.uint32, np.uint64],
61+
'float': [np.float16, np.float32, np.float64],
62+
'complex': [np.complex64, np.complex128],
63+
'others': [bool, object, bytes, str, np.void]}
64+
65+
66+
def deprecate_with_doc(msg):
67+
# Adapted from: https://stackoverflow.com/a/30253848/1939576
68+
69+
def dep(func):
70+
71+
@functools.wraps(func)
72+
def new_func(*args, **kwargs):
73+
warnings.warn(
74+
f"{func.__name__} deprecated, {msg}",
75+
category=DeprecationWarning, stacklevel=2)
76+
return func(*args, **kwargs)
77+
78+
return new_func
79+
80+
return dep

nipy/utils/tests/test_arrays.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@
66
from numpy.testing import assert_array_almost_equal, assert_array_equal
77

88
from ..arrays import strides_from
9+
from nipy.utils import SCTYPES
910

1011

1112
def test_strides_from():
1213
for shape in ((3,), (2,3), (2,3,4), (5,4,3,2)):
1314
for order in 'FC':
14-
for dtype in sum(np.sctypes.values(), []):
15+
for dtype in sum(SCTYPES.values(), []):
1516
if dtype is bytes:
1617
dtype = 'S3'
1718
elif dtype is str:

0 commit comments

Comments
 (0)