Skip to content

brainhops.io.transformations.freesurfer.lta

Readers and writers for FreeSurfer's Linear Transform Array (LTA) format.

An LTA file stores a linear (affine) transformation together with the coordinate systems it maps between, recorded as its type and as the geometry of its source and destination volumes.

Classes

LtaMatrixType

Bases: int, Enum

The element type of a matrix parsed from an LTA file.

LtaType

Bases: int, Enum

The affine transformation type recorded in an LTA file header.

This enumeration identifies the coordinate systems that the transformation maps between, such as voxel-to-voxel or RAS-to-RAS.

LtaValidity

Bases: int, Enum

Whether a volume-geometry block in an LTA file is populated.

LtaStruct magic

LtaStruct(
    type: LtaType = LINEAR_VOX_TO_VOX,
    nxforms: int = 1,
    mean: _3Floats = (0.0, 0.0, 0.0),
    sigma: float = 0.0,
    affine: Affine = Factory(Affine),
    label: int | None = None,
    src: SrcVolumeInfo | None = None,
    dst: DstVolumeInfo | None = None,
)

Bases: LtaParser

In-memory representation of an LTA file.

The parsing mechanisms are implemented in the parent classes: LtaParser, MatrixParser, and VolumeInfoParser.

:: note "Reference" https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/LtaFormat

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.

Classes

Affine magic
Affine(matrix: _Matrix = ())

Bases: MatrixParser

A matrix, encoded in ASCII.

This encoding is ubiquitous in Freesurfer (not only in LTA files) and can represent any 2D matrix of real or complex numbers, as indicated by the first value in the header (1 => real, 2 => complex). The second and third numbers indicate the number of rows and columns.

In LTA files, they are always 4x4 real matrices, but the parser is flexible enough to handle any size and type.

The matrix attribute is a tuple of tuples, not a NumPy array.

:: example "Example" A 4x4 real matrix:

1 4 4
+1.141600  +0.018630  +0.010876  -23.066311
-0.019849  +1.142709  +0.150979  -29.566288
-0.010058  -0.155729  +0.919673  +26.393215
+0.000000  +0.000000  +0.000000  +1.000000

A 4x4 complex matrix:
```
2 4 4
+1.141600 +0.0   +0.018630 +0.0   +0.010876 +0.0   -23.066311 +0.0
-0.019849 +0.0   +1.142709 +0.0   +0.150979 +0.0   -29.566288 +0.0
-0.010058 +0.0   -0.155729 +0.0   +0.919673 +0.0   +26.393215 +0.0
+0.000000 +0.0   +0.000000 +0.0   +0.000000 +0.0   +1.000000 +0.0
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_type property
matrix_type: LtaMatrixType

Determines the type of the matrix based on its contents.

dtype property
dtype: type | None

The Python type corresponding to the matrix type.

Either float for real matrices, complex for complex matrices, or None if unknown.

shape property
shape: _2Ints

The shape of the matrix as a tuple (rows, columns).

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileOrContentLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given content is of the type that this parser can handle.

Parameters:

Name Type Description Default
content ContentLike

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.

{}

Returns:

Type Description
float

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

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,
) -> float

Determine if the given text is of the type that this parser can handle.

Parameters:

Name Type Description Default
text str

The text to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given lines are of the type that this parser can handle.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Score how likely a line is to be the first line of an LTA file.

The first line of an LTA file, once comments are stripped, is its type: type = <int>.

Parameters:

Name Type Description Default
line str

The first line that is not blank or a comment.

required
error bool | type[Exception]

If not False, raise an error if the line is not the first line of an LTA file.

False

Returns:

Type Description
float

Confidence that the line opens an LTA file, in [0, 1].

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

Build an object from a file (path, file-like object or iterable of lines).

This is the generic front door to the from_* family: it looks at what it was handed and calls the right one.

A str is always a path, whether or not the file exists, so a missing file raises FileNotFoundError whichever way its path was spelled. Text held in memory is read with from_text or from_content.

Parameters:

Name Type Description Default
other FileOrContentLike

Input file, or its content.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

Raises:

Type Description
ParserExistsError

If other is a path to a file that does not exist. It is a FileNotFoundError.

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

Build an object from an unqualified structured source.

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

Build an object from a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file-like object.

The default implementation reads the whole stream and hands its content to from_content (hence to from_bytes for binary streams). Parsers that only need part of the stream (e.g., a header) should override this method; from_bytes then falls back to it.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file content (bytes, str, or iterable of lines).

Parameters:

Name Type Description Default
content ContentLike

The content to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a text representation of a file.

Parameters:

Name Type Description Default
text str

The text to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build the matrix block from an iterable over lines of an LTA file.

Parameters:

Name Type Description Default
lines Iterable[str]

Iterable content of an LTA file, positioned at the start of the block.

required

Returns:

Type Description
obj

The parsed matrix block.

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

Build an object from a single line of text.

Parameters:

Name Type Description Default
line str

The line to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

Convert the object to a string in LTA format, ending with a newline.

Returns:

Type Description
str

The string representation of the object in LTA format.

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

Convert the matrix block to an iterable over lines of an LTA file.

Entries are written at full double precision, so that a matrix survives a round trip unchanged. FreeSurfer writes six decimals, but reads either.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

from_ classmethod
from_(other: FileOrContentLike) -> Self

Build an object from a file, or from its content.

Deprecated

Use load for a file, a file object or bytes, and from_text or from_lines for content held in memory. Unlike load, from_ reads a string that names no existing file as LTA content.

Parameters:

Name Type Description Default
other str | PathLike | IO | bytes | Iterable[str]

Input file, or its content.

required

Returns:

Type Description
obj

The parsed object.

VolumeInfo magic
VolumeInfo(
    valid: LtaValidity = VOLUME_INFO_INVALID,
    filename: str = "",
    volume: _3Ints = (0, 0, 0),
    voxelsize: _3Floats = (1.0, 1.0, 1.0),
    xras: _3Floats = (1.0, 0.0, 0.0),
    yras: _3Floats = (0.0, 1.0, 0.0),
    zras: _3Floats = (0.0, 0.0, 1.0),
    cras: _3Floats = (0.0, 0.0, 0.0),
)

Bases: VolumeInfoParser

The geometry of a volume.

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.

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileOrContentLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given content is of the type that this parser can handle.

Parameters:

Name Type Description Default
content ContentLike

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.

{}

Returns:

Type Description
float

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

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,
) -> float

Determine if the given text is of the type that this parser can handle.

Parameters:

Name Type Description Default
text str

The text to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given lines are of the type that this parser can handle.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Score how likely a line is to be the first line of an LTA file.

The first line of an LTA file, once comments are stripped, is its type: type = <int>.

Parameters:

Name Type Description Default
line str

The first line that is not blank or a comment.

required
error bool | type[Exception]

If not False, raise an error if the line is not the first line of an LTA file.

False

Returns:

Type Description
float

Confidence that the line opens an LTA file, in [0, 1].

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

Build an object from a file (path, file-like object or iterable of lines).

This is the generic front door to the from_* family: it looks at what it was handed and calls the right one.

A str is always a path, whether or not the file exists, so a missing file raises FileNotFoundError whichever way its path was spelled. Text held in memory is read with from_text or from_content.

Parameters:

Name Type Description Default
other FileOrContentLike

Input file, or its content.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

Raises:

Type Description
ParserExistsError

If other is a path to a file that does not exist. It is a FileNotFoundError.

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

Build an object from an unqualified structured source.

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

Build an object from a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file-like object.

The default implementation reads the whole stream and hands its content to from_content (hence to from_bytes for binary streams). Parsers that only need part of the stream (e.g., a header) should override this method; from_bytes then falls back to it.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file content (bytes, str, or iterable of lines).

Parameters:

Name Type Description Default
content ContentLike

The content to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a text representation of a file.

Parameters:

Name Type Description Default
text str

The text to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build a volume-geometry block from an iterable over lines of an LTA file.

Returns None, without consuming any line, if the next line is not this block's header.

Parameters:

Name Type Description Default
lines Iterable[str]

Iterable content of an LTA file, positioned at the start of the block.

required

Returns:

Type Description
obj or None

The parsed volume-geometry block, or None.

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

Build an object from a single line of text.

Parameters:

Name Type Description Default
line str

The line to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

Convert the object to a string in LTA format, ending with a newline.

Returns:

Type Description
str

The string representation of the object in LTA format.

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

Convert the volume-geometry block to an iterable over lines of an LTA file, header included.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

from_ classmethod
from_(other: FileOrContentLike) -> Self

Build an object from a file, or from its content.

Deprecated

Use load for a file, a file object or bytes, and from_text or from_lines for content held in memory. Unlike load, from_ reads a string that names no existing file as LTA content.

Parameters:

Name Type Description Default
other str | PathLike | IO | bytes | Iterable[str]

Input file, or its content.

required

Returns:

Type Description
obj

The parsed object.

SrcVolumeInfo
SrcVolumeInfo(
    valid: LtaValidity = VOLUME_INFO_INVALID,
    filename: str = "",
    volume: _3Ints = (0, 0, 0),
    voxelsize: _3Floats = (1.0, 1.0, 1.0),
    xras: _3Floats = (1.0, 0.0, 0.0),
    yras: _3Floats = (0.0, 1.0, 0.0),
    zras: _3Floats = (0.0, 0.0, 1.0),
    cras: _3Floats = (0.0, 0.0, 0.0),
)

Bases: VolumeInfo

The geometry of the source volume.

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.

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileOrContentLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given content is of the type that this parser can handle.

Parameters:

Name Type Description Default
content ContentLike

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.

{}

Returns:

Type Description
float

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

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,
) -> float

Determine if the given text is of the type that this parser can handle.

Parameters:

Name Type Description Default
text str

The text to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given lines are of the type that this parser can handle.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Score how likely a line is to be the first line of an LTA file.

The first line of an LTA file, once comments are stripped, is its type: type = <int>.

Parameters:

Name Type Description Default
line str

The first line that is not blank or a comment.

required
error bool | type[Exception]

If not False, raise an error if the line is not the first line of an LTA file.

False

Returns:

Type Description
float

Confidence that the line opens an LTA file, in [0, 1].

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

Build an object from a file (path, file-like object or iterable of lines).

This is the generic front door to the from_* family: it looks at what it was handed and calls the right one.

A str is always a path, whether or not the file exists, so a missing file raises FileNotFoundError whichever way its path was spelled. Text held in memory is read with from_text or from_content.

Parameters:

Name Type Description Default
other FileOrContentLike

Input file, or its content.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

Raises:

Type Description
ParserExistsError

If other is a path to a file that does not exist. It is a FileNotFoundError.

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

Build an object from an unqualified structured source.

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

Build an object from a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file-like object.

The default implementation reads the whole stream and hands its content to from_content (hence to from_bytes for binary streams). Parsers that only need part of the stream (e.g., a header) should override this method; from_bytes then falls back to it.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file content (bytes, str, or iterable of lines).

Parameters:

Name Type Description Default
content ContentLike

The content to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a text representation of a file.

Parameters:

Name Type Description Default
text str

The text to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build a volume-geometry block from an iterable over lines of an LTA file.

Returns None, without consuming any line, if the next line is not this block's header.

Parameters:

Name Type Description Default
lines Iterable[str]

Iterable content of an LTA file, positioned at the start of the block.

required

Returns:

Type Description
obj or None

The parsed volume-geometry block, or None.

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

Build an object from a single line of text.

Parameters:

Name Type Description Default
line str

The line to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

Convert the object to a string in LTA format, ending with a newline.

Returns:

Type Description
str

The string representation of the object in LTA format.

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

Convert the volume-geometry block to an iterable over lines of an LTA file, header included.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

from_ classmethod
from_(other: FileOrContentLike) -> Self

Build an object from a file, or from its content.

Deprecated

Use load for a file, a file object or bytes, and from_text or from_lines for content held in memory. Unlike load, from_ reads a string that names no existing file as LTA content.

Parameters:

Name Type Description Default
other str | PathLike | IO | bytes | Iterable[str]

Input file, or its content.

required

Returns:

Type Description
obj

The parsed object.

DstVolumeInfo
DstVolumeInfo(
    valid: LtaValidity = VOLUME_INFO_INVALID,
    filename: str = "",
    volume: _3Ints = (0, 0, 0),
    voxelsize: _3Floats = (1.0, 1.0, 1.0),
    xras: _3Floats = (1.0, 0.0, 0.0),
    yras: _3Floats = (0.0, 1.0, 0.0),
    zras: _3Floats = (0.0, 0.0, 1.0),
    cras: _3Floats = (0.0, 0.0, 0.0),
)

Bases: VolumeInfo

The geometry of the destination volume.

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.

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileOrContentLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given content is of the type that this parser can handle.

Parameters:

Name Type Description Default
content ContentLike

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.

{}

Returns:

Type Description
float

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

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,
) -> float

Determine if the given text is of the type that this parser can handle.

Parameters:

Name Type Description Default
text str

The text to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given lines are of the type that this parser can handle.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Score how likely a line is to be the first line of an LTA file.

The first line of an LTA file, once comments are stripped, is its type: type = <int>.

Parameters:

Name Type Description Default
line str

The first line that is not blank or a comment.

required
error bool | type[Exception]

If not False, raise an error if the line is not the first line of an LTA file.

False

Returns:

Type Description
float

Confidence that the line opens an LTA file, in [0, 1].

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

Build an object from a file (path, file-like object or iterable of lines).

This is the generic front door to the from_* family: it looks at what it was handed and calls the right one.

A str is always a path, whether or not the file exists, so a missing file raises FileNotFoundError whichever way its path was spelled. Text held in memory is read with from_text or from_content.

Parameters:

Name Type Description Default
other FileOrContentLike

Input file, or its content.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

Raises:

Type Description
ParserExistsError

If other is a path to a file that does not exist. It is a FileNotFoundError.

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

Build an object from an unqualified structured source.

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

Build an object from a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file-like object.

The default implementation reads the whole stream and hands its content to from_content (hence to from_bytes for binary streams). Parsers that only need part of the stream (e.g., a header) should override this method; from_bytes then falls back to it.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file content (bytes, str, or iterable of lines).

Parameters:

Name Type Description Default
content ContentLike

The content to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a text representation of a file.

Parameters:

Name Type Description Default
text str

The text to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build a volume-geometry block from an iterable over lines of an LTA file.

Returns None, without consuming any line, if the next line is not this block's header.

Parameters:

Name Type Description Default
lines Iterable[str]

Iterable content of an LTA file, positioned at the start of the block.

required

Returns:

Type Description
obj or None

The parsed volume-geometry block, or None.

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

Build an object from a single line of text.

Parameters:

Name Type Description Default
line str

The line to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

Convert the object to a string in LTA format, ending with a newline.

Returns:

Type Description
str

The string representation of the object in LTA format.

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

Convert the volume-geometry block to an iterable over lines of an LTA file, header included.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

from_ classmethod
from_(other: FileOrContentLike) -> Self

Build an object from a file, or from its content.

Deprecated

Use load for a file, a file object or bytes, and from_text or from_lines for content held in memory. Unlike load, from_ reads a string that names no existing file as LTA content.

Parameters:

Name Type Description Default
other str | PathLike | IO | bytes | Iterable[str]

Input file, or its content.

required

Returns:

Type Description
obj

The parsed object.

Methods:

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileOrContentLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file is of the type that this parser can handle.

Parameters:

Name Type Description Default
file FileLike

The file to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given content is of the type that this parser can handle.

Parameters:

Name Type Description Default
content ContentLike

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.

{}

Returns:

Type Description
float

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

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,
) -> float

Determine if the given text is of the type that this parser can handle.

Parameters:

Name Type Description Default
text str

The text to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given lines are of the type that this parser can handle.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Score how likely a line is to be the first line of an LTA file.

The first line of an LTA file, once comments are stripped, is its type: type = <int>.

Parameters:

Name Type Description Default
line str

The first line that is not blank or a comment.

required
error bool | type[Exception]

If not False, raise an error if the line is not the first line of an LTA file.

False

Returns:

Type Description
float

Confidence that the line opens an LTA file, in [0, 1].

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

Build an object from a file (path, file-like object or iterable of lines).

This is the generic front door to the from_* family: it looks at what it was handed and calls the right one.

A str is always a path, whether or not the file exists, so a missing file raises FileNotFoundError whichever way its path was spelled. Text held in memory is read with from_text or from_content.

Parameters:

Name Type Description Default
other FileOrContentLike

Input file, or its content.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

Raises:

Type Description
ParserExistsError

If other is a path to a file that does not exist. It is a FileNotFoundError.

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

Build an object from an unqualified structured source.

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

Build an object from a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file-like object.

The default implementation reads the whole stream and hands its content to from_content (hence to from_bytes for binary streams). Parsers that only need part of the stream (e.g., a header) should override this method; from_bytes then falls back to it.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a file content (bytes, str, or iterable of lines).

Parameters:

Name Type Description Default
content ContentLike

The content to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from a text representation of a file.

Parameters:

Name Type Description Default
text str

The text to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Build an object from an iterable over lines of an LTA file.

Parameters:

Name Type Description Default
lines Iterable[str]

Iterable content of an LTA file.

required

Returns:

Type Description
obj

The parsed object.

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

Build an object from a single line of text.

Parameters:

Name Type Description Default
line str

The line to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a file (path or file-like object).

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

Convert the object to a string in LTA format, ending with a newline.

Returns:

Type Description
str

The string representation of the object in LTA format.

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

Convert the object to an iterable over lines of an LTA file.

Additional keyword arguments are passed to the underlying field formatter.

Returns:

Type Description
Iterator[str]

An iterable over lines of an LTA file representing the object.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

from_ classmethod
from_(other: FileOrContentLike) -> Self

Build an object from a file, or from its content.

Deprecated

Use load for a file, a file object or bytes, and from_text or from_lines for content held in memory. Unlike load, from_ reads a string that names no existing file as LTA content.

Parameters:

Name Type Description Default
other str | PathLike | IO | bytes | Iterable[str]

Input file, or its content.

required

Returns:

Type Description
obj

The parsed object.

LtaCoordinateSystem

LtaCoordinateSystem(
    axes: _Axes[_3SpatialAxes] = (
        SpaceAxis(),
        SpaceAxis(),
        SpaceAxis(),
    ),
)

Bases: SpatialCoordinateSystem3D

Base class for coordinate systems specific to LTA files.

Concrete subclasses

LtaVoxelSystem Voxel space (unitless) of a volume. Coordinate (0,0,0) is the center of the first (corner) voxel. Axes correspond to the F-ordered dimensions of the volume, where the first axis is the fastest changing in memory. LtaScaledSystem Scaled voxel space (in mm) of a volume. Coordinate (0,0,0) is the center of the first (corner) voxel. Axes correspond to the F-ordered dimensions of the volume, where the first axis is the fastest changing in memory. LtaPhysicalSystem Physical space of a volume (source or destination). Coordinate (0,0,0) is the center of volume. Axes correspond to the F-ordered dimensions of the volume, where the first axis is the fastest changing in memory.

Attributes

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

The name of the coordinate system.

order class-attribute instance-attribute
order: Literal['C', 'F'] | None = None

The memory order of the array the coordinates index: "C" (the last axis changes fastest), "F" (the first axis does), or None when it is not specified. Only an ArrayCoordinateSystem indexes an array, so any other system refuses an order; the field is declared here so that every class can be called with it, and pass it on to the C- or F-ordered class it selects.

ndim property
ndim: int | None

The number of axes, or None when the system is open.

A closed system has exactly len(axes) axes. An open system, whose axes hold ..., has an unknown number of axes, and its ndim is None. This is AxisSequence.ndim of its axes.

Example

>>> CoordinateSystem(axes=[Axis(), Axis()]).ndim
2
>>> CoordinateSystem(axes=[Axis(), ...]).ndim is None
True
>>> CoordinateSystem().ndim is None
True

Methods:

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: Self, *args, **kwargs) -> Self

Create an instance of the class from an instance of a similar class.

Only attributes of the other instance that match keyword-like fields of this class will be used. An attribute that is None is unset, and leaves the default of this class in place.

Additional positional and/or keyword arguments can be provided, and will take precedence over the attributes in the instance.

Unless the other instance is already an instance of this class, an attribute naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: an instance that sets it to anything other than None or the value of this class is refused with a ValueError. A generic Axis whose orientation is right-to-left, for example, cannot be read as a LeftToRightAxis.

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

Create an instance of the class from any object that can be interpreted as a dictionary, or an instance of a similar class, or an arguments to be passed to the constructor.

A similar class is this class or one of its parents within the data model, or another member of a polymorphic family this class belongs to: calling a polymorphic class such as Axis builds the subclass its arguments select, so a "generic" axis is usually an instance of a sibling (a RightToLeftAxis, a TimeAxis) rather than of a parent. Any other object, including an instance of a parent that is not a data model (such as a plain object), is passed to the constructor.

Unlike from_dict, a dictionary with a key that matches no field of this class is refused with a TypeError naming the keys, so that a misspelt key is not silently dropped.

expand
expand(ndim: int) -> Self

The closed system of ndim axes that this system describes.

The axes are expanded by AxisSequence.expand: in an open system, ... is replaced with as many unknown Axis() as needed to reach ndim axes. The class is called again with the closed axes, and the other fields, the name included, are kept: the result is of this class, or of the subclass that the closed axes select from it (an ArrayCoordinateSystem closed to two axes is an ArrayCoordinateSystem2D). Each unknown Axis() is first read as the type of axis the class declares, so a SpatialCoordinateSystem closed to three axes has three spatial axes, and is a SpatialCoordinateSystem3D. Use it once the number of axes is known, for instance from the shape of the data.

Example

>>> CoordinateSystem(axes=[Axis(name="x"), ...]).expand(4)
CoordinateSystem(axes=[Axis(name='x'), Axis(), Axis(), Axis()])
>>> CoordinateSystem().expand(2)
CoordinateSystem2D(axes=(Axis(), Axis()))

Parameters:

Name Type Description Default
ndim int

The number of axes.

required

Returns:

Type Description
CoordinateSystem

A closed system of ndim axes, of this class or of one of its subclasses. A closed system is returned as itself.

Raises:

Type Description
ValueError

If ndim is less than the number of explicit axes of an open system, or differs from the number of axes of a closed one.

TypeError

If ndim is not an integer.

restrict
restrict(refs: Iterable[int | str]) -> CoordinateSystem

The system of the axes at some positions of this system.

The axes are restricted by AxisSequence.restrict: a reference is a position in the space or a name, and a position of an open system that falls among the axes that ... stands for gives an unknown Axis(). The axes are listed in the order of refs. The result describes a different space, so the class and the name of this system are not carried over: it is the closed system that CoordinateSystem(axes=...) builds from the restricted axes, which is a CoordinateSystem2D, an RASCoordinateSystem, ... when the axes select one.

Example

>>> x, y, z = Axis(name="x"), Axis(name="y"), Axis(name="z")
>>> CoordinateSystem(axes=[x, y, z]).restrict(["z", 0])
CoordinateSystem2D(axes=(Axis(name='z'), Axis(name='x')))
>>> CoordinateSystem(axes=[x, ...]).restrict([0])
CoordinateSystem(axes=[Axis(name='x')])

Parameters:

Name Type Description Default
refs iterable of int or str

The positions or names of the axes to keep.

required

Returns:

Type Description
CoordinateSystem

A closed system of len(refs) axes.

Raises:

Type Description
(ValueError, IndexError, TypeError)
embed
embed(
    positions: Iterable[int], ndim: int | None = None
) -> CoordinateSystem

The system of a larger space in which this system's axes sit.

This is the inverse of restrict. The axes are embedded by AxisSequence.embed: axis j of this system sits at positions[j] of the result, and every other position holds an unknown Axis(). The result describes a different space, so the class and the name of this system are not carried over: it is the system that CoordinateSystem(axes=...) builds from the embedded axes -- a plain, open CoordinateSystem when ndim is not given, and the closed system the axes select when it is.

Example

>>> x = Axis(name="x")
>>> CoordinateSystem(axes=[x]).embed([1])
CoordinateSystem(axes=[Axis(), Axis(name='x'), Ellipsis])
>>> CoordinateSystem(axes=[x]).embed([1], ndim=4)
CoordinateSystem(axes=[Axis(), Axis(name='x'), Axis(), Axis()])

Parameters:

Name Type Description Default
positions iterable of int

The non-negative position of each axis in the larger space.

required
ndim int

The number of axes of the larger space. When it is not given, the number is unknown, and the result ends with ... after the last embedded axis.

None

Returns:

Type Description
CoordinateSystem

A system that is closed when ndim is given, and open otherwise.

Raises:

Type Description
(ValueError, TypeError)
compatible_with
compatible_with(other: CoordinateSystem | None) -> bool

Whether self and other could describe the same space.

Two systems are compatible when their axes are AxisSequence.compatible_with each other: some choice of the axes that each ... stands for makes them match axis by axis, each pair being Axis.compatible_with. Only the axes are compared, not the names of the systems. None is read as a system about which nothing is known, which is compatible with every system.

For two closed systems, this asks for the same number of axes, pairwise compatible. Unlike ==, an unknown Axis() matches any axis. The relation is symmetric, but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> CoordinateSystem(axes=[x, ...]).compatible_with(
...     CoordinateSystem(axes=[x, Axis(), t])
... )
True
>>> CoordinateSystem(axes=[..., t]).compatible_with(
...     CoordinateSystem(axes=[x])
... )
False

Parameters:

Name Type Description Default
other CoordinateSystem or None

The system to compare with.

required

Returns:

Type Description
bool

Whether the two systems could describe the same space.

Raises:

Type Description
TypeError

If other is neither a CoordinateSystem nor None.

LtaPhysicalSystem magic

LtaPhysicalSystem(
    name: str | None = "physical",
    axes: _3SpatialAxes = _make_axes(
        ("x", "y", "z"), unit=_MM
    ),
    struct: VolumeInfo | None = None,
)

Bases: LtaCoordinateSystem, FVoxelCoordinateSystem

Physical space of a volume (source or destination).

This is the scaled voxel space, with an additional shift such that the origin is at the center of the volume rather than the corner.

Attributes

order class-attribute instance-attribute
order: Literal['C', 'F'] | None = None

The memory order of the array the coordinates index: "C" (the last axis changes fastest), "F" (the first axis does), or None when it is not specified. Only an ArrayCoordinateSystem indexes an array, so any other system refuses an order; the field is declared here so that every class can be called with it, and pass it on to the C- or F-ordered class it selects.

ndim property
ndim: int | None

The number of axes, or None when the system is open.

A closed system has exactly len(axes) axes. An open system, whose axes hold ..., has an unknown number of axes, and its ndim is None. This is AxisSequence.ndim of its axes.

Example

>>> CoordinateSystem(axes=[Axis(), Axis()]).ndim
2
>>> CoordinateSystem(axes=[Axis(), ...]).ndim is None
True
>>> CoordinateSystem().ndim is None
True

Methods:

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: Self, *args, **kwargs) -> Self

Create an instance of the class from an instance of a similar class.

Only attributes of the other instance that match keyword-like fields of this class will be used. An attribute that is None is unset, and leaves the default of this class in place.

Additional positional and/or keyword arguments can be provided, and will take precedence over the attributes in the instance.

Unless the other instance is already an instance of this class, an attribute naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: an instance that sets it to anything other than None or the value of this class is refused with a ValueError. A generic Axis whose orientation is right-to-left, for example, cannot be read as a LeftToRightAxis.

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

Create an instance of the class from any object that can be interpreted as a dictionary, or an instance of a similar class, or an arguments to be passed to the constructor.

A similar class is this class or one of its parents within the data model, or another member of a polymorphic family this class belongs to: calling a polymorphic class such as Axis builds the subclass its arguments select, so a "generic" axis is usually an instance of a sibling (a RightToLeftAxis, a TimeAxis) rather than of a parent. Any other object, including an instance of a parent that is not a data model (such as a plain object), is passed to the constructor.

Unlike from_dict, a dictionary with a key that matches no field of this class is refused with a TypeError naming the keys, so that a misspelt key is not silently dropped.

expand
expand(ndim: int) -> Self

The closed system of ndim axes that this system describes.

The axes are expanded by AxisSequence.expand: in an open system, ... is replaced with as many unknown Axis() as needed to reach ndim axes. The class is called again with the closed axes, and the other fields, the name included, are kept: the result is of this class, or of the subclass that the closed axes select from it (an ArrayCoordinateSystem closed to two axes is an ArrayCoordinateSystem2D). Each unknown Axis() is first read as the type of axis the class declares, so a SpatialCoordinateSystem closed to three axes has three spatial axes, and is a SpatialCoordinateSystem3D. Use it once the number of axes is known, for instance from the shape of the data.

Example

>>> CoordinateSystem(axes=[Axis(name="x"), ...]).expand(4)
CoordinateSystem(axes=[Axis(name='x'), Axis(), Axis(), Axis()])
>>> CoordinateSystem().expand(2)
CoordinateSystem2D(axes=(Axis(), Axis()))

Parameters:

Name Type Description Default
ndim int

The number of axes.

required

Returns:

Type Description
CoordinateSystem

A closed system of ndim axes, of this class or of one of its subclasses. A closed system is returned as itself.

Raises:

Type Description
ValueError

If ndim is less than the number of explicit axes of an open system, or differs from the number of axes of a closed one.

TypeError

If ndim is not an integer.

restrict
restrict(refs: Iterable[int | str]) -> CoordinateSystem

The system of the axes at some positions of this system.

The axes are restricted by AxisSequence.restrict: a reference is a position in the space or a name, and a position of an open system that falls among the axes that ... stands for gives an unknown Axis(). The axes are listed in the order of refs. The result describes a different space, so the class and the name of this system are not carried over: it is the closed system that CoordinateSystem(axes=...) builds from the restricted axes, which is a CoordinateSystem2D, an RASCoordinateSystem, ... when the axes select one.

Example

>>> x, y, z = Axis(name="x"), Axis(name="y"), Axis(name="z")
>>> CoordinateSystem(axes=[x, y, z]).restrict(["z", 0])
CoordinateSystem2D(axes=(Axis(name='z'), Axis(name='x')))
>>> CoordinateSystem(axes=[x, ...]).restrict([0])
CoordinateSystem(axes=[Axis(name='x')])

Parameters:

Name Type Description Default
refs iterable of int or str

The positions or names of the axes to keep.

required

Returns:

Type Description
CoordinateSystem

A closed system of len(refs) axes.

Raises:

Type Description
(ValueError, IndexError, TypeError)
embed
embed(
    positions: Iterable[int], ndim: int | None = None
) -> CoordinateSystem

The system of a larger space in which this system's axes sit.

This is the inverse of restrict. The axes are embedded by AxisSequence.embed: axis j of this system sits at positions[j] of the result, and every other position holds an unknown Axis(). The result describes a different space, so the class and the name of this system are not carried over: it is the system that CoordinateSystem(axes=...) builds from the embedded axes -- a plain, open CoordinateSystem when ndim is not given, and the closed system the axes select when it is.

Example

>>> x = Axis(name="x")
>>> CoordinateSystem(axes=[x]).embed([1])
CoordinateSystem(axes=[Axis(), Axis(name='x'), Ellipsis])
>>> CoordinateSystem(axes=[x]).embed([1], ndim=4)
CoordinateSystem(axes=[Axis(), Axis(name='x'), Axis(), Axis()])

Parameters:

Name Type Description Default
positions iterable of int

The non-negative position of each axis in the larger space.

required
ndim int

The number of axes of the larger space. When it is not given, the number is unknown, and the result ends with ... after the last embedded axis.

None

Returns:

Type Description
CoordinateSystem

A system that is closed when ndim is given, and open otherwise.

Raises:

Type Description
(ValueError, TypeError)
compatible_with
compatible_with(other: CoordinateSystem | None) -> bool

Whether self and other could describe the same space.

Two systems are compatible when their axes are AxisSequence.compatible_with each other: some choice of the axes that each ... stands for makes them match axis by axis, each pair being Axis.compatible_with. Only the axes are compared, not the names of the systems. None is read as a system about which nothing is known, which is compatible with every system.

For two closed systems, this asks for the same number of axes, pairwise compatible. Unlike ==, an unknown Axis() matches any axis. The relation is symmetric, but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> CoordinateSystem(axes=[x, ...]).compatible_with(
...     CoordinateSystem(axes=[x, Axis(), t])
... )
True
>>> CoordinateSystem(axes=[..., t]).compatible_with(
...     CoordinateSystem(axes=[x])
... )
False

Parameters:

Name Type Description Default
other CoordinateSystem or None

The system to compare with.

required

Returns:

Type Description
bool

Whether the two systems could describe the same space.

Raises:

Type Description
TypeError

If other is neither a CoordinateSystem nor None.

from_struct classmethod
from_struct(
    struct: VolumeInfo,
    names: tuple[str, str, str] = ("x", "y", "z"),
) -> Self

Build the physical system of the volume described by struct.

LtaScaledSystem magic

LtaScaledSystem(
    name: str | None = "scaled",
    axes: _3SpatialAxes = _make_axes(
        ("x", "y", "z"), unit=_MM
    ),
    struct: VolumeInfo | None = None,
)

Bases: LtaCoordinateSystem, FVoxelCoordinateSystem

Voxel space (scaled) of a volume (source or destination).

Attributes

order class-attribute instance-attribute
order: Literal['C', 'F'] | None = None

The memory order of the array the coordinates index: "C" (the last axis changes fastest), "F" (the first axis does), or None when it is not specified. Only an ArrayCoordinateSystem indexes an array, so any other system refuses an order; the field is declared here so that every class can be called with it, and pass it on to the C- or F-ordered class it selects.

ndim property
ndim: int | None

The number of axes, or None when the system is open.

A closed system has exactly len(axes) axes. An open system, whose axes hold ..., has an unknown number of axes, and its ndim is None. This is AxisSequence.ndim of its axes.

Example

>>> CoordinateSystem(axes=[Axis(), Axis()]).ndim
2
>>> CoordinateSystem(axes=[Axis(), ...]).ndim is None
True
>>> CoordinateSystem().ndim is None
True

Methods:

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: Self, *args, **kwargs) -> Self

Create an instance of the class from an instance of a similar class.

Only attributes of the other instance that match keyword-like fields of this class will be used. An attribute that is None is unset, and leaves the default of this class in place.

Additional positional and/or keyword arguments can be provided, and will take precedence over the attributes in the instance.

Unless the other instance is already an instance of this class, an attribute naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: an instance that sets it to anything other than None or the value of this class is refused with a ValueError. A generic Axis whose orientation is right-to-left, for example, cannot be read as a LeftToRightAxis.

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

Create an instance of the class from any object that can be interpreted as a dictionary, or an instance of a similar class, or an arguments to be passed to the constructor.

A similar class is this class or one of its parents within the data model, or another member of a polymorphic family this class belongs to: calling a polymorphic class such as Axis builds the subclass its arguments select, so a "generic" axis is usually an instance of a sibling (a RightToLeftAxis, a TimeAxis) rather than of a parent. Any other object, including an instance of a parent that is not a data model (such as a plain object), is passed to the constructor.

Unlike from_dict, a dictionary with a key that matches no field of this class is refused with a TypeError naming the keys, so that a misspelt key is not silently dropped.

expand
expand(ndim: int) -> Self

The closed system of ndim axes that this system describes.

The axes are expanded by AxisSequence.expand: in an open system, ... is replaced with as many unknown Axis() as needed to reach ndim axes. The class is called again with the closed axes, and the other fields, the name included, are kept: the result is of this class, or of the subclass that the closed axes select from it (an ArrayCoordinateSystem closed to two axes is an ArrayCoordinateSystem2D). Each unknown Axis() is first read as the type of axis the class declares, so a SpatialCoordinateSystem closed to three axes has three spatial axes, and is a SpatialCoordinateSystem3D. Use it once the number of axes is known, for instance from the shape of the data.

Example

>>> CoordinateSystem(axes=[Axis(name="x"), ...]).expand(4)
CoordinateSystem(axes=[Axis(name='x'), Axis(), Axis(), Axis()])
>>> CoordinateSystem().expand(2)
CoordinateSystem2D(axes=(Axis(), Axis()))

Parameters:

Name Type Description Default
ndim int

The number of axes.

required

Returns:

Type Description
CoordinateSystem

A closed system of ndim axes, of this class or of one of its subclasses. A closed system is returned as itself.

Raises:

Type Description
ValueError

If ndim is less than the number of explicit axes of an open system, or differs from the number of axes of a closed one.

TypeError

If ndim is not an integer.

restrict
restrict(refs: Iterable[int | str]) -> CoordinateSystem

The system of the axes at some positions of this system.

The axes are restricted by AxisSequence.restrict: a reference is a position in the space or a name, and a position of an open system that falls among the axes that ... stands for gives an unknown Axis(). The axes are listed in the order of refs. The result describes a different space, so the class and the name of this system are not carried over: it is the closed system that CoordinateSystem(axes=...) builds from the restricted axes, which is a CoordinateSystem2D, an RASCoordinateSystem, ... when the axes select one.

Example

>>> x, y, z = Axis(name="x"), Axis(name="y"), Axis(name="z")
>>> CoordinateSystem(axes=[x, y, z]).restrict(["z", 0])
CoordinateSystem2D(axes=(Axis(name='z'), Axis(name='x')))
>>> CoordinateSystem(axes=[x, ...]).restrict([0])
CoordinateSystem(axes=[Axis(name='x')])

Parameters:

Name Type Description Default
refs iterable of int or str

The positions or names of the axes to keep.

required

Returns:

Type Description
CoordinateSystem

A closed system of len(refs) axes.

Raises:

Type Description
(ValueError, IndexError, TypeError)
embed
embed(
    positions: Iterable[int], ndim: int | None = None
) -> CoordinateSystem

The system of a larger space in which this system's axes sit.

This is the inverse of restrict. The axes are embedded by AxisSequence.embed: axis j of this system sits at positions[j] of the result, and every other position holds an unknown Axis(). The result describes a different space, so the class and the name of this system are not carried over: it is the system that CoordinateSystem(axes=...) builds from the embedded axes -- a plain, open CoordinateSystem when ndim is not given, and the closed system the axes select when it is.

Example

>>> x = Axis(name="x")
>>> CoordinateSystem(axes=[x]).embed([1])
CoordinateSystem(axes=[Axis(), Axis(name='x'), Ellipsis])
>>> CoordinateSystem(axes=[x]).embed([1], ndim=4)
CoordinateSystem(axes=[Axis(), Axis(name='x'), Axis(), Axis()])

Parameters:

Name Type Description Default
positions iterable of int

The non-negative position of each axis in the larger space.

required
ndim int

The number of axes of the larger space. When it is not given, the number is unknown, and the result ends with ... after the last embedded axis.

None

Returns:

Type Description
CoordinateSystem

A system that is closed when ndim is given, and open otherwise.

Raises:

Type Description
(ValueError, TypeError)
compatible_with
compatible_with(other: CoordinateSystem | None) -> bool

Whether self and other could describe the same space.

Two systems are compatible when their axes are AxisSequence.compatible_with each other: some choice of the axes that each ... stands for makes them match axis by axis, each pair being Axis.compatible_with. Only the axes are compared, not the names of the systems. None is read as a system about which nothing is known, which is compatible with every system.

For two closed systems, this asks for the same number of axes, pairwise compatible. Unlike ==, an unknown Axis() matches any axis. The relation is symmetric, but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> CoordinateSystem(axes=[x, ...]).compatible_with(
...     CoordinateSystem(axes=[x, Axis(), t])
... )
True
>>> CoordinateSystem(axes=[..., t]).compatible_with(
...     CoordinateSystem(axes=[x])
... )
False

Parameters:

Name Type Description Default
other CoordinateSystem or None

The system to compare with.

required

Returns:

Type Description
bool

Whether the two systems could describe the same space.

Raises:

Type Description
TypeError

If other is neither a CoordinateSystem nor None.

from_struct classmethod
from_struct(
    struct: VolumeInfo,
    names: tuple[str, str, str] = ("x", "y", "z"),
) -> Self

Build the scaled voxel system of the volume described by struct.

LtaVoxelSystem magic

LtaVoxelSystem(
    name: str | None = "voxel",
    axes: _3SpatialAxes = _make_axes(
        ("i", "j", "k"), unit=_INDEX
    ),
    struct: VolumeInfo | None = None,
)

Bases: LtaCoordinateSystem, FVoxelCoordinateSystem

Voxel space (unscaled) of a volume (source or destination).

Attributes

order class-attribute instance-attribute
order: Literal['C', 'F'] | None = None

The memory order of the array the coordinates index: "C" (the last axis changes fastest), "F" (the first axis does), or None when it is not specified. Only an ArrayCoordinateSystem indexes an array, so any other system refuses an order; the field is declared here so that every class can be called with it, and pass it on to the C- or F-ordered class it selects.

ndim property
ndim: int | None

The number of axes, or None when the system is open.

A closed system has exactly len(axes) axes. An open system, whose axes hold ..., has an unknown number of axes, and its ndim is None. This is AxisSequence.ndim of its axes.

Example

>>> CoordinateSystem(axes=[Axis(), Axis()]).ndim
2
>>> CoordinateSystem(axes=[Axis(), ...]).ndim is None
True
>>> CoordinateSystem().ndim is None
True

Methods:

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: Self, *args, **kwargs) -> Self

Create an instance of the class from an instance of a similar class.

Only attributes of the other instance that match keyword-like fields of this class will be used. An attribute that is None is unset, and leaves the default of this class in place.

Additional positional and/or keyword arguments can be provided, and will take precedence over the attributes in the instance.

Unless the other instance is already an instance of this class, an attribute naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: an instance that sets it to anything other than None or the value of this class is refused with a ValueError. A generic Axis whose orientation is right-to-left, for example, cannot be read as a LeftToRightAxis.

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

Create an instance of the class from any object that can be interpreted as a dictionary, or an instance of a similar class, or an arguments to be passed to the constructor.

A similar class is this class or one of its parents within the data model, or another member of a polymorphic family this class belongs to: calling a polymorphic class such as Axis builds the subclass its arguments select, so a "generic" axis is usually an instance of a sibling (a RightToLeftAxis, a TimeAxis) rather than of a parent. Any other object, including an instance of a parent that is not a data model (such as a plain object), is passed to the constructor.

Unlike from_dict, a dictionary with a key that matches no field of this class is refused with a TypeError naming the keys, so that a misspelt key is not silently dropped.

expand
expand(ndim: int) -> Self

The closed system of ndim axes that this system describes.

The axes are expanded by AxisSequence.expand: in an open system, ... is replaced with as many unknown Axis() as needed to reach ndim axes. The class is called again with the closed axes, and the other fields, the name included, are kept: the result is of this class, or of the subclass that the closed axes select from it (an ArrayCoordinateSystem closed to two axes is an ArrayCoordinateSystem2D). Each unknown Axis() is first read as the type of axis the class declares, so a SpatialCoordinateSystem closed to three axes has three spatial axes, and is a SpatialCoordinateSystem3D. Use it once the number of axes is known, for instance from the shape of the data.

Example

>>> CoordinateSystem(axes=[Axis(name="x"), ...]).expand(4)
CoordinateSystem(axes=[Axis(name='x'), Axis(), Axis(), Axis()])
>>> CoordinateSystem().expand(2)
CoordinateSystem2D(axes=(Axis(), Axis()))

Parameters:

Name Type Description Default
ndim int

The number of axes.

required

Returns:

Type Description
CoordinateSystem

A closed system of ndim axes, of this class or of one of its subclasses. A closed system is returned as itself.

Raises:

Type Description
ValueError

If ndim is less than the number of explicit axes of an open system, or differs from the number of axes of a closed one.

TypeError

If ndim is not an integer.

restrict
restrict(refs: Iterable[int | str]) -> CoordinateSystem

The system of the axes at some positions of this system.

The axes are restricted by AxisSequence.restrict: a reference is a position in the space or a name, and a position of an open system that falls among the axes that ... stands for gives an unknown Axis(). The axes are listed in the order of refs. The result describes a different space, so the class and the name of this system are not carried over: it is the closed system that CoordinateSystem(axes=...) builds from the restricted axes, which is a CoordinateSystem2D, an RASCoordinateSystem, ... when the axes select one.

Example

>>> x, y, z = Axis(name="x"), Axis(name="y"), Axis(name="z")
>>> CoordinateSystem(axes=[x, y, z]).restrict(["z", 0])
CoordinateSystem2D(axes=(Axis(name='z'), Axis(name='x')))
>>> CoordinateSystem(axes=[x, ...]).restrict([0])
CoordinateSystem(axes=[Axis(name='x')])

Parameters:

Name Type Description Default
refs iterable of int or str

The positions or names of the axes to keep.

required

Returns:

Type Description
CoordinateSystem

A closed system of len(refs) axes.

Raises:

Type Description
(ValueError, IndexError, TypeError)
embed
embed(
    positions: Iterable[int], ndim: int | None = None
) -> CoordinateSystem

The system of a larger space in which this system's axes sit.

This is the inverse of restrict. The axes are embedded by AxisSequence.embed: axis j of this system sits at positions[j] of the result, and every other position holds an unknown Axis(). The result describes a different space, so the class and the name of this system are not carried over: it is the system that CoordinateSystem(axes=...) builds from the embedded axes -- a plain, open CoordinateSystem when ndim is not given, and the closed system the axes select when it is.

Example

>>> x = Axis(name="x")
>>> CoordinateSystem(axes=[x]).embed([1])
CoordinateSystem(axes=[Axis(), Axis(name='x'), Ellipsis])
>>> CoordinateSystem(axes=[x]).embed([1], ndim=4)
CoordinateSystem(axes=[Axis(), Axis(name='x'), Axis(), Axis()])

Parameters:

Name Type Description Default
positions iterable of int

The non-negative position of each axis in the larger space.

required
ndim int

The number of axes of the larger space. When it is not given, the number is unknown, and the result ends with ... after the last embedded axis.

None

Returns:

Type Description
CoordinateSystem

A system that is closed when ndim is given, and open otherwise.

Raises:

Type Description
(ValueError, TypeError)
compatible_with
compatible_with(other: CoordinateSystem | None) -> bool

Whether self and other could describe the same space.

Two systems are compatible when their axes are AxisSequence.compatible_with each other: some choice of the axes that each ... stands for makes them match axis by axis, each pair being Axis.compatible_with. Only the axes are compared, not the names of the systems. None is read as a system about which nothing is known, which is compatible with every system.

For two closed systems, this asks for the same number of axes, pairwise compatible. Unlike ==, an unknown Axis() matches any axis. The relation is symmetric, but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> CoordinateSystem(axes=[x, ...]).compatible_with(
...     CoordinateSystem(axes=[x, Axis(), t])
... )
True
>>> CoordinateSystem(axes=[..., t]).compatible_with(
...     CoordinateSystem(axes=[x])
... )
False

Parameters:

Name Type Description Default
other CoordinateSystem or None

The system to compare with.

required

Returns:

Type Description
bool

Whether the two systems could describe the same space.

Raises:

Type Description
TypeError

If other is neither a CoordinateSystem nor None.

from_struct classmethod
from_struct(
    struct: VolumeInfo,
    names: tuple[str, str, str] = ("i", "j", "k"),
) -> Self

Build the voxel system of the volume described by struct.

LtaTransformation magic

LtaTransformation(
    struct: LtaStruct = Factory(LtaStruct, repr=False),
)

Bases: LtaFormat, TextFileParserWriter, Affine, WritableFileBasedTransformation

A transformation than can be encoded as a Linear Transform Array (LTA).

LTA files are the default format used for linear transformations in Freesurfer, and can represent different types of Affine transformations.

This is the registered format for .lta files: io.load, io.transformations.load and from_other read them, and io.save writes them. The views below it (LtaTransformationVoxToVox, LtaTransformationPhysToPhys, LtaTransformationRASToRAS) read the same files, but are not registered: they would claim every .lta file exactly as well as this class does.

What is written

A transformation read from a file, and left untouched, is written back as the struct it was read from. One whose matrix, input or output has been set -- including one converted from another affine -- is written with the LTA type its coordinate systems call for:

input and output LTA type
both RASmm LINEAR_RAS_TO_RAS
both RSAmm LINEAR_RSA_TO_RSA
both LtaVoxelSystem LINEAR_VOX_TO_VOX
both LtaPhysicalSystem LINEAR_PHYSVOX_TO_PHYSVOX

Any other pair of systems has no LTA encoding, and writing it raises UnrepresentableTransformationError.

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

input property writable

The transformation's input coordinate system.

Derived from the struct's type and its source volume geometry, unless it has been set explicitly.

output property writable

The transformation's output coordinate system.

Derived from the struct's type and its destination volume geometry, unless it has been set explicitly.

data property writable
data: ndarray

The transformation's affine matrix.

Read from the struct's affine block, unless it has been set explicitly.

Methods:

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

On a dispatcher, identify which registered format would read file. On a concrete format, score how confident it is that file, in any supported form, is its own.

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

On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

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

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

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

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

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

Create an instance of the class from a dictionary-like object.

Only keys in the dictionary that match keyword-like fields of this class, or the keywords its constructor takes without storing them (its InitVars, such as the matrix= of an Affine), will be used. Other keys are ignored, but see from_other, which refuses them.

Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.

A key naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: a dictionary that sets it to anything other than None or the value of this class is refused with a ValueError.

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

Create an instance from an instance of a similar class.

See DataModelBase.from_instance. The map of an Affine is copied through its matrix view, not its stored data, which a lazy wrapper derives and a tangent (log=True) stores as its logarithm. A tangent is copied into a tangent through its data.

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

Create an instance from a file, or from anything the data model reads.

A path (str or os.PathLike), an open file, bytes or a structured source (SourceSpec) is read with load: on a dispatcher such as FileBasedImage, the best-matching registered format reads it, and on a concrete format, that format does. Any other value is handed to the data model's own from_other, which reads a mapping field by field, copies an instance of a similar class, and passes anything else to the constructor.

Parameters:

Name Type Description Default
other Any

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

required
*args

Constructor arguments. A file is read with keyword options only.

()
**kwargs

Format-specific options when reading a file, and field values otherwise.

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

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

Compute the transformation, downcasting it to the cheapest compatible kind.

A concrete transformation holds a parameter, so it simplifies to the simplest compatible kind, whose compatibility can be detected with (almost) no overhead. For example, a transformation whose parameter is set to None is treated as an identity.

Parameters:

Name Type Description Default
mode [list of] name or type

Ignored on a leaf. mode gates which kinds compose, and a leaf has nothing to compose; its downcast is gated only by simplify (simplification is decoupled from the compose mode).

True
simplify simplify policy

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

"analytic"
factor bool

Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default.

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

Simplify this transformation under a per-kind policy.

Convenience sugar for compute: t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy).

By default simplify() does no computation at all: compute=False maps to mode=False, which composes nothing (no matrices multiplied, no fields sampled, no lazy inverse materialized). It only downcasts each leaf under policy (analytic by default). Pass an explicit compute=<mode> to also compose that kind.

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the result now rather than return it lazily.

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

to
to(
    cls: Type[Self] | None = None,
    *,
    lossy: bool = False,
    error: Type[Exception] | Exception | bool = True,
    **kwargs,
) -> Self

Convert this transformation to a different type.

Conversion can be

  • between type: linear.to(Affine) ; or
  • within type: displacement.to(coeff=True) ; or
  • both: coords.to(DisplacementField, coeff=True) .

Parameters:

Name Type Description Default
cls type

The type to convert to. If None, keep the current type.

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

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

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

{}

Returns:

Type Description
Transformation

The converted transformation.

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

Score how likely a line is to be the first line of an LTA file. See LtaStruct.sniff_line.

from_ classmethod
from_(other: Any) -> Self

Build the transformation from a struct, a file, or file content.

Deprecated

Use from_struct for a struct, load for a file, a file object or bytes, and from_text or from_lines for content held in memory.

from_struct classmethod
from_struct(struct: LtaStruct, **kwargs) -> Self

Build the transformation from an already-parsed LtaStruct.

Keyword arguments are passed to the constructor, and override what the struct says (input, output, matrix).

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

Build the transformation from an iterable over lines of an LTA file.

Keyword arguments are passed to the constructor, and override what the file says (input, output, matrix).

to_struct
to_struct() -> LtaStruct

The LtaStruct that encodes this transformation.

A transformation whose matrix, input and output are all derived from its struct is encoded by that struct, unchanged. Otherwise a struct is built from them: its type is the one the coordinate systems call for (see the class documentation), its matrix is matrix, and its volume geometries are those the systems were built from (voxel and physical types) or those of the current struct (RAS and RSA types). The other header fields are kept from the current struct.

Raises:

Type Description
UnrepresentableTransformationError

If LTA cannot encode the coordinate systems or the matrix.

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

Write the transformation to a file (path or file-like object) in LTA format.

The struct is built before the file is opened, so a transformation that LTA cannot encode is refused without creating or truncating the file.

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

The lines of the LTA file that encodes this transformation.

to_text
to_text(**kwargs) -> str

The content of the LTA file that encodes this transformation.

LtaTransformationPhysToPhys magic

LtaTransformationPhysToPhys(
    struct: LtaStruct = Factory(
        partial(
            LtaStruct,
            type=LINEAR_PHYSVOX_TO_PHYSVOX,
            src=SrcVolumeInfo(),
            dst=DstVolumeInfo(),
        ),
        repr=False,
    ),
)

Bases: LtaTransformation

A Linear Transform Array (LTA) file interpreted as a physical-to-physical affine transformation.

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

input property writable

The physical system of the struct's source volume, unless it has been set explicitly.

output property writable

The physical system of the struct's destination volume, unless it has been set explicitly.

data property writable
data: ndarray

The physical-to-physical affine matrix derived from the struct, unless it has been set explicitly.

Methods:

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

On a dispatcher, identify which registered format would read file. On a concrete format, score how confident it is that file, in any supported form, is its own.

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

On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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_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,
) -> float

Score how likely a line is to be the first line of an LTA file. See LtaStruct.sniff_line.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build the transformation from an iterable over lines of an LTA file.

Keyword arguments are passed to the constructor, and override what the file says (input, output, matrix).

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

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

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the transformation to a file (path or file-like object) in LTA format.

The struct is built before the file is opened, so a transformation that LTA cannot encode is refused without creating or truncating the file.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

The content of the LTA file that encodes this transformation.

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

The lines of the LTA file that encodes this transformation.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

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

Create an instance of the class from a dictionary-like object.

Only keys in the dictionary that match keyword-like fields of this class, or the keywords its constructor takes without storing them (its InitVars, such as the matrix= of an Affine), will be used. Other keys are ignored, but see from_other, which refuses them.

Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.

A key naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: a dictionary that sets it to anything other than None or the value of this class is refused with a ValueError.

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

Create an instance from an instance of a similar class.

See DataModelBase.from_instance. The map of an Affine is copied through its matrix view, not its stored data, which a lazy wrapper derives and a tangent (log=True) stores as its logarithm. A tangent is copied into a tangent through its data.

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

Create an instance from a file, or from anything the data model reads.

A path (str or os.PathLike), an open file, bytes or a structured source (SourceSpec) is read with load: on a dispatcher such as FileBasedImage, the best-matching registered format reads it, and on a concrete format, that format does. Any other value is handed to the data model's own from_other, which reads a mapping field by field, copies an instance of a similar class, and passes anything else to the constructor.

Parameters:

Name Type Description Default
other Any

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

required
*args

Constructor arguments. A file is read with keyword options only.

()
**kwargs

Format-specific options when reading a file, and field values otherwise.

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

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

Compute the transformation, downcasting it to the cheapest compatible kind.

A concrete transformation holds a parameter, so it simplifies to the simplest compatible kind, whose compatibility can be detected with (almost) no overhead. For example, a transformation whose parameter is set to None is treated as an identity.

Parameters:

Name Type Description Default
mode [list of] name or type

Ignored on a leaf. mode gates which kinds compose, and a leaf has nothing to compose; its downcast is gated only by simplify (simplification is decoupled from the compose mode).

True
simplify simplify policy

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

"analytic"
factor bool

Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default.

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

Simplify this transformation under a per-kind policy.

Convenience sugar for compute: t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy).

By default simplify() does no computation at all: compute=False maps to mode=False, which composes nothing (no matrices multiplied, no fields sampled, no lazy inverse materialized). It only downcasts each leaf under policy (analytic by default). Pass an explicit compute=<mode> to also compose that kind.

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the result now rather than return it lazily.

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

to
to(
    cls: Type[Self] | None = None,
    *,
    lossy: bool = False,
    error: Type[Exception] | Exception | bool = True,
    **kwargs,
) -> Self

Convert this transformation to a different type.

Conversion can be

  • between type: linear.to(Affine) ; or
  • within type: displacement.to(coeff=True) ; or
  • both: coords.to(DisplacementField, coeff=True) .

Parameters:

Name Type Description Default
cls type

The type to convert to. If None, keep the current type.

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

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

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

{}

Returns:

Type Description
Transformation

The converted transformation.

from_ classmethod
from_(other: Any) -> Self

Build the transformation from a struct, a file, or file content.

Deprecated

Use from_struct for a struct, load for a file, a file object or bytes, and from_text or from_lines for content held in memory.

from_struct classmethod
from_struct(struct: LtaStruct, **kwargs) -> Self

Build the transformation from an already-parsed LtaStruct.

Keyword arguments are passed to the constructor, and override what the struct says (input, output, matrix).

to_struct
to_struct() -> LtaStruct

The LtaStruct that encodes this transformation.

A transformation whose matrix, input and output are all derived from its struct is encoded by that struct, unchanged. Otherwise a struct is built from them: its type is the one the coordinate systems call for (see the class documentation), its matrix is matrix, and its volume geometries are those the systems were built from (voxel and physical types) or those of the current struct (RAS and RSA types). The other header fields are kept from the current struct.

Raises:

Type Description
UnrepresentableTransformationError

If LTA cannot encode the coordinate systems or the matrix.

LtaTransformationRASToRAS magic

LtaTransformationRASToRAS(
    struct: LtaStruct = Factory(
        partial(LtaStruct, type=LINEAR_RAS_TO_RAS),
        repr=False,
    ),
)

Bases: LtaTransformation

A Linear Transform Array (LTA) file interpreted as a RAS-to-RAS affine transformation.

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

input property writable

The RAS coordinate system, unless it has been set explicitly.

output property writable

The RAS coordinate system, unless it has been set explicitly.

data property writable
data: ndarray

The RAS-to-RAS affine matrix derived from the struct, unless it has been set explicitly.

Methods:

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

On a dispatcher, identify which registered format would read file. On a concrete format, score how confident it is that file, in any supported form, is its own.

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

On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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_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,
) -> float

Score how likely a line is to be the first line of an LTA file. See LtaStruct.sniff_line.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build the transformation from an iterable over lines of an LTA file.

Keyword arguments are passed to the constructor, and override what the file says (input, output, matrix).

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

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

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the transformation to a file (path or file-like object) in LTA format.

The struct is built before the file is opened, so a transformation that LTA cannot encode is refused without creating or truncating the file.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

The content of the LTA file that encodes this transformation.

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

The lines of the LTA file that encodes this transformation.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

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

Create an instance of the class from a dictionary-like object.

Only keys in the dictionary that match keyword-like fields of this class, or the keywords its constructor takes without storing them (its InitVars, such as the matrix= of an Affine), will be used. Other keys are ignored, but see from_other, which refuses them.

Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.

A key naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: a dictionary that sets it to anything other than None or the value of this class is refused with a ValueError.

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

Create an instance from an instance of a similar class.

See DataModelBase.from_instance. The map of an Affine is copied through its matrix view, not its stored data, which a lazy wrapper derives and a tangent (log=True) stores as its logarithm. A tangent is copied into a tangent through its data.

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

Create an instance from a file, or from anything the data model reads.

A path (str or os.PathLike), an open file, bytes or a structured source (SourceSpec) is read with load: on a dispatcher such as FileBasedImage, the best-matching registered format reads it, and on a concrete format, that format does. Any other value is handed to the data model's own from_other, which reads a mapping field by field, copies an instance of a similar class, and passes anything else to the constructor.

Parameters:

Name Type Description Default
other Any

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

required
*args

Constructor arguments. A file is read with keyword options only.

()
**kwargs

Format-specific options when reading a file, and field values otherwise.

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

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

Compute the transformation, downcasting it to the cheapest compatible kind.

A concrete transformation holds a parameter, so it simplifies to the simplest compatible kind, whose compatibility can be detected with (almost) no overhead. For example, a transformation whose parameter is set to None is treated as an identity.

Parameters:

Name Type Description Default
mode [list of] name or type

Ignored on a leaf. mode gates which kinds compose, and a leaf has nothing to compose; its downcast is gated only by simplify (simplification is decoupled from the compose mode).

True
simplify simplify policy

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

"analytic"
factor bool

Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default.

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

Simplify this transformation under a per-kind policy.

Convenience sugar for compute: t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy).

By default simplify() does no computation at all: compute=False maps to mode=False, which composes nothing (no matrices multiplied, no fields sampled, no lazy inverse materialized). It only downcasts each leaf under policy (analytic by default). Pass an explicit compute=<mode> to also compose that kind.

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the result now rather than return it lazily.

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

to
to(
    cls: Type[Self] | None = None,
    *,
    lossy: bool = False,
    error: Type[Exception] | Exception | bool = True,
    **kwargs,
) -> Self

Convert this transformation to a different type.

Conversion can be

  • between type: linear.to(Affine) ; or
  • within type: displacement.to(coeff=True) ; or
  • both: coords.to(DisplacementField, coeff=True) .

Parameters:

Name Type Description Default
cls type

The type to convert to. If None, keep the current type.

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

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

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

{}

Returns:

Type Description
Transformation

The converted transformation.

from_ classmethod
from_(other: Any) -> Self

Build the transformation from a struct, a file, or file content.

Deprecated

Use from_struct for a struct, load for a file, a file object or bytes, and from_text or from_lines for content held in memory.

from_struct classmethod
from_struct(struct: LtaStruct, **kwargs) -> Self

Build the transformation from an already-parsed LtaStruct.

Keyword arguments are passed to the constructor, and override what the struct says (input, output, matrix).

to_struct
to_struct() -> LtaStruct

The LtaStruct that encodes this transformation.

A transformation whose matrix, input and output are all derived from its struct is encoded by that struct, unchanged. Otherwise a struct is built from them: its type is the one the coordinate systems call for (see the class documentation), its matrix is matrix, and its volume geometries are those the systems were built from (voxel and physical types) or those of the current struct (RAS and RSA types). The other header fields are kept from the current struct.

Raises:

Type Description
UnrepresentableTransformationError

If LTA cannot encode the coordinate systems or the matrix.

LtaTransformationVoxToVox magic

LtaTransformationVoxToVox(
    struct: LtaStruct = Factory(
        partial(
            LtaStruct,
            type=LINEAR_VOX_TO_VOX,
            src=SrcVolumeInfo(),
            dst=DstVolumeInfo(),
        ),
        repr=False,
    ),
)

Bases: LtaTransformation

A Linear Transform Array (LTA) file interpreted as a voxel-to-voxel affine transformation.

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

input property writable

The voxel system of the struct's source volume, unless it has been set explicitly.

output property writable

The voxel system of the struct's destination volume, unless it has been set explicitly.

data property writable
data: ndarray

The voxel-to-voxel affine matrix derived from the struct, unless it has been set explicitly.

Methods:

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

On a dispatcher, identify which registered format would read file. On a concrete format, score how confident it is that file, in any supported form, is its own.

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

On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Determine if the given filename is of the type that this parser can handle.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to sniff.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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

Determine if the given file-like object is of the type that this parser can handle.

A text stream decodes as it is read, so content that is not text -- a binary file that shares an extension with a text format -- fails there. That is a "no", not a failure to sniff.

Parameters:

Name Type Description Default
file IO

A file object open for reading.

required
error bool | type[Exception]

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

False
**kwargs

Parser-specific options.

{}

Returns:

Type Description
float

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

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_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,
) -> float

Score how likely a line is to be the first line of an LTA file. See LtaStruct.sniff_line.

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

Build an object from bytes, by decoding them to text and delegating to from_text.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

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

{}

Returns:

Type Description
obj

The parsed object.

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

Build the transformation from an iterable over lines of an LTA file.

Keyword arguments are passed to the constructor, and override what the file says (input, output, matrix).

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

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

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

Write the object to a file (path or file-like object).

This is the generic front door to the to_* family. It is named save rather than to because to already means something else on the data models these parsers are mixed into: Transformation.to converts an object to another type. A writer's to was shadowed by it on every writable transformation.

Parameters:

Name Type Description Default
file FileLike

The file to write to.

required
**kwargs

Parser-specific options.

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

Write the transformation to a file (path or file-like object) in LTA format.

The struct is built before the file is opened, so a transformation that LTA cannot encode is refused without creating or truncating the file.

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

Write the object to a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to write to.

required
**kwargs

Parser-specific options.

{}
to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file-like object open for writing.

Parameters:

Name Type Description Default
file IO

A file object open for writing.

required
**kwargs

Parser-specific options.

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

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

Parameters:

Name Type Description Default
**kwargs

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

{}

Returns:

Type Description
bytes

The byte representation of the object.

to_text
to_text(**kwargs) -> str

The content of the LTA file that encodes this transformation.

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

The lines of the LTA file that encodes this transformation.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

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

Create an instance of the class from a dictionary-like object.

Only keys in the dictionary that match keyword-like fields of this class, or the keywords its constructor takes without storing them (its InitVars, such as the matrix= of an Affine), will be used. Other keys are ignored, but see from_other, which refuses them.

Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.

A key naming a field that this class fixes (a field that cannot be passed to its constructor) is checked instead of used: a dictionary that sets it to anything other than None or the value of this class is refused with a ValueError.

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

Create an instance from an instance of a similar class.

See DataModelBase.from_instance. The map of an Affine is copied through its matrix view, not its stored data, which a lazy wrapper derives and a tangent (log=True) stores as its logarithm. A tangent is copied into a tangent through its data.

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

Create an instance from a file, or from anything the data model reads.

A path (str or os.PathLike), an open file, bytes or a structured source (SourceSpec) is read with load: on a dispatcher such as FileBasedImage, the best-matching registered format reads it, and on a concrete format, that format does. Any other value is handed to the data model's own from_other, which reads a mapping field by field, copies an instance of a similar class, and passes anything else to the constructor.

Parameters:

Name Type Description Default
other Any

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

required
*args

Constructor arguments. A file is read with keyword options only.

()
**kwargs

Format-specific options when reading a file, and field values otherwise.

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

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

Compute the transformation, downcasting it to the cheapest compatible kind.

A concrete transformation holds a parameter, so it simplifies to the simplest compatible kind, whose compatibility can be detected with (almost) no overhead. For example, a transformation whose parameter is set to None is treated as an identity.

Parameters:

Name Type Description Default
mode [list of] name or type

Ignored on a leaf. mode gates which kinds compose, and a leaf has nothing to compose; its downcast is gated only by simplify (simplification is decoupled from the compose mode).

True
simplify simplify policy

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

"analytic"
factor bool

Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default.

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

Simplify this transformation under a per-kind policy.

Convenience sugar for compute: t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy).

By default simplify() does no computation at all: compute=False maps to mode=False, which composes nothing (no matrices multiplied, no fields sampled, no lazy inverse materialized). It only downcasts each leaf under policy (analytic by default). Pass an explicit compute=<mode> to also compose that kind.

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the result now rather than return it lazily.

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

to
to(
    cls: Type[Self] | None = None,
    *,
    lossy: bool = False,
    error: Type[Exception] | Exception | bool = True,
    **kwargs,
) -> Self

Convert this transformation to a different type.

Conversion can be

  • between type: linear.to(Affine) ; or
  • within type: displacement.to(coeff=True) ; or
  • both: coords.to(DisplacementField, coeff=True) .

Parameters:

Name Type Description Default
cls type

The type to convert to. If None, keep the current type.

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

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

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

{}

Returns:

Type Description
Transformation

The converted transformation.

from_ classmethod
from_(other: Any) -> Self

Build the transformation from a struct, a file, or file content.

Deprecated

Use from_struct for a struct, load for a file, a file object or bytes, and from_text or from_lines for content held in memory.

from_struct classmethod
from_struct(struct: LtaStruct, **kwargs) -> Self

Build the transformation from an already-parsed LtaStruct.

Keyword arguments are passed to the constructor, and override what the struct says (input, output, matrix).

to_struct
to_struct() -> LtaStruct

The LtaStruct that encodes this transformation.

A transformation whose matrix, input and output are all derived from its struct is encoded by that struct, unchanged. Otherwise a struct is built from them: its type is the one the coordinate systems call for (see the class documentation), its matrix is matrix, and its volume geometries are those the systems were built from (voxel and physical types) or those of the current struct (RAS and RSA types). The other header fields are kept from the current struct.

Raises:

Type Description
UnrepresentableTransformationError

If LTA cannot encode the coordinate systems or the matrix.