Skip to content

brainhops.datamodel.multiscale

Pyramids of scales, and the method that builds their coarser scales.

A multiscale object, such as a MultiScaleImage or a MultiscaleField, holds the same image or field at several resolutions, finest first, so that a viewer or an algorithm that only needs a coarse view reads less data. Multiscale.with_scales gives it the scales that it should have: as many as the rules allow, a number of them, the factors of each of them, or a complete list of them. The arithmetic, its modes, its alignments and its edges are explained in brainhops._core.pyramids.

A conversion builds the scales too, with the same values under the keyword nscales= and the keywords factor=, mode=, align=, min_size= and strict= of with_scales: image.to(MultiScaleImage, nscales=4) calls with_scales(4) on the converted pyramid. A class whose BUILDS_SCALES is true, such as the formats of OME-Zarr, builds them even without nscales= when it is converted from a single scale, as with_scales() builds them, so that image.to(OmeZarrImage) and io.save(image, "image.ome.zarr") write a full pyramid, and nscales=1 keeps the single scale.

Attributes

AxisReference module-attribute

AxisReference: TypeAlias = int | AxisQuery

One axis of a pyramid: its position, its name or another axis query.

FactorLike module-attribute

FactorLike: TypeAlias = (
    int | Sequence[int] | Mapping[AxisReference | None, int]
)

The factor of each axis of one level, in one of three forms.

An int is the factor of every axis that is downsampled by default, which are the spatial axes, and the other axes get 1. A sequence gives one factor per axis of the arrays, or one factor per axis that is downsampled by default, in their order. A mapping gives the factor of the axes that it names, by position, which counts from the end when it is negative, or by name, and the other axes get 1, unless the mapping has the key None. The factor of the key None goes to every axis that an int would downsample and that the mapping does not name, so that {"z": 1, None: 2} halves the spatial axes but z. It never reaches an axis that an int leaves alone, such as a time axis or the axis of the vectors of a field, which a mapping must name to downsample. A factor of 1 leaves its axis as it is.

Classes

Multiscale magic

Multiscale(scales: list[SINGLE_SCALE] = ())

Bases: DataModelBase, Generic[SINGLE_SCALE]

Mixin for a pyramid of scales, finest first.

Index 0 is the scale with the highest resolution.

This base class provides the list of scales, the operations that select one of these scales, and the method that gives the pyramid its scales, with_scales.

It does not define what a scale is: a subclass supplies the scales and, by registering its version of the internal function level_resolution, the physical grid size of each one, from which nearest_level picks the scale whose resolution is closest to a target grid. A subclass that builds its scales also registers its versions of the internal functions pyramid_layout, build_scales, keeps_scale, check_scales and adopt_scales of brainhops.datamodel._multiscale.

Parameters:

Name Type Description Default
scales list[SINGLE_SCALE]

Scales, from finest to coarsest.

()

Attributes

BUILDS_SCALES class-attribute
BUILDS_SCALES: bool = False

Whether converting a single scale builds the coarser scales.

When it is true, a conversion to this class from a single-scale object builds as many scales as with_scales() builds, unless nscales= says otherwise. The formats of OME-Zarr set it.

WRITES_SCALES class-attribute
WRITES_SCALES: bool = False

Whether the writer builds the coarser scales of a single scale.

When it is true, io.save gives the options of a pyramid to the writer of this class rather than to the conversion, when it saves a single scale. The writer then writes the finest scale, and builds each coarser scale from the scales that it has written, read back from the store. The formats of OME-Zarr set it.

scales class-attribute instance-attribute
scales: NotKwOnly[list[SINGLE_SCALE]] = ()

Scales, from finest to coarsest.

nscales property
nscales: int

Number of scales.

Methods:

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

Return the scale at index, where 0 is the finest.

The scale is returned as it is stored: for a field, it is the plain transformation of that scale, not a multiscale field.

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.

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.