Skip to content

Commit 2951ce0

Browse files
keewiskmuehlbauermathausemax-sixtydcherian
authored
fix miscellaneous numpy=2.0 errors (#8117)
* replace `np.unicode_` with `np.str_` * replace `np.NaN` with `np.nan` * replace more instances of `np.unicode_` note that with more modern versions of `numpy` the `.astype(np.str_)` don't actually change the dtype, so maybe we can remove those. * more instances of renamed / removed dtypes * more dtype replacements * use `str.encode(encoding)` instead of `bytes(str, encoding)` * explicitly import `RankWarning` * left-over `np.RankWarning` * use `float` instead of the removed `np.float_` * ignore missing stubs for `numpy.exceptions` --------- Co-authored-by: Kai Mühlbauer <[email protected]> Co-authored-by: Mathias Hauser <[email protected]> Co-authored-by: Maximilian Roos <[email protected]> Co-authored-by: Deepak Cherian <[email protected]>
1 parent 0b3b20a commit 2951ce0

18 files changed

+158
-134
lines changed

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ module = [
6464
"sparse.*",
6565
"toolz.*",
6666
"zarr.*",
67+
"numpy.exceptions.*", # remove once support for `numpy<2.0` has been dropped
6768
]
6869

6970
[[tool.mypy.overrides]]

xarray/backends/netCDF4_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def _ensure_fill_value_valid(data, attributes):
207207
# work around for netCDF4/scipy issue where _FillValue has the wrong type:
208208
# https://github.com/Unidata/netcdf4-python/issues/271
209209
if data.dtype.kind == "S" and "_FillValue" in attributes:
210-
attributes["_FillValue"] = np.string_(attributes["_FillValue"])
210+
attributes["_FillValue"] = np.bytes_(attributes["_FillValue"])
211211

212212

213213
def _force_native_endianness(var):

xarray/coding/strings.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def ensure_fixed_length_bytes(var):
100100
dims, data, attrs, encoding = unpack_for_encoding(var)
101101
if check_vlen_dtype(data.dtype) == bytes:
102102
# TODO: figure out how to handle this with dask
103-
data = np.asarray(data, dtype=np.string_)
103+
data = np.asarray(data, dtype=np.bytes_)
104104
return Variable(dims, data, attrs, encoding)
105105

106106

@@ -151,7 +151,7 @@ def bytes_to_char(arr):
151151
def _numpy_bytes_to_char(arr):
152152
"""Like netCDF4.stringtochar, but faster and more flexible."""
153153
# ensure the array is contiguous
154-
arr = np.array(arr, copy=False, order="C", dtype=np.string_)
154+
arr = np.array(arr, copy=False, order="C", dtype=np.bytes_)
155155
return arr.reshape(arr.shape + (1,)).view("S1")
156156

157157

@@ -168,7 +168,7 @@ def char_to_bytes(arr):
168168

169169
if not size:
170170
# can't make an S0 dtype
171-
return np.zeros(arr.shape[:-1], dtype=np.string_)
171+
return np.zeros(arr.shape[:-1], dtype=np.bytes_)
172172

173173
if is_chunked_array(arr):
174174
chunkmanager = get_chunked_array_type(arr)

xarray/coding/times.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ def convert_times(times, date_type, raise_on_invalid: bool = True) -> np.ndarray
467467
Useful to convert between calendars in numpy and cftime or between cftime calendars.
468468
469469
If raise_on_valid is True (default), invalid dates trigger a ValueError.
470-
Otherwise, the invalid element is replaced by np.NaN for cftime types and np.NaT for np.datetime64.
470+
Otherwise, the invalid element is replaced by np.nan for cftime types and np.NaT for np.datetime64.
471471
"""
472472
if date_type in (pd.Timestamp, np.datetime64) and not is_np_datetime_like(
473473
times.dtype
@@ -489,7 +489,7 @@ def convert_times(times, date_type, raise_on_invalid: bool = True) -> np.ndarray
489489
f"{date_type(2000, 1, 1).calendar} calendar. Reason: {e}."
490490
)
491491
else:
492-
dt = np.NaN
492+
dt = np.nan
493493

494494
new[i] = dt
495495
return new

xarray/core/accessor_str.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ def cat(self, *others, sep: str | bytes | Any = "") -> T_DataArray:
471471
... )
472472
>>> values_2 = np.array(3.4)
473473
>>> values_3 = ""
474-
>>> values_4 = np.array("test", dtype=np.unicode_)
474+
>>> values_4 = np.array("test", dtype=np.str_)
475475
476476
Determine the separator to use
477477

xarray/core/dataarray.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5772,8 +5772,8 @@ def idxmin(
57725772
>>> array = xr.DataArray(
57735773
... [
57745774
... [2.0, 1.0, 2.0, 0.0, -2.0],
5775-
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
5776-
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
5775+
... [-4.0, np.nan, 2.0, np.nan, -2.0],
5776+
... [np.nan, np.nan, 1.0, np.nan, np.nan],
57775777
... ],
57785778
... dims=["y", "x"],
57795779
... coords={"y": [-1, 0, 1], "x": np.arange(5.0) ** 2},
@@ -5868,8 +5868,8 @@ def idxmax(
58685868
>>> array = xr.DataArray(
58695869
... [
58705870
... [2.0, 1.0, 2.0, 0.0, -2.0],
5871-
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
5872-
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
5871+
... [-4.0, np.nan, 2.0, np.nan, -2.0],
5872+
... [np.nan, np.nan, 1.0, np.nan, np.nan],
58735873
... ],
58745874
... dims=["y", "x"],
58755875
... coords={"y": [-1, 0, 1], "x": np.arange(5.0) ** 2},

xarray/core/dataset.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@
2424
from typing import IO, TYPE_CHECKING, Any, Callable, Generic, Literal, cast, overload
2525

2626
import numpy as np
27+
28+
# remove once numpy 2.0 is the oldest supported version
29+
try:
30+
from numpy.exceptions import RankWarning
31+
except ImportError:
32+
from numpy import RankWarning
33+
2734
import pandas as pd
2835

2936
from xarray.coding.calendar_ops import convert_calendar, interp_calendar
@@ -8785,9 +8792,9 @@ def polyfit(
87858792

87868793
with warnings.catch_warnings():
87878794
if full: # Copy np.polyfit behavior
8788-
warnings.simplefilter("ignore", np.RankWarning)
8795+
warnings.simplefilter("ignore", RankWarning)
87898796
else: # Raise only once per variable
8790-
warnings.simplefilter("once", np.RankWarning)
8797+
warnings.simplefilter("once", RankWarning)
87918798

87928799
coeffs, residuals = duck_array_ops.least_squares(
87938800
lhs, rhs.data, rcond=rcond, skipna=skipna_da
@@ -9077,8 +9084,8 @@ def idxmin(
90779084
>>> array2 = xr.DataArray(
90789085
... [
90799086
... [2.0, 1.0, 2.0, 0.0, -2.0],
9080-
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
9081-
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
9087+
... [-4.0, np.nan, 2.0, np.nan, -2.0],
9088+
... [np.nan, np.nan, 1.0, np.nan, np.nan],
90829089
... ],
90839090
... dims=["y", "x"],
90849091
... coords={"y": [-1, 0, 1], "x": ["a", "b", "c", "d", "e"]},
@@ -9174,8 +9181,8 @@ def idxmax(
91749181
>>> array2 = xr.DataArray(
91759182
... [
91769183
... [2.0, 1.0, 2.0, 0.0, -2.0],
9177-
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
9178-
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
9184+
... [-4.0, np.nan, 2.0, np.nan, -2.0],
9185+
... [np.nan, np.nan, 1.0, np.nan, np.nan],
91799186
... ],
91809187
... dims=["y", "x"],
91819188
... coords={"y": [-1, 0, 1], "x": ["a", "b", "c", "d", "e"]},

xarray/core/dtypes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def __eq__(self, other):
4040
PROMOTE_TO_OBJECT: tuple[tuple[type[np.generic], type[np.generic]], ...] = (
4141
(np.number, np.character), # numpy promotes to character
4242
(np.bool_, np.character), # numpy promotes to character
43-
(np.bytes_, np.unicode_), # numpy promotes to unicode
43+
(np.bytes_, np.str_), # numpy promotes to unicode
4444
)
4545

4646

xarray/core/missing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ def interp_func(var, x, new_x, method: InterpOptions, kwargs):
730730
# scipy.interpolate.interp1d always forces to float.
731731
# Use the same check for blockwise as well:
732732
if not issubclass(var.dtype.type, np.inexact):
733-
dtype = np.float_
733+
dtype = float
734734
else:
735735
dtype = var.dtype
736736

xarray/core/nputils.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66
import pandas as pd
77
from numpy.core.multiarray import normalize_axis_index # type: ignore[attr-defined]
88

9+
# remove once numpy 2.0 is the oldest supported version
10+
try:
11+
from numpy.exceptions import RankWarning
12+
except ImportError:
13+
from numpy import RankWarning
14+
915
from xarray.core.options import OPTIONS
1016
from xarray.core.pycompat import is_duck_array
1117

@@ -194,7 +200,7 @@ def _nanpolyfit_1d(arr, x, rcond=None):
194200

195201
def warn_on_deficient_rank(rank, order):
196202
if rank != order:
197-
warnings.warn("Polyfit may be poorly conditioned", np.RankWarning, stacklevel=2)
203+
warnings.warn("Polyfit may be poorly conditioned", RankWarning, stacklevel=2)
198204

199205

200206
def least_squares(lhs, rhs, rcond=None, skipna=False):

0 commit comments

Comments
 (0)