Skip to content

brainhops.io.transformations.niftyreg

Readers and writers for NiftyReg transformations.

Written by intent_p1 Class
reg_aladin -aff -- NiftyRegAffine
reg_f3d -cpp 2 CUB_SPLINE_GRID NiftyRegControlPointGrid
(linear grid) 6 LIN_SPLINE_GRID NiftyRegControlPointGrid
reg_transform -def 0 DEF_FIELD NiftyRegDeformationField
reg_transform -disp 1 DISP_FIELD NiftyRegDisplacementField
reg_f3d -vel -cpp 5 SPLINE_VEL_GRID NiftyRegVelocityGrid
(dense velocity) 3 DEF_VEL_FIELD NiftyRegVelocityField
(dense velocity) 4 DISP_VEL_FIELD NiftyRegVelocityField

Hints: niftyreg.aladin, niftyreg.cpp (or niftyreg.f3d), niftyreg.deformation (niftyreg.def), niftyreg.displacement (niftyreg.disp) and niftyreg.velocity (niftyreg.vel); niftyreg alone selects any of them.

The NIfTI files are claimed from their header alone; the affine, a bare matrix, only with a hint (hint="niftyreg").

Every reader writes back what it reads.

Conventions

Checked against the NiftyReg sources (KCL-BMEIS/niftyreg, commit 79a1762, September 2026):

  • Direction. Every NiftyReg transformation maps the reference image's world to the floating image's world -- reg_aladin states it as Affine * Reference = Floating -- which is the direction the data model uses to resample a moving (floating) image onto a reference. Nothing is inverted.
  • World. World coordinates are the NIfTI ones, RAS millimetres, with no sign flip: NiftyReg takes an image's sform when sform_code > 0, and its qform otherwise (sto_xyz / qto_xyz in reg-lib). With both codes zero, nifti1_io makes the qform a diagonal of pixel sizes with no offset, which is what is used here (not nibabel's centred fallback).
  • The NIfTI files are VECTOR (1007) images named "NREG_TRANS", of shape (X, Y, Z, 1, 3), whose intent_p1 holds the NREG_TRANS_TYPE (reg-lib/cpu/Maths.hpp). The generic NIfTI and ITK field readers decline a file with that name.
  • Deformation vs displacement. A deformation field holds positions, a displacement field holds position - voxel world position (reg_getDisplacementFromDeformation): the sign is +1.
  • Control-point grids hold positions, not displacements: the floating world position of each control point (reg_createControlPointGrid initialises them to the identity). The grid's header places it: the reference orientation, scaled to the control-point spacing, with its origin one control point before the reference origin. The spline is the centred cubic B-spline in the grid's voxel units (reg_cubic_spline_getDeformationField3D).
  • Beyond the grid, NiftyReg slides the displacement of the nearest grid point (get_SlidedValues): every field is read as displacements with the nearest boundary condition, which reproduces that.

  • Velocities (reg_f3d -vel) are read as the same chain, whose field is a StationaryVelocityField (log=True): the velocity, in voxel units -- the grid's cubic coefficients for a velocity grid -- integrated by scaling and squaring with |intent_p2| steps (the default rule when it is zero). A negative intent_p2 marks a backward field, whose velocity is negated (reg_defField_getDeformationFieldFromFlowField). A velocity read from a file is written back as it was read; one built from a chain is written as positions, with its steps in intent_p2.

Not supported

  • Velocities with an affine in their extensions (a symmetric registration): NiftyReg removes that affine before integrating the velocity and composes it back after, which is not decoded. They are read and written back, but using one raises NotImplementedError. Integrate them with reg_transform -def and read the deformation field instead.
  • 2-D fields and grids (two components) are not decoded.
  • The non-composition shortcut NiftyReg uses on the reference grid (reg_cubic_spline_getDeformationField3D with composition=false) places the grid by the ratio of pixel sizes rather than by the header; the two agree for a grid made on that reference, which is the case NiftyReg supports.

Classes

NiftyRegAffine

NiftyRegAffine(
    *,
    _input: CoordinateSystem = RASmm(),
    _output: CoordinateSystem = RASmm(),
)

Bases: NiftyRegAffineFormat, TxtArrayParser, TextFileParserWriter, RASToRAS, WritableFileBasedTransformation

A NiftyReg affine, as written by reg_aladin -aff.

The file is plain text: the four rows of a (4, 4) homogeneous matrix, four whitespace-separated numbers per line (reg_tool_WriteAffineFile, reg-io/_reg_ReadWriteMatrix.cpp). NiftyReg documents it as Affine * Reference = Floating: it maps a world coordinate of the reference image to a world coordinate of the floating image. That is the direction the data model uses to resample a moving (floating) image onto a reference, so the matrix is read as it is, with no inversion.

The world coordinates are the NIfTI ones, RAS millimetres: NiftyReg applies the matrix to the reference voxel-to-world affine (its sform when sform_code > 0, its qform otherwise) and then the floating world-to-voxel affine, with no sign flip (reg_affine_deformationField3D, reg-lib/cpu/_reg_globalTrans.cpp). No image is needed to read it.

Dispatch. Nothing in the file says it is NiftyReg's: it is a bare (4, 4) matrix. So this reader scores WEAK, below the generic matrix reader ([TxtMatrixAffine][]) and FLIRT, and is reached with hint="niftyreg" (or "niftyreg.aladin", "aladin").

Writing prints the homogeneous matrix in the same layout, each number with as many digits as it takes to read it back exactly (NiftyReg itself prints %.7g).

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.

matrix property
matrix: ArrayProtocol | None

The affine matrix, of shape (No, Ni + 1), whose last column is the translation component.

homogeneous_matrix property
homogeneous_matrix: ArrayProtocol

The homogeneous matrix of the affine transformation, of shape (No + 1, Ni + 1). The last row of the homogeneous matrix is [0, 0, ..., 1].

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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_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
sniff_bytes(
    content: BinaryContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given bytes are of the type that this parser can handle, by decoding them to text and delegating to sniff_text. Bytes that do not decode are not text, so they score NO.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to sniff.

required
error bool | type[Exception]

If not False, raise an error if the content cannot be sniffed.

False
**kwargs

Parser-specific options, plus encoding (default "utf-8") for decoding content.

{}

Returns:

Type Description
float

Confidence that the content is of this type, in [0, 1].

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

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_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the file (path or file-like object). On a concrete format, build an instance of this class from the file.

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_text classmethod
from_text(text: str, **kwargs) -> Self

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_line classmethod
from_line(line: str, **kwargs) -> Self

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 file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

{}
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 object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

{}
to_bytes
to_bytes(**kwargs) -> bytes

Convert the object to bytes, by converting it to text and encoding the result.

Parameters:

Name Type Description Default
**kwargs

Writer-specific options, plus encoding (default "utf-8") for encoding the text.

{}

Returns:

Type Description
bytes

The byte representation of the 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_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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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
from_other(other: Any, *args, **kwargs) -> Self

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.

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. mode gates which kinds compose, and a leaf has nothing to compose; its downcast is gated only by simplify (simplification is decoupled from the compose mode).

True
simplify simplify policy

How hard this leaf may be looked at. The resolved SimplifyPolicy decides whether the kind-checks run structure-only (analytic) or read values (numeric), or are skipped entirely (none).

"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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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, keep the current type.

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

  • If an Exception, raise it.
  • If True, raise the original error.
  • Otherwise, return the value of error.
True
**kwargs dict

Attributes to override in the converted transform. This allows transformations to be modified within their type. For example, a DisplacementField can be converted from a field of values to a field of spline coefficients by setting coeff=True in kwargs: a change of encoding flag re-encodes the stored data, and keeps the map. A view's name (field=, matrix=, ...) sets the map, as values, and it is stored in the encoding of the result; data= is stored as given.

{}

Returns:

Type Description
Transformation

The converted transformation.

from_array classmethod
from_array(
    array: ndarray, key: str | None = None, **kwargs
) -> Self

Build the affine from the (4, 4) matrix read from the file.

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

The four lines of the file, one row of the matrix per line.

NiftyRegControlPointGrid

NiftyRegControlPointGrid(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegSequence

A NiftyReg control-point grid (CUB_SPLINE_GRID, intent_p1 = 2), as written by reg_f3d -cpp; also a linear one (LIN_SPLINE_GRID, intent_p1 = 6).

The grid holds, at each control point, the floating world (RAS) position of that control point, in millimetres -- not a displacement: reg_createControlPointGrid initialises it with the identity positions and reg_f3d optimises them. The deformation at a reference world point x is the cubic B-spline of those positions, evaluated at x mapped into the grid's voxels by the grid's own header (reg_cubic_spline_getDeformationField3D): the basis is the centred cubic B-spline in grid units (get_BSplineBasisValues), so the control points that act on x are floor(g) - 1 to floor(g) + 2, where g is its grid coordinate.

The grid's header places it: reg_createControlPointGrid copies the reference orientation, scales it to the control-point spacing (the pixdims, in mm) and moves its origin one control point before the reference origin. So no reference image is needed to read it.

The positions are read as spline coefficients of displacements, by subtracting the world position of each control point. A cubic B-spline reproduces linear functions, so the two are the same map wherever every control point that acts is inside the grid, which is everywhere on the reference image. Beyond the grid, NiftyReg slides the displacement of the nearest control point (get_GridValues), which the nearest boundary condition on the coefficients reproduces. A linear grid is a field of linearly interpolated positions on the control points, read the same way at degree 1.

The chain is that of NiftyRegSequence, with degree 3 and coefficients. When the header carries an affine in its extensions (as the grids of a symmetric registration do), NiftyReg applies it to the reference position before the spline (reg_spline_getDeformationField), so the chain starts with that affine, as a [RASToRAS][brainhops.io.transformations.base.affines.RASToRAS] (affine slot), and has four slots.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

log class-attribute
log: bool = False

Whether the field holds a stationary velocity rather than the displacement of the map.

steps property
steps: int | None

The number of squaring steps of a velocity: none here.

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.

voxel2ras property
voxel2ras: Transformation | None

The affine from the field's voxels back to RAS world.

degree property
degree: int

The B-spline degree of the grid: 3, or 1 for a linear grid.

coeff property
coeff: bool

Whether the grid holds spline coefficients: so it does, at any degree above one (at degree one, coefficients are values).

affine property
affine: Transformation | None

The affine applied before the spline, or None.

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

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

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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

sniff_nibabel classmethod
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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.

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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 NIfTI image NiftyReg would write for this grid: the coefficients are turned back into control-point positions.

A chain of four slots, whose first is an affine, has that affine written to the header extension NiftyReg reads it from. When like is given, non-encoding header fields are copied from it. Keyword arguments override header fields last.

NiftyRegDeformationField

NiftyRegDeformationField(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegSequence

A NiftyReg deformation field (DEF_FIELD, intent_p1 = 0).

reg_transform -def (and reg_resample -def) write one: on the reference grid, each voxel holds the floating world (RAS) position, in millimetres, that it maps to (reg_createDeformationField, reg_spline_getDeformationField).

The positions are read as displacements, by subtracting the world position of their voxel, and written back by adding it: the field is the same chain as a NiftyRegDisplacementField, interpolated linearly and extended with the displacement of the nearest edge voxel, which is how NiftyReg composes a deformation field (reg_defField_compose, get_SlidedValues).

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

degree class-attribute
degree: int = 1

The spline degree used to interpolate the field.

bound class-attribute

The boundary condition used outside of the field of view.

coeff class-attribute
coeff: bool = False

Whether the field holds spline coefficients rather than values.

log class-attribute
log: bool = False

Whether the field holds a stationary velocity rather than the displacement of the map.

steps property
steps: int | None

The number of squaring steps of a velocity: none here.

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.

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

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

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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

sniff_nibabel classmethod
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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.

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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 NIfTI image NiftyReg would write for this field: the displacements are turned back into positions.

When like is given, non-encoding header fields are copied from it. Keyword arguments override header fields last.

NiftyRegDisplacementField

NiftyRegDisplacementField(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegSequence

A NiftyReg displacement field (DISP_FIELD, intent_p1 = 1).

reg_transform -disp writes one: on the reference grid, each voxel holds the displacement, in world (RAS) millimetres, from its own world position to the floating position it maps to. The sign is displacement = deformation - position (reg_getDisplacementFromDeformation), so the field maps reference RAS to floating RAS as x -> x + u(x).

It is interpolated linearly, and extended beyond its grid with the displacement of the nearest edge voxel, as NiftyReg composes it (reg_defField_compose). See NiftyRegSequence for the chain.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

degree class-attribute
degree: int = 1

The spline degree used to interpolate the field.

bound class-attribute

The boundary condition used outside of the field of view.

coeff class-attribute
coeff: bool = False

Whether the field holds spline coefficients rather than values.

log class-attribute
log: bool = False

Whether the field holds a stationary velocity rather than the displacement of the map.

steps property
steps: int | None

The number of squaring steps of a velocity: none here.

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.

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

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

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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

sniff_nibabel classmethod
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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.

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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 NIfTI image NiftyReg would write for this field.

When like is given, non-encoding header fields are copied from it. Keyword arguments override header fields last.

NiftyRegField

NiftyRegField(
    data_fields: ClassVar[tuple[str, ...]] = (),
    metadata_fields: ClassVar[tuple[str, ...]] = (),
    derived_fields: ClassVar[tuple[str, ...]] = (),
    *,
    _input: CoordinateSystem | None = None,
    _output: CoordinateSystem | None = None,
)

Bases: NiftyRegTransformationFormat, NiftiBasedTransformation

A NiftyReg transformation stored in a NIfTI file.

NiftyReg writes every non-linear transformation as a VECTOR (1007) image named "NREG_TRANS", and says which kind it is in intent_p1 (NREG_TRANS_TYPE). Each concrete reader claims the kinds listed in its TYPES, with certainty.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

TYPES class-attribute
TYPES: FrozenSet[int] = frozenset()

The intent_p1 values this reader decodes.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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
from_other(other: Any, *args, **kwargs) -> Self

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(**kwargs) -> Nifti1Image

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
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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 (the default) admits every kind. On a leaf transformation, if a mode is given and this leaf is not admitted by it, the leaf is returned unchanged. Keys are transformation types, names or symbols (e.g., "affine", "Aff", "rigid", "SO(3)").

True
simplify SimplifyLike
"analytic"
What

Whether to simplify the transformation prior if possible, 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.

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 compute() result is unchanged. Nothing is ever composed across axis groups; mode still decides whether the restricted pieces inside a group compose.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

False
inverse
inverse(compute: bool = False, **kwargs) -> Self

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 compute when compute is true.

{}

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 compute when compute is true.

{}

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 (log=True), whose square root halves its velocity.

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, keep the current type.

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

  • If an Exception, raise it.
  • If True, raise the original error.
  • Otherwise, return the value of error.
True
**kwargs dict

Attributes to override in the converted transform. This allows transformations to be modified within their type. For example, a DisplacementField can be converted from a field of values to a field of spline coefficients by setting coeff=True in kwargs: a change of encoding flag re-encodes the stored data, and keeps the map. A view's name (field=, matrix=, ...) sets the map, as values, and it is stored in the encoding of the result; data= is stored as given.

{}

Returns:

Type Description
Transformation

The converted transformation.

NiftyRegSequence

NiftyRegSequence(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegField, ImmutableSequence

A NiftyReg field that the data model represents: a chain of transformations from reference RAS to floating RAS.

The stored vectors are world positions or displacements, in NIfTI world (RAS) millimetres, sampled on the file's own grid. A DisplacementField adds its values in the units of its own grid, so each field is read as the chain of [ras_displacement_chain][brainhops.io.transformations.base.fields.ras_displacement_chain]:

Slot Transformation
ras2voxel RAS world coordinates to the field's voxels
displacement the displacements, in voxel units
voxel2ras the field's voxels back to RAS world

Positions are read as displacements, by subtracting the world coordinate of their voxel -- exactly what NiftyReg does (reg_getDisplacementFromDeformation) -- because NiftyReg extends a field beyond its grid by sliding: it keeps the displacement of the nearest edge voxel (get_SlidedValues), which a displacement field with the nearest boundary condition reproduces, and a field of positions would not.

Only three-dimensional fields are decoded: a 2-D NiftyReg field (two components) is refused when read.

Abstract: it is not decorated with @register_format.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

TYPES class-attribute
TYPES: FrozenSet[int] = frozenset()

The intent_p1 values this reader decodes.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

degree class-attribute
degree: int = 1

The spline degree used to interpolate the field.

bound class-attribute

The boundary condition used outside of the field of view.

coeff class-attribute
coeff: bool = False

Whether the field holds spline coefficients rather than values.

log class-attribute
log: bool = False

Whether the field holds a stationary velocity rather than the displacement of the map.

steps property
steps: int | None

The number of squaring steps of a velocity: none here.

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.

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_other(other: Any, *args, **kwargs) -> Self

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
to_nibabel(**kwargs) -> Nifti1Image

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
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

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

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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.

NiftyRegVelocity

NiftyRegVelocity(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegSequence

A NiftyReg stationary velocity field or grid.

reg_f3d -vel parametrises the deformation by a stationary velocity field, and its output is the deformation's exponential: the velocity is scaled down by 2 ** n (n = |intent_p2|) and composed with itself n times (reg_defField_getDeformationFieldFromFlowField); a negative intent_p2 marks a backward field, whose velocity is negated first.

The file is read as the chain of NiftyRegSequence, whose displacement slot is a StationaryVelocityField: the velocity, in voxel units, negated for a backward field, integrated with steps = |intent_p2| squaring steps (the default rule when it is zero). Its flow commutes with the change of coordinates the chain makes, so the chain maps reference RAS to floating RAS as NiftyReg's deformation does.

A velocity grid is read as the coefficients of the velocity, and is squared on its own grid, of control points. NiftyReg evaluates the grid onto the dense reference grid first, and squares there, so the flow matches reg_transform -def closely but not exactly.

NiftyReg removes the affine it keeps in the extensions of a symmetric registration's velocity before the squaring, and composes it back after; that is not decoded here, so a velocity whose header carries an affine raises NotImplementedError when its chain is built.

A velocity read from a file is written back as it was read, header and extensions included. One built from a chain is written as a velocity, with its squaring steps in intent_p2: a displacement field is refused, since it has no logarithm that brainhops computes.

Abstract: it is not decorated with @register_format.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

TYPES class-attribute
TYPES: FrozenSet[int] = frozenset()

The intent_p1 values this reader decodes.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

degree class-attribute
degree: int = 1

The spline degree used to interpolate the field.

bound class-attribute

The boundary condition used outside of the field of view.

coeff class-attribute
coeff: bool = False

Whether the field holds spline coefficients rather than values.

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.

voxel2ras property
voxel2ras: Transformation | None

The affine from the field's voxels back to RAS world.

squaring_steps property
squaring_steps: int | None

The number of squaring steps of the exponentiation, as stored (intent_p2; negative for a backward field).

steps property
steps: int | None

The number of squaring steps that integrate the velocity: |intent_p2|, or None (the default rule) when it is zero.

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

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

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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

to_nibabel
to_nibabel(**kwargs) -> Nifti1Image

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
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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.

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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.

NiftyRegVelocityField

NiftyRegVelocityField(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegVelocity

A dense stationary velocity field, stored as positions (DEF_VEL_FIELD, intent_p1 = 3) or as displacements (DISP_VEL_FIELD, intent_p1 = 4).

The positions are read as the velocity by subtracting the world position of their voxel, as NiftyReg does before integrating them. See NiftyRegVelocity for how it is integrated.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

degree class-attribute
degree: int = 1

The spline degree used to interpolate the field.

bound class-attribute

The boundary condition used outside of the field of view.

coeff class-attribute
coeff: bool = False

Whether the field holds spline coefficients rather than values.

steps property
steps: int | None

The number of squaring steps that integrate the velocity: |intent_p2|, or None (the default rule) when it is zero.

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.

voxel2ras property
voxel2ras: Transformation | None

The affine from the field's voxels back to RAS world.

squaring_steps property
squaring_steps: int | None

The number of squaring steps of the exponentiation, as stored (intent_p2; negative for a backward field).

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

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

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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

sniff_nibabel classmethod
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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.

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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 NIfTI image NiftyReg would write for this velocity: the positions of a DEF_VEL_FIELD (the type NiftyReg integrates), with its squaring steps in intent_p2.

A velocity read from a file is written back as it was read. When like is given, non-encoding header fields are copied from it. Keyword arguments override header fields last.

NiftyRegVelocityGrid

NiftyRegVelocityGrid(
    _transformations: tuple[Transformation, ...]
    | None = None,
)

Bases: NiftyRegVelocity

A cubic B-spline grid of a stationary velocity (SPLINE_VEL_GRID, intent_p1 = 5), as written by reg_f3d -vel -cpp.

Like a NiftyRegControlPointGrid, it holds the floating world position of each control point, and is read as the spline coefficients of their displacement -- here, of the velocity -- by subtracting the world position of each control point. See NiftyRegVelocity for how it is integrated.

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
header: Nifti1Header | None

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
data: ArrayProtocol | None

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.

niftyreg_type property
niftyreg_type: int | None

The NiftyReg transformation type (intent_p1) of the file.

extension_affines property
extension_affines: list[ndarray]

The (4, 4) affines NiftyReg stored in the header extensions.

bound class-attribute

The boundary condition used outside of the field of view.

steps property
steps: int | None

The number of squaring steps that integrate the velocity: |intent_p2|, or None (the default rule) when it is zero.

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.

voxel2ras property
voxel2ras: Transformation | None

The affine from the field's voxels back to RAS world.

squaring_steps property
squaring_steps: int | None

The number of squaring steps of the exponentiation, as stored (intent_p2; negative for a backward field).

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
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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 [0, 1].

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
sniff_bytes(
    data: bytes,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confident the class is that bytes hold a NIfTI-1 or NIfTI-2 header.

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

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
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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
from_file(file: FileLike, **kwargs) -> Self

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
from_fileobj(fileobj: BinaryIO, **kwargs) -> Self

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
from_bytes(data: bytes, **kwargs) -> Self

Build the object from bytes in NIfTI format.

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

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
from_lines(lines: Iterable[str], **kwargs) -> Self

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
from_line(line: str, **kwargs) -> Self

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_bytes
to_bytes(**kwargs) -> bytes

Return the uncompressed NIfTI-1 encoding of the 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
to_lines(**kwargs) -> Iterator[str]

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
from_dict(other: Mapping, *args, **kwargs) -> Self

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
from_instance(other: Any, *args, **kwargs) -> Self

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: that header is another format's, and this one would read its vectors as its own (a displacement as a velocity, say).

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

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.

A NiftyReg field is (X, Y, Z, 1, 3), with its components in the fifth axis (reg_createDeformationField, reg_createControlPointGrid). Anything else -- a 2-D field (X, Y, 1, 1, 2) in particular -- is refused here, from the header alone.

sniff_nibabel classmethod
sniff_nibabel(
    nifti: _NiftiObject,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

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.

input
input() -> CoordinateSystem | None

The reference world space the field maps from.

output
output() -> CoordinateSystem | None

The floating world space the field maps to.

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 compute accepts.

"analytic"
compute [list of] name or type

The compose mode. The default, False, composes nothing (mode=False in compute); None would compose every kind. A real mode passes straight through.

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 compute when compute is true.

{}

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] (see sqrt) keeps its ends, and re-encodes X: 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 NIfTI image NiftyReg would write for this velocity grid: the velocity's cubic coefficients, turned back into control-point positions, with its squaring steps in intent_p2.

A grid read from a file is written back as it was read. When like is given, non-encoding header fields are copied from it. Keyword arguments override header fields last.