Skip to content
Draft
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
8 changes: 8 additions & 0 deletions src/datasource/zarr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ Dimension names may be specified using an `_ARRAY_DIMENSIONS` attribute,

## Zarr v3

Supported chunk grids:

- regular
- regular_bounded (a regular grid with an `origin` and a `lower_bound`, under which chunk keys
may be negative and the first chunk may be partly filled). A bare array is displayed in its own
coordinates, starting at `lower_bound`. Inside an OME-Zarr multiscale group each level's
`translation` refers to its first element, as OME-NGFF defines the array index space.

Supported codecs:

- crc32c (not validated)
Expand Down
31 changes: 22 additions & 9 deletions src/datasource/zarr/frontend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,18 +119,25 @@ export class MultiscaleVolumeChunkSource extends GenericMultiscaleVolumeChunkSou
return transposeNestedArrays(
this.multiscale.scales.map((scale) => {
const { metadata } = scale;
const { rank, codecs, shape } = metadata;
const { rank, codecs, shape, chunkGridOrigin, lowerBound } = metadata;
const readChunkShape = codecs.layoutInfo[0].readChunkShape;
const { physicalToLogicalDimension } = metadata.codecs.layoutInfo[0];
const permutedChunkShape = new Uint32Array(rank);
const permutedDataShape = new Float32Array(rank);
const permutedLowerBound = new Float32Array(rank);
const permutedUpperBound = new Float32Array(rank);
const orderTransform = new Float32Array((rank + 1) ** 2);
orderTransform[(rank + 1) ** 2 - 1] = 1;
// Chunk coordinates are relative to the chunk grid origin; the index
// space the scale transform maps starts at the first element.
for (let i = 0; i < rank; ++i) {
const decodedDim = physicalToLogicalDimension[rank - 1 - i];
permutedChunkShape[i] = readChunkShape[decodedDim];
permutedDataShape[i] = shape[decodedDim];
permutedLowerBound[i] =
lowerBound[decodedDim] - chunkGridOrigin[decodedDim];
permutedUpperBound[i] = permutedLowerBound[i] + shape[decodedDim];
orderTransform[decodedDim + i * (rank + 1)] = 1;
orderTransform[(rank + 1) * rank + i] =
chunkGridOrigin[i] - lowerBound[i];
}
const transform = new Float32Array((rank + 1) ** 2);
matrix.multiply<Float32Array | Float64Array>(
Expand All @@ -148,7 +155,8 @@ export class MultiscaleVolumeChunkSource extends GenericMultiscaleVolumeChunkSou
rank,
chunkToMultiscaleTransform: transform,
dataType: metadata.dataType,
upperVoxelBound: permutedDataShape,
lowerVoxelBound: permutedLowerBound,
upperVoxelBound: permutedUpperBound,
volumeType: this.volumeType,
chunkDataSizes: [permutedChunkShape],
volumeSourceOptions,
Expand Down Expand Up @@ -275,23 +283,28 @@ function getMultiscaleInfoForSingleArray(
units: Array.from(unitsAndScales, (x) => x.unit),
boundingBoxes: [
makeIdentityTransformedBoundingBox({
lowerBounds: new Float64Array(metadata.rank),
upperBounds: Float64Array.from(metadata.shape),
lowerBounds: Float64Array.from(metadata.lowerBound),
upperBounds: Float64Array.from(
metadata.shape,
(n, i) => metadata.lowerBound[i] + n,
),
}),
],
});
const transform = matrix.createIdentity(Float64Array, metadata.rank + 1);
return {
coordinateSpace: modelSpace,
dataType: metadata.dataType,
scales: [
{
url,
transform,
transform: matrix.createHomogeneousTranslationMatrix(
Float64Array,
metadata.lowerBound,
),
metadata,
},
],
baseTransform: transform,
baseTransform: matrix.createIdentity(Float64Array, metadata.rank + 1),
};
}

Expand Down
4 changes: 4 additions & 0 deletions src/datasource/zarr/metadata/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export interface ArrayMetadata {
userAttributes: Record<string, unknown>;
dimensionSeparator: DimensionSeparator;
chunkKeyEncoding: ChunkKeyEncoding;
// Array coordinate where chunk 0 starts, and coordinate of the first
// element; all zero except under the `regular_bounded` chunk grid.
chunkGridOrigin: number[];
lowerBound: number[];
codecs: CodecChainSpec;
}

Expand Down
62 changes: 51 additions & 11 deletions src/datasource/zarr/metadata/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ export function parseChunkShape(obj: unknown, rank: number): number[] {
});
}

enum ChunkGrid {
REGULAR = 0,
REGULAR_BOUNDED = 1,
}

function verifyInteger(value: unknown): number {
if (!Number.isInteger(value)) {
throw new Error(
`Expected integer, but received: ${JSON.stringify(value)}.`,
);
}
return value as number;
}

export function parseDimensionSeparator(value: unknown): "/" | "." {
if (value !== "." && value !== "/") {
throw new Error(
Expand Down Expand Up @@ -225,18 +239,40 @@ export function parseV3Metadata(
verifyEnumString(x, DataType, /^[a-z0-9]+$/),
);

const { configuration: chunkShape } = verifyObjectProperty(
obj,
"chunk_grid",
(chunkGrid) =>
parseNameAndConfiguration(
chunkGrid,
(name) => verifyConstant(name, "regular"),
(configuration) =>
verifyObjectProperty(configuration, "chunk_shape", (chunks) =>
parseChunkShape(chunks, rank),
const {
configuration: { chunkShape, chunkGridOrigin, lowerBound },
} = verifyObjectProperty(obj, "chunk_grid", (chunkGrid) =>
parseNameAndConfiguration(
chunkGrid,
(name) =>
verifyEnumString(name, ChunkGrid, /^(regular|regular_bounded)$/),
(configuration, name) => {
const chunkShape = verifyObjectProperty(
configuration,
"chunk_shape",
(chunks) => parseChunkShape(chunks, rank),
);
if (name === ChunkGrid.REGULAR) {
const zeros = new Array<number>(rank).fill(0);
return { chunkShape, chunkGridOrigin: zeros, lowerBound: zeros };
}
const parseCoordinates = (x: unknown) =>
parseFixedLengthArray(new Array<number>(rank), x, verifyInteger);
return {
chunkShape,
chunkGridOrigin: verifyObjectProperty(
configuration,
"origin",
parseCoordinates,
),
),
lowerBound: verifyObjectProperty(
configuration,
"lower_bound",
parseCoordinates,
),
};
},
),
);

const { userAttributes, dimensionUnits } = verifyObjectProperty(
Expand Down Expand Up @@ -291,6 +327,8 @@ export function parseV3Metadata(
dimensionUnits,
chunkKeyEncoding,
dimensionSeparator,
chunkGridOrigin,
lowerBound,
userAttributes,
codecs,
};
Expand Down Expand Up @@ -436,6 +474,8 @@ export function parseV2Metadata(
userAttributes: attrs,
dimensionSeparator,
chunkKeyEncoding: ChunkKeyEncoding.V2,
chunkGridOrigin: new Array<number>(rank).fill(0),
lowerBound: new Array<number>(rank).fill(0),
codecs: codecChainSpec,
};
} catch (e) {
Expand Down
86 changes: 86 additions & 0 deletions src/datasource/zarr/metadata/regular_bounded.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* @license
* Copyright 2026 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { describe, expect, it } from "vitest";
import "#src/datasource/zarr/codec/bytes/resolve.js";
import type { ArrayMetadata } from "#src/datasource/zarr/metadata/index.js";
import { parseV3Metadata } from "#src/datasource/zarr/metadata/parse.js";

function parseArray(chunkGrid: unknown): ArrayMetadata {
const metadata = parseV3Metadata(
{
zarr_format: 3,
node_type: "array",
shape: [6, 7],
data_type: "uint16",
chunk_grid: chunkGrid,
chunk_key_encoding: { name: "default" },
fill_value: 0,
codecs: [{ name: "bytes", configuration: { endian: "little" } }],
},
"array",
);
if (metadata.nodeType !== "array") throw new Error("expected an array");
return metadata;
}

describe("regular_bounded chunk grid", () => {
it("parses the origin and lower bound", () => {
const metadata = parseArray({
name: "regular_bounded",
configuration: {
chunk_shape: [4, 5],
origin: [1, 0],
lower_bound: [-3, -2],
},
});
expect(metadata.chunkShape).toEqual([4, 5]);
expect(metadata.chunkGridOrigin).toEqual([1, 0]);
expect(metadata.lowerBound).toEqual([-3, -2]);
});

it("leaves a regular grid at zero", () => {
const metadata = parseArray({
name: "regular",
configuration: { chunk_shape: [4, 5] },
});
expect(metadata.chunkGridOrigin).toEqual([0, 0]);
expect(metadata.lowerBound).toEqual([0, 0]);
});

it("requires one integer per dimension for both fields", () => {
const grid = (configuration: object) => ({
name: "regular_bounded",
configuration: { chunk_shape: [4, 5], ...configuration },
});
expect(() => parseArray(grid({ origin: [0, 0] }))).toThrow(/lower_bound/);
expect(() =>
parseArray(grid({ origin: [0], lower_bound: [0, 0] })),
).toThrow(/length 2/);
expect(() =>
parseArray(grid({ origin: [0, 0], lower_bound: [0, 0.5] })),
).toThrow(/integer/);
});

it("refuses an unknown chunk grid", () => {
expect(() =>
parseArray({
name: "regular_offset",
configuration: { chunk_shape: [4, 5] },
}),
).toThrow(/Invalid enum/);
});
});
84 changes: 84 additions & 0 deletions testdata/datasource/zarr/ome_zarr/generate_regular_bounded_0.5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Writes `regular_bounded_0.5`: the `simple_0.5` image grown in front by 3 rows and 2 columns.

Requires a zarr-python with `Array.prepend` (zarr-developers/zarr-python#4516). Both levels are
grown with `prepend`, and each level's `translation` moves to its new first element, as OME-NGFF
defines the array index space, so the original elements keep their physical positions.
"""

import json
import pathlib
import shutil

import numpy as np
import zarr

root = pathlib.Path(__file__).parent / "regular_bounded_0.5"
shutil.rmtree(root, ignore_errors=True)
root.mkdir()


def level(path, data):
a = zarr.create_array(
store=str(root / path),
shape=data.shape,
chunks=(5, 5),
dtype="uint16",
fill_value=0,
compressors=None,
dimension_names=["y", "x"],
)
a[:] = data
return a


# Level 0: 10 x 10 at 4 x 30 nm, then rows [-3, 0) and columns [-2, 0) in front.
s0 = level("scale0/image", np.arange(100, dtype="uint16").reshape(10, 10))
s0.prepend(np.arange(30, dtype="uint16").reshape(3, 10) + 1000, axis=0)
s0.prepend(np.arange(26, dtype="uint16").reshape(13, 2) + 2000, axis=1)

# Level 1: 2 x 2 bins on even level-0 coordinates: rows [-4, 10), columns [-2, 10).
grown = np.zeros((14, 12), dtype="float64")
grown[1:] = s0[:]
binned = grown.reshape(7, 2, 6, 2).mean(axis=(1, 3)).astype("uint16")
s1 = level("scale1/image", binned[2:, 1:])
s1.prepend(binned[:2, 1:], axis=0)
s1.prepend(binned[:, :1], axis=1)

# Translations are voxel centres of each level's first element:
# level 0 row -3 -> 4 * -3 = -12 nm, column -2 -> 30 * -2 = -60 nm;
# level 1 rows {-4, -3} -> -14 nm, columns {-2, -1} -> -45 nm.
ome = {
"version": "0.5",
"multiscales": [
{
"name": "image",
"axes": [
{"name": "y", "type": "space", "unit": "nanometer"},
{"name": "x", "type": "space", "unit": "nanometer"},
],
"datasets": [
{
"path": "scale0/image",
"coordinateTransformations": [
{"type": "scale", "scale": [4, 30]},
{"type": "translation", "translation": [-12, -60]},
],
},
{
"path": "scale1/image",
"coordinateTransformations": [
{"type": "scale", "scale": [8, 60]},
{"type": "translation", "translation": [-14, -45]},
],
},
],
}
],
}
for group in (root, root / "scale0", root / "scale1"):
attrs = {"ome": ome} if group == root else {}
(group / "zarr.json").write_text(
json.dumps(
{"zarr_format": 3, "node_type": "group", "attributes": attrs}, indent=2
)
)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading
Loading