brainhops.io.transformations.nifti
Readers and writers for transformations stored in NIfTI files.
Fields of RAS displacements and of RAS coordinates
The NIfTI-1 standard (nifti1.h) gives a field of vectors two intent
codes, and they do not mean the same map:
DISPVECT(1006), "specifically for displacements", is read and written byNiftiRASDisplacementField.VECTOR(1007), "for any other type of vector", is read and written byNiftiRASCoordinatesField.
A displacement field maps x -> x + u(x); a coordinates field maps a
voxel to the position its vector holds. Reading one as the other moves
every point by the whole world position of its voxel, so the intent code
decides between them.
DISPVECT is read as RAS displacements in millimetres, as ITK 5.4 and
later reads it. A field of coordinates is written as VECTOR, with the
intent name "Mapping", which is what SPM writes for its y_
deformations -- the same kind of field. POINTSET (1008) would name the
content better ("the vector value at each voxel is really a spatial
coordinate"), but the standard ties it to a flat list of points
(dim[2] = dim[3] = dim[4] = 1), and readers -- brainhops included --
lay out its axes as one, so a grid written with it would be misread.
Coordinates fields written by brainhops before this change
Older versions of brainhops wrote fields of RAS coordinates with
the DISPVECT intent and nothing else to mark them. Such a file is
byte-for-byte a standard displacement field, so it is now read as
one. Nothing in the file tells the two apart, and guessing from the
values would be just that, so read them explicitly:
load(path, hint="nifti.coordinates"), or
NiftiRASCoordinatesField.from_file(path). Saving the result
rewrites it with the VECTOR intent.
Classes
NiftiRASToVoxel
NiftiRASToVoxel(
*,
_input: CoordinateSystem = RASmm(),
_output: CoordinateSystem = VoxelCoordinateSystem(),
)
Bases: RASToVoxel, _NiftiAffine
Affine transformation from RAS space to voxel space, derived from a NIfTI header.
Not a registered format
A NIfTI header encodes voxel-to-RAS; RAS-to-voxel is its
inverse, computed rather than stored. The two are
indistinguishable by content -- same container, same extension,
same confidence -- so registering both would make every .nii
an ambiguity. Reach this one through
NiftiVoxelToRAS.inverse().
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`
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.
matrix
property
The affine matrix, of shape (No, Ni + 1), whose last column is
the translation component.
homogeneous_matrix
property
The homogeneous matrix of the affine transformation, of shape
(No + 1, Ni + 1). The last row of the homogeneous matrix is
[0, 0, ..., 1].
data
property
writable
The stored affine matrix, which the matrix view reads.
It is derived from the header, unless it has been set explicitly.
It takes the name of the NIfTI parser's image data (the file
holds no voxels of interest, only the header's affine), but not
its storage: an explicit matrix has a slot of its own, so that
reading the image through the parser never stands in for it.
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.
See DataModelBase.from_instance. The map of an Affine is copied through
its matrix view, not its stored data, which a lazy wrapper
derives and a tangent (log=True) stores as its logarithm. A
tangent is copied into a tangent through its data.
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 object from an already-loaded nibabel header or
image.
to_nibabel
to_nibabel(
like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image
Build a nibabel image whose affine is this transformation.
NIfTI stores an affine only as the geometry of a data array, so a single-voxel placeholder volume carries it. The voxel-to-RAS matrix becomes both the sform and the qform, under the code the source header recorded.
When like is given, non-encoding header fields are copied from it.
Keyword arguments override header fields last. The geometry always
comes from this transformation.
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,
) -> Self
Compute the transformation, downcasting it to the cheapest compatible kind.
A concrete transformation holds a parameter, so it simplifies to
the simplest compatible kind, whose compatibility can be detected
with (almost) no overhead. For example, a transformation whose
parameter is set to None is treated as an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
[list of] name or type
|
Ignored on a leaf. |
True
|
simplify
|
simplify policy
|
How hard this leaf may be looked at. The resolved
|
"analytic"
|
factor
|
bool
|
Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default. |
False
|
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. |
to
to(
cls: Type[Self] | None = None,
*,
lossy: bool = False,
error: Type[Exception] | Exception | bool = True,
**kwargs,
) -> Self
Convert this transformation to a different type.
Conversion can be
- between type:
linear.to(Affine); or - within type:
displacement.to(coeff=True); or - both:
coords.to(DisplacementField, coeff=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The type to convert to. If |
None
|
lossy
|
bool
|
Whether to allow lossy conversions. |
False
|
error
|
bool or Exception
|
Whether to raise an error if the conversion fails:
|
True
|
**kwargs
|
dict
|
Attributes to override in the converted transform.
This allows transformations to be modified within their type.
For example, a |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation. |
inverse
inverse(compute: bool = False, **kwargs) -> VoxelToRAS
The inverse transformation, from RAS space to voxel space.
NiftiVoxelToRAS
NiftiVoxelToRAS(
*,
_input: CoordinateSystem = VoxelCoordinateSystem(),
_output: CoordinateSystem = RASmm(),
)
Bases: VoxelToRAS, _NiftiAffine
Affine transformation from voxel space to RAS space, derived from a NIfTI header.
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`
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.
matrix
property
The affine matrix, of shape (No, Ni + 1), whose last column is
the translation component.
homogeneous_matrix
property
The homogeneous matrix of the affine transformation, of shape
(No + 1, Ni + 1). The last row of the homogeneous matrix is
[0, 0, ..., 1].
data
property
writable
The stored affine matrix, which the matrix view reads.
It is derived from the header, unless it has been set explicitly.
It takes the name of the NIfTI parser's image data (the file
holds no voxels of interest, only the header's affine), but not
its storage: an explicit matrix has a slot of its own, so that
reading the image through the parser never stands in for it.
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.
See DataModelBase.from_instance. The map of an Affine is copied through
its matrix view, not its stored data, which a lazy wrapper
derives and a tangent (log=True) stores as its logarithm. A
tangent is copied into a tangent through its data.
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 object from an already-loaded nibabel header or
image.
to_nibabel
to_nibabel(
like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image
Build a nibabel image whose affine is this transformation.
NIfTI stores an affine only as the geometry of a data array, so a single-voxel placeholder volume carries it. The voxel-to-RAS matrix becomes both the sform and the qform, under the code the source header recorded.
When like is given, non-encoding header fields are copied from it.
Keyword arguments override header fields last. The geometry always
comes from this transformation.
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,
) -> Self
Compute the transformation, downcasting it to the cheapest compatible kind.
A concrete transformation holds a parameter, so it simplifies to
the simplest compatible kind, whose compatibility can be detected
with (almost) no overhead. For example, a transformation whose
parameter is set to None is treated as an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
[list of] name or type
|
Ignored on a leaf. |
True
|
simplify
|
simplify policy
|
How hard this leaf may be looked at. The resolved
|
"analytic"
|
factor
|
bool
|
Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default. |
False
|
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. |
to
to(
cls: Type[Self] | None = None,
*,
lossy: bool = False,
error: Type[Exception] | Exception | bool = True,
**kwargs,
) -> Self
Convert this transformation to a different type.
Conversion can be
- between type:
linear.to(Affine); or - within type:
displacement.to(coeff=True); or - both:
coords.to(DisplacementField, coeff=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The type to convert to. If |
None
|
lossy
|
bool
|
Whether to allow lossy conversions. |
False
|
error
|
bool or Exception
|
Whether to raise an error if the conversion fails:
|
True
|
**kwargs
|
dict
|
Attributes to override in the converted transform.
This allows transformations to be modified within their type.
For example, a |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation. |
inverse
inverse(compute: bool = False, **kwargs) -> RASToVoxel
The inverse transformation, from RAS space to voxel space.
NiftiBasedTransformation
NiftiBasedTransformation(
data_fields: ClassVar[tuple[str, ...]] = (),
metadata_fields: ClassVar[tuple[str, ...]] = (),
derived_fields: ClassVar[tuple[str, ...]] = (),
*,
_input: CoordinateSystem | None = None,
_output: CoordinateSystem | None = None,
)
Bases: WritableFileBasedTransformation, NiftiParser
A transformation that is stored in a NIfTI file.
Abstract: it is not decorated with @register_format, so it never
takes part in dispatch. Concrete NIfTI transformations inherit from
it and register themselves.
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.
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 object from an already-loaded nibabel header or
image.
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,
) -> Self
Compute the transformation, if it is not already fully defined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
[list of] name or type
|
Which kinds of transformations to materialize.
|
True
|
simplify
|
SimplifyLike
|
|
"analytic"
|
What
|
Whether to simplify the transformation prior if possible,
and how hard to try to simplify them.
* |
required | |
factor
|
bool
|
Whether to rewrite the transformation into its axis-group
normal form, splitting it into independent factors that each
act on a group of axes that transform together. Off by default,
so a plain |
False
|
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
|
inverse
Return the inverse of this transformation.
Some classes of transformations return a lazy inverse by default,
which is only evaluated when the compute() method is called.
This allows for efficient composition of transformations.
Or the inverse can be computed immediately by setting compute=True.
The inverse can also be obtained using the __invert__ operator:
T.inverse() is equivalent to ~T.
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 transformation.
The square root S of T is the transformation with
S @ S == T, the half-transformation. The principal one, whose
linear part has its eigenvalues in the open right half-plane, is
unique, and it is of the same kind as T: the square root of a
rotation is a rotation, of a translation a translation, of a
scaling a scaling, of an affine an affine. The square root of a
permutation is a Linear transformation.
The square root is lazy: an Sqrt wrapper is returned, and
computed when it is applied, computed or converted. A transformation
that needs no wrapper (an identity) is returned as is. A
Sequence is reduced first (see Sequence.sqrt).
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, or, when the result is computed, if its linear part has an eigenvalue on the closed negative real axis (a reflection, a rotation by a half turn, a singular matrix), so that it has no real principal square root. |
NotImplementedError
|
If brainhops does not compute the square root of this kind of
transformation. A displacement field has one only when it is a
stationary velocity field ( |
to
to(
cls: Type[Self] | None = None,
*,
lossy: bool = False,
error: Type[Exception] | Exception | bool = True,
**kwargs,
) -> Self
Convert this transformation to a different type.
Conversion can be
- between type:
linear.to(Affine); or - within type:
displacement.to(coeff=True); or - both:
coords.to(DisplacementField, coeff=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The type to convert to. If |
None
|
lossy
|
bool
|
Whether to allow lossy conversions. |
False
|
error
|
bool or Exception
|
Whether to raise an error if the conversion fails:
|
True
|
**kwargs
|
dict
|
Attributes to override in the converted transform.
This allows transformations to be modified within their type.
For example, a |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation. |
NiftiRASCoordinatesField
NiftiRASCoordinatesField(
*,
_input: CoordinateSystem = VoxelCoordinateSystem(),
_output: CoordinateSystem = RASmm(),
)
Bases: RASCoordinatesField, NiftiBasedTransformation
Field of RAS coordinates, stored in a NIfTI file.
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`
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.
data
property
writable
The field of RAS coordinates, as an (X, Y, Z, 3) array.
It is the image data that the NIfTI parser reads from the file,
and the array this field stores: its field view reads it.
NIfTI stores a vector field as (X, Y, Z, 1, 3), with the
components in the fifth axis, and SPM writes its y_ fields that
way. The singleton axis before the components is dropped, or the
field would be sampled as a 4-D grid of 3-vectors.
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.
See DataModelBase.from_instance. A lazy wrapper derives its data and its
flags, so they are read through their public names.
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 object from an already-loaded nibabel header or
image.
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,
) -> Self
Compute the transformation, downcasting it to the cheapest compatible kind.
A concrete transformation holds a parameter, so it simplifies to
the simplest compatible kind, whose compatibility can be detected
with (almost) no overhead. For example, a transformation whose
parameter is set to None is treated as an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
[list of] name or type
|
Ignored on a leaf. |
True
|
simplify
|
simplify policy
|
How hard this leaf may be looked at. The resolved
|
"analytic"
|
factor
|
bool
|
Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default. |
False
|
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. |
to
to(
cls: Type[Self] | None = None,
*,
lossy: bool = False,
error: Type[Exception] | Exception | bool = True,
**kwargs,
) -> Self
Convert this transformation to a different type.
Conversion can be
- between type:
linear.to(Affine); or - within type:
displacement.to(coeff=True); or - both:
coords.to(DisplacementField, coeff=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The type to convert to. If |
None
|
lossy
|
bool
|
Whether to allow lossy conversions. |
False
|
error
|
bool or Exception
|
Whether to raise an error if the conversion fails:
|
True
|
**kwargs
|
dict
|
Attributes to override in the converted transform.
This allows transformations to be modified within their type.
For example, a |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation. |
field
The field, as values: an array of shape (*shape, ndim).
It is data itself when coeff is false, and data decoded
from spline coefficients (once, then cached) when it is true.
to_nibabel
to_nibabel(
like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image
Build the nibabel image that encodes this field of RAS coordinates.
The field array becomes the NIfTI data array, and the header
carries the VECTOR (1007) intent code, with SPM's intent name
"Mapping", that marks the file as a field of coordinates rather
than a plain image. DISPVECT (1006) is not used: the standard
reserves it for displacements, and ITK and brainhops read it as
such. The voxel-to-RAS affine of the
grid is taken from the source header when the field was read from
one, and is the identity otherwise.
The field array keeps its own array backend. A cupy or dask
array is passed through rather than coerced into numpy. When
like is given, non-encoding header fields are copied from it.
Keyword arguments override header fields last, so an explicit value
wins.
NiftiRASDisplacementField
magic
Bases: ImmutableSequence, NiftiBasedTransformation
Field of RAS displacements, stored in a NIfTI file.
This is the DISPVECT (1006) field of the NIfTI-1 standard: each
voxel holds the displacement, in RAS millimetres, of the point at
its centre, and the field maps RAS to RAS as x -> x + u(x). It is
how ITK 5.4 and later reads and writes a DISPVECT image.
A DisplacementField adds its values in the units of its own grid,
so the field is the
ImmutableSequence
of three named slots:
| Slot | Transformation |
|---|---|
ras2voxel |
RAS world coordinates to the field's voxels |
displacement |
the displacement field, in voxel units |
voxel2ras |
the field's voxels back to RAS world |
The displacements are interpolated linearly and extended with the
nearest value outside the grid, as ITK's DisplacementFieldTransform
does by default.
The file may hold a stationary velocity instead, whose flow at time
one is the map: the standard has no code for one, so it is said with
the log option (warp.nii.gz|displacements|log:true, or its alias
warp.nii.gz|svf; in Python, load(path, log=True)). The
displacement slot is then a
StationaryVelocityField, integrated with steps squaring steps
(|svf|steps:6). The field is written in the encoding the options
say: a velocity when log is set, and otherwise the displacement,
which a velocity is integrated into.
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.
bound
class-attribute
bound: BoundaryCondition = BoundaryCondition.nearest
The boundary condition used outside of the field of view.
ras2voxel
property
ras2voxel: Transformation | None
The affine from RAS world coordinates to the field's voxels.
displacement
property
displacement: Transformation | None
The displacement field, in the voxel units of its grid (a
velocity, with log).
voxel2ras
property
voxel2ras: Transformation | None
The affine from the field's voxels back to RAS 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_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_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_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 object from an already-loaded nibabel header or
image.
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_instance
classmethod
Create an instance from an instance of a similar class.
The chain of another transformation is carried over, rather than
re-read from a NIfTI header that comes with it and says something
else (a NiftyReg file holds positions, say). Its encoding is not:
log and steps are this format's options, so a velocity copied
here is written as its displacement unless log=True is given --
to this copy, or to save.
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. Either way it is a
tuple, and the field refuses in-place edits: its slots name fixed
positions in the chain, so a copy with other slots is made with
replace.
to_nibabel
Build the nibabel image that encodes this field of displacements.
The displacements are rotated from voxel units into RAS
millimetres and written as a DISPVECT (1006) image of shape
(X, Y, Z, 1, 3), whose voxel-to-RAS affine is the grid's. With
log (this field's own, unless one is given here, as in
save(path, log=True)), the velocity is written instead;
otherwise a velocity is integrated into its displacement.
When like is given, non-encoding header fields are copied from
it. Keyword arguments override header fields last.