Skip to content

Implement preferred_chunks for netcdf 4 backends #7948

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ New Features
different collections of coordinates prior to assign them to a Dataset or
DataArray (:pull:`8102`) at once.
By `Benoît Bovy <https://github.com/benbovy>`_.
- Provide `preferred_chunks` for data read from netcdf files (:issue:`1440`, :pull:`7948`)

Breaking changes
~~~~~~~~~~~~~~~~
Expand Down
2 changes: 2 additions & 0 deletions xarray/backends/h5netcdf_.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ def open_store_variable(self, name, var):
"fletcher32": var.fletcher32,
"shuffle": var.shuffle,
}
if var.chunks:
encoding["preferred_chunks"] = dict(zip(var.dimensions, var.chunks))
# Convert h5py-style compression options to NetCDF4-Python
# style, if possible
if var.compression == "gzip":
Expand Down
1 change: 1 addition & 0 deletions xarray/backends/netCDF4_.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ def open_store_variable(self, name, var):
else:
encoding["contiguous"] = False
encoding["chunksizes"] = tuple(chunking)
encoding["preferred_chunks"] = dict(zip(var.dimensions, chunking))
# TODO: figure out how to round-trip "endian-ness" without raising
# warnings from netCDF4
# encoding['endian'] = var.endian()
Expand Down
79 changes: 78 additions & 1 deletion xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import tempfile
import uuid
import warnings
from collections.abc import Iterator
from collections.abc import Generator, Iterator
from contextlib import ExitStack
from io import BytesIO
from os import listdir
Expand Down Expand Up @@ -1536,6 +1536,83 @@ def test_keep_chunksizes_if_no_original_shape(self) -> None:
ds["x"].encoding["chunksizes"], actual["x"].encoding["chunksizes"]
)

def test_preferred_chunks_is_present(self) -> None:
ds = Dataset({"x": [1, 2, 3]})
chunksizes = (2,)
ds.variables["x"].encoding = {"chunksizes": chunksizes}

with self.roundtrip(ds) as actual:
assert actual["x"].encoding["preferred_chunks"] == {"x": 2}

@requires_dask
def test_auto_chunking_is_based_on_disk_chunk_sizes(self) -> None:
x_size = y_size = 1000
y_chunksize = y_size
x_chunksize = 10

with dask.config.set({"array.chunk-size": "100KiB"}):
with self.chunked_roundtrip(
(1, y_size, x_size),
(1, y_chunksize, x_chunksize),
open_kwargs={"chunks": "auto"},
) as ds:
t_chunks, y_chunks, x_chunks = ds["image"].data.chunks
assert all(np.asanyarray(y_chunks) == y_chunksize)
# Check that the chunk size is a multiple of the file chunk size
assert all(np.asanyarray(x_chunks) % x_chunksize == 0)

@requires_dask
def test_base_chunking_uses_disk_chunk_sizes(self) -> None:
x_size = y_size = 1000
y_chunksize = y_size
x_chunksize = 10

with self.chunked_roundtrip(
(1, y_size, x_size),
(1, y_chunksize, x_chunksize),
open_kwargs={"chunks": {}},
) as ds:
for chunksizes, expected in zip(
ds["image"].data.chunks, (1, y_chunksize, x_chunksize)
):
assert all(np.asanyarray(chunksizes) == expected)

@contextlib.contextmanager
def chunked_roundtrip(
self,
array_shape: tuple[int, int, int],
chunk_sizes: tuple[int, int, int],
open_kwargs: dict[str, Any] | None = None,
) -> Generator[Dataset, None, None]:
t_size, y_size, x_size = array_shape
t_chunksize, y_chunksize, x_chunksize = chunk_sizes

image = xr.DataArray(
np.arange(t_size * x_size * y_size, dtype=np.int16).reshape(
(t_size, y_size, x_size)
),
dims=["t", "y", "x"],
)
image.encoding = {"chunksizes": (t_chunksize, y_chunksize, x_chunksize)}
dataset = xr.Dataset(dict(image=image))

with self.roundtrip(dataset, open_kwargs=open_kwargs) as ds:
yield ds

def test_preferred_chunks_are_disk_chunk_sizes(self) -> None:
x_size = y_size = 1000
y_chunksize = y_size
x_chunksize = 10

with self.chunked_roundtrip(
(1, y_size, x_size), (1, y_chunksize, x_chunksize)
) as ds:
assert ds["image"].encoding["preferred_chunks"] == {
"t": 1,
"y": y_chunksize,
"x": x_chunksize,
}

def test_encoding_chunksizes_unlimited(self) -> None:
# regression test for GH1225
ds = Dataset({"x": [1, 2, 3], "y": ("x", [2, 3, 4])})
Expand Down