Skip to content

Commit f69ba29

Browse files
committed
Revert "WIP"
This reverts commit 54be9b1.
1 parent 856b299 commit f69ba29

File tree

4 files changed

+24
-83
lines changed

4 files changed

+24
-83
lines changed

xarray/coding/strings.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from xarray.core.utils import module_available
1919
from xarray.core.variable import Variable
2020
from xarray.namedarray.parallelcompat import get_chunked_array_type
21-
from xarray.namedarray.pycompat import is_chunked_array, to_numpy
21+
from xarray.namedarray.pycompat import is_chunked_array
2222

2323
HAS_NUMPY_2_0 = module_available("numpy", minversion="2.0.0.dev0")
2424

@@ -135,8 +135,7 @@ def decode(self, variable, name=None):
135135
if data.dtype == "S1" and dims:
136136
encoding["char_dim_name"] = dims[-1]
137137
dims = dims[:-1]
138-
# TODO (duck array encoding)
139-
data = char_to_bytes(to_numpy(data))
138+
data = char_to_bytes(data)
140139
return Variable(dims, data, attrs, encoding)
141140

142141

xarray/coding/times.py

Lines changed: 21 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -21,24 +21,14 @@
2121
unpack_for_encoding,
2222
)
2323
from xarray.core import indexing
24-
from xarray.core.array_api_compat import get_array_namespace
2524
from xarray.core.common import contains_cftime_datetimes, is_np_datetime_like
26-
from xarray.core.duck_array_ops import (
27-
array_all,
28-
array_any,
29-
asarray,
30-
astype,
31-
concatenate,
32-
isnull,
33-
ravel,
34-
reshape,
35-
)
25+
from xarray.core.duck_array_ops import array_all, array_any, asarray, ravel, reshape
3626
from xarray.core.formatting import first_n_items, format_timestamp, last_item
3727
from xarray.core.pdcompat import default_precision_timestamp, timestamp_as_unit
3828
from xarray.core.utils import attempt_import, emit_user_level_warning
3929
from xarray.core.variable import Variable
4030
from xarray.namedarray.parallelcompat import T_ChunkedArray, get_chunked_array_type
41-
from xarray.namedarray.pycompat import is_chunked_array, to_duck_array, to_numpy
31+
from xarray.namedarray.pycompat import is_chunked_array, to_numpy
4232
from xarray.namedarray.utils import is_duck_dask_array
4333

4434
try:
@@ -110,7 +100,7 @@ def _is_numpy_compatible_time_range(times):
110100
if is_np_datetime_like(times.dtype):
111101
return True
112102
# times array contains cftime objects
113-
times = to_duck_array(times)
103+
times = np.asarray(times)
114104
tmin = times.min()
115105
tmax = times.max()
116106
try:
@@ -319,9 +309,8 @@ def _decode_cf_datetime_dtype(
319309
# successfully. Otherwise, tracebacks end up swallowed by
320310
# Dataset.__repr__ when users try to view their lazily decoded array.
321311
values = indexing.ImplicitToExplicitIndexingAdapter(indexing.as_indexable(data))
322-
zero = asarray([0], xp=get_array_namespace(values))
323-
example_value = concatenate(
324-
[first_n_items(values, 1) or zero, last_item(values) or zero]
312+
example_value = np.concatenate(
313+
[to_numpy(first_n_items(values, 1) or [0]), to_numpy(last_item(values) or [0])]
325314
)
326315

327316
try:
@@ -353,13 +342,7 @@ def _decode_datetime_with_cftime(
353342
cftime = attempt_import("cftime")
354343
if num_dates.size > 0:
355344
return np.asarray(
356-
cftime.num2date(
357-
# cftime uses Cython so we must convert to numpy here.
358-
to_numpy(num_dates),
359-
units,
360-
calendar,
361-
only_use_cftime_datetimes=True,
362-
)
345+
cftime.num2date(num_dates, units, calendar, only_use_cftime_datetimes=True)
363346
)
364347
else:
365348
return np.array([], dtype=object)
@@ -374,7 +357,7 @@ def _check_date_for_units_since_refdate(
374357
f"Value {date} can't be represented as Datetime/Timedelta."
375358
)
376359
delta = date * np.timedelta64(1, unit)
377-
if not isnull(delta):
360+
if not np.isnan(delta):
378361
# this will raise on dtype overflow for integer dtypes
379362
if date.dtype.kind in "u" and not np.int64(delta) == date:
380363
raise OutOfBoundsTimedelta(
@@ -398,7 +381,7 @@ def _check_timedelta_range(value, data_unit, time_unit):
398381
"ignore", "invalid value encountered in multiply", RuntimeWarning
399382
)
400383
delta = value * np.timedelta64(1, data_unit)
401-
if not isnull(delta):
384+
if not np.isnan(delta):
402385
# this will raise on dtype overflow for integer dtypes
403386
if value.dtype.kind in "u" and not np.int64(delta) == value:
404387
raise OutOfBoundsTimedelta(
@@ -466,9 +449,9 @@ def _decode_datetime_with_pandas(
466449
# respectively. See https://github.com/pandas-dev/pandas/issues/56996 for
467450
# more details.
468451
if flat_num_dates.dtype.kind == "i":
469-
flat_num_dates = astype(flat_num_dates, np.int64)
452+
flat_num_dates = flat_num_dates.astype(np.int64)
470453
elif flat_num_dates.dtype.kind == "u":
471-
flat_num_dates = astype(flat_num_dates, np.uint64)
454+
flat_num_dates = flat_num_dates.astype(np.uint64)
472455

473456
try:
474457
time_unit, ref_date = _unpack_time_unit_and_ref_date(units)
@@ -500,9 +483,9 @@ def _decode_datetime_with_pandas(
500483
# overflow when converting to np.int64 would not be representable with a
501484
# timedelta64 value, and therefore would raise an error in the lines above.
502485
if flat_num_dates.dtype.kind in "iu":
503-
flat_num_dates = astype(flat_num_dates, np.int64)
486+
flat_num_dates = flat_num_dates.astype(np.int64)
504487
elif flat_num_dates.dtype.kind in "f":
505-
flat_num_dates = astype(flat_num_dates, np.float64)
488+
flat_num_dates = flat_num_dates.astype(np.float64)
506489

507490
timedeltas = _numbers_to_timedelta(
508491
flat_num_dates, time_unit, ref_date.unit, "datetime"
@@ -545,12 +528,8 @@ def decode_cf_datetime(
545528
)
546529
except (KeyError, OutOfBoundsDatetime, OutOfBoundsTimedelta, OverflowError):
547530
dates = _decode_datetime_with_cftime(
548-
astype(flat_num_dates, float), units, calendar
531+
flat_num_dates.astype(float), units, calendar
549532
)
550-
# This conversion to numpy is only needed for nanarg* below.
551-
# TODO: explore removing it.
552-
# Note that `dates` is already a numpy object array of cftime objects.
553-
num_dates = to_numpy(num_dates)
554533
# retrieve cftype
555534
dates_min = dates[np.nanargmin(num_dates)]
556535
dates_max = dates[np.nanargmax(num_dates)]
@@ -607,16 +586,16 @@ def _numbers_to_timedelta(
607586
"""Transform numbers to np.timedelta64."""
608587
# keep NaT/nan mask
609588
if flat_num.dtype.kind == "f":
610-
nan = isnull(flat_num)
589+
nan = np.asarray(np.isnan(flat_num))
611590
elif flat_num.dtype.kind == "i":
612-
nan = flat_num == np.iinfo(np.int64).min
591+
nan = np.asarray(flat_num == np.iinfo(np.int64).min)
613592

614593
# in case we need to change the unit, we fix the numbers here
615594
# this should be safe, as errors would have been raised above
616595
ns_time_unit = _NS_PER_TIME_DELTA[time_unit]
617596
ns_ref_date_unit = _NS_PER_TIME_DELTA[ref_unit]
618597
if ns_time_unit > ns_ref_date_unit:
619-
flat_num = flat_num * np.int64(ns_time_unit / ns_ref_date_unit)
598+
flat_num = np.asarray(flat_num * np.int64(ns_time_unit / ns_ref_date_unit))
620599
time_unit = ref_unit
621600

622601
# estimate fitting resolution for floating point values
@@ -639,12 +618,12 @@ def _numbers_to_timedelta(
639618
# to prevent casting NaN to int
640619
with warnings.catch_warnings():
641620
warnings.simplefilter("ignore", RuntimeWarning)
642-
flat_num = astype(flat_num, np.int64)
643-
if array_any(nan):
621+
flat_num = flat_num.astype(np.int64)
622+
if nan.any():
644623
flat_num[nan] = np.iinfo(np.int64).min
645624

646625
# cast to wanted type
647-
return astype(flat_num, f"timedelta64[{time_unit}]")
626+
return flat_num.astype(f"timedelta64[{time_unit}]")
648627

649628

650629
def decode_cf_timedelta(
@@ -733,8 +712,8 @@ def infer_datetime_units(dates) -> str:
733712
'hours', 'minutes' or 'seconds' (the first one that can evenly divide all
734713
unique time deltas in `dates`)
735714
"""
736-
dates = ravel(to_duck_array(dates))
737-
if np.issubdtype(dates.dtype, "datetime64"):
715+
dates = ravel(np.asarray(dates))
716+
if np.issubdtype(np.asarray(dates).dtype, "datetime64"):
738717
dates = to_datetime_unboxed(dates)
739718
dates = dates[pd.notnull(dates)]
740719
reference_date = dates[0] if len(dates) > 0 else "1970-01-01"

xarray/tests/arrays.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -51,18 +51,6 @@ def __init__(self, array: np.ndarray):
5151
def __getitem__(self, key):
5252
return type(self)(self.array[key])
5353

54-
def min(self):
55-
return self.array.min()
56-
57-
def max(self):
58-
return self.array.max()
59-
60-
def __mul__(self, other):
61-
return type(self)(self.array.__mul__(other))
62-
63-
def __radd__(self, other):
64-
return type(self)(other + self.array)
65-
6654
def to_numpy(self) -> np.ndarray:
6755
"""Allow explicit conversions to numpy in `to_numpy`, but disallow np.asarray etc."""
6856
return self.array

xarray/tests/namespace.py

Lines changed: 1 addition & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,5 @@
1-
import numpy as np
2-
3-
from xarray.core import array_api_compat, duck_array_ops
1+
from xarray.core import duck_array_ops
42

53

64
def reshape(array, shape, **kwargs):
75
return type(array)(duck_array_ops.reshape(array.array, shape=shape, **kwargs))
8-
9-
10-
def concatenate(arrays, axis):
11-
return type(arrays[0])(
12-
duck_array_ops.concatenate([a.array for a in arrays], axis=axis)
13-
)
14-
15-
16-
def result_type(*arrays_and_dtypes):
17-
parsed = [a.array if hasattr(a, "array") else a for a in arrays_and_dtypes]
18-
return array_api_compat.result_type(*parsed, xp=np)
19-
20-
21-
def astype(array, dtype, **kwargs):
22-
return type(array)(duck_array_ops.astype(array.array, dtype=dtype, **kwargs))
23-
24-
25-
def isnan(array):
26-
return type(array)(duck_array_ops.isnull(array.array))
27-
28-
29-
def any(array, *args, **kwargs): # TODO: keepdims
30-
return duck_array_ops.array_any(array.array, *args, **kwargs)

0 commit comments

Comments
 (0)