Skip to content

brainhops.io.images.stack

Image stacks: folders of numbered two-dimensional images.

Light-sheet microscopes, electron microscopes and many export tools write a volume as one image file per slice. This module reads such a folder as one three-dimensional image, a StackImage, and writes an image as such a folder. The files are TIFF files, read and written with tifffile (the tiff extra), or images in a format that Pillow reads and writes (the pillow extra), such as PNG or JPEG.

A folder is read as a stack only when it is asked for, with the format hint "stack" or with StackImage.load. The stack is never recognized from its path, so io.load, io.images.load and io.sniff choose it only with the hint, and a single TIFF or Pillow file is read by its own format.

import brainhops.io as io
from brainhops.io.images.stack import StackImage

image = io.load("slices/", hint="stack")         # a StackImage
image = StackImage.load("slices/")               # the same
image = io.load("slices/", hint="stack", pattern="ch1_*.tif")
image = io.load("slices/", hint="stack", spacing=2.0, unit="um")
image = io.load("slices/", hint="stack", axis="y")  # coronal slices
image.data.shape                                 # (x, y, z) or (x, y, z, c)
image.metadata.raw.names                         # the files, in order
image.save("copy/")                              # a folder of the same files
image.save("out/slice.png")                      # slice_0.png, slice_1.png...
io.save(image, "volume.nii.gz")                  # or any other format
StackImage.from_instance(io.load("volume.nii.gz")).save("slices/")

Files

A stack is a local folder. Its files are, by default, every file of the folder whose extension is that of a TIFF file or of a format that the Pillow reader claims, and subfolders are not searched. The option pattern gives a glob pattern relative to the folder instead, such as "slice_*.png" or "ch1/*.tif", and every file that it selects must be an image file. A pattern cannot reach outside the folder. Hidden files, whose names start with a dot, are never taken. The format of a file is told from its extension, and TIFF files need tifffile while other images need Pillow. A folder that holds a Zarr store is not a stack.

The names of the files must differ in one run of digits only, which is the number of the file, as in z0.tif, z1.tif, ..., z10.tif. The files are sorted by that number, compared as an integer, so z2.tif comes before z10.tif, whether or not the numbers are padded with zeros. The numbers may start at any value, and a number may not be repeated. Names that differ in two numbers, such as t01_z005.tif, are refused, and pattern then selects the files of one stack.

Each file holds one plane, rows and columns, with at most one channel axis, such as the samples of an RGB image. A TIFF file must hold a single series, and a Pillow file a single frame. Every file must have the same format, number of rows, number of columns, number of channels and data type, so that they can be stacked. A file that breaks one of these rules raises a ParserContentError that names it.

Missing slices

The stack has one slice for every number from the first file to the last. A number that no file carries, such as 4 among z3.tif and z5.tif, is a missing slice, which the record lists in StackRaw.missing. Its pixels are the value fill of the reader, which is NaN for a floating type and 0 for any other type by default. Reading a missing slice reads no file. Duplicated numbers and names that follow no single numbering are still refused. An untouched stack is written without its missing slices, while assigned data covers every slice, so a stack with assigned data writes a file for each missing slice, which holds the values that filled it.

Data

The files are stacked along the axis that the option axis names, the slowest axis, z, by default. The columns of a file lie along the first of the two other axes and its rows along the second, which gives the following orders.

axis A file is Stored volume Data
"z" (x, y) (z, y, x[, c]) (x, y, z[, c])
"y" (x, z) (y, z, x[, c]) (x, y, z[, c])
"x" (y, z) (x, z, y[, c]) (x, y, z[, c])

The stored volume is the one that tifffile would spell ZYX for the default axis, and the data of the image is its view in the brainhops order. Within a file, row zero is the top row, so the axis along the rows points down, as for a single TIFF or Pillow image. The file of the first number is the first slice.

After a read, image.rawdata is a lazy array that reads a file only when one of its pixels is needed, with the reader of the single-file format: read_series of the TIFF reader and read_pillow of the Pillow reader. With NumPy as the array backend, image.data reads every file. With Dask, image.data is a Dask array with one chunk per slice, and a file is read only when its chunk is computed.

Geometry

The folder has no header, so it records no origin and no orientation. The geometry of the stack is held by its record, in three fields: pixel_size, the size of a pixel along the columns and the rows of the files, spacing, the distance from one slice to the next, and unit. The image has a single transformation, a Scaling from the voxels to the "physical" system, which these fields scale. A size that the record does not know is 1 along that axis, without a unit.

  • The pixel size is the one that every TIFF file records, read as the TIFF reader reads it: from OME-XML, from ImageJ metadata, or from resolution tags. Pillow files record no size that the Pillow reader uses by default, so their pixel size is unknown.
  • The spacing is the PhysicalSizeZ of the OME-XML that every file records, or else their ImageJ spacing, and a negative ImageJ spacing reverses the stacking axis. Other files do not record it.
  • A size that the files do not all record the same is unknown, and a warning is issued.
  • The options pixel_size, spacing and unit of the reader set the fields instead. pixel_size is one size, or a pair (columns, rows). The sizes that the files record are converted to unit, and the sizes of the options are in unit, or else in the unit that the files record.

Metadata

image.metadata is a StackMetadata, whose record, a StackRaw, lists the files as StackMember objects, in order, and holds the stacking axis and the geometry. Each member gives the name of its file relative to the folder, its number, its axes, shape and type, and its header: the SeriesMetadata that the TIFF reader parses, with the tags, the OME-XML and the ImageJ metadata, or the PillowHeader of a Pillow file, with its mode and the info dictionary of Pillow. Reading the metadata alone, with StackMetadata.load(folder) or MetadataFormat.load(folder, hint="stack"), reads the header of every file but none of their pixels, and takes the same options as the image, except fill.

Writing

image.save(path) writes one file per slice, through the TIFF and Pillow writers of single files, and the path decides the names of the files.

  • A path whose name ends with the extension of a TIFF file or of a format that Pillow writes names the files: the number of each slice is appended to the name before its extension, after an underscore, and padded with zeros to the digits of the largest number. out.tif thus gives out_0.tif, out_1.tif, ..., out_9.tif for ten slices, and out_000.tif to out_119.tif for 120. The files are written in the folder of the path, whose other files are kept.
  • Any other path is the folder of the stack. The files keep the names of the record, and a new stack is named slice_<number>.tif. The folder is written beside its target and then moved in its place. An existing folder is replaced only if it holds nothing but image files, and a folder from which the image reads some files only if it holds nothing else, so that the files of another channel, which a pattern left out, are never removed.

The numbers are those of the record, or 0, 1, 2 and so on for an image without a record. A missing slice is not written. An image that was read and not changed is written by copying its files, so that each file keeps its bytes when it keeps its format. Otherwise, each slice is encoded by the writer of its format. A TIFF file records the pixel size when it has a unit of length, and the magnitude of the spacing when it has no channels, as the PhysicalSizeZ of a volume of one slice. A file with channels is written as a plane, and records no spacing, and a Pillow file records no size. The option axis of the writer cuts the volume along another axis.

Writing follows the rules of the format records: the image is consolidated into a copy, as by StackImage.consolidate, which is written, and the image itself is not changed. A slice of assigned data is written even where the record has no file, since the data of the model takes precedence over the record. When the files that are replaced are files that the lazy array reads, the image is consolidated in place, and its lazy array then reads the new files. Bytes and streams cannot hold a folder, so they are refused. io.save chooses a format from the extension of the path, so it saves a stack to volume.tif as one multi-page TIFF file, and a folder is written with StackImage.from_instance(image).save(folder).

Classes

StackImage magic

StackImage(
    metadata: NoRepr[StackMetadata | 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: BinaryFileReader, BinaryFileWriter, ImageFormat, SingleScaleImage

A volume stored as a folder of numbered two-dimensional images.

Light-sheet microscopes, electron microscopes and many export tools write a volume as one image file per slice, such as z0000.tif, z0001.tif and so on. This class reads such a folder as one image, and writes an image as such a folder. The files are TIFF files, read and written with tifffile, or images in a format that Pillow reads and writes, such as PNG. A stack is never recognized from its path, so a folder is read as a stack only with the format hint "stack", as in load(folder, hint="stack"), or with StackImage.load(folder) (see brainhops.io.images.stack for the rules).

The image holds the list of its files, their headers and the geometry of the stack as StackMetadata, whose record is a StackRaw, and its pixels in rawdata, a lazy array that reads each file only when one of its pixels is needed. A number that no file carries is a missing slice, which the lazy array fills without reading a file. The files are stacked along the axis that the record names, z by default, so the data are indexed (x, y, z), or (x, y, z, c) for files with channels.

The image has one transformation, a [Scaling][] from voxels to "physical", which the record decodes to: the size of the pixels of the files scales the axes along their columns and rows, and the spacing of the slices scales the stacking axis. A size that the record does not know is 1, without a unit, as for a single TIFF or Pillow image.

Assigned data and transformations are pending until [consolidate][] or a write encodes them. A write consolidates a copy, writes it, and leaves the image as it is, except when it replaces files that the lazy array reads (#426).

Parameters:

Name Type Description Default
metadata NoRepr[StackMetadata | 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 until [consolidate][] moves it into rawdata.

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. The constructor still takes transformations in the same place, and the property of the same name reads it. 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 and caches it apart, and assigning other metadata drops that cache.

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

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

()
rawdata NoRepr[ArrayProtocol | None]

The slices stacked along a first axis, or None. After a read, rawdata is a lazy array of shape (slices, rows, columns[, channels]). Assigning data leaves rawdata as it is, and [consolidate][] stores the assigned array here, with its spatial axes in the order of the stored volume.

None
labels NoRepr[LabelsLike]

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

None

Attributes

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

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

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 slices stacked along a first axis, or None.

After a read, rawdata is a lazy array of shape (slices, rows, columns[, channels]). Assigning data leaves rawdata as it is, and [consolidate][] stores the assigned array here, with its spatial axes in the order of the stored volume.

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

The metadata of the stack, 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, so that they are decoded from the new one, and keeps the transformations that were assigned.

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

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

The shape is that of the assigned data, or else the shape of rawdata with its axes in the order of the data. The lazy array knows its shape from the record. An image without data raises as SingleScaleImage does.

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_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_bytes classmethod
from_bytes(content: BinaryContentLike, **kwargs) -> Self

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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.

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_file
to_file(file: FileLike, **kwargs) -> None

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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.

data
data() -> ArrayProtocol | None

The pixels as (x, y, z[, c]), assigned or decoded from rawdata.

An array assigned to the image is returned as it is, and stays pending until [consolidate][] moves it into rawdata. 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. Converted to Dask, the data have one block per slice, and each file is read when its block is computed. To change the pixels, assign data, and assigning None gives the lazy array of the file again.

transformations
transformations() -> list[Transformation]

Voxel-to-world transformations, decoded from the record.

The list is decoded on first access from the geometry fields of the record, and cached, apart from an assigned list, so img.transformation is img.transformation, and a change made to the list in place, such as an appended transformation, is kept. Assigning other metadata drops the decoded list, so that it is decoded from the new record, and keeps an assigned list. A change made in place to a decoded list is therefore lost when other metadata is assigned. An image without metadata has no transformations. Assigning a list replaces the stored one, and assigning None decodes the record again.

to_filename
to_filename(filename: FilenameLike, **kwargs) -> None

Write the image as numbered files, in a folder or beside a name.

A path whose name ends with the extension of a TIFF file or of a format that Pillow writes, such as out.tif or out.png, names the files: the number of each slice is appended to the name, so that the files are out_0.tif, out_1.tif and so on, padded with zeros to the digits of the largest number, in the folder of the path, whose other files are kept. Any other path is the folder of the stack, whose files keep the names of the record, and which replaces any folder of that name that holds only images.

The image is consolidated into a copy with the keyword arguments, as by [consolidate][], which is written, and the image itself is not changed. A slice without a file is not written. The files of an image that was read and not changed are copied, byte for byte, when they keep their format. Every file is written before any is replaced. A folder from which the image reads some files is replaced only if it holds no other file. When the lazy array of the image reads a file that is replaced, the image is consolidated in place instead, so that it holds what the files hold (#426), and its lazy array reads the new files.

Parameters:

Name Type Description Default
filename path - like

The local path of the folder, or the name of the files.

required
**kwargs Any

The options of [consolidate][].

{}

Raises:

Type Description
TypeError

If an unknown option is given.

WriterError

If the path is not local, if the image cannot be encoded, or if the folder to replace holds files that are not images.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    pattern: str | None = None,
    **kwargs,
) -> float

Refuse a path, since a stack is read only with its hint.

A stack is never recognized from its path, neither a folder nor a file, so load chooses this class only with the hint "stack", and this class never takes a folder or a file from another reader.

Parameters:

Name Type Description Default
filename path - like

The path of the folder.

required
error bool or type[Exception]

Whether to raise an error, which tells why the path is not the folder of a stack, or that a stack is read only by hint.

False
pattern str

The glob pattern that selects the files of the stack.

None
**kwargs Any

Other options of the reader, which are ignored.

{}

Returns:

Type Description
float

NO.

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

Refuse a stream, which cannot hold a folder.

Parameters:

Name Type Description Default
file IO

The stream.

required
error bool or type[Exception]

Whether to raise an error, since a stream is never a stack.

False
**kwargs Any

Options of the reader, which are ignored.

{}

Returns:

Type Description
float

NO.

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

Refuse bytes, which cannot hold a folder.

Parameters:

Name Type Description Default
content bytes

The bytes.

required
error bool or type[Exception]

Whether to raise an error, since bytes are never a stack.

False
**kwargs Any

Options of the reader, which are ignored.

{}

Returns:

Type Description
float

NO.

from_filename classmethod
from_filename(
    filename: FilenameLike,
    pattern: str | None = None,
    axis: str | int | None = None,
    pixel_size: float | Sequence[float] | None = None,
    spacing: float | None = None,
    unit: Any | None = None,
    fill: Any | None = None,
    **kwargs,
) -> StackImage

Read the image stack in a folder, without reading pixels.

The header of every file is read to check that the files can be stacked. The lazy array reads the pixels of a file, by name, when they are needed. The options axis, pixel_size, spacing and unit set the fields of the record, which the transformations are decoded from.

Parameters:

Name Type Description Default
filename path - like

The path of a local folder.

required
pattern str

The glob pattern, relative to the folder, that selects the files of the stack, such as "slice_*.tif". By default, every image file of the folder is taken. Hidden files are never taken.

None
axis (x, y, z, 0, 1, 2)

The axis of the volume along which the files are stacked, by name or by its position in (x, y, z). It is z by default, the slowest axis.

"x"
pixel_size float or Sequence[float]

The size of a pixel of the files, one size for the columns and the rows or a pair (columns, rows), which replaces the size that the files record.

None
spacing float

The distance from one slice to the next, which replaces the spacing that the files record. A negative spacing reverses the stacking axis.

None
unit str or Unit

The unit of length of pixel_size and spacing. The sizes that the files record are converted to it.

None
fill number

The value of the pixels of a slice whose number no file carries. It is NaN for a floating type and 0 for any other type by default.

None
**kwargs Any

Other options, which are refused.

{}

Returns:

Type Description
StackImage

The image, whose pixels are read lazily.

Raises:

Type Description
TypeError

If an unknown option is given.

ValueError

If an option is not valid, or if fill cannot be stored in the type of the files.

ParserExistsError

If the folder does not exist.

ParserContentError

If the folder does not hold a stack that can be read: the names of its image files do not follow one numbering, a number is repeated, or the files differ in format, shape, type or number of channels.

StackMetadata magic

StackMetadata(
    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[StackRaw | None] = None,
    *,
    extra: dict[str, Any] = Factory(),
)

Bases: BinaryFileReader, MetadataFormat

Metadata of an image stack, which is the list of its files.

An image stack is a folder of numbered two-dimensional images that form one volume. Its metadata holds a StackRaw record, which lists the files, holds the header of each one and the geometry of the stack. Reading the metadata reads the header of every file, but never their pixels, and the metadata keeps no open file. A folder of headers alone would not be a stack, so the metadata is not written on its own: it is written with the image, by StackImage.

A stack is never recognized from its path, so this class never takes a folder or a file from another reader. The format hint "stack" selects it, as in MetadataFormat.load(folder, hint="stack") (see brainhops.io.images.stack for the rules).

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[StackRaw | None]

The record of the stack, 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

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

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

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[StackRaw | None] = None

The record of the stack, 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_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_bytes classmethod
from_bytes(content: BinaryContentLike, **kwargs) -> Self

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    pattern: str | None = None,
    **kwargs,
) -> float

Refuse a path, since a stack is read only with its hint.

Parameters:

Name Type Description Default
filename path - like

The path of the folder.

required
error bool or type[Exception]

Whether to raise an error, which tells why the path is not the folder of a stack, or that a stack is read only by hint.

False
pattern str

The glob pattern that selects the files of the stack.

None
**kwargs Any

Other options of the reader, which are ignored.

{}

Returns:

Type Description
float

NO.

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

Refuse a stream, which cannot hold a folder.

Parameters:

Name Type Description Default
file IO

The stream.

required
error bool or type[Exception]

Whether to raise an error, since a stream is never a stack.

False
**kwargs Any

Options of the reader, which are ignored.

{}

Returns:

Type Description
float

NO.

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

Refuse bytes, which cannot hold a folder.

Parameters:

Name Type Description Default
content bytes

The bytes.

required
error bool or type[Exception]

Whether to raise an error, since bytes are never a stack.

False
**kwargs Any

Options of the reader, which are ignored.

{}

Returns:

Type Description
float

NO.

from_filename classmethod
from_filename(
    filename: FilenameLike,
    pattern: str | None = None,
    axis: str | int | None = None,
    pixel_size: float | Sequence[float] | None = None,
    spacing: float | None = None,
    unit: Any | None = None,
    **kwargs,
) -> StackMetadata

Read the metadata of the image stack in a folder.

The record is read with StackRaw.from_folder, which reads the header of every file but not their pixels. The options are those of the reader of the image, except fill, which concerns the pixels.

Parameters:

Name Type Description Default
filename path - like

The path of the folder.

required
pattern str

The glob pattern, relative to the folder, that selects the files of the stack. By default, every image file of the folder is taken.

None
axis (x, y, z, 0, 1, 2)

The axis of the volume along which the files are stacked, z by default.

"x"
pixel_size float or Sequence[float]

The size of a pixel of the files, one size or a pair (columns, rows), which replaces the size that they record.

None
spacing float

The distance from one slice to the next, which replaces the spacing that the files record.

None
unit str or Unit

The unit of length of pixel_size and spacing.

None
**kwargs Any

Other options, which are refused.

{}

Returns:

Type Description
StackMetadata

The metadata, which holds the record of the stack.

Raises:

Type Description
TypeError

If an unknown option is given.

ValueError

If an option is not valid.

ParserExistsError

If the folder does not exist.

ParserContentError

If the folder does not hold a stack that can be read.

StackMember magic

StackMember(
    name: str,
    number: int,
    format: str,
    axes: str,
    shape: tuple[int, ...],
    dtype: str,
    header: Any = None,
)

Bases: Magic

One file of an image stack, and what its header says.

A member is a two-dimensional image, possibly with several channels, stored in a TIFF file or in a raster format that Pillow reads, such as PNG. The member records the name of the file, the number that the name carries, and the header that the reader of that format parses: a SeriesMetadata from brainhops.io.images.tiff._utils for a TIFF file, and a PillowHeader from brainhops.io.images.pillow._utils for any other file.

Parameters:

Name Type Description Default
name str

The path of the file relative to the folder, with / separators.

required
number int

The number that the name of the file carries. The number gives the position of the file in the stack. A stack whose names carry several numbers, such as a time point and a slice, would give each member one number per stacking axis, which is not supported yet.

required
format str

The reader of the file: "tiff" (tifffile) or "pillow".

required
axes str

The axes of the decoded file, slowest first, spelled as in tifffile, such as "YX", "YXS" or "SYX".

required
shape tuple[int, ...]

The shape of the decoded file, in the order of axes.

required
dtype str

The NumPy type of the decoded pixels, in native byte order.

required
header Any

The header that the reader of the format parses, or None. It is a SeriesMetadata for a TIFF file, which holds its tags, its OME-XML and its ImageJ metadata, and a PillowHeader for any other file, which holds its mode and the info dictionary of Pillow. It is None in a record that was encoded for files that are not written yet, since the header of a file is known only once the file is written.

None

Attributes

name instance-attribute
name: str

The path of the file relative to the folder, with / separators.

number instance-attribute
number: int

The number that the name of the file carries.

The number gives the position of the file in the stack. A stack whose names carry several numbers, such as a time point and a slice, would give each member one number per stacking axis, which is not supported yet.

format instance-attribute
format: str

The reader of the file: "tiff" (tifffile) or "pillow".

axes instance-attribute
axes: str

The axes of the decoded file, slowest first, spelled as in tifffile, such as "YX", "YXS" or "SYX".

shape instance-attribute
shape: tuple[int, ...]

The shape of the decoded file, in the order of axes.

dtype instance-attribute
dtype: str

The NumPy type of the decoded pixels, in native byte order.

header class-attribute instance-attribute
header: Any = None

The header that the reader of the format parses, or None.

It is a SeriesMetadata for a TIFF file, which holds its tags, its OME-XML and its ImageJ metadata, and a PillowHeader for any other file, which holds its mode and the info dictionary of Pillow. It is None in a record that was encoded for files that are not written yet, since the header of a file is known only once the file is written.

plane_axes property
plane_axes: str

The axes in which the stack presents the file: "YX", or "YXS" for a file with channels.

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

The permutation from axes to plane_axes.

Element i is the position, in the decoded file, of axis i of the presented plane. A channel axis, stored as S or C and wherever it lies, comes last.

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

The shape of the presented plane, (rows, columns[, channels]).

Methods:

StackRaw magic

StackRaw(
    members: tuple[StackMember, ...] = (),
    pattern: str | None = None,
    axis: str = "z",
    pixel_size: tuple[float, float] | None = None,
    spacing: float | None = None,
    unit: str | None = None,
)

Bases: Raw

The record of an image stack, which lists its files.

An image stack is a folder of numbered two-dimensional images, such as slice_000.tif, slice_001.tif and so on, which together form one volume. The folder has no header of its own, so the record lists its members, sorted by the number that their names carry, with the header of each file, and it holds the geometry of the stack: the axis along which the files are stacked, the size of their pixels and the spacing of the slices. The geometry is decoded from the files when they record it, and the options of the reader can set it. Every member has the same format, shape, type and number of channels. The record never reads pixels.

The numbers of the members may skip some values. The stack then has a slice for every number from the first to the last, and the slices whose number no member carries are missing: they have no file, and the lazy array of the image fills them (see missing).

The record is held by StackMetadata. It is frozen, and two records are equal when their fields are.

Parameters:

Name Type Description Default
members tuple[StackMember, ...]

The files of the stack, sorted by their numbers.

()
pattern str | None

The glob pattern that selected the files in the folder, or None when every image file of the folder was taken.

None
axis str

The axis of the volume along which the files are stacked: "x", "y" or "z". The files of a stack along z are (x, y) planes, those of a stack along y are (x, z) planes and those of a stack along x are (y, z) planes. In each case, the columns of a file lie along the first of the two other axes, and its rows along the second.

'z'
pixel_size tuple[float, float] | None

The size of a pixel of the files along their columns and their rows, in unit, or None when it is unknown.

None
spacing float | None

The distance from one slice to the next, in unit, or None when it is unknown. A negative spacing means that the slices run backwards along the stacking axis.

None
unit str | None

The unit of length of pixel_size and spacing, or None when they have no unit.

None

Attributes

members class-attribute instance-attribute
members: tuple[StackMember, ...] = ()

The files of the stack, sorted by their numbers.

pattern class-attribute instance-attribute
pattern: str | None = None

The glob pattern that selected the files in the folder, or None when every image file of the folder was taken.

axis class-attribute instance-attribute
axis: str = 'z'

The axis of the volume along which the files are stacked: "x", "y" or "z".

The files of a stack along z are (x, y) planes, those of a stack along y are (x, z) planes and those of a stack along x are (y, z) planes. In each case, the columns of a file lie along the first of the two other axes, and its rows along the second.

pixel_size class-attribute instance-attribute
pixel_size: tuple[float, float] | None = None

The size of a pixel of the files along their columns and their rows, in unit, or None when it is unknown.

spacing class-attribute instance-attribute
spacing: float | None = None

The distance from one slice to the next, in unit, or None when it is unknown.

A negative spacing means that the slices run backwards along the stacking axis.

unit class-attribute instance-attribute
unit: str | None = None

The unit of length of pixel_size and spacing, or None when they have no unit.

names property
names: tuple[str, ...]

The names of the files, relative to the folder, in order.

format property
format: str | None

The reader of the files, "tiff" or "pillow", or None for a record without members.

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

The numbers of the slices, from the first member to the last, whether a member carries them or not.

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

The numbers of the slices that no member carries, in order.

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

The position of each member along the stacking axis, in order.

axes property
axes: str

The axes of the stored volume, slowest first, as storage codes.

The first axis is the stacking axis, and the two others are the rows and the columns of the files (see [PLANES][brainhops.io.images.stack._raw.PLANES]), followed by S for files with channels. A stack along z is therefore stored as "ZYX" or "ZYXS", as tifffile spells a volume.

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

The shape of the stored volume, in the order of axes.

dtype property
dtype: dtype

The NumPy type of the pixels.

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() -> StackRaw

Return a copy of the record.

The record is frozen and its fields are tuples, so the copy shares its members.

Returns:

Type Description
StackRaw

The copy.

from_folder classmethod
from_folder(
    folder: FilenameLike,
    pattern: str | None = None,
    axis: str | int | None = None,
    pixel_size: float | Sequence[float] | None = None,
    spacing: float | None = None,
    unit: Any | None = None,
) -> StackRaw

Read the record of the image stack that a folder holds.

The files are listed, their names are checked and sorted by the number that they carry, and the header of each file is read. The pixels are not read. The size of the pixels and the spacing of the slices are those on which every file agrees, unless the options set them.

Parameters:

Name Type Description Default
folder path - like

The path of a local folder.

required
pattern str

A glob pattern, relative to the folder, that selects the files of the stack, such as "slice_*.tif". By default, every file of the folder whose extension is that of a TIFF file or of a format that Pillow reads is taken. Hidden files, whose names start with a dot, are never taken.

None
axis (x, y, z, 0, 1, 2)

The axis of the volume along which the files are stacked, by name or by its position in (x, y, z). It is z by default.

"x"
pixel_size float or Sequence[float]

The size of a pixel of the files, one size for the columns and the rows or a pair (columns, rows), which replaces the size that the files record.

None
spacing float

The distance from one slice to the next, which replaces the spacing that the files record. A negative spacing reverses the stacking axis.

None
unit str or Unit

The unit of length of pixel_size and spacing. The sizes that the files record are converted to it.

None

Returns:

Type Description
StackRaw

The record.

Raises:

Type Description
ValueError

If an option is not valid.

ParserExistsError

If the folder does not exist.

ParserContentError

If the path is not a local folder, if it holds no image file, if the names of the files do not follow one numbering, if a number is repeated, or if the files differ in format, shape, type or number of channels.