Skip to content

Commit 086ef74

Browse files
Add fallback to {} chunking strategy if dataset contains non-cftime object variables
1 parent da1f52e commit 086ef74

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

‎intake_esm/source.py‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,11 @@ def _open_dataset(
104104
# How should we handle concat_dim, and other xr.open_mfdataset kwargs?
105105
xarray_open_kwargs.update(preprocess=preprocess)
106106
xarray_open_kwargs.update(parallel=True)
107-
ds = xr.open_mfdataset(url, **xarray_open_kwargs)
107+
# ds = xr.open_mfdataset(url, **xarray_open_kwargs)
108+
ds = _open_dataset_try_auto(url, xr.open_mfdataset, xarray_open_kwargs)
108109
else:
109-
ds = xr.open_dataset(url, **xarray_open_kwargs)
110+
# ds = xr.open_dataset(url, **xarray_open_kwargs)
111+
ds = _open_dataset_try_auto(url, xr.open_dataset, xarray_open_kwargs)
110112
if preprocess is not None:
111113
ds = preprocess(ds)
112114

@@ -137,6 +139,30 @@ def _open_dataset(
137139
return ds
138140

139141

142+
def _open_dataset_try_auto(url, func: typing.Callable, xarray_open_kwargs) -> xr.Dataset:
143+
"""
144+
Try to open a dataset with chunks set to auto. If we fail because dask doesn't know how to chunk
145+
it, set chunks to `{}` and retry. Handles cases where datasets contain things like string variables,
146+
which can't be autochunked, as that's restricted to cftime arrays only.
147+
148+
Attempting to autochunk, rather than always using disk chunks (`{}`) is advantageous as it is generally
149+
quite a lot more performant. Unfortunately, there is no straightforward way to detect which variables
150+
within a dataset can and can't be autochunked without opening it.
151+
"""
152+
try:
153+
ds = func(url, **xarray_open_kwargs)
154+
except NotImplementedError as exc:
155+
if (
156+
'Can not use auto rechunking with object dtype. We are unable to estimate the size in bytes of object data'
157+
in str(exc)
158+
):
159+
xarray_open_kwargs['chunks'] = {}
160+
ds = func(url, **xarray_open_kwargs)
161+
else:
162+
raise exc
163+
return ds
164+
165+
140166
def _update_attrs(*, additional_attrs, ds):
141167
additional_attrs = additional_attrs or {}
142168
if additional_attrs:

‎tests/test_source.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def test_open_dataset_kerchunk(kerchunk_file=kerchunk_file):
9595
# chunking
9696
xarray_open_kwargs = _get_xarray_open_kwargs(
9797
'reference',
98-
dict(engine='zarr', consolidated=False, drop_variables='crs'),
98+
dict(engine='zarr', consolidated=False),
9999
storage_options={
100100
'remote_protocol': 's3',
101101
'remote_options': {'anon': True, 'asynchronous': _zarr_async()},

0 commit comments

Comments
 (0)