Skip to content

brainhops.io.transformations.itk.h5

ITK binary transformations are saved in H5 format and support a variety of (chained) transformations.

They support the same transformation types as the text-based TFM format, although TFM files are rarely used to store displacement fields, which are usually stored in H5 files.

The supported displacement fields have the following encoding:

  • BSplineTransform Deforms space using a sparse regular grid of control points to represent free-form distortions.

  • Parameters: Array of multi-dimensional deformation vector displacements (x, y, z) for every single control point in the grid.

    • Total count = (Number of Grid Control Points) x Spatial Dimension.
  • FixedParameters: Information describing the spatial bounds of the grid:

    • [0-2] Grid Size (number of control points along each axis)
    • [3-5] Grid Origin (physical starting coordinates)
    • [6-8] Grid Spacing (physical distance between control points)
    • [9-17] Grid Direction Matrix (orientation of the grid, 3 x 3 row-major)
  • DisplacementFieldTransform A dense deformation map where every individual pixel/voxel in the image gets its own explicit displacement vector.

    • Parameters: Multi-dimensional displacement values for every voxel.

    • Total count = (Total Image Voxels) x Spatial Dimension.

    • FixedParameters: Empty. The transform topology matches the physical coordinate space of the primary image metadata instead.

Furthermore, the H5 format holds chained transforms (ANTs' <prefix>Composite.h5). A CompositeTransform is written as a first block of class CompositeTransform, which has no parameters, followed by the blocks of its transform queue, front to back. ITK applies that queue back to front (CompositeTransform::TransformPoint): a file [Composite, T0, T1] maps x to T0(T1(x)). A brainhops Sequence lists its transformations in the order they apply, so the reader lists the blocks of a composite in reverse file order: [T1, T0]. A file with several blocks but no CompositeTransform header is a list of separate transforms, which ITK does not compose. The reader loads one of them: the first, as SimpleITK's ReadTransform does, with a warning that the file holds several, or the one at position= (H5Transform.from_file(path, position=1)). A composite file holds a single transform, the composite, at position 0. Composites cannot be nested: ITK only writes a CompositeTransform as the first block.

Approximate specification

1. File Level Attributes

At the root directory level (/), the format embeds global provenance metadata to validate software compatibility. These are saved as standard HDF5 Attributes or standalone datasets:

  • /ITKVersion: String attribute tracking the compiling library version (e.g., "5.3.0").
  • /HDFVersion: String attribute detailing the underlying dataset library version.
  • /OSName: String attribute indicating the operating system name.
  • /OSVersion: String attribute indicating the operating system version.

2. The /TransformGroup Directory Hierarchy

All transformation records are wrapped inside a top-level group path named exactly /TransformGroup.

Every block is stored in a sub-group named after its position in the file, counting from zero, and ITK reads them back by number (so 10 comes after 9, not after 1):

  • /TransformGroup/0 -- the CompositeTransform header, if any
  • /TransformGroup/1
  • /TransformGroup/2

The blocks of a composite are applied in the reverse of this order.

3. Internal Group Structure

Every numerical sub-group (e.g., /TransformGroup/0) must contain the following specific objects:

/TransformGroup
  └── /0
       ├── TransformType             (Dataset: String attribute/value)
       ├── TransformParameters       (Dataset: 1D Floating-point array)
       └── TransformFixedParameters  (Dataset: 1D Floating-point array)
  1. TransformType

    • Data Type: String (Variable length or fixed character array).
    • Specification: Holds the exact C++ Run-Time Type Information (RTTI) name of the ITK class.
    • Example Value: "AffineTransform_double_3_3" or "BSplineTransform_double_3_3".
  2. TransformParameters

    • Data Type: 1D Array of HDF5 Floats (H5T_NATIVE_FLOAT or H5T_NATIVE_DOUBLE).
    • Specification: Stores the optimisable/variable coefficients of the transform.
    • Note on Bug-Compatibility: To maintain backward compatibility with a legacy spelling error in older ITK versions, modern ITK parsers fallback to search for TranformParameters (missing the "s" in "Trans") if TransformParameters is missing.
  3. TransformFixedParameters

    • Data Type: 1D Array of HDF5 Floats (H5T_NATIVE_FLOAT or H5T_NATIVE_DOUBLE).
    • Specification: Stores structural constants (such as centers of rotation or deformation grid bounds).
    • Note on Bug-Compatibility: The parser will fall back to look for the legacy misspelled string TranformFixedParameters if the properly spelled version cannot be indexed.

Classes

DelayedH5Array

DelayedH5Array(file: H5Like, path: str)

An HDF5 dataset that can be read even after its file was closed, by reopening the file when needed.

Attributes

shape property
shape: tuple

The shape of the dataset.

dtype property
dtype: dtype

The data type of the dataset.

chunks property
chunks: tuple

The chunk shape of the dataset, or None if it is not chunked.

ndim property
ndim: int

The number of dimensions of the dataset.

size property
size: int

The total number of elements in the dataset.

nbytes property
nbytes: int

The size of the dataset in bytes.

Methods:

open
open() -> File

Open (or reuse) the underlying HDF5 file and return it.

close
close() -> None

Close the underlying HDF5 file, if this array opened it.

__del__
__del__() -> None

Close the underlying HDF5 file, if this array opened it.

to_dataset
to_dataset(
    file: H5Like | None = None, keep_open: bool = False
) -> Dataset

Return the underlying h5py.Dataset, opening the file if needed.

to_array
to_array(**kwargs) -> ndarray

Read the whole dataset into a numpy array.

to_dask
to_dask(
    *, keep_open: bool = False, **kwargs
) -> ArrayProtocol

Wrap the dataset as a dask array that reads chunks lazily.

__getitem__
__getitem__(index: Any) -> Any

Read the indexed chunk of the dataset, opening the file if needed.

__array__
__array__(dtype: dtype = None, copy: Any = None) -> ndarray

Read the whole dataset into a numpy array.

H5Header magic

H5Header(
    HDFVersion: str | None = None,
    ITKVersion: str | None = None,
    OSName: str | None = None,
    OSVersion: str | None = None,
)

Bases: Magic

Header of a ITK H5 file.

Attributes

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

A string describing the version of the HDF5 library used. Ex: "HDF5 library version: 1.10.4"

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

A string describing the version of the ITK library used. Ex: "5.1.0"

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

A string describing the operating system name. Ex: "Linux"

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

A string describing the operating system version. Ex: "6.1.0-1007-oem"

H5TransformParser magic

H5TransformParser(
    file: File | None = None,
    header: H5Header = Factory(H5Header),
)

Bases: Magic, Hdf5Parser

Parses an ITK binary (.h5) transform file into a chain of transform blocks.

The blocks of a CompositeTransform (such as ANTs' <prefix>Composite.h5) are listed in the order they apply to points, which is the reverse of their order in the file (ITK applies the last block of a composite first).

Each block is itself a brainhops transformation, so the parsed blocks are stored straight into the transformations of the sequence that this parser is mixed into.

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

Score a path, open HDF5 file, or binary stream.

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

Score the HDF5 file found at a path.

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

Score an open, seekable binary stream.

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

Score the bytes of an HDF5 file.

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

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 [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: H5Like,
    keep_open: bool = False,
    load: bool = True,
    **kwargs,
) -> Self

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

Parameters:

Name Type Description Default
file str | PathLike | IO | File

Input file.

required
keep_open bool

If True, keep the HDF5 file open after loading. If False, close the file after loading. If load=False and keep_open=False, the file is reopened every time a lazily read dataset is accessed.

False
load bool

If True, read large datasets into memory. If False, keep them on disk.

True
from_filename classmethod
from_filename(
    filename: str | PathLike,
    keep_open: bool = False,
    load: bool = True,
    **kwargs,
) -> Self

Build an object from the HDF5 file found at a path.

from_fileobj classmethod
from_fileobj(
    file: IO,
    keep_open: bool = False,
    load: bool = True,
    **kwargs,
) -> Self

Build an object from an open, seekable binary stream.

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 a binary representation of a file.

If the class implements from_fileobj itself, the bytes are wrapped in an io.BytesIO stream and handed to from_fileobj. Otherwise, this raises ParserNotImplementedError: the default from_fileobj delegates to from_bytes, so falling back to it would recurse. A from_fileobj override that only forwards to super().from_fileobj should be decorated with _passthrough_from_fileobj; if it is not, the loop is still detected when from_bytes is re-entered for the same class, and ParserNotImplementedError is raised.

Parameters:

Name Type Description Default
content BinaryContentLike

The content to parse.

required
**kwargs

Parser-specific options.

{}

Returns:

Type Description
obj

The parsed object.

Raises:

Type Description
ParserNotImplementedError

If neither from_bytes nor from_fileobj is implemented.

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 of lines (e.g., the content of a file).

Parameters:

Name Type Description Default
lines Iterable[str]

The lines to sniff.

required
**kwargs

Parser-specific options.

{}

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.

sniff_h5 classmethod
sniff_h5(
    h5file: File, error: bool | Type[Exception] = False
) -> float

Score how confident the parser is that an open HDF5 file is an ITK transform file.

from_h5 classmethod
from_h5(
    h5file: File,
    keep_open: bool = False,
    load: bool = True,
    position: int | None = None,
    **kwargs,
) -> Self

Build an object from an HDF5 file.

Parameters:

Name Type Description Default
h5file File

Input HDF5 file.

required
load bool

If True, load the data into memory. If False, keep the data on disk.

True
keep_open bool

If True, keep the HDF5 file open after loading. If False, close the file after loading.

False
position int

Which top-level transform of the file to read: the composite, if the file starts with a CompositeTransform header, else one of its blocks. By default, the first one, with a warning if the file holds several.

None

Returns:

Type Description
obj

The parsed object.

__del__
__del__() -> None

Close the underlying HDF5 file, if one is still open.

H5Transform magic

H5Transform(
    file: File | None = None,
    header: H5Header = Factory(H5Header),
)

Bases: H5TransformParser, ItkTransform

A transformation stored in an ITK binary (.h5) file.

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.

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

Score a path, open HDF5 file, or binary stream.

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

Score the HDF5 file found at a path.

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

Score an open, seekable binary stream.

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

Score the bytes of an HDF5 file.

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: H5Like,
    keep_open: bool = False,
    load: bool = True,
    **kwargs,
) -> Self

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

Parameters:

Name Type Description Default
file str | PathLike | IO | File

Input file.

required
keep_open bool

If True, keep the HDF5 file open after loading. If False, close the file after loading. If load=False and keep_open=False, the file is reopened every time a lazily read dataset is accessed.

False
load bool

If True, read large datasets into memory. If False, keep them on disk.

True
from_filename classmethod
from_filename(
    filename: str | PathLike,
    keep_open: bool = False,
    load: bool = True,
    **kwargs,
) -> Self

Build an object from the HDF5 file found at a path.

from_fileobj classmethod
from_fileobj(
    file: IO,
    keep_open: bool = False,
    load: bool = True,
    **kwargs,
) -> Self

Build an object from an open, seekable binary stream.

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

Compute the resulting transform of the sequence of transformations.

Assuming that mode=True:

  • If all transformations in the sequence are affine-like transformations, compute() returns an affine-like transform.

  • If the first (= rightmost) transform in the sequence is a coordinate field, compute() returns a coordinate field.

  • If the first (= rightmost) transform in the sequence is an affine-like transform, and the sequence contains at least one non-affine-like transform, compute() returns a sequence of two transformations:

  • the composition of all affine-like transformations that appear before the first non-affine-like transform in the sequence, and

  • the composition of all transformations in the sequence, starting from the first non-affine-like transform in the sequence.
Parameters

mode : [list of] name or type, optional Kinds of transformations to compose. * If True (default): compose every kind in the sequence. * If False: compose nothing (simplify-only). * If a (list of) transformation type(s): compose only pairs of transformations of these kinds. simplify : simplify policy, default="analytic" Whether to simplify sub-transformations prior to composition, and how hard to try to simplify them. * "analytic" (the default) looks at the type structure only; * "numeric" looks at the numeric values of the transformation; * False/"none"/None disables simplification. factor : bool, default=False Whether to rewrite the sequence into its axis-group normal form [grid?, F_1..F_m, Pi_perm?]: a leading grid (if any), one axis-preserving subspace factor per group of axes that transform together, and a trailing reindex permutation. Off by default, so the result is byte-for-byte the plain compute() result. Nothing is ever composed across groups; mode still decides whether the restricted pieces inside a group compose. A chain that creates or drops axes is left unfactored. With mode=False nothing is computed, so factor has nothing to act on and is ignored.

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

Simplify this transformation under a per-kind policy.

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

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

Parameters:

Name Type Description Default
policy simplify policy

The simplify policy, in the grammar compute accepts.

"analytic"
compute [list of] name or type

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

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

Return the square of this transformation, self @ self.

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

Parameters:

Name Type Description Default
compute bool

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

False
**kwargs

Passed to compute when compute is true.

{}

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

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

Return the principal square root of this chain.

The chain is first simplified, which costs nothing. A chain [P, *X, P^-1], where P^-1 is the lazy inverse of P, or both are affines whose product is exactly the identity, is a change of coordinates around X, and its square root is [P, sqrt(X), P^-1]: a field stored in voxels between a world-to-voxel affine and its lazy inverse keeps that form. Any other chain is composed now, and the square root of the transformation it composes to is returned.

Raises:

Type Description
DomainError

If the chain does not map a space to itself, or if the square root of what it reduces to is not defined.

NotImplementedError

If the chain does not compose to a single transformation.

to
to(
    cls: Type[Transformation] | None = None, **kwargs
) -> Transformation

Convert this chain to a different type or encoding.

See Transformation.to. A chain has no tangent of its own -- the tangent of a composition is not the sum of the tangents -- so log= re-encodes the transformation it reduces to, and anything else is refused before it is computed:

  • a chain that simplifies to one transformation is that one;
  • a change of coordinates [P, *X, P^-1] (see sqrt) keeps its ends, and re-encodes X: the flow of a velocity commutes with the conjugation, so this is exact. A velocity read between a world-to-voxel affine and its inverse (|svf) is turned into its displacement that way;
  • a chain of affines is composed, which is cheap and exact.

Any other chain -- one with a field, between ends that do not undo each other -- raises ConversionError.

sniff_h5 classmethod
sniff_h5(
    h5file: File, error: bool | Type[Exception] = False
) -> float

Score how confident the parser is that an open HDF5 file is an ITK transform file.

from_h5 classmethod
from_h5(
    h5file: File,
    keep_open: bool = False,
    load: bool = True,
    position: int | None = None,
    **kwargs,
) -> Self

Build an object from an HDF5 file.

Parameters:

Name Type Description Default
h5file File

Input HDF5 file.

required
load bool

If True, load the data into memory. If False, keep the data on disk.

True
keep_open bool

If True, keep the HDF5 file open after loading. If False, close the file after loading.

False
position int

Which top-level transform of the file to read: the composite, if the file starts with a CompositeTransform header, else one of its blocks. By default, the first one, with a warning if the file holds several.

None

Returns:

Type Description
obj

The parsed object.

__del__
__del__() -> None

Close the underlying HDF5 file, if one is still open.