brainhops.io.transformations.fsl.flirt
FLIRT linear transformation matrices (.mat).
A FLIRT .mat file holds a (4, 4) affine that maps moving-image
scaled-mm coordinates to reference-image scaled-mm coordinates.
Classes
FlirtMatrixParser
magic
FlirtMatrixParser(
flirt_matrix: ArrayLike | None = None,
moving: _ImageLike | None = None,
reference: _ImageLike | None = None,
)
Bases: Magic, TextFileParser
Reader for a FLIRT .mat file.
A FLIRT .mat file is a plain text (4, 4) affine matrix, one row
per line, whitespace separated. The matrix alone carries no image
geometry, so the reference and moving images must be supplied for the
matrix to be turned into a world-space transformation.
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.
flirt_matrix
class-attribute
instance-attribute
The raw (4, 4) FLIRT matrix, as read from the file.
An array-like of shape (4, 4) mapping moving-image scaled-mm
coordinates to reference-image scaled-mm coordinates. It is converted
to a NumPy array and used to build the world-space affine.
moving
class-attribute
instance-attribute
The moving (source) image, a nibabel image or header, or a brainhops image.
reference
class-attribute
instance-attribute
The reference image, a nibabel image or header, or a brainhops image.
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 |
sniff_file
classmethod
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 |
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Determine if the given filename is of the type that this parser can handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to sniff. |
required |
error
|
bool | type[Exception]
|
If not False, raise an error if the filename cannot be sniffed. |
False
|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the filename is of this type, in |
sniff_fileobj
classmethod
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 |
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 |
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 |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the content is of this type, in |
sniff_text
classmethod
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 |
sniff_line
classmethod
Determine if the given line is of the type that this parser can handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The line 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 line is of this type, in |
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 |
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Build an object from an unqualified structured source.
from_file
classmethod
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
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 |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The parsed object. |
from_text
classmethod
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. |
FlirtTransform
magic
FlirtTransform(flirt_matrix: ArrayLike | None = None, moving: _ImageLike | None = None, reference: _ImageLike | None = None, _matrix: Deactivated[None], *, _input: CoordinateSystem = RASmm(), _output: CoordinateSystem = RASmm())
Bases: FslAffineFormat, FlirtMatrixParser, Affine, FileBasedTransformation
A linear transformation stored in a FLIRT .mat file.
A FLIRT matrix maps moving-image scaled-mm coordinates to
reference-image scaled-mm coordinates. This reader exposes it as an
affine whose matrix maps reference-image world (RAS) coordinates to
moving-image world (RAS) coordinates, which is the direction the data
model uses to resample a moving image onto a reference.
The reference and moving images must be supplied, because the .mat
file carries no image geometry. They may be passed as keyword
arguments to load or from_file (reference=, moving=), or set
on the object before its matrix is read.
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
The affine matrix, of shape (No, Ni + 1), whose last column is
the translation component.
homogeneous_matrix
property
The homogeneous matrix of the affine transformation, of shape
(No + 1, Ni + 1). The last row of the homogeneous matrix is
[0, 0, ..., 1].
flirt_matrix
class-attribute
instance-attribute
The raw (4, 4) FLIRT matrix, as read from the file.
An array-like of shape (4, 4) mapping moving-image scaled-mm
coordinates to reference-image scaled-mm coordinates. It is converted
to a NumPy array and used to build the world-space affine.
moving
class-attribute
instance-attribute
The moving (source) image, a nibabel image or header, or a brainhops image.
reference
class-attribute
instance-attribute
The reference image, a nibabel image or header, or a brainhops image.
data
property
writable
The reference-RAS to moving-RAS affine, as a (3, 4) matrix.
Reading this (or the matrix view) resolves the affine from the
raw FLIRT matrix and the two image geometries. It raises when the
raw matrix is present but either image is missing, because the
affine cannot be placed in world coordinates without both.
Methods:
sniff
classmethod
sniff(
file: FileOrContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> type | None
On a dispatcher, identify which registered format would read
file. On a concrete format, score how confident it is that
file, in any supported form, is its own.
sniff_file
classmethod
On a dispatcher, identify which registered format would read the file (path or file-like object). On a concrete format, score how confident it is that the file is its own.
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Determine if the given filename is of the type that this parser can handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
FilenameLike
|
The filename to sniff. |
required |
error
|
bool | type[Exception]
|
If not False, raise an error if the filename cannot be sniffed. |
False
|
**kwargs
|
Parser-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the filename is of this type, in |
sniff_fileobj
classmethod
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 |
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 |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Confidence that the content is of this type, in |
sniff_text
classmethod
On a dispatcher, identify which registered format would read the text. On a concrete format, score how confident it is that the text is its own.
sniff_line
classmethod
On a dispatcher, identify which registered format would read the line. On a concrete format, score how confident it is that the line is its own.
load
classmethod
load(other: FileOrContentLike, **kwargs) -> Self
On a dispatcher, pick the best-matching registered format and
build an instance of it from other. On a concrete format,
build an instance of this class from other, in any supported
form.
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Load a structured source specification through this dispatcher.
from_file
classmethod
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
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 |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The parsed object. |
from_text
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the text. On a concrete format, build an instance of this class from the text.
from_line
classmethod
On a dispatcher, pick the best-matching registered format and build an instance of it from the line. On a concrete format, build an instance of this class from the line.
from_dict
classmethod
Create an instance of the class from a dictionary-like object.
Only keys in the dictionary that match keyword-like fields of
this class, or the keywords its constructor takes without
storing them (its InitVars, such as the matrix= of an
Affine), will be used. Other keys are ignored, but see
from_other,
which refuses them.
Additional positional and/or keyword arguments can be provided, and will take precedence over the values in the dictionary.
A key naming a field that this class fixes (a field that cannot
be passed to its constructor) is checked instead of used: a
dictionary that sets it to anything other than None or the
value of this class is refused with a ValueError.
from_instance
classmethod
Create an instance from an instance of a similar class.
See DataModelBase.from_instance. The map of an Affine is copied through
its matrix view, not its stored data, which a lazy wrapper
derives and a tangent (log=True) stores as its logarithm. A
tangent is copied into a tangent through its data.
from_other
classmethod
Create an instance from a file, or from anything the data model reads.
A path (str or os.PathLike), an open file, bytes or a
structured source (SourceSpec)
is read with load: on a dispatcher such as FileBasedImage,
the best-matching registered format reads it, and on a concrete
format, that format does. Any other value is handed to the data
model's own from_other, which reads a mapping field by field,
copies an instance of a similar class, and passes anything else
to the constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A file, its content, a mapping, or an instance of a similar class. |
required |
*args
|
Constructor arguments. A file is read with keyword options only. |
()
|
|
**kwargs
|
Format-specific options when reading a file, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
obj
|
The object that was built. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments come with a file to read. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Compute the transformation, downcasting it to the cheapest compatible kind.
A concrete transformation holds a parameter, so it simplifies to
the simplest compatible kind, whose compatibility can be detected
with (almost) no overhead. For example, a transformation whose
parameter is set to None is treated as an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
[list of] name or type
|
Ignored on a leaf. |
True
|
simplify
|
simplify policy
|
How hard this leaf may be looked at. The resolved
|
"analytic"
|
factor
|
bool
|
Whether to factor this leaf into its axis-group normal form. A leaf factors by wrapping itself in a one-element sequence, so a diagonal affine (say) splits into its per-axis blocks. Off by default. |
False
|
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify this transformation under a per-kind policy.
Convenience sugar for
compute: t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy).
By default simplify() does no computation at all: compute=False
maps to mode=False, which composes nothing (no matrices multiplied,
no fields sampled, no lazy inverse materialized). It only downcasts
each leaf under policy (analytic by default). Pass an explicit
compute=<mode> to also compose that kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
simplify policy
|
The simplify policy, in the grammar |
"analytic"
|
compute
|
[list of] name or type
|
The compose mode. The default, |
False
|
square
square(compute: bool = False, **kwargs) -> Transformation
Return the square of this transformation, self @ self.
The square is the sequence [self, self], which composes when it
is computed. It is defined for a transformation that maps a space
to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the result now rather than return it lazily. |
False
|
**kwargs
|
Passed to |
{}
|
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
to
to(
cls: Type[Self] | None = None,
*,
lossy: bool = False,
error: Type[Exception] | Exception | bool = True,
**kwargs,
) -> Self
Convert this transformation to a different type.
Conversion can be
- between type:
linear.to(Affine); or - within type:
displacement.to(coeff=True); or - both:
coords.to(DisplacementField, coeff=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The type to convert to. If |
None
|
lossy
|
bool
|
Whether to allow lossy conversions. |
False
|
error
|
bool or Exception
|
Whether to raise an error if the conversion fails:
|
True
|
**kwargs
|
dict
|
Attributes to override in the converted transform.
This allows transformations to be modified within their type.
For example, a |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation. |