Skip to content

yaozarrs.write.v06#

Functions to write OME-Zarr v0.6 stores from yaozarrs.v06 models. See Writing OME-Zarr for how to use them.

Notes for v0.6#

  • dimension_names are still written. v0.5 required each array's zarr.json to include dimension_names matching the axes. v0.6 no longer requires it, but yaozarrs still writes them, using the axis names of the multiscale's "intrinsic" coordinate system.
  • No transformation is added between an image and its labels. Without one, a label image is usually understood to share the image's intrinsic coordinate system. If it doesn't (e.g. your labels were written for a crop of the image, with the crop's corner as their origin), add a transformation to the image's Multiscale.coordinateTransformations (see Lining labels up with the image).
  • write_scene writes the Scene as given, after checking it against the images. Transformation parameters stored in Zarr arrays (at a path) aren't written for you.

yaozarrs.write.v06 #

Writing utilities for OME-Zarr v0.6 format.

LabelsBuilder #

LabelsBuilder(
    dest: str | PathLike,
    *,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
)

Builder for labels groups within an Image.

The labels group structure includes: - A labels group with LabelsGroup metadata listing all label names - Each label as a separate LabelImage subgroup (e.g., cells/, nuclei/)

This builder supports two workflows:

  1. Immediate write (simpler): Use write_label() to write each label with its data immediately. The builder auto-generates and updates LabelsGroup metadata after each call.

  2. Prepare-only (flexible): Use add_label() to register all labels, then prepare() to create the hierarchy with empty arrays. Write data to the returned array handles yourself.

See Also
  • write_image : High-level function with labels parameter for writing everything at once.

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the labels Zarr group (typically image_path/labels).

required
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. Default is "auto".

'auto'
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. Default is "auto".

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
overwrite bool

If True, overwrite existing groups. Default is False. Note: existing directories that don't look like zarr groups will NOT be removed, an exception will be raised instead.

False
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'

Examples:

Immediate write workflow:

>>> import numpy as np
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import LabelsBuilder
>>> def make_label_image():
...     return v06.LabelImage(
...         multiscales=[
...             v06.Multiscale.from_dims([DimSpec(name="y"), DimSpec(name="x")])
...         ],
...         image_label=v06.ImageLabel(),
...     )
>>> builder = LabelsBuilder("my_image.zarr/labels")
>>> builder.write_label(
...     "cells", make_label_image(), np.zeros((64, 64), dtype=np.uint32)
... )
<LabelsBuilder: 1 labels>
>>> builder.write_label(
...     "nuclei", make_label_image(), np.zeros((64, 64), dtype=np.uint32)
... )
<LabelsBuilder: 2 labels>

Prepare-only workflow:

>>> builder2 = LabelsBuilder("my_image2.zarr/labels")
>>> builder2.add_label(
...     "cells",
...     make_label_image(),
...     ((64, 64), np.uint32),  # shape, dtype spec
... )
<LabelsBuilder: 1 labels>
>>> path, arrays = builder2.prepare()
>>> arrays["cells/0"][:] = np.random.randint(0, 10, (64, 64), dtype=np.uint32)
Source code in src/yaozarrs/write/v06/_write.py
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
def __init__(
    self,
    dest: str | PathLike,
    *,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
) -> None:
    super().__init__(
        Path(dest),
        writer=writer,
        chunks=chunks,
        shards=shards,
        overwrite=overwrite,
        compression=compression,
    )

root_path property #

root_path: Path

Path to the labels group.

write_label #

write_label(
    name: str,
    label_image: LabelImage,
    datasets: ArrayOrPyramid,
    *,
    progress: bool = False,
) -> Self

Write a label immediately with its data.

This method creates the label structure and writes data in one call. The labels group structure and LabelsGroup metadata are created/updated automatically. Use this for the "immediate write" workflow.

Parameters:

Name Type Description Default
name str

Label name (becomes the subgroup path, e.g., "cells", "nuclei").

required
label_image LabelImage

OME-Zarr LabelImage metadata model for this label.

required
datasets ArrayOrPyramid

Data array(s) for each resolution level. For a single dataset, pass the array directly without wrapping in a list.

required
progress bool

Show progress bar for dask arrays. Default is False.

False

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If a label with this name was already written or added.

NotImplementedError

If the LabelImage has multiple multiscales.

Source code in src/yaozarrs/write/_common/_builders.py
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
def write_label(
    self,
    name: str,
    label_image: LabelImage,
    datasets: ArrayOrPyramid,
    *,
    progress: bool = False,
) -> Self:
    """Write a label immediately with its data.

    This method creates the label structure and writes data in one call.
    The labels group structure and LabelsGroup metadata are created/updated
    automatically. Use this for the "immediate write" workflow.

    Parameters
    ----------
    name : str
        Label name (becomes the subgroup path, e.g., "cells", "nuclei").
    label_image : LabelImage
        OME-Zarr LabelImage metadata model for this label.
    datasets : ArrayOrPyramid
        Data array(s) for each resolution level. For a single dataset,
        pass the array directly without wrapping in a list.
    progress : bool, optional
        Show progress bar for dask arrays. Default is False.

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If a label with this name was already written or added.
    NotImplementedError
        If the LabelImage has multiple multiscales.
    """
    self._validate_label_name(name)
    context = f"Label '{name}': "
    datasets_seq = self._check_datasets(label_image, datasets, context)
    _check_label_dtypes(datasets_seq, context)
    self._ensure_initialized()
    self._update_labels_group(name)
    # (`_image_type` is the Image model, of which LabelImage is a subclass)
    self._write(label_image, datasets, name, progress=progress)
    return self

add_label #

add_label(
    name: str,
    label_image: LabelImage,
    datasets: ShapeAndDTypeOrPyramid,
) -> Self

Add a label for the prepare-only workflow.

Registers a label to be created when prepare() is called. Use this when you want to create the Zarr structure without writing data immediately. After calling prepare(), write data to the returned array handles.

Parameters:

Name Type Description Default
name str

Label name (becomes the subgroup path, e.g., "cells", "nuclei").

required
label_image LabelImage

OME-Zarr LabelImage metadata model for this label.

required
datasets ShapeAndDTypeOrPyramid

Shape/dtype spec(s) for each resolution level: - Single level: (shape, dtype) - Multiple levels: [(shape1, dtype1), (shape2, dtype2)]

required

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If a label with this name was already added or written, or if the number of specs doesn't match the metadata.

NotImplementedError

If the LabelImage has multiple multiscales.

Source code in src/yaozarrs/write/_common/_builders.py
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
def add_label(
    self,
    name: str,
    label_image: LabelImage,
    datasets: ShapeAndDTypeOrPyramid,
) -> Self:
    """Add a label for the prepare-only workflow.

    Registers a label to be created when `prepare()` is called. Use this
    when you want to create the Zarr structure without writing data
    immediately. After calling `prepare()`, write data to the returned
    array handles.

    Parameters
    ----------
    name : str
        Label name (becomes the subgroup path, e.g., "cells", "nuclei").
    label_image : LabelImage
        OME-Zarr LabelImage metadata model for this label.
    datasets : ShapeAndDTypeOrPyramid
        Shape/dtype spec(s) for each resolution level:
        - Single level: `(shape, dtype)`
        - Multiple levels: `[(shape1, dtype1), (shape2, dtype2)]`

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If a label with this name was already added or written, or if the
        number of specs doesn't match the metadata.
    NotImplementedError
        If the LabelImage has multiple multiscales.
    """
    self._validate_label_name(name)
    context = f"Label '{name}': "
    specs_seq = self._check_datasets(label_image, datasets, context)
    _check_label_dtypes(specs_seq, context)
    self._labels[name] = (label_image, specs_seq)
    return self

prepare #

prepare() -> tuple[Path, dict[str, Any]]

Create the Zarr hierarchy and return array handles.

Creates the complete labels group structure including LabelsGroup metadata, and empty arrays for all registered labels. Call this after registering all labels with add_label().

The returned arrays support numpy-style indexing for writing data: arrays["label_name/dataset"][:] = data.

Returns:

Type Description
tuple[Path, dict[str, Any]]

A tuple of (root_path, arrays) where arrays maps composite keys like "cells/0" (label name / dataset path) to array objects. The array type depends on the configured writer (zarr.Array or tensorstore.TensorStore).

Raises:

Type Description
ValueError

If no labels have been added with add_label().

FileExistsError

If destination exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Source code in src/yaozarrs/write/_common/_builders.py
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
def prepare(self) -> tuple[Path, dict[str, Any]]:
    """Create the Zarr hierarchy and return array handles.

    Creates the complete labels group structure including LabelsGroup
    metadata, and empty arrays for all registered labels. Call this after
    registering all labels with `add_label()`.

    The returned arrays support numpy-style indexing for writing data:
    `arrays["label_name/dataset"][:] = data`.

    Returns
    -------
    tuple[Path, dict[str, Any]]
        A tuple of (root_path, arrays) where `arrays` maps composite keys
        like `"cells/0"` (label name / dataset path) to array objects. The
        array type depends on the configured writer (zarr.Array or
        tensorstore.TensorStore).

    Raises
    ------
    ValueError
        If no labels have been added with `add_label()`.
    FileExistsError
        If destination exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.
    """
    if not self._labels:  # pragma: no cover
        raise ValueError("No labels added. Use add_label() before prepare().")

    labels_group = self._labels_group_type(labels=self._all_labels(self._labels))
    # (an existing labels group is added to, not replaced)
    if (self._dest / "zarr.json").exists():
        _update_zarr3_group(self._dest, labels_group)
    else:
        _create_zarr3_group(self._dest, labels_group, self._overwrite)

    all_arrays: dict[str, Any] = {}
    for label_name, (label_image, datasets) in self._labels.items():
        all_arrays.update(self._prepare(label_image, datasets, label_name))
    return self._dest, all_arrays

PlateBuilder #

PlateBuilder(
    dest: str | PathLike,
    *,
    plate: Plate | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
)

Builder for OME-Zarr v0.6 Plate hierarchies with auto-generated metadata.

The Plate hierarchy includes: - A root Plate group with metadata (auto-generated from written wells) - Well subgroups (e.g., A/1/, B/2/, etc...) each containing Well metadata - Field subgroups (e.g., 0/, 1/) within each well, each an Image

This builder supports two workflows:

  1. Immediate write (simpler): Use write_well() to write each well with its field data immediately. The builder auto-generates and updates plate metadata (rows, columns, wells) after each call, similar to how Bf2RawBuilder auto-updates the series list.

  2. Prepare-only (flexible): Use add_well() to register all wells, then prepare() to create the hierarchy with empty arrays. Plate metadata is auto-generated from all registered wells.

See Also
  • write_plate : High-level function to write all wells at once.

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the Plate Zarr group.

required
plate Plate | None

Optional OME-Zarr Plate metadata model. If None (default), plate metadata (rows, columns, wells) is auto-generated from written/added wells. If provided, validates that written wells match the metadata.

None
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in the root zarr.json.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. Default is "auto".

'auto'
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. Default is "auto".

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
overwrite bool

If True, overwrite existing groups. Default is False. If False and dest already holds a plate, the wells written are added to it. Note: existing directories that don't look like zarr groups will NOT be removed, an exception will be raised instead.

False
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'

Examples:

Auto-generation workflow (recommended):

>>> import numpy as np
>>> from pathlib import Path
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import PlateBuilder
>>>
>>> def make_image():
...     return v06.Image(
...         multiscales=[
...             v06.Multiscale.from_dims([DimSpec(name="y"), DimSpec(name="x")])
...         ]
...     )
>>>
>>> # No plate metadata needed - it's auto-generated!
>>> builder = PlateBuilder("plate_auto.zarr")
>>> builder.write_well(
...     row="A",
...     col="1",
...     images={"0": (make_image(), np.zeros((32, 32), dtype=np.uint16))},
... )
<PlateBuilder: 1 wells>
>>> builder.write_well(
...     row="A",
...     col="2",
...     images={"0": (make_image(), np.zeros((32, 32), dtype=np.uint16))},
... )
<PlateBuilder: 2 wells>
>>> assert (builder.root_path / "zarr.json").exists()  # Plate metadata auto-updated

With explicit plate metadata:

>>> plate = v06.Plate(
...     plate=v06.PlateDef(
...         columns=[v06.Column(name="1")],
...         rows=[v06.Row(name="A")],
...         wells=[v06.PlateWell(path="A/1", rowIndex=0, columnIndex=0)],
...     )
... )
>>> builder2 = PlateBuilder("plate_explicit.zarr", plate=plate)
>>> builder2.write_well(
...     row="A",
...     col="1",
...     images={"0": (make_image(), np.zeros((32, 32), dtype=np.uint16))},
... )
<PlateBuilder: 1 wells>
Source code in src/yaozarrs/write/v06/_write.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
def __init__(
    self,
    dest: str | PathLike,
    *,
    plate: Plate | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
) -> None:
    super().__init__(
        Path(dest),
        plate=plate,
        extra_attributes=extra_attributes,
        writer=writer,
        chunks=chunks,
        shards=shards,
        overwrite=overwrite,
        compression=compression,
    )

root_path property #

root_path: Path

Path to the root of the plate hierarchy.

write_well #

write_well(
    row: str,
    col: str,
    images: Mapping[str, ImageWithDatasets[Image]],
    *,
    progress: bool = False,
) -> Self

Write a well immediately with its images (fields of view) and data.

This method creates the well structure and writes all field data in one call. The plate structure and well metadata are created/updated automatically. Plate metadata (rows, columns, wells) is auto-generated from all written wells and rewritten after each call.

Parameters:

Name Type Description Default
row str

Row name like "A", "B", etc.

required
col str

Column name like "1", "2", etc.

required
images Mapping[str, ImageWithDatasets]

Mapping of {fov -> (image_model, datasets)} where: - fov: Field of view identifier like "0", "1", etc. - datasets can be: - Single array (for one dataset): {"0": (image, data)} - Sequence (for multiple datasets): {"0": (image, [data1, data2])}

required
progress bool

Show progress bar for dask arrays. Default is False.

False

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If row/col combination was already written or added, or if a user- provided Plate doesn't include this well.

NotImplementedError

If any Image has multiple multiscales.

Source code in src/yaozarrs/write/_common/_builders.py
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def write_well(
    self,
    row: str,
    col: str,
    images: Mapping[str, ImageWithDatasets[Image]],
    *,
    progress: bool = False,
) -> Self:
    """Write a well immediately with its `images` (fields of view) and data.

    This method creates the well structure and writes all field data in one
    call. The plate structure and well metadata are created/updated
    automatically. Plate metadata (rows, columns, wells) is auto-generated
    from all written wells and rewritten after each call.

    Parameters
    ----------
    row : str
        Row name like "A", "B", etc.
    col : str
        Column name like "1", "2", etc.
    images : Mapping[str, ImageWithDatasets]
        Mapping of `{fov -> (image_model, datasets)}` where:
        - fov: Field of view identifier like "0", "1", etc.
        - datasets can be:
          - Single array (for one dataset): `{"0": (image, data)}`
          - Sequence (for multiple datasets): `{"0": (image, [data1, data2])}`
    progress : bool, optional
        Show progress bar for dask arrays. Default is False.

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If row/col combination was already written or added, or if a user-
        provided Plate doesn't include this well.
    NotImplementedError
        If any Image has multiple multiscales.
    """
    self._validate_well_coordinates(row, col)
    normalized_fields = self._check_fields(row, col, images)
    # (after the checks, so nothing is created for a well that would be rejected)
    self._ensure_initialized()

    self._written_wells_data[(row, col)] = cast(
        "dict[str, ImageWithDatasets]", normalized_fields
    )
    self._update_plate_metadata()

    well_path = f"{row}/{col}"
    self._create_well_group(well_path, list(images))
    for fov, (image_model, datasets_seq) in normalized_fields.items():
        self._write(image_model, datasets_seq, well_path, fov, progress=progress)
    return self

add_well #

add_well(
    *,
    row: str,
    col: str,
    images: Mapping[str, ImageWithShapeSpecs[Image]],
) -> Self

Add a well for the prepare-only workflow.

Registers a well with its fields to be created when prepare() is called. Use this when you want to create the Zarr structure without writing data immediately. After calling prepare(), write data to the returned array handles.

Parameters:

Name Type Description Default
row str

Row name like "A", "B", etc.

required
col str

Column name like "1", "2", etc.

required
images Mapping[str, ImageWithShapeSpecs]

Mapping of {fov -> (image_model, specs)} where specs provide the dtype and shape for each resolution level: - Single level: (image, (shape, dtype)) - Multiple levels: (image, [(shape1, dtype1), (shape2, dtype2)])

required

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If row/col combination was already added/written, or if a user- provided Plate doesn't include this well, or if field specs don't match Image metadata.

NotImplementedError

If any Image has multiple multiscales.

Source code in src/yaozarrs/write/_common/_builders.py
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def add_well(
    self,
    *,
    row: str,
    col: str,
    images: Mapping[str, ImageWithShapeSpecs[Image]],
) -> Self:
    """Add a well for the prepare-only workflow.

    Registers a well with its fields to be created when `prepare()` is called.
    Use this when you want to create the Zarr structure without writing data
    immediately. After calling `prepare()`, write data to the returned array
    handles.

    Parameters
    ----------
    row : str
        Row name like "A", "B", etc.
    col : str
        Column name like "1", "2", etc.
    images : Mapping[str, ImageWithShapeSpecs]
        Mapping of `{fov -> (image_model, specs)}` where specs provide the
        dtype and shape for each resolution level:
        - Single level: `(image, (shape, dtype))`
        - Multiple levels: `(image, [(shape1, dtype1), (shape2, dtype2)])`

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If row/col combination was already added/written, or if a user-
        provided Plate doesn't include this well, or if field specs
        don't match Image metadata.
    NotImplementedError
        If any Image has multiple multiscales.
    """
    self._validate_well_coordinates(row, col)
    normalized_fields = cast(
        "dict[str, ImageWithShapeSpecs[Image]]",
        self._check_fields(row, col, images),
    )
    self._wells[f"{row}/{col}"] = normalized_fields
    return self

prepare #

prepare() -> tuple[Path, dict[str, Any]]

Create the Zarr hierarchy and return array handles.

Creates the complete Plate structure including plate metadata (auto- generated from registered wells), well subgroups with Well metadata, and empty arrays for all registered fields. Call this after registering all wells with add_well().

The returned arrays support numpy-style indexing for writing data: arrays["well/field/dataset"][:] = data.

Returns:

Type Description
tuple[Path, dict[str, Any]]

A tuple of (root_path, arrays) where arrays maps composite keys like "A/1/0/0" (well_path / field / dataset_path) to array objects. The array type depends on the configured writer (zarr.Array or tensorstore.TensorStore).

Raises:

Type Description
ValueError

If no wells have been added with add_well().

FileExistsError

If destination exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Source code in src/yaozarrs/write/_common/_builders.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
def prepare(self) -> tuple[Path, dict[str, Any]]:
    """Create the Zarr hierarchy and return array handles.

    Creates the complete Plate structure including plate metadata (auto-
    generated from registered wells), well subgroups with Well metadata,
    and empty arrays for all registered fields. Call this after registering
    all wells with `add_well()`.

    The returned arrays support numpy-style indexing for writing data:
    `arrays["well/field/dataset"][:] = data`.

    Returns
    -------
    tuple[Path, dict[str, Any]]
        A tuple of (root_path, arrays) where `arrays` maps composite keys
        like `"A/1/0/0"` (well_path / field / dataset_path) to array
        objects. The array type depends on the configured writer
        (zarr.Array or tensorstore.TensorStore).

    Raises
    ------
    ValueError
        If no wells have been added with `add_well()`.
    FileExistsError
        If destination exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.
    """
    if not self._wells:
        raise ValueError("No wells added. Use add_well() before prepare().")

    plate = _merge_plate_metadata(
        self._get_images_dict(), self._user_plate, self._plate_type
    )
    _create_zarr3_group(
        self._dest, plate, self._overwrite, extra_attributes=self._extra_attributes
    )

    all_arrays: dict[str, Any] = {}
    for well_path, fields in self._wells.items():
        self._create_well_group(well_path, list(fields))
        for fov, (image_model, datasets) in fields.items():
            all_arrays.update(self._prepare(image_model, datasets, well_path, fov))
    return self._dest, all_arrays

Bf2RawBuilder #

Bf2RawBuilder(
    dest: str | PathLike,
    *,
    ome_xml: str | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
)

Builder for bioformats2raw layout hierarchies.

The bioformats2raw layout is a convention for storing multiple OME-Zarr images in a single hierarchy. It includes:

  • A root group with bioformats2raw.layout version attribute
  • An OME/ subgroup listing all series names
  • Each series as a separate Image subgroup (e.g., 0/, 1/)
  • Optional OME/METADATA.ome.xml with full OME-XML metadata

This builder supports three workflows:

  1. Immediate write (simpler): Use write_image() to write each series with its data immediately. The builder manages root structure and series list automatically.

  2. Prepare-only (flexible): Use add_series() to register all series, then prepare() to create the hierarchy with empty arrays. Write data to the returned arrays yourself.

  3. Create now, write later: Use prepare_series() to create one series at a time, with empty arrays, and write to the returned arrays yourself (the builder doesn't keep them: hold on to them, or reopen them yourself).

Each series is listed in OME/zarr.json only once its arrays exist (and the root zarr.json is written with the first series), so the store is a valid collection after every call. A collection already at dest (of this version, with a series list) is added to, unless overwrite.

A builder isn't thread-safe: create series from one thread (or behind your own lock), then write their data from as many threads or processes as you like.

See Also

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the root Zarr group.

required
ome_xml str | None

Original OME-XML string to store as OME/METADATA.ome.xml.

None
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in the root zarr.json.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. Default is "auto".

'auto'
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. Default is "auto".

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
overwrite bool

If True, replace whatever is at dest (when the first series is created). If False (default), add to the collection at dest, if there is one: anything else at dest raises FileExistsError. Note: existing directories that don't look like zarr groups will NOT be removed, an exception will be raised instead.

False
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'

Examples:

Immediate write workflow:

>>> import numpy as np
>>> from pathlib import Path
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import Bf2RawBuilder
>>> def make_image():
...     return v06.Image(
...         multiscales=[
...             v06.Multiscale.from_dims([DimSpec(name="y"), DimSpec(name="x")])
...         ]
...     )
>>> builder = Bf2RawBuilder("builder_immediate.zarr")
>>> builder.write_image("0", make_image(), np.zeros((32, 32), dtype=np.uint16))
<Bf2RawBuilder: 1 images>
>>> builder.write_image("1", make_image(), np.zeros((16, 16), dtype=np.uint16))
<Bf2RawBuilder: 2 images>
>>> assert (builder.root_path / "0" / "zarr.json").exists()

Prepare-only workflow:

>>> builder2 = Bf2RawBuilder("builder_prepare.zarr")
>>> builder2.add_series("0", make_image(), ((32, 32), np.uint16))  # shape, dtype
<Bf2RawBuilder: 1 images>
>>> builder2.add_series("1", make_image(), ((16, 16), np.uint16))
<Bf2RawBuilder: 2 images>
>>> path, arrays = builder2.prepare()
>>> arrays["0/0"][:] = np.zeros((32, 32), dtype=np.uint16)  # Write data yourself
>>> arrays["1/0"][:] = np.zeros((16, 16), dtype=np.uint16)
>>> assert path.exists()

Create now, write later:

>>> builder3 = Bf2RawBuilder("builder_incremental.zarr")
>>> _, arrays = builder3.prepare_series("0", make_image(), ((32, 32), np.uint16))
>>> arrays["0"][:16] = np.ones((16, 32), dtype=np.uint16)  # e.g. tile by tile
>>> _ = builder3.prepare_series("1", make_image(), ((16, 16), np.uint8))
>>> builder3.series
('0', '1')
Source code in src/yaozarrs/write/v06/_write.py
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def __init__(
    self,
    dest: str | PathLike,
    *,
    ome_xml: str | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
) -> None:
    super().__init__(
        Path(dest),
        ome_xml=ome_xml,
        extra_attributes=extra_attributes,
        writer=writer,
        chunks=chunks,
        shards=shards,
        overwrite=overwrite,
        compression=compression,
    )

root_path property #

root_path: Path

Path to the root of the bioformats2raw hierarchy.

series property #

series: tuple[str, ...]

The series of the collection, in OME/zarr.json order.

(Including any that were already at dest.)

prepare_series #

prepare_series(
    name: str,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
    *,
    chunks: ShapeLike
    | Literal["auto"]
    | _Default
    | None = BUILDER,
    shards: ShapeLike | _Default | None = BUILDER,
    compression: CompressionName | _Default = BUILDER,
) -> tuple[Path, dict[str, Any]]

Create a series now, with empty arrays, and add it to the collection.

The series' group and arrays are created first, and only then is the series listed in OME/zarr.json (which creates the collection, if this is its first series). Write data into the returned arrays at any time, in any order. The builder doesn't keep them: hold on to them, or reopen them later with your own backend (at root_path / name / <dataset path>).

Parameters:

Name Type Description Default
name str

Path of the series' image group below the root, e.g. "0", or "group_1/array_1_0" (intermediate groups are created).

required
image Image

OME-Zarr Image metadata model for this series.

required
datasets ShapeAndDTypeOrPyramid

Shape and dtype specification(s) for each resolution level, as (shape, dtype) tuples. For a single dataset, pass the tuple directly without wrapping in a list.

required
chunks tuple[int, ...] | 'auto' | None

Chunk shape for this series' arrays. Default is the builder's.

BUILDER
shards tuple[int, ...] | None

Shard shape for this series' arrays. Default is the builder's.

BUILDER
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec for this series' arrays. Default is the builder's.

BUILDER

Returns:

Type Description
tuple[Path, dict[str, Any]]

The path of the series' group, and its arrays by dataset path (e.g. "0"). The array type depends on the configured writer (zarr.Array or tensorstore.TensorStore).

Raises:

Type Description
ValueError

If name isn't a valid path (or is inside "OME"), if a series with this name was already added or written, or if the dataset specs don't match the metadata.

FileExistsError

If something is already at the series' path, or if overwrite is True but dest isn't a Zarr group (which isn't deleted).

NotImplementedError

If the Image has multiple multiscales.

ImportError

If no suitable writer backend is installed.

Source code in src/yaozarrs/write/_common/_builders.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
def prepare_series(
    self,
    name: str,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
    *,
    chunks: ShapeLike | Literal["auto"] | _Default | None = _Default.BUILDER,
    shards: ShapeLike | _Default | None = _Default.BUILDER,
    compression: CompressionName | _Default = _Default.BUILDER,
) -> tuple[Path, dict[str, Any]]:
    """Create a series now, with empty arrays, and add it to the collection.

    The series' group and arrays are created first, and only then is the series
    listed in `OME/zarr.json` (which creates the collection, if this is its first
    series).  Write data into the returned arrays at any time, in any order.  The
    builder doesn't keep them: hold on to them, or reopen them later with your own
    backend (at `root_path / name / <dataset path>`).

    Parameters
    ----------
    name : str
        Path of the series' image group below the root, e.g. "0", or
        "group_1/array_1_0" (intermediate groups are created).
    image : Image
        OME-Zarr Image metadata model for this series.
    datasets : ShapeAndDTypeOrPyramid
        Shape and dtype specification(s) for each resolution level, as
        `(shape, dtype)` tuples. For a single dataset, pass the tuple
        directly without wrapping in a list.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for this series' arrays.  Default is the builder's.
    shards : tuple[int, ...] | None, optional
        Shard shape for this series' arrays.  Default is the builder's.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec for this series' arrays.  Default is the builder's.

    Returns
    -------
    tuple[Path, dict[str, Any]]
        The path of the series' group, and its arrays by dataset path (e.g.
        "0").  The array type depends on the configured writer (zarr.Array or
        tensorstore.TensorStore).

    Raises
    ------
    ValueError
        If `name` isn't a valid path (or is inside "OME"), if a series with this
        name was already added or written, or if the dataset specs don't match
        the metadata.
    FileExistsError
        If something is already at the series' path, or if `overwrite` is True
        but `dest` isn't a Zarr group (which isn't deleted).
    NotImplementedError
        If the Image has multiple multiscales.
    ImportError
        If no suitable writer backend is installed.
    """
    self._validate_series_name(name)
    options = self._array_options(chunks, shards, compression)
    _, specs = _check_image_args(
        image,
        datasets,
        self._image_type,
        f"Series '{name}': ",
        options["chunks"],
        options["shards"],
    )
    series = {name: (image, specs, options)}
    arrays = self._create_series(series)
    return self._dest / name, arrays[name]

write_image #

write_image(
    name: str,
    image: Image,
    datasets: ArrayOrPyramid,
    *,
    progress: bool = False,
) -> Self

Write a series immediately with its data.

This method creates the series structure and writes data in one call. The root structure and OME metadata are created/updated automatically. Use this for the "immediate write" workflow.

Parameters:

Name Type Description Default
name str

Series name (becomes the subgroup path, e.g., "0", "1").

required
image Image

OME-Zarr Image metadata model for this series.

required
datasets ArrayOrPyramid

Data array(s) for each resolution level. For a single dataset, pass the array directly without wrapping in a list.

required
progress bool

Show progress bar when writing dask arrays. Default is False.

False

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If name isn't a valid path (or is inside "OME"), or if a series with this name was already written or added.

FileExistsError

If something is already at the series' path, or if overwrite is True but dest isn't a Zarr group (which isn't deleted).

NotImplementedError

If the Image has multiple multiscales.

Source code in src/yaozarrs/write/_common/_builders.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def write_image(
    self,
    name: str,
    image: Image,
    datasets: ArrayOrPyramid,
    *,
    progress: bool = False,
) -> Self:
    """Write a series immediately with its data.

    This method creates the series structure and writes data in one call.
    The root structure and OME metadata are created/updated automatically.
    Use this for the "immediate write" workflow.

    Parameters
    ----------
    name : str
        Series name (becomes the subgroup path, e.g., "0", "1").
    image : Image
        OME-Zarr Image metadata model for this series.
    datasets : ArrayOrPyramid
        Data array(s) for each resolution level. For a single dataset,
        pass the array directly without wrapping in a list.
    progress : bool, optional
        Show progress bar when writing dask arrays. Default is False.

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If `name` isn't a valid path (or is inside "OME"), or if a series with
        this name was already written or added.
    FileExistsError
        If something is already at the series' path, or if `overwrite` is True
        but `dest` isn't a Zarr group (which isn't deleted).
    NotImplementedError
        If the Image has multiple multiscales.
    """
    self._validate_series_name(name)
    datasets_seq = self._check_datasets(image, datasets, f"Series '{name}': ")
    specs = [(arr.shape, arr.dtype) for arr in datasets_seq]
    series = {name: (image, specs, self._array_options())}
    self._create_series(series, data={name: datasets_seq}, progress=progress)
    return self

add_series #

add_series(
    name: str,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
) -> Self

Add a series for the prepare-only workflow.

Registers a series to be created when prepare() is called. Use this when you want to create the Zarr structure without writing data immediately. After calling prepare(), write data to the returned array handles.

Parameters:

Name Type Description Default
name str

Series name (becomes the subgroup path, e.g., "0", "1").

required
image Image

OME-Zarr Image metadata model for this series.

required
datasets ShapeAndDTypeOrPyramid

Shape and dtype specification(s) for each resolution level, as (shape, dtype) tuples. For a single dataset, pass the tuple directly without wrapping in a list.

required

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If name isn't a valid path (or is inside "OME"), if a series with this name was already added or written, or if the number of dataset specs doesn't match the metadata.

NotImplementedError

If the Image has multiple multiscales.

Source code in src/yaozarrs/write/_common/_builders.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def add_series(
    self,
    name: str,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
) -> Self:
    """Add a series for the prepare-only workflow.

    Registers a series to be created when `prepare()` is called. Use this
    when you want to create the Zarr structure without writing data
    immediately. After calling `prepare()`, write data to the returned
    array handles.

    Parameters
    ----------
    name : str
        Series name (becomes the subgroup path, e.g., "0", "1").
    image : Image
        OME-Zarr Image metadata model for this series.
    datasets : ShapeAndDTypeOrPyramid
        Shape and dtype specification(s) for each resolution level, as
        `(shape, dtype)` tuples. For a single dataset, pass the tuple
        directly without wrapping in a list.

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If `name` isn't a valid path (or is inside "OME"), if a series with this
        name was already added or written, or if the number of dataset specs
        doesn't match the metadata.
    NotImplementedError
        If the Image has multiple multiscales.
    """
    self._validate_series_name(name)
    datasets_seq = self._check_datasets(image, datasets, f"Series '{name}': ")
    self._series[name] = (image, datasets_seq)
    return self

prepare #

prepare() -> tuple[Path, dict[str, Any]]

Create the Zarr hierarchy and return array handles.

Creates the series registered with add_series() since the last call (with empty arrays), then lists them in OME/zarr.json, creating the collection if needed. If creating any of them fails, none are added (add them again to retry).

The returned arrays support numpy-style indexing for writing data: arrays["series/dataset"][:] = data.

Returns:

Type Description
tuple[Path, dict[str, Any]]

A tuple of (root_path, arrays) where arrays maps composite keys like "0/0" (series name / dataset path) to array objects. The array type depends on the configured writer (zarr.Array or tensorstore.TensorStore).

Raises:

Type Description
ValueError

If no series have been added with add_series() since the last call.

FileExistsError

If something is already at the path of one of the series, or if overwrite is True but dest isn't a Zarr group (which isn't deleted).

ImportError

If no suitable writer backend is installed.

Source code in src/yaozarrs/write/_common/_builders.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
def prepare(self) -> tuple[Path, dict[str, Any]]:
    """Create the Zarr hierarchy and return array handles.

    Creates the series registered with `add_series()` since the last call (with
    empty arrays), then lists them in `OME/zarr.json`, creating the collection
    if needed.  If creating any of them fails, none are added (add them again to
    retry).

    The returned arrays support numpy-style indexing for writing data:
    `arrays["series/dataset"][:] = data`.

    Returns
    -------
    tuple[Path, dict[str, Any]]
        A tuple of (root_path, arrays) where `arrays` maps composite keys
        like `"0/0"` (series name / dataset path) to array objects. The
        array type depends on the configured writer (zarr.Array or
        tensorstore.TensorStore).

    Raises
    ------
    ValueError
        If no series have been added with `add_series()` since the last call.
    FileExistsError
        If something is already at the path of one of the series, or if
        `overwrite` is True but `dest` isn't a Zarr group (which isn't deleted).
    ImportError
        If no suitable writer backend is installed.
    """
    if not self._series:
        raise ValueError("No series added. Use add_series() before prepare().")

    queued, self._series = self._series, {}
    options = self._array_options()
    series = {
        name: (image, specs, options) for name, (image, specs) in queued.items()
    }
    arrays = self._create_series(series)
    all_arrays = {
        f"{name}/{dataset_path}": arr
        for name, series_arrays in arrays.items()
        for dataset_path, arr in series_arrays.items()
    }
    return self._dest, all_arrays

SceneBuilder #

SceneBuilder(
    dest: str | PathLike,
    scene: Scene,
    *,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
)

Builder for OME-Zarr v0.6 scene hierarchies.

A scene group holds Scene metadata, describing the spatial relationship between the images in its subgroups. Unlike a plate's, the scene metadata is not generated: it is given up front, and written as is.

This builder supports two workflows:

  1. Immediate write (simpler): Use write_image() to write each image with its data (and labels) immediately. Each image is checked against the scene's references to it (that the coordinate systems they name exist) as it is written; that every referenced image gets written is up to you.
  2. Prepare-only (flexible): Use add_image() to register all images, then prepare() to create the hierarchy with empty arrays. prepare() checks the scene as a whole first (as write_scene does): every referenced image is there, and the graph is connected.

chunks, shards and compression are defaults for every image: write_image() and add_image() can override them per image (e.g. for images with different numbers of dimensions).

See Also
  • write_scene : High-level function to write all images at once.

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the scene Zarr group.

required
scene Scene

OME-Zarr Scene metadata model.

required
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in the scene's zarr.json.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. Default is "auto".

'auto'
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. Default is "auto".

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
overwrite bool

If True, overwrite existing groups. Default is False. Note: existing directories that don't look like zarr groups will NOT be removed, an exception will be raised instead.

False
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'

Examples:

>>> import numpy as np
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import SceneBuilder
>>>
>>> def make_image():
...     return v06.Image(
...         multiscales=[
...             v06.Multiscale.from_dims([DimSpec(name="y"), DimSpec(name="x")])
...         ]
...     )
>>> scene = v06.Scene(
...     scene=v06.SceneDef(
...         coordinateTransformations=[
...             v06.TranslationTransformation(
...                 translation=[0, 100],
...                 input={"path": "b", "name": "intrinsic"},
...                 output={"path": "a", "name": "intrinsic"},
...             )
...         ]
...     )
... )

Immediate write workflow:

>>> builder = SceneBuilder("scene_immediate.zarr", scene)
>>> builder.write_image("a", make_image(), np.zeros((32, 32), dtype=np.uint16))
<SceneBuilder: 1 images>
>>> builder.write_image("b", make_image(), np.zeros((32, 32), dtype=np.uint16))
<SceneBuilder: 2 images>

Prepare-only workflow:

>>> builder2 = SceneBuilder("scene_prepare.zarr", scene)
>>> builder2.add_image("a", make_image(), ((32, 32), np.uint16))
<SceneBuilder: 1 images>
>>> builder2.add_image("b", make_image(), ((32, 32), np.uint16))
<SceneBuilder: 2 images>
>>> path, arrays = builder2.prepare()
>>> arrays["b/0"][:] = np.zeros((32, 32), dtype=np.uint16)
Source code in src/yaozarrs/write/v06/_write.py
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
def __init__(
    self,
    dest: str | PathLike,
    scene: Scene,
    *,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    chunks: ShapeLike | Literal["auto"] | None = "auto",
    shards: ShapeLike | None = None,
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
) -> None:
    _check_model(scene, Scene, "scene: ")
    super().__init__(
        Path(dest),
        writer=writer,
        chunks=chunks,
        shards=shards,
        overwrite=overwrite,
        compression=compression,
    )
    self._scene = scene
    self._extra_attributes = extra_attributes

    # For prepare-only workflow: {path: (image, dataset_specs, array_options)}
    self._images: dict[str, AddedImage] = {}
    # For immediate write workflow: {path: image}, and {label path: label image}
    self._written_images: dict[str, Image] = {}
    self._written_labels: dict[str, LabelImage] = {}

root_path property #

root_path: Path

Path to the scene group.

write_image #

write_image(
    path: str,
    image: Image,
    datasets: ArrayOrPyramid,
    *,
    labels: LabelsWithDatasets | None = None,
    chunks: ShapeLike
    | Literal["auto"]
    | _Default
    | None = BUILDER,
    shards: ShapeLike | _Default | None = BUILDER,
    compression: CompressionName | _Default = BUILDER,
    progress: bool = False,
) -> Self

Write an image of the scene immediately, with its data.

The scene group is created along with the first image.

Parameters:

Name Type Description Default
path str

Path of the image subgroup, relative to the scene group (e.g. "tile_0", or "tiles/0").

required
image Image

OME-Zarr Image metadata model for this image.

required
datasets ArrayOrPyramid

Data array(s) for each resolution level. For a single dataset, pass the array directly without wrapping in a list.

required
labels Mapping[str, tuple[LabelImage, ArrayOrPyramid]] | None

Label images to write alongside the image, as {label name -> (LabelImage, datasets)} (see write_image). They are written to {path}/labels/{label name}/, with this image's array settings.

None
chunks tuple[int, ...] | 'auto' | None

Chunk shape for this image's arrays. Default is the builder's.

BUILDER
shards tuple[int, ...] | None

Shard shape for this image's arrays. Default is the builder's.

BUILDER
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec for this image's arrays. Default is the builder's.

BUILDER
progress bool

Show progress bar when writing dask arrays. Default is False.

False

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If the path is invalid or already used, if the scene references a coordinate system this image doesn't have, or if datasets don't match the metadata.

NotImplementedError

If the Image has multiple multiscales.

Source code in src/yaozarrs/write/v06/_write.py
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
def write_image(
    self,
    path: str,
    image: Image,
    datasets: ArrayOrPyramid,
    *,
    labels: LabelsWithDatasets | None = None,
    chunks: ShapeLike | Literal["auto"] | _Default | None = _Default.BUILDER,
    shards: ShapeLike | _Default | None = _Default.BUILDER,
    compression: CompressionName | _Default = _Default.BUILDER,
    progress: bool = False,
) -> Self:
    """Write an image of the scene immediately, with its data.

    The scene group is created along with the first image.

    Parameters
    ----------
    path : str
        Path of the image subgroup, relative to the scene group (e.g. "tile_0",
        or "tiles/0").
    image : Image
        OME-Zarr Image metadata model for this image.
    datasets : ArrayOrPyramid
        Data array(s) for each resolution level. For a single dataset,
        pass the array directly without wrapping in a list.
    labels : Mapping[str, tuple[LabelImage, ArrayOrPyramid]] | None, optional
        Label images to write alongside the image, as `{label name ->
        (LabelImage, datasets)}` (see `write_image`).  They are written to
        `{path}/labels/{label name}/`, with this image's array settings.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for this image's arrays.  Default is the builder's.
    shards : tuple[int, ...] | None, optional
        Shard shape for this image's arrays.  Default is the builder's.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec for this image's arrays.  Default is the builder's.
    progress : bool, optional
        Show progress bar when writing dask arrays. Default is False.

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If the path is invalid or already used, if the scene references a
        coordinate system this image doesn't have, or if datasets don't match
        the metadata.
    NotImplementedError
        If the Image has multiple multiscales.
    """
    self._check_image(
        path, image, datasets, chunks=chunks, shards=shards, labels=labels
    )
    label_images = _label_paths(path, labels)
    # (only the references to this image: the others may not be written yet)
    _check_scene(self._scene, {path: image, **label_images}, complete=False)

    self._ensure_initialized()
    _ensure_parent_groups(self._dest, path)
    self._write(
        image,
        datasets,
        path,
        labels=labels,
        labels_builder_type=LabelsBuilder,
        progress=progress,
        chunks=chunks,
        shards=shards,
        compression=compression,
    )
    self._written_images[path] = image
    self._written_labels.update(label_images)
    return self

add_image #

add_image(
    path: str,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
    *,
    labels: LabelsWithSpecs | None = None,
    chunks: ShapeLike
    | Literal["auto"]
    | _Default
    | None = BUILDER,
    shards: ShapeLike | _Default | None = BUILDER,
    compression: CompressionName | _Default = BUILDER,
) -> Self

Add an image for the prepare-only workflow.

Registers an image to be created when prepare() is called.

Parameters:

Name Type Description Default
path str

Path of the image subgroup, relative to the scene group (e.g. "tile_0", or "tiles/0").

required
image Image

OME-Zarr Image metadata model for this image.

required
datasets ShapeAndDTypeOrPyramid

Shape and dtype specification(s) for each resolution level, as (shape, dtype) tuples. For a single dataset, pass the tuple directly without wrapping in a list.

required
labels Mapping[str, tuple[LabelImage, ShapeAndDTypeOrPyramid]] | None

Label images to create alongside the image, as {label name -> (LabelImage, specs)}. Their arrays are created at {path}/labels/{label name}/, with this image's array settings.

None
chunks tuple[int, ...] | 'auto' | None

Chunk shape for this image's arrays. Default is the builder's.

BUILDER
shards tuple[int, ...] | None

Shard shape for this image's arrays. Default is the builder's.

BUILDER
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec for this image's arrays. Default is the builder's.

BUILDER

Returns:

Type Description
Self

The builder instance (for method chaining).

Raises:

Type Description
ValueError

If the path is invalid or already used, or if the number of dataset specs doesn't match the metadata.

NotImplementedError

If the Image has multiple multiscales.

Source code in src/yaozarrs/write/v06/_write.py
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
def add_image(
    self,
    path: str,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
    *,
    labels: LabelsWithSpecs | None = None,
    chunks: ShapeLike | Literal["auto"] | _Default | None = _Default.BUILDER,
    shards: ShapeLike | _Default | None = _Default.BUILDER,
    compression: CompressionName | _Default = _Default.BUILDER,
) -> Self:
    """Add an image for the prepare-only workflow.

    Registers an image to be created when `prepare()` is called.

    Parameters
    ----------
    path : str
        Path of the image subgroup, relative to the scene group (e.g. "tile_0",
        or "tiles/0").
    image : Image
        OME-Zarr Image metadata model for this image.
    datasets : ShapeAndDTypeOrPyramid
        Shape and dtype specification(s) for each resolution level, as
        `(shape, dtype)` tuples. For a single dataset, pass the tuple
        directly without wrapping in a list.
    labels : Mapping[str, tuple[LabelImage, ShapeAndDTypeOrPyramid]] | None
        Label images to create alongside the image, as `{label name ->
        (LabelImage, specs)}`.  Their arrays are created at
        `{path}/labels/{label name}/`, with this image's array settings.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for this image's arrays.  Default is the builder's.
    shards : tuple[int, ...] | None, optional
        Shard shape for this image's arrays.  Default is the builder's.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec for this image's arrays.  Default is the builder's.

    Returns
    -------
    Self
        The builder instance (for method chaining).

    Raises
    ------
    ValueError
        If the path is invalid or already used, or if the number of dataset
        specs doesn't match the metadata.
    NotImplementedError
        If the Image has multiple multiscales.
    """
    _, specs = self._check_image(
        path, image, datasets, chunks=chunks, shards=shards, labels=labels
    )
    options = self._array_options(chunks, shards, compression)
    self._images[path] = (image, specs, options, labels or {})
    return self

prepare #

prepare() -> tuple[Path, dict[str, Any]]

Create the Zarr hierarchy and return array handles.

Checks the scene against all its images (those added with add_image() and any already written with write_image()), then creates the scene group and empty arrays for every added image.

Returns:

Type Description
tuple[Path, dict[str, Any]]

A tuple of (root_path, arrays) where arrays maps composite keys like "tile_0/0" (image path / dataset path) to array objects, and "tile_0/labels/cells/0" for label images. The array type depends on the configured writer (zarr.Array or tensorstore.TensorStore).

Raises:

Type Description
ValueError

If no images have been added with add_image(), if the scene references an image (or coordinate system) that isn't there, or if its coordinate systems aren't all connected.

FileExistsError

If destination exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Source code in src/yaozarrs/write/v06/_write.py
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
def prepare(self) -> tuple[Path, dict[str, Any]]:
    """Create the Zarr hierarchy and return array handles.

    Checks the scene against all its images (those added with `add_image()` and
    any already written with `write_image()`), then creates the scene group and
    empty arrays for every added image.

    Returns
    -------
    tuple[Path, dict[str, Any]]
        A tuple of (root_path, arrays) where `arrays` maps composite keys
        like `"tile_0/0"` (image path / dataset path) to array objects, and
        `"tile_0/labels/cells/0"` for label images. The array type depends on
        the configured writer (zarr.Array or tensorstore.TensorStore).

    Raises
    ------
    ValueError
        If no images have been added with `add_image()`, if the scene
        references an image (or coordinate system) that isn't there, or if
        its coordinate systems aren't all connected.
    FileExistsError
        If destination exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.
    """
    if not self._images:
        raise ValueError("No images added. Use add_image() before prepare().")
    added: dict[str, Image] = {}
    for path, (image, _, _, labels) in self._images.items():
        added[path] = image
        added.update(_label_paths(path, labels))
    _check_scene(
        self._scene, {**self._written_images, **self._written_labels, **added}
    )

    self._ensure_initialized()
    all_arrays: dict[str, Any] = {}
    for path, (image, specs, options, labels) in self._images.items():
        _ensure_parent_groups(self._dest, path)
        all_arrays.update(self._prepare(image, specs, path, **options))
        if labels:
            builder = LabelsBuilder(
                self._dest / path / "labels",
                writer=self._writer,
                overwrite=self._overwrite,
                **options,
            )
            for name, (label_image, label_specs) in labels.items():
                builder.add_label(name, label_image, label_specs)
            for key, arr in builder.prepare()[1].items():
                all_arrays[f"{path}/labels/{key}"] = arr
    return self._dest, all_arrays

write_image #

write_image(
    dest: str | PathLike,
    image: Image,
    datasets: ArrayOrPyramid,
    *,
    labels: Mapping[str, tuple[LabelImage, ArrayOrPyramid]]
    | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...]
    | Literal["auto"]
    | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path

Write an OME-Zarr v0.6 Image group with data.

This is the high-level function for writing a complete OME-Zarr image. It creates the Zarr group hierarchy, writes metadata, and stores data in a single call.

See Also

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the Zarr group. Will be created if it doesn't exist.

required
image Image

OME-Zarr Image metadata model. Must have exactly one multiscale, with one Dataset entry per array in datasets.

required
datasets ArrayOrPyramid

Data array(s) to write (numpy, dask, or any array with shape/dtype). - For a single dataset, pass the array directly: write_image(dest, image, data) - For multiple datasets (e.g., multiscale pyramid), pass a sequence: write_image(dest, image, [data0, data1, ...]) Must match the number and order of image.multiscales[0].datasets.

required
labels Mapping[str, tuple[LabelImage, ArrayOrPyramid]] | None

Optional label images to write alongside the image. Keys are label names (e.g., "cells", "nuclei"), values are (LabelImage, datasets) tuples. Labels will be written to dest/labels/{name}/. Default is None.

None
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in zarr.json. For example, {"custom": {...}} will produce attributes: {"ome": {...}, "custom": {...}}.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. "auto" prefers tensorstore if available, otherwise falls back to zarr-python. Pass a custom function matching the CreateArrayFunc protocol for custom backends.

'auto'
overwrite bool

If True, overwrite existing Zarr group at dest. Default is False.

False
chunks tuple[int, ...] | 'auto' | None

Chunk shape for storage. "auto" (default) calculates ~4MB chunks with non-spatial dims set to 1. None uses the full array shape (single chunk). Tuple values must have one entry per array dimension, and are clamped to the array shape.

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. "blosc-zstd" (default) provides good compression with shuffle filter. "zstd" uses raw zstd without blosc container.

'blosc-zstd'
progress bool

Show progress bar when writing dask arrays. Default is False.

False

Returns:

Type Description
Path

Path to the created Zarr group.

Raises:

Type Description
TypeError

If given a model from another OME-Zarr version (e.g. a v05.Image).

NotImplementedError

If the Image model has multiple multiscales (not yet supported).

ValueError

If the number of datasets doesn't match the metadata.

FileExistsError

If dest exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Examples:

Write a simple 3D image (CYX) - single dataset:

>>> import numpy as np
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import write_image
>>>
>>> data = np.zeros((2, 64, 64), dtype=np.uint16)
>>> image = v06.Image(
...     multiscales=[
...         v06.Multiscale.from_dims(
...             [
...                 DimSpec(name="c"),
...                 DimSpec(name="y", scale=0.5, unit="micrometer"),
...                 DimSpec(name="x", scale=0.5, unit="micrometer"),
...             ]
...         )
...     ]
... )
>>> result = write_image("example.ome.zarr", image, data)
>>> assert result.exists()

Write a 3D image (CYX) with associated labels:

>>> # Create label images for segmentation
>>> cells_label = v06.LabelImage(
...     **image.model_dump(),
...     image_label={"colors": [{"label_value": 1, "rgba": [255, 0, 0, 255]}]},
... )
>>> cells_data = np.zeros((2, 64, 64), dtype=np.uint8)
>>> nuclei_label = v06.LabelImage(**image.model_dump(), image_label={})
>>> nuclei_data = np.zeros((2, 64, 64), dtype=np.uint8)
>>> result = write_image(
...     "example.ome.zarr",
...     image,
...     data,
...     labels={
...         "cells": (cells_label, cells_data),
...         "nuclei": (nuclei_label, nuclei_data),
...     },
...     overwrite=True,
... )
>>> assert (result / "labels" / "cells" / "0" / "zarr.json").exists()
Source code in src/yaozarrs/write/v06/_write.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def write_image(
    dest: str | PathLike,
    image: Image,
    datasets: ArrayOrPyramid,
    *,
    labels: Mapping[str, tuple[LabelImage, ArrayOrPyramid]] | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...] | Literal["auto"] | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path:
    """Write an OME-Zarr v0.6 Image group with data.

    This is the high-level function for writing a complete OME-Zarr image.
    It creates the Zarr group hierarchy, writes metadata, and stores data
    in a single call.

    See Also
    --------
    - [`prepare_image`][yaozarrs.write.v06.prepare_image] : Create arrays without
      writing data (for custom write logic).
    - [`write_bioformats2raw`][yaozarrs.write.v06.write_bioformats2raw] : Write
      multi-series bioformats2raw layout.

    Parameters
    ----------
    dest : str | PathLike
        Destination path for the Zarr group. Will be created if it doesn't exist.
    image : Image
        OME-Zarr Image metadata model. Must have exactly one multiscale, with
        one Dataset entry per array in `datasets`.
    datasets : ArrayOrPyramid
        Data array(s) to write (numpy, dask, or any array with shape/dtype).
        - For a single dataset, pass the array directly:
          `write_image(dest, image, data)`
        - For multiple datasets (e.g., multiscale pyramid), pass a sequence:
          `write_image(dest, image, [data0, data1, ...])`
        Must match the number and order of `image.multiscales[0].datasets`.
    labels : Mapping[str, tuple[LabelImage, ArrayOrPyramid]] | None, optional
        Optional label images to write alongside the image. Keys are label names
        (e.g., "cells", "nuclei"), values are (LabelImage, datasets) tuples.
        Labels will be written to `dest/labels/{name}/`. Default is None.
    extra_attributes : dict[str, Any] | None, optional
        Additional attributes to write alongside "ome" in zarr.json.
        For example, `{"custom": {...}}` will produce
        `attributes: {"ome": {...}, "custom": {...}}`.
    writer : "zarr" | "tensorstore" | "auto" | CreateArrayFunc, optional
        Backend to use for writing arrays. "auto" prefers tensorstore if
        available, otherwise falls back to zarr-python. Pass a custom function
        matching the `CreateArrayFunc` protocol for custom backends.
    overwrite : bool, optional
        If True, overwrite existing Zarr group at `dest`. Default is False.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for storage. "auto" (default) calculates ~4MB chunks with
        non-spatial dims set to 1. None uses the full array shape (single chunk).
        Tuple values must have one entry per array dimension, and are clamped
        to the array shape.
    shards : tuple[int, ...] | None, optional
        Shard shape for Zarr v3 sharding. Default is None (no sharding).
        When present, shard_shape must be divisible by chunk shape.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec. "blosc-zstd" (default) provides good compression with
        shuffle filter. "zstd" uses raw zstd without blosc container.
    progress : bool, optional
        Show progress bar when writing dask arrays. Default is False.


    Returns
    -------
    Path
        Path to the created Zarr group.

    Raises
    ------
    TypeError
        If given a model from another OME-Zarr version (e.g. a v05.Image).
    NotImplementedError
        If the Image model has multiple multiscales (not yet supported).
    ValueError
        If the number of datasets doesn't match the metadata.
    FileExistsError
        If `dest` exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.

    Examples
    --------
    Write a simple 3D image (CYX) - single dataset:

    >>> import numpy as np
    >>> from yaozarrs import DimSpec, v06
    >>> from yaozarrs.write.v06 import write_image
    >>>
    >>> data = np.zeros((2, 64, 64), dtype=np.uint16)
    >>> image = v06.Image(
    ...     multiscales=[
    ...         v06.Multiscale.from_dims(
    ...             [
    ...                 DimSpec(name="c"),
    ...                 DimSpec(name="y", scale=0.5, unit="micrometer"),
    ...                 DimSpec(name="x", scale=0.5, unit="micrometer"),
    ...             ]
    ...         )
    ...     ]
    ... )
    >>> result = write_image("example.ome.zarr", image, data)
    >>> assert result.exists()

    Write a 3D image (CYX) with associated labels:

    >>> # Create label images for segmentation
    >>> cells_label = v06.LabelImage(
    ...     **image.model_dump(),
    ...     image_label={"colors": [{"label_value": 1, "rgba": [255, 0, 0, 255]}]},
    ... )
    >>> cells_data = np.zeros((2, 64, 64), dtype=np.uint8)
    >>> nuclei_label = v06.LabelImage(**image.model_dump(), image_label={})
    >>> nuclei_data = np.zeros((2, 64, 64), dtype=np.uint8)
    >>> result = write_image(
    ...     "example.ome.zarr",
    ...     image,
    ...     data,
    ...     labels={
    ...         "cells": (cells_label, cells_data),
    ...         "nuclei": (nuclei_label, nuclei_data),
    ...     },
    ...     overwrite=True,
    ... )
    >>> assert (result / "labels" / "cells" / "0" / "zarr.json").exists()
    """
    return _write_image(
        Path(dest),
        image,
        datasets,
        image_type=Image,
        labels=labels,
        labels_builder_type=LabelsBuilder,
        extra_attributes=extra_attributes,
        writer=writer,
        overwrite=overwrite,
        chunks=chunks,
        shards=shards,
        compression=compression,
        progress=progress,
    )

write_plate #

write_plate(
    dest: str | PathLike,
    images: Mapping[
        tuple[str, str, str], ImageWithDatasets
    ],
    *,
    plate: Plate | dict[str, Any] | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...]
    | Literal["auto"]
    | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path

Write an OME-Zarr v0.6 Plate group with data.

This is the high-level function for writing a complete OME-Zarr plate. It creates the plate hierarchy (plate/wells/fields), writes metadata, and stores image data in a single call.

The plate structure::

dest/
├── zarr.json          # Plate metadata
├── A/
│   ├── 1/
│   │   ├── zarr.json  # Well metadata (auto-generated)
│   │   ├── 0/         # Field 0
│   │   │   ├── zarr.json  # Image metadata
│   │   │   └── 0/     # dataset arrays
│   │   └── 1/         # Field 1 (if multiple fields)
│   └── 2/
└── B/
    └── ...
See Also

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the Plate Zarr group.

required
images Mapping[tuple[str, str, str], ImageWithDatasets]

Mapping of {(row, col, fov) -> (image_model, [datasets, ...])}. Each tuple key specifies (row_name, column_name, field_of_view) like ("A", "1", "0"). Row and column names are auto-extracted from the keys. (Zero-padded column names like "01" are kept as they are.)

required
plate Plate | dict[str, Any] | None

Optional plate metadata. Can be: - None (default): Auto-generate from images dict keys - dict: Merge with auto-generated metadata (user values take precedence) - Plate: Use as-is (must match images dict) Common dict keys: 'name', 'acquisitions', 'field_count'. Auto-generated: 'rows', 'columns', 'wells'.

None
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in zarr.json.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. Default is "auto".

'auto'
overwrite bool

If True, overwrite existing Zarr groups. Default is False.

False
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. See write_image for details.

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'
progress bool

Show progress bar when writing dask arrays. Default is False.

False

Returns:

Type Description
Path

Path to the created Plate Zarr group.

Raises:

Type Description
TypeError

If given a model from another OME-Zarr version (e.g. a v05.Image).

ValueError

If image keys don't match plate wells, or if datasets don't match metadata.

FileExistsError

If dest exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Examples:

Write a simple 2x2 plate with auto-generated metadata:

>>> import numpy as np
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import write_plate
>>>
>>> # Create image metadata (same for all fields)
>>> def make_image():
...     return v06.Image(
...         multiscales=[
...             v06.Multiscale.from_dims(
...                 [
...                     DimSpec(name="y", scale=0.5, unit="micrometer"),
...                     DimSpec(name="x", scale=0.5, unit="micrometer"),
...                 ]
...             )
...         ]
...     )
>>>
>>> # Rows, columns, and wells are auto-generated from the images dict!
>>> images = {
...     ("A", "1", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
...     ("A", "2", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
...     ("B", "1", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
...     ("B", "2", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
... }
>>>
>>> result = write_plate("my_plate1.ome.zarr", images)
>>> assert (result / "A" / "1" / "0" / "zarr.json").exists()
>>>
>>> # Or add custom metadata like a name
>>> result2 = write_plate(
...     "my_plate2.ome.zarr",
...     images,
...     plate={"name": "My Experiment"},
...     overwrite=True,
... )
Source code in src/yaozarrs/write/v06/_write.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def write_plate(
    dest: str | PathLike,
    images: Mapping[tuple[str, str, str], ImageWithDatasets],
    *,
    plate: Plate | dict[str, Any] | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...] | Literal["auto"] | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path:
    """Write an OME-Zarr v0.6 Plate group with data.

    This is the high-level function for writing a complete OME-Zarr plate.
    It creates the plate hierarchy (plate/wells/fields), writes metadata,
    and stores image data in a single call.

    The plate structure::

        dest/
        ├── zarr.json          # Plate metadata
        ├── A/
        │   ├── 1/
        │   │   ├── zarr.json  # Well metadata (auto-generated)
        │   │   ├── 0/         # Field 0
        │   │   │   ├── zarr.json  # Image metadata
        │   │   │   └── 0/     # dataset arrays
        │   │   └── 1/         # Field 1 (if multiple fields)
        │   └── 2/
        └── B/
            └── ...

    See Also
    --------
    - [`PlateBuilder`][yaozarrs.write.v06.PlateBuilder]: Builder class for incremental
      well/field writing.
    - [`write_image`][yaozarrs.write.v06.write_image]: Write a single Image group.

    Parameters
    ----------
    dest : str | PathLike
        Destination path for the Plate Zarr group.
    images : Mapping[tuple[str, str, str], ImageWithDatasets]
        Mapping of `{(row, col, fov) -> (image_model, [datasets, ...])}`.
        Each tuple key specifies (row_name, column_name, field_of_view) like
        ("A", "1", "0"). Row and column names are auto-extracted from the keys.
        (Zero-padded column names like "01" are kept as they are.)
    plate : Plate | dict[str, Any] | None, optional
        Optional plate metadata. Can be:
        - None (default): Auto-generate from images dict keys
        - dict: Merge with auto-generated metadata (user values take precedence)
        - Plate: Use as-is (must match images dict)
        Common dict keys: 'name', 'acquisitions', 'field_count'.
        Auto-generated: 'rows', 'columns', 'wells'.
    extra_attributes : dict[str, Any] | None, optional
        Additional attributes to write alongside "ome" in zarr.json.
    writer : "zarr" | "tensorstore" | "auto" | CreateArrayFunc, optional
        Backend to use for writing arrays. Default is "auto".
    overwrite : bool, optional
        If True, overwrite existing Zarr groups. Default is False.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for all arrays. See `write_image` for details.
    shards : tuple[int, ...] | None, optional
        Shard shape for Zarr v3 sharding. Default is None (no sharding).
        When present, shard_shape must be divisible by chunk shape.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec. Default is "blosc-zstd".
    progress : bool, optional
        Show progress bar when writing dask arrays. Default is False.

    Returns
    -------
    Path
        Path to the created Plate Zarr group.

    Raises
    ------
    TypeError
        If given a model from another OME-Zarr version (e.g. a v05.Image).
    ValueError
        If image keys don't match plate wells, or if datasets don't match metadata.
    FileExistsError
        If `dest` exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.

    Examples
    --------
    Write a simple 2x2 plate with auto-generated metadata:

    >>> import numpy as np
    >>> from yaozarrs import DimSpec, v06
    >>> from yaozarrs.write.v06 import write_plate
    >>>
    >>> # Create image metadata (same for all fields)
    >>> def make_image():
    ...     return v06.Image(
    ...         multiscales=[
    ...             v06.Multiscale.from_dims(
    ...                 [
    ...                     DimSpec(name="y", scale=0.5, unit="micrometer"),
    ...                     DimSpec(name="x", scale=0.5, unit="micrometer"),
    ...                 ]
    ...             )
    ...         ]
    ...     )
    >>>
    >>> # Rows, columns, and wells are auto-generated from the images dict!
    >>> images = {
    ...     ("A", "1", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
    ...     ("A", "2", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
    ...     ("B", "1", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
    ...     ("B", "2", "0"): (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
    ... }
    >>>
    >>> result = write_plate("my_plate1.ome.zarr", images)
    >>> assert (result / "A" / "1" / "0" / "zarr.json").exists()
    >>>
    >>> # Or add custom metadata like a name
    >>> result2 = write_plate(
    ...     "my_plate2.ome.zarr",
    ...     images,
    ...     plate={"name": "My Experiment"},
    ...     overwrite=True,
    ... )
    """
    return _write_plate(
        PlateBuilder,
        dest,
        images,
        plate=plate,
        extra_attributes=extra_attributes,
        writer=writer,
        overwrite=overwrite,
        chunks=chunks,
        shards=shards,
        compression=compression,
        progress=progress,
    )

write_bioformats2raw #

write_bioformats2raw(
    dest: str | PathLike,
    images: Mapping[str, ImageWithDatasets],
    *,
    ome_xml: str | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...]
    | Literal["auto"]
    | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path

Write a bioformats2raw-layout OME-Zarr with multiple series.

The bioformats2raw layout is a convention for storing multiple images (series) in a single Zarr hierarchy. It includes a root group with bioformats2raw.layout version, an OME/ group with series metadata, and each series as a separate Image subgroup.

This is the high-level function for writing all series at once. For incremental writes, use Bf2RawBuilder directly.

Writes the following structure:

dest/
├── zarr.json              # root: attributes["ome"]["bioformats2raw.layout"]
├── 0/                     # first series (images["0"])
│   ├── zarr.json          # Image metadata (images["0"][0])
│   ├── 0/                 # first resolution level
│   │   ├── zarr.json      # array metadata
│   │   └── c/             # chunks directory
│   └── 1/                 # second resolution level (if multiscale)
│       ├── zarr.json
│       └── c/
├── 1/                     # second series (images["1"])
│   └── ...
└── OME/
    ├── zarr.json          # attributes["ome"]["series"] = ["0", "1", ...]
    └── METADATA.ome.xml   # optional OME-XML (if ome_xml provided)
See Also

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the root Zarr group.

required
images dict[str, ImageWithDatasets]

Mapping of {series_name -> (image_model, [datasets, ...])}. Each series name (e.g., "0", "1") becomes a subgroup in the root group, with the Image model defining the zarr.json and the datasets providing the data arrays.

required
ome_xml str | None

OME-XML string to store as OME/METADATA.ome.xml. Useful for preserving full metadata from converted files.

None
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in zarr.json.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays.

'auto'
overwrite bool

If True, overwrite existing Zarr groups. Default is False.

False
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. See write_image for details.

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'
progress bool

Show progress bar when writing dask arrays. Default is False.

False

Returns:

Type Description
Path

Path to the root Zarr group.

Raises:

Type Description
TypeError

If given a model from another OME-Zarr version (e.g. a v05.Image).

FileExistsError

If dest exists and overwrite is False.

ValueError

If any series has an invalid name, or mismatched datasets/metadata.

ImportError

If no suitable writer backend is installed.

Examples:

Write a multi-series OME-Zarr:

>>> import numpy as np
>>> from pathlib import Path
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import write_bioformats2raw
>>>
>>> def make_image():
...     return v06.Image(
...         multiscales=[
...             v06.Multiscale.from_dims(
...                 [
...                     DimSpec(name="y", scale=0.5, unit="micrometer"),
...                     DimSpec(name="x", scale=0.5, unit="micrometer"),
...                 ]
...             )
...         ]
...     )
>>> images = {
...     "0": (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
...     "1": (make_image(), [np.zeros((32, 32), dtype=np.uint16)]),
... }
>>> result = write_bioformats2raw("multi_series.zarr", images)
>>> (result / "OME" / "zarr.json").exists()
True
>>> (result / "0" / "zarr.json").exists()
True
Source code in src/yaozarrs/write/v06/_write.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def write_bioformats2raw(
    dest: str | PathLike,
    # mapping of {series_name -> ( Image, [datasets, ...] )}
    images: Mapping[str, ImageWithDatasets],
    *,
    ome_xml: str | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...] | Literal["auto"] | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path:
    """Write a bioformats2raw-layout OME-Zarr with multiple series.

    The bioformats2raw layout is a convention for storing multiple images
    (series) in a single Zarr hierarchy. It includes a root group with
    `bioformats2raw.layout` version, an `OME/` group with series metadata,
    and each series as a separate Image subgroup.

    This is the high-level function for writing all series at once. For
    incremental writes, use [`Bf2RawBuilder`][yaozarrs.write.v06.Bf2RawBuilder]
    directly.

    Writes the following structure:

        dest/
        ├── zarr.json              # root: attributes["ome"]["bioformats2raw.layout"]
        ├── 0/                     # first series (images["0"])
        │   ├── zarr.json          # Image metadata (images["0"][0])
        │   ├── 0/                 # first resolution level
        │   │   ├── zarr.json      # array metadata
        │   │   └── c/             # chunks directory
        │   └── 1/                 # second resolution level (if multiscale)
        │       ├── zarr.json
        │       └── c/
        ├── 1/                     # second series (images["1"])
        │   └── ...
        └── OME/
            ├── zarr.json          # attributes["ome"]["series"] = ["0", "1", ...]
            └── METADATA.ome.xml   # optional OME-XML (if ome_xml provided)

    See Also
    --------
    - [`Bf2RawBuilder`][yaozarrs.write.v06.Bf2RawBuilder] : Builder class for
      incremental series writing.
    - [`write_image`][yaozarrs.write.v06.write_image] : Write a single Image group.

    Parameters
    ----------
    dest : str | PathLike
        Destination path for the root Zarr group.
    images : dict[str, ImageWithDatasets]
        Mapping of `{series_name -> (image_model, [datasets, ...])}`.
        Each series name (e.g., "0", "1") becomes a subgroup in the root group, with
        the Image model defining the zarr.json and the datasets providing the data
        arrays.
    ome_xml : str | None, optional
        OME-XML string to store as `OME/METADATA.ome.xml`.
        Useful for preserving full metadata from converted files.
    extra_attributes : dict[str, Any] | None, optional
        Additional attributes to write alongside "ome" in zarr.json.
    writer : "zarr" | "tensorstore" | "auto" | CreateArrayFunc, optional
        Backend to use for writing arrays.
    overwrite : bool, optional
        If True, overwrite existing Zarr groups. Default is False.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for all arrays. See `write_image` for details.
    shards : tuple[int, ...] | None, optional
        Shard shape for Zarr v3 sharding. Default is None (no sharding).
        When present, shard_shape must be divisible by chunk shape.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec. Default is "blosc-zstd".
    progress : bool, optional
        Show progress bar when writing dask arrays. Default is False.

    Returns
    -------
    Path
        Path to the root Zarr group.

    Raises
    ------
    TypeError
        If given a model from another OME-Zarr version (e.g. a v05.Image).
    FileExistsError
        If `dest` exists and `overwrite` is False.
    ValueError
        If any series has an invalid name, or mismatched datasets/metadata.
    ImportError
        If no suitable writer backend is installed.

    Examples
    --------
    Write a multi-series OME-Zarr:

    >>> import numpy as np
    >>> from pathlib import Path
    >>> from yaozarrs import DimSpec, v06
    >>> from yaozarrs.write.v06 import write_bioformats2raw
    >>>
    >>> def make_image():
    ...     return v06.Image(
    ...         multiscales=[
    ...             v06.Multiscale.from_dims(
    ...                 [
    ...                     DimSpec(name="y", scale=0.5, unit="micrometer"),
    ...                     DimSpec(name="x", scale=0.5, unit="micrometer"),
    ...                 ]
    ...             )
    ...         ]
    ...     )
    >>> images = {
    ...     "0": (make_image(), [np.zeros((64, 64), dtype=np.uint16)]),
    ...     "1": (make_image(), [np.zeros((32, 32), dtype=np.uint16)]),
    ... }
    >>> result = write_bioformats2raw("multi_series.zarr", images)
    >>> (result / "OME" / "zarr.json").exists()
    True
    >>> (result / "0" / "zarr.json").exists()
    True
    """
    return _write_bioformats2raw(
        Bf2RawBuilder,
        dest,
        images,
        ome_xml=ome_xml,
        extra_attributes=extra_attributes,
        writer=writer,
        overwrite=overwrite,
        chunks=chunks,
        shards=shards,
        compression=compression,
        progress=progress,
    )

write_scene #

write_scene(
    dest: str | PathLike,
    scene: Scene,
    images: Mapping[str, ImageWithDatasets],
    *,
    labels: Mapping[str, LabelsWithDatasets] | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...]
    | Literal["auto"]
    | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path

Write an OME-Zarr v0.6 scene: images that share a spatial relationship.

The scene group holds the Scene metadata (transformations between the coordinate systems of its images, and optionally coordinate systems of its own), and each image is written as a subgroup at its path:

dest/
├── zarr.json          # attributes["ome"]["scene"]
├── tile_0/            # images["tile_0"]
│   ├── zarr.json      # Image metadata
│   └── 0/             # dataset arrays
└── tile_1/
    └── ...

Before anything is written, the scene's references are checked: every transformation input/output with a path must name one of images, with a coordinate system of that name, the transformation's dimensions must fit the coordinate systems it links, and the coordinate systems of the scene and its images must form one connected graph. Label images given in labels are checked (and can be referenced) like the images. A reference to any other multiscale image inside one of images (such as a label image you write afterwards with a LabelsBuilder) is allowed, but not checked, as that image isn't written here; nor is the graph, in that case.

chunks, shards and compression apply to every image. If the images have different numbers of dimensions, use chunks="auto" (the default) or None, or write them with a SceneBuilder, which takes these settings per image.

With overwrite=True, an existing store at dest is replaced once the checks pass.

Transformation parameters stored in Zarr arrays (e.g. an affine with a path) are not written by this function: write them below dest afterwards (the spec recommends a coordinateTransformations group).

See Also

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the scene Zarr group.

required
scene Scene

OME-Zarr Scene metadata model.

required
images Mapping[str, ImageWithDatasets]

Mapping of {path -> (image_model, [datasets, ...])}. Each path (e.g. "tile_0", or "tiles/0") becomes an Image subgroup of the scene group.

required
labels Mapping[str, Mapping[str, tuple[LabelImage, ArrayOrPyramid]]] | None

Label images to write alongside the images, as {image path -> {label name -> (LabelImage, datasets)}} (see write_image). Each one is written to dest/{image path}/labels/{label name}/, and the scene may refer to it there. Default is None.

None
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in the scene's zarr.json.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend to use for writing arrays. Default is "auto".

'auto'
overwrite bool

If True, overwrite existing Zarr groups. Default is False.

False
chunks tuple[int, ...] | 'auto' | None

Chunk shape for all arrays. See write_image for details.

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'
progress bool

Show progress bar when writing dask arrays. Default is False.

False

Returns:

Type Description
Path

Path to the scene Zarr group.

Raises:

Type Description
TypeError

If given a model from another OME-Zarr version (e.g. a v05.Image).

ValueError

If the scene references an image (or coordinate system) that isn't in images, if its coordinate systems aren't all connected, if any image (or label image) has mismatched datasets/metadata, or if labels names an image that isn't in images.

NotImplementedError

If any Image has multiple multiscales.

FileExistsError

If dest exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Examples:

Two tiles, placed side by side in a "world" coordinate system:

>>> import numpy as np
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import write_scene
>>>
>>> def make_image():
...     dims = [
...         DimSpec(name="y", scale=0.5, unit="micrometer"),
...         DimSpec(name="x", scale=0.5, unit="micrometer"),
...     ]
...     return v06.Image(multiscales=[v06.Multiscale.from_dims(dims)])
>>>
>>> world = v06.CoordinateSystem(
...     name="world",
...     axes=[
...         v06.Axis(name="y", type="space", unit="micrometer"),
...         v06.Axis(name="x", type="space", unit="micrometer"),
...     ],
... )
>>> scene = v06.Scene(
...     scene=v06.SceneDef(
...         coordinateSystems=[world],
...         coordinateTransformations=[
...             v06.TranslationTransformation(
...                 translation=[0, 32 * i],
...                 input={"path": f"tile_{i}", "name": "intrinsic"},
...                 output={"name": "world"},
...             )
...             for i in range(2)
...         ],
...     )
... )
>>> images = {
...     f"tile_{i}": (make_image(), np.zeros((64, 64), dtype=np.uint16))
...     for i in range(2)
... }
>>> result = write_scene("my_scene.zarr", scene, images)
>>> (result / "tile_1" / "zarr.json").exists()
True
Source code in src/yaozarrs/write/v06/_write.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
def write_scene(
    dest: str | PathLike,
    scene: Scene,
    images: Mapping[str, ImageWithDatasets],
    *,
    labels: Mapping[str, LabelsWithDatasets] | None = None,
    extra_attributes: dict[str, Any] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    chunks: tuple[int, ...] | Literal["auto"] | None = "auto",
    shards: tuple[int, ...] | None = None,
    compression: CompressionName = "blosc-zstd",
    progress: bool = False,
) -> Path:
    """Write an OME-Zarr v0.6 scene: images that share a spatial relationship.

    The scene group holds the [`Scene`][yaozarrs.v06.Scene] metadata (transformations
    between the coordinate systems of its images, and optionally coordinate systems
    of its own), and each image is written as a subgroup at its path:

        dest/
        ├── zarr.json          # attributes["ome"]["scene"]
        ├── tile_0/            # images["tile_0"]
        │   ├── zarr.json      # Image metadata
        │   └── 0/             # dataset arrays
        └── tile_1/
            └── ...

    Before anything is written, the scene's references are checked: every
    transformation `input`/`output` with a `path` must name one of `images`, with a
    coordinate system of that `name`, the transformation's dimensions must fit the
    coordinate systems it links, and the coordinate systems of the scene and its
    images must form one connected graph.  Label images given in `labels` are checked
    (and can be referenced) like the images.  A reference to any other multiscale
    image *inside* one of `images` (such as a label image you write afterwards with a
    [`LabelsBuilder`][yaozarrs.write.v06.LabelsBuilder]) is allowed, but not checked,
    as that image isn't written here; nor is the graph, in that case.

    `chunks`, `shards` and `compression` apply to every image.  If the images have
    different numbers of dimensions, use `chunks="auto"` (the default) or `None`, or
    write them with a [`SceneBuilder`][yaozarrs.write.v06.SceneBuilder], which takes
    these settings per image.

    With `overwrite=True`, an existing store at `dest` is replaced once the checks pass.

    Transformation parameters stored in Zarr arrays (e.g. an `affine` with a `path`)
    are not written by this function: write them below `dest` afterwards (the spec
    recommends a `coordinateTransformations` group).

    See Also
    --------
    - [`SceneBuilder`][yaozarrs.write.v06.SceneBuilder] : Builder class for
      incremental image writing.
    - [`write_image`][yaozarrs.write.v06.write_image] : Write a single Image group.

    Parameters
    ----------
    dest : str | PathLike
        Destination path for the scene Zarr group.
    scene : Scene
        OME-Zarr Scene metadata model.
    images : Mapping[str, ImageWithDatasets]
        Mapping of `{path -> (image_model, [datasets, ...])}`.  Each path (e.g.
        "tile_0", or "tiles/0") becomes an Image subgroup of the scene group.
    labels : Mapping[str, Mapping[str, tuple[LabelImage, ArrayOrPyramid]]] | None
        Label images to write alongside the images, as `{image path -> {label name ->
        (LabelImage, datasets)}}` (see `write_image`).  Each one is written to
        `dest/{image path}/labels/{label name}/`, and the scene may refer to it there.
        Default is None.
    extra_attributes : dict[str, Any] | None, optional
        Additional attributes to write alongside "ome" in the scene's zarr.json.
    writer : "zarr" | "tensorstore" | "auto" | CreateArrayFunc, optional
        Backend to use for writing arrays. Default is "auto".
    overwrite : bool, optional
        If True, overwrite existing Zarr groups. Default is False.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape for all arrays. See `write_image` for details.
    shards : tuple[int, ...] | None, optional
        Shard shape for Zarr v3 sharding. Default is None (no sharding).
        When present, shard_shape must be divisible by chunk shape.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec. Default is "blosc-zstd".
    progress : bool, optional
        Show progress bar when writing dask arrays. Default is False.

    Returns
    -------
    Path
        Path to the scene Zarr group.

    Raises
    ------
    TypeError
        If given a model from another OME-Zarr version (e.g. a v05.Image).
    ValueError
        If the scene references an image (or coordinate system) that isn't in
        `images`, if its coordinate systems aren't all connected, if any image (or
        label image) has mismatched datasets/metadata, or if `labels` names an image
        that isn't in `images`.
    NotImplementedError
        If any Image has multiple multiscales.
    FileExistsError
        If `dest` exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.

    Examples
    --------
    Two tiles, placed side by side in a "world" coordinate system:

    >>> import numpy as np
    >>> from yaozarrs import DimSpec, v06
    >>> from yaozarrs.write.v06 import write_scene
    >>>
    >>> def make_image():
    ...     dims = [
    ...         DimSpec(name="y", scale=0.5, unit="micrometer"),
    ...         DimSpec(name="x", scale=0.5, unit="micrometer"),
    ...     ]
    ...     return v06.Image(multiscales=[v06.Multiscale.from_dims(dims)])
    >>>
    >>> world = v06.CoordinateSystem(
    ...     name="world",
    ...     axes=[
    ...         v06.Axis(name="y", type="space", unit="micrometer"),
    ...         v06.Axis(name="x", type="space", unit="micrometer"),
    ...     ],
    ... )
    >>> scene = v06.Scene(
    ...     scene=v06.SceneDef(
    ...         coordinateSystems=[world],
    ...         coordinateTransformations=[
    ...             v06.TranslationTransformation(
    ...                 translation=[0, 32 * i],
    ...                 input={"path": f"tile_{i}", "name": "intrinsic"},
    ...                 output={"name": "world"},
    ...             )
    ...             for i in range(2)
    ...         ],
    ...     )
    ... )
    >>> images = {
    ...     f"tile_{i}": (make_image(), np.zeros((64, 64), dtype=np.uint16))
    ...     for i in range(2)
    ... }
    >>> result = write_scene("my_scene.zarr", scene, images)
    >>> (result / "tile_1" / "zarr.json").exists()
    True
    """
    builder = SceneBuilder(
        dest,
        scene,
        extra_attributes=extra_attributes,
        writer=writer,
        chunks=chunks,
        shards=shards,
        overwrite=overwrite,
        compression=compression,
    )
    labels = labels or {}
    if unknown := sorted(set(labels) - set(images)):
        raise ValueError(
            f"labels: {unknown} are not among the scene's images ({sorted(images)})"
        )
    # (check everything first, so a bad image doesn't leave a partial scene behind)
    seen: list[str] = []
    for path, (image_model, datasets) in images.items():
        builder._check_image(
            path, image_model, datasets, others=seen, labels=labels.get(path)
        )
        seen.append(path)
    all_images: dict[str, Image] = {}
    for path, (image, _) in images.items():
        all_images[path] = image
        all_images.update(_label_paths(path, labels.get(path)))
    _check_scene(scene, all_images)

    builder._ensure_initialized()
    for path, (image_model, datasets) in images.items():
        builder.write_image(
            path, image_model, datasets, labels=labels.get(path), progress=progress
        )

    return builder.root_path

prepare_image #

prepare_image(
    dest: str | PathLike,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
    *,
    extra_attributes: dict[str, Any] | None = None,
    chunks: tuple[int, ...]
    | Literal["auto"]
    | None = "auto",
    shards: tuple[int, ...] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
) -> tuple[Path, dict[str, Any]]

Create OME-Zarr v0.6 Image structure and return array handles for writing.

This is a lower-level function that creates the Zarr group hierarchy and empty arrays, but does not write data. Use this when you need custom control over how data is written (e.g., chunk-by-chunk streaming, parallel writes).

To write data immediately, use write_image instead.

See Also

Parameters:

Name Type Description Default
dest str | PathLike

Destination path for the Zarr group.

required
image Image

OME-Zarr Image metadata model.

required
datasets ShapeAndDTypeOrPyramid

Shape and dtype specification(s) for each dataset, as (shape, dtype) tuples. Can be:

  • Single (shape, dtype): For one dataset, no wrapping needed
  • Sequence of (shape, dtype): For multiple datasets (multiscale pyramid)

Must match the number and order of image.multiscales[0].datasets.

required
extra_attributes dict[str, Any] | None

Additional attributes to write alongside "ome" in zarr.json.

None
chunks tuple[int, ...] | 'auto' | None

Chunk shape. See write_image for details.

'auto'
shards tuple[int, ...] | None

Shard shape for Zarr v3 sharding. Default is None (no sharding). When present, shard_shape must be divisible by chunk shape.

None
writer 'zarr' | 'tensorstore' | 'auto' | CreateArrayFunc

Backend for creating arrays. When you specify "zarr" or "tensorstore", the return type is narrowed to the specific array type.

'auto'
overwrite bool

If True, overwrite existing Zarr group. Default is False.

False
compression 'blosc-zstd' | 'blosc-lz4' | 'zstd' | 'none'

Compression codec. Default is "blosc-zstd".

'blosc-zstd'

Returns:

Type Description
tuple[Path, dict[str, AnyZarrArray]]

A tuple of (path, arrays) where arrays maps dataset paths (e.g., "0") to array objects. The array type depends on the writer:

  • writer="zarr": Returns dict[str, zarr.Array]
  • writer="tensorstore": Returns dict[str, tensorstore.TensorStore]
  • writer="auto": Returns whichever is available

Raises:

Type Description
TypeError

If given a model from another OME-Zarr version (e.g. a v05.Image).

NotImplementedError

If the Image model has multiple multiscales.

ValueError

If the number of dataset specs doesn't match the metadata.

FileExistsError

If dest exists and overwrite is False.

ImportError

If no suitable writer backend is installed.

Examples:

Create arrays and write data in chunks - single dataset, no list needed:

>>> import numpy as np
>>> from yaozarrs import DimSpec, v06
>>> from yaozarrs.write.v06 import prepare_image
>>> image = v06.Image(
...     multiscales=[
...         v06.Multiscale.from_dims(
...             [
...                 DimSpec(name="y", scale=0.5, unit="micrometer"),
...                 DimSpec(name="x", scale=0.5, unit="micrometer"),
...             ]
...         )
...     ]
... )
>>> # Prepare with just shape/dtype (no data yet) - no list wrapping!
>>> path, arrays = prepare_image("prepared.zarr", image, ((64, 64), "uint16"))
>>> arrays["0"][:] = np.zeros((64, 64), dtype=np.uint16)
>>> assert path.exists()
Source code in src/yaozarrs/write/v06/_write.py
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
def prepare_image(
    dest: str | PathLike,
    image: Image,
    datasets: ShapeAndDTypeOrPyramid,
    *,
    extra_attributes: dict[str, Any] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] | None = "auto",
    shards: tuple[int, ...] | None = None,
    writer: ZarrWriter = "auto",
    overwrite: bool = False,
    compression: CompressionName = "blosc-zstd",
) -> tuple[Path, dict[str, Any]]:
    """Create OME-Zarr v0.6 Image structure and return array handles for writing.

    This is a lower-level function that creates the Zarr group hierarchy and
    empty arrays, but does not write data. Use this when you need custom control
    over how data is written (e.g., chunk-by-chunk streaming, parallel writes).

    To write data immediately, use `write_image` instead.

    See Also
    --------
    - [`write_image`][yaozarrs.write.v06.write_image] : High-level function that writes
      data immediately.
    - [`Bf2RawBuilder.prepare`][yaozarrs.write.v06.Bf2RawBuilder.prepare] : Prepare
      multiple series at once.

    Parameters
    ----------
    dest : str | PathLike
        Destination path for the Zarr group.
    image : Image
        OME-Zarr Image metadata model.
    datasets : ShapeAndDTypeOrPyramid
        Shape and dtype specification(s) for each dataset, as `(shape, dtype)`
        tuples. Can be:

        - Single `(shape, dtype)`: For one dataset, no wrapping needed
        - Sequence of `(shape, dtype)`: For multiple datasets (multiscale pyramid)

        Must match the number and order of `image.multiscales[0].datasets`.
    extra_attributes : dict[str, Any] | None, optional
        Additional attributes to write alongside "ome" in zarr.json.
    chunks : tuple[int, ...] | "auto" | None, optional
        Chunk shape. See `write_image` for details.
    shards : tuple[int, ...] | None, optional
        Shard shape for Zarr v3 sharding. Default is None (no sharding).
        When present, shard_shape must be divisible by chunk shape.
    writer : "zarr" | "tensorstore" | "auto" | CreateArrayFunc, optional
        Backend for creating arrays. When you specify "zarr" or "tensorstore",
        the return type is narrowed to the specific array type.
    overwrite : bool, optional
        If True, overwrite existing Zarr group. Default is False.
    compression : "blosc-zstd" | "blosc-lz4" | "zstd" | "none", optional
        Compression codec. Default is "blosc-zstd".

    Returns
    -------
    tuple[Path, dict[str, AnyZarrArray]]
        A tuple of (path, arrays) where `arrays` maps dataset paths (e.g., "0")
        to array objects. The array type depends on the writer:

        - `writer="zarr"`: Returns `dict[str, zarr.Array]`
        - `writer="tensorstore"`: Returns `dict[str, tensorstore.TensorStore]`
        - `writer="auto"`: Returns whichever is available

    Raises
    ------
    TypeError
        If given a model from another OME-Zarr version (e.g. a v05.Image).
    NotImplementedError
        If the Image model has multiple multiscales.
    ValueError
        If the number of dataset specs doesn't match the metadata.
    FileExistsError
        If `dest` exists and `overwrite` is False.
    ImportError
        If no suitable writer backend is installed.

    Examples
    --------
    Create arrays and write data in chunks - single dataset, no list needed:

    >>> import numpy as np
    >>> from yaozarrs import DimSpec, v06
    >>> from yaozarrs.write.v06 import prepare_image
    >>> image = v06.Image(
    ...     multiscales=[
    ...         v06.Multiscale.from_dims(
    ...             [
    ...                 DimSpec(name="y", scale=0.5, unit="micrometer"),
    ...                 DimSpec(name="x", scale=0.5, unit="micrometer"),
    ...             ]
    ...         )
    ...     ]
    ... )
    >>> # Prepare with just shape/dtype (no data yet) - no list wrapping!
    >>> path, arrays = prepare_image("prepared.zarr", image, ((64, 64), "uint16"))
    >>> arrays["0"][:] = np.zeros((64, 64), dtype=np.uint16)
    >>> assert path.exists()
    """
    return _prepare_image(
        Path(dest),
        image,
        datasets,
        image_type=Image,
        extra_attributes=extra_attributes,
        chunks=chunks,
        shards=shards,
        writer=writer,
        overwrite=overwrite,
        compression=compression,
    )

Types#

See also the types shared by both write modules.

ImageWithDatasets module-attribute #

ImageWithDatasets: TypeAlias = tuple[Image, ArrayOrPyramid]

A v0.6 Image model, with its array data (one array per dataset).

LabelsWithDatasets module-attribute #

LabelsWithDatasets: TypeAlias = Mapping[
    str, tuple[LabelImage, ArrayOrPyramid]
]

The label images of an image, with their data: {name: (LabelImage, data)}.

LabelsWithSpecs module-attribute #

The label images of an image, with the (shape, dtype) of their datasets.

_Default #

Sentinel for a per-image setting that defaults to the builder's.

BUILDER class-attribute instance-attribute #

BUILDER = 'builder'

Use the setting passed to the builder.