brainhops.io.images.n5
N5 datasets and pyramids.
N5 is a chunked format of the Saalfeld lab for large arrays, such as
light-sheet or electron microscopy volumes, in which a container is a
directory tree and each dataset stores its blocks as separate files. The
classes of this module only read local containers, with
TensorStore
(pip install brainhops[n5]), and answer to the format hint n5.
| Class | Reads |
|---|---|
N5MultiScaleImage |
every level s0, s1, ... of a pyramid |
N5Image |
one dataset, or one level of a pyramid (level=) |
import brainhops.io as io
pyramid = io.images.load("container.n5/raw") # an N5MultiScaleImage
pyramid.images[0].data.shape # (x, y, z)
pyramid.images[1].transformation # voxel -> physical
level = io.images.load("container.n5/raw", level=2) # an N5Image
dataset = io.images.load("container.n5/raw/s0") # an N5Image
dataset.metadata.raw.attributes # the attributes.json
io.save(dataset, "s0.nii.gz") # to another format
A dataset or a pyramid is named by its directory or by its
attributes.json file. A pyramid of a single level is read as an
N5Image.
Each image holds the attributes as N5Metadata, whose record is an
N5Raw, and the samples of its dataset in rawdata, a lazy array
that TensorStore reads block by block when the data are needed. The data
are indexed in the order of the dimensions of the dataset,
[x, y, z, ...], whose first dimension varies fastest in a block. The datasets
compressed with rawdata, gzip, bzip2, xz and blosc are read,
and the others, such as lz4, zstd or the compressionType of
version 0 of the specification, are refused when they are loaded.
The specification of N5 defines no spatial attribute. Each image maps
its voxels to a "physical" space with the pixelResolution,
resolution, unit, downsamplingFactors, offset and scales
attributes that the n5-viewer, n5-ij, BigDataViewer and Paintera write,
and with the identity when there is none. The conventions are
described, with their sources, in the section on the format below.
N5 containers are not written: the images have no writer, and an image is saved to another format.
The format
A container is a directory tree, and every directory in it is a group. A
group may hold its attributes in a JSON file named attributes.json,
and a dataset is a group whose attributes describe an array, which is
cut into blocks that are stored as separate files:
container.n5/
attributes.json {"n5": "4.0.0"}
raw/
attributes.json {"resolution": [4, 4, 40], "multiScale": true}
s0/
attributes.json {"dimensions": [1000, 800, 50],
"blockSize": [64, 64, 64],
"dataType": "uint8",
"compression": {"type": "gzip", "level": -1}}
0/0/0
0/1/0
...
s1/
attributes.json {..., "downsamplingFactors": [2, 2, 1]}
The attributes of a dataset give its dimensions, its blockSize, its
dataType (uint8 to uint64, int8 to int64, float32,
float64 or object) and its compression, an object whose type is
rawdata, gzip, bzip2, lz4, xz or a scheme of an extension,
such as blosc. Version 0 of the specification named the scheme in a
compressionType string instead. The block at grid position
(i, j, k) is the file i/j/k below the dataset, and a block that is
missing reads as zeros, since datasets are sparse. A block starts with a
big-endian header: a mode (uint16, 0 by default, 1 for a block of
variable length and 2 for serialized objects), the number of
dimensions (uint16), the size of the block along each dimension
(uint32 each, smaller than blockSize for a block at an upper edge)
and, in mode 1, the number of elements (uint32). The samples follow,
big-endian and compressed.
The first dimension varies fastest in a block. The specification does
not say so, but the readers that brainhops relies on agree:
TensorStore decodes a block in Fortran order with the dimensions in the
order of dimensions, and zarr-python reverses dimensions,
blockSize and the grid positions to present the array in C order. In
the usual order of the Java tools, dimensions therefore lists x
first, which is the order of the data of brainhops, and the reverse of
the order of a Zarr array in C order.
The specification defines no spatial attribute, so the voxel size and
the position of a dataset are conventions of its tools. brainhops reads
the following attributes, which apply to the leading dimensions in the
same order as dimensions:
pixelResolution, the size of a voxel of the finest level, as an object{"dimensions": [rx, ry, rz], "unit": "um"}or as a bare array, which has no unit (the n5-viewer, n5-ij and n5-universe);resolution, the same size as a bare array, with the unit of aunitstring when there is one (Paintera, BigDataViewer and n5-universe), read whenpixelResolutionis absent;downsamplingFactors, the factors of a level from the finest one (the n5-viewer, n5-ij, Paintera and BigDataViewer);scales, the factors of every level, finest first, on the group of a pyramid (the deprecated layout of the n5-viewer);offset, a position in the units of the size (Paintera and n5-universe).
A dataset downsampled by f from a finest level of voxel size r has
voxels of size r * f, and its voxel i lies at
r * (f * i + (f - 1) / 2) + o, so that an integer index is the centre
of a voxel, as in brainhops, and the voxels of every level cover the
same extent. The origin o is the offset of the group of a pyramid,
or 0. A dataset that gives its own offset gives the position of its
first voxel instead, so its voxel i lies at r * f * i + offset.
Without these attributes, the voxel size is 1 and has no unit, so the
geometry of a dataset without spatial attributes stays unknown, as for
a raster image. A unit that names no physical length, such as pixel,
gives no unit. An attribute that breaks these conventions is ignored
with an N5AttributeWarning.
The attributes of a dataset that is read on its own are its own, as
the n5-universe library reads them. A pyramid is a group whose
datasets are s0, s1, ..., read up to the first one that is missing.
For a level of a pyramid, an attribute that the dataset does not give
is read from the group: the voxel size from its pixelResolution or
resolution, the factors from its scales, and its offset when the
voxel size comes from the group, as Paintera and the deprecated layout
of the n5-viewer store them. A level that gives no factors, while its
group gives no scales, has factors of 1. brainhops does not infer
factors of 2**k from the name s<k>, which n5-universe does.
Other spatial conventions are not read: the affineTransform of the
n5-viewer, the transform of COSEM, the pixelWidth and xOrigin
attributes of the ImageJ layout of n5-ij, the multiscales of
OME-NGFF, the channel groups c0, c1, ... of the n5-viewer (each of
which is a pyramid of its own), and the registrations of BigDataViewer,
which live in its XML file.
The specification was checked at
saalfeldlab/n5@c489d1653e05b3bac38f433037befd79f62586c4 (tag n5-3.5.1):
the section "File-system specification" of README.md, version 4.0.0,
and DatasetAttributes.java, DataType.java and
DefaultBlockReader.java. The order of the dimensions was checked in
tensorstore/driver/n5/metadata.cc of
google/tensorstore@97c57499888348dca3d41e6d66fb9a69de1ba046 (tag
v0.1.45), whose DecodeChunk reads a block in Fortran order, and in
zarr/n5.py of
zarr-developers/zarr-python@f1978dde52b11a7803a1a06937e69948acc8fe84
(tag v2.18.3), whose N5Store reverses the dimensions. The spatial
attributes were checked in these sources:
- the section "Container structure" of
README.mdof saalfeldlab/n5-viewer@36e75fd88ebcbc88a64da9fb082a28f9b46ded21, which definesdownsamplingFactorsandpixelResolutionon each level and marks thescalesandpixelResolutionof the group as deprecated, andN5ExportMetadataReader.javaat the same commit, which reads them; N5SingleScaleMetadataParser.java(buildTransform, and a barepixelResolutionwithout a unit) andN5GenericSingleScaleMetadataParser.java(resolution,unit, and anoffsetthat replaces the translation) of saalfeldlab/n5-universe@b4ba6f5a0d3de7fef4a1a3f1c4aaaef10e23958d;N5ScalePyramidExporter.java(buildN5VMetadata) of saalfeldlab/n5-ij@248569553f26e7a9522e6d4472b3d0b5267b8cba, which writes thepixelResolutionof the finest level with the factors of averaging, or the voxel size of each level with factors of 1;- the section on supported data of
README.mdof saalfeldlab/paintera@a0ad809d3f9460ade96ba7b705c55341267c4fce, which putsresolutionandoffseton the group of a pyramid marked"multiScale": trueand ignores those of its datasets, andN5Helpers.considerDownsamplingof saalfeldlab/paintera@b629633508f653e1936e3bea96834dcd6f6592e0 (tag paintera-0.23.0), which shifts the levels by half a voxel per factor; BDV N5 format.mdof bigdataviewer/bigdataviewer-core@dfe1a66fd05613dbceaee9211d4266cee3520f98, which writes"multiScale": trueandresolutionon each time point anddownsamplingFactorson each level, for Paintera.
Some conventions are not settled by these sources. Paintera can reverse
resolution and offset, because some tools wrote them in the reverse
order (its option --reverse-array-attributes), and brainhops reads
them in the order of dimensions, as the Java tools write them. The
older n5-viewer read a bare pixelResolution in micrometres, and
n5-universe reads it without a unit, which brainhops follows.
Classes
N5Image
magic
N5Image(
metadata: NoRepr[N5Metadata | None] = Inherit(
"metadata", default=None
),
data: ArrayProtocol | None = Inherit(
"_data", default=None
),
transformations: list[Transformation] | None = None,
frames: NoRepr[Any] = (),
rawdata: NoRepr[ArrayProtocol | None] = None,
level: int | None = None,
*,
labels: NoRepr[LabelsLike] = None,
)
Bases: BinaryFileReader, ImageFormat, SingleScaleImage
One N5 dataset, or one level of an N5 pyramid.
An N5 container is a directory tree in which a dataset is a directory
that holds an attributes.json file and the blocks of an array (see
brainhops.io.images.n5). This class reads
a dataset, named by its directory or its attributes.json file. It
also reads one level of a pyramid, a group whose datasets are s0,
s1, ..., the finest by default or the one that level selects. A
pyramid of several levels is read whole by
N5MultiScaleImage
unless level is given.
The image holds the attributes as N5Metadata, whose record is
an N5Raw, and the samples in rawdata, a lazy array that
TensorStore reads block by block when the data are needed. The data
are indexed in the order of the dimensions of the dataset, whose
first dimension varies fastest in a block, so the axes are named
x, y, z, t and c, as for an array without a description.
The transformation maps the voxels to a "physical" space with the
voxel size, the downsampling factors and the offset that the spatial
attributes of the tools of the N5 ecosystem give, as
brainhops.io.images.n5 describes them.
Without such attributes, the transformation is the identity and the
physical axes have no unit, as for a raster image whose pixel size is
unknown.
N5 containers are not written, so the class has no writer, and
save refuses to write the image as an N5
dataset. Assigned data are pending until [consolidate][] moves them
into rawdata, and the transformations that the image holds, read
or assigned, are kept, since no record can be encoded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[N5Metadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
ArrayProtocol | None
|
The data given to the image, or |
Inherit('_data', default=None)
|
transformations
|
list[Transformation] | None
|
The transformations assigned to the image, or |
None
|
frames
|
NoRepr[Any]
|
The frames of the values, as they were given (see |
()
|
rawdata
|
NoRepr[ArrayProtocol | None]
|
The samples as the dataset stores them, or |
None
|
level
|
int | None
|
The index of the level of a pyramid, where 0 is the finest level |
None
|
labels
|
NoRepr[LabelsLike]
|
Whether the image is a label map, as it was given (see |
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.
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
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:
Noneis 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
|
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 samples as the dataset stores them, or None without data.
After a read, rawdata is a lazy array of the dataset. Assigning
data leaves rawdata as it is, and [consolidate][] stores the
assigned array here.
metadata
class-attribute
instance-attribute
The metadata of the dataset or pyramid, 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.
level
class-attribute
instance-attribute
level: int | None = None
The index of the level of a pyramid, where 0 is the finest level s0.
It is None for a dataset that was read on its own.
shape
property
shape: tuple[int, ...]
The shape of the data, read without reading the samples.
The shape is that of the assigned data, or else the shape of
rawdata, which the lazy array knows 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: |
False
|
**kwargs
|
Any
|
Parser options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. An unsupported input scores zero. |
sniff_file
classmethod
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
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
sniff_lines
classmethod
Same as sniff, for an iterable of lines.
The first line is passed to sniff_line.
sniff_line
classmethod
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
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_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
from_lines
classmethod
Read an object from an iterable of lines.
The first line is passed to from_line.
from_line
classmethod
Read an object from a single line.
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In the base class, which cannot read a line. |
from_dict
classmethod
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 |
from_instance
classmethod
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 |
()
|
**kwargs
|
Any
|
Constructor arguments, which take precedence over the fields
of |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The copy. |
from_any
classmethod
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_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
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
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 |
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
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
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.
Nonewhen it is not known whether the image is a label map.Falsewhen the image is known not to be a label map.Truewhen the image is a label map whose names are not known.- A
LabelTablewhen 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__
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 |
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
|
"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 |
False
|
clip
|
float, pair, sequence of pairs, or None
|
A scalar sets symmetric margins. A |
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
|
frame
|
int or str or Transformation or None or dict
|
The frame in which the values are re-expressed when |
-1
|
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The resliced image. Its metadata is derived from the metadata
of this image with a |
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
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
|
-1
|
method
|
ReframeMethod | str | callable
|
What is applied to the values. |
"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 |
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, |
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
|
UNSET
|
on_loss
|
ErrorAction
|
What to do with a loss, with the same values as a single
action of |
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 |
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 |
data
The samples, 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. To change the samples, assign data, and assigning
None gives the lazy array of the file again.
transformations
transformations() -> list[Transformation]
Voxel-to-physical transformations, decoded from the record.
The list is decoded on first access and cached, apart from an
assigned list, so img.transformation is img.transformation,
and a change made to the list in place 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.
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
level: int | None = None,
**kwargs,
) -> float
Return the confidence that a name designates a dataset.
The name is the directory or the attributes.json file of a
dataset or of a pyramid. A dataset is certainly read by this
class, and so is a pyramid when level is given. A pyramid
without level scores Confidence.LIKELY, below
N5MultiScaleImage,
which reads a pyramid of several levels whole.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The directory or the |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the name designates no dataset and no pyramid. |
False
|
level
|
int
|
The level of a pyramid to read. |
None
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_fileobj
classmethod
Return the confidence that a stream reads dataset attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The stream of the |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the stream holds no attributes of an N5 dataset. |
False
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, |
sniff_bytes
classmethod
Return Confidence.NO, since bytes cannot hold a whole dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The bytes, which are not read. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error, which is then always raised. |
False
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
|
from_filename
classmethod
from_filename(
filename: FilenameLike,
level: int | None = None,
**kwargs,
) -> N5Image
Read a dataset, or one level of a pyramid, from its directory.
Only the attributes are read. The lazy array reads the blocks when the samples are needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The directory or the |
required |
level
|
int
|
The index of the level of a pyramid, 0 (the finest) by default. A negative index counts from the coarsest level. A dataset read on its own takes no level other than 0. |
None
|
**kwargs
|
Any
|
Refused, since the format has no other option. |
{}
|
Returns:
| Type | Description |
|---|---|
N5Image
|
The image, whose samples are read lazily. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If another option is given. |
ParserExistsError
|
If there is no node at that name. |
ParserContentError
|
If the node is neither a dataset nor a pyramid, if there is no such level, or if the samples cannot be read. |
from_fileobj
classmethod
Read a dataset from an open attributes.json file.
The dataset is found from the name of the stream, which must have one, and its attributes are read again from there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
BinaryIO
|
The open |
required |
level
|
int
|
The index of the level of a pyramid, 0 by default. |
None
|
**kwargs
|
Any
|
Refused, since the format has no other option. |
{}
|
Returns:
| Type | Description |
|---|---|
N5Image
|
The image, whose samples are read lazily. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If another option is given. |
ParserTypeError
|
If the stream has no file name. |
N5Metadata
magic
N5Metadata(
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[N5Raw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: MetadataReader, MetadataFormat
Metadata of an N5 dataset or pyramid, which is its attributes.
The metadata of an N5 dataset is the content of its attributes.json
file, held as an N5Raw record. The metadata of a pyramid holds
the attributes of its group and of each of its datasets. It is read
from the directory of the node, from its attributes.json file, or
from the content of that file, and reading it never reads a block.
The metadata keeps no open file and no location. N5 containers are
not written, so the metadata cannot be written either.
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 ( |
None
|
intent
|
IntentEnum | str | None
|
What the values are, as a NIfTI intent name (a known one is an |
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 |
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 |
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 |
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 |
None
|
channels
|
tuple[Channel, ...] | None
|
One description per channel. The descriptions run along the axes of type |
None
|
data_unit
|
Unit | str | None
|
Unit of the data values: a |
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 |
None
|
scale_slope
|
float | None
|
The slope of the intensity scaling: a value is |
None
|
scale_intercept
|
float | None
|
The intercept of the intensity scaling (see |
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 |
None
|
contrast_method
|
ContrastMethod | str | None
|
Contrast method (a known one is a |
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[N5Raw | None]
|
The record of the node, or |
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
A short name for the data.
description
class-attribute
instance-attribute
A free-text description.
history
class-attribute
instance-attribute
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
When the file was created.
sources
class-attribute
instance-attribute
Files the data was derived from (BIDS provenance).
space
class-attribute
instance-attribute
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, in seconds.
echo_time
class-attribute
instance-attribute
Echo time, in seconds.
inversion_time
class-attribute
instance-attribute
Inversion time, in seconds.
flip_angle
class-attribute
instance-attribute
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 responsible for the equipment.
acquisition_time
class-attribute
instance-attribute
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, 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
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
One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."
bvectors
class-attribute
instance-attribute
One unit gradient direction per index along the time axis, in world (RAS) coordinates."
display_range
class-attribute
instance-attribute
Display window (min, max).
channels
class-attribute
instance-attribute
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
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
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
The slope of the intensity scaling:
a value is stored * scale_slope + scale_intercept.
None means no scaling.
scale_intercept
class-attribute
instance-attribute
The intercept of the intensity scaling (see scale_slope).
None means no intercept.
objective_magnification
class-attribute
instance-attribute
Nominal magnification of the objective.
objective_numerical_aperture
class-attribute
instance-attribute
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
The moving image of a registration (file reference).
fixed
class-attribute
instance-attribute
The fixed image of a registration (file reference).
input_space
class-attribute
instance-attribute
Label of the space a transformation maps from.
output_space
class-attribute
instance-attribute
Label of the space a transformation maps to.
extra
class-attribute
instance-attribute
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
instance-attribute
The record of the node, 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: |
False
|
**kwargs
|
Any
|
Parser options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. An unsupported input scores zero. |
sniff_file
classmethod
Same as sniff, for a path or an open file.
sniff_fileobj
classmethod
Score an open file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The open file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the file is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_bytes
classmethod
sniff_bytes(
content: BinaryContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Score the content of a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the content is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_text
classmethod
Score the text of a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the text is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_lines
classmethod
Score the lines of a file, as the record class scores them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
The lines of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the lines are not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_line
classmethod
Score the first line of a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The line. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the line is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
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
Read an object from a path or an open file.
from_fileobj
classmethod
Read the metadata from an open file, through the record class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The open file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
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 the metadata from the content of a file.
The content is read by the record class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_text
classmethod
Read the metadata from the text of a file, through the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_lines
classmethod
Read the metadata from the lines of a file, through the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
The lines of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_line
classmethod
Read the metadata from a single line, through the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The line. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_dict
classmethod
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 |
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 |
()
|
on_loss
|
ErrorAction
|
What to do with the fields that this format cannot store:
|
UNSET
|
on_error
|
ErrorPolicy
|
What to do with a conversion error of the copy, including a
loss (see |
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 |
from_any
classmethod
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 |
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 |
UNSET
|
on_error
|
ErrorPolicy
|
What to do with a conversion error, including a loss (see
|
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 |
Examples:
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 |
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
|
UNSET
|
on_loss
|
ErrorAction
|
What to do with a loss, with the same values as a single
action of |
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 |
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 |
from_raw
classmethod
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,
**kwargs,
) -> float
Return the confidence that a name designates an N5 node.
The name is the directory or the attributes.json file of a
dataset or of a pyramid, and the attributes are read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The directory or the |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the name designates no dataset and no pyramid. |
False
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, |
from_filename
classmethod
from_filename(
filename: FilenameLike, **kwargs
) -> N5Metadata
Read the metadata of an N5 node from its directory or attributes.
The attributes of a pyramid are read with those of its datasets
s0, s1, ...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The directory or the |
required |
**kwargs
|
Any
|
Refused, since the metadata has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
N5Metadata
|
The metadata, which holds the record of the node. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given. |
ParserExistsError
|
If there is no node at that name. |
ParserContentError
|
If the node is neither a dataset nor a pyramid, or its attributes break the specification. |
N5MultiScaleImage
magic
N5MultiScaleImage(
images: list[SingleScaleImage] = (),
transformations: list[Transformation] = (),
*,
metadata: NoRepr[N5Metadata | None] = None,
labels: NoRepr[LabelsLike] = None,
)
Bases: BinaryFileReader, ImageFormat, MultiScaleImage
An N5 pyramid, read as a multiscale image.
An N5 pyramid is a group whose datasets s0, s1, ... hold the same
image at decreasing resolutions, finest first, as the n5-viewer,
Paintera and BigDataViewer write it (see
brainhops.io.images.n5). Each level is an
N5Image whose samples are read lazily, and every level maps its
voxels to the same "physical" space by the spatial attributes of
its dataset and of the group. The pyramid therefore has no
transformation of its own.
The pyramid holds the attributes of the group and of its datasets as
N5Metadata, which its levels share, and it has no rawdata of
its own: each level holds the lazy array of its dataset. A pyramid
of a single level is read as an N5Image by
load, unless this class is asked for.
N5 containers are not written, so the class has no writer.
[consolidate][] only moves the pending data of each level into its
rawdata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
list[SingleScaleImage]
|
Each image in the multi-resolution pyramid, ordered from highest to lowest resolution. |
()
|
transformations
|
list[Transformation]
|
A list of transformations from each level's preferred space to different world spaces. The last transformation in the list is the preferred one. |
()
|
metadata
|
NoRepr[N5Metadata | None]
|
The metadata of the pyramid, which holds its record, or |
None
|
labels
|
NoRepr[LabelsLike]
|
Whether the image is a label map, as it was given (see |
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.
BUILDS_SCALES
class-attribute
BUILDS_SCALES: bool = False
Whether converting a single scale builds the coarser scales.
When it is true, a conversion to this class from a single-scale
object builds as many scales as with_scales() builds, unless
nscales= says otherwise. The formats of OME-Zarr set it.
WRITES_SCALES
class-attribute
WRITES_SCALES: bool = False
Whether the writer builds the coarser scales of a single scale.
When it is true, io.save gives the options of a pyramid to the
writer of this class rather than to the conversion, when it saves a
single scale. The writer then writes the finest scale, and builds
each coarser scale from the scales that it has written, read back
from the store. The formats of OME-Zarr set it.
scales
property
scales: list[SingleScaleImage]
The pyramid levels, from highest to lowest resolution.
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']
images
class-attribute
instance-attribute
images: NotKwOnly[list[SingleScaleImage]] = ()
Each image in the multi-resolution pyramid, ordered from highest to lowest resolution.
transformations
class-attribute
instance-attribute
transformations: NotKwOnly[list[Transformation]] = ()
A list of transformations from each level's preferred space to different world spaces.
The last transformation in the list is the preferred one.
geometry
property
geometry: Geometry
The geometry of the highest-resolution level.
The geometry pairs the grid of the highest-resolution level with the preferred transformation of the pyramid, composed with that level's own transformation.
metadata
class-attribute
instance-attribute
metadata: KwOnly[NoRepr[N5Metadata | None]] = None
The metadata of the pyramid, which holds its record, or None.
A pyramid built from images has no metadata.
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: |
False
|
**kwargs
|
Any
|
Parser options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. An unsupported input scores zero. |
sniff_file
classmethod
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
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
sniff_lines
classmethod
Same as sniff, for an iterable of lines.
The first line is passed to sniff_line.
sniff_line
classmethod
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
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_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
from_lines
classmethod
Read an object from an iterable of lines.
The first line is passed to from_line.
from_line
classmethod
Read an object from a single line.
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In the base class, which cannot read a line. |
from_dict
classmethod
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 |
from_instance
classmethod
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 |
()
|
**kwargs
|
Any
|
Constructor arguments, which take precedence over the fields
of |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The copy. |
from_any
classmethod
Build an object from a file or any value the data model takes.
A path, an open file (any object with a read method), bytes,
bytearray or a SourceSpec is read with load. A dispatcher
then chooses the best format, and a concrete format reads the input as
an instance of its own class. Any other value is passed to the
from_any of the data model, which maps a mapping field by field,
copies an instance of a similar class, or calls the constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A file, its content, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A file is read with keyword options only. |
()
|
**kwargs
|
Any
|
Format options when reading a file, and field values otherwise. |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a file. |
to_singlescale
to_singlescale(index: int = 0) -> SingleScaleImage
Return a level as a single-scale image in world space.
with_scales
with_scales(
scales: None = None,
*,
factor: FactorLike | None = None,
mode: str | None = None,
align: str = DEFAULT_ALIGN,
min_size: int = MIN_SIZE,
strict: bool = False,
) -> Self
with_scales(
scales: int,
*,
factor: FactorLike | None = None,
mode: str | None = None,
align: str = DEFAULT_ALIGN,
min_size: int = MIN_SIZE,
strict: bool = False,
) -> Self
with_scales(
scales: Sequence[FactorLike],
*,
mode: str | None = None,
align: str = DEFAULT_ALIGN,
) -> Self
Return a copy with the given scales, finest first.
A pyramid lets a viewer that shows a large image whole, or an algorithm that works from coarse to fine, read a coarse scale instead of the finest one. This method gives a multiscale object the scales that it should have. The finest scale is always kept.
scales is read by its type:
None, the default, builds as many scales as the rules allow.- An int is the number of scales, the finest one included. When
the rules stop before, fewer scales are built, unless
strictis true. - A sequence of factors gives, for each coarser scale, its
factor from the finest scale along each axis, in a form that
FactorLikedescribes. The factors are positive integers, and the factor of an axis never decreases from a scale to the next. - A sequence of scales, such as single-scale images for an image, is the complete list of scales, finest first, which the copy takes as they are. They must be ordered from fine to coarse and share one world space.
The rules build the scales step by step. At each step, an axis
is downsampled by its factor of factor, which is 2 for the
spatial axes and 1, which leaves an axis as it is, for the other
axes by default. An axis is downsampled while it has more than
min_size voxels, even when its next scale has fewer, so that
an axis of 40 voxels becomes an axis of 20 voxels and an axis of
32 voxels stays as it is. The rules stop when no axis can be
downsampled. An axis whose voxels are more than sqrt(f) times
larger than the smallest voxels of the axes that can still be
downsampled waits, so that anisotropic voxels become roughly
isotropic first.
A scale is computed from the scale before it whenever its
factors are multiples of the factors of that scale, and from the
finest scale otherwise, or always in the mode "nearest", which
picks the voxels of the finest scale. A coarser scale that the
object already holds is kept when its factors, its placement and
its shape are those that are asked for, and the scales after it
are built from it. The voxels of a scale lie where align says,
and its values are computed as mode says, as
brainhops._core.pyramids explains.
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scales
|
int or sequence
|
The number of scales, the factors of the coarser scales, or the list of scales. By default, as many scales as the rules allow. |
None
|
factor
|
int or sequence of int or mapping
|
The factor of each axis at each step of the rules, in a form
that |
None
|
mode
|
str
|
How a coarse voxel is computed from the voxels that it
covers, one of |
None
|
align
|
(exact, edges, centers)
|
How the voxels of a coarse scale are laid over those of the
finest scale. |
"exact"
|
min_size
|
int
|
The number of voxels at or below which the rules stop downsampling an axis. |
32
|
strict
|
bool
|
Whether to refuse to build fewer scales than an int |
False
|
Returns:
| Type | Description |
|---|---|
Self
|
The copy with its scales. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
KeyError
|
If no axis has a name that a factor gives. |
IndexError
|
If a position that a factor gives is out of range. |
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
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
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 |
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
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
__array__
Convert the data to a NumPy array, optionally of a given type.
reslice
reslice(
geometry: _GeometryLike | None = None,
degree: InterpolationLike | None = None,
bound: BoundaryLike = "reflect",
coeff: bool = False,
copy: bool = False,
*,
clip: Clip = None,
dtype: DTypeLike | None = None,
reframe: bool | ReframeMethodOrCallable = False,
frame: FrameTargets = -1,
) -> SingleScaleImage
Reslice the level whose voxel size best matches the target grid.
The method always returns a single-scale image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
Image or Geometry or Transformation
|
The target geometry, interpreted as in
|
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 |
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
|
"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
|
False
|
clip
|
float, pair, sequence of pairs, or None
|
A scalar sets symmetric margins. A |
None
|
dtype
|
DTypeLike
|
Output dtype, as in |
None
|
reframe
|
bool | ReframeMethod | str | callable
|
Whether and how the values of vector and tensor axes are
re-expressed, as in |
False
|
frame
|
int or str or Transformation or None or dict
|
The frame in which the values are re-expressed, as in
|
-1
|
Returns:
| Type | Description |
|---|---|
SingleScaleImage
|
The resliced image. |
__call__
__call__(transform: Transformation) -> MultiScaleImage
Apply a transformation to the pyramid lazily, without reslicing.
The transformation is handled as in SingleScaleImage.
consolidate
consolidate(
*,
inplace: bool = False,
on_error: ErrorPolicy = UNSET,
on_loss: ErrorAction = UNSET,
**fields: Any,
) -> Self
Encode the object into the record that its file format writes.
An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.
What the record cannot hold, such as a field of the metadata that
the format has no slot for, is reported as lost or approximated,
and the error policy of the call decides what happens to the
report: by default, the policy in effect warns (see
metadata_loss_policy).
A format that cannot encode the object at all raises a conversion
error, to which the policy applies as well.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether to change this object rather than a copy. |
False
|
on_error
|
ErrorPolicy
|
What to do with a conversion error, including a loss (see
|
UNSET
|
on_loss
|
ErrorAction
|
What to do with a loss, with the same values as a single
action of |
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 |
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 |
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
level: int | None = None,
**kwargs,
) -> float
Return the confidence that a name designates a pyramid.
The name is the directory or the attributes.json file of a
group. The score is Confidence.CERTAIN for a pyramid of several
levels when no level is given, and Confidence.NO otherwise, so
that N5Image reads a dataset or a single level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The directory or the |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the name designates no pyramid. |
False
|
level
|
int
|
The level to read, which this class does not read alone. |
None
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, |
sniff_fileobj
classmethod
sniff_fileobj(
file: IO,
error: bool | Type[Exception] = False,
level: int | None = None,
**kwargs,
) -> float
Return the confidence that a stream reads the group of a pyramid.
The levels of a pyramid are found from the name of the stream, which must have one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The stream of the |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the stream reads no pyramid. |
False
|
level
|
int
|
The level to read, which this class does not read alone. |
None
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, |
sniff_bytes
classmethod
Return Confidence.NO, since bytes cannot hold a pyramid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The bytes, which are not read. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error, which is then always raised. |
False
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
|
from_filename
classmethod
from_filename(
filename: FilenameLike, **kwargs
) -> N5MultiScaleImage
Read every level of a pyramid from the directory of its group.
Only the attributes are read. The lazy array of each level reads the blocks of its dataset when its samples are needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The directory or the |
required |
**kwargs
|
Any
|
Refused, since the pyramid has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
N5MultiScaleImage
|
The pyramid, whose levels are read lazily. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given. |
ParserExistsError
|
If there is no node at that name. |
ParserContentError
|
If the node is not a pyramid, or a level cannot be read. |
from_fileobj
classmethod
from_fileobj(file: BinaryIO, **kwargs) -> N5MultiScaleImage
Read every level of a pyramid from an open attributes.json.
The pyramid is found from the name of the stream, which must have one, and its attributes are read again from there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
BinaryIO
|
The open |
required |
**kwargs
|
Any
|
Refused, since the pyramid has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
N5MultiScaleImage
|
The pyramid, whose levels are read lazily. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given. |
ParserTypeError
|
If the stream has no file name. |
N5Raw
magic
N5Raw(
attributes: dict[str, Any],
dimensions: tuple[int, ...] | None = None,
block_size: tuple[int, ...] | None = None,
data_type: str | None = None,
compression: dict[str, Any] | None = None,
levels: tuple[N5Raw, ...] = (),
)
Bases: Raw, BinaryFileReader
The attributes of an N5 dataset, or of a group that holds a pyramid.
An N5 container is a directory tree in which every directory is a
group, and each group may hold its attributes in a JSON file named
attributes.json. A dataset is a group whose attributes give its
dimensions, its blockSize, its dataType and its compression,
and whose blocks are files below it. The record holds the attributes
of one directory as the file stores them, in attributes, together
with the mandatory attributes of a dataset, read and checked.
A group whose subdirectories s0, s1, ... are datasets holds a
pyramid, finest first, as the n5-viewer, Paintera and BigDataViewer
write it. The record of such a group has no mandatory attributes of
its own, and lists the records of its datasets in levels.
Reading a record never reads a block. A record is frozen, and two
records are equal when their fields are. The record is held by
N5Metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attributes
|
dict[str, Any]
|
The content of |
required |
dimensions
|
tuple[int, ...] | None
|
The number of samples along each dimension, fastest first. The first dimension varies fastest in a block, so it is |
None
|
block_size
|
tuple[int, ...] | None
|
The size of a block along each dimension, or |
None
|
data_type
|
str | None
|
The |
None
|
compression
|
dict[str, Any] | None
|
The |
None
|
levels
|
tuple[N5Raw, ...]
|
The records of the datasets |
()
|
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.
attributes
instance-attribute
The content of attributes.json, or an empty dictionary.
Every attribute is kept, including those that the specification does
not define, such as the spatial attributes that brainhops interprets
(see brainhops.io.images.n5).
dimensions
class-attribute
instance-attribute
dimensions: tuple[int, ...] | None = None
The number of samples along each dimension, fastest first.
The first dimension varies fastest in a block, so it is x in the
usual order of the Java tools. It is None for a group.
block_size
class-attribute
instance-attribute
block_size: tuple[int, ...] | None = None
The size of a block along each dimension, or None for a group.
data_type
class-attribute
instance-attribute
data_type: str | None = None
The dataType of the samples, such as "uint16", or None.
compression
class-attribute
instance-attribute
The compression of the blocks, or None for a group.
It is a dictionary whose type names the scheme, such as "raw" or
"gzip", beside the parameters of the scheme. A dataset of version 0
of the specification gives only a compressionType, which is read as
{"type": compressionType}.
levels
class-attribute
instance-attribute
levels: tuple[N5Raw, ...] = ()
The records of the datasets s0, s1, ... of a pyramid.
They are listed finest first, and the tuple is empty for a dataset or a group that holds no pyramid.
dtype
property
dtype: dtype
The NumPy type of the samples, in the native byte order.
Raises:
| Type | Description |
|---|---|
ParserContentError
|
If the record is a group, or its samples are serialized objects, which have no NumPy type. |
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: |
False
|
**kwargs
|
Any
|
Parser options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. An unsupported input scores zero. |
sniff_file
classmethod
Same as sniff, for a path or an open file.
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for a path.
A missing file scores Confidence.NO, or raises
SnifferExistsError if error is set. A compressed file is
decompressed as it is read.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_bytes
classmethod
sniff_bytes(
content: BinaryContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for binary content.
Compressed content is decompressed first. The content is then
wrapped in an io.BytesIO and scored with sniff_fileobj, so
that a class that scores a stream also scores bytes. If that
method only reads the stream back into bytes, as the default
does, the content would come back to this method, which then
raises instead.
Raises:
| Type | Description |
|---|---|
SnifferNotImplementedError
|
If neither this method nor |
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
sniff_lines
classmethod
Same as sniff, for an iterable of lines.
The first line is passed to sniff_line.
sniff_line
classmethod
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
Read an object from a path or an open file.
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
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_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
from_lines
classmethod
Read an object from an iterable of lines.
The first line is passed to from_line.
from_line
classmethod
Read an object from a single line.
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In the base class, which cannot read a line. |
from_dict
classmethod
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 |
from_instance
classmethod
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
Noneleaves the default of the class in place. - Extra arguments (
*argsand**kwargs) are passed to the constructor and take precedence. - Unless
otheris 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 toother.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 |
()
|
**kwargs
|
Any
|
Constructor arguments, which take precedence over the fields
of |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ConversionError
|
If the class of |
ValueError
|
If a fixed field of |
from_any
classmethod
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
|
to
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 |
Raises:
| Type | Description |
|---|---|
ConversionError
|
If |
copy
copy() -> N5Raw
Return a copy of the record.
The attributes and the compression are copied deeply, so that the copy shares no mutable value with the record.
Returns:
| Type | Description |
|---|---|
N5Raw
|
The copy. |
from_fileobj
classmethod
Read the attributes of an N5 node from a stream.
The stream holds an attributes.json file. A record read from a
stream has no levels, because the datasets of a pyramid are other
files. The position of the stream is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
BinaryIO
|
The stream of the |
required |
**kwargs
|
Any
|
Refused, since the record has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
N5Raw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given. |
ParserContentError
|
If the stream does not hold a JSON object, or holds the attributes of a dataset that break the specification. |
sniff_fileobj
classmethod
Return the confidence that a stream holds dataset attributes.
The stream must hold a JSON object with the mandatory attributes of a dataset, which the specification requires. The attributes of a group are not recognized from their content alone, since any JSON object may be the attributes of a group. The position of the stream is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The stream to test, open in binary mode. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the content is not the
attributes of a dataset. With |
False
|
**kwargs
|
Any
|
Ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, |
Raises:
| Type | Description |
|---|---|
SnifferContentError
|
If the content is not the attributes of a dataset and |
N5AttributeWarning
Bases: UserWarning
A spatial attribute of an N5 node was ignored.
The spatial attributes of N5 are conventions of its tools, not part
of its specification, so a value that breaks a convention, such as a
pixelResolution of the wrong length or a unit that brainhops does
not know, is ignored with this warning instead of making the dataset
unreadable.