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: 1 addition & 1 deletion examples/era5_climatology_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test(self):
input_path = self.create_tempdir('source').full_path
output_path = self.create_tempdir('destination').full_path

input_ds = test_util.dummy_era5_surface_dataset(times=90 * 24, freq='1H')
input_ds = test_util.dummy_era5_surface_dataset(times=90 * 24, freq='1h')
input_ds.chunk({'time': 31}).to_zarr(input_path)

expected = input_ds.groupby('time.month').apply(
Expand Down
11 changes: 6 additions & 5 deletions xarray_beam/_src/combiners.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import dataclasses
import logging
import math
from typing import Literal
from typing import TypeVar

import apache_beam as beam
import numpy.typing as npt
Expand All @@ -32,6 +32,7 @@


DimLike = str | Sequence[str] | None
_T = TypeVar('_T')


@dataclasses.dataclass
Expand Down Expand Up @@ -350,8 +351,8 @@ def _finalize_no_combiner(
return key, chunk

def _prepare_key(
self, key: core.Key, chunk: xarray.Dataset
) -> tuple[tuple[tuple[int, ...], core.Key], xarray.Dataset]:
self, key: core.Key, chunk: _T
) -> tuple[tuple[tuple[int, ...], core.Key], _T]:
assert self.bins_per_stage # not empty
index = _get_chunk_index(key, self.dims, self.chunks, self.sizes)
# strip the final bin because it isn't needed for the combiner
Expand All @@ -360,8 +361,8 @@ def _prepare_key(
return ((bin_ids, key), chunk)

def _strip_leading_fanout_bin(
self, bin_key: tuple[tuple[int, ...], core.Key], value: xarray.Dataset
) -> tuple[tuple[tuple[int, ...], core.Key], xarray.Dataset]:
self, bin_key: tuple[tuple[int, ...], core.Key], value: _T
) -> tuple[tuple[tuple[int, ...], core.Key], _T]:
bin_ids, key = bin_key
return (bin_ids[1:], key), value

Expand Down
3 changes: 2 additions & 1 deletion xarray_beam/_src/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,8 @@ def from_zarr(
path: Zarr path to read from.
chunks: optional mapping from dimension names to chunk sizes, or any value
that can be passed to :py:func:`xarray_beam.normalize_chunks`. If not
provided, the chunk sizes will be inferred from the Zarr file.
provided, the chunk sizes (or shard sizes, for sharded Zarr v3 stores)
will be inferred from the Zarr file.
split_vars: whether variables are split between separate elements in the
ptransform, or all stored in the same element.
pipeline: Beam pipeline to use for this dataset. If not provided, you will
Expand Down
88 changes: 75 additions & 13 deletions xarray_beam/_src/dataset_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,63 @@ def test_from_zarr_with_chunks(self):
collected = beam_ds.collect_with_direct_runner()
xarray.testing.assert_identical(ds, collected)

@parameterized.parameters(
dict(split_vars=False),
dict(split_vars=True),
)
def test_from_zarr_sharded(self, split_vars):
"""Dataset.from_zarr defaults to shard boundaries and honors overrides."""
temp_dir = self.create_tempdir().full_path
ds = xarray.Dataset(
{
'foo': (('x', 'y'), np.arange(72).reshape(12, 6)),
'bar': (('x', 'y'), -np.arange(72).reshape(12, 6)),
},
coords={'x': np.arange(12), 'y': np.arange(6)},
attrs={'description': 'sharded zarr v3'},
)
ds.to_zarr(
temp_dir,
zarr_format=3,
encoding={
'foo': {'chunks': (2, 3), 'shards': (6, 6)},
'bar': {'chunks': (2, 3), 'shards': (6, 6)},
},
)

beam_ds = xbeam.Dataset.from_zarr(temp_dir, split_vars=split_vars)
self.assertEqual(beam_ds.chunks, {'x': 6, 'y': 6})
actual_chunks = test_util.EagerPipeline() | beam_ds.ptransform
keys = [k for k, _ in actual_chunks]
if split_vars:
expected_keys = [
xbeam.Key({'x': 0, 'y': 0}, {'foo'}),
xbeam.Key({'x': 6, 'y': 0}, {'foo'}),
xbeam.Key({'x': 0, 'y': 0}, {'bar'}),
xbeam.Key({'x': 6, 'y': 0}, {'bar'}),
]
else:
expected_keys = [
xbeam.Key({'x': 0, 'y': 0}),
xbeam.Key({'x': 6, 'y': 0}),
]
self.assertCountEqual(keys, expected_keys)
collected = beam_ds.collect_with_direct_runner()
xarray.testing.assert_identical(ds, collected)

beam_ds_override = xbeam.Dataset.from_zarr(
temp_dir, chunks={'x': 2, 'y': 3}, split_vars=split_vars
)
self.assertEqual(beam_ds_override.chunks, {'x': 2, 'y': 3})
collected_override = beam_ds_override.collect_with_direct_runner()
xarray.testing.assert_identical(ds, collected_override)

target_bytes = 6 * 6 * 8 * (1 if split_vars else 2) * 2
beam_ds_bytes = xbeam.Dataset.from_zarr(
temp_dir, chunks=f'{target_bytes}B', split_vars=split_vars
)
self.assertEqual(beam_ds_bytes.chunks, {'x': 12, 'y': 6})

def test_to_zarr(self):
temp_dir = self.create_tempdir().full_path
ds = xarray.Dataset({'foo': ('x', np.arange(12))})
Expand Down Expand Up @@ -691,7 +748,8 @@ def test_to_zarr_shards(self):
)
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(chunks, {'x': 3})
self.assertEqual(chunks, {'x': 6})
self.assertEqual(opened['foo'].encoding['chunks'], (3,))
self.assertEqual(opened['foo'].encoding['shards'], (6,))

with self.subTest('unnormalized_shards'):
Expand All @@ -703,7 +761,8 @@ def test_to_zarr_shards(self):
)
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(chunks, {'x': 3})
self.assertEqual(chunks, {'x': 6})
self.assertEqual(opened['foo'].encoding['chunks'], (3,))
self.assertEqual(opened['foo'].encoding['shards'], (6,))

with self.subTest('larger_shards'):
Expand Down Expand Up @@ -737,7 +796,8 @@ def test_to_zarr_shards_round_up(self, zarr_shards):
)
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(chunks, {'x': 10})
self.assertEqual(chunks, {'x': 19})
self.assertEqual(opened['foo'].encoding['chunks'], (10,))
self.assertEqual(opened['foo'].encoding['shards'], (20,))

def test_to_zarr_chunks_per_shard(self):
Expand All @@ -750,7 +810,7 @@ def test_to_zarr_chunks_per_shard(self):
p |= beam_ds.to_zarr(temp_dir, zarr_chunks_per_shard={'x': 2})
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(chunks, {'x': 3})
self.assertEqual(chunks, {'x': 6})
self.assertEqual(opened['foo'].encoding['chunks'], (3,))
self.assertEqual(opened['foo'].encoding['shards'], (6,))

Expand All @@ -770,7 +830,7 @@ def test_to_zarr_chunks_per_shard(self):
p |= beam_ds.to_zarr(temp_dir, zarr_chunks_per_shard={...: 2})
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(chunks, {'x': 3})
self.assertEqual(chunks, {'x': 6})
self.assertEqual(opened['foo'].encoding['chunks'], (3,))
self.assertEqual(opened['foo'].encoding['shards'], (6,))

Expand All @@ -782,7 +842,7 @@ def test_to_zarr_chunks_per_shard(self):
p |= beam_ds2.to_zarr(temp_dir, zarr_chunks_per_shard={'x': 3, ...: 1})
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds2, opened)
self.assertEqual(chunks, {'x': 2, 'y': 5})
self.assertEqual(chunks, {'x': 6, 'y': 5})
self.assertEqual(opened['foo'].encoding['chunks'], (2, 5))
self.assertEqual(opened['foo'].encoding['shards'], (6, 5))

Expand All @@ -798,7 +858,7 @@ def test_to_zarr_chunks_per_shard(self):
)
opened, chunks = xbeam.open_zarr(temp_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(chunks, {'x': 3})
self.assertEqual(chunks, {'x': 6})
self.assertEqual(opened['foo'].encoding['chunks'], (3,))
self.assertEqual(opened['foo'].encoding['shards'], (6,))

Expand Down Expand Up @@ -1262,7 +1322,7 @@ class EndToEndTest(test_util.TestCase):

def test_bytes_per_chunk_and_chunk_count(self):
source_ds = test_util.dummy_era5_surface_dataset(
variables=2, latitudes=73, longitudes=144, times=365, freq='24H'
variables=2, latitudes=73, longitudes=144, times=365, freq='24h'
)

xbeam_ds = xbeam.Dataset.from_xarray(
Expand All @@ -1288,7 +1348,7 @@ def test_docstring_example(self):
output_path = self.create_tempdir('output').full_path

source_ds = test_util.dummy_era5_surface_dataset(
variables=2, latitudes=73, longitudes=144, times=365, freq='24H'
variables=2, latitudes=73, longitudes=144, times=365, freq='24h'
)
source_ds.chunk({'time': 90}).to_zarr(input_path)

Expand All @@ -1309,7 +1369,7 @@ def test_climatology(self):
input_path = self.create_tempdir('source').full_path
output_path = self.create_tempdir('output').full_path

source_ds = test_util.dummy_era5_surface_dataset(times=365, freq='24H')
source_ds = test_util.dummy_era5_surface_dataset(times=365, freq='24h')
source_ds.chunk({'time': 90}).to_zarr(input_path)

transform = (
Expand All @@ -1330,7 +1390,7 @@ def test_resample(self):
output_path = self.create_tempdir('output').full_path

source_ds = test_util.dummy_era5_surface_dataset(
latitudes=73, longitudes=144, times=365, freq='24H'
latitudes=73, longitudes=144, times=365, freq='24h'
)
source_ds.chunk({'time': 90}).to_zarr(input_path)

Expand All @@ -1351,15 +1411,17 @@ def test_resample(self):
expected = source_ds.resample(time='10D').mean()
actual, chunks = xbeam.open_zarr(output_path)
xarray.testing.assert_identical(expected, actual)
self.assertEqual(chunks, {'time': 10, 'latitude': 73, 'longitude': 144})
self.assertEqual(chunks, {'time': 20, 'latitude': 73, 'longitude': 144})
self.assertEqual(actual['asn'].encoding['chunks'], (10, 73, 144))
self.assertEqual(actual['asn'].encoding['shards'], (20, 73, 144))

def test_multiple_analysis_ready_outputs(self):
input_path = self.create_tempdir('source').full_path
temporal_path = self.create_tempdir('temporal').full_path
climatology_path = self.create_tempdir('climatology').full_path

source_ds = test_util.dummy_era5_surface_dataset(
latitudes=73, longitudes=144, times=365, freq='24H'
latitudes=73, longitudes=144, times=365, freq='24h'
)
source_ds.chunk({'time': 30}).to_zarr(input_path)

Expand Down
2 changes: 1 addition & 1 deletion xarray_beam/_src/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def dummy_era5_surface_dataset(
latitudes=73,
longitudes=144,
times=365 * 4,
freq='6H',
freq='6h',
):
"""A mock version of the Pangeo ERA5 surface reanalysis dataset."""
# based on: gs://pangeo-era5/reanalysis/spatial-analysis
Expand Down
19 changes: 13 additions & 6 deletions xarray_beam/_src/zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,18 @@
def _infer_chunks(dataset: xarray.Dataset) -> dict[str, int]:
"""Infer chunks for an xarray.Dataset loaded from Zarr."""
# The original Zarr array chunks (as tuples) are stored in the "encoding"
# dictionary on each DataArray object.
# dictionary on each DataArray object. For sharded Zarr v3 arrays, prefer
# shard sizes over inner chunk sizes so keys align with shard boundaries.

chunks_sets = collections.defaultdict(set)
for name, variable in dataset.items():
# exclude variables that are indexed, which are loaded into memory already
if name not in dataset.indexes:
for dim, size in zip(variable.dims, variable.encoding['chunks']):
shards = variable.encoding.get('shards')
sizes = shards if shards is not None else variable.encoding['chunks']
for dim, size in zip(variable.dims, sizes):
if dataset.sizes[dim] > 0:
size = min(size, dataset.sizes[dim])
chunks_sets[dim].add(size)

chunks = {}
Expand All @@ -74,9 +79,10 @@ def open_zarr(
) -> tuple[xarray.Dataset, dict[str, int]]:
"""Returns a lazily indexable xarray.Dataset and chunks from a Zarr store.

Only Zarr stores with the consistent chunking between non-indexed variables
(i.e., those for which the ``Dataset.chunks`` property is valid) can be
opened.
Only Zarr stores with consistent chunking (or sharding, for sharded Zarr v3
stores) between non-indexed variables can be opened. For sharded Zarr v3
stores, the returned chunk sizes correspond to the outer shard sizes rather
than inner chunk sizes.

Args:
store: Xarray compatible Zarr store to open.
Expand All @@ -85,7 +91,8 @@ def open_zarr(

Returns:
(dataset, chunks) pair, consisting of a Dataset with the contents of the
Zarr store and a dict mapping from dimensions to integer chunk sizes.
Zarr store and a dict mapping from dimensions to integer chunk (or shard)
sizes.
"""
if 'chunks' in kwargs:
raise TypeError(
Expand Down
Loading
Loading