Skip to content

brainhops.io.images.zarr

Zarr and OME-Zarr images.

A plain Zarr array is read as a ZarrImage without a world geometry, and an OME-Zarr group, which stores a pyramid of resolution levels with its metadata, is read as an OmeZarrImage. The metadata is parsed by abczarr and normalized to OME-NGFF 0.6, the version that adopted RFC-5, whatever version the store uses.

Coordinate systems

OME-NGFF 0.6 names its coordinate systems and gives each of them a list of axes, with a name, a type such as space or time, and a unit such as micrometer. Every named system of a multiscale becomes a brainhops [CoordinateSystem][brainhops.datamodel.systems.CoordinateSystem] of the same name, whose axes are sorted into the brainhops order: the spatial axes first, as x, y and z, then time, channels and the other axes. Each system is sorted on its own, so two systems that list the same axes in different orders end up with the same brainhops order. The levels map their voxels onto the intrinsic system, which every level names as its output, and the transformations declared on the whole multiscale carry the intrinsic system to the other systems. They become the placements in transformations, whose last entry is the preferred one.

OME-NGFF 0.6 names a system by any non-empty string, unique among the systems of its multiscale, and refers to a system of another group by the path of that group and the name (ngff-spec tag 0.6 at 89da1da, index.md, sections "coordinateSystems metadata" and "Constraints"). brainhops tells two systems apart by their name and axes, so the systems of a pyramid that is not in the root of its hierarchy are named after the path of its group, followed by // and their OME name, as in labels/cells//physical. A Zarr node name is never empty and never holds a /, so // never occurs in a group path, and the name splits back unambiguously. The systems of the root group keep their OME names, and one whose name holds // is preceded by //. A Zarr group does not know its path in its hierarchy, so the reader that opened the root gives it to OmeZarrImage as group. The writer writes the systems of that group under their OME names.

Transformations

A transformation maps points of its input system to points of its output system, in OME-NGFF 0.6 as in brainhops (ngff-spec, branch 0.6 at 89da1da, index.md, section "coordinateTransformations metadata"). Its parameters follow the order in which its systems list their axes, which for an image is the order of the array dimensions, and they are reordered when they are read (same file, sections "Additional details" and "Matrix transformations"). The types are read as follows.

OME-NGFF 0.6 brainhops
identity Identity
scale Scaling
translation Translation
rotation Rotation
affine Affine
mapAxis Permutation
projectAxis Projection
sequence Sequence
displacements, coordinates the field of the group it names
bijection Bijection
byDimension Affine, or subspace parts

When the two systems of a transformation sort their axes differently, a type that cannot express the reordering, such as a scale, is followed by a Permutation, so that the result stays exact. A byDimension whose parts are not all affine becomes a Sequence of SubspaceTransformation objects. Version 0.6 also allows a transformation of the multiscale to end in the intrinsic system instead of starting there, and such a transformation is read as its inverse, unless it drops axes and so has no inverse, in which case it is refused.

A field transformation, displacements or coordinates, names a multiscale group that holds the vectors, with an axis of type displacement or coordinate before the spatial axes. Component i of a vector belongs to axis i of the output system as OME lists it, so the components are reordered with the axes of that system. Drafts of version 0.6 named the array of the field instead of a group, and such a field is read too.

Voxel centres

An integer index is the centre of a voxel. OME-NGFF 0.6 states this convention in its section "Coordinate convention", and brainhops uses the same one, as NIfTI and ITK do, so the transformations are read and written without a shift of half a voxel. Versions 0.4 and 0.5 do not state a convention. They are read with the same one, which agrees with the note of version 0.6 that a level downsampled by a factor f is translated by (f - 1) / 2 base voxels, and with ngff-zarr (5187d94), whose module ngff_transform_to_itk_transform states that both OME and ITK put the centre of a voxel at its integer index. Whether every writer of versions 0.4 and 0.5 follows it is not verified.

Building a pyramid

The writer writes the levels that a pyramid holds, and nothing more. An image that has a single resolution gets its coarser levels when it is converted to OmeZarrImage, which happens when it is saved under a name that ends with .ome.zarr. By default, the conversion builds as many levels as the rules of Multiscale.with_scales allow, by averaging blocks of 2 voxels along each spatial axis until the axes have 32 voxels or fewer. The keyword nscales= takes the values of the argument of with_scales, as in image.to(OmeZarrImage, nscales=4) or image.to(OmeZarrImage, nscales=[2, 4]), and nscales=1 keeps the single level. The keywords factor=, mode=, align=, min_size= and strict= are those of with_scales, which OmeZarrImage inherits from MultiScaleImage, and which builds the levels of a pyramid afterwards. The axes are those that the writer stores, so they are selected by the names of axes.

With the default alignment "exact", a level is placed by the rule of version 0.6 for a level downsampled by a factor f, which puts its voxel i at the base voxel f * i + (f - 1) / 2. The alignments "edges" and "centers" place it by the actual scale of each axis, as brainhops._core.pyramids explains, and every level is still written as a scale and a translation. OmeZarrField builds the levels of a field in the same way, and builds its metadata again when it is written.

Every level is written with the chunks of the finest level, which shrink to the shape of a level that is smaller. These chunks are those given to save, or else those of the store or of the Dask array that the finest level reads, or else those that the writer chooses for the finest level. A coarser level that is a Dask array is rechunked to them before it is written, and the shards, when the levels are sharded, follow the same rule.

Limitations

The draft type inverseOf was removed before version 0.6 and is refused. A byDimension is read only when its parts are affine, or when each part writes the axes that it reads. A transformation of the multiscale that refers to a system of another group, such as a labels image, is skipped, since labels and scenes are not read yet (items 132 and 133 of the tensions in spec/design/format-records.md), and only the first multiscale of a group is read. A scale or a translation whose values are stored in an array named by path is refused, since the schema of version 0.6 requires them inline, as those of versions 0.4 and 0.5 do. Only the drafts 0.6.dev1 and 0.6.dev2 allowed it, and they are still read. An affine or a rotation may name an array of parameters (item 134).

The writer encodes the geometry from the levels and the placements, and does not keep the metadata as it was read, so a pyramid that is saved unchanged does not keep the bytes of its metadata (item 130). It writes every placement that reduces to an affine as a scale, a translation, a rotation, an affine or a sequence of them, so that a placement read as an inverse is written in the forward direction. It refuses the other placements, such as a projection, a bijection or a field, with a WriterError. Version 0.6 only allows a scale, an identity, or a scale followed by a translation in the dataset of a level. The writer writes the geometry of a level that only scales and translates each axis in that form, whatever its spelling. When a level also rotates, shears or flips its axes, the writer splits the geometry of every level into a positive scale and a translation, which the dataset of the level holds, and a placement that every level shares, which goes before the placements of the pyramid (issue #447, item 131). OME-NGFF 0.6 makes the intrinsic system physical, so the dataset of a level holds the size of its voxels and the position of its voxels in physical units. The size of a voxel along an axis is the length of the column of that axis in the linear part of the geometry, which is the distance between two neighbouring voxels along the axis, even when the axes are sheared. A polar or a QR decomposition would not give that distance. The shared placement holds the rest of the geometry of the finest level: its linear part with columns of unit length, which only rotates, shears or flips the axes, and the position of its first voxel. It is therefore a map between two physical spaces. The translation of a coarser level is the offset of its first voxel from that of the finest level, which is (f - 1) / 2 voxels of the finest level for a level downsampled by a factor f. A single level is split in the same way, so that a rotated image with voxels of 0.5 mm is written with a scale of 0.5 and a rotation.

The split exists when every level is rotated, sheared and flipped in the same way, so that the levels differ only by a positive scale and a translation along each axis. The columns of their matrices are compared with a relative tolerance of 1e-6, which accepts geometries stored in single precision. Levels whose geometries differ in any other way, such as levels that flip different axes, are refused with a WriterError. A flip is never written as a negative scale, which the schema of version 0.6 refuses, but as an affine (item 135). A pyramid that is read back keeps the geometry of each level, but not necessarily the way in which it was split between the level and the placements.

Classes

ZarrMetadata magic

ZarrMetadata(
    name: str | None = None,
    description: str | None = None,
    history: tuple[str, ...] | None = None,
    generated_by: tuple[GeneratedBy, ...] | None = None,
    creation_time: datetime | None = None,
    sources: tuple[str, ...] | None = None,
    space: SpaceEnum | str | None = None,
    intent: IntentEnum | str | None = None,
    repetition_time: float | None = None,
    echo_time: float | None = None,
    inversion_time: float | None = None,
    flip_angle: float | None = None,
    magnetic_field_strength: float | None = None,
    manufacturer: Manufacturer | str | None = None,
    manufacturers_model_name: str | None = None,
    institution_name: str | None = None,
    acquisition_time: datetime | None = None,
    phase_encoding_direction: EncodingDirection
    | None = None,
    total_readout_time: float | None = None,
    effective_echo_spacing: float | None = None,
    slice_encoding_direction: EncodingDirection
    | None = None,
    slice_timing: tuple[float, ...] | None = None,
    multiband_acceleration_factor: int | None = None,
    bvalues: tuple[float, ...] | None = None,
    bvectors: tuple[tuple[float, float, float], ...]
    | None = None,
    display_range: tuple[float, float] | None = None,
    channels: tuple[Channel, ...] | None = None,
    data_unit: Unit | str | None = None,
    dtype: dtype | None = None,
    scale_slope: float | None = None,
    scale_intercept: float | None = None,
    objective_magnification: float | None = None,
    objective_numerical_aperture: float | None = None,
    illumination_type: IlluminationType | str | None = None,
    contrast_method: ContrastMethod | str | None = None,
    moving: str | None = None,
    fixed: str | None = None,
    input_space: SpaceEnum | str | None = None,
    output_space: SpaceEnum | str | None = None,
    raw: NoRepr[ZarrRaw | None] = None,
    *,
    extra: dict[str, Any] = Factory(),
)

Bases: ZarrReader, MetadataFormat

Metadata of a Zarr array, which is the document of the array.

The metadata of a Zarr array is the document that its store keeps, zarr.json in Zarr version 3, or .zarray and .zattrs in version 2, held as a ZarrRaw record. ZarrImage uses that record as the base of the document that it writes. Reading the metadata never reads a chunk, so a store whose chunks were removed can still be read. The metadata keeps no handle on the store.

A store is a directory or a remote prefix of keys, not a file, so the metadata is read from a store location with [from_store][] or from an opened array with from_node, and bytes and streams are refused. The metadata writes nothing by itself: the documents are written by the image, with its chunks.

Parameters:

Name Type Description Default
name str | None

A short name for the data.

None
description str | None

A free-text description.

None
history tuple[str, ...] | None

The commands that produced the data, oldest first.

None
generated_by tuple[GeneratedBy, ...] | None

The programs that produced the data.

None
creation_time datetime | None

When the file was created.

None
sources tuple[str, ...] | None

Files the data was derived from (BIDS provenance).

None
space SpaceEnum | str | None

The label of the world space ('MNI152NLin6Asym', 'scanner', ...; a known one is a SpaceEnum); the space itself is geometry.

None
intent IntentEnum | str | None

What the values are, as a NIfTI intent name (a known one is an IntentEnum).

None
repetition_time float | None

Repetition time, in seconds.

None
echo_time float | None

Echo time, in seconds.

None
inversion_time float | None

Inversion time, in seconds.

None
flip_angle float | None

Flip angle, in degrees.

None
magnetic_field_strength float | None

Nominal field strength, in tesla.

None
manufacturer Manufacturer | str | None

Manufacturer of the equipment (a known one is a Manufacturer).

None
manufacturers_model_name str | None

Model name of the equipment.

None
institution_name str | None

Institution responsible for the equipment.

None
acquisition_time datetime | None

When the acquisition started.

None
phase_encoding_direction EncodingDirection | None

Phase-encoding direction: a unit vector. By default in voxel axes (BIDS 'j-' is accepted).

None
total_readout_time float | None

Total readout time, in seconds.

None
effective_echo_spacing float | None

Effective echo spacing, in seconds.

None
slice_encoding_direction EncodingDirection | None

Slice-encoding direction: a unit vector, by default in voxel axes (BIDS 'k' is accepted)."

None
slice_timing tuple[float, ...] | None

Acquisition time of each slice, in seconds, along the slice encoding direction.

None
multiband_acceleration_factor int | None

Multiband acceleration factor.

None
bvalues tuple[float, ...] | None

One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."

None
bvectors tuple[tuple[float, float, float], ...] | None

One unit gradient direction per index along the time axis, in world (RAS) coordinates."

None
display_range tuple[float, float] | None

Display window (min, max).

None
channels tuple[Channel, ...] | None

One description per channel. The descriptions run along the axes of type channel only. The entries of a component axis, such as a vector or a tensor axis, are described by the type, the valence, the layout and the frame of that axis, so a change of frame, which only re-expresses the values of component axes, keeps these descriptions.

None
data_unit Unit | str | None

Unit of the data values: a Unit whenever the units module parses the name ('a.u.', 'mm/s', 'HU'), and the name itself, as a string, when it does not, so that a file with an odd unit still reads. Formats write it as its symbol (Unit.symbol), which parses back to the same unit.

None
dtype dtype | None

The element type of the data as stored, in native byte order. It may differ from the type of the loaded array: a scaled integer file loads as floating-point values. An override given to save or to consolidate takes precedence over it.

None
scale_slope float | None

The slope of the intensity scaling: a value is stored * scale_slope + scale_intercept. None means no scaling.

None
scale_intercept float | None

The intercept of the intensity scaling (see scale_slope). None means no intercept.

None
objective_magnification float | None

Nominal magnification of the objective.

None
objective_numerical_aperture float | None

Numerical aperture of the objective.

None
illumination_type IlluminationType | str | None

Illumination type (a known one is an IlluminationType).

None
contrast_method ContrastMethod | str | None

Contrast method (a known one is a ContrastMethod).

None
moving str | None

The moving image of a registration (file reference).

None
fixed str | None

The fixed image of a registration (file reference).

None
input_space SpaceEnum | str | None

Label of the space a transformation maps from.

None
output_space SpaceEnum | str | None

Label of the space a transformation maps to.

None
raw NoRepr[ZarrRaw | None]

The record of the array, or None for metadata without a record.

None
extra dict[str, Any]

Free-form keys the vocabulary does not cover, copied into any free-form store a format has."

Factory()

Attributes

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

name class-attribute instance-attribute
name: Annotated[str | None, Scoped(FILE)] = None

A short name for the data.

description class-attribute instance-attribute
description: Annotated[
    str | None, Bids(Description), Scoped(FILE)
] = None

A free-text description.

history class-attribute instance-attribute
history: Annotated[tuple[str, ...] | None, Scoped(FILE)] = (
    None
)

The commands that produced the data, oldest first.

generated_by class-attribute instance-attribute
generated_by: Annotated[
    tuple[GeneratedBy, ...] | None,
    Bids(GeneratedBy),
    Scoped(FILE),
] = None

The programs that produced the data.

creation_time class-attribute instance-attribute
creation_time: Annotated[datetime | None, Scoped(FILE)] = (
    None
)

When the file was created.

sources class-attribute instance-attribute
sources: Annotated[
    tuple[str, ...] | None, Bids(Sources), Scoped(FILE)
] = None

Files the data was derived from (BIDS provenance).

space class-attribute instance-attribute
space: Annotated[
    SpaceEnum | str | None,
    Bids(SpatialReference),
    Scoped(FILE),
] = None

The label of the world space ('MNI152NLin6Asym', 'scanner', ...; a known one is a SpaceEnum); the space itself is geometry.

intent class-attribute instance-attribute
intent: Annotated[IntentEnum | str | None, Scoped(FILE)] = (
    None
)

What the values are, as a NIfTI intent name (a known one is an IntentEnum).

repetition_time class-attribute instance-attribute
repetition_time: Annotated[
    float | None, Bids(RepetitionTime), Scoped(ACQUISITION)
] = None

Repetition time, in seconds.

echo_time class-attribute instance-attribute
echo_time: Annotated[
    float | None, Bids(EchoTime), Scoped(ACQUISITION)
] = None

Echo time, in seconds.

inversion_time class-attribute instance-attribute
inversion_time: Annotated[
    float | None, Bids(InversionTime), Scoped(ACQUISITION)
] = None

Inversion time, in seconds.

flip_angle class-attribute instance-attribute
flip_angle: Annotated[
    float | None, Bids(FlipAngle), Scoped(ACQUISITION)
] = None

Flip angle, in degrees.

magnetic_field_strength class-attribute instance-attribute
magnetic_field_strength: Annotated[
    float | None,
    Bids(MagneticFieldStrength),
    Scoped(ACQUISITION),
] = None

Nominal field strength, in tesla.

manufacturer class-attribute instance-attribute
manufacturer: Annotated[
    Manufacturer | str | None,
    Bids(Manufacturer),
    Scoped(ACQUISITION),
] = None

Manufacturer of the equipment (a known one is a Manufacturer).

manufacturers_model_name class-attribute instance-attribute
manufacturers_model_name: Annotated[
    str | None,
    Bids(ManufacturersModelName),
    Scoped(ACQUISITION),
] = None

Model name of the equipment.

institution_name class-attribute instance-attribute
institution_name: Annotated[
    str | None, Bids(InstitutionName), Scoped(ACQUISITION)
] = None

Institution responsible for the equipment.

acquisition_time class-attribute instance-attribute
acquisition_time: Annotated[
    datetime | None,
    Bids(AcquisitionTime),
    Scoped(ACQUISITION),
] = None

When the acquisition started.

phase_encoding_direction class-attribute instance-attribute
phase_encoding_direction: Annotated[
    EncodingDirection | None,
    Bids(PhaseEncodingDirection),
    Scoped(SPATIAL),
    ConvertTo(direction),
] = None

Phase-encoding direction: a unit vector. By default in voxel axes (BIDS 'j-' is accepted).

total_readout_time class-attribute instance-attribute
total_readout_time: Annotated[
    float | None,
    Bids(TotalReadoutTime),
    Scoped(ACQUISITION),
] = None

Total readout time, in seconds.

effective_echo_spacing class-attribute instance-attribute
effective_echo_spacing: Annotated[
    float | None,
    Bids(EffectiveEchoSpacing),
    Scoped(ACQUISITION),
] = None

Effective echo spacing, in seconds.

slice_encoding_direction class-attribute instance-attribute
slice_encoding_direction: Annotated[
    EncodingDirection | None,
    Bids(SliceEncodingDirection),
    Scoped(SPATIAL),
    ConvertTo(direction),
] = None

Slice-encoding direction: a unit vector, by default in voxel axes (BIDS 'k' is accepted)."

slice_timing class-attribute instance-attribute
slice_timing: Annotated[
    tuple[float, ...] | None,
    Bids(SliceTiming),
    Scoped(SPATIAL),
] = None

Acquisition time of each slice, in seconds, along the slice encoding direction.

multiband_acceleration_factor class-attribute instance-attribute
multiband_acceleration_factor: Annotated[
    int | None,
    Bids(MultibandAccelerationFactor),
    Scoped(ACQUISITION),
] = None

Multiband acceleration factor.

bvalues class-attribute instance-attribute
bvalues: Annotated[
    tuple[float, ...] | None, Along(time)
] = None

One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."

bvectors class-attribute instance-attribute
bvectors: Annotated[
    tuple[tuple[float, float, float], ...] | None,
    Along(time),
] = None

One unit gradient direction per index along the time axis, in world (RAS) coordinates."

display_range class-attribute instance-attribute
display_range: Annotated[
    tuple[float, float] | None, Scoped(VALUES)
] = None

Display window (min, max).

channels class-attribute instance-attribute
channels: Annotated[
    tuple[Channel, ...] | None, Along(channel)
] = None

One description per channel. The descriptions run along the axes of type channel only. The entries of a component axis, such as a vector or a tensor axis, are described by the type, the valence, the layout and the frame of that axis, so a change of frame, which only re-expresses the values of component axes, keeps these descriptions.

data_unit class-attribute instance-attribute
data_unit: Annotated[
    Unit | str | None, Scoped(VALUES), ConvertTo(unit)
] = None

Unit of the data values: a Unit whenever the units module parses the name ('a.u.', 'mm/s', 'HU'), and the name itself, as a string, when it does not, so that a file with an odd unit still reads. Formats write it as its symbol (Unit.symbol), which parses back to the same unit.

dtype class-attribute instance-attribute
dtype: Annotated[
    dtype | None, Scoped(VALUES), ConvertTo(to_dtype)
] = None

The element type of the data as stored, in native byte order.

It may differ from the type of the loaded array: a scaled integer file loads as floating-point values. An override given to save or to consolidate takes precedence over it.

scale_slope class-attribute instance-attribute
scale_slope: Annotated[float | None, Scoped(VALUES)] = None

The slope of the intensity scaling: a value is stored * scale_slope + scale_intercept. None means no scaling.

scale_intercept class-attribute instance-attribute
scale_intercept: Annotated[float | None, Scoped(VALUES)] = (
    None
)

The intercept of the intensity scaling (see scale_slope). None means no intercept.

objective_magnification class-attribute instance-attribute
objective_magnification: Annotated[
    float | None, Scoped(ACQUISITION)
] = None

Nominal magnification of the objective.

objective_numerical_aperture class-attribute instance-attribute
objective_numerical_aperture: Annotated[
    float | None, Scoped(ACQUISITION)
] = None

Numerical aperture of the objective.

illumination_type class-attribute instance-attribute
illumination_type: Annotated[
    IlluminationType | str | None, Scoped(ACQUISITION)
] = None

Illumination type (a known one is an IlluminationType).

contrast_method class-attribute instance-attribute
contrast_method: Annotated[
    ContrastMethod | str | None, Scoped(ACQUISITION)
] = None

Contrast method (a known one is a ContrastMethod).

moving class-attribute instance-attribute
moving: Annotated[str | None, Scoped(FILE)] = None

The moving image of a registration (file reference).

fixed class-attribute instance-attribute
fixed: Annotated[str | None, Scoped(FILE)] = None

The fixed image of a registration (file reference).

input_space class-attribute instance-attribute
input_space: Annotated[
    SpaceEnum | str | None, Scoped(FILE)
] = None

Label of the space a transformation maps from.

output_space class-attribute instance-attribute
output_space: Annotated[
    SpaceEnum | str | None, Scoped(FILE)
] = None

Label of the space a transformation maps to.

extra class-attribute instance-attribute
extra: Annotated[
    dict[str, Any], Scoped(FILE), HideIf(not_)
] = Factory()

Free-form keys the vocabulary does not cover, copied into any free-form store a format has."

SUPPORTED_FIELDS class-attribute
SUPPORTED_FIELDS: tuple[str, ...] = ()

The fields of the metadata that the format can store.

The names are those of the vocabulary, and "extra" when the format has a free-form store. A field that is not listed is decoded as None, and its value is reported as lost when the metadata is consolidated. A conversion into the format reads this list to report a lower bound of what a write would lose. The base class lists no field.

RAW class-attribute
RAW: type | None = None

The class of the record of the format, or None.

When the record class of a format can read or write a file, the format sets this constant to it and lists MetadataReader or MetadataWriter among its bases. These classes pass every input to the record class and every output to the record, so the record class decides how each input is read and which options it takes. A format that reads or writes its header in another way leaves this constant at None and uses the readers and writers of io/base/parsers.py instead.

raw class-attribute instance-attribute
raw: NoRepr[ZarrRaw | None] = None

The record of the array, or None for metadata without a record.

Methods:

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

sniff_file classmethod
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a path or an open file.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for bytes, text, or lines.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

from_file classmethod
from_file(file: FileLike, **kwargs) -> Self

Read an object from a path or an open file.

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Read an object from the Zarr store at a path.

The inherited reader opens the path as a file, which fails because a Zarr store is a directory. This method reads the store with from_store instead. The inherited load and from_file pass a path to this method, and a dispatcher calls it by name, so all of them read the store in the same way.

Parameters:

Name Type Description Default
filename str or PathLike

The location of the store.

required
**kwargs Any

mode and driver, and the options of the reader.

{}

Returns:

Type Description
Self

The object read from the store.

Raises:

Type Description
ParserExistsError

If no Zarr store exists at filename.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_text classmethod
from_text(text: str, **kwargs) -> Self

Read an object from text.

The text is split into lines and passed to from_lines.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

Read an object from an iterable of lines.

The first line is passed to from_line.

from_line classmethod
from_line(line: str, **kwargs) -> Self

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod
from_instance(
    other: Any,
    *args: Any,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    **kwargs: Any,
) -> Self

Copy metadata into this format, field by field.

Every field of the vocabulary and extra are copied by name, including those that this format cannot store, which are dropped and reported only when the metadata is consolidated. The record of another format means nothing to this one, so it is copied only from metadata of this class. The fields that are set and that SUPPORTED_FIELDS does not list are reported here as lost, because a write will drop them, so the report is a lower bound of what a write loses.

Parameters:

Name Type Description Default
other object

The metadata to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
on_loss ErrorAction

What to do with the fields that this format cannot store: "ignore" accepts the loss, "warn" warns about it, "raise" raises, and a report is filled instead of warning or raising. By default, the action of on_error, or else the policy in effect (see metadata_loss_policy).

UNSET
on_error ErrorPolicy

What to do with a conversion error of the copy, including a loss (see ErrorPolicy). A mapping may also name other errors. An entry for a loss in on_error takes precedence over on_loss. By default, an error is raised.

UNSET
**kwargs Any

Fields to set on the result.

{}

Returns:

Type Description
MetadataFormat

The copy.

Raises:

Type Description
MetadataLossError

If a field is reported under the "raise" policy.

from_any classmethod
from_any(other: Any, *args, **kwargs) -> Self

Build metadata from a file, from other metadata, or from a value.

Metadata of any class, generic or of another format, is copied field by field with from_instance. A file is read as FileBasedModelMixin.from_any reads it, and any other value is passed to the data model.

Parameters:

Name Type Description Default
other object

A file, its content, metadata, or a mapping of fields.

required
*args Any

Constructor arguments.

()
**kwargs Any

Fields of the metadata, or the options of the reader for a file.

{}

Returns:

Type Description
MetadataFormat

The metadata.

to
to(
    cls: Type[Metadata] | None = None,
    *,
    copy: bool = False,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    **values: Any,
) -> Metadata

Convert this metadata into another class.

This is the metadata counterpart of to on images and transformations. Each field is copied by name. The record of a file format means nothing to another format, so it is copied only into the same class. A file format that has no slot for a field that is set still receives the value, and reports it as lost, because its next consolidation will drop it. The report is acted on by the action that on_loss or on_error takes for a MetadataLossError.

Parameters:

Name Type Description Default
cls type

The metadata class to convert into, such as Metadata or NiftiMetadata. By default, the class of this metadata.

None
copy bool

Whether to return new metadata when nothing changes. By default, metadata converted to its own class without any field is returned itself.

False
on_loss ErrorAction

What to do with the fields that cls has no slot for: "ignore" accepts the loss, "warn" warns about it, "raise" raises, and a report, ConversionReport, is filled instead of warning or raising. By default, the action of on_error, or else the policy in effect (see metadata_loss_policy).

UNSET
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. An entry for a loss in on_error takes precedence over on_loss. By default, an error is raised.

UNSET
**values Any

Fields to set on the result.

{}

Returns:

Type Description
Metadata

The converted metadata.

Raises:

Type Description
MetadataLossError

If a field is reported under the "raise" policy.

Examples:

report = ConversionReport()
mgh = metadata.to(MghMetadata, on_loss=report)
report.lost  # the fields MGH has no slot for
derive
derive(
    operation: Indexed | Resampled | None = None,
    *,
    history: str | Sequence[str] | None = None,
) -> Self

Return the metadata of an image computed from this one.

The fields follow Metadata.derive, which records the derivation in history and generated_by. Those two fields keep their value when the format has no slot for them, so that a derived image of the format is not reported to lose a provenance that only the derivation added.

Parameters:

Name Type Description Default
operation Indexed or Resampled

What the image operation did to the axes of the image.

None
history str or sequence of str

The steps of the derivation, appended to history.

None

Returns:

Type Description
MetadataFormat

New metadata, of the same class, which shares the record.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

from_raw classmethod
from_raw(raw: Any, **kwargs) -> Self

Build the metadata that holds a record.

A reader calls this method once it has parsed the header of a file. The record is held as it is given, without a copy. The format decodes the fields of the vocabulary from the record here, and the base class, which knows no record, decodes none.

Parameters:

Name Type Description Default
raw object

The header of a file, in the representation of the format.

required
**kwargs Any

Other fields of the metadata, which take precedence over the decoded values.

{}

Returns:

Type Description
MetadataFormat

The metadata.

from_store classmethod
from_store(location: StoreLike, **kwargs) -> Self

Read an object from a Zarr store location.

The keyword arguments mode and driver are passed to abczarr.open, and the remaining ones to from_node. A local path is made absolute first, so that the opened node knows where its store lies whatever the working directory.

Parameters:

Name Type Description Default
location str or PathLike

The location of the store.

required
**kwargs Any

mode and driver, and the options of the reader.

{}

Returns:

Type Description
Self

The object read from the store.

Raises:

Type Description
ParserExistsError

If no Zarr store exists at location.

from_node classmethod
from_node(node: Any, **kwargs) -> ZarrMetadata

Read the metadata of an opened Zarr array.

Parameters:

Name Type Description Default
node ZarrArray or native Zarr array

The opened array.

required
**kwargs Any

Refused, since the metadata has no reader option.

{}

Returns:

Type Description
ZarrMetadata

The metadata, which holds the record of the array.

Raises:

Type Description
TypeError

If an option is given.

ParserTypeError

If node is a path, or an object that cannot be wrapped.

ParserContentError

If the node is a group.

ZarrRaw magic

ZarrRaw(
    document: ArrayMetadata,
    stored: NoRepr[tuple[tuple[str, bytes], ...]] = (),
)

Bases: Raw

The metadata of a Zarr array, as its store keeps it.

A Zarr array is described by a small JSON document: zarr.json in Zarr version 3, or .zarray with the attributes in .zattrs in version 2. The record holds that description as the typed model of abczarr, an ArrayMetadata of the version of the store, which gives the shape, the data type, the chunks, the codecs, the dimension names and the attributes of the array. It also keeps the bytes of each document as they were read, so that a document that is written again without changes keeps its bytes, whatever its layout.

The record never reads the chunks of the array, and it holds no handle on the store, so it can be copied and pickled. It is held by ZarrMetadata, which never changes it in place: an edit is made on a copy, as in replace(record, document=record.document.update_attributes(...)).

The record is shaped so that the record of an OME-Zarr pyramid can hold one such record for each of its levels, next to the record of its group.

Parameters:

Name Type Description Default
document ArrayMetadata

The document of the array, as the typed model of abczarr.

required
stored NoRepr[tuple[tuple[str, bytes], ...]]

The bytes of each document as read, with the key of its file. The key is the name of the file in the store, such as zarr.json. The tuple is empty for a record built in memory. A writer writes these bytes again for each document that is the same as the one that the record describes, as documents tells.

()

Attributes

document instance-attribute
document: ArrayMetadata

The document of the array, as the typed model of abczarr.

stored class-attribute instance-attribute
stored: NoRepr[tuple[tuple[str, bytes], ...]] = ()

The bytes of each document as read, with the key of its file.

The key is the name of the file in the store, such as zarr.json. The tuple is empty for a record built in memory. A writer writes these bytes again for each document that is the same as the one that the record describes, as documents tells.

zarr_version property
zarr_version: int

The version of the Zarr format of the store, 2 or 3.

shape property
shape: tuple[int, ...]

The shape of the array, in the order of the store.

dtype property
dtype: dtype

The data type of the array, as a NumPy type.

chunks property
chunks: tuple[int, ...] | None

The shape of a chunk, or of a shard, or None if irregular.

A sharded array of Zarr version 3 stores its chunks in shards, so the shape returned is the shape of a shard, which is the unit of the files of the store.

dimension_names property
dimension_names: tuple[str | None, ...] | None

The name of each dimension, or None when none is stored.

Only Zarr version 3 stores dimension names.

attributes property
attributes: dict[str, Any]

The attributes of the array, as plain JSON values.

Methods:

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod
from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod
from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to
to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

copy
copy() -> Self

Return a copy of the object.

Returns:

Type Description
self

The copy.

from_node classmethod
from_node(node: Any) -> ZarrRaw

Read the record of an opened Zarr array, without its chunks.

The document is the model that the node holds, and the bytes of each document are read from the store of the node, when the store can be read through its path.

Parameters:

Name Type Description Default
node ZarrArray

The opened array.

required

Returns:

Type Description
ZarrRaw

The record of the array.

Raises:

Type Description
ParserContentError

If the node is a group.

documents
documents() -> dict[str, bytes]

Return the bytes of each document that a writer writes.

A document is written with the bytes as read when the parsed bytes give the same document as the record. Both sides are read through the model of abczarr and then compared through a canonical serialization, which tells the whole number 1 from the number 1.0, so that a document that was only read keeps its bytes, and a document whose model changed is serialized again. In version 2, the attributes are written to .zattrs, which is left out when it was not stored and the record has no attribute.

Returns:

Type Description
dict of str to bytes

The bytes of each document, by the name of its file.

Raises:

Type Description
WriterError

If the record is of a version other than 2 or 3.

ZarrImage magic

ZarrImage(
    metadata: NoRepr[ZarrMetadata | None] = Inherit(
        "metadata", default=None
    ),
    data: ArrayProtocol | None = Inherit(
        "_data", default=None
    ),
    transformations: list[Transformation] | None = Inherit(
        "transformations", default=None
    ),
    frames: NoRepr[Any] = (),
    rawdata: NoRepr[ArrayProtocol | None] = None,
    *,
    labels: NoRepr[LabelsLike] = None,
)

Bases: ZarrReaderWriter, ImageFormat, SingleScaleImage

An image stored as a plain Zarr array.

A plain Zarr array is a store, a directory or a remote prefix of keys, that holds the document of one array and its chunks. The image holds the document as ZarrMetadata, whose record is a ZarrRaw, and the array as the store keeps it in rawdata. When the image is read from a store, rawdata is a lazy array that reads the chunks only when they are needed, and data returns that lazy array. An OME-Zarr pyramid, a group with a multiscale geometry, is read by OmeZarrImage instead.

A plain array stores no geometry, so the image decodes no transformation from its record. The reader option transformation places the voxels in the world, as an assigned transformation. A writer cannot store a geometry either, so it refuses an image whose transformations are not the identity, with UnrepresentableTransformationError, rather than drop them: such an image is written as OME-Zarr, or its transformations are cleared first with image.transformations = [].

rawdata and the record describe the store as it was read, or as the image was last consolidated. Data that are assigned are pending until [consolidate][] encodes them into a copy, or until the image is written, which writes such a copy and leaves the image as it was.

An image that is read and written again to a local directory without changes gives the same files, byte for byte: the chunk files are copied, and each document is written with the bytes that were read when the record still describes it. A local directory is written in a new directory beside the target, which then replaces the target, so that a failed write leaves the old store as it was. A new store is written in Zarr version 3, and a store that was read keeps its version. A remote store cannot be replaced in one step, so it is written in place, and an image is never written over the remote store that its lazy array reads.

Parameters:

Name Type Description Default
metadata NoRepr[ZarrMetadata | None]
Inherit('metadata', default=None)
data ArrayProtocol | None

The data given to the image, or None to decode it from rawdata. The image takes over the data field of SingleScaleImage to store it under this private name. The constructor still takes data in the same place, and the property of the same name reads it. An array stored here is pending: it is encoded into rawdata only by [consolidate][] or by a write.

Inherit('_data', default=None)
transformations list[Transformation] | None

The transformations assigned to the image, or None. The image takes over the transformations field of SingleScaleImage to store it under this private name. Only an assigned list, even an empty one, is stored here. None, the default, means that no list was assigned, so the property decodes the list of the record, which is empty.

Inherit('transformations', default=None)
frames NoRepr[Any]

The frames of the values, as they were given (see frames).

()
rawdata NoRepr[ArrayProtocol | None]

The array as the store keeps it, or None without data. After a read, rawdata is a lazy array of the store, which reads its chunks only when it is indexed. rawdata describes the store as it was read, or as the image was last consolidated, so assigning data leaves it as it is.

None
labels NoRepr[LabelsLike]

Whether the image is a label map, as it was given (see labels).

None

Attributes

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 10

Precedence of images over other kinds of object, used to break ties.

When a file could be read as several kinds of object, the readers that score their input, for example by the NIfTI intent code, normally decide first, and this priority matters only when nothing else does. A NIfTI file, for instance, is both an image and a set of affines, and it is read as an image when nothing else separates the two.

ndim property
ndim: int

The number of dimensions of the data.

dtype class-attribute instance-attribute
dtype = alias('data.dtype', readonly=True)

The data type of the data.

grid class-attribute instance-attribute
grid = alias('geometry.grid', readonly=True)

The Cartesian field that defines the sampling grid.

transformation property writable
transformation: Transformation

The preferred transformation, which is always the last in the transformations list.

When the list is empty, this property return an Identity.

Assigning a transformation makes it the preferred one:

  • if the assigned value is an integer, the transformation at that index is selected and moved to the end of the list;
  • if the assigned value is a string, the transformation whose output system has that name is selected and moved to the end of the list. When several output systems have that name, the transformation closest to the end of the list is selected, so that the preferred transformation stays preferred if it matches;
  • if the assigned value is a transformation that is already in the list, it is moved to the end of the list;
  • if it is a new transformation, it is appended to the list.

An unknown index or system name raises a KeyError.

Example

>>> voxel = CoordinateSystem(["i", "j", "k"], name="voxel")
>>> phys = CoordinateSystem(["x", "y", "z"], name="phys")
>>> world = CoordinateSystem(["x", "y", "z"], name="world")
>>> aligned = CoordinateSystem(["x", "y", "z"], name="aligned")
>>>
>>> vox2scanner = Affine(input=voxel, output=phys)
>>> vox2world = Affine(input=voxel, output=world)
>>> vox2aligned = Affine(input=voxel, output=aligned)
>>>
>>> img = SingleScaleImage(data, [vox2scanner, vox2world])
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = 0
>>> img.transformation.output
CoordinateSystem(name='phys', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = "world"
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = vox2aligned
>>> img.transformation.output
CoordinateSystem(name='aligned', axes=['x', 'y', 'z'])
>>>
>>> [t.output.name for t in img.transformations]
['phys', 'world', 'aligned']
frames property writable
frames: tuple[FrameSlot, ...]

The frame of the values along each axis.

Some axes hold the components of points, vectors or tensors, and the type of such an axis says which (see [ComponentAxis][brainhops.datamodel.axes.ComponentAxis]). The components are expressed in a coordinate system, called the frame of the values, and each axis has one slot that records it:

  • None is the array system of the image, so that the components are in voxel units along the axes of the data. This is the default.
  • A transformation maps the array system to the frame. It is often an entry of transformations, such as the map to scanner RAS for a file that stores its vectors in RAS.
  • A coordinate system names a foreign frame, which belongs to another space that no transformation of the image reaches. The values along such an axis are never re-expressed.

Only a component axis can have a frame. The constructor and the setter also accept a mapping from axis names or indices to slots, and an empty tuple, which leaves every slot None.

A stored transformation corresponds exactly to the components: the outputs that no component axis of the array feeds are as many as the components, which follow them in order. A transformation that is given with more such outputs, such as a map that also carries a time axis along, is restricted to the outputs that share one axis type, when exactly one type has as many outputs as there are components. A projection that removes the other outputs is then composed onto the transformation.

Lazily applying a transformation keeps the frames, because the values do not change. Indexing and reslicing compose each frame with the map of the voxels, so that the values keep their meaning without being rotated. reframe re-expresses the values in another frame. The design is recorded in spec/design/vector-and-tensor-images.md.

Raises:

Type Description
TypeError

If a slot is neither a transformation, a coordinate system nor None.

ValueError

If there is not one slot per axis, if an axis that is not a component axis has a frame, or if a transformation does not tell which of its axes the components follow.

KeyError

If a mapping names an axis that does not exist.

geometry property
geometry: Geometry

The geometry of the image.

The geometry pairs the Cartesian field matching the data shape with the preferred voxel-to-world transformation. Any image can be resliced onto this geometry.

rawdata class-attribute instance-attribute
rawdata: NoRepr[ArrayProtocol | None] = None

The array as the store keeps it, or None without data.

After a read, rawdata is a lazy array of the store, which reads its chunks only when it is indexed. rawdata describes the store as it was read, or as the image was last consolidated, so assigning data leaves it as it is.

metadata class-attribute instance-attribute
metadata = smartproperty(
    "metadata", invalidates="transformations"
)

The metadata of the store, which holds its record, or None.

An image built from data has no metadata. Assigning other metadata drops the transformations decoded from the previous record and keeps the transformations that were assigned.

shape property
shape: tuple[int, ...]

The shape of the data, read without reading the chunks.

The shape is that of the assigned data, or else of rawdata, which the lazy array knows from the record. An image without data has the empty shape.

Methods:

save
save(file: FileLike, **kwargs) -> None

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

to_lines
to_lines(**kwargs) -> Iterator[str]

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

sniff_file classmethod
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a path or an open file.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for bytes, text, or lines.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

from_file classmethod
from_file(file: FileLike, **kwargs) -> Self

Read an object from a path or an open file.

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Read an object from the Zarr store at a path.

The inherited reader opens the path as a file, which fails because a Zarr store is a directory. This method reads the store with from_store instead. The inherited load and from_file pass a path to this method, and a dispatcher calls it by name, so all of them read the store in the same way.

Parameters:

Name Type Description Default
filename str or PathLike

The location of the store.

required
**kwargs Any

mode and driver, and the options of the reader.

{}

Returns:

Type Description
Self

The object read from the store.

Raises:

Type Description
ParserExistsError

If no Zarr store exists at filename.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_text classmethod
from_text(text: str, **kwargs) -> Self

Read an object from text.

The text is split into lines and passed to from_lines.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

Read an object from an iterable of lines.

The first line is passed to from_line.

from_line classmethod
from_line(line: str, **kwargs) -> Self

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod
from_instance(other: Any, *args, **kwargs) -> Self

Copy an instance, resetting fields that belong to another format.

The data model copies the fields of other by name. Fields declared by a file format, such as the rawdata array and the metadata of NIfTI and MGH, are copied only from an object of the same format; otherwise the class default is kept, because the same field name holds something different. Converting NIfTI to MGH on save therefore converts the data model only, and the writer rebuilds the format state.

A format that decodes its data or its transformations from its file stores them in the private fields _data and _transformations, where None means that they are decoded. Within the format, the stored values are copied, so a copy of an image whose data was not assigned holds the same rawdata as other, which stays lazy if it is a proxy, and decodes the same record. From another class, the data, the levels of a pyramid and the transformations that other reports are copied, decoded if need be, because its rawdata and its record mean nothing to this format. A format that takes metadata over receives the metadata of other, which its field converts into the metadata of the format, without the record of other.

Parameters:

Name Type Description Default
other object

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The copy.

from_any classmethod
from_any(other: Any, *args, **kwargs) -> Self

Build an object from a file or any value the data model takes.

A path, an open file (any object with a read method), bytes, bytearray or a SourceSpec is read with load. A dispatcher then chooses the best format, and a concrete format reads the input as an instance of its own class. Any other value is passed to the from_any of the data model, which maps a mapping field by field, copies an instance of a similar class, or calls the constructor.

Parameters:

Name Type Description Default
other object

A file, its content, a mapping, or an instance of a similar class.

required
*args Any

Constructor arguments. A file is read with keyword options only.

()
**kwargs Any

Format options when reading a file, and field values otherwise.

{}

Raises:

Type Description
TypeError

If positional arguments accompany a file.

to_backend
to_backend(
    backend: BackendLike | None = None,
    *,
    device: DeviceLike | None = None,
) -> ArrayProtocol | None

Return the data as a bare array of the backend of a setting.

The object does not change. Small parameters, such as the matrix of an affine transformation, are converted too, since the caller asks for them. An object without data, such as the identity, gives None.

Parameters:

Name Type Description Default
backend str | module

The setting. By default, the current setting is used.

None
device str | int

The device for converted arrays. The backend supplies its default.

None

Returns:

Type Description
array | None

The data.

to_numpy
to_numpy() -> ArrayProtocol

Return the data as a NumPy array, reading or computing them.

to_cupy
to_cupy(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a CuPy array on the GPU.

to_dask
to_dask(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a Dask array, without reading them.

as_numpy
as_numpy(*, inplace: bool = False) -> Self

Return the object with its data as NumPy arrays.

On an object read from a file, as_numpy(inplace=True) reads the file once and keeps its values.

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_cupy
as_cupy(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as CuPy arrays on the GPU.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_dask
as_dask(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

labels
labels() -> LabelsLike

Whether the image is a label map, and the names of its labels.

A label map is an image whose values are integers that each stand for a region or a class, such as a segmentation. Code that resamples an image reads this property to avoid averaging labels. The property takes one of four values.

  • None when it is not known whether the image is a label map.
  • False when the image is known not to be a label map.
  • True when the image is a label map whose names are not known.
  • A LabelTable when the names of the labels are known. The table is never empty.

A value given to the constructor or assigned to the property is returned as it is. Otherwise the value is derived from the intent field of the metadata: the intents label and neuroname give True, any other intent gives False, and an image without an intent gives None. A multi-scale image that was given no value takes the value of its finest level. Assigning None restores the derived value. The data are never read to find the values that they hold.

__array__
__array__(dtype: DTypeLike | None = None) -> ndarray

Convert the data to a NumPy array, optionally of a given type.

reslice
reslice(
    geometry: _GeometryLike | None = None,
    degree: InterpolationLike | None = None,
    bound: BoundaryLike = "reflect",
    coeff: bool = False,
    copy: bool = False,
    *,
    clip: Clip = None,
    dtype: DTypeLike | None = None,
    reframe: bool | ReframeMethodOrCallable = False,
    frame: FrameTargets = -1,
) -> SingleScaleImage

Resample the data onto another geometry.

The values along an axis that holds vectors or tensors are sampled without being rotated: each of their frames is composed with the map of the voxels, so that the values keep their meaning. With reframe, the values are then re-expressed in the frame frame of the result, as by reframe.

Parameters:

Name Type Description Default
geometry Image or Geometry or Transformation

The target voxel-to-world geometry. An image or a geometry also determines the output shape, whereas a bare transformation keeps the current shape. By default, the image is resampled onto its ow geometry.

None
degree int

Spline degree, from 0 (nearest neighbour) up to 7. A degree of 1 gives linear interpolation. By default, the degree is 0 for a label map, whose labels is true, so that labels are not averaged, and 1 otherwise.

None
bound str or float

Boundary condition, which says how the data continues beyond its edges. A float is a constant value beyond the edges. The strings are the following names, and their aliases listed in BoundaryCondition, such as 'wrap' for 'grid-wrap':

- 'nearest': nearest edge value  (a a a a | a b c d | d d d d)
- 'reflect': reflect at edge     (d c b a | a b c d | d c b a)
- 'mirror': mirror at edge       (d c b | a b c d | c b a)
- 'grid-wrap': wrap around       (a b c d | a b c d | a b c d)
- 'constant': zero beyond edge   (0 0 0 0 | a b c d | 0 0 0 0)
- 'antimirror': odd mirror       (-b -a 0 | a b c d | 0 -d -c)
- 'antireflect': odd reflection  (-b -a | a b c d | -d -c)
"reflect"
coeff bool

Whether the data already holds spline coefficients. If false, the data is prefiltered before interpolation.

False
copy bool

If true, the output never shares memory with the input. If false, a reslicing that only rearranges existing voxels, such as a flip, a permutation or a slice with a unit step, may return a view, as torch.Tensor.to does. Dask arrays are immutable and are never copied.

False
clip float, pair, sequence of pairs, or None

A scalar sets symmetric margins. A (lower, upper) pair sets asymmetric margins on every input axis; a sequence of pairs follows the input data axes, independently of output permutations. Samples outside the closed interval [-lower, size - 1 + upper] on any axis are zero. None preserves extrapolation with bound. Use 0.5 for the outer voxel edges, 0 for border voxel centres, or -0.5 for inner voxel edges. Inside this interval, bound still extends interpolation stencils; clipping never clamps the coordinates.

None
dtype DTypeLike

Output dtype. None preserves the input dtype. A floating dtype retains interpolated fractions of integer input. An explicit dtype promotes the input and output dtypes to choose working precision, with a minimum of float32. Integer-only combinations use float64. Integer output keeps rounding half away from zero and saturation. Dask arrays remain lazy.

None
reframe bool | ReframeMethod | str | callable

Whether and how the values of vector and tensor axes are re-expressed after they are sampled. False keeps them in their frame, True is the same as "jacobian", and the other values are the methods of reframe.

False
frame int or str or Transformation or None or dict

The frame in which the values are re-expressed when reframe is set, as in reframe. It is read on the result, whose only transformation is that of geometry, so -1 is the world of geometry.

-1

Returns:

Type Description
SingleScaleImage

The resliced image. Its metadata is derived from the metadata of this image with a Resampled record (see Metadata.derive): the fields tied to the spatial sampling are cleared, an encoding direction given in voxel axes is mapped through the map of the voxels, and "reslice" is appended to history. The metadata keeps its class and its record.

reframe
reframe(
    frame: FrameTargets = -1,
    *,
    method: ReframeMethodOrCallable = "jacobian",
) -> SingleScaleImage

Re-express the values of vectors and tensors in another frame.

Some axes hold the components of vectors or tensors, expressed in a frame that frames records. This method changes that frame. With the default arguments, the values are re-expressed in the world of the preferred transformation, which is what a writer or a viewer of the image expects. No voxel moves.

If the values are in the frame F and are re-expressed in the frame F′, the components at each voxel x are changed by

J(x) = D F′(x) · (D F(x))⁻¹

where D is the Jacobian, which is the linear part of a map that is affine. The type and the valence of the axis say how the components change (see [ComponentAxis][brainhops.datamodel.axes.ComponentAxis]): each vector index is multiplied by J and each covector index by J⁻ᵀ, so that a vector becomes J v, a gradient becomes J⁻ᵀ g and a diffusion tensor becomes J T Jᵀ. A tensor stored in a layout with components that are zero by construction is stored in a closed layout afterwards (see [TensorAxis][brainhops.datamodel.axes.TensorAxis]), which changes the length of its axis. The coordinates of points cannot be re-expressed this way.

The components follow some axes of the system of their frame, in order, and these axes are read from the structure of the frame, not from the types of the axes. They are the outputs of the frame that no component axis of the array feeds, and a stored frame has exactly one such output per component. A frame given as frame that has more of them is first restricted to the outputs that share one axis type, as the setter of frames does. The Jacobian is taken along the axes of the array that the frame maps onto these outputs, and the two frames of a change must map the same axes of the array. The array system takes the axes of the other frame.

The Jacobian of a map that is not affine is computed by finite differences between the voxels: central inside the image and one-sided at its edges. Along an axis of one voxel, the fields of the map are taken to be constant.

Parameters:

Name Type Description Default
frame int or str or Transformation or None or dict

The new frame. An integer selects an entry of transformations, without reordering it, so that -1 is the preferred transformation. A string selects the most preferred transformation whose output system has that name. None is the array system, in which the components are in voxel units. A transformation maps the array system to the new frame. A single value applies to every component axis, except the axes whose frame is foreign. A dictionary maps axis names or indices to frames, and the axes that it leaves out keep their frame.

-1
method ReframeMethod | str | callable

What is applied to the values. "jacobian" applies J, which changes the frame exactly. "rotation" applies the rotation R of the polar decomposition J = R P, which keeps the length of vectors and the eigenvalues of tensors, as the finite-strain reorientation of diffusion tensors does. A callable receives J, of shape (n, n) or (*shape, n, n), and returns the matrix to apply.

"jacobian"

Returns:

Type Description
SingleScaleImage

The image with its values re-expressed, the same transformations, and its new frames. The image itself is returned when no value changes frame. Its metadata is derived from the metadata of this image with a Reframed record (see Metadata.derive): the fields that describe the values, such as data_unit and display_range, are cleared, and so are the fields with one entry per index along an axis whose values were re-expressed. "reframe" is appended to history.

Raises:

Type Description
KeyError

If a frame names a system that no transformation ends in, or if a dictionary names an axis that does not exist.

ValueError

If a dictionary names an axis that is not a component axis or that has a foreign frame, if the frames do not tell which of their axes the components follow, or if they map different axes of the array onto them.

NotImplementedError

If the values of an axis whose frame changes are the coordinates of points.

__call__
__call__(
    transformation: Transformation,
) -> SingleScaleImage

Apply a transformation lazily, without reslicing.

The output space of transform should match the output space of the preferred transformation. The new preferred transformation, transform.inverse() @ self.transformation, is appended to the existing ones. No voxel moves, so the new image shares the metadata and the frames of this image.

__getitem__
__getitem__(index: CartesianIndex) -> SingleScaleImage

Index the data, keeping every transformation consistent with it.

The metadata is derived from the metadata of this image with an Indexed record (see Metadata.derive). An index along a time or a channel axis keeps the entries of the fields that run along that axis at the positions that it keeps, and an index of a spatial axis, or of an axis of unknown type, clears the fields tied to the spatial sampling and maps an encoding direction given in voxel axes. "getitem" is appended to history, and the metadata keeps its class and its record.

The frames of the values are composed with the map from the indexed voxels to the original ones, so the values are not changed. A component axis stays a component axis only when it is indexed with its full range in order. Otherwise its remaining entries are no longer the components of one object, so it becomes a channel axis and loses its frame.

Parameters:

Name Type Description Default
index [tuple of] (int | slice | None)

The index, as for the data array. A tuple may contain integers, slices, None and ....

required

Returns:

Type Description
SingleScaleImage

The indexed image.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

data
data() -> ArrayProtocol | None

The image data, assigned or decoded from rawdata.

An array assigned to the image is returned as it is, and stays pending until [consolidate][] or a write encodes it. Otherwise, the data are the lazy array of the file, which reads its values when a computation needs them and refuses an edit in place. To change the voxels, assign data, and assigning None gives the lazy array of the file again.

transformations
transformations() -> list[Transformation]

Voxel-to-world transformations, which a plain array never stores.

The list decoded from the record is empty, because a plain Zarr array has no geometry. It is cached, apart from an assigned list, so a change made to it in place is kept. Assigning a list, as the reader option transformation does, replaces it. The list is compared at [consolidate][], and by a write, with the empty list of the record, and a list that is not the identity is refused.

from_node classmethod
from_node(
    node: Any,
    transformation: Transformation | None = None,
    **kwargs,
) -> ZarrImage

Read an image from an opened Zarr array.

The record is read from the document of the array, and rawdata is a lazy array of the node, which reads no chunk until it is indexed. Without a transformation, which places voxels in the world, the image has no geometry.

Parameters:

Name Type Description Default
node ZarrArray or native Zarr array

The opened array. A native zarr-python, TensorStore or zarrista array is wrapped in an abczarr node first.

required
transformation Transformation

The voxel-to-world transformation of the image, which is assigned to it.

None
**kwargs Any

Refused, since the reader has no other option.

{}

Returns:

Type Description
ZarrImage

The image, whose chunks are read lazily.

Raises:

Type Description
TypeError

If another option is given.

ParserTypeError

If node is a path, or an object that cannot be wrapped.

ParserContentError

If the node is a group: there is no array to read, and reading the group would fail later, more obscurely.

from_store classmethod
from_store(location: StoreLike, **kwargs) -> ZarrImage

Read an image from a Zarr store location.

The array is opened as by from_node, and the lazy array of the image knows the location that it was read from, so that the image is never written over the store that it still reads.

Parameters:

Name Type Description Default
location str or PathLike

The location of the array.

required
**kwargs Any

mode and driver, which are passed to abczarr.open, and the options of from_node.

{}

Returns:

Type Description
ZarrImage

The image, whose chunks are read lazily.

Raises:

Type Description
ParserExistsError

If no Zarr store exists at location.

ParserContentError

If the store is a group, not a plain array.

to_node
to_node(node: Any, **kwargs) -> ZarrNode

Write the data of the image into an opened Zarr array.

The image is consolidated into a copy, whose array is written into the node as it is. The document of the node is left as it is, so the node must have the shape of the image.

Parameters:

Name Type Description Default
node ZarrArray or native Zarr array

The opened array to write into.

required
**kwargs Any

Refused, since the node already decides how it stores its chunks.

{}

Returns:

Type Description
ZarrNode

The node that was written into.

Raises:

Type Description
TypeError

If an option is given.

WriterError

If the node is a group or a path, or if the image has no data.

UnrepresentableTransformationError

If a transformation of the image is not the identity.

to_store
to_store(
    location: StoreLike, driver: str | None = None, **kwargs
) -> None

Write the image to a store location, or into an opened array.

The image is consolidated into a copy with the keyword arguments, as by [consolidate][], and the copy is written. The image itself is not changed. A local directory is filled beside the target and then moved into place, so a failed write leaves the old store as it was. A lazy array whose chunks are stored as the copy stores them is copied file by file, and each document keeps the bytes that were read when the record still describes it, so an image that did not change is written byte for byte. When the lazy array of the image reads the local directory that is written, the image is consolidated in place instead, so that it holds what the store holds (#426), and its lazy array and its record are read again from the new store. A remote location is written in place.

Parameters:

Name Type Description Default
location (str, PathLike or ZarrArray)

The location of the store, or an opened array, which to_node writes into.

required
driver str

The abczarr driver that creates the array, or None to let abczarr choose one.

None
**kwargs Any

The options of [consolidate][].

{}

Raises:

Type Description
TypeError

If an unknown option is given.

WriterError

If the image has no data, or if the location is the remote store that the lazy array of the image reads, which cannot be written without the lazy array reading a store half written.

UnrepresentableTransformationError

If a transformation of the image is not the identity.

OmeZarrImage magic

OmeZarrImage(
    images: list[SingleScaleImage] | None = Inherit(
        "images", default=None
    ),
    transformations: list[Transformation] | None = Inherit(
        "transformations", default=None
    ),
    axes: AxisList[Axis | EllipsisType] | None = None,
    ome: Multiscale | None = None,
    group: str = "",
    *,
    metadata: NoRepr[Metadata | None] = None,
    labels: NoRepr[LabelsLike] = None,
)

Bases: ZarrNodeReaderWriter, ImageFormat, MultiScaleImage

Multiscale image backed by an OME-Zarr pyramid.

Each level is a single-scale image placed by the coordinate transformation of its dataset. The metadata is read with abczarr and normalized to OME-NGFF 0.6. Levels run from finest to coarsest, their axes are permuted into the brainhops order, and their arrays are read lazily. A plain Zarr array is read by ZarrImage instead.

Parameters:

Name Type Description Default
images list[SingleScaleImage] | None

The levels given to the pyramid, or None to read them. The pyramid takes over the images field of MultiScaleImage to store it under this private name. The constructor still takes images in the same place, and the property of the same name reads it. None, the default, means that the levels are read from node, while a list, even an empty one, is used as it is.

Inherit('images', default=None)
transformations list[Transformation] | None

The placements given to the pyramid, or None to read them. The pyramid takes over the transformations field of MultiScaleImage in the same way as images. None, the default, means that the placements are read from node, while a list, even an empty one, is used as it is.

Inherit('transformations', default=None)
axes AxisList[Axis | EllipsisType] | None

The axes to store a pyramid under, in the brainhops order, when it is built from scratch, as an AxisList. As in a coordinate system, a single ... may stand for the axes about which nothing is known; it is closed to the number of axes of the data when the pyramid is written. None is not [...]: it leaves the axes unset, so a pyramid read from a store takes its axes from ome.

None
ome Multiscale | None

The OME multiscale metadata, normalized to 0.6.

None
group str

The path of the group of the pyramid from the root of its Zarr hierarchy, such as labels/cells. The coordinate systems of a pyramid in another group than the root are named after that path, as in labels/cells//physical, so that the systems of two groups stay distinct. A Zarr group does not know its path, so the reader that opened the root of the hierarchy gives it. The empty string, the default, is the root group, whose systems keep their OME names.

''
metadata NoRepr[Metadata | None]

What describes the image beyond its data and geometry.

None
labels NoRepr[LabelsLike]

Whether the image is a label map, as it was given (see labels).

None

Attributes

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 10

Precedence of images over other kinds of object, used to break ties.

When a file could be read as several kinds of object, the readers that score their input, for example by the NIfTI intent code, normally decide first, and this priority matters only when nothing else does. A NIfTI file, for instance, is both an image and a set of affines, and it is read as an image when nothing else separates the two.

scales property
scales: list[SingleScaleImage]

The pyramid levels, from highest to lowest resolution.

nscales property
nscales: int

The number of pyramid levels.

metadata class-attribute instance-attribute
metadata: NoRepr[Metadata | None] = None

What describes the image beyond its data and geometry.

shape property
shape: Shape

The shape of the data.

ndim property
ndim: int

The number of dimensions of the data.

dtype class-attribute instance-attribute
dtype = alias('data.dtype', readonly=True)

The data type of the data.

grid class-attribute instance-attribute
grid = alias('geometry.grid', readonly=True)

The Cartesian field that defines the sampling grid.

transformation property writable
transformation: Transformation

The preferred transformation, which is always the last in the transformations list.

When the list is empty, this property return an Identity.

Assigning a transformation makes it the preferred one:

  • if the assigned value is an integer, the transformation at that index is selected and moved to the end of the list;
  • if the assigned value is a string, the transformation whose output system has that name is selected and moved to the end of the list. When several output systems have that name, the transformation closest to the end of the list is selected, so that the preferred transformation stays preferred if it matches;
  • if the assigned value is a transformation that is already in the list, it is moved to the end of the list;
  • if it is a new transformation, it is appended to the list.

An unknown index or system name raises a KeyError.

Example

>>> voxel = CoordinateSystem(["i", "j", "k"], name="voxel")
>>> phys = CoordinateSystem(["x", "y", "z"], name="phys")
>>> world = CoordinateSystem(["x", "y", "z"], name="world")
>>> aligned = CoordinateSystem(["x", "y", "z"], name="aligned")
>>>
>>> vox2scanner = Affine(input=voxel, output=phys)
>>> vox2world = Affine(input=voxel, output=world)
>>> vox2aligned = Affine(input=voxel, output=aligned)
>>>
>>> img = SingleScaleImage(data, [vox2scanner, vox2world])
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = 0
>>> img.transformation.output
CoordinateSystem(name='phys', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = "world"
>>> img.transformation.output
CoordinateSystem(name='world', axes=['x', 'y', 'z'])
>>>
>>> img.transformation = vox2aligned
>>> img.transformation.output
CoordinateSystem(name='aligned', axes=['x', 'y', 'z'])
>>>
>>> [t.output.name for t in img.transformations]
['phys', 'world', 'aligned']
data property
data: ArrayProtocol

The data of the highest-resolution level.

iterscales property

Every level, as a single-scale image.

geometry property
geometry: Geometry

The geometry of the highest-resolution level.

The geometry pairs the grid of the highest-resolution level with the preferred transformation of the pyramid, composed with that level's own transformation.

group property
group: str

Path of the group of the pyramid from the root of its hierarchy.

axes property
axes: AxisList[Axis | EllipsisType] | None

Axes under which a pyramid built from scratch is stored.

Methods:

save
save(file: FileLike, **kwargs) -> None

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

to_lines
to_lines(**kwargs) -> Iterator[str]

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

sniff_file classmethod
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a path or an open file.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for bytes, text, or lines.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

from_file classmethod
from_file(file: FileLike, **kwargs) -> Self

Read an object from a path or an open file.

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Read an object from the Zarr store at a path.

The inherited reader opens the path as a file, which fails because a Zarr store is a directory. This method reads the store with from_store instead. The inherited load and from_file pass a path to this method, and a dispatcher calls it by name, so all of them read the store in the same way.

Parameters:

Name Type Description Default
filename str or PathLike

The location of the store.

required
**kwargs Any

mode and driver, and the options of the reader.

{}

Returns:

Type Description
Self

The object read from the store.

Raises:

Type Description
ParserExistsError

If no Zarr store exists at filename.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_text classmethod
from_text(text: str, **kwargs) -> Self

Read an object from text.

The text is split into lines and passed to from_lines.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

Read an object from an iterable of lines.

The first line is passed to from_line.

from_line classmethod
from_line(line: str, **kwargs) -> Self

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

from_store classmethod
from_store(location: StoreLike, **kwargs) -> Self

Read an object from a Zarr store location.

The keyword arguments mode and driver are passed to abczarr.open, and the remaining ones to from_node. A local path is made absolute first, so that the opened node knows where its store lies whatever the working directory.

Parameters:

Name Type Description Default
location str or PathLike

The location of the store.

required
**kwargs Any

mode and driver, and the options of the reader.

{}

Returns:

Type Description
Self

The object read from the store.

Raises:

Type Description
ParserExistsError

If no Zarr store exists at location.

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod
from_instance(other: Any, *args, **kwargs) -> Self

Copy an instance, resetting fields that belong to another format.

The data model copies the fields of other by name. Fields declared by a file format, such as the rawdata array and the metadata of NIfTI and MGH, are copied only from an object of the same format; otherwise the class default is kept, because the same field name holds something different. Converting NIfTI to MGH on save therefore converts the data model only, and the writer rebuilds the format state.

A format that decodes its data or its transformations from its file stores them in the private fields _data and _transformations, where None means that they are decoded. Within the format, the stored values are copied, so a copy of an image whose data was not assigned holds the same rawdata as other, which stays lazy if it is a proxy, and decodes the same record. From another class, the data, the levels of a pyramid and the transformations that other reports are copied, decoded if need be, because its rawdata and its record mean nothing to this format. A format that takes metadata over receives the metadata of other, which its field converts into the metadata of the format, without the record of other.

Parameters:

Name Type Description Default
other object

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The copy.

from_any classmethod
from_any(other: Any, *args, **kwargs) -> Self

Build an object from a file or any value the data model takes.

A path, an open file (any object with a read method), bytes, bytearray or a SourceSpec is read with load. A dispatcher then chooses the best format, and a concrete format reads the input as an instance of its own class. Any other value is passed to the from_any of the data model, which maps a mapping field by field, copies an instance of a similar class, or calls the constructor.

Parameters:

Name Type Description Default
other object

A file, its content, a mapping, or an instance of a similar class.

required
*args Any

Constructor arguments. A file is read with keyword options only.

()
**kwargs Any

Format options when reading a file, and field values otherwise.

{}

Raises:

Type Description
TypeError

If positional arguments accompany a file.

to_singlescale
to_singlescale(index: int = 0) -> SingleScaleImage

Return a level as a single-scale image in world space.

with_scales
with_scales(
    scales: None = None,
    *,
    factor: FactorLike | None = None,
    mode: str | None = None,
    align: str = DEFAULT_ALIGN,
    min_size: int = MIN_SIZE,
    strict: bool = False,
) -> Self
with_scales(
    scales: int,
    *,
    factor: FactorLike | None = None,
    mode: str | None = None,
    align: str = DEFAULT_ALIGN,
    min_size: int = MIN_SIZE,
    strict: bool = False,
) -> Self
with_scales(
    scales: Sequence[FactorLike],
    *,
    mode: str | None = None,
    align: str = DEFAULT_ALIGN,
) -> Self
with_scales(scales: Sequence[SINGLE_SCALE]) -> Self

Return a copy with the given scales, finest first.

A pyramid lets a viewer that shows a large image whole, or an algorithm that works from coarse to fine, read a coarse scale instead of the finest one. This method gives a multiscale object the scales that it should have. The finest scale is always kept.

scales is read by its type:

  • None, the default, builds as many scales as the rules allow.
  • An int is the number of scales, the finest one included. When the rules stop before, fewer scales are built, unless strict is true.
  • A sequence of factors gives, for each coarser scale, its factor from the finest scale along each axis, in a form that FactorLike describes. The factors are positive integers, and the factor of an axis never decreases from a scale to the next.
  • A sequence of scales, such as single-scale images for an image, is the complete list of scales, finest first, which the copy takes as they are. They must be ordered from fine to coarse and share one world space.

The rules build the scales step by step. At each step, an axis is downsampled by its factor of factor, which is 2 for the spatial axes and 1, which leaves an axis as it is, for the other axes by default. An axis is downsampled while it has more than min_size voxels, even when its next scale has fewer, so that an axis of 40 voxels becomes an axis of 20 voxels and an axis of 32 voxels stays as it is. The rules stop when no axis can be downsampled. An axis whose voxels are more than sqrt(f) times larger than the smallest voxels of the axes that can still be downsampled waits, so that anisotropic voxels become roughly isotropic first.

A scale is computed from the scale before it whenever its factors are multiples of the factors of that scale, and from the finest scale otherwise, or always in the mode "nearest", which picks the voxels of the finest scale. A coarser scale that the object already holds is kept when its factors, its placement and its shape are those that are asked for, and the scales after it are built from it. The voxels of a scale lie where align says, and its values are computed as mode says, as brainhops._core.pyramids explains.

Example

pyramid.with_scales()
pyramid.with_scales(4, factor={"z": 1, None: 2})
pyramid.with_scales([2, 4, {"x": 8, "y": 8, "z": 4}])
pyramid.with_scales(3, mode="mode")  # labels
pyramid.with_scales(3, mode="vote_gaussian")  # smooth labels

Parameters:

Name Type Description Default
scales int or sequence

The number of scales, the factors of the coarser scales, or the list of scales. By default, as many scales as the rules allow.

None
factor int or sequence of int or mapping

The factor of each axis at each step of the rules, in a form that FactorLike describes. By default, 2 for the spatial axes. It is refused with a sequence of scales.

None
mode str

How a coarse voxel is computed from the voxels that it covers, one of MODES. By default, "mode", the most frequent value, for an object whose labels is true, so that labels are not averaged, and "mean" otherwise.

None
align (exact, edges, centers)

How the voxels of a coarse scale are laid over those of the finest scale. "exact" crops each axis to a multiple of f and puts the voxel i at the voxel f * i + (f - 1) / 2, which is the rule of OME-NGFF 0.6. "edges" keeps the outer edges of the field of view, with ceil(n / f) voxels, and "centers" keeps the centres of the first and the last voxels, and both pull the voxels by interpolation after smoothing them. The modes "max" and "min" take "exact" only.

"exact"
min_size int

The number of voxels at or below which the rules stop downsampling an axis.

32
strict bool

Whether to refuse to build fewer scales than an int scales asks for.

False

Returns:

Type Description
Self

The copy with its scales.

Raises:

Type Description
TypeError

If scales is none of these types, mixes factors and scales, or comes with factor, or if this class cannot build its scales.

ValueError

If scales is empty, if strict is true and the rules stop early, if the factors are not positive or decrease, if a list of scales is not ordered from fine to coarse or does not share one world space, if a factor downsamples the axis of the vectors of a field, or if the mode or the alignment does not apply.

KeyError

If no axis has a name that a factor gives.

IndexError

If a position that a factor gives is out of range.

to_backend
to_backend(
    backend: BackendLike | None = None,
    *,
    device: DeviceLike | None = None,
) -> ArrayProtocol | None

Return the data as a bare array of the backend of a setting.

The object does not change. Small parameters, such as the matrix of an affine transformation, are converted too, since the caller asks for them. An object without data, such as the identity, gives None.

Parameters:

Name Type Description Default
backend str | module

The setting. By default, the current setting is used.

None
device str | int

The device for converted arrays. The backend supplies its default.

None

Returns:

Type Description
array | None

The data.

to_numpy
to_numpy() -> ArrayProtocol

Return the data as a NumPy array, reading or computing them.

to_cupy
to_cupy(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a CuPy array on the GPU.

to_dask
to_dask(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a Dask array, without reading them.

as_numpy
as_numpy(*, inplace: bool = False) -> Self

Return the object with its data as NumPy arrays.

On an object read from a file, as_numpy(inplace=True) reads the file once and keeps its values.

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_cupy
as_cupy(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as CuPy arrays on the GPU.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_dask
as_dask(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

__array__
__array__(dtype: DTypeLike | None = None) -> ndarray

Convert the data to a NumPy array, optionally of a given type.

reslice
reslice(
    geometry: _GeometryLike | None = None,
    degree: InterpolationLike | None = None,
    bound: BoundaryLike = "reflect",
    coeff: bool = False,
    copy: bool = False,
    *,
    clip: Clip = None,
    dtype: DTypeLike | None = None,
    reframe: bool | ReframeMethodOrCallable = False,
    frame: FrameTargets = -1,
) -> SingleScaleImage

Reslice the level whose voxel size best matches the target grid.

The method always returns a single-scale image.

Parameters:

Name Type Description Default
geometry Image or Geometry or Transformation

The target geometry, interpreted as in SingleScaleImage.reslice.

None
degree int

Spline degree, from 0 (nearest neighbour) up to 7. A degree of 1 gives linear interpolation. By default, the degree is 0 for a label map, whose labels is true, and 1 otherwise.

None
bound str or float

Boundary condition, which says how the data continues beyond its edges. A float is a constant value beyond the edges. The strings are the following names, and their aliases listed in BoundaryCondition, such as 'wrap' for 'grid-wrap':

- 'nearest': nearest edge value  (a a a a | a b c d | d d d d)
- 'reflect': reflect at edge     (d c b a | a b c d | d c b a)
- 'mirror': mirror at edge       (d c b | a b c d | c b a)
- 'grid-wrap': wrap around       (a b c d | a b c d | a b c d)
- 'constant': zero beyond edge   (0 0 0 0 | a b c d | 0 0 0 0)
- 'antimirror': odd mirror       (-b -a 0 | a b c d | 0 -d -c)
- 'antireflect': odd reflection  (-b -a | a b c d | -d -c)
"reflect"
coeff bool

Whether the data already holds spline coefficients. If false, the data is prefiltered before interpolation.

False
copy bool

If true, the output never shares memory with the input. If false, a reslicing that only rearranges existing voxels, such as a flip, a permutation or a slice with a unit step, may return a view, as torch.Tensor.to does. Dask arrays are immutable and are never copied.

False
clip float, pair, sequence of pairs, or None

A scalar sets symmetric margins. A (lower, upper) pair sets asymmetric margins on every input axis; a sequence of pairs follows the input data axes, independently of output permutations. Samples outside the closed interval [-lower, size - 1 + upper] on any axis are zero. None preserves extrapolation with bound. Use 0.5 for the outer voxel edges, 0 for border voxel centres, or -0.5 for inner voxel edges. Inside this interval, bound still extends interpolation stencils; clipping never clamps the coordinates.

None
dtype DTypeLike

Output dtype, as in SingleScaleImage.reslice. None preserves the selected level's dtype.

None
reframe bool | ReframeMethod | str | callable

Whether and how the values of vector and tensor axes are re-expressed, as in SingleScaleImage.reslice.

False
frame int or str or Transformation or None or dict

The frame in which the values are re-expressed, as in SingleScaleImage.reslice.

-1

Returns:

Type Description
SingleScaleImage

The resliced image.

__call__
__call__(transform: Transformation) -> MultiScaleImage

Apply a transformation to the pyramid lazily, without reslicing.

The transformation is handled as in SingleScaleImage.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

images
images() -> list[SingleScaleImage]

Levels of the pyramid, read from node on first access.

The levels read from node are cached, and assigning another node drops them. Assigning a list replaces the levels that were read, and an empty list means that the pyramid has no level. Assigning None reads the levels from node again.

transformations
transformations() -> list[Transformation]

Placements of the pyramid, read from node on first access.

There is one placement per named world space, and the preferred one is last. The list is empty when the levels sit directly in world space. The placements read from node are cached, so a placement appended to the list in place is kept, and assigning another node drops them. Assigning a list replaces the placements that were read, and an empty list means that the pyramid has no placement. Assigning None reads the placements from node again.

from_node classmethod
from_node(node: Any, **kwargs) -> Self

Read a pyramid from an opened Zarr group.

The metadata is parsed immediately, so unreadable metadata is refused when the group is opened rather than on first access.

to_node
to_node(
    node: Any,
    chunks: Any = None,
    version: str | None = None,
    **kwargs,
) -> None

Write the pyramid into an opened Zarr group.

Each level becomes an array named after its index, and the placements of the pyramid become common transformations of the multiscale. When a level does more than scale and translate each axis, the geometries of the levels are split into the scale and the translation of each level and a placement that they share, as the section "Limitations" of brainhops.io.images.zarr explains.

Parameters:

Name Type Description Default
node ZarrGroup

Group that receives the levels and the metadata.

required
chunks sequence of int

Chunk shape of every level, in the brainhops axis order, capped at the shape of each level. By default, the chunks of the finest level when it is a lazy array of a chunked store or a Dask array, and otherwise the chunks that abczarr chooses for the finest level. A Dask array is rechunked to the chunk shape of its level, so that each of its blocks is written into chunks of its own. A shard shape given as shards is capped in the same way.

None
version str

OME-NGFF version. By default, the source version or 0.6 is used.

None
**kwargs Any

Passed to the creation of each level array, except the options of a pyramid (nscales=, factor=, mode=, align=, min_size= and strict=). Given to a pyramid that holds a single level, as io.save gives them, these options build its coarser levels as with_scales builds them, except that each level is computed from the levels already written, read back from the store.

{}

Raises:

Type Description
WriterError

If node is an array, if a level is missing or empty, if the axes or transformations cannot be written, or if the options of a pyramid are given to a pyramid of several levels or are wrong.

UnrepresentableTransformationError

If the levels are rotated, sheared or flipped in different ways, so that their geometries cannot be split into the positive scale and the translation that an OME-NGFF 0.6 dataset holds and a placement that every level shares. This error is a kind of WriterError.

to_store
to_store(
    location: StoreLike,
    chunks: Any = None,
    version: str | None = None,
    **kwargs,
) -> None

Write the pyramid to a store location or an opened group.

A location is opened with mode "w", which replaces any existing store there. The other arguments are those of to_node.

The levels of a pyramid read from a store are lazy arrays of that store. When the location is the local store that they read, the new store is filled beside it and then moved into place, so that the levels are read before the old store is removed.

Raises:

Type Description
WriterError

If the location is the remote store that a level reads, which cannot be replaced without the level reading a store half written.

OmeImageError

Bases: ParserContentError

Error raised when an OME-Zarr image group cannot be read.

The group either has no multiscale metadata, or its metadata does not parse into a valid pyramid.