brainhops.io.transformations.itk.nifti
ITK nonlinear warps stored as NIfTI vector images, in LPS space.
ITK (and therefore ANTs, which writes its warps through ITK) stores a
dense displacement field as a NIfTI vector image. Three facts define
the encoding, and each one differs from the RAS NIfTI fields of
brainhops.io.transformations.nifti:
-
Layout. The array is five-dimensional:
(X, Y, Z, 1, 3)for a 3-D field,(X, Y, 1, 1, 2)for a 2-D one -- the spatial axes, singletons in place of the dimensions the image does not have, and the vector components in the fifth axis. ITK'sNiftiImageIOalways writesdim[0] = 5for a vector image, setsdim[4] = 1when the image has fewer than four dimensions, and stores the components indim[5]. -
Intent code. ITK writes
NIFTI_INTENT_VECTOR(1007) for a vector image. Since ITK 5.4 it writesNIFTI_INTENT_DISPVECT(1006) instead only when the image's metadata dictionary explicitly asks for it. -
Frame of the vectors. The voxel-to-world affine in the header is the usual NIfTI RAS sform/qform: ITK negates the first two rows of its LPS direction and origin when it writes them. The vector values are not converted for a
VECTOR(1007) file, so they stay in ITK's LPS physical space. ADISPVECT(1006) file is the exception: since ITK 5.4, ITK flips the first two components of a three-componentDISPVECTimage between RAS (in the file) and LPS (in memory), both on reading and on writing. It never converts a two-component one.
So, for a point x of the field's grid, an ITK displacement field maps
x_lps -> x_lps + u_lps(x). In RAS world, the same displacement is
(-u_x, -u_y, u_z).
The same holds in 2-D. ITK negates the x and y rows of the geometry of an
image of any dimension when it writes or reads a NIfTI, so a 2-D ITK
image lives in (L, P), and a 2-D displacement (u_x, u_y) is
(-u_x, -u_y) in (R, A). Both dimensions are read by the same classes;
the endpoints are the ITK spaces of the field's dimension, LPSmm in
3-D and (L, P) in millimetres in 2-D -- the spaces the .tfm and .h5
readers use, so a warp and an affine from ITK name the same space.
Sources
- ITK,
Modules/IO/NIFTI/src/itkNiftiImageIO.cxx(WriteImageInformation,SetNIfTIOrientationFromImageIO,ReadImageInformation, andConvertRASToFromLPS_*), andModules/IO/NIFTI/include/itkNiftiImageIO.h(ConvertRASVectors, off by default, andConvertRASDisplacementVectors, 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: it requires the(X, Y, Z, 1, 2|3)shape and thevectorintent, and it negates components 0 and 1 to go between ITK (LPS) and RAS. https://github.com/nipy/nitransforms/blob/master/nitransforms/io/itk.py - ANTs writes the warps of
antsRegistration(<prefix><n>Warp.nii.gz,<prefix><n>InverseWarp.nii.gz) with anitk::ImageFileWriterof the displacement field image (itk::ants::WriteTransform,Utilities/itkantsReadWriteTransform.h; file names fromRegTypeToFileName,Examples/antsRegistrationTemplateHeader.cxx), so they follow the encoding above. These readers therefore also answer tohint="ants", exactly as they do tohint="itk".
Telling an ITK field from a RAS NIfTI field
NIfTI has no field that says which frame the vector values live in, so the header alone cannot always tell. The readers here are honest about that:
| 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 |
The RAS readers are NiftiRASCoordinatesField and
NiftiRASDisplacementField, in brainhops.io.transformations.nifti.
VECTORis exactly what ITK writes, but it is a generic code that any software may use, and ITK itself does not treat its vectors as spatial by default. So the ITK displacement reader and the RAS reader claim it with equal confidence, and loading such a file without more evidence raisesAmbiguousFormatErrorrather than guessing a frame.- The intent name is that evidence when it is
"Mapping": SPM12 names itsy_deformations so, and so does brainhops' RAS coordinates writer, while ITK'sNiftiImageIOnever writes an intent name (and ANTs writes through it). The ITK reader does not claim such a file. - An explicit hint decides:
load(path, hint="itk")(or"ants") reads the file as an ITK displacement field, whatever its intent code, andhint="itk.coordinates"as an ITK coordinates field. Calling the class directly,ItkNiftiDisplacementField.from_file(path), does the same. DISPVECTand no intent stay with the RAS readers. ADISPVECTfile holds RAS displacements, which is also what ITK 5.4 and later assumes of one. Read with a hint, a three-componentDISPVECTfile has its RAS vectors converted to LPS, as ITK does.- ITK and ANTs only ever write displacements. A field of absolute LPS coordinates is never claimed from the file's content, because nothing in a NIfTI header separates it from a displacement field.
- ANTs' file names (
*Warp.nii.gz) are not used as evidence: they are a convention of one program, not of the format.
Two- and three-dimensional fields are supported. ITK can also write a four-dimensional vector image, with its fourth dimension in the NIfTI time axis, but NIfTI has no geometry for that axis, and it is not read.
Classes
ItkNiftiCoordinatesField
ItkNiftiCoordinatesField(
_transformations: tuple[Transformation, ...]
| None = None,
)
Bases: ItkNiftiField
Field of LPS coordinates, stored as an ITK NIfTI vector image.
Each voxel holds the absolute LPS position it maps to. The field maps
LPS to LPS (or (L, P) to (L, P) in 2-D), as the
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 NIfTI header
cannot say whether its vectors are displacements or positions, so
this reader never claims a file from its content. Ask for it with
hint="itk.coordinates", or use the class directly.
Attributes
PREFIXES
class-attribute
PREFIXES: tuple[str, ...] = ()
Filename prefixes required by this parser, e.g. ("y_", "iy_").
An empty tuple means "no constraint". A parser that constrains the prefix is more specific than one that does not, and wins ties.
Declaring EXTENSIONS and PREFIXES separately states the
cross-product implicitly, which is how these conventions actually
work: SPM's four names are {y_, iy_} x {.nii, .nii.gz}.
header
property
writable
The NIfTI header associated with this object.
If a header was explicitly set by the user (at construction or later), this will be pointing to that header.
Otherwise, if the object was created from a NIfTI header, this will be pointing to that header.
Otherwise, if the object was created from a NIfTI image, this will be pointing to the header of that image.
Example
import nibabel as nb
image1 = nb.load("image1.nii")
image2 = nb.load("image2.nii")
NiftiParser(image1).header # `image1.header`
NiftiParser(header=image2.header).header # `image2.header`
NiftiParser(image1, header=image2.header).header # `image2.header`
obj = NiftiParser(image1)
obj.header = image2.header
obj.header # `image2.header`
data
property
writable
The image data, read lazily from image and cached, unless
it has been set explicitly.
The axes that the intent code marks as irrelevant, such as a singleton axis before a vector's components, are dropped.
system
property
writable
system: CoordinateSystem | None
The voxel coordinate system, derived from header, unless it
has been set explicitly.
The axes that the intent code marks as irrelevant are dropped.
None when there is no header to derive it from.
lps2voxel
property
lps2voxel: Transformation | None
The affine from LPS world coordinates to the field's voxels.
PRIORITY
class-attribute
PRIORITY: int = -1
Under hint="itk", a file in ITK's layout with another intent than
VECTOR is claimed by neither ITK reader, and both match its
extension, so the two genuinely tie. ITK and ANTs mean a
displacement, so this reader yields to that one.
coordinates
property
coordinates: Transformation | None
The field of LPS coordinates, on the field's grid.
Methods:
sniff
classmethod
sniff(
file: FileOrContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read
file. On a concrete format, score how confident it is that
file, in any supported form, is its own.
sniff_file
classmethod
On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Determine if the given filename is of the type that this parser can handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to sniff. |
required |
error
|
bool | type[Exception]
|
If not False, raise an error if the filename cannot be sniffed. |
False
|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the filename is of this type, in |
sniff_fileobj
classmethod
sniff_fileobj(
file: IO,
error: bool | Type[Exception] = False,
*,
version: int | None = None,
**kwargs,
) -> float
Score how confident the class is that an open file object
holds a NIfTI-1 or NIfTI-2 header, or a header of the given
version when one is passed.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read the content (text or bytes). On a concrete format, score how confident it is that the content is its own.
sniff_bytes
classmethod
Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.
sniff_text
classmethod
On a dispatcher, identify which registered format would read the text. On a concrete format, score how confident it is that the text is its own.
sniff_lines
classmethod
sniff_lines(
lines: Iterable[str],
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read the lines. On a concrete format, score how confident it is that the lines are its own.
sniff_line
classmethod
On a dispatcher, identify which registered format would read the line. On a concrete format, score how confident it is that the line is its own.
load
classmethod
load(other: FileOrContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and
build an instance of it from other. On a concrete format,
build an instance of this class from other, in any supported
form.
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Load a structured source specification through this dispatcher.
from_file
classmethod
Build the object from a NIfTI file.
A local path is handed to nibabel by name, so that it owns the
file handle and can memory-map the voxels: its array proxy reads
them lazily, long after the call returns. A remote path is opened
through its own backend instead, since nibabel would take its
name for a local file. See _load_nifti.
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Build an object from a filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to parse. |
required |
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The parsed object. |
from_fileobj
classmethod
Build the object from an open NIfTI file object, image data included when the stream allows reading it.
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and build an instance of it from the content (text or bytes). On a concrete format, build an instance of this class from the content.
from_bytes
classmethod
Build the object from bytes in NIfTI format.
from_text
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the text. On a concrete format, build an instance of this class from the text.
from_lines
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the lines. On a concrete format, build an instance of this class from the lines.
from_line
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the line. On a concrete format, build an instance of this class from the line.
save
save(file: FileLike, **kwargs) -> None
Write the object to a file (path or file-like object).
This is the generic front door to the to_* family. It is named
save rather than to because to already means something else
on the data models these parsers are mixed into: Transformation.to
converts an object to another type. A writer's to was shadowed
by it on every writable transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileLike
|
The file to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_file
to_file(file: FileLike, **kwargs) -> None
Write the object to a NIfTI file.
A path is written gzipped when its name ends in .gz: a local
path is handed to nibabel by name, and a remote one is opened
through its own backend. See _save_nifti. A file-like object is
written the uncompressed NIfTI bytes.
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the object to a filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the uncompressed NIfTI-1 encoding of the object to an open file object.
to_text
to_text(**kwargs) -> str
Return a text version of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A text version of the file. |
to_lines
Return a text version of the file as an iterable of lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
Iterator[str]
|
An iterable of lines representing the object. |
to_line
to_line(**kwargs) -> str
Return a line representing the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A line representing the object. |
from_dict
classmethod
Create an instance of the class from a dictionary-like object.
Only keys in the dictionary that match keyword-like fields of
this class, or the keywords its constructor takes without
storing them (its InitVars, such as the matrix= of an
Affine), will be used. Other keys are ignored, but see
from_other,
which refuses them.
Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.
A key naming a field that this class fixes (a field that cannot
be passed to its constructor) is checked instead of used: a
dictionary that sets it to anything other than None or the
value of this class is refused with a ValueError.
from_instance
classmethod
Create an instance from an instance of a similar class.
The data model copies the fields both classes share, by name.
A field that a file format declares for its own use -- such as
the nibabel image and header of the NIfTI and MGH formats
-- is only copied from an object of that same format: from any
other object, a field of the same name holds something else
(a NIfTI image is no MGH image), so this class's default is
kept instead. Saving a NIfTI image to MGH, or the converse,
therefore converts the data model only, and the format-specific
state is rebuilt by the writer.
from_other
classmethod
Create an instance from a file, or from anything the data model reads.
A path (str or os.PathLike), an open file, bytes or a
structured source (SourceSpec)
is read with load: on a dispatcher such as FileBasedImage,
the best-matching registered format reads it, and on a concrete
format, that format does. Any other value is handed to the data
model's own from_other, which reads a mapping field by field,
copies an instance of a similar class, and passes anything else
to the constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A file, its content, a mapping, or an instance of a similar class. |
required |
*args
|
Constructor arguments. A file is read with keyword options only. |
()
|
|
**kwargs
|
Format-specific options when reading a file, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The object that was built. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments come with a file to read. |
from_nibabel
classmethod
from_nibabel(nifti: _NiftiObject, **kwargs) -> Self
Build the field from a nibabel header or image.
The header must be in ITK's layout, so a file that is not an ITK field is refused here, from its header alone, rather than when its chain is first built.
sniff_nibabel
classmethod
Score how confident the class is that an already-loaded
nibabel header or image matches this format.
The header's magic number is checked first. A header that passes is then scored for how well it matches this particular format, as opposed to another kind of NIfTI-based format.
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Transformation
Compute the resulting transform of the sequence of transformations.
Assuming that mode=True:
-
If all transformations in the sequence are affine-like transformations,
compute()returns an affine-like transform. -
If the first (= rightmost) transform in the sequence is a coordinate field,
compute()returns a coordinate field. -
If the first (= rightmost) transform in the sequence is an affine-like transform, and the sequence contains at least one non-affine-like transform,
compute()returns a sequence of two transformations: -
the composition of all affine-like transformations that appear before the first non-affine-like transform in the sequence, and
- the composition of all transformations in the sequence, starting from the first non-affine-like transform in the sequence.
Parameters
mode : [list of] name or type, optional
Kinds of transformations to compose.
* If True (default): compose every kind in the sequence.
* If False: compose nothing (simplify-only).
* If a (list of) transformation type(s): compose only pairs
of transformations of these kinds.
simplify : simplify policy, default="analytic"
Whether to simplify sub-transformations prior to composition,
and how hard to try to simplify them.
* "analytic" (the default) looks at the type structure only;
* "numeric" looks at the numeric values of the transformation;
* False/"none"/None disables simplification.
factor : bool, default=False
Whether to rewrite the sequence into its axis-group normal
form [grid?, F_1..F_m, Pi_perm?]: a leading grid (if any),
one axis-preserving subspace factor per group of axes that
transform together, and a trailing reindex permutation. Off
by default, so the result is byte-for-byte the plain
compute() result. Nothing is ever composed across groups;
mode still decides whether the restricted pieces inside a
group compose. A chain that creates or drops axes is left
unfactored. With mode=False nothing is computed, so
factor has nothing to act on and is ignored.
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify this transformation under a per-kind policy.
Convenience sugar for
compute: t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy).
By default simplify() does no computation at all: compute=False
maps to mode=False, which composes nothing (no matrices multiplied,
no fields sampled, no lazy inverse materialized). It only downcasts
each leaf under policy (analytic by default). Pass an explicit
compute=<mode> to also compose that kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
simplify policy
|
The simplify policy, in the grammar |
"analytic"
|
compute
|
[list of] name or type
|
The compose mode. The default, |
False
|
square
square(compute: bool = False, **kwargs) -> Transformation
Return the square of this transformation, self @ self.
The square is the sequence [self, self], which composes when it
is computed. It is defined for a transformation that maps a space
to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the result now rather than return it lazily. |
False
|
**kwargs
|
Passed to |
{}
|
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 this chain.
The chain is first simplified, which costs nothing. A chain
[P, *X, P^-1], where P^-1 is the lazy inverse of P, or both
are affines whose product is exactly the identity, is a change of
coordinates around X, and its square root is
[P, sqrt(X), P^-1]: a field stored in voxels between a
world-to-voxel affine and its lazy inverse keeps that form. Any
other chain is composed now, and the square root of the
transformation it composes to is returned.
Raises:
| Type | Description |
|---|---|
DomainError
|
If the chain does not map a space to itself, or if the square root of what it reduces to is not defined. |
NotImplementedError
|
If the chain does not compose to a single transformation. |
to
to(
cls: Type[Transformation] | None = None, **kwargs
) -> Transformation
Convert this chain to a different type or encoding.
See Transformation.to. A chain has no tangent of its own -- the tangent of a
composition is not the sum of the tangents -- so log= re-encodes
the transformation it reduces to, and anything else is refused
before it is computed:
- a chain that simplifies to one transformation is that one;
- a change of coordinates
[P, *X, P^-1](seesqrt) keeps its ends, and re-encodesX: the flow of a velocity commutes with the conjugation, so this is exact. A velocity read between a world-to-voxel affine and its inverse (|svf) is turned into its displacement that way; - a chain of affines is composed, which is cheap and exact.
Any other chain -- one with a field, between ends that do not undo
each other -- raises ConversionError.
transformations
transformations() -> tuple[Transformation, ...]
The chain of transformations that the field encodes.
It is built from the NIfTI header and data on first access, and cached. Assigning to it overrides the derived chain.
to_nibabel
to_nibabel(
like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image
Build the nibabel image of this field of LPS coordinates.
The coordinates are written, unconverted, as a VECTOR (1007)
image of shape (X, Y, Z, 1, 3), or (X, Y, 1, 1, 2) in 2-D,
and the inverse of the lps2voxel affine becomes a voxel-to-RAS
sform and qform.
When like is given, non-encoding header fields are copied from
it. Keyword arguments override header fields last.
ItkNiftiDisplacementField
ItkNiftiDisplacementField(
_transformations: tuple[Transformation, ...]
| None = None,
)
Bases: ItkNiftiField
ITK displacement field, stored as a NIfTI vector image.
This is how ITK, and ANTs through it, store a dense nonlinear warp,
such as antsRegistration's <prefix>1Warp.nii.gz. The field maps
LPS to LPS, as x_lps -> x_lps + u_lps(x_lps), and is the
Sequence of three
named slots that the ITK warp blocks use too:
| 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 field may be 3-D, stored as (X, Y, Z, 1, 3) and mapping LPS to
LPS, or 2-D, stored as (X, Y, 1, 1, 2) and mapping (L, P) to
(L, P).
The displacements are interpolated linearly and extended with the
nearest value outside the grid, which is the default interpolator of
ITK's DisplacementFieldTransform
(VectorLinearInterpolateNearestNeighborExtrapolateImageFunction).
A VECTOR (1007) file with ITK's layout is claimed with certainty,
but so is it by the RAS NIfTI field reader: the header alone cannot
tell the two apart, so loading one without a hint is ambiguous. An
explicit hint="itk" (or hint="ants") decides, and also reaches a
file in ITK's layout with any other intent code.
Attributes
PREFIXES
class-attribute
PREFIXES: tuple[str, ...] = ()
Filename prefixes required by this parser, e.g. ("y_", "iy_").
An empty tuple means "no constraint". A parser that constrains the prefix is more specific than one that does not, and wins ties.
Declaring EXTENSIONS and PREFIXES separately states the
cross-product implicitly, which is how these conventions actually
work: SPM's four names are {y_, iy_} x {.nii, .nii.gz}.
PRIORITY
class-attribute
PRIORITY: int = 0
Explicit tie-breaker, consulted only when specificity cannot decide.
Higher wins. Leave at 0 unless two parsers genuinely collide.
header
property
writable
The NIfTI header associated with this object.
If a header was explicitly set by the user (at construction or later), this will be pointing to that header.
Otherwise, if the object was created from a NIfTI header, this will be pointing to that header.
Otherwise, if the object was created from a NIfTI image, this will be pointing to the header of that image.
Example
import nibabel as nb
image1 = nb.load("image1.nii")
image2 = nb.load("image2.nii")
NiftiParser(image1).header # `image1.header`
NiftiParser(header=image2.header).header # `image2.header`
NiftiParser(image1, header=image2.header).header # `image2.header`
obj = NiftiParser(image1)
obj.header = image2.header
obj.header # `image2.header`
data
property
writable
The image data, read lazily from image and cached, unless
it has been set explicitly.
The axes that the intent code marks as irrelevant, such as a singleton axis before a vector's components, are dropped.
system
property
writable
system: CoordinateSystem | None
The voxel coordinate system, derived from header, unless it
has been set explicitly.
The axes that the intent code marks as irrelevant are dropped.
None when there is no header to derive it from.
lps2voxel
property
lps2voxel: Transformation | None
The affine from LPS world coordinates to the field's voxels.
bound
class-attribute
bound: BoundaryCondition = BoundaryCondition.nearest
The boundary condition used outside of the field of view.
displacement
property
displacement: Transformation | None
The displacement field, in the voxel units of its grid.
voxel2lps
property
voxel2lps: Transformation | None
The affine from the field's voxels back to LPS world.
Methods:
sniff
classmethod
sniff(
file: FileOrContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read
file. On a concrete format, score how confident it is that
file, in any supported form, is its own.
sniff_file
classmethod
On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Determine if the given filename is of the type that this parser can handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to sniff. |
required |
error
|
bool | type[Exception]
|
If not False, raise an error if the filename cannot be sniffed. |
False
|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the filename is of this type, in |
sniff_fileobj
classmethod
sniff_fileobj(
file: IO,
error: bool | Type[Exception] = False,
*,
version: int | None = None,
**kwargs,
) -> float
Score how confident the class is that an open file object
holds a NIfTI-1 or NIfTI-2 header, or a header of the given
version when one is passed.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read the content (text or bytes). On a concrete format, score how confident it is that the content is its own.
sniff_bytes
classmethod
Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.
sniff_text
classmethod
On a dispatcher, identify which registered format would read the text. On a concrete format, score how confident it is that the text is its own.
sniff_lines
classmethod
sniff_lines(
lines: Iterable[str],
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read the lines. On a concrete format, score how confident it is that the lines are its own.
sniff_line
classmethod
On a dispatcher, identify which registered format would read the line. On a concrete format, score how confident it is that the line is its own.
load
classmethod
load(other: FileOrContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and
build an instance of it from other. On a concrete format,
build an instance of this class from other, in any supported
form.
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Load a structured source specification through this dispatcher.
from_file
classmethod
Build the object from a NIfTI file.
A local path is handed to nibabel by name, so that it owns the
file handle and can memory-map the voxels: its array proxy reads
them lazily, long after the call returns. A remote path is opened
through its own backend instead, since nibabel would take its
name for a local file. See _load_nifti.
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Build an object from a filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to parse. |
required |
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The parsed object. |
from_fileobj
classmethod
Build the object from an open NIfTI file object, image data included when the stream allows reading it.
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and build an instance of it from the content (text or bytes). On a concrete format, build an instance of this class from the content.
from_bytes
classmethod
Build the object from bytes in NIfTI format.
from_text
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the text. On a concrete format, build an instance of this class from the text.
from_lines
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the lines. On a concrete format, build an instance of this class from the lines.
from_line
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the line. On a concrete format, build an instance of this class from the line.
save
save(file: FileLike, **kwargs) -> None
Write the object to a file (path or file-like object).
This is the generic front door to the to_* family. It is named
save rather than to because to already means something else
on the data models these parsers are mixed into: Transformation.to
converts an object to another type. A writer's to was shadowed
by it on every writable transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileLike
|
The file to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_file
to_file(file: FileLike, **kwargs) -> None
Write the object to a NIfTI file.
A path is written gzipped when its name ends in .gz: a local
path is handed to nibabel by name, and a remote one is opened
through its own backend. See _save_nifti. A file-like object is
written the uncompressed NIfTI bytes.
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the object to a filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the uncompressed NIfTI-1 encoding of the object to an open file object.
to_text
to_text(**kwargs) -> str
Return a text version of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A text version of the file. |
to_lines
Return a text version of the file as an iterable of lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
Iterator[str]
|
An iterable of lines representing the object. |
to_line
to_line(**kwargs) -> str
Return a line representing the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A line representing the object. |
from_dict
classmethod
Create an instance of the class from a dictionary-like object.
Only keys in the dictionary that match keyword-like fields of
this class, or the keywords its constructor takes without
storing them (its InitVars, such as the matrix= of an
Affine), will be used. Other keys are ignored, but see
from_other,
which refuses them.
Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.
A key naming a field that this class fixes (a field that cannot
be passed to its constructor) is checked instead of used: a
dictionary that sets it to anything other than None or the
value of this class is refused with a ValueError.
from_instance
classmethod
Create an instance from an instance of a similar class.
The data model copies the fields both classes share, by name.
A field that a file format declares for its own use -- such as
the nibabel image and header of the NIfTI and MGH formats
-- is only copied from an object of that same format: from any
other object, a field of the same name holds something else
(a NIfTI image is no MGH image), so this class's default is
kept instead. Saving a NIfTI image to MGH, or the converse,
therefore converts the data model only, and the format-specific
state is rebuilt by the writer.
from_other
classmethod
Create an instance from a file, or from anything the data model reads.
A path (str or os.PathLike), an open file, bytes or a
structured source (SourceSpec)
is read with load: on a dispatcher such as FileBasedImage,
the best-matching registered format reads it, and on a concrete
format, that format does. Any other value is handed to the data
model's own from_other, which reads a mapping field by field,
copies an instance of a similar class, and passes anything else
to the constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A file, its content, a mapping, or an instance of a similar class. |
required |
*args
|
Constructor arguments. A file is read with keyword options only. |
()
|
|
**kwargs
|
Format-specific options when reading a file, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The object that was built. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments come with a file to read. |
from_nibabel
classmethod
from_nibabel(nifti: _NiftiObject, **kwargs) -> Self
Build the field from a nibabel header or image.
The header must be in ITK's layout, so a file that is not an ITK field is refused here, from its header alone, rather than when its chain is first built.
sniff_nibabel
classmethod
Score how confident the class is that an already-loaded
nibabel header or image matches this format.
The header's magic number is checked first. A header that passes is then scored for how well it matches this particular format, as opposed to another kind of NIfTI-based format.
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Transformation
Compute the resulting transform of the sequence of transformations.
Assuming that mode=True:
-
If all transformations in the sequence are affine-like transformations,
compute()returns an affine-like transform. -
If the first (= rightmost) transform in the sequence is a coordinate field,
compute()returns a coordinate field. -
If the first (= rightmost) transform in the sequence is an affine-like transform, and the sequence contains at least one non-affine-like transform,
compute()returns a sequence of two transformations: -
the composition of all affine-like transformations that appear before the first non-affine-like transform in the sequence, and
- the composition of all transformations in the sequence, starting from the first non-affine-like transform in the sequence.
Parameters
mode : [list of] name or type, optional
Kinds of transformations to compose.
* If True (default): compose every kind in the sequence.
* If False: compose nothing (simplify-only).
* If a (list of) transformation type(s): compose only pairs
of transformations of these kinds.
simplify : simplify policy, default="analytic"
Whether to simplify sub-transformations prior to composition,
and how hard to try to simplify them.
* "analytic" (the default) looks at the type structure only;
* "numeric" looks at the numeric values of the transformation;
* False/"none"/None disables simplification.
factor : bool, default=False
Whether to rewrite the sequence into its axis-group normal
form [grid?, F_1..F_m, Pi_perm?]: a leading grid (if any),
one axis-preserving subspace factor per group of axes that
transform together, and a trailing reindex permutation. Off
by default, so the result is byte-for-byte the plain
compute() result. Nothing is ever composed across groups;
mode still decides whether the restricted pieces inside a
group compose. A chain that creates or drops axes is left
unfactored. With mode=False nothing is computed, so
factor has nothing to act on and is ignored.
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify this transformation under a per-kind policy.
Convenience sugar for
compute: t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy).
By default simplify() does no computation at all: compute=False
maps to mode=False, which composes nothing (no matrices multiplied,
no fields sampled, no lazy inverse materialized). It only downcasts
each leaf under policy (analytic by default). Pass an explicit
compute=<mode> to also compose that kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
simplify policy
|
The simplify policy, in the grammar |
"analytic"
|
compute
|
[list of] name or type
|
The compose mode. The default, |
False
|
square
square(compute: bool = False, **kwargs) -> Transformation
Return the square of this transformation, self @ self.
The square is the sequence [self, self], which composes when it
is computed. It is defined for a transformation that maps a space
to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the result now rather than return it lazily. |
False
|
**kwargs
|
Passed to |
{}
|
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 this chain.
The chain is first simplified, which costs nothing. A chain
[P, *X, P^-1], where P^-1 is the lazy inverse of P, or both
are affines whose product is exactly the identity, is a change of
coordinates around X, and its square root is
[P, sqrt(X), P^-1]: a field stored in voxels between a
world-to-voxel affine and its lazy inverse keeps that form. Any
other chain is composed now, and the square root of the
transformation it composes to is returned.
Raises:
| Type | Description |
|---|---|
DomainError
|
If the chain does not map a space to itself, or if the square root of what it reduces to is not defined. |
NotImplementedError
|
If the chain does not compose to a single transformation. |
to
to(
cls: Type[Transformation] | None = None, **kwargs
) -> Transformation
Convert this chain to a different type or encoding.
See Transformation.to. A chain has no tangent of its own -- the tangent of a
composition is not the sum of the tangents -- so log= re-encodes
the transformation it reduces to, and anything else is refused
before it is computed:
- a chain that simplifies to one transformation is that one;
- a change of coordinates
[P, *X, P^-1](seesqrt) keeps its ends, and re-encodesX: the flow of a velocity commutes with the conjugation, so this is exact. A velocity read between a world-to-voxel affine and its inverse (|svf) is turned into its displacement that way; - a chain of affines is composed, which is cheap and exact.
Any other chain -- one with a field, between ends that do not undo
each other -- raises ConversionError.
transformations
transformations() -> tuple[Transformation, ...]
The chain of transformations that the field encodes.
It is built from the NIfTI header and data on first access, and cached. Assigning to it overrides the derived chain, which is how a field that was not read from a file is built.
to_nibabel
to_nibabel(
like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image
Build the nibabel image that ITK would write for this field.
The displacements are rotated from voxel units back into LPS
millimetres and written, unconverted, as a VECTOR (1007)
image of shape (X, Y, Z, 1, 3), or (X, Y, 1, 1, 2) in 2-D.
The grid's voxel-to-LPS affine becomes a voxel-to-RAS sform and
qform.
When like is given, non-encoding header fields are copied from
it. Keyword arguments override header fields last.
ItkNiftiField
ItkNiftiField(
_transformations: tuple[Transformation, ...]
| None = None,
)
Bases: ImmutableSequence, NiftiBasedTransformation
A field stored in an ITK NIfTI vector image, from LPS to LPS.
The vectors of the image are in ITK's LPS physical space, while the
NIfTI header carries the usual voxel-to-RAS affine. This base reads
both, and leaves to its subclasses what the vectors mean:
displacements (ItkNiftiDisplacementField) or absolute
coordinates (ItkNiftiCoordinatesField).
The same code reads 2-D and 3-D fields: the dimension is read off the
header, and the endpoints are the ITK spaces of that dimension --
(L, P) in 2-D and LPSmm in 3-D, both in millimetres.
The chain is made of named slots, so the field is an
ImmutableSequence:
editing it in place raises TypeError.
Abstract: it is not decorated with @register_format, so it never
takes part in dispatch.
Attributes
PREFIXES
class-attribute
PREFIXES: tuple[str, ...] = ()
Filename prefixes required by this parser, e.g. ("y_", "iy_").
An empty tuple means "no constraint". A parser that constrains the prefix is more specific than one that does not, and wins ties.
Declaring EXTENSIONS and PREFIXES separately states the
cross-product implicitly, which is how these conventions actually
work: SPM's four names are {y_, iy_} x {.nii, .nii.gz}.
PRIORITY
class-attribute
PRIORITY: int = 0
Explicit tie-breaker, consulted only when specificity cannot decide.
Higher wins. Leave at 0 unless two parsers genuinely collide.
header
property
writable
The NIfTI header associated with this object.
If a header was explicitly set by the user (at construction or later), this will be pointing to that header.
Otherwise, if the object was created from a NIfTI header, this will be pointing to that header.
Otherwise, if the object was created from a NIfTI image, this will be pointing to the header of that image.
Example
import nibabel as nb
image1 = nb.load("image1.nii")
image2 = nb.load("image2.nii")
NiftiParser(image1).header # `image1.header`
NiftiParser(header=image2.header).header # `image2.header`
NiftiParser(image1, header=image2.header).header # `image2.header`
obj = NiftiParser(image1)
obj.header = image2.header
obj.header # `image2.header`
data
property
writable
The image data, read lazily from image and cached, unless
it has been set explicitly.
The axes that the intent code marks as irrelevant, such as a singleton axis before a vector's components, are dropped.
system
property
writable
system: CoordinateSystem | None
The voxel coordinate system, derived from header, unless it
has been set explicitly.
The axes that the intent code marks as irrelevant are dropped.
None when there is no header to derive it from.
lps2voxel
property
lps2voxel: Transformation | None
The affine from LPS world coordinates to the field's voxels.
Methods:
sniff
classmethod
sniff(
file: FileOrContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read
file. On a concrete format, score how confident it is that
file, in any supported form, is its own.
sniff_file
classmethod
On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Determine if the given filename is of the type that this parser can handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to sniff. |
required |
error
|
bool | type[Exception]
|
If not False, raise an error if the filename cannot be sniffed. |
False
|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the filename is of this type, in |
sniff_fileobj
classmethod
sniff_fileobj(
file: IO,
error: bool | Type[Exception] = False,
*,
version: int | None = None,
**kwargs,
) -> float
Score how confident the class is that an open file object
holds a NIfTI-1 or NIfTI-2 header, or a header of the given
version when one is passed.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read the content (text or bytes). On a concrete format, score how confident it is that the content is its own.
sniff_bytes
classmethod
Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.
sniff_text
classmethod
On a dispatcher, identify which registered format would read the text. On a concrete format, score how confident it is that the text is its own.
sniff_lines
classmethod
sniff_lines(
lines: Iterable[str],
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read the lines. On a concrete format, score how confident it is that the lines are its own.
sniff_line
classmethod
On a dispatcher, identify which registered format would read the line. On a concrete format, score how confident it is that the line is its own.
load
classmethod
load(other: FileOrContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and
build an instance of it from other. On a concrete format,
build an instance of this class from other, in any supported
form.
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Load a structured source specification through this dispatcher.
from_file
classmethod
Build the object from a NIfTI file.
A local path is handed to nibabel by name, so that it owns the
file handle and can memory-map the voxels: its array proxy reads
them lazily, long after the call returns. A remote path is opened
through its own backend instead, since nibabel would take its
name for a local file. See _load_nifti.
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Build an object from a filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to parse. |
required |
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The parsed object. |
from_fileobj
classmethod
Build the object from an open NIfTI file object, image data included when the stream allows reading it.
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and build an instance of it from the content (text or bytes). On a concrete format, build an instance of this class from the content.
from_bytes
classmethod
Build the object from bytes in NIfTI format.
from_text
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the text. On a concrete format, build an instance of this class from the text.
from_lines
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the lines. On a concrete format, build an instance of this class from the lines.
from_line
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the line. On a concrete format, build an instance of this class from the line.
save
save(file: FileLike, **kwargs) -> None
Write the object to a file (path or file-like object).
This is the generic front door to the to_* family. It is named
save rather than to because to already means something else
on the data models these parsers are mixed into: Transformation.to
converts an object to another type. A writer's to was shadowed
by it on every writable transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileLike
|
The file to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_file
to_file(file: FileLike, **kwargs) -> None
Write the object to a NIfTI file.
A path is written gzipped when its name ends in .gz: a local
path is handed to nibabel by name, and a remote one is opened
through its own backend. See _save_nifti. A file-like object is
written the uncompressed NIfTI bytes.
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the object to a filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to write to. |
required |
**kwargs
|
Parser-specific options. |
{}
|
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the uncompressed NIfTI-1 encoding of the object to an open file object.
to_text
to_text(**kwargs) -> str
Return a text version of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A text version of the file. |
to_lines
Return a text version of the file as an iterable of lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
Iterator[str]
|
An iterable of lines representing the object. |
to_line
to_line(**kwargs) -> str
Return a line representing the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A line representing the object. |
from_dict
classmethod
Create an instance of the class from a dictionary-like object.
Only keys in the dictionary that match keyword-like fields of
this class, or the keywords its constructor takes without
storing them (its InitVars, such as the matrix= of an
Affine), will be used. Other keys are ignored, but see
from_other,
which refuses them.
Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.
A key naming a field that this class fixes (a field that cannot
be passed to its constructor) is checked instead of used: a
dictionary that sets it to anything other than None or the
value of this class is refused with a ValueError.
from_instance
classmethod
Create an instance from an instance of a similar class.
The data model copies the fields both classes share, by name.
A field that a file format declares for its own use -- such as
the nibabel image and header of the NIfTI and MGH formats
-- is only copied from an object of that same format: from any
other object, a field of the same name holds something else
(a NIfTI image is no MGH image), so this class's default is
kept instead. Saving a NIfTI image to MGH, or the converse,
therefore converts the data model only, and the format-specific
state is rebuilt by the writer.
from_other
classmethod
Create an instance from a file, or from anything the data model reads.
A path (str or os.PathLike), an open file, bytes or a
structured source (SourceSpec)
is read with load: on a dispatcher such as FileBasedImage,
the best-matching registered format reads it, and on a concrete
format, that format does. Any other value is handed to the data
model's own from_other, which reads a mapping field by field,
copies an instance of a similar class, and passes anything else
to the constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A file, its content, a mapping, or an instance of a similar class. |
required |
*args
|
Constructor arguments. A file is read with keyword options only. |
()
|
|
**kwargs
|
Format-specific options when reading a file, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The object that was built. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments come with a file to read. |
to_nibabel
Build the nibabel image that encodes this object.
Each concrete NIfTI format overrides this method to describe how its own contents map onto a NIfTI image. The other writer methods are defined in terms of this one.
sniff_nibabel
classmethod
Score how confident the class is that an already-loaded
nibabel header or image matches this format.
The header's magic number is checked first. A header that passes is then scored for how well it matches this particular format, as opposed to another kind of NIfTI-based format.
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Transformation
Compute the resulting transform of the sequence of transformations.
Assuming that mode=True:
-
If all transformations in the sequence are affine-like transformations,
compute()returns an affine-like transform. -
If the first (= rightmost) transform in the sequence is a coordinate field,
compute()returns a coordinate field. -
If the first (= rightmost) transform in the sequence is an affine-like transform, and the sequence contains at least one non-affine-like transform,
compute()returns a sequence of two transformations: -
the composition of all affine-like transformations that appear before the first non-affine-like transform in the sequence, and
- the composition of all transformations in the sequence, starting from the first non-affine-like transform in the sequence.
Parameters
mode : [list of] name or type, optional
Kinds of transformations to compose.
* If True (default): compose every kind in the sequence.
* If False: compose nothing (simplify-only).
* If a (list of) transformation type(s): compose only pairs
of transformations of these kinds.
simplify : simplify policy, default="analytic"
Whether to simplify sub-transformations prior to composition,
and how hard to try to simplify them.
* "analytic" (the default) looks at the type structure only;
* "numeric" looks at the numeric values of the transformation;
* False/"none"/None disables simplification.
factor : bool, default=False
Whether to rewrite the sequence into its axis-group normal
form [grid?, F_1..F_m, Pi_perm?]: a leading grid (if any),
one axis-preserving subspace factor per group of axes that
transform together, and a trailing reindex permutation. Off
by default, so the result is byte-for-byte the plain
compute() result. Nothing is ever composed across groups;
mode still decides whether the restricted pieces inside a
group compose. A chain that creates or drops axes is left
unfactored. With mode=False nothing is computed, so
factor has nothing to act on and is ignored.
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify this transformation under a per-kind policy.
Convenience sugar for
compute: t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy).
By default simplify() does no computation at all: compute=False
maps to mode=False, which composes nothing (no matrices multiplied,
no fields sampled, no lazy inverse materialized). It only downcasts
each leaf under policy (analytic by default). Pass an explicit
compute=<mode> to also compose that kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
simplify policy
|
The simplify policy, in the grammar |
"analytic"
|
compute
|
[list of] name or type
|
The compose mode. The default, |
False
|
square
square(compute: bool = False, **kwargs) -> Transformation
Return the square of this transformation, self @ self.
The square is the sequence [self, self], which composes when it
is computed. It is defined for a transformation that maps a space
to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the result now rather than return it lazily. |
False
|
**kwargs
|
Passed to |
{}
|
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 this chain.
The chain is first simplified, which costs nothing. A chain
[P, *X, P^-1], where P^-1 is the lazy inverse of P, or both
are affines whose product is exactly the identity, is a change of
coordinates around X, and its square root is
[P, sqrt(X), P^-1]: a field stored in voxels between a
world-to-voxel affine and its lazy inverse keeps that form. Any
other chain is composed now, and the square root of the
transformation it composes to is returned.
Raises:
| Type | Description |
|---|---|
DomainError
|
If the chain does not map a space to itself, or if the square root of what it reduces to is not defined. |
NotImplementedError
|
If the chain does not compose to a single transformation. |
to
to(
cls: Type[Transformation] | None = None, **kwargs
) -> Transformation
Convert this chain to a different type or encoding.
See Transformation.to. A chain has no tangent of its own -- the tangent of a
composition is not the sum of the tangents -- so log= re-encodes
the transformation it reduces to, and anything else is refused
before it is computed:
- a chain that simplifies to one transformation is that one;
- a change of coordinates
[P, *X, P^-1](seesqrt) keeps its ends, and re-encodesX: the flow of a velocity commutes with the conjugation, so this is exact. A velocity read between a world-to-voxel affine and its inverse (|svf) is turned into its displacement that way; - a chain of affines is composed, which is cheap and exact.
Any other chain -- one with a field, between ends that do not undo
each other -- raises ConversionError.
from_nibabel
classmethod
from_nibabel(nifti: _NiftiObject, **kwargs) -> Self
Build the field from a nibabel header or image.
The header must be in ITK's layout, so a file that is not an ITK field is refused here, from its header alone, rather than when its chain is first built.