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
71 changes: 43 additions & 28 deletions kerchunk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,17 @@ def inline_array(store, threshold=1000, names=None, remote_options=None):

def subchunk(store, variable, factor):
"""
Split uncompressed chunks into integer subchunks on the largest axis
Split uncompressed chunks into integer subchunks along the leading axes

Each input chunk becomes exactly ``factor`` output chunks, each of which is a
contiguous byte range of the original. The split is therefore applied along
the leading (slowest-varying) axes only, skipping any axis whose chunk length
is 1. If ``factor`` divides the first such axis, only that axis is split. If
``factor`` is instead a multiple of it, that axis is split into chunks of
length 1 and the remaining factor is applied to the next axis in the same way,
for example chunks ``(2, 12)`` with ``factor=4`` become ``(1, 6)``. Any other
factor raises ``ValueError``; in particular an axis that is not divisible by
the remaining factor can never be split, even if a later axis is.

Parameters
----------
Expand All @@ -369,8 +379,8 @@ def subchunk(store, variable, factor):
variable: str
the named zarr variable (give as /-separated path if deep)
factor: int
the number of chunks each input chunk turns into. Must be an exact divisor
of the original largest dimension length.
the number of chunks each input chunk turns into; see above for which
values are possible

Returns
-------
Expand All @@ -382,29 +392,32 @@ def subchunk(store, variable, factor):
meta = ujson.loads(fs.cat(meta_file))
if meta["compressor"] is not None:
raise ValueError("Can only subchunk an uncompressed array")
if factor < 1:
raise ValueError("Subchunk factor must be a positive integer")
chunks_orig = meta["chunks"]
chunk_new = []
# plan
multi = None
chunk_new = list(chunks_orig)
# plan: consume leading axes until the whole factor is accounted for
remaining = factor
for ind, this_chunk in enumerate(chunks_orig):
if this_chunk == 1:
chunk_new.append(1)
continue
elif this_chunk % factor == 0:
chunk_new.extend([this_chunk // factor] + chunks_orig[ind + 1 :])
if remaining == 1:
break
elif factor % this_chunk == 0:
# if factor // chunks_orig[0] > 1:
chunk_new.append(1)
if multi is None:
multi = this_chunk
factor //= this_chunk
elif this_chunk % remaining == 0:
chunk_new[ind] = this_chunk // remaining
remaining = 1
elif remaining % this_chunk == 0:
chunk_new[ind] = 1
remaining //= this_chunk
else:
raise ValueError("Must subchunk by exact integer factor")

if multi:
# TODO: this reloads the referenceFS; *maybe* reuses it
return subchunk(store, variable, multi)
break
if remaining != 1:
raise ValueError(
f"Cannot split chunks {chunks_orig} into {factor} contiguous "
"sub-chunks: the factor must divide the leading non-unit chunk "
"axis, or be the product of whole leading axes and a divisor "
"of the axis that follows them"
)
# number of sub-chunks along each axis; their product is factor
splits = [orig // new for orig, new in zip(chunks_orig, chunk_new)]

# execute
meta["chunks"] = chunk_new
Expand All @@ -427,12 +440,14 @@ def subchunk(store, variable, factor):
(url,) = v
offset = 0
size = fs.info(k)["size"]
for subpart in range(factor):
new_index = (
chunk_index[:ind]
+ [chunk_index[ind] * factor + subpart]
+ chunk_index[ind + 1 :]
)
# sub-chunks are enumerated in C order, which is also their byte order
# within the original chunk, because every axis before the last one
# that is split has a new chunk length of 1
subparts = itertools.product(*(range(s) for s in splits))
for subpart, sub_index in enumerate(subparts):
new_index = [
i * s + sub for i, s, sub in zip(chunk_index, splits, sub_index)
]
newpart = sep.join(str(_) for _ in new_index)
newv = [url, offset + subpart * size // factor, size // factor]
store[f"{variable}/{newpart}"] = newv
Expand Down
83 changes: 73 additions & 10 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,24 +97,51 @@ def test_json():
assert out == expected


@pytest.mark.parametrize("chunks", [[10, 10], [5, 10]])
def test_subchunk_exact(m, chunks):
def _subchunk_refs(shape, chunks):
g = zarr.open_group("memory://test.zarr", mode="w", zarr_format=2)
data = np.arange(100).reshape(10, 10)
data = np.arange(np.prod(shape)).reshape(shape)
arr = g.create_array(
"data", dtype=data.dtype, shape=data.shape, chunks=chunks, compressor=None
)
arr[:] = data
ref = kerchunk.zarr.single_zarr("memory://test.zarr")["refs"]
return ref, data

extra = [] if chunks[0] == 10 else ["data/1.0"]
ref2 = list(_ for _ in ref if not _.endswith("zattrs")) # ignore empty attrs
assert ref2 == [".zgroup", "data/.zarray", "data/0.0"] + extra

out = kerchunk.utils.subchunk(ref, "data", 5)
nchunk = 10 // chunks[0] * 5
out2 = list(_ for _ in out if not _.endswith("zattrs"))
assert out2 == [".zgroup", "data/.zarray"] + [f"data/{_}.0" for _ in range(nchunk)]
def _chunk_keys(ref):
return sorted(
k for k in ref if k.startswith("data/") and not k.startswith("data/.z")
)


@pytest.mark.parametrize(
"chunks, factor, expected",
[
([10, 10], 5, [2, 10]),
([5, 10], 5, [1, 10]),
# factor larger than the leading axis: it is split into ones and the
# rest of the factor applies to the next axis
([2, 10], 4, [1, 5]),
([10, 10], 20, [1, 5]),
([5, 10], 25, [1, 2]),
([10, 10], 100, [1, 1]),
],
)
def test_subchunk_exact(m, chunks, factor, expected):
ref, data = _subchunk_refs((10, 10), chunks)

ref2 = list(_ for _ in ref if not _.endswith("zattrs")) # ignore empty attrs
assert ref2 == [".zgroup", "data/.zarray"] + [
f"data/{_}.0" for _ in range(10 // chunks[0])
]

out = kerchunk.utils.subchunk(ref, "data", factor)
assert json.loads(out["data/.zarray"])["chunks"] == expected
nchunk = [10 // _ for _ in expected]
assert _chunk_keys(out) == sorted(
f"data/{i}.{j}" for i in range(nchunk[0]) for j in range(nchunk[1])
)
assert len(_chunk_keys(out)) == factor * len(_chunk_keys(ref))

store = kerchunk.utils.refs_as_store(out, remote_protocol="memory")
g2 = zarr.open_group(store, mode="r", zarr_format=2)
Expand All @@ -125,6 +152,42 @@ def test_subchunk_exact(m, chunks):
assert (g2["data"][:] == data).all()


@pytest.mark.parametrize(
"factor, expected",
[(2, [1, 3, 8]), (6, [1, 1, 8]), (12, [1, 1, 4]), (48, [1, 1, 1])],
)
def test_subchunk_multiple_axes(m, factor, expected):
ref, data = _subchunk_refs((4, 3, 8), [2, 3, 8])
assert len(_chunk_keys(ref)) == 2

out = kerchunk.utils.subchunk(ref, "data", factor)
assert json.loads(out["data/.zarray"])["chunks"] == expected
assert len(_chunk_keys(out)) == 2 * factor

store = kerchunk.utils.refs_as_store(out, remote_protocol="memory")
g2 = zarr.open_group(store, mode="r", zarr_format=2)
assert (g2["data"][:] == data).all()


@pytest.mark.parametrize(
"chunks, factor",
[
# 2 does not divide the leading axis, even though it divides the next
([5, 10], 2),
# 4 = 2 * 2, but 2 neither divides nor is a multiple of the next axis
([2, 3, 8], 4),
# more sub-chunks than there are elements in a chunk
([2, 10], 40),
([1, 1], 2),
([10, 10], 0),
],
)
def test_subchunk_impossible(m, chunks, factor):
ref, _ = _subchunk_refs((10, 10) if len(chunks) == 2 else (4, 3, 8), chunks)
with pytest.raises(ValueError):
kerchunk.utils.subchunk(ref, "data", factor)


@pytest.mark.parametrize("archive", ["zip", "tar"])
def test_archive(m, archive):
import zipfile
Expand Down