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
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
33 changes: 17 additions & 16 deletions 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 Expand Up @@ -740,7 +741,16 @@ def _check_shards_or_chunks(
zarr_chunks: Mapping[str, int],
chunks_name: Literal['shards', 'chunks'],
) -> None:
"""Verify dataset chunks divide evenly into Zarr chunks or shards."""
for k in self.chunks:
if zarr_chunks[k] == 0:
if self.chunks[k] != 0:
raise ValueError(
f'cannot write a dataset with chunks {self.chunks} to Zarr with '
f'{chunks_name} {zarr_chunks}, which do not divide evenly into '
f'{chunks_name}'
)
continue
if (
self.chunks[k] % zarr_chunks[k]
and self.chunks[k] != self.template.sizes[k]
Expand Down Expand Up @@ -839,28 +849,19 @@ def to_zarr(
previous_chunks=self.chunks,
)
if zarr_shards is not None:
# Zarr shards are currently constrained to be an integer multiple of
# chunk sizes, which means shard sizes must be rounded up to be larger
# than the full dimension size. This will likely be relaxed in the future:
# https://github.com/zarr-developers/zarr-extensions/issues/34
zarr_shards = dict(zarr_shards) # pyrefly: ignore[no-matching-overload]
for k in zarr_shards:
if zarr_shards[k] == self.sizes[k]:
zarr_shards[k] = (
math.ceil(zarr_shards[k] / zarr_chunks[k]) * zarr_chunks[k] # pyrefly: ignore[bad-index, unsupported-operation]
)
self._check_shards_or_chunks(zarr_shards, 'shards')
final_zarr_shards = zarr._round_up_full_dim_shards( # pylint: disable=protected-access
self.sizes, zarr_chunks, zarr_shards # pyrefly: ignore[bad-argument-type]
)
self._check_shards_or_chunks(final_zarr_shards, 'shards')
else:
final_zarr_shards = None
self._check_shards_or_chunks(zarr_chunks, 'chunks') # pyrefly: ignore[bad-argument-type]

if zarr_shards is not None and zarr_format is None:
zarr_format = 3 # required for shards

return self.ptransform | label >> zarr.ChunksToZarr(
path,
self.template,
zarr_chunks=zarr_chunks, # pyrefly: ignore[bad-argument-type]
zarr_shards=zarr_shards,
zarr_shards=final_zarr_shards,
zarr_format=zarr_format,
stage_locally=stage_locally,
)
Expand Down
147 changes: 139 additions & 8 deletions xarray_beam/_src/dataset_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,132 @@ 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_sharded_zarr_v3_roundtrip_and_rechunk(self):
"""Roundtrips sharded Zarr v3 and rechunks to unsharded Zarr v2."""
src_dir = self.create_tempdir('src').full_path
dst_sharded_dir = self.create_tempdir('dst_sharded').full_path
dst_unsharded_dir = self.create_tempdir('dst_unsharded').full_path
ds = xarray.Dataset(
{'foo': (('x', 'y'), np.arange(60, dtype=np.float32).reshape(10, 6))},
coords={'x': np.arange(10), 'y': np.arange(6)},
attrs={'meta': 'roundtrip'},
)
with beam.Pipeline() as p:
p |= xbeam.Dataset.from_xarray(ds, {'x': 6, 'y': 6}).to_zarr(
src_dir, zarr_chunks={'x': 2, 'y': 3}, zarr_shards={'x': 6, 'y': 6}
)

with beam.Pipeline() as p:
beam_ds = xbeam.Dataset.from_zarr(src_dir, pipeline=p)
self.assertEqual(beam_ds.chunks, {'x': 6, 'y': 6})
beam_ds.to_zarr(dst_sharded_dir, zarr_chunks_per_shard={'x': 3, 'y': 2})
opened_sharded, shards = xbeam.open_zarr(dst_sharded_dir)
xarray.testing.assert_identical(ds, opened_sharded)
self.assertEqual(shards, {'x': 6, 'y': 6})
self.assertEqual(opened_sharded['foo'].encoding['chunks'], (2, 3))
self.assertEqual(opened_sharded['foo'].encoding['shards'], (6, 6))

with beam.Pipeline() as p:
(
xbeam.Dataset.from_zarr(src_dir, pipeline=p)
.rechunk({'x': 5, 'y': 3})
.to_zarr(dst_unsharded_dir, zarr_format=2)
)
opened_v2, v2_chunks = xbeam.open_zarr(dst_unsharded_dir)
xarray.testing.assert_identical(ds, opened_v2)
self.assertEqual(v2_chunks, {'x': 5, 'y': 3})
self.assertIsNone(opened_v2['foo'].encoding.get('shards'))

def test_dataset_sharded_partial_end_shard_roundtrip(self):
"""Roundtrips a sharded dataset whose trailing shard is not a chunk multiple."""
src_dir = self.create_tempdir('src_lat').full_path
dst_dir = self.create_tempdir('dst_lat').full_path
ds = xarray.Dataset(
{'foo': ('lat', np.arange(721, dtype=np.float32))},
coords={'lat': np.linspace(-90.0, 90.0, 721)},
)
with beam.Pipeline() as p:
p |= xbeam.Dataset.from_xarray(ds, {'lat': 405}).to_zarr(
src_dir, zarr_chunks={'lat': 45}, zarr_shards={'lat': 405}
)
with beam.Pipeline() as p:
beam_ds = xbeam.Dataset.from_zarr(src_dir, pipeline=p)
self.assertEqual(beam_ds.chunks, {'lat': 405})
beam_ds.to_zarr(dst_dir, zarr_chunks_per_shard={'lat': 9})
opened, shards = xbeam.open_zarr(dst_dir)
xarray.testing.assert_identical(ds, opened)
self.assertEqual(shards, {'lat': 405})
self.assertEqual(opened['foo'].encoding['chunks'], (45,))
self.assertEqual(opened['foo'].encoding['shards'], (405,))

def test_to_zarr_sharded_empty_dim(self):
"""Validates shards on zero-length dims and rejects zero shards on non-empty dims."""
ds = xarray.Dataset({'foo': ('x', np.zeros(0, dtype=np.float32))})
beam_ds = xbeam.Dataset.from_xarray(ds, {'x': 0})
beam_ds._check_shards_or_chunks({'x': 0}, 'shards')
with self.assertRaisesRegex(ValueError, 'do not divide evenly into shards'):
xbeam.Dataset.from_xarray(
xarray.Dataset({'foo': ('x', np.zeros(4, dtype=np.float32))}),
{'x': 2},
)._check_shards_or_chunks({'x': 0}, 'shards')

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 +817,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 +830,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 +865,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 +879,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 +899,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 +911,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 +927,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 @@ -1351,7 +1480,9 @@ 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
Expand Down
Loading
Loading