Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ Deprecations
Bug Fixes
~~~~~~~~~

- Preserve standard-calendar dates outside the NumPy range when infinite time
offsets are present, including in chunked arrays (:issue:`11988`).

Documentation
~~~~~~~~~~~~~
Expand Down
44 changes: 35 additions & 9 deletions xarray/coding/common.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from collections.abc import Callable, Hashable, MutableMapping
from typing import TYPE_CHECKING, Any, Union, override
from typing import TYPE_CHECKING, Any, Self, Union, override

import numpy as np

Expand Down Expand Up @@ -53,11 +53,28 @@ class _ElementwiseFunctionArray(indexing.ExplicitlyIndexedNDArrayMixin):
Values are computed upon indexing or coercion to a NumPy array.
"""

def __init__(self, array, func: Callable, dtype: np.typing.DTypeLike | None):
def __init__(
self,
array,
func: Callable,
dtype: np.typing.DTypeLike | None,
chunked_func: Callable | None = None,
) -> None:
assert not is_chunked_array(array)
self.array = indexing.as_indexable(array)
self.func = func
self._dtype = dtype
self._chunked_func = chunked_func

def _with_array(self, array: Any) -> Self:
return type(self)(array, self.func, self.dtype, self._chunked_func)

@override
def _prepare_for_chunking(self) -> Self:
array = self.array._prepare_for_chunking()
if self._chunked_func is not None:
return type(self)(array, self._chunked_func, self.dtype)
return self if array is self.array else self._with_array(array)

@override
@property
Expand All @@ -66,19 +83,19 @@ def dtype(self) -> np.dtype:

def transpose(self, order):
# For elementwise functions, we can compose transpose and function application
return type(self)(self.array.transpose(order), self.func, self.dtype)
return self._with_array(self.array.transpose(order))

@override
def _oindex_get(self, key):
return type(self)(self.array.oindex[key], self.func, self.dtype)
return self._with_array(self.array.oindex[key])

@override
def _vindex_get(self, key):
return type(self)(self.array.vindex[key], self.func, self.dtype)
return self._with_array(self.array.vindex[key])

@override
def __getitem__(self, key):
return type(self)(self.array[key], self.func, self.dtype)
return self._with_array(self.array[key])

@override
def get_duck_array(self):
Expand All @@ -93,7 +110,13 @@ def __repr__(self) -> str:
return f"{type(self).__name__}({self.array!r}, func={self.func!r}, dtype={self.dtype!r})"


def lazy_elemwise_func(array, func: Callable, dtype: np.typing.DTypeLike | None):
def lazy_elemwise_func(
array,
func: Callable,
dtype: np.typing.DTypeLike | None,
*,
chunked_func: Callable | None = None,
) -> Any:
"""Lazily apply an element-wise function to an array.

Parameters
Expand All @@ -104,17 +127,20 @@ def lazy_elemwise_func(array, func: Callable, dtype: np.typing.DTypeLike | None)
this should be a pickle-able object.
dtype : coercible to np.dtype
Dtype for the result of this function.
chunked_func : callable, optional
Function to apply when values are decoded in independent chunks.

Returns
-------
Either a dask.array.Array or _ElementwiseFunctionArray.
"""
if is_chunked_array(array):
chunkmanager = get_chunked_array_type(array)

if chunked_func is not None:
func = chunked_func
return chunkmanager.map_blocks(func, array, dtype=dtype) # type: ignore[arg-type]
else:
return _ElementwiseFunctionArray(array, func, dtype)
return _ElementwiseFunctionArray(array, func, dtype, chunked_func)


def safe_setitem(dest, key: Hashable, value, name: T_Name = None):
Expand Down
70 changes: 61 additions & 9 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,30 @@ def _decode_cf_datetime_as(num_dates, *, dtype: np.dtype, **kwargs) -> np.ndarra
return result


def _decode_cf_datetime_chunk(
num_dates: np.ndarray, *, dtype: np.dtype, **kwargs
) -> np.ndarray:
"""Keep the sampled date representation consistent across chunks."""
result = decode_cf_datetime(num_dates, **kwargs)
if result.dtype.kind == dtype.kind:
return result
if dtype.kind == "O":
# Casting a datetime64[ns] array to object produces integers. Decode
# from the original offsets and leave NaT positions missing.
valid = ~np.isnat(result)
dates = np.full(result.shape, None, dtype=object)
if valid.any():
kwargs["use_cftime"] = True
dates[valid] = decode_cf_datetime(to_numpy(num_dates)[valid], **kwargs)
return dates

raise ValueError(
f"time values with units {kwargs['units']!r} decode to "
f"{result.dtype}, not to {dtype} as inferred from data. "
"Set use_cftime or time_unit to match the stored values."
)


def _decode_datetime_with_cftime(
num_dates: np.ndarray, units: str, calendar: str
) -> np.ndarray:
Expand Down Expand Up @@ -619,12 +643,23 @@ def decode_cf_datetime(
flat_num_dates, units, calendar, time_unit
)
except (KeyError, OutOfBoundsDatetime, OutOfBoundsTimedelta, OverflowError):
dates = _decode_datetime_with_cftime(
flat_num_dates.astype(float), units, calendar
)
cftime_offsets = flat_num_dates.astype(float)
dates = _decode_datetime_with_cftime(cftime_offsets, units, calendar)
standard_calendar = _is_standard_calendar(calendar)
range_dates = dates
range_offsets = flat_num_dates
valid = None
# cftime masks infinities, but nanargmin/nanargmax include them.
if standard_calendar and np.isinf(cftime_offsets).any():
finite = np.isfinite(cftime_offsets)
if finite.any():
valid = finite
range_dates = dates[valid]
range_offsets = range_offsets[valid]

# retrieve cftype
dates_min = dates[np.nanargmin(num_dates)]
dates_max = dates[np.nanargmax(num_dates)]
dates_min = range_dates[np.nanargmin(range_offsets)]
dates_max = range_dates[np.nanargmax(range_offsets)]
cftype = type(dates_min)
# create first day of gregorian calendar in current cf calendar type
border = cftype(1582, 10, 15)
Expand All @@ -634,7 +669,7 @@ def decode_cf_datetime(
upper = cftype(2262, 4, 11, 23, 47, 16, 854775)

if dates_min < border:
if _is_standard_calendar(calendar):
if standard_calendar:
emit_user_level_warning(
"Unable to decode time axis into full "
"numpy.datetime64 objects, continuing using "
Expand All @@ -652,8 +687,13 @@ def decode_cf_datetime(
"'time_unit' or specify 'use_cftime=True'.",
SerializationWarning,
)
elif _is_standard_calendar(calendar):
dates = cftime_to_nptime(dates, time_unit=time_unit)
elif standard_calendar:
converted = cftime_to_nptime(range_dates, time_unit=time_unit)
if valid is None:
dates = converted
else:
dates = np.full(dates.shape, np.datetime64("NaT", time_unit))
dates[valid] = converted
elif use_cftime:
dates = _decode_datetime_with_cftime(flat_num_dates, units, calendar)
else:
Expand Down Expand Up @@ -1551,11 +1591,16 @@ def decode(self, variable: Variable, name: T_Name = None) -> Variable:
dtype = _decode_cf_datetime_dtype_from_metadata(
units, calendar, self.use_cftime, self.time_unit
)
chunked_decode = None
if dtype is None:
dtype = _decode_cf_datetime_dtype(
data, units, calendar, self.use_cftime, self.time_unit
)
decode = decode_cf_datetime
if self.use_cftime is None and (
calendar is None or _is_standard_calendar(calendar)
):
chunked_decode = partial(_decode_cf_datetime_chunk, dtype=dtype)
else:
# nothing was read, so check every decoded chunk against the
# inferred dtype instead of letting it be cast silently
Expand All @@ -1567,7 +1612,14 @@ def decode(self, variable: Variable, name: T_Name = None) -> Variable:
use_cftime=self.use_cftime,
time_unit=self.time_unit,
)
data = lazy_elemwise_func(data, transform, dtype)
chunked_transform = (
partial(chunked_decode, **transform.keywords)
if chunked_decode is not None
else None
)
data = lazy_elemwise_func(
data, transform, dtype, chunked_func=chunked_transform
)

return Variable(dims, data, attrs, encoding, fastpath=True)
else:
Expand Down
24 changes: 24 additions & 0 deletions xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,10 @@ def __array__(
def get_duck_array(self):
return self.array

def _prepare_for_chunking(self) -> Self:
"""Return a source suitable for reading as independent chunks."""
return self


class ExplicitlyIndexedNDArrayMixin(NDArrayMixin, ExplicitlyIndexed):
__slots__ = ()
Expand Down Expand Up @@ -749,6 +753,11 @@ def __init__(self, array: Any, key: ExplicitIndexer | None = None):
shape += (k.size,)
self._shape = shape

@override
def _prepare_for_chunking(self) -> Self:
array = self.array._prepare_for_chunking()
return self if array is self.array else type(self)(array, self.key)

def _updated_key(self, new_key: ExplicitIndexer) -> BasicIndexer | OuterIndexer:
iter_new_key = iter(expanded_indexer(new_key.tuple, self.ndim))

Expand Down Expand Up @@ -856,6 +865,11 @@ def __init__(self, array: duckarray[Any, Any], key: ExplicitIndexer):
self.key = _arrayize_vectorized_indexer(key, array.shape)
self.array = as_indexable(array)

@override
def _prepare_for_chunking(self) -> Self:
array = self.array._prepare_for_chunking()
return self if array is self.array else type(self)(array, self.key)

@override
@property
def shape(self) -> Shape:
Expand Down Expand Up @@ -943,6 +957,11 @@ def __init__(self, array: duckarray[Any, Any]):
self.array = as_indexable(array)
self._copied = False

@override
def _prepare_for_chunking(self) -> Self:
array = self.array._prepare_for_chunking()
return self if array is self.array else type(self)(array)

def _ensure_copied(self):
if not self._copied:
self.array = as_indexable(np.array(self.array))
Expand Down Expand Up @@ -1001,6 +1020,11 @@ class MemoryCachedArray(ExplicitlyIndexedNDArrayMixin):
def __init__(self, array):
self.array = _wrap_numpy_scalars(as_indexable(array))

@override
def _prepare_for_chunking(self) -> Self:
array = self.array._prepare_for_chunking()
return self if array is self.array else type(self)(array)

@override
def get_duck_array(self):
duck_array = self.array.get_duck_array()
Expand Down
4 changes: 3 additions & 1 deletion xarray/namedarray/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,7 +959,9 @@ def chunk(
# Using OuterIndexer is a pragmatic choice: dask does not yet handle
# different indexing types in an explicit way:
# https://github.com/dask/dask/issues/2883
ndata = ImplicitToExplicitIndexingAdapter(data_old, OuterIndexer) # type: ignore[assignment]
ndata = ImplicitToExplicitIndexingAdapter( # type: ignore[assignment]
data_old._prepare_for_chunking(), OuterIndexer
)

if is_dict_like(chunks):
chunks = tuple(starmap(chunks.get, enumerate(ndata.shape)))
Expand Down
Loading
Loading