Skip to content

A plain matrix file stores an affine and nothing else. There is one reader per container, each built on that container's generic array parser from brainhops.io.base.arrays, and all deriving from the abstract MatrixAffine, which is never registered:

Class Container Extensions Hints
TxtMatrixAffine whitespace-separated text .txt, .dat, .1D "matrix.txt"
CsvMatrixAffine comma-separated text .csv "matrix.csv"
TsvMatrixAffine tab-separated text .tsv "matrix.tsv"
NpyMatrixAffine NumPy .npy .npy "matrix.npy"
NpzMatrixAffine NumPy .npz .npz "matrix.npz"
MatLegacyMatrixAffine MATLAB v4, v5-v7 (scipy) .mat "matrix.mat"
Mat73MatrixAffine MATLAB v7.3 (h5py) .mat "matrix.mat", "mat.73", "matrix.mat.73"

MatMatrixAffine (hint "matrix.mat") is the parent of the two MATLAB readers. It is not registered (its variants are), but it can be used directly: it reads any MATLAB version and returns an object of the variant that matches the file. AFNI .1D and generic .dat files are whitespace-separated columns with # comments, so they are read by TxtMatrixAffine.

hint="matrix" selects among all of them by content; a container hint selects one. The conventions are given when reading:

Keyword Default Meaning
vector "column" "row" if the file maps row vectors (y = x @ A); it is transposed.
ndim None 2 to read a (3, 3) matrix as a 2-D affine (else 3-D linear).
direction "forward" "inverse" if the file maps output to input; it is inverted.
input None "voxel", "ras", "lps", a CoordinateSystem, or unnamed.
output None Same as input.
index_base 0 1 for 1-based voxel indices (MATLAB, SPM), or an (input, output) pair.
source None Image whose voxel-to-world affine maps a voxel input to world.
target None Image whose voxel-to-world affine maps a voxel output to world.
variable None .npz key or .mat variable (alias key); by default the only 2-D numeric array.

They are applied in the order: transposition, inversion, index shift, image placement. The result is a column-vector, 0-based affine (#201: integer index = voxel centre).

Because any small numeric table reads as a matrix, these readers score low and never take a file away from FLIRT (.mat text) or ITK (.mat v4, .tfm, .h5), except that a text matrix named .txt, .csv, .tsv, .dat or .1D (with that file's separator) is preferred to FLIRT. Without a telling name, text content goes to one reader only: a comma makes it CSV, tab-separated values TSV, anything else TXT. Use hint="matrix" (or a container hint) to force them.

brainhops.io.transformations.matrix

Plain affine matrices stored in text, NumPy (.npy, .npz) or MATLAB (.mat) files.

The file stores only the numbers; what they mean (spaces, index base, direction, vector convention) is given by the caller when reading. See MatrixAffine, the abstract base of one reader per container: TxtMatrixAffine, CsvMatrixAffine, TsvMatrixAffine, NpyMatrixAffine, NpzMatrixAffine, and MatMatrixAffine, which dispatches to MatLegacyMatrixAffine (MATLAB v4-v7) or Mat73MatrixAffine (MATLAB v7.3).

Reading a 1-based voxel-to-voxel matrix saved by MATLAB

from brainhops.io.transformations import load

xform = load(
    "M.mat", hint="matrix", variable="M",
    input="voxel", output="voxel", index_base=1,
)

Classes

CsvMatrixAffine

CsvMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: CsvArrayParser, MatrixAffine

An affine stored as a bare matrix in comma-separated text (.csv). See MatrixAffine for the conventions.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

NAMED_CONFIDENCE class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY

The least score of a text array whose file name has one of the reader's 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_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.

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

Apply the conventions to the raw matrix read from the file.

Mat73MatrixAffine

Mat73MatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: Mat73ArrayParser, MatMatrixAffine

An affine stored as a bare matrix in a MATLAB v7.3 (HDF5) .mat file, read with h5py. v7.3 stores arrays transposed, which is undone. See MatMatrixAffine.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

VARIANTS class-attribute
VARIANTS: tuple[type, ...] = ()

The readers this class dispatches to: the v4-v7 reader, then the v7.3 reader.

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

Score an open file, reading at most SNIFF_LIMIT bytes.

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_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_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the open file object. On a concrete format, build an instance of this class from the file 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.

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

Apply the conventions to the raw matrix read from the file.

MatLegacyMatrixAffine

MatLegacyMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: MatLegacyArrayParser, MatMatrixAffine

An affine stored as a bare matrix in a MATLAB v4 or v5-v7 .mat file, read with scipy.io. See MatMatrixAffine.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

VARIANTS class-attribute
VARIANTS: tuple[type, ...] = ()

The readers this class dispatches to: the v4-v7 reader, then the v7.3 reader.

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

Score an open file, reading at most SNIFF_LIMIT bytes.

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_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_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the open file object. On a concrete format, build an instance of this class from the file 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.

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

Apply the conventions to the raw matrix read from the file.

MatMatrixAffine

MatMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: MatArrayParser, MatrixAffine

An affine stored as a bare matrix in a MATLAB .mat file of any version. Select the variable with variable=; by default, the only 2-D numeric variable. See MatrixAffine for the conventions.

It dispatches to MatLegacyMatrixAffine (v4, v5-v7) or Mat73MatrixAffine (v7.3) by content, and returns an object of that class. It is not registered itself: its two variants are, and answer to its hint "matrix.mat", so registering it too would only put it in competition with its own subclasses.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

VARIANTS class-attribute
VARIANTS: tuple[type, ...] = ()

The readers this class dispatches to: the v4-v7 reader, then the v7.3 reader.

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

Score an open file, reading at most SNIFF_LIMIT bytes.

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_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_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the open file object. On a concrete format, build an instance of this class from the file 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.

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

Apply the conventions to the raw matrix read from the file.

MatrixAffine magic

MatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: AffineTransformationFormat, ArrayParser, Affine, FileBasedTransformation

An affine stored as a bare matrix in a generic array container.

The file holds a (3, 3), (3, 4) or (4, 4) matrix (in 2-D, (2, 3) or (3, 3)), and nothing else: no coordinate systems, no index base, no direction. The caller states those as keyword arguments to load / from_file; the defaults are listed below.

Abstract: it reads no container, and is not decorated with @register_format, so it never takes part in dispatch. Each container has its own registered subclass, which mixes in that container's ArrayParser:

MatMatrixAffine (hint "matrix.mat") is their unregistered parent: it reads any MATLAB version by dispatching to them.

All of them answer to hint="matrix", which then picks the container from the content. In a container that holds several arrays (.npz, .mat), select the matrix with variable= (or key=); by default, the only 2-D numeric array is read.

Conventions (keyword arguments)

  • vector="column": "column" if the matrix maps column vectors (y = A @ x), "row" if it maps row vectors (y = x @ A, the matrix is then transposed).
  • ndim=None: the number of spatial dimensions. Only needed for a (3, 3) matrix, which is read as a 3-D linear map unless ndim=2 makes it a 2-D homogeneous affine.
  • direction="forward": "inverse" if the file stores the map from output to input; it is then inverted.
  • input=None, output=None: the spaces the (forward) matrix maps from and to: "voxel" (or "pixel" / "index"), "ras", "lps", a CoordinateSystem, or None for a generic, unnamed space.
  • index_base=0: 1 if voxel indices are 1-based (MATLAB, SPM), or an (input, output) pair. A 1-based voxel endpoint is shifted to the 0-based, voxel-centred index space of the data model. A scalar applies to every voxel endpoint and requires at least one.
  • source=None, target=None: images (nibabel image or header, or brainhops image). When given, the voxel input (output) is mapped to that image's world space through its voxel-to-world affine, so the result is a world-to-world affine. Passing an image makes that endpoint default to "voxel".

The conventions are applied in this order: transposition, inversion, index shift, image placement. The raw matrix and the conventions it was read with are kept on the object (raw_matrix, variable, vector, direction, index_base); the container is the class's CONTAINER.

Dispatch

Any small numeric table reads as a matrix, so these readers score WEAK and lose to every format that recognizes a file positively: a FLIRT .mat (a text (4, 4)), an ITK .mat (MATLAB v4), an ITK .tfm / .txt / .h5. The exception is a text matrix whose file name has a text-array extension (.txt, .csv, .tsv, .dat, .1D) matching its separator, which scores LIKELY so it is not read as a FLIRT matrix. Files over 1 MiB are not sniffed. Pass hint="matrix" (or a container hint) to force these readers.

Attributes

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

File extensions handled by this parser, e.g. (".nii", ".nii.gz").

Used as a first, cheap dispatch pass. When several parsers match, the longest matching extension wins, so a parser declaring ".nii.gz" takes precedence over one declaring ".gz".

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].

CONTAINER class-attribute
CONTAINER: str = ''

A short name for the container, e.g. "npy".

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

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

Score an open file, reading at most SNIFF_LIMIT bytes.

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,
) -> type | None

On a dispatcher, identify which registered format would read the bytes. On a concrete format, score how confident it is that the bytes are its own.

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

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_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

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

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

On a dispatcher, pick the best-matching registered format and build an instance of it from the content (text or bytes). On a concrete format, build an instance of this class from the content.

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

On a dispatcher, pick the best-matching registered format and build an instance of it from the bytes. On a concrete format, build an instance of this class from the bytes.

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.

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

Apply the conventions to the raw matrix read from the file.

NpyMatrixAffine

NpyMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: NpyArrayParser, MatrixAffine

An affine stored as a bare matrix in a NumPy .npy file, read without unpickling. See MatrixAffine for the conventions.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

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

Score an open file, reading at most SNIFF_LIMIT bytes.

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_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_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the open file object. On a concrete format, build an instance of this class from the file 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.

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

Apply the conventions to the raw matrix read from the file.

NpzMatrixAffine

NpzMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: NpzArrayParser, MatrixAffine

An affine stored as a bare matrix in a NumPy .npz archive, read without unpickling. Select the array with variable= (or key=); by default, the only 2-D numeric array. See MatrixAffine for the conventions.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

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

Score an open file, reading at most SNIFF_LIMIT bytes.

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_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_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

On a dispatcher, pick the best-matching registered format and build an instance of it from the open file object. On a concrete format, build an instance of this class from the file 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.

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

Apply the conventions to the raw matrix read from the file.

TsvMatrixAffine

TsvMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: TsvArrayParser, MatrixAffine

An affine stored as a bare matrix in tab-separated text (.tsv). See MatrixAffine for the conventions.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

NAMED_CONFIDENCE class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY

The least score of a text array whose file name has one of the reader's 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_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.

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

Apply the conventions to the raw matrix read from the file.

TxtMatrixAffine

TxtMatrixAffine(
    raw_matrix: ArrayLike | None = None,
    variable: str | None = None,
    vector: str | None = None,
    direction: str | None = None,
    index_base: tuple[int, int] | None = None,
)

Bases: TxtArrayParser, MatrixAffine

An affine stored as a bare matrix in whitespace-separated text (.txt, also .dat and AFNI-style .1D): one row per line, # starting a comment, blank lines skipped. See MatrixAffine for the conventions.

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].

raw_matrix class-attribute instance-attribute
raw_matrix: ArrayLike | None = None

The matrix exactly as stored in the file, before any convention (transposition, inversion, index shift, image placement) is applied.

variable class-attribute instance-attribute
variable: str | None = None

The .npz key or .mat variable the matrix was read from.

vector class-attribute instance-attribute
vector: str | None = None

The vector convention the raw matrix was read with.

direction class-attribute instance-attribute
direction: str | None = None

The direction the raw matrix was read with.

index_base class-attribute instance-attribute
index_base: tuple[int, int] | None = None

The (input, output) voxel index base the raw matrix was read with.

NAMED_CONFIDENCE class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY

The least score of a text array whose file name has one of the reader's 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_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.

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

Apply the conventions to the raw matrix read from the file.