Skip to content

brainhops.io.transformations.itk.nifti

ITK non-linear warps stored as NIfTI vector images, in LPS.

ITK and ANTs store a dense displacement field as a NIfTI vector image. The encoding differs from the RAS fields of brainhops.io.transformations.nifti in three ways.

  1. Layout. The image is 5-D: (X, Y, Z, 1, 3) in 3-D and (X, Y, 1, 1, 2) in 2-D, with singletons for the missing dimensions and the components on the fifth axis.
  2. Intent. ITK writes NIFTI_INTENT_VECTOR (1007). Since ITK 5.4, it writes NIFTI_INTENT_DISPVECT (1006) only when the metadata of the image explicitly asks for it.
  3. Frame. The header affine is the usual RAS sform or qform, but the vector values of a VECTOR file are not converted and stay in LPS. Since ITK 5.4, the first two components of a three-component DISPVECT file are flipped between RAS in the file and LPS in memory; two-component files are never converted.

An ITK field therefore maps x_lps to x_lps + u_lps(x), and the same displacement in RAS is (-u_x, -u_y, u_z). In 2-D, ITK negates the x and y rows of the geometry as well, so a 2-D image is expressed in (L, P) and the displacement (u_x, u_y) is (-u_x, -u_y) in (R, A). The same classes read both dimensionalities, and their endpoints are the ITK spaces used by the .tfm and .h5 readers, so that a warp and an affine from ITK name the same space.

Telling an ITK field from a RAS NIfTI field

The header alone does not always reveal which frame a field uses:

Header Read as, without a hint
VECTOR (1007), ITK's layout ambiguous: AmbiguousFormatError
VECTOR (1007), named "Mapping" RAS coordinates (SPM12, brainhops)
DISPVECT (1006) RAS displacements
no intent (0) RAS coordinates
  • VECTOR is what ITK writes, but it is a generic code. The ITK reader and the RAS reader claim it equally, so loading such a file without further evidence raises AmbiguousFormatError.
  • The intent name "Mapping", used by SPM12 y_ deformations and by the brainhops RAS writer, is such evidence, since ITK never writes an intent name.
  • A hint settles the question. With load(path, hint="itk"), or with hint="ants", the file is read as an ITK displacement field whatever its intent, and with hint="itk.coordinates" it is read as an ITK coordinate field. Calling ItkNiftiDisplacementField.from_file(path) does the same. A three-component DISPVECT file read this way has its RAS vectors converted to LPS, as ITK does.
  • ITK and ANTs only write displacements, so an absolute LPS coordinate field is never claimed from the content alone. ANTs file names such as *Warp.nii.gz are not used as evidence either.

Fields in 2-D and 3-D are supported. ITK can also write 4-D vector images, but these are not read, because NIfTI has no geometry for the fourth axis.

Sources
  • ITK Modules/IO/NIFTI/src/itkNiftiImageIO.cxx (WriteImageInformation, SetNIfTIOrientationFromImageIO, ReadImageInformation, ConvertRASToFromLPS_*) and Modules/IO/NIFTI/include/itkNiftiImageIO.h (ConvertRASVectors, off by default, and ConvertRASDisplacementVectors, on by default, both new in v5.4.0). https://github.com/InsightSoftwareConsortium/ITK/blob/v5.4.0/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx
  • NiTransforms nitransforms/io/itk.py, ITKDisplacementsField, which requires the (X, Y, Z, 1, 2|3) shape and the vector intent, and negates components 0 and 1 between ITK (LPS) and RAS. https://github.com/nipy/nitransforms/blob/master/nitransforms/io/itk.py
  • ANTs writes the antsRegistration warps (<prefix><n>Warp.nii.gz, <prefix><n>InverseWarp.nii.gz) with itk::ImageFileWriter (itk::ants::WriteTransform in Utilities/itkantsReadWriteTransform.h), so they follow this encoding, and the readers treat hint="ants" in the same way as hint="itk".

Classes

ItkNiftiCoordinateField magic

ItkNiftiCoordinateField(
    transformations: tuple[Transformation, ...]
    | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = Inherit(
        "rawdata", var=True
    ),
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None, var=True
    ),
    *,
    input: CoordinateSystem | None = None,
    output: CoordinateSystem | None = None,
    image: NoRepr[Any | None] = Field(
        default=None, convert=False
    ),
    data: NoRepr[ArrayProtocol | None] = None,
)

Bases: ItkNiftiField

Field of absolute LPS coordinates stored as an ITK NIfTI vector image.

Each voxel holds the LPS position that it maps to. The field is a Sequence of two named slots:

Slot Transformation
lps2voxel LPS world coordinates to the field's voxels
coordinates the field of LPS coordinates, on that grid

ITK and ANTs only write displacement fields, and a header cannot say whether it holds displacements or positions. This reader is therefore never chosen from the content of a file, only with hint="itk.coordinates" or by using the class directly.

Parameters:

Name Type Description Default
transformations tuple[Transformation, ...] | None
None
rawdata NoRepr[ArrayProtocol | None]
Inherit('rawdata', var=True)
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None, var=True)
input CoordinateSystem | None

Input coordinate system, which may be inferred from context if unset.

None
output CoordinateSystem | None

Output coordinate system, which may be inferred from context if unset.

None
image NoRepr[Any | None]

The image that holds the file, which the constructor always sets. The image describes the file as it was read, or as the transformation was last consolidated, and it never holds pending data or transformations.

Field(default=None, convert=False)
data NoRepr[ArrayProtocol | None]

The vectors given to the field, or None to decode them from rawdata. Vectors stored here are pending until [consolidate][] or a write encodes them into rawdata.

None

Attributes

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

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

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

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

Names of the attributes that define the encoding.

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

Names of the derived attributes, such as views and caches.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

metadata property writable
metadata: Any | None

The metadata of the file, which holds its header, or None.

The metadata is that of the stored image. A transformation built from its data alone has none. Assigning other metadata replaces the stored image with a copy that holds it, converted into the metadata of the image class, and drops the views decoded from the previous header.

rawdata property writable
rawdata: ArrayProtocol | None

The array of the file as it is stored, or None without one.

The array is the rawdata of the stored image. After a read, it is a lazy array of the file, which applies the scaling of the header when it is read. It describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is. Assigning rawdata replaces the stored image with a copy that holds the new array.

lps2voxel property
lps2voxel: Transformation | None

The affine from LPS world coordinates to the voxels of the field.

PRIORITY class-attribute
PRIORITY: int = -1

Priority below the displacement reader.

Under hint="itk", a file in the ITK layout without the VECTOR intent is claimed by neither reader, and the tie is resolved in favour of displacements, which is what ITK and ANTs write.

coordinates property
coordinates: Transformation | None

The field of LPS coordinates, on the grid of the field.

Methods:

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

Write the object to a path or an open file.

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

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

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

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

Return the lines of the file, without terminators.

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

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

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

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

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

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

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

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

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

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

sniff_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_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

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

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

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

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

Raises:

Type Description
TypeError

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

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

Read an object from a path or an open file.

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

Read a transformation from the path of its file.

The file is read by the reader of the image class, whose array is read lazily, and the transformation is built from that image with from_image. The keywords that name an argument of the constructor of the transformation, under any of their aliases, go to the transformation, and the other keywords go to the reader of the image, which refuses those that it does not know.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the reader of the image, such as mmap, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

from_fileobj classmethod
from_fileobj(file: BinaryIO, **kwargs: Any) -> Self

Read a transformation from an open stream of its file.

The stream is read by the reader of the image class, whose lazy array keeps the stream, so the stream must stay open while the array may be read. The transformation is built from that image with from_image, and the keywords are shared out as by from_filename.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of the reader of the image, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

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

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

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

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

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

Raises:

Type Description
ValueError

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

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: Type[Transformation] | None = None,
    *,
    copy: bool = False,
    **kwargs,
) -> Transformation

Convert the chain to another type or encoding.

A chain has no tangent of its own, because the tangent of a composition is not the sum of the tangents. A log= keyword therefore re-encodes the transformation that the chain reduces to, which is possible in three cases:

  • A chain that simplifies to a single transformation is converted as that transformation.
  • A change of coordinates [P, *X, P^-1] (see Sequence.sqrt) keeps its ends and re-encodes X, which is exact because the flow of a velocity commutes with a change of coordinates.
  • A chain of affine transformations is composed.

Any other chain raises a ConversionError before anything is computed. Without log=, the conversion follows Transformation.to, and so do copy=, on_loss= and on_error=. With log=, on_loss= and on_error= apply to the whole conversion of the chain.

to_numpy
to_numpy() -> ArrayProtocol

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

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

Return the data as a CuPy array on the GPU.

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

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

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

Return the object with its data as NumPy arrays.

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

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

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

Parameters:

Name Type Description Default
device str | int | None

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

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

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

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

input
input() -> CoordinateSystem | None

The ITK physical space that the field maps from.

output
output() -> CoordinateSystem | None

The ITK physical space that the field maps to.

compute
compute(
    mode: ModeLike = True,
    *,
    simplify: SimplifyLike = "analytic",
    factor: bool = False,
) -> Transformation

Compute the transformation that results from the chain.

With mode=True, a chain of affine-like transformations yields an affine-like transformation, and a chain whose first applied element is a coordinate field yields a coordinate field. When the first applied element is affine-like but the chain contains other elements, the result is a sequence of two: the composition of the affine-like elements before the first other element, then the composition of everything from that element onward.

Parameters:

Name Type Description Default
mode ModeLike

Kinds to compose, as a name, a type or a list of them. True composes everything, and False only simplifies.

True
simplify SimplifyLike

Simplification policy applied before composition: "analytic" uses the type structure only, "numeric" also inspects the values of matrix transformations, {None: "numeric"} inspects the values of every transformation, and False, "none" or None disables simplification.

"analytic"
factor bool

Whether to rewrite the chain into a normal form organized by groups of axes, [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?]. The normal form starts with an optional grid and an optional projection that drops the inputs that nothing reads. It continues with one subspace factor for each group of axes that transform together, where each factor preserves its axes, and it ends with an optional permutation and an optional projection that creates the outputs that read no input. Nothing is composed across groups. The option is ignored with mode=False.

False
simplify
simplify(
    policy: SimplifyLike = "analytic",
    *,
    compute: ModeLike | bool | None = False,
) -> Self

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

factor
factor(
    policy: SimplifyLike = "analytic",
    *,
    compute: ModeLike | bool | None = False,
) -> Transformation

Rewrite the chain as one factor per group of axes.

The axes of a chain often fall into groups that never interact, as when each axis is scaled on its own and two axes are then swapped. Factoring finds those groups and rewrites the chain as [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?], with one axis-preserving factor F_i = Subspace(inner_i, A_i, A_i) per group, ordered by their first axis, and a permutation that carries each group to the axes that it occupies at the output (see [factor_sequence][brainhops.datamodel._transformations.compute.factor.factor_sequence]). The projection delta drops the inputs that no output reads, and the projection kappa creates the outputs that read no input, at their constant values. Nothing is composed across groups, so the coordinates of independent axes are never tiled into a grid over all of them, and each group can be resampled on its own.

The chain is unnested first, and a leading CartesianField is the sampling grid, which is kept as the same object. Every other element is cut into one piece per group, and an element that lies within a single group is kept as it is, so a lazy inverse stays lazy and still cancels with its forward transformation.

Note

The pass reads the chain as it stands, and it is idempotent. It declines a chain in which an element shifts or scales an output that reads no input, because it carries such a constant only through the elements that pass it through unchanged. compute with factor=True composes such a chain, and then simplifies and factors the result.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the elements may be read, with the values and the meaning of the policy of [simplify][]. Under the analytic policy, a matrix couples all its axes, and under the numeric policy, its exact zeros are read, so that an affine with independent axes splits.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. The default, False, composes nothing, so each factor holds the sub-chain of its own group, whereas True leaves each factor holding a single transformation.

False

Returns:

Type Description
Transformation

The normal form, or self when the chain is already in normal form or does not factor at all, as when it forms a single group and has neither end, its two ends differ in dimension in a way that the end projections do not explain, a grid sits inside it, or one of its elements cannot be read or restricted. An Identity is returned when no factor is left.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

square
square(compute: bool = False, **kwargs) -> Transformation

Return the transformation composed with itself.

The square is the Sequence [self, self], which is composed when it is computed. It is defined only for a transformation that maps a space to itself.

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

sqrt
sqrt(compute: bool = False, **kwargs) -> Transformation

Return the principal square root of the chain.

The chain is first simplified. A chain of the form [P, *X, P^-1] is a change of coordinates around X, and its square root is [P, sqrt(X), P^-1]. The chain has this form when its last element is the lazy inverse of its first element, or when its two ends are affine transformations whose product is exactly the identity. Any other chain is composed, and the square root of the result is returned.

Raises:

Type Description
DomainError

If the chain does not map a space onto itself, or if the square root of its reduced form is undefined (see DomainError).

NotImplementedError

If the chain is not a change of coordinates and does not compose to a single transformation.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

bridge
bridge() -> Self

Reconcile the coordinate systems at every boundary of the chain.

Two neighbours in a chain share a coordinate system: the output system of one is the input system of the next. Where the two disagree, as when one works in millimetres and the next in voxels, or when the two name the same axes in a different order, a bridge is inserted between them. A bridge reads no parameter, so bridging costs nothing, and two opposite bridges cancel when the chain is simplified.

Bridging is also the only pass that lengthens a chain, which is why compute runs it before anything else: a bridge reads its neighbours, and a reversed array-index axis needs the extent of the adjacent grid, which composition may drop.

A nested sequence is bridged in place and stays nested, so a boundary that it hides is reconciled inside it. Call flatten afterwards for a flat chain. A sequence with a fixed shape, such as a geometry or a multiscale field, is left alone. A generic Inverse is replaced by the typed inverse of its forward transformation, so that the engine can compute it and cancellation can recognize it. No leaf has its endpoints rebuilt.

Returns:

Type Description
Sequence

The chain, with a bridge at each boundary that needed one.

Raises:

Type Description
AdaptationError

If a boundary cannot be bridged, because an axis that must be matched has no counterpart on the other side.

flatten
flatten(endpoints: bool = True) -> Self

Splice the nested sequences of the chain into the chain itself.

A chain whose elements are themselves chains applies exactly as the flat chain of their elements, so flattening changes nothing about what the transformation does. It is what lets the simplifier and the composers see two leaves as neighbours when a nesting boundary sits between them.

A nested child is asked to flatten itself, so a child with a shape of its own contributes what it chooses: a geometry contributes its grid and its transformation, and a multiscale field contributes the elements of its finest scale.

Parameters:

Name Type Description Default
endpoints bool

Whether to push the coordinate systems of the chain onto its first and last element, which is where the composers read them. A child with a shape of its own may contribute a sequence, so one level of nesting can survive this mode, and the next pass splices it. With endpoints=False, nesting is unwound all the way to the leaves in one pass, no leaf is rebuilt and each one stays the same object, so that a transformation still cancels with the lazy inverse that names it; a generic Inverse is then also replaced by the typed inverse of its forward transformation.

True

Returns:

Type Description
Sequence

The flattened chain.

data
data() -> ArrayProtocol | None

The stored vectors, as an (X, Y, Z, 3) or (X, Y, 2) array.

Vectors that are assigned are returned as they are, and stay pending until [consolidate][] or a write encodes them. Otherwise they are decoded from rawdata without the singleton axes of the ITK layout, and they are those of the file, before the frame of a DISPVECT file is converted. Assigning the data drops the chain decoded from the previous data.

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

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

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

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

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

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

UNSET
on_loss ErrorAction

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

UNSET
**fields Any

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

{}

Returns:

Type Description
Self

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

Raises:

Type Description
TypeError

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

MetadataLossError

If something is lost under the "raise" policy.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an object from a nibabel image or header.

The array of an image becomes rawdata, and a copy of its header becomes the record of the metadata. A header alone gives an object without an array. The array proxy of an image that nibabel read from a file is replaced by the lazy array that from_filename builds for that file, and any other array is kept as it is.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the object.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(**options) -> _NibabelImage

Build the nibabel image that a file written from this object holds.

The object is consolidated with the options into a copy, and the nibabel image holds the rawdata and the header of that copy. The object itself is not changed.

Parameters:

Name Type Description Default
**options Any

The options of consolidate, such as the template like and the fields of the header.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

Raises:

Type Description
WriterError

If the object has no array to write.

from_image classmethod
from_image(image: Any, **options: Any) -> Self

Build a transformation from the image that stores it.

The image becomes the stored image of the transformation, and the transformation decodes its data and its chain from that image when they are needed. The call is the same as cls(image=image, **options).

Parameters:

Name Type Description Default
image Any

The image, of the class that IMAGE names, which is consolidated first if it has pending data or transformations.

required
**options Any

The other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation.

Raises:

Type Description
TypeError

If the image is not of the class that IMAGE names.

to_image
to_image() -> Any

Return the image that a file of this transformation holds.

The transformation is consolidated into a copy, as by [consolidate][], and the stored image of that copy is returned. The transformation itself is not changed.

Returns:

Type Description
Any

The image, of the class that IMAGE names, without pending data or transformations.

score_header classmethod
score_header(header: NiftiObject) -> float

Claim only the files that brainhops writes as such fields.

ITK and ANTs never write a field of coordinates, so a file is read as one only with a hint, or when it is a VECTOR image in the ITK layout that carries the intent name "ITKCoordinates", which brainhops writes on it.

transformations
transformations() -> tuple[Transformation, ...]

The chain of transformations that the field encodes.

The chain is built lazily from the header and the data, and then cached. Assigning a chain overrides the derived one.

ItkNiftiDisplacementField magic

ItkNiftiDisplacementField(
    transformations: tuple[Transformation, ...]
    | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = Inherit(
        "rawdata", var=True
    ),
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None, var=True
    ),
    *,
    input: CoordinateSystem | None = None,
    output: CoordinateSystem | None = None,
    image: NoRepr[Any | None] = Field(
        default=None, convert=False
    ),
    data: NoRepr[ArrayProtocol | None] = None,
)

Bases: ItkNiftiField

Dense nonlinear ITK or ANTs warp stored as a NIfTI vector image.

Such a field, for example the <prefix>1Warp.nii.gz file of antsRegistration, maps LPS to LPS as x -> x + u(x), or (L, P) to (L, P) in 2-D. It is a Sequence of three named slots:

Slot Transformation
lps2voxel LPS world coordinates to the field's voxels
displacement the displacement field, in voxel units
voxel2lps the field's voxels back to LPS world

The displacements are interpolated linearly and extrapolated with the nearest value, as by the default interpolator of ITK's DisplacementFieldTransform.

The RAS NIfTI field reader also claims a VECTOR file (1007) in the ITK layout with certainty, and the header cannot tell the two apart. Such a file is therefore read with hint="itk" or hint="ants", which also reaches a file in the ITK layout with any other intent code.

Parameters:

Name Type Description Default
transformations tuple[Transformation, ...] | None
None
rawdata NoRepr[ArrayProtocol | None]
Inherit('rawdata', var=True)
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None, var=True)
input CoordinateSystem | None

Input coordinate system, which may be inferred from context if unset.

None
output CoordinateSystem | None

Output coordinate system, which may be inferred from context if unset.

None
image NoRepr[Any | None]

The image that holds the file, which the constructor always sets. The image describes the file as it was read, or as the transformation was last consolidated, and it never holds pending data or transformations.

Field(default=None, convert=False)
data NoRepr[ArrayProtocol | None]

The vectors given to the field, or None to decode them from rawdata. Vectors stored here are pending until [consolidate][] or a write encodes them into rawdata.

None

Attributes

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

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

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

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

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

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

Names of the attributes that define the encoding.

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

Names of the derived attributes, such as views and caches.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

metadata property writable
metadata: Any | None

The metadata of the file, which holds its header, or None.

The metadata is that of the stored image. A transformation built from its data alone has none. Assigning other metadata replaces the stored image with a copy that holds it, converted into the metadata of the image class, and drops the views decoded from the previous header.

rawdata property writable
rawdata: ArrayProtocol | None

The array of the file as it is stored, or None without one.

The array is the rawdata of the stored image. After a read, it is a lazy array of the file, which applies the scaling of the header when it is read. It describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is. Assigning rawdata replaces the stored image with a copy that holds the new array.

lps2voxel property
lps2voxel: Transformation | None

The affine from LPS world coordinates to the voxels of the field.

degree class-attribute
degree: int = 1

Spline degree of the interpolation.

bound class-attribute

Boundary condition outside the field of view.

displacement property
displacement: Transformation | None

The displacement field, in voxel units.

voxel2lps property
voxel2lps: Transformation | None

The affine from the voxels of the field back to LPS world coordinates.

Methods:

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

Write the object to a path or an open file.

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

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

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

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

Return the lines of the file, without terminators.

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

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

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

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

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

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

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

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

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

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

sniff_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_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

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

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

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

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

Raises:

Type Description
TypeError

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

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

Read an object from a path or an open file.

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

Read a transformation from the path of its file.

The file is read by the reader of the image class, whose array is read lazily, and the transformation is built from that image with from_image. The keywords that name an argument of the constructor of the transformation, under any of their aliases, go to the transformation, and the other keywords go to the reader of the image, which refuses those that it does not know.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the reader of the image, such as mmap, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

from_fileobj classmethod
from_fileobj(file: BinaryIO, **kwargs: Any) -> Self

Read a transformation from an open stream of its file.

The stream is read by the reader of the image class, whose lazy array keeps the stream, so the stream must stay open while the array may be read. The transformation is built from that image with from_image, and the keywords are shared out as by from_filename.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of the reader of the image, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

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

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

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

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

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

Raises:

Type Description
ValueError

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

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: Type[Transformation] | None = None,
    *,
    copy: bool = False,
    **kwargs,
) -> Transformation

Convert the chain to another type or encoding.

A chain has no tangent of its own, because the tangent of a composition is not the sum of the tangents. A log= keyword therefore re-encodes the transformation that the chain reduces to, which is possible in three cases:

  • A chain that simplifies to a single transformation is converted as that transformation.
  • A change of coordinates [P, *X, P^-1] (see Sequence.sqrt) keeps its ends and re-encodes X, which is exact because the flow of a velocity commutes with a change of coordinates.
  • A chain of affine transformations is composed.

Any other chain raises a ConversionError before anything is computed. Without log=, the conversion follows Transformation.to, and so do copy=, on_loss= and on_error=. With log=, on_loss= and on_error= apply to the whole conversion of the chain.

to_numpy
to_numpy() -> ArrayProtocol

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

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

Return the data as a CuPy array on the GPU.

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

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

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

Return the object with its data as NumPy arrays.

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

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

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

Parameters:

Name Type Description Default
device str | int | None

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

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

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

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

input
input() -> CoordinateSystem | None

The ITK physical space that the field maps from.

output
output() -> CoordinateSystem | None

The ITK physical space that the field maps to.

compute
compute(
    mode: ModeLike = True,
    *,
    simplify: SimplifyLike = "analytic",
    factor: bool = False,
) -> Transformation

Compute the transformation that results from the chain.

With mode=True, a chain of affine-like transformations yields an affine-like transformation, and a chain whose first applied element is a coordinate field yields a coordinate field. When the first applied element is affine-like but the chain contains other elements, the result is a sequence of two: the composition of the affine-like elements before the first other element, then the composition of everything from that element onward.

Parameters:

Name Type Description Default
mode ModeLike

Kinds to compose, as a name, a type or a list of them. True composes everything, and False only simplifies.

True
simplify SimplifyLike

Simplification policy applied before composition: "analytic" uses the type structure only, "numeric" also inspects the values of matrix transformations, {None: "numeric"} inspects the values of every transformation, and False, "none" or None disables simplification.

"analytic"
factor bool

Whether to rewrite the chain into a normal form organized by groups of axes, [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?]. The normal form starts with an optional grid and an optional projection that drops the inputs that nothing reads. It continues with one subspace factor for each group of axes that transform together, where each factor preserves its axes, and it ends with an optional permutation and an optional projection that creates the outputs that read no input. Nothing is composed across groups. The option is ignored with mode=False.

False
simplify
simplify(
    policy: SimplifyLike = "analytic",
    *,
    compute: ModeLike | bool | None = False,
) -> Self

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

factor
factor(
    policy: SimplifyLike = "analytic",
    *,
    compute: ModeLike | bool | None = False,
) -> Transformation

Rewrite the chain as one factor per group of axes.

The axes of a chain often fall into groups that never interact, as when each axis is scaled on its own and two axes are then swapped. Factoring finds those groups and rewrites the chain as [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?], with one axis-preserving factor F_i = Subspace(inner_i, A_i, A_i) per group, ordered by their first axis, and a permutation that carries each group to the axes that it occupies at the output (see [factor_sequence][brainhops.datamodel._transformations.compute.factor.factor_sequence]). The projection delta drops the inputs that no output reads, and the projection kappa creates the outputs that read no input, at their constant values. Nothing is composed across groups, so the coordinates of independent axes are never tiled into a grid over all of them, and each group can be resampled on its own.

The chain is unnested first, and a leading CartesianField is the sampling grid, which is kept as the same object. Every other element is cut into one piece per group, and an element that lies within a single group is kept as it is, so a lazy inverse stays lazy and still cancels with its forward transformation.

Note

The pass reads the chain as it stands, and it is idempotent. It declines a chain in which an element shifts or scales an output that reads no input, because it carries such a constant only through the elements that pass it through unchanged. compute with factor=True composes such a chain, and then simplifies and factors the result.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the elements may be read, with the values and the meaning of the policy of [simplify][]. Under the analytic policy, a matrix couples all its axes, and under the numeric policy, its exact zeros are read, so that an affine with independent axes splits.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. The default, False, composes nothing, so each factor holds the sub-chain of its own group, whereas True leaves each factor holding a single transformation.

False

Returns:

Type Description
Transformation

The normal form, or self when the chain is already in normal form or does not factor at all, as when it forms a single group and has neither end, its two ends differ in dimension in a way that the end projections do not explain, a grid sits inside it, or one of its elements cannot be read or restricted. An Identity is returned when no factor is left.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

square
square(compute: bool = False, **kwargs) -> Transformation

Return the transformation composed with itself.

The square is the Sequence [self, self], which is composed when it is computed. It is defined only for a transformation that maps a space to itself.

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

sqrt
sqrt(compute: bool = False, **kwargs) -> Transformation

Return the principal square root of the chain.

The chain is first simplified. A chain of the form [P, *X, P^-1] is a change of coordinates around X, and its square root is [P, sqrt(X), P^-1]. The chain has this form when its last element is the lazy inverse of its first element, or when its two ends are affine transformations whose product is exactly the identity. Any other chain is composed, and the square root of the result is returned.

Raises:

Type Description
DomainError

If the chain does not map a space onto itself, or if the square root of its reduced form is undefined (see DomainError).

NotImplementedError

If the chain is not a change of coordinates and does not compose to a single transformation.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

bridge
bridge() -> Self

Reconcile the coordinate systems at every boundary of the chain.

Two neighbours in a chain share a coordinate system: the output system of one is the input system of the next. Where the two disagree, as when one works in millimetres and the next in voxels, or when the two name the same axes in a different order, a bridge is inserted between them. A bridge reads no parameter, so bridging costs nothing, and two opposite bridges cancel when the chain is simplified.

Bridging is also the only pass that lengthens a chain, which is why compute runs it before anything else: a bridge reads its neighbours, and a reversed array-index axis needs the extent of the adjacent grid, which composition may drop.

A nested sequence is bridged in place and stays nested, so a boundary that it hides is reconciled inside it. Call flatten afterwards for a flat chain. A sequence with a fixed shape, such as a geometry or a multiscale field, is left alone. A generic Inverse is replaced by the typed inverse of its forward transformation, so that the engine can compute it and cancellation can recognize it. No leaf has its endpoints rebuilt.

Returns:

Type Description
Sequence

The chain, with a bridge at each boundary that needed one.

Raises:

Type Description
AdaptationError

If a boundary cannot be bridged, because an axis that must be matched has no counterpart on the other side.

flatten
flatten(endpoints: bool = True) -> Self

Splice the nested sequences of the chain into the chain itself.

A chain whose elements are themselves chains applies exactly as the flat chain of their elements, so flattening changes nothing about what the transformation does. It is what lets the simplifier and the composers see two leaves as neighbours when a nesting boundary sits between them.

A nested child is asked to flatten itself, so a child with a shape of its own contributes what it chooses: a geometry contributes its grid and its transformation, and a multiscale field contributes the elements of its finest scale.

Parameters:

Name Type Description Default
endpoints bool

Whether to push the coordinate systems of the chain onto its first and last element, which is where the composers read them. A child with a shape of its own may contribute a sequence, so one level of nesting can survive this mode, and the next pass splices it. With endpoints=False, nesting is unwound all the way to the leaves in one pass, no leaf is rebuilt and each one stays the same object, so that a transformation still cancels with the lazy inverse that names it; a generic Inverse is then also replaced by the typed inverse of its forward transformation.

True

Returns:

Type Description
Sequence

The flattened chain.

data
data() -> ArrayProtocol | None

The stored vectors, as an (X, Y, Z, 3) or (X, Y, 2) array.

Vectors that are assigned are returned as they are, and stay pending until [consolidate][] or a write encodes them. Otherwise they are decoded from rawdata without the singleton axes of the ITK layout, and they are those of the file, before the frame of a DISPVECT file is converted. Assigning the data drops the chain decoded from the previous data.

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

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

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

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

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

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

UNSET
on_loss ErrorAction

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

UNSET
**fields Any

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

{}

Returns:

Type Description
Self

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

Raises:

Type Description
TypeError

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

MetadataLossError

If something is lost under the "raise" policy.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an object from a nibabel image or header.

The array of an image becomes rawdata, and a copy of its header becomes the record of the metadata. A header alone gives an object without an array. The array proxy of an image that nibabel read from a file is replaced by the lazy array that from_filename builds for that file, and any other array is kept as it is.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the object.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(**options) -> _NibabelImage

Build the nibabel image that a file written from this object holds.

The object is consolidated with the options into a copy, and the nibabel image holds the rawdata and the header of that copy. The object itself is not changed.

Parameters:

Name Type Description Default
**options Any

The options of consolidate, such as the template like and the fields of the header.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

Raises:

Type Description
WriterError

If the object has no array to write.

from_image classmethod
from_image(image: Any, **options: Any) -> Self

Build a transformation from the image that stores it.

The image becomes the stored image of the transformation, and the transformation decodes its data and its chain from that image when they are needed. The call is the same as cls(image=image, **options).

Parameters:

Name Type Description Default
image Any

The image, of the class that IMAGE names, which is consolidated first if it has pending data or transformations.

required
**options Any

The other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation.

Raises:

Type Description
TypeError

If the image is not of the class that IMAGE names.

to_image
to_image() -> Any

Return the image that a file of this transformation holds.

The transformation is consolidated into a copy, as by [consolidate][], and the stored image of that copy is returned. The transformation itself is not changed.

Returns:

Type Description
Any

The image, of the class that IMAGE names, without pending data or transformations.

score_header classmethod
score_header(header: NiftiObject) -> float

Score a header as an ITK displacement field.

A VECTOR image in the ITK layout scores Confidence.CERTAIN, deliberately equal to the RAS reader, since neither frame may outrank the other. Other intent codes are left to a hint. The intent name "Mapping", which SPM12 and the brainhops coordinates writer use but ITK never writes, is not claimed, and neither is the NiftyReg name "NREG_TRANS".

transformations
transformations() -> tuple[Transformation, ...]

The chain of transformations that the field encodes.

The chain is built lazily from the header and the data, and then cached. Assigning a chain overrides the derived one, which is how fields that do not come from a file are built.

ItkNiftiField magic

ItkNiftiField(
    transformations: tuple[Transformation, ...]
    | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = Inherit(
        "rawdata", var=True
    ),
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None, var=True
    ),
    *,
    input: CoordinateSystem | None = None,
    output: CoordinateSystem | None = None,
    image: NoRepr[Any | None] = Field(
        default=None, convert=False
    ),
    data: NoRepr[ArrayProtocol | None] = None,
)

Bases: NiftiImageBackedTransformation, DerivedSequence

Base class of the fields stored in ITK NIfTI vector images.

The vectors are expressed in the LPS physical space of ITK, while the header holds the usual voxel-to-RAS affine. Subclasses decide whether the vectors are displacements (ItkNiftiDisplacementField) or absolute coordinates (ItkNiftiCoordinateField).

The dimension of the field is read from the header, and its endpoints are the ITK spaces of that dimension: (L, P) in 2-D and LPSmm in 3-D. The field is an ImmutableSequence of named slots, so editing it in place raises a TypeError. This class is not registered as a format.

Parameters:

Name Type Description Default
transformations tuple[Transformation, ...] | None
None
rawdata NoRepr[ArrayProtocol | None]
Inherit('rawdata', var=True)
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None, var=True)
input CoordinateSystem | None

Input coordinate system, which may be inferred from context if unset.

None
output CoordinateSystem | None

Output coordinate system, which may be inferred from context if unset.

None
image NoRepr[Any | None]

The image that holds the file, which the constructor always sets. The image describes the file as it was read, or as the transformation was last consolidated, and it never holds pending data or transformations.

Field(default=None, convert=False)
data NoRepr[ArrayProtocol | None]

The vectors given to the field, or None to decode them from rawdata. Vectors stored here are pending until [consolidate][] or a write encodes them into rawdata.

None

Attributes

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

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

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

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

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

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

Names of the attributes that define the encoding.

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

Names of the derived attributes, such as views and caches.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

metadata property writable
metadata: Any | None

The metadata of the file, which holds its header, or None.

The metadata is that of the stored image. A transformation built from its data alone has none. Assigning other metadata replaces the stored image with a copy that holds it, converted into the metadata of the image class, and drops the views decoded from the previous header.

rawdata property writable
rawdata: ArrayProtocol | None

The array of the file as it is stored, or None without one.

The array is the rawdata of the stored image. After a read, it is a lazy array of the file, which applies the scaling of the header when it is read. It describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is. Assigning rawdata replaces the stored image with a copy that holds the new array.

INTENT_NAME class-attribute
INTENT_NAME: str = ''

The intent name that brainhops writes on the field, so that it reads the field back as this class without a hint. ITK ignores it.

lps2voxel property
lps2voxel: Transformation | None

The affine from LPS world coordinates to the voxels of the field.

Methods:

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

Write the object to a path or an open file.

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

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

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

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

Return the lines of the file, without terminators.

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

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

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

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

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

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

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

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

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

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

sniff_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_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

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

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

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

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

Raises:

Type Description
TypeError

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

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

Read an object from a path or an open file.

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

Read a transformation from the path of its file.

The file is read by the reader of the image class, whose array is read lazily, and the transformation is built from that image with from_image. The keywords that name an argument of the constructor of the transformation, under any of their aliases, go to the transformation, and the other keywords go to the reader of the image, which refuses those that it does not know.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the reader of the image, such as mmap, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

from_fileobj classmethod
from_fileobj(file: BinaryIO, **kwargs: Any) -> Self

Read a transformation from an open stream of its file.

The stream is read by the reader of the image class, whose lazy array keeps the stream, so the stream must stay open while the array may be read. The transformation is built from that image with from_image, and the keywords are shared out as by from_filename.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of the reader of the image, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

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

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

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

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

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

Raises:

Type Description
ValueError

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

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: Type[Transformation] | None = None,
    *,
    copy: bool = False,
    **kwargs,
) -> Transformation

Convert the chain to another type or encoding.

A chain has no tangent of its own, because the tangent of a composition is not the sum of the tangents. A log= keyword therefore re-encodes the transformation that the chain reduces to, which is possible in three cases:

  • A chain that simplifies to a single transformation is converted as that transformation.
  • A change of coordinates [P, *X, P^-1] (see Sequence.sqrt) keeps its ends and re-encodes X, which is exact because the flow of a velocity commutes with a change of coordinates.
  • A chain of affine transformations is composed.

Any other chain raises a ConversionError before anything is computed. Without log=, the conversion follows Transformation.to, and so do copy=, on_loss= and on_error=. With log=, on_loss= and on_error= apply to the whole conversion of the chain.

to_numpy
to_numpy() -> ArrayProtocol

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

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

Return the data as a CuPy array on the GPU.

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

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

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

Return the object with its data as NumPy arrays.

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

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

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

Parameters:

Name Type Description Default
device str | int | None

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

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

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

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

compute
compute(
    mode: ModeLike = True,
    *,
    simplify: SimplifyLike = "analytic",
    factor: bool = False,
) -> Transformation

Compute the transformation that results from the chain.

With mode=True, a chain of affine-like transformations yields an affine-like transformation, and a chain whose first applied element is a coordinate field yields a coordinate field. When the first applied element is affine-like but the chain contains other elements, the result is a sequence of two: the composition of the affine-like elements before the first other element, then the composition of everything from that element onward.

Parameters:

Name Type Description Default
mode ModeLike

Kinds to compose, as a name, a type or a list of them. True composes everything, and False only simplifies.

True
simplify SimplifyLike

Simplification policy applied before composition: "analytic" uses the type structure only, "numeric" also inspects the values of matrix transformations, {None: "numeric"} inspects the values of every transformation, and False, "none" or None disables simplification.

"analytic"
factor bool

Whether to rewrite the chain into a normal form organized by groups of axes, [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?]. The normal form starts with an optional grid and an optional projection that drops the inputs that nothing reads. It continues with one subspace factor for each group of axes that transform together, where each factor preserves its axes, and it ends with an optional permutation and an optional projection that creates the outputs that read no input. Nothing is composed across groups. The option is ignored with mode=False.

False
simplify
simplify(
    policy: SimplifyLike = "analytic",
    *,
    compute: ModeLike | bool | None = False,
) -> Self

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

factor
factor(
    policy: SimplifyLike = "analytic",
    *,
    compute: ModeLike | bool | None = False,
) -> Transformation

Rewrite the chain as one factor per group of axes.

The axes of a chain often fall into groups that never interact, as when each axis is scaled on its own and two axes are then swapped. Factoring finds those groups and rewrites the chain as [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?], with one axis-preserving factor F_i = Subspace(inner_i, A_i, A_i) per group, ordered by their first axis, and a permutation that carries each group to the axes that it occupies at the output (see [factor_sequence][brainhops.datamodel._transformations.compute.factor.factor_sequence]). The projection delta drops the inputs that no output reads, and the projection kappa creates the outputs that read no input, at their constant values. Nothing is composed across groups, so the coordinates of independent axes are never tiled into a grid over all of them, and each group can be resampled on its own.

The chain is unnested first, and a leading CartesianField is the sampling grid, which is kept as the same object. Every other element is cut into one piece per group, and an element that lies within a single group is kept as it is, so a lazy inverse stays lazy and still cancels with its forward transformation.

Note

The pass reads the chain as it stands, and it is idempotent. It declines a chain in which an element shifts or scales an output that reads no input, because it carries such a constant only through the elements that pass it through unchanged. compute with factor=True composes such a chain, and then simplifies and factors the result.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the elements may be read, with the values and the meaning of the policy of [simplify][]. Under the analytic policy, a matrix couples all its axes, and under the numeric policy, its exact zeros are read, so that an affine with independent axes splits.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. The default, False, composes nothing, so each factor holds the sub-chain of its own group, whereas True leaves each factor holding a single transformation.

False

Returns:

Type Description
Transformation

The normal form, or self when the chain is already in normal form or does not factor at all, as when it forms a single group and has neither end, its two ends differ in dimension in a way that the end projections do not explain, a grid sits inside it, or one of its elements cannot be read or restricted. An Identity is returned when no factor is left.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

square
square(compute: bool = False, **kwargs) -> Transformation

Return the transformation composed with itself.

The square is the Sequence [self, self], which is composed when it is computed. It is defined only for a transformation that maps a space to itself.

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

sqrt
sqrt(compute: bool = False, **kwargs) -> Transformation

Return the principal square root of the chain.

The chain is first simplified. A chain of the form [P, *X, P^-1] is a change of coordinates around X, and its square root is [P, sqrt(X), P^-1]. The chain has this form when its last element is the lazy inverse of its first element, or when its two ends are affine transformations whose product is exactly the identity. Any other chain is composed, and the square root of the result is returned.

Raises:

Type Description
DomainError

If the chain does not map a space onto itself, or if the square root of its reduced form is undefined (see DomainError).

NotImplementedError

If the chain is not a change of coordinates and does not compose to a single transformation.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

bridge
bridge() -> Self

Reconcile the coordinate systems at every boundary of the chain.

Two neighbours in a chain share a coordinate system: the output system of one is the input system of the next. Where the two disagree, as when one works in millimetres and the next in voxels, or when the two name the same axes in a different order, a bridge is inserted between them. A bridge reads no parameter, so bridging costs nothing, and two opposite bridges cancel when the chain is simplified.

Bridging is also the only pass that lengthens a chain, which is why compute runs it before anything else: a bridge reads its neighbours, and a reversed array-index axis needs the extent of the adjacent grid, which composition may drop.

A nested sequence is bridged in place and stays nested, so a boundary that it hides is reconciled inside it. Call flatten afterwards for a flat chain. A sequence with a fixed shape, such as a geometry or a multiscale field, is left alone. A generic Inverse is replaced by the typed inverse of its forward transformation, so that the engine can compute it and cancellation can recognize it. No leaf has its endpoints rebuilt.

Returns:

Type Description
Sequence

The chain, with a bridge at each boundary that needed one.

Raises:

Type Description
AdaptationError

If a boundary cannot be bridged, because an axis that must be matched has no counterpart on the other side.

flatten
flatten(endpoints: bool = True) -> Self

Splice the nested sequences of the chain into the chain itself.

A chain whose elements are themselves chains applies exactly as the flat chain of their elements, so flattening changes nothing about what the transformation does. It is what lets the simplifier and the composers see two leaves as neighbours when a nesting boundary sits between them.

A nested child is asked to flatten itself, so a child with a shape of its own contributes what it chooses: a geometry contributes its grid and its transformation, and a multiscale field contributes the elements of its finest scale.

Parameters:

Name Type Description Default
endpoints bool

Whether to push the coordinate systems of the chain onto its first and last element, which is where the composers read them. A child with a shape of its own may contribute a sequence, so one level of nesting can survive this mode, and the next pass splices it. With endpoints=False, nesting is unwound all the way to the leaves in one pass, no leaf is rebuilt and each one stays the same object, so that a transformation still cancels with the lazy inverse that names it; a generic Inverse is then also replaced by the typed inverse of its forward transformation.

True

Returns:

Type Description
Sequence

The flattened chain.

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

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

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

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

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

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

UNSET
on_loss ErrorAction

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

UNSET
**fields Any

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

{}

Returns:

Type Description
Self

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

Raises:

Type Description
TypeError

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

MetadataLossError

If something is lost under the "raise" policy.

score_header classmethod
score_header(header: NiftiObject) -> float

Return how well a valid NIfTI header matches this class.

The header has already passed the check of its size and magic number, so the score says how likely the file holds the kind of object that this class builds. A format that can tell its files apart from the header, such as by its intent code, overrides this method. The default is Confidence.MAYBE.

Parameters:

Name Type Description Default
header Nifti1Header or Nifti2Header

The header of the file.

required

Returns:

Type Description
float

The confidence, between 0 and 1.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an object from a nibabel image or header.

The array of an image becomes rawdata, and a copy of its header becomes the record of the metadata. A header alone gives an object without an array. The array proxy of an image that nibabel read from a file is replaced by the lazy array that from_filename builds for that file, and any other array is kept as it is.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the object.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(**options) -> _NibabelImage

Build the nibabel image that a file written from this object holds.

The object is consolidated with the options into a copy, and the nibabel image holds the rawdata and the header of that copy. The object itself is not changed.

Parameters:

Name Type Description Default
**options Any

The options of consolidate, such as the template like and the fields of the header.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

Raises:

Type Description
WriterError

If the object has no array to write.

from_image classmethod
from_image(image: Any, **options: Any) -> Self

Build a transformation from the image that stores it.

The image becomes the stored image of the transformation, and the transformation decodes its data and its chain from that image when they are needed. The call is the same as cls(image=image, **options).

Parameters:

Name Type Description Default
image Any

The image, of the class that IMAGE names, which is consolidated first if it has pending data or transformations.

required
**options Any

The other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation.

Raises:

Type Description
TypeError

If the image is not of the class that IMAGE names.

to_image
to_image() -> Any

Return the image that a file of this transformation holds.

The transformation is consolidated into a copy, as by [consolidate][], and the stored image of that copy is returned. The transformation itself is not changed.

Returns:

Type Description
Any

The image, of the class that IMAGE names, without pending data or transformations.

data
data() -> ArrayProtocol | None

The stored vectors, as an (X, Y, Z, 3) or (X, Y, 2) array.

Vectors that are assigned are returned as they are, and stay pending until [consolidate][] or a write encodes them. Otherwise they are decoded from rawdata without the singleton axes of the ITK layout, and they are those of the file, before the frame of a DISPVECT file is converted. Assigning the data drops the chain decoded from the previous data.

input
input() -> CoordinateSystem | None

The ITK physical space that the field maps from.

output
output() -> CoordinateSystem | None

The ITK physical space that the field maps to.