Skip to content

brainhops.io.transformations.base

The format-independent base of every file-based transformation.

Classes

FileBasedTransformation

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

Bases: _FileBasedModelMixin, TransformationFormat, Transformation, FileBasedObject

A transformation that is stored in a file.

This is the dispatcher for transformation formats: concrete readers inherit from it and opt in with @register_format, which is what makes brainhops.io.transformations.load work.

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

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

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

On a dispatcher, identify which registered format would read the content (text or bytes). On a concrete format, score how confident it is that the content is its own.

sniff_bytes classmethod
sniff_bytes(
    content: BinaryContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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

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

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

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

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

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

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

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

On a dispatcher, pick the best-matching registered format and build an instance of it from other. On a concrete format, build an instance of this class from other, in any supported form.

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

Load a structured source specification through this dispatcher.

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

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

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Build an object from a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

from_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Create an instance from an instance of a similar class.

The data model copies the fields both classes share, by name. A field that a file format declares for its own use -- such as the nibabel image and header of the NIfTI and MGH formats -- is only copied from an object of that same format: from any other object, a field of the same name holds something else (a NIfTI image is no MGH image), so this class's default is kept instead. Saving a NIfTI image to MGH, or the converse, therefore converts the data model only, and the format-specific state is rebuilt by the writer.

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

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

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

Parameters:

Name Type Description Default
other Any

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

required
*args

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

()
**kwargs

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

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

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

Compute the transformation, if it is not already fully defined.

Parameters:

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

Which kinds of transformations to materialize. True (the default) admits every kind. On a leaf transformation, if a mode is given and this leaf is not admitted by it, the leaf is returned unchanged. Keys are transformation types, names or symbols (e.g., "affine", "Aff", "rigid", "SO(3)").

True
simplify SimplifyLike
"analytic"
What

Whether to simplify the transformation prior if possible, and how hard to try to simplify them. * "analytic" (the default) looks at the type structure only; * "numeric" looks at the numeric values of the transformation; * False/"none"/None disables simplification.

required
factor bool

Whether to rewrite the transformation into its axis-group normal form, splitting it into independent factors that each act on a group of axes that transform together. Off by default, so a plain compute() result is unchanged. Nothing is ever composed across axis groups; mode still decides whether the restricted pieces inside a group compose.

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

Simplify this transformation under a per-kind policy.

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

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

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the inverse of this transformation.

Some classes of transformations return a lazy inverse by default, which is only evaluated when the compute() method is called. This allows for efficient composition of transformations. Or the inverse can be computed immediately by setting compute=True.

The inverse can also be obtained using the __invert__ operator: T.inverse() is equivalent to ~T.

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

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

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

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

Return the principal square root of this transformation.

The square root S of T is the transformation with S @ S == T, the half-transformation. The principal one, whose linear part has its eigenvalues in the open right half-plane, is unique, and it is of the same kind as T: the square root of a rotation is a rotation, of a translation a translation, of a scaling a scaling, of an affine an affine. The square root of a permutation is a Linear transformation.

The square root is lazy: an Sqrt wrapper is returned, and computed when it is applied, computed or converted. A transformation that needs no wrapper (an identity) is returned as is. A Sequence is reduced first (see Sequence.sqrt).

Parameters:

Name Type Description Default
compute bool

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

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself, or, when the result is computed, if its linear part has an eigenvalue on the closed negative real axis (a reflection, a rotation by a half turn, a singular matrix), so that it has no real principal square root.

NotImplementedError

If brainhops does not compute the square root of this kind of transformation. A displacement field has one only when it is a stationary velocity field (log=True), whose square root halves its velocity.

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

Convert this transformation to a different type.

Conversion can be

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

Parameters:

Name Type Description Default
cls type

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

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

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

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

{}

Returns:

Type Description
Transformation

The converted transformation.

WritableFileBasedTransformation

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

Bases: FileBasedTransformation, WritableFileBasedObject

A transformation that is stored in a file and can be written.

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

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

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

On a dispatcher, identify which registered format would read the content (text or bytes). On a concrete format, score how confident it is that the content is its own.

sniff_bytes classmethod
sniff_bytes(
    content: BinaryContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

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

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

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

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

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

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

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

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

On a dispatcher, pick the best-matching registered format and build an instance of it from other. On a concrete format, build an instance of this class from other, in any supported form.

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

Load a structured source specification through this dispatcher.

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

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

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Build an object from a filename.

Parameters:

Name Type Description Default
filename FilenameLike

The filename to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

from_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

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

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

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

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

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

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

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

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

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

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

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

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

Return a binary version of the file.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
bytes

A binary version of the file.

to_text
to_text(**kwargs) -> str

Return a text version of the file.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A text version of the file.

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

Return a text version of the file as an iterable of lines.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
Iterator[str]

An iterable of lines representing the object.

to_line
to_line(**kwargs) -> str

Return a line representing the object.

Parameters:

Name Type Description Default
**kwargs

Parser-specific options.

{}

Returns:

Type Description
str

A line representing the object.

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

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

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

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

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

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

Create an instance from an instance of a similar class.

The data model copies the fields both classes share, by name. A field that a file format declares for its own use -- such as the nibabel image and header of the NIfTI and MGH formats -- is only copied from an object of that same format: from any other object, a field of the same name holds something else (a NIfTI image is no MGH image), so this class's default is kept instead. Saving a NIfTI image to MGH, or the converse, therefore converts the data model only, and the format-specific state is rebuilt by the writer.

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

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

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

Parameters:

Name Type Description Default
other Any

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

required
*args

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

()
**kwargs

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

{}

Returns:

Type Description
obj

The object that was built.

Raises:

Type Description
TypeError

If positional arguments come with a file to read.

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

Compute the transformation, if it is not already fully defined.

Parameters:

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

Which kinds of transformations to materialize. True (the default) admits every kind. On a leaf transformation, if a mode is given and this leaf is not admitted by it, the leaf is returned unchanged. Keys are transformation types, names or symbols (e.g., "affine", "Aff", "rigid", "SO(3)").

True
simplify SimplifyLike
"analytic"
What

Whether to simplify the transformation prior if possible, and how hard to try to simplify them. * "analytic" (the default) looks at the type structure only; * "numeric" looks at the numeric values of the transformation; * False/"none"/None disables simplification.

required
factor bool

Whether to rewrite the transformation into its axis-group normal form, splitting it into independent factors that each act on a group of axes that transform together. Off by default, so a plain compute() result is unchanged. Nothing is ever composed across axis groups; mode still decides whether the restricted pieces inside a group compose.

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

Simplify this transformation under a per-kind policy.

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

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

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the inverse of this transformation.

Some classes of transformations return a lazy inverse by default, which is only evaluated when the compute() method is called. This allows for efficient composition of transformations. Or the inverse can be computed immediately by setting compute=True.

The inverse can also be obtained using the __invert__ operator: T.inverse() is equivalent to ~T.

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

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

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

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

Return the principal square root of this transformation.

The square root S of T is the transformation with S @ S == T, the half-transformation. The principal one, whose linear part has its eigenvalues in the open right half-plane, is unique, and it is of the same kind as T: the square root of a rotation is a rotation, of a translation a translation, of a scaling a scaling, of an affine an affine. The square root of a permutation is a Linear transformation.

The square root is lazy: an Sqrt wrapper is returned, and computed when it is applied, computed or converted. A transformation that needs no wrapper (an identity) is returned as is. A Sequence is reduced first (see Sequence.sqrt).

Parameters:

Name Type Description Default
compute bool

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

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself, or, when the result is computed, if its linear part has an eigenvalue on the closed negative real axis (a reflection, a rotation by a half turn, a singular matrix), so that it has no real principal square root.

NotImplementedError

If brainhops does not compute the square root of this kind of transformation. A displacement field has one only when it is a stationary velocity field (log=True), whose square root halves its velocity.

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

Convert this transformation to a different type.

Conversion can be

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

Parameters:

Name Type Description Default
cls type

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

None
lossy bool

Whether to allow lossy conversions.

False
error bool or Exception

Whether to raise an error if the conversion fails:

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

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

{}

Returns:

Type Description
Transformation

The converted transformation.

AffineTransformationFormat

Bases: TransformationFormat

A format that stores an affine transformation.

TransformationFormat

A stored transformation format.

Functions:

load

load(
    filelike: FileOrContentLike,
    brute: bool = False,
    **kwargs,
) -> FileBasedTransformation

Read a transformation from a file, whatever its format.

Parameters:

Name Type Description Default
filelike FileOrContentLike

Input file, or its content.

required
brute bool

If no format recognizes the input, try every registered reader.

False
**kwargs

Format-specific options.

{}

Returns:

Name Type Description
transformation FileBasedTransformation

The transformation that was read.

sniff

sniff(filelike: FileOrContentLike, **kwargs) -> type | None

Identify which transformation format would read this file.

The file is not parsed, only inspected, so this is a prediction of what load would reach for rather than a guarantee.

Parameters:

Name Type Description Default
filelike FileOrContentLike

Input file, or its content.

required
**kwargs

Format-specific options.

{}

Returns:

Name Type Description
format type | None

The best match among registered transformation formats, or None if no single one stands out.