Skip to content

brainhops.io.transformations.nifti

Readers and writers for transformations stored in NIfTI files.

Each transformation holds the header of its file as NiftiMetadata, whose record is a NiftiRaw, and the array of the file as it is stored, in rawdata. The two classes of the header are defined in brainhops.io.common.nifti and exported here as well. An affine keeps its matrix in the header, and the data of a field is a lazy array of its file, which reads the voxels only when a computation needs them. A field keeps its header and its array in a NiftiImage, through which it is read and written. A field that is read and written again without changes is written as its file stored it.

Fields of RAS displacements and of RAS coordinates

The NIfTI-1 standard (nifti1.h) gives vector fields two intent codes with different meanings. DISPVECT (1006) is "specifically for displacements" and is read and written by NiftiRASDisplacementField. VECTOR (1007) is "for any other type of vector" and is read and written by NiftiRASCoordinateField.

A displacement field maps x to x + u(x), while a coordinate field maps each voxel to the position that its vector holds. Reading one kind as the other shifts every point by the world position of its voxel, so the intent code decides. DISPVECT fields are read as RAS displacements in millimetres, as ITK 5.4 and later read them. Coordinates are written under VECTOR with the intent name "Mapping", which is what SPM writes for its y_ deformations, a field of the same kind.

POINTSET (1008) would describe coordinates better, but the standard ties it to a flat list of points (dim[2] = dim[3] = dim[4] = 1), so readers, brainhops included, would misread a grid written with it.

Classes

NiftiMetadata magic

NiftiMetadata(
    name: str | None = None,
    description: str | None = None,
    history: tuple[str, ...] | None = None,
    generated_by: tuple[GeneratedBy, ...] | None = None,
    creation_time: datetime | None = None,
    sources: tuple[str, ...] | None = None,
    space: SpaceEnum | str | None = None,
    intent: IntentEnum | str | None = None,
    repetition_time: float | None = None,
    echo_time: float | None = None,
    inversion_time: float | None = None,
    flip_angle: float | None = None,
    magnetic_field_strength: float | None = None,
    manufacturer: Manufacturer | str | None = None,
    manufacturers_model_name: str | None = None,
    institution_name: str | None = None,
    acquisition_time: datetime | None = None,
    phase_encoding_direction: EncodingDirection
    | None = None,
    total_readout_time: float | None = None,
    effective_echo_spacing: float | None = None,
    slice_encoding_direction: EncodingDirection
    | None = None,
    slice_timing: tuple[float, ...] | None = None,
    multiband_acceleration_factor: int | None = None,
    bvalues: tuple[float, ...] | None = None,
    bvectors: tuple[tuple[float, float, float], ...]
    | None = None,
    display_range: tuple[float, float] | None = None,
    channels: tuple[Channel, ...] | None = None,
    data_unit: Unit | str | None = None,
    dtype: dtype | None = None,
    scale_slope: float | None = None,
    scale_intercept: float | None = None,
    objective_magnification: float | None = None,
    objective_numerical_aperture: float | None = None,
    illumination_type: IlluminationType | str | None = None,
    contrast_method: ContrastMethod | str | None = None,
    moving: str | None = None,
    fixed: str | None = None,
    input_space: SpaceEnum | str | None = None,
    output_space: SpaceEnum | str | None = None,
    raw: NoRepr[NiftiRaw | None] = None,
    *,
    extra: dict[str, Any] = Factory(),
)

Bases: MetadataReader, BinaryFileWriter, MetadataFormat

Metadata of a NIfTI file, which holds the header of the file.

The metadata of a NIfTI file is read from the header alone, so the voxels that follow the header are never read, and a file cut after its header can still be read. The header is held as a NiftiRaw record, which NiftiImage uses as the base of the header that it writes. The metadata keeps no open file.

A file is read through the record: [from_fileobj][] reads a NiftiRaw and wraps it, and writing the metadata writes the header of the consolidated record without voxels.

The fields of the vocabulary that the header stores are decoded when the metadata is built, and are listed in SUPPORTED_FIELDS. The slot of each field is given in the table of brainhops.io.common.nifti._vocabulary. The world space (space) and an intent that changes how the axes are read belong to the geometry, so a change of them is reported as approximated. NIfTI has no free-form store, so extra is not supported.

Parameters:

Name Type Description Default
name str | None

A short name for the data.

None
description str | None

A free-text description.

None
history tuple[str, ...] | None

The commands that produced the data, oldest first.

None
generated_by tuple[GeneratedBy, ...] | None

The programs that produced the data.

None
creation_time datetime | None

When the file was created.

None
sources tuple[str, ...] | None

Files the data was derived from (BIDS provenance).

None
space SpaceEnum | str | None

The label of the world space ('MNI152NLin6Asym', 'scanner', ...; a known one is a SpaceEnum); the space itself is geometry.

None
intent IntentEnum | str | None

What the values are, as a NIfTI intent name (a known one is an IntentEnum).

None
repetition_time float | None

Repetition time, in seconds.

None
echo_time float | None

Echo time, in seconds.

None
inversion_time float | None

Inversion time, in seconds.

None
flip_angle float | None

Flip angle, in degrees.

None
magnetic_field_strength float | None

Nominal field strength, in tesla.

None
manufacturer Manufacturer | str | None

Manufacturer of the equipment (a known one is a Manufacturer).

None
manufacturers_model_name str | None

Model name of the equipment.

None
institution_name str | None

Institution responsible for the equipment.

None
acquisition_time datetime | None

When the acquisition started.

None
phase_encoding_direction EncodingDirection | None

Phase-encoding direction: a unit vector. By default in voxel axes (BIDS 'j-' is accepted).

None
total_readout_time float | None

Total readout time, in seconds.

None
effective_echo_spacing float | None

Effective echo spacing, in seconds.

None
slice_encoding_direction EncodingDirection | None

Slice-encoding direction: a unit vector, by default in voxel axes (BIDS 'k' is accepted)."

None
slice_timing tuple[float, ...] | None

Acquisition time of each slice, in seconds, along the slice encoding direction.

None
multiband_acceleration_factor int | None

Multiband acceleration factor.

None
bvalues tuple[float, ...] | None

One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."

None
bvectors tuple[tuple[float, float, float], ...] | None

One unit gradient direction per index along the time axis, in world (RAS) coordinates."

None
display_range tuple[float, float] | None

Display window (min, max).

None
channels tuple[Channel, ...] | None

One description per channel. The descriptions run along the axes of type channel only. The entries of a component axis, such as a vector or a tensor axis, are described by the type, the valence, the layout and the frame of that axis, so a change of frame, which only re-expresses the values of component axes, keeps these descriptions.

None
data_unit Unit | str | None

Unit of the data values: a Unit whenever the units module parses the name ('a.u.', 'mm/s', 'HU'), and the name itself, as a string, when it does not, so that a file with an odd unit still reads. Formats write it as its symbol (Unit.symbol), which parses back to the same unit.

None
dtype dtype | None

The element type of the data as stored, in native byte order. It may differ from the type of the loaded array: a scaled integer file loads as floating-point values. An override given to save or to consolidate takes precedence over it.

None
scale_slope float | None

The slope of the intensity scaling: a value is stored * scale_slope + scale_intercept. None means no scaling.

None
scale_intercept float | None

The intercept of the intensity scaling (see scale_slope). None means no intercept.

None
objective_magnification float | None

Nominal magnification of the objective.

None
objective_numerical_aperture float | None

Numerical aperture of the objective.

None
illumination_type IlluminationType | str | None

Illumination type (a known one is an IlluminationType).

None
contrast_method ContrastMethod | str | None

Contrast method (a known one is a ContrastMethod).

None
moving str | None

The moving image of a registration (file reference).

None
fixed str | None

The fixed image of a registration (file reference).

None
input_space SpaceEnum | str | None

Label of the space a transformation maps from.

None
output_space SpaceEnum | str | None

Label of the space a transformation maps to.

None
raw NoRepr[NiftiRaw | None]

The header of the file, or None for metadata without a record.

None
extra dict[str, Any]

Free-form keys the vocabulary does not cover, copied into any free-form store a format has."

Factory()

Attributes

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

name class-attribute instance-attribute
name: Annotated[str | None, Scoped(FILE)] = None

A short name for the data.

description class-attribute instance-attribute
description: Annotated[
    str | None, Bids(Description), Scoped(FILE)
] = None

A free-text description.

history class-attribute instance-attribute
history: Annotated[tuple[str, ...] | None, Scoped(FILE)] = (
    None
)

The commands that produced the data, oldest first.

generated_by class-attribute instance-attribute
generated_by: Annotated[
    tuple[GeneratedBy, ...] | None,
    Bids(GeneratedBy),
    Scoped(FILE),
] = None

The programs that produced the data.

creation_time class-attribute instance-attribute
creation_time: Annotated[datetime | None, Scoped(FILE)] = (
    None
)

When the file was created.

sources class-attribute instance-attribute
sources: Annotated[
    tuple[str, ...] | None, Bids(Sources), Scoped(FILE)
] = None

Files the data was derived from (BIDS provenance).

space class-attribute instance-attribute
space: Annotated[
    SpaceEnum | str | None,
    Bids(SpatialReference),
    Scoped(FILE),
] = None

The label of the world space ('MNI152NLin6Asym', 'scanner', ...; a known one is a SpaceEnum); the space itself is geometry.

intent class-attribute instance-attribute
intent: Annotated[IntentEnum | str | None, Scoped(FILE)] = (
    None
)

What the values are, as a NIfTI intent name (a known one is an IntentEnum).

repetition_time class-attribute instance-attribute
repetition_time: Annotated[
    float | None, Bids(RepetitionTime), Scoped(ACQUISITION)
] = None

Repetition time, in seconds.

echo_time class-attribute instance-attribute
echo_time: Annotated[
    float | None, Bids(EchoTime), Scoped(ACQUISITION)
] = None

Echo time, in seconds.

inversion_time class-attribute instance-attribute
inversion_time: Annotated[
    float | None, Bids(InversionTime), Scoped(ACQUISITION)
] = None

Inversion time, in seconds.

flip_angle class-attribute instance-attribute
flip_angle: Annotated[
    float | None, Bids(FlipAngle), Scoped(ACQUISITION)
] = None

Flip angle, in degrees.

magnetic_field_strength class-attribute instance-attribute
magnetic_field_strength: Annotated[
    float | None,
    Bids(MagneticFieldStrength),
    Scoped(ACQUISITION),
] = None

Nominal field strength, in tesla.

manufacturer class-attribute instance-attribute
manufacturer: Annotated[
    Manufacturer | str | None,
    Bids(Manufacturer),
    Scoped(ACQUISITION),
] = None

Manufacturer of the equipment (a known one is a Manufacturer).

manufacturers_model_name class-attribute instance-attribute
manufacturers_model_name: Annotated[
    str | None,
    Bids(ManufacturersModelName),
    Scoped(ACQUISITION),
] = None

Model name of the equipment.

institution_name class-attribute instance-attribute
institution_name: Annotated[
    str | None, Bids(InstitutionName), Scoped(ACQUISITION)
] = None

Institution responsible for the equipment.

acquisition_time class-attribute instance-attribute
acquisition_time: Annotated[
    datetime | None,
    Bids(AcquisitionTime),
    Scoped(ACQUISITION),
] = None

When the acquisition started.

phase_encoding_direction class-attribute instance-attribute
phase_encoding_direction: Annotated[
    EncodingDirection | None,
    Bids(PhaseEncodingDirection),
    Scoped(SPATIAL),
    ConvertTo(direction),
] = None

Phase-encoding direction: a unit vector. By default in voxel axes (BIDS 'j-' is accepted).

total_readout_time class-attribute instance-attribute
total_readout_time: Annotated[
    float | None,
    Bids(TotalReadoutTime),
    Scoped(ACQUISITION),
] = None

Total readout time, in seconds.

effective_echo_spacing class-attribute instance-attribute
effective_echo_spacing: Annotated[
    float | None,
    Bids(EffectiveEchoSpacing),
    Scoped(ACQUISITION),
] = None

Effective echo spacing, in seconds.

slice_encoding_direction class-attribute instance-attribute
slice_encoding_direction: Annotated[
    EncodingDirection | None,
    Bids(SliceEncodingDirection),
    Scoped(SPATIAL),
    ConvertTo(direction),
] = None

Slice-encoding direction: a unit vector, by default in voxel axes (BIDS 'k' is accepted)."

slice_timing class-attribute instance-attribute
slice_timing: Annotated[
    tuple[float, ...] | None,
    Bids(SliceTiming),
    Scoped(SPATIAL),
] = None

Acquisition time of each slice, in seconds, along the slice encoding direction.

multiband_acceleration_factor class-attribute instance-attribute
multiband_acceleration_factor: Annotated[
    int | None,
    Bids(MultibandAccelerationFactor),
    Scoped(ACQUISITION),
] = None

Multiband acceleration factor.

bvalues class-attribute instance-attribute
bvalues: Annotated[
    tuple[float, ...] | None, Along(time)
] = None

One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."

bvectors class-attribute instance-attribute
bvectors: Annotated[
    tuple[tuple[float, float, float], ...] | None,
    Along(time),
] = None

One unit gradient direction per index along the time axis, in world (RAS) coordinates."

display_range class-attribute instance-attribute
display_range: Annotated[
    tuple[float, float] | None, Scoped(VALUES)
] = None

Display window (min, max).

channels class-attribute instance-attribute
channels: Annotated[
    tuple[Channel, ...] | None, Along(channel)
] = None

One description per channel. The descriptions run along the axes of type channel only. The entries of a component axis, such as a vector or a tensor axis, are described by the type, the valence, the layout and the frame of that axis, so a change of frame, which only re-expresses the values of component axes, keeps these descriptions.

data_unit class-attribute instance-attribute
data_unit: Annotated[
    Unit | str | None, Scoped(VALUES), ConvertTo(unit)
] = None

Unit of the data values: a Unit whenever the units module parses the name ('a.u.', 'mm/s', 'HU'), and the name itself, as a string, when it does not, so that a file with an odd unit still reads. Formats write it as its symbol (Unit.symbol), which parses back to the same unit.

dtype class-attribute instance-attribute
dtype: Annotated[
    dtype | None, Scoped(VALUES), ConvertTo(to_dtype)
] = None

The element type of the data as stored, in native byte order.

It may differ from the type of the loaded array: a scaled integer file loads as floating-point values. An override given to save or to consolidate takes precedence over it.

scale_slope class-attribute instance-attribute
scale_slope: Annotated[float | None, Scoped(VALUES)] = None

The slope of the intensity scaling: a value is stored * scale_slope + scale_intercept. None means no scaling.

scale_intercept class-attribute instance-attribute
scale_intercept: Annotated[float | None, Scoped(VALUES)] = (
    None
)

The intercept of the intensity scaling (see scale_slope). None means no intercept.

objective_magnification class-attribute instance-attribute
objective_magnification: Annotated[
    float | None, Scoped(ACQUISITION)
] = None

Nominal magnification of the objective.

objective_numerical_aperture class-attribute instance-attribute
objective_numerical_aperture: Annotated[
    float | None, Scoped(ACQUISITION)
] = None

Numerical aperture of the objective.

illumination_type class-attribute instance-attribute
illumination_type: Annotated[
    IlluminationType | str | None, Scoped(ACQUISITION)
] = None

Illumination type (a known one is an IlluminationType).

contrast_method class-attribute instance-attribute
contrast_method: Annotated[
    ContrastMethod | str | None, Scoped(ACQUISITION)
] = None

Contrast method (a known one is a ContrastMethod).

moving class-attribute instance-attribute
moving: Annotated[str | None, Scoped(FILE)] = None

The moving image of a registration (file reference).

fixed class-attribute instance-attribute
fixed: Annotated[str | None, Scoped(FILE)] = None

The fixed image of a registration (file reference).

input_space class-attribute instance-attribute
input_space: Annotated[
    SpaceEnum | str | None, Scoped(FILE)
] = None

Label of the space a transformation maps from.

output_space class-attribute instance-attribute
output_space: Annotated[
    SpaceEnum | str | None, Scoped(FILE)
] = None

Label of the space a transformation maps to.

extra class-attribute instance-attribute
extra: Annotated[
    dict[str, Any], Scoped(FILE), HideIf(not_)
] = Factory()

Free-form keys the vocabulary does not cover, copied into any free-form store a format has."

SUPPORTED_FIELDS class-attribute
SUPPORTED_FIELDS: tuple[str, ...] = (
    "description",
    "sources",
    "intent",
    "space",
    "display_range",
    "phase_encoding_direction",
    "slice_encoding_direction",
    "slice_timing",
    "repetition_time",
    "dtype",
    "scale_slope",
    "scale_intercept",
)

The fields of the vocabulary that a NIfTI header stores.

raw class-attribute instance-attribute
raw: NoRepr[NiftiRaw | None] = None

The header of the file, or None for metadata without a record.

Methods:

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Score a file, as the record class scores it.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
error bool or type[Exception]

Whether to raise an error when the file is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score an open file, as the record class scores it.

Parameters:

Name Type Description Default
file IO

The open file.

required
error bool or type[Exception]

Whether to raise an error when the file is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Same as sniff, for bytes, text, or lines.

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

Score the content of a file, as the record class scores it.

Parameters:

Name Type Description Default
content bytes

The content of the file.

required
error bool or type[Exception]

Whether to raise an error when the content is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score the text of a file, as the record class scores it.

Parameters:

Name Type Description Default
text str

The text of the file.

required
error bool or type[Exception]

Whether to raise an error when the text is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score the lines of a file, as the record class scores them.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines of the file.

required
error bool or type[Exception]

Whether to raise an error when the lines are not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score the first line of a file, as the record class scores it.

Parameters:

Name Type Description Default
line str

The line.

required
error bool or type[Exception]

Whether to raise an error when the line is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read the metadata from a path, through the record class.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from an open file, through the record class.

Parameters:

Name Type Description Default
file IO

The open file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read an object from bytes, text, or lines.

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

Read the metadata from the content of a file.

The content is read by the record class.

Parameters:

Name Type Description Default
content bytes

The content of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from the text of a file, through the record.

Parameters:

Name Type Description Default
text str

The text of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from the lines of a file, through the record.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from a single line, through the record.

Parameters:

Name Type Description Default
line str

The line.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod
from_instance(
    other: Any,
    *args: Any,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    **kwargs: Any,
) -> Self

Copy metadata into this format, field by field.

Every field of the vocabulary and extra are copied by name, including those that this format cannot store, which are dropped and reported only when the metadata is consolidated. The record of another format means nothing to this one, so it is copied only from metadata of this class. The fields that are set and that SUPPORTED_FIELDS does not list are reported here as lost, because a write will drop them, so the report is a lower bound of what a write loses.

Parameters:

Name Type Description Default
other object

The metadata to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
on_loss ErrorAction

What to do with the fields that this format cannot store: "ignore" accepts the loss, "warn" warns about it, "raise" raises, and a report is filled instead of warning or raising. By default, the action of on_error, or else the policy in effect (see metadata_loss_policy).

UNSET
on_error ErrorPolicy

What to do with a conversion error of the copy, including a loss (see ErrorPolicy). A mapping may also name other errors. An entry for a loss in on_error takes precedence over on_loss. By default, an error is raised.

UNSET
**kwargs Any

Fields to set on the result.

{}

Returns:

Type Description
MetadataFormat

The copy.

Raises:

Type Description
MetadataLossError

If a field is reported under the "raise" policy.

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

Build metadata from a file, from other metadata, or from a value.

Metadata of any class, generic or of another format, is copied field by field with from_instance. A file is read as FileBasedModelMixin.from_any reads it, and any other value is passed to the data model.

Parameters:

Name Type Description Default
other object

A file, its content, metadata, or a mapping of fields.

required
*args Any

Constructor arguments.

()
**kwargs Any

Fields of the metadata, or the options of the reader for a file.

{}

Returns:

Type Description
MetadataFormat

The metadata.

to
to(
    cls: Type[Metadata] | None = None,
    *,
    copy: bool = False,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    **values: Any,
) -> Metadata

Convert this metadata into another class.

This is the metadata counterpart of to on images and transformations. Each field is copied by name. The record of a file format means nothing to another format, so it is copied only into the same class. A file format that has no slot for a field that is set still receives the value, and reports it as lost, because its next consolidation will drop it. The report is acted on by the action that on_loss or on_error takes for a MetadataLossError.

Parameters:

Name Type Description Default
cls type

The metadata class to convert into, such as Metadata or NiftiMetadata. By default, the class of this metadata.

None
copy bool

Whether to return new metadata when nothing changes. By default, metadata converted to its own class without any field is returned itself.

False
on_loss ErrorAction

What to do with the fields that cls has no slot for: "ignore" accepts the loss, "warn" warns about it, "raise" raises, and a report, ConversionReport, is filled instead of warning or raising. By default, the action of on_error, or else the policy in effect (see metadata_loss_policy).

UNSET
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. An entry for a loss in on_error takes precedence over on_loss. By default, an error is raised.

UNSET
**values Any

Fields to set on the result.

{}

Returns:

Type Description
Metadata

The converted metadata.

Raises:

Type Description
MetadataLossError

If a field is reported under the "raise" policy.

Examples:

report = ConversionReport()
mgh = metadata.to(MghMetadata, on_loss=report)
report.lost  # the fields MGH has no slot for
consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path, always as bytes.

The content is encoded before the target changes, so that an error while it is encoded leaves the target as it was. A local file is written next to its target, which it then replaces at once. A remote file is written once the whole content is encoded. A text format is written with to_bytes, so that its line endings are written as they are, on every system. A binary format is written with to_fileobj, which a local file receives as it is written and a remote file receives once it is complete. A name that ends with .gz, .bz2 or .xz compresses the file, whatever the format.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

from_raw classmethod
from_raw(
    raw: NiftiRaw | None, **kwargs: Any
) -> NiftiMetadata

Build the metadata of a record, decoding its vocabulary.

Parameters:

Name Type Description Default
raw NiftiRaw

The record, held as it is given.

required
**kwargs Any

Other fields, which take precedence over the decoded values.

{}

Returns:

Type Description
NiftiMetadata

The metadata.

derive
derive(
    operation: Indexed | Resampled | None = None,
    *,
    history: str | Sequence[str] | None = None,
) -> NiftiMetadata

Return the metadata of an image computed from this one.

The fields follow Metadata.derive. When the operation moves the spatial axes, the record is also replaced by a copy without dim_info and the slice slots, which describe the old voxel axes. The encoding directions that the derivation maps differ from that copy, so the next consolidation writes them.

Parameters:

Name Type Description Default
operation Indexed or Resampled

What the image operation did to the axes of the image.

None
history str or sequence of str

The steps of the derivation, appended to history.

None

Returns:

Type Description
NiftiMetadata

New metadata.

to_bytes
to_bytes(**fields: Any) -> bytes

Return the header of the consolidated record as NIfTI stores it.

The metadata is consolidated first, with the overrides given, so a field that was changed is written. The metadata itself is not changed. Metadata without a record is written as an empty NIfTI-1 header.

Parameters:

Name Type Description Default
**fields Any

Fields to override, as in [consolidate][].

{}

Returns:

Type Description
bytes

The header and its extensions.

to_fileobj
to_fileobj(file: BinaryIO, **fields: Any) -> None

Write the header of the consolidated record to a stream.

The metadata is consolidated first, as in to_bytes, so that a file written from the metadata holds what to_bytes returns.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**fields Any

Fields to override, as in [consolidate][].

{}

NiftiRaw magic

NiftiRaw(header: _NiftiHeader = Nifti1Header())

Bases: Raw, BinaryFileReader, BinaryFileWriter

Header of a NIfTI file, as the file stores it.

The record of a NIfTI file is its nibabel header, which also holds the extensions that follow the header in the file. A record is read from the start of a file without reading the voxels, and it is written as the header alone, so a record read from a file and written again gives back the first bytes of that file. The geometry, the data type and the other fields of the header are kept as they are stored, and only the readers of the NIfTI formats decode them.

A record is held by NiftiMetadata, which never changes it in place. A writer works on the copy that copy returns.

Parameters:

Name Type Description Default
header _NiftiHeader

The NIfTI-1 or NIfTI-2 header, with its extensions. A new record holds an empty NIfTI-1 header.

Nifti1Header()

Attributes

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

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

header instance-attribute
header: Annotated[_NiftiHeader, Factory(Nifti1Header)]

The NIfTI-1 or NIfTI-2 header, with its extensions.

A new record holds an empty NIfTI-1 header.

Methods:

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path, always as bytes.

The content is encoded before the target changes, so that an error while it is encoded leaves the target as it was. A local file is written next to its target, which it then replaces at once. A remote file is written once the whole content is encoded. A text format is written with to_bytes, so that its line endings are written as they are, on every system. A binary format is written with to_fileobj, which a local file receives as it is written and a remote file receives once it is complete. A name that ends with .gz, .bz2 or .xz compresses the file, whatever the format.

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

Write the object to a file object open for writing.

A binary format writes the result of to_bytes. A text format writes the result of to_text to a text stream, such as a file opened with "w" or an io.StringIO, and the result of to_bytes to any other stream, such as a file opened with "wb" or an io.BytesIO.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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

Same as sniff, for bytes, text, or lines.

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

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read an object from a path.

The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.

Raises:

Type Description
ParserExistsError

If the file does not exist.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

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

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to
to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

copy
copy() -> Self

Return a copy of the record that can be changed freely.

The fields of the header are copied. The list of extensions is new, but the extensions themselves are shared, because nibabel copies a header in this way.

Returns:

Type Description
NiftiRaw

The copy.

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

Return the confidence that a stream holds a NIfTI header.

A stream that starts with the header size and the magic number of NIfTI-1 or NIfTI-2 is a NIfTI file with certainty. The stream may be compressed with gzip, and its position is restored.

Parameters:

Name Type Description Default
file file object

The stream to test, open in binary mode.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
version int

The NIfTI version to look for, 1 or 2. Both are tried by default.

None
**kwargs Any

Ignored.

{}

Returns:

Type Description
float

Confidence.CERTAIN or Confidence.NO.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

from_fileobj classmethod
from_fileobj(
    file: BinaryIO, check: bool = True, **kwargs
) -> NiftiRaw

Read the header at the start of a NIfTI stream.

The stream may be compressed with gzip. Only the header and its extensions are read, so the stream may end before the voxels.

Parameters:

Name Type Description Default
file file object

The stream, open in binary mode.

required
check bool

Whether nibabel checks the header.

True
**kwargs Any

Refused, since the record has no other option.

{}

Raises:

Type Description
TypeError

If another option is given.

to_bytes
to_bytes(**kwargs) -> bytes

Return the header and its extensions as a NIfTI file stores them.

The header is written from a copy, because nibabel sets the offset of the voxels in the header that it writes when the offset is zero.

NiftiRASToVoxel magic

NiftiRASToVoxel(
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None
    ),
    data: npmatrix[Real] | None = None,
    log: bool = False,
    matrix: npmatrix[Real] | None = None,
    homogeneous_matrix: npmatrix[Real] | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = None,
    *,
    input: CoordinateSystem = RASmm(),
    output: CoordinateSystem = VoxelCoordinateSystem(),
)

Bases: _NiftiAffine, RASToVoxel

Affine from RAS to voxel space, stored in the header of a NIfTI file.

Not a registered format

The header encodes the voxel-to-RAS affine, and the RAS-to-voxel affine is its computed inverse. The two cannot be told apart by content, since they share the container, the extension and the confidence, so registering both would make every .nii file ambiguous. This affine is reached through NiftiVoxelToRAS.inverse().

Parameters:

Name Type Description Default
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None)
data npmatrix[Real] | None

Matrix of shape (No, Ni+1), whose last column is the translation. It maps Ni input axes to No output axes. None stands for the identity.

None
log bool

Whether data is the tangent of the map rather than its matrix. A transformation that holds the tangent is an AffineExponential.

False
matrix npmatrix[Real] | None

Matrix of shape (No, Ni+1), accepted in place of data.

None
homogeneous_matrix npmatrix[Real] | None

Homogeneous matrix of shape (No+1, Ni+1), accepted for data.

None
rawdata NoRepr[ArrayProtocol | None]

The array of the file as it is stored, or None without one. After a read, rawdata is a lazy array of the file, which applies the scaling of the header when it is read, as nibabel applies it. A transformation that keeps its data in the header, such as an affine, has no array. rawdata describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is.

None
input CoordinateSystem
RASmm()
output CoordinateSystem
VoxelCoordinateSystem()

Attributes

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

rawdata class-attribute instance-attribute
rawdata: NoRepr[ArrayProtocol | None] = None

The array of the file as it is stored, or None without one.

After a read, rawdata is a lazy array of the file, which applies the scaling of the header when it is read, as nibabel applies it. A transformation that keeps its data in the header, such as an affine, has no array. rawdata describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is.

metadata class-attribute instance-attribute
metadata = smartproperty(
    "metadata", invalidates=("data", _FORGET_VIEWS)
)

The metadata of the file, which holds its header, or None.

Without an assigned matrix, the matrix is decoded from the header, so assigning other metadata drops the matrix decoded from the previous header.

Methods:

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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

Same as sniff, for bytes, text, or lines.

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

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read an affine from the header of a NIfTI file.

Raises:

Type Description
ParserExistsError

If the path does not exist.

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

Read an affine from the header at the start of a NIfTI stream.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: Type[Self] | None = None,
    *,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    copy: bool = False,
    **kwargs,
) -> Self

Convert the transformation to another type or encoding.

The conversion takes one of three forms:

  • between types: linear.to(Affine) ; or
  • within a type: displacement.to(store="coefficients") ; or
  • both: coords.to(DisplacementField, store="values") .

A conversion that would lose information raises a LossyConversionError, which carries the lossy result. A conversion that cannot be made raises a ConversionError. An error policy decides what happens to these errors (see ErrorPolicy). Its scope is (ConversionError,), so that a single action applies to these errors only, and any other error is raised unless a mapping names it. The policy that the call applies is {LossyConversionError: on_loss, **on_error}, so that on_loss="ignore" returns the lossy result. Without on_loss=, a loss falls under on_error=, so that on_error="ignore" alone also returns the lossy result. A loss of metadata, in the conversions of metadata that the conversion triggers, follows the same policy, because a MetadataLossError is a lossy conversion error.

Parameters:

Name Type Description Default
cls type of Transformation

Type to convert to. By default, the type is normally kept.

None
on_loss ErrorAction

What to do with a conversion that loses information, with the same values as a single action of on_error. "ignore" returns the lossy result, "warn" warns and returns it, and a report records the loss and returns it. By default, a loss falls under on_error.

UNSET
on_error ErrorPolicy

What to do when the conversion fails. One action applies to a ConversionError, which includes a loss, and any other error, such as an OSError, is raised unchanged. A mapping chooses an action by the class of the error, and may name a class outside the conversion errors, as {Exception: None} does. An entry for a loss in on_error takes precedence over on_loss. True and False are refused. By default, every error is raised.

UNSET
copy bool

Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself.

False
**kwargs Any

Attributes of the converted transformation. store="coefficients" re-encodes the data of a displacement field and keeps its map. A view such as field= or matrix= sets the map, stored in the encoding of the result, whereas data= is stored as given.

{}

Returns:

Type Description
Transformation

The converted transformation, or what the policy returns in its place.

Examples:

# Accept a loss, and return None if no converter exists.
t.to(Rotation, on_loss="ignore", on_error=None)
to_backend
to_backend(
    backend: BackendLike | None = None,
    *,
    device: DeviceLike | None = None,
) -> ArrayProtocol | None

Return the data as a bare array of the backend of a setting.

The object does not change. Small parameters, such as the matrix of an affine transformation, are converted too, since the caller asks for them. An object without data, such as the identity, gives None.

Parameters:

Name Type Description Default
backend str | module

The setting. By default, the current setting is used.

None
device str | int

The device for converted arrays. The backend supplies its default.

None

Returns:

Type Description
array | None

The data.

to_numpy
to_numpy() -> ArrayProtocol

Return the data as a NumPy array, reading or computing them.

to_cupy
to_cupy(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a CuPy array on the GPU.

to_dask
to_dask(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a Dask array, without reading them.

as_numpy
as_numpy(*, inplace: bool = False) -> Self

Return the object with its data as NumPy arrays.

On an object read from a file, as_numpy(inplace=True) reads the file once and keeps its values.

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_cupy
as_cupy(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as CuPy arrays on the GPU.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_dask
as_dask(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Convert the transformation to the cheapest type that represents it.

Parameters:

Name Type Description Default
mode ModeLike

Kinds of transformation that may be composed, used only when factor is true. A concrete transformation has nothing to compose on its own, so otherwise only simplify decides whether it is converted.

True
simplify SimplifyLike

How much effort to spend on simplification. "analytic" decides from the type alone, "numeric" also reads the parameter values of a matrix transformation, {None: "numeric"} also reads those of a field, and "none" skips simplification.

"analytic"
factor bool

Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Rewrite the transformation as one factor per group of axes.

The axes of a transformation often fall into groups that never interact, as with a diagonal matrix, whose axes each scale on their own. Factoring finds those groups and gives each one a factor that acts on its axes alone, which lets a resampler work group by group rather than over the whole grid. The transformation is factored as a chain of one element, so that, under the numeric policy, a diagonal affine splits into one factor per axis. See Sequence.factor for the normal form that the pass produces and for what is left unfactored.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the transformation may be read, with the values and the meaning of the policy of simplify. Under the analytic policy, a matrix couples all its axes, so a diagonal affine splits only under the numeric policy.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. It decides nothing about what is factored, and the default composes nothing.

False

Returns:

Type Description
Transformation

The factored transformation, or self when it does not factor.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

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

Return the transformation composed with itself.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

score_header classmethod
score_header(header: NiftiObject) -> float

Score a header as a bare affine, always Confidence.WEAK.

Every NIfTI file carries an affine, but loading a .nii file rarely means loading its voxel-to-RAS matrix, which is reached through the image instead. The weak score keeps these readers as a last resort that never outranks an image or a field.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an affine from the header of a nibabel image or header.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the affine.

{}

Returns:

Type Description
_NiftiAffine

The affine.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(
    like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image

Build the nibabel image whose affine is this transformation.

The affine is consolidated with the options, as by [consolidate][], into a copy, and the header of that copy is written over a single-voxel placeholder volume. The affine itself is not changed.

Parameters:

Name Type Description Default
like path, nibabel image or header, or NIfTI object

Template whose header fields that do not encode the transformation are copied.

None
**overrides Any

Header fields that take precedence over the derived values and like.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

data
data() -> ArrayProtocol | None

The (3, 4) matrix of the affine, which the matrix view reads.

A matrix that is assigned is returned as it is, and stays pending until [consolidate][] or a write encodes it. Otherwise, the matrix is decoded from a homogeneous matrix in rawdata, or else it is the inverse of the voxel-to-RAS affine of the header, which is read-only, or None without metadata.

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

Return the inverse transformation, from voxel to RAS space.

The inverse of an affine read from a header is the affine of the same header, rather than an inverse of its inverse.

Parameters:

Name Type Description Default
compute bool

Whether to compute the inverse now rather than lazily. It is ignored for an affine read from a header.

False
**kwargs Any

Arguments passed to the inverse of the data model, which are ignored for an affine read from a header.

{}

Returns:

Type Description
VoxelToRAS

The inverse transformation.

NiftiVoxelToRAS magic

NiftiVoxelToRAS(
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None
    ),
    data: npmatrix[Real] | None = None,
    log: bool = False,
    matrix: npmatrix[Real] | None = None,
    homogeneous_matrix: npmatrix[Real] | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = None,
    *,
    input: CoordinateSystem = VoxelCoordinateSystem(),
    output: CoordinateSystem = RASmm(),
)

Bases: _NiftiAffine, VoxelToRAS

Affine from voxel to RAS space, stored in the header of a NIfTI file.

The matrix of an affine read from a file is the grid that a NiftiImage of the same file decodes: the sform when its code is set, and otherwise the qform when its code is set. When both codes are zero, the matrix is the default grid that NiftiImage describes, which is centred on the middle of the image and flips the first axis. Setting the matrix stores it in rawdata, which then takes precedence over the header.

Parameters:

Name Type Description Default
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None)
data npmatrix[Real] | None

Matrix of shape (No, Ni+1), whose last column is the translation. It maps Ni input axes to No output axes. None stands for the identity.

None
log bool

Whether data is the tangent of the map rather than its matrix. A transformation that holds the tangent is an AffineExponential.

False
matrix npmatrix[Real] | None

Matrix of shape (No, Ni+1), accepted in place of data.

None
homogeneous_matrix npmatrix[Real] | None

Homogeneous matrix of shape (No+1, Ni+1), accepted for data.

None
rawdata NoRepr[ArrayProtocol | None]

The array of the file as it is stored, or None without one. After a read, rawdata is a lazy array of the file, which applies the scaling of the header when it is read, as nibabel applies it. A transformation that keeps its data in the header, such as an affine, has no array. rawdata describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is.

None
input CoordinateSystem
VoxelCoordinateSystem()
output CoordinateSystem
RASmm()

Attributes

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

rawdata class-attribute instance-attribute
rawdata: NoRepr[ArrayProtocol | None] = None

The array of the file as it is stored, or None without one.

After a read, rawdata is a lazy array of the file, which applies the scaling of the header when it is read, as nibabel applies it. A transformation that keeps its data in the header, such as an affine, has no array. rawdata describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is.

metadata class-attribute instance-attribute
metadata = smartproperty(
    "metadata", invalidates=("data", _FORGET_VIEWS)
)

The metadata of the file, which holds its header, or None.

Without an assigned matrix, the matrix is decoded from the header, so assigning other metadata drops the matrix decoded from the previous header.

Methods:

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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

Same as sniff, for bytes, text, or lines.

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

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read an affine from the header of a NIfTI file.

Raises:

Type Description
ParserExistsError

If the path does not exist.

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

Read an affine from the header at the start of a NIfTI stream.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: Type[Self] | None = None,
    *,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    copy: bool = False,
    **kwargs,
) -> Self

Convert the transformation to another type or encoding.

The conversion takes one of three forms:

  • between types: linear.to(Affine) ; or
  • within a type: displacement.to(store="coefficients") ; or
  • both: coords.to(DisplacementField, store="values") .

A conversion that would lose information raises a LossyConversionError, which carries the lossy result. A conversion that cannot be made raises a ConversionError. An error policy decides what happens to these errors (see ErrorPolicy). Its scope is (ConversionError,), so that a single action applies to these errors only, and any other error is raised unless a mapping names it. The policy that the call applies is {LossyConversionError: on_loss, **on_error}, so that on_loss="ignore" returns the lossy result. Without on_loss=, a loss falls under on_error=, so that on_error="ignore" alone also returns the lossy result. A loss of metadata, in the conversions of metadata that the conversion triggers, follows the same policy, because a MetadataLossError is a lossy conversion error.

Parameters:

Name Type Description Default
cls type of Transformation

Type to convert to. By default, the type is normally kept.

None
on_loss ErrorAction

What to do with a conversion that loses information, with the same values as a single action of on_error. "ignore" returns the lossy result, "warn" warns and returns it, and a report records the loss and returns it. By default, a loss falls under on_error.

UNSET
on_error ErrorPolicy

What to do when the conversion fails. One action applies to a ConversionError, which includes a loss, and any other error, such as an OSError, is raised unchanged. A mapping chooses an action by the class of the error, and may name a class outside the conversion errors, as {Exception: None} does. An entry for a loss in on_error takes precedence over on_loss. True and False are refused. By default, every error is raised.

UNSET
copy bool

Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself.

False
**kwargs Any

Attributes of the converted transformation. store="coefficients" re-encodes the data of a displacement field and keeps its map. A view such as field= or matrix= sets the map, stored in the encoding of the result, whereas data= is stored as given.

{}

Returns:

Type Description
Transformation

The converted transformation, or what the policy returns in its place.

Examples:

# Accept a loss, and return None if no converter exists.
t.to(Rotation, on_loss="ignore", on_error=None)
to_backend
to_backend(
    backend: BackendLike | None = None,
    *,
    device: DeviceLike | None = None,
) -> ArrayProtocol | None

Return the data as a bare array of the backend of a setting.

The object does not change. Small parameters, such as the matrix of an affine transformation, are converted too, since the caller asks for them. An object without data, such as the identity, gives None.

Parameters:

Name Type Description Default
backend str | module

The setting. By default, the current setting is used.

None
device str | int

The device for converted arrays. The backend supplies its default.

None

Returns:

Type Description
array | None

The data.

to_numpy
to_numpy() -> ArrayProtocol

Return the data as a NumPy array, reading or computing them.

to_cupy
to_cupy(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a CuPy array on the GPU.

to_dask
to_dask(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a Dask array, without reading them.

as_numpy
as_numpy(*, inplace: bool = False) -> Self

Return the object with its data as NumPy arrays.

On an object read from a file, as_numpy(inplace=True) reads the file once and keeps its values.

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_cupy
as_cupy(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as CuPy arrays on the GPU.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_dask
as_dask(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Convert the transformation to the cheapest type that represents it.

Parameters:

Name Type Description Default
mode ModeLike

Kinds of transformation that may be composed, used only when factor is true. A concrete transformation has nothing to compose on its own, so otherwise only simplify decides whether it is converted.

True
simplify SimplifyLike

How much effort to spend on simplification. "analytic" decides from the type alone, "numeric" also reads the parameter values of a matrix transformation, {None: "numeric"} also reads those of a field, and "none" skips simplification.

"analytic"
factor bool

Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Rewrite the transformation as one factor per group of axes.

The axes of a transformation often fall into groups that never interact, as with a diagonal matrix, whose axes each scale on their own. Factoring finds those groups and gives each one a factor that acts on its axes alone, which lets a resampler work group by group rather than over the whole grid. The transformation is factored as a chain of one element, so that, under the numeric policy, a diagonal affine splits into one factor per axis. See Sequence.factor for the normal form that the pass produces and for what is left unfactored.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the transformation may be read, with the values and the meaning of the policy of simplify. Under the analytic policy, a matrix couples all its axes, so a diagonal affine splits only under the numeric policy.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. It decides nothing about what is factored, and the default composes nothing.

False

Returns:

Type Description
Transformation

The factored transformation, or self when it does not factor.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

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

Return the transformation composed with itself.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

score_header classmethod
score_header(header: NiftiObject) -> float

Score a header as a bare affine, always Confidence.WEAK.

Every NIfTI file carries an affine, but loading a .nii file rarely means loading its voxel-to-RAS matrix, which is reached through the image instead. The weak score keeps these readers as a last resort that never outranks an image or a field.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an affine from the header of a nibabel image or header.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the affine.

{}

Returns:

Type Description
_NiftiAffine

The affine.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(
    like: Any = None, **overrides
) -> Nifti1Image | Nifti2Image

Build the nibabel image whose affine is this transformation.

The affine is consolidated with the options, as by [consolidate][], into a copy, and the header of that copy is written over a single-voxel placeholder volume. The affine itself is not changed.

Parameters:

Name Type Description Default
like path, nibabel image or header, or NIfTI object

Template whose header fields that do not encode the transformation are copied.

None
**overrides Any

Header fields that take precedence over the derived values and like.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

data
data() -> ArrayProtocol | None

The (3, 4) matrix of the affine, which the matrix view reads.

A matrix that is assigned is returned as it is, and stays pending until [consolidate][] or a write encodes it. Otherwise, the matrix is decoded from a homogeneous matrix in rawdata, or else it is the voxel-to-RAS affine of the header, which is read-only, or None without metadata.

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

Return the inverse transformation, from RAS to voxel space.

The inverse of an affine read from a header is the RAS-to-voxel affine of the same header.

Parameters:

Name Type Description Default
compute bool

Whether to compute the inverse now rather than lazily. It is ignored for an affine read from a header.

False
**kwargs Any

Arguments passed to the inverse of the data model, which are ignored for an affine read from a header.

{}

Returns:

Type Description
RASToVoxel

The inverse transformation.

NiftiBackedTransformation magic

NiftiBackedTransformation(
    rawdata: NoRepr[ArrayProtocol | None] = None,
)

Bases: NiftiReaderWriter, TransformationFormat

A transformation stored in a NIfTI file.

A NIfTI transformation holds the header of its file as NiftiMetadata, and the array of the file as it is stored in rawdata. When the transformation is read from a file, rawdata is a lazy array, which reads the array of the file only when it is needed. Each concrete format decodes its data, and the transformation of the data model, from rawdata and from the header, and caches what it decodes.

rawdata and the header describe the file as it was read, or as the transformation was last consolidated. Data and transformations that are assigned are pending until [consolidate][] encodes them into a copy, or until the transformation is written. A write encodes them in the same way, into a copy, and leaves the transformation as it was.

When the transformation is consolidated, a copy of the header of its file is the base of the new header. A transformation whose data model was not changed keeps its array under that header, and one whose data model was changed encodes the model over the header. This class is abstract and is not registered as a format. Its subclasses implement [consolidate][], on which the writers rely.

The metadata is the metadata field of the transformation of the data model. This class does not derive from that transformation, so it cannot take the field over: each concrete subclass does, with _metadata: ... = Inherit("metadata", default=None), so that the field holds NiftiMetadata and converts other metadata into it.

Parameters:

Name Type Description Default
rawdata NoRepr[ArrayProtocol | None]

The array of the file as it is stored, or None without one. After a read, rawdata is a lazy array of the file, which applies the scaling of the header when it is read, as nibabel applies it. A transformation that keeps its data in the header, such as an affine, has no array. rawdata describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is.

None

Attributes

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

rawdata class-attribute instance-attribute
rawdata: NoRepr[ArrayProtocol | None] = None

The array of the file as it is stored, or None without one.

After a read, rawdata is a lazy array of the file, which applies the scaling of the header when it is read, as nibabel applies it. A transformation that keeps its data in the header, such as an affine, has no array. rawdata describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is.

Methods:

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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

Same as sniff, for bytes, text, or lines.

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

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read an object from the path of a NIfTI file.

A local file is kept by its name, so that the lazy array opens it whenever the array is read, and memory-maps it when the file is not compressed. The lazy array outlives this call, so a remote file is read into memory and then read by [from_bytes][], rather than from a stream that would be closed.

Parameters:

Name Type Description Default
filename path - like

The path of the file, which may be compressed.

required
**kwargs Any

The reader options, which nibabel's readers also take. mmap tells whether the array of a local file that is not compressed is memory-mapped. keep_file_open is accepted and ignored, because the lazy array never keeps a file open.

{}

Returns:

Type Description
Self

The object, whose array is read lazily.

Raises:

Type Description
TypeError

If another option is given.

ValueError

If mmap is not one of True, False, "c" and "r".

ParserExistsError

If the path does not exist.

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

Read an object from an open NIfTI stream.

The record is read first, and the position of the stream is restored so that the lazy array reads the array from the same start. The lazy array keeps the stream, so the stream must stay open while the array may be read. A stream that cannot seek is read into memory first, and a stream is never memory-mapped.

Parameters:

Name Type Description Default
file BinaryIO

The stream, which may be compressed with gzip.

required
**kwargs Any

The reader options, as for from_filename.

{}

Returns:

Type Description
Self

The object, whose array is read lazily.

Raises:

Type Description
TypeError

If another option is given.

ValueError

If mmap is not one of True, False, "c" and "r".

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

score_header classmethod
score_header(header: NiftiObject) -> float

Return how well a valid NIfTI header matches this class.

The header has already passed the check of its size and magic number, so the score says how likely the file holds the kind of object that this class builds. A format that can tell its files apart from the header, such as by its intent code, overrides this method. The default is Confidence.MAYBE.

Parameters:

Name Type Description Default
header Nifti1Header or Nifti2Header

The header of the file.

required

Returns:

Type Description
float

The confidence, between 0 and 1.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an object from a nibabel image or header.

The array of an image becomes rawdata, and a copy of its header becomes the record of the metadata. A header alone gives an object without an array. The array proxy of an image that nibabel read from a file is replaced by the lazy array that from_filename builds for that file, and any other array is kept as it is.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the object.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(**options) -> _NibabelImage

Build the nibabel image that a file written from this object holds.

The object is consolidated with the options into a copy, and the nibabel image holds the rawdata and the header of that copy. The object itself is not changed.

Parameters:

Name Type Description Default
**options Any

The options of consolidate, such as the template like and the fields of the header.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

Raises:

Type Description
WriterError

If the object has no array to write.

NiftiRASCoordinateField magic

NiftiRASCoordinateField(
    data: ArrayProtocol | None = None,
    degree: InterpolationOrder = linear,
    bound: BoundaryCondition | float = nearest,
    store: StoreEnum | None = None,
    field: ArrayProtocol | None = None,
    values: ArrayProtocol | None = None,
    coefficients: ArrayProtocol | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = Inherit(
        "rawdata", var=True
    ),
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None, var=True
    ),
    *,
    input: CoordinateSystem = VoxelCoordinateSystem(),
    output: CoordinateSystem = RASmm(),
    image: NoRepr[Any | None] = Field(
        default=None, convert=False
    ),
)

Bases: NiftiImageBackedTransformation, RASCoordinateField

Field of RAS coordinates stored in a NIfTI file.

Each voxel of the file holds the RAS position, in millimetres, to which the field maps the centre of that voxel. The field keeps its file in a NiftiImage, as it was read or as the field was last consolidated, and rawdata and metadata read that image. [from_image][] builds a field from such an image, and [to_image][] returns the image that a file of the field holds. Assigned coordinates are pending until the field is consolidated or written, which encodes them through the image, so a field that is read and written again without changes is copied byte for byte.

Parameters:

Name Type Description Default
data ArrayProtocol | None

Stored field, of shape (*shape, ndim). It holds the values, or the spline coefficients when store is "coefficients". The map is read through field.

None
degree InterpolationOrder

Degree of the spline that interpolates the field.

linear
bound BoundaryCondition | float

Boundary condition for coordinates outside the field of view. A float is a constant fill value.

nearest
store StoreEnum | None

Whether data holds spline coefficients or values (see store).

None
field ArrayProtocol | None

Field as values, accepted in place of data. It is encoded according to store before it is stored.

None
values ArrayProtocol | None

Same as field.

None
coefficients ArrayProtocol | None

Field as spline coefficients, accepted in place of data. It sets store to "coefficients" unless the flag is given. With store="values", the spline is evaluated before the field is stored.

None
rawdata NoRepr[ArrayProtocol | None]
Inherit('rawdata', var=True)
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None, var=True)
input CoordinateSystem
VoxelCoordinateSystem()
output CoordinateSystem
RASmm()
image NoRepr[Any | None]

The image that holds the file, which the constructor always sets. The image describes the file as it was read, or as the transformation was last consolidated, and it never holds pending data or transformations.

Field(default=None, convert=False)

Attributes

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

metadata property writable
metadata: Any | None

The metadata of the file, which holds its header, or None.

The metadata is that of the stored image. A transformation built from its data alone has none. Assigning other metadata replaces the stored image with a copy that holds it, converted into the metadata of the image class, and drops the views decoded from the previous header.

rawdata property writable
rawdata: ArrayProtocol | None

The array of the file as it is stored, or None without one.

The array is the rawdata of the stored image. After a read, it is a lazy array of the file, which applies the scaling of the header when it is read. It describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is. Assigning rawdata replaces the stored image with a copy that holds the new array.

Methods:

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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

Same as sniff, for bytes, text, or lines.

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

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read a transformation from the path of its file.

The file is read by the reader of the image class, whose array is read lazily, and the transformation is built from that image with from_image. The keywords that name an argument of the constructor of the transformation, under any of their aliases, go to the transformation, and the other keywords go to the reader of the image, which refuses those that it does not know.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the reader of the image, such as mmap, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read a transformation from an open stream of its file.

The stream is read by the reader of the image class, whose lazy array keeps the stream, so the stream must stay open while the array may be read. The transformation is built from that image with from_image, and the keywords are shared out as by from_filename.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of the reader of the image, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

to
to(
    cls: Type[Self] | None = None,
    *,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    copy: bool = False,
    **kwargs,
) -> Self

Convert the transformation to another type or encoding.

The conversion takes one of three forms:

  • between types: linear.to(Affine) ; or
  • within a type: displacement.to(store="coefficients") ; or
  • both: coords.to(DisplacementField, store="values") .

A conversion that would lose information raises a LossyConversionError, which carries the lossy result. A conversion that cannot be made raises a ConversionError. An error policy decides what happens to these errors (see ErrorPolicy). Its scope is (ConversionError,), so that a single action applies to these errors only, and any other error is raised unless a mapping names it. The policy that the call applies is {LossyConversionError: on_loss, **on_error}, so that on_loss="ignore" returns the lossy result. Without on_loss=, a loss falls under on_error=, so that on_error="ignore" alone also returns the lossy result. A loss of metadata, in the conversions of metadata that the conversion triggers, follows the same policy, because a MetadataLossError is a lossy conversion error.

Parameters:

Name Type Description Default
cls type of Transformation

Type to convert to. By default, the type is normally kept.

None
on_loss ErrorAction

What to do with a conversion that loses information, with the same values as a single action of on_error. "ignore" returns the lossy result, "warn" warns and returns it, and a report records the loss and returns it. By default, a loss falls under on_error.

UNSET
on_error ErrorPolicy

What to do when the conversion fails. One action applies to a ConversionError, which includes a loss, and any other error, such as an OSError, is raised unchanged. A mapping chooses an action by the class of the error, and may name a class outside the conversion errors, as {Exception: None} does. An entry for a loss in on_error takes precedence over on_loss. True and False are refused. By default, every error is raised.

UNSET
copy bool

Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself.

False
**kwargs Any

Attributes of the converted transformation. store="coefficients" re-encodes the data of a displacement field and keeps its map. A view such as field= or matrix= sets the map, stored in the encoding of the result, whereas data= is stored as given.

{}

Returns:

Type Description
Transformation

The converted transformation, or what the policy returns in its place.

Examples:

# Accept a loss, and return None if no converter exists.
t.to(Rotation, on_loss="ignore", on_error=None)
to_backend
to_backend(
    backend: BackendLike | None = None,
    *,
    device: DeviceLike | None = None,
) -> ArrayProtocol | None

Return the data as a bare array of the backend of a setting.

The object does not change. Small parameters, such as the matrix of an affine transformation, are converted too, since the caller asks for them. An object without data, such as the identity, gives None.

Parameters:

Name Type Description Default
backend str | module

The setting. By default, the current setting is used.

None
device str | int

The device for converted arrays. The backend supplies its default.

None

Returns:

Type Description
array | None

The data.

as_backend
as_backend(
    backend: BackendLike | None = None,
    *,
    device: DeviceLike | None = None,
    inplace: bool = False,
) -> Self

Return the object with its data converted to the requested backend.

By default, the object holds no voxels and is returned as it is. Small parameters stay NumPy arrays where they are stored, so that code can convert a list of objects without testing their type.

Parameters:

Name Type Description Default
backend str | module

The setting. By default, the current setting is used.

None
device str | int

The device for converted arrays. The backend supplies its default.

None
inplace bool

Whether this object holds the converted data and is returned, instead of a new object.

False

Returns:

Type Description
object

An object of the same class.

to_numpy
to_numpy() -> ArrayProtocol

Return the data as a NumPy array, reading or computing them.

to_cupy
to_cupy(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a CuPy array on the GPU.

to_dask
to_dask(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a Dask array, without reading them.

as_numpy
as_numpy(*, inplace: bool = False) -> Self

Return the object with its data as NumPy arrays.

On an object read from a file, as_numpy(inplace=True) reads the file once and keeps its values.

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_cupy
as_cupy(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as CuPy arrays on the GPU.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_dask
as_dask(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Convert the transformation to the cheapest type that represents it.

Parameters:

Name Type Description Default
mode ModeLike

Kinds of transformation that may be composed, used only when factor is true. A concrete transformation has nothing to compose on its own, so otherwise only simplify decides whether it is converted.

True
simplify SimplifyLike

How much effort to spend on simplification. "analytic" decides from the type alone, "numeric" also reads the parameter values of a matrix transformation, {None: "numeric"} also reads those of a field, and "none" skips simplification.

"analytic"
factor bool

Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Rewrite the transformation as one factor per group of axes.

The axes of a transformation often fall into groups that never interact, as with a diagonal matrix, whose axes each scale on their own. Factoring finds those groups and gives each one a factor that acts on its axes alone, which lets a resampler work group by group rather than over the whole grid. The transformation is factored as a chain of one element, so that, under the numeric policy, a diagonal affine splits into one factor per axis. See Sequence.factor for the normal form that the pass produces and for what is left unfactored.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the transformation may be read, with the values and the meaning of the policy of simplify. Under the analytic policy, a matrix couples all its axes, so a diagonal affine splits only under the numeric policy.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. It decides nothing about what is factored, and the default composes nothing.

False

Returns:

Type Description
Transformation

The factored transformation, or self when it does not factor.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

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

Return the transformation composed with itself.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

Raises:

Type Description
DomainError

If the transformation does not map a space to itself.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an object from a nibabel image or header.

The array of an image becomes rawdata, and a copy of its header becomes the record of the metadata. A header alone gives an object without an array. The array proxy of an image that nibabel read from a file is replaced by the lazy array that from_filename builds for that file, and any other array is kept as it is.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the object.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_nibabel
to_nibabel(**options) -> _NibabelImage

Build the nibabel image that a file written from this object holds.

The object is consolidated with the options into a copy, and the nibabel image holds the rawdata and the header of that copy. The object itself is not changed.

Parameters:

Name Type Description Default
**options Any

The options of consolidate, such as the template like and the fields of the header.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.

Raises:

Type Description
WriterError

If the object has no array to write.

from_image classmethod
from_image(image: Any, **options: Any) -> Self

Build a transformation from the image that stores it.

The image becomes the stored image of the transformation, and the transformation decodes its data and its chain from that image when they are needed. The call is the same as cls(image=image, **options).

Parameters:

Name Type Description Default
image Any

The image, of the class that IMAGE names, which is consolidated first if it has pending data or transformations.

required
**options Any

The other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation.

Raises:

Type Description
TypeError

If the image is not of the class that IMAGE names.

to_image
to_image() -> Any

Return the image that a file of this transformation holds.

The transformation is consolidated into a copy, as by [consolidate][], and the stored image of that copy is returned. The transformation itself is not changed.

Returns:

Type Description
Any

The image, of the class that IMAGE names, without pending data or transformations.

score_header classmethod
score_header(header: NiftiObject) -> float

Score a header as a field of RAS coordinates.

A VECTOR image (1007), the intent that this reader and SPM write, scores Confidence.CERTAIN. A DISPVECT image (1006) is left to NiftiRASDisplacementField, and a file named "NREG_TRANS" to brainhops.io.transformations.niftyreg. A file named "ITKDisplacement" or "ITKCoordinates", which brainhops writes on ITK fields, is left to the ITK readers. The ITK displacement reader ties on any other VECTOR image in the ITK layout unless its intent name is "Mapping", so a hint decides (see brainhops.io.transformations.itk.nifti). Any other file whose trailing axis has length 3 scores Confidence.MAYBE.

data
data() -> ArrayProtocol | None

The field as an (X, Y, Z, 3) array, which its field view reads.

An array that is assigned is returned as it is, and stays pending until [consolidate][] or a write encodes it. Otherwise, the data is decoded from rawdata. NIfTI stores a vector field with shape (X, Y, Z, 1, 3), and the data is decoded without the singleton axis, since the array would otherwise be sampled as a 4-D grid of vectors. A file whose fourth axis is longer than one holds a field per volume, which is not supported yet, so reading its data raises ParserContentError.

NiftiRASDisplacementField magic

NiftiRASDisplacementField(
    transformations: tuple[Transformation, ...]
    | None = None,
    rawdata: NoRepr[ArrayProtocol | None] = Inherit(
        "rawdata", var=True
    ),
    log: bool = False,
    steps: int | None = None,
    data: NoRepr[ArrayProtocol | None] = None,
    metadata: NoRepr[NiftiMetadata | None] = Inherit(
        "metadata", default=None, var=True
    ),
    *,
    input: CoordinateSystem | None = None,
    output: CoordinateSystem | None = None,
    image: NoRepr[Any | None] = Field(
        default=None, convert=False
    ),
)

Bases: NiftiImageBackedTransformation, DerivedSequence

Field of RAS displacements stored in a NIfTI file.

The file holds a DISPVECT field (1006), in which each voxel holds the displacement, in RAS millimetres, of the point at its centre. The field maps RAS to RAS as x -> x + u(x), which is how ITK 5.4 and later read and write DISPVECT. A displacement field adds its values in the units of its own grid, so this field is an ImmutableSequence of three named slots:

Slot Transformation
ras2voxel RAS world coordinates to the field's voxels
displacement the displacement field, in voxel units
voxel2ras the field's voxels back to RAS world

The displacements are interpolated linearly and extrapolated with the nearest value outside the grid, as by the default DisplacementFieldTransform of ITK.

The file may hold a stationary velocity instead, whose flow at time one is the map: the standard has no code for one, so it is said with the log option (warp.nii.gz|displacements|log:true, or its alias warp.nii.gz|svf; in Python, load(path, log=True)). The displacement slot is then a StationaryVelocityField, integrated with steps squaring steps (|svf|steps:6). The field is written in the encoding the options say: a velocity when log is set, and otherwise the displacement, which a velocity is integrated into.

Another transformation is converted to this format by its converters ([brainhops.io.transformations.nifti._converters][]), exactly or not at all. Its chain is carried over, rather than re-read from a NIfTI header that comes with it and says something else (a NiftyReg file holds positions, say). Its encoding is not: log and steps are this format's options, so a velocity converted here is written as its displacement unless log=True is given -- to the conversion, or to save.

The field keeps its file in a NiftiImage, as it was read or as the field was last consolidated, and rawdata and metadata read that image. from_image builds a field from such an image, and [to_image][] returns the image that a file of the field holds. Assigned vectors and an assigned chain are pending until the field is consolidated or written, which encodes them through the image. A chain that is encoded gives its grid to the image as its voxel-to-world transformation, so the sform and the qform are written as for any NIfTI image.

Parameters:

Name Type Description Default
transformations tuple[Transformation, ...] | None
None
rawdata NoRepr[ArrayProtocol | None]
Inherit('rawdata', var=True)
log bool

Whether the file holds the stationary velocity whose flow is the map, rather than its displacement.

False
steps int | None

The number of squaring steps that integrate a velocity (log only). If None, the default of [StationaryVelocityField][].

None
data NoRepr[ArrayProtocol | None]

The vectors given to the field, or None to decode them from rawdata. Vectors stored here are pending until [consolidate][] or a write encodes them into rawdata.

None
metadata NoRepr[NiftiMetadata | None]
Inherit('metadata', default=None, var=True)
input CoordinateSystem | None

Input coordinate system, which may be inferred from context if unset.

None
output CoordinateSystem | None

Output coordinate system, which may be inferred from context if unset.

None
image NoRepr[Any | None]

The image that holds the file, which the constructor always sets. The image describes the file as it was read, or as the transformation was last consolidated, and it never holds pending data or transformations.

Field(default=None, convert=False)

Attributes

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

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

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

Names of the attributes that define the encoding.

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

Names of the derived attributes, such as views and caches.

mutually_exclusive_fields class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None

Constructor arguments that may not be given together.

A view is another name under which the stored parameter can be given, such as matrix for the data of an affine transformation. The default, None, makes the stored parameter and all of its views mutually exclusive, so the group is data_fields followed by derived_fields. This default applies only to a class with at most one data field. A class with several independent data fields has no group unless it declares one.

metadata property writable
metadata: Any | None

The metadata of the file, which holds its header, or None.

The metadata is that of the stored image. A transformation built from its data alone has none. Assigning other metadata replaces the stored image with a copy that holds it, converted into the metadata of the image class, and drops the views decoded from the previous header.

rawdata property writable
rawdata: ArrayProtocol | None

The array of the file as it is stored, or None without one.

The array is the rawdata of the stored image. After a read, it is a lazy array of the file, which applies the scaling of the header when it is read. It describes the file as it was read, or as the transformation was last consolidated, so assigning data leaves it as it is. Assigning rawdata replaces the stored image with a copy that holds the new array.

degree class-attribute
degree: int = 1

Spline degree of the interpolation.

bound class-attribute

Boundary condition outside the field of view.

log class-attribute instance-attribute
log: bool = False

Whether the file holds the stationary velocity whose flow is the map, rather than its displacement.

steps class-attribute instance-attribute
steps: int | None = None

The number of squaring steps that integrate a velocity (log only). If None, the default of [StationaryVelocityField][].

ras2voxel property
ras2voxel: Transformation | None

The affine from RAS world coordinates to the voxels of the field.

displacement property
displacement: Transformation | None

The displacement field in voxel units, or the velocity with log.

voxel2ras property
voxel2ras: Transformation | None

The affine from the voxels of the field back to RAS world coordinates.

Methods:

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

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

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

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

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

Write the object to a path.

The object is consolidated into a copy, which is written as the base writer writes any file: a local file is replaced at once, and a name that ends with .gz compresses the file. An object can therefore be written over the file that its lazy array reads. It is then consolidated in place, so that it holds what the file holds (#426): its lazy array reads the new file, and its record is the header of that file.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_fileobj
to_fileobj(file: BinaryIO, **kwargs) -> None

Write the object to a stream as an uncompressed NIfTI file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of consolidate.

{}

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_bytes
to_bytes(**kwargs) -> bytes

Return the content of an uncompressed NIfTI file of the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of consolidate.

{}

Returns:

Type Description
bytes

The content of the file.

Raises:

Type Description
WriterError

If the object cannot be encoded.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

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

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

Same as sniff, for a path or an open file.

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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

Return the confidence that a stream holds an object of this class.

A stream that starts with a NIfTI header is scored by score_header. Any other stream is declined by NiftiRaw.sniff_fileobj, which raises the requested error.

Parameters:

Name Type Description Default
file IO

The stream, open in binary mode and read from its current position, which is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream holds no NIfTI header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

The NIfTI version to look for, 1 or 2. Other options are ignored.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

Raises:

Type Description
SnifferContentError

If the stream holds no NIfTI header and error is True.

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

Same as sniff, for bytes, text, or lines.

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

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

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

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read a transformation from the path of its file.

The file is read by the reader of the image class, whose array is read lazily, and the transformation is built from that image with from_image. The keywords that name an argument of the constructor of the transformation, under any of their aliases, go to the transformation, and the other keywords go to the reader of the image, which refuses those that it does not know.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the reader of the image, such as mmap, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read a transformation from an open stream of its file.

The stream is read by the reader of the image class, whose lazy array keeps the stream, so the stream must stay open while the array may be read. The transformation is built from that image with from_image, and the keywords are shared out as by from_filename.

Parameters:

Name Type Description Default
file BinaryIO

The stream, open in binary mode.

required
**kwargs Any

The options of the reader of the image, and the other fields of the transformation.

{}

Returns:

Type Description
Self

The transformation, whose array is read lazily.

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

Read an object from bytes, text, or lines.

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

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

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

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

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

Copy an instance, or convert a transformation to this format.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. An instance of this format is copied as [FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance] copies it, except that a format that stores its data in the private field _data passes the stored value on. That value is None unless the data were assigned, so the copy decodes the same record as other, and a record that was not decoded stays so.

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

Constructor arguments. A transformation that is converted takes keyword options only.

()
**kwargs Any

Options of the conversion, or field values of the copy.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Build an object from a file, a transformation or any other value.

A transformation that is not of this format is converted exactly as other.to(cls) converts it. Anything else is read or built as [FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.

Parameters:

Name Type Description Default
other object

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

required
*args Any

Constructor arguments. A file and a transformation that is converted take keyword options only.

()
**kwargs Any

Options of the reader or of the conversion, and field values otherwise.

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a file or a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

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

Convert the chain to another type or encoding.

A chain has no tangent of its own, because the tangent of a composition is not the sum of the tangents. A log= keyword therefore re-encodes the transformation that the chain reduces to, which is possible in three cases:

  • A chain that simplifies to a single transformation is converted as that transformation.
  • A change of coordinates [P, *X, P^-1] (see Sequence.sqrt) keeps its ends and re-encodes X, which is exact because the flow of a velocity commutes with a change of coordinates.
  • A chain of affine transformations is composed.

Any other chain raises a ConversionError before anything is computed. Without log=, the conversion follows Transformation.to, and so do copy=, on_loss= and on_error=. With log=, on_loss= and on_error= apply to the whole conversion of the chain.

to_numpy
to_numpy() -> ArrayProtocol

Return the data as a NumPy array, reading or computing them.

to_cupy
to_cupy(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a CuPy array on the GPU.

to_dask
to_dask(device: DeviceLike | None = None) -> ArrayProtocol

Return the data as a Dask array, without reading them.

as_numpy
as_numpy(*, inplace: bool = False) -> Self

Return the object with its data as NumPy arrays.

On an object read from a file, as_numpy(inplace=True) reads the file once and keeps its values.

Parameters:

Name Type Description Default
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_cupy
as_cupy(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as CuPy arrays on the GPU.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

as_dask
as_dask(
    device: str | int | None = None,
    *,
    inplace: bool = False,
) -> Self

Return the object with its data as Dask arrays.

Parameters:

Name Type Description Default
device str | int | None

The device, such as "cuda:0" or 0. By default, the backend supplies its device.

None
inplace bool

Whether this object holds the converted data and is returned.

False

Returns:

Type Description
object

An object of the same class.

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

Compute the transformation that results from the chain.

With mode=True, a chain of affine-like transformations yields an affine-like transformation, and a chain whose first applied element is a coordinate field yields a coordinate field. When the first applied element is affine-like but the chain contains other elements, the result is a sequence of two: the composition of the affine-like elements before the first other element, then the composition of everything from that element onward.

Parameters:

Name Type Description Default
mode ModeLike

Kinds to compose, as a name, a type or a list of them. True composes everything, and False only simplifies.

True
simplify SimplifyLike

Simplification policy applied before composition: "analytic" uses the type structure only, "numeric" also inspects the values of matrix transformations, {None: "numeric"} inspects the values of every transformation, and False, "none" or None disables simplification.

"analytic"
factor bool

Whether to rewrite the chain into a normal form organized by groups of axes, [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?]. The normal form starts with an optional grid and an optional projection that drops the inputs that nothing reads. It continues with one subspace factor for each group of axes that transform together, where each factor preserves its axes, and it ends with an optional permutation and an optional projection that creates the outputs that read no input. Nothing is composed across groups. The option is ignored with mode=False.

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

Simplify the transformation, without composing it unless asked.

t.simplify(policy, compute=mode) is t.compute(mode, simplify=policy). By default nothing is composed: no matrix is multiplied, no field is sampled and no lazy inverse is evaluated. Each concrete transformation is only converted to the cheapest type that still represents it, as far as policy can tell.

Parameters:

Name Type Description Default
policy SimplifyLike

How hard to simplify, with the values accepted by the simplify argument of compute.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed, with the values accepted by the mode argument of compute. The default, False, composes nothing, whereas None composes every kind.

False

Returns:

Type Description
Transformation

The simplified transformation.

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

Rewrite the chain as one factor per group of axes.

The axes of a chain often fall into groups that never interact, as when each axis is scaled on its own and two axes are then swapped. Factoring finds those groups and rewrites the chain as [grid?, delta?, F_1, ..., F_m, Pi_perm?, kappa?], with one axis-preserving factor F_i = Subspace(inner_i, A_i, A_i) per group, ordered by their first axis, and a permutation that carries each group to the axes that it occupies at the output (see [factor_sequence][brainhops.datamodel._transformations.compute.factor.factor_sequence]). The projection delta drops the inputs that no output reads, and the projection kappa creates the outputs that read no input, at their constant values. Nothing is composed across groups, so the coordinates of independent axes are never tiled into a grid over all of them, and each group can be resampled on its own.

The chain is unnested first, and a leading CartesianField is the sampling grid, which is kept as the same object. Every other element is cut into one piece per group, and an element that lies within a single group is kept as it is, so a lazy inverse stays lazy and still cancels with its forward transformation.

Note

The pass reads the chain as it stands, and it is idempotent. It declines a chain in which an element shifts or scales an output that reads no input, because it carries such a constant only through the elements that pass it through unchanged. compute with factor=True composes such a chain, and then simplifies and factors the result.

Parameters:

Name Type Description Default
policy SimplifyLike

How closely the elements may be read, with the values and the meaning of the policy of [simplify][]. Under the analytic policy, a matrix couples all its axes, and under the numeric policy, its exact zeros are read, so that an affine with independent axes splits.

"analytic"
compute ModeLike or bool or None

Kinds of transformation that may be composed inside a group, with the values accepted by the mode argument of compute. The default, False, composes nothing, so each factor holds the sub-chain of its own group, whereas True leaves each factor holding a single transformation.

False

Returns:

Type Description
Transformation

The normal form, or self when the chain is already in normal form or does not factor at all, as when it forms a single group and has neither end, its two ends differ in dimension in a way that the end projections do not explain, a grid sits inside it, or one of its elements cannot be read or restricted. An Identity is returned when no factor is left.

restrict
restrict(
    input_axes: AxisReferences,
    output_axes: AxisReferences,
    at: InputValues | None = None,
) -> Transformation

Return the transformation restricted to some of its axes.

A restriction keeps a part of a transformation, such as the spatial part of a map of space and time, or the map of one volume of a time series. It is lazy, like inverse. The result is a Sequence of three elements: a Projection that creates the inputs that input_axes leaves out, the transformation itself, and a projection that drops the outputs that output_axes leaves out. Nothing is computed until compute is called, and simplify then removes the axes that are not needed. When both sides keep every axis, the transformation itself is returned.

A removed input takes the value that at gives it, which selects the section of the transformation at that value. A removed input that at does not name is free, which means that the kept outputs must not read it. compute raises a RestrictionError when a kept output reads a free input, whereas restrict and simplify never raise for that reason. With one affine per volume of a time series, for example, the spatial outputs read the time axis, so the restriction to the spatial axes needs a value of time, which selects one volume.

Each side is a list of references, or a single reference. A reference is a position, the name of an axis, or any other query of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an axis class. It is resolved against the input or the output system of the transformation, as [AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict] resolves it, so a query never matches the unknown axes that the ... of an open system stands for. A name must designate exactly one axis, and any other query must designate at least one. Each side is a set of axes, so the order of the references does not matter: the kept axes stay in the order that they have in the transformation, and an axis must not be designated twice. Positions also work on a transformation without systems, or with open systems, provided that its numbers of axes are known, for example from the shape of its matrix. The systems of the result are the systems of the transformation restricted to the kept axes.

A subspace transformation, an instance of SubspaceTransformation, often does not know how many axes it passes through, which a restriction needs. When it is restricted to the axes that it acts on, however, the result is the transformation that it wraps, whatever that number is, and this result is returned. A subspace that lists its axes in another order than the full space gives the wrapped transformation between two permutations, which put its axes in the order of the full space. A geometry, an instance of Geometry, restricts its grid as well when it can, as its own method describes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
       [0., 3., 2.]])

Parameters:

Name Type Description Default
input_axes AxisQuery or iterable of (int or AxisQuery)

Input axes to keep, given by position, by name or by query.

required
output_axes AxisQuery or iterable of (int or AxisQuery)

Output axes to keep, given by position, by name or by query.

required
at mapping of (int or AxisQuery) to float

Values of some of the removed inputs. Each key designates input axes as an item of input_axes does, and every axis that it designates takes its value. NaN makes an input free, as leaving it out of at does.

None

Returns:

Type Description
Transformation

The lazy restriction, or the transformation itself when both sides keep every axis.

Raises:

Type Description
RestrictionError

If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown.

KeyError

If no axis has a name that a reference gives.

IndexError

If a position lies outside the axes of the transformation.

ValueError

If a query matches no axis, a name is shared by several axes, an axis is designated twice, or at gives a value to an input that is kept.

TypeError

If a reference is neither a position nor a query, or if at is not a mapping of real numbers.

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

Return the transformation composed with itself.

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

Parameters:

Name Type Description Default
compute bool

Whether to compute the square now rather than return the sequence.

False
**kwargs Any

Arguments passed to compute when compute is true.

{}

Returns:

Type Description
Transformation

The square.

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 the chain.

The chain is first simplified. A chain of the form [P, *X, P^-1] is a change of coordinates around X, and its square root is [P, sqrt(X), P^-1]. The chain has this form when its last element is the lazy inverse of its first element, or when its two ends are affine transformations whose product is exactly the identity. Any other chain is composed, and the square root of the result is returned.

Raises:

Type Description
DomainError

If the chain does not map a space onto itself, or if the square root of its reduced form is undefined (see DomainError).

NotImplementedError

If the chain is not a change of coordinates and does not compose to a single transformation.

is_kind
is_kind(kind: Type[Kind], compute: bool = False) -> bool

Return whether the transformation is of a given kind.

A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.

Parameters:

Name Type Description Default
kind type of Kind

Kind to test, from kinds.

required
compute bool

Whether to read the values of the parameters rather than only the structure of the types.

False

Returns:

Type Description
bool

Whether the transformation is of the kind.

is_identity
is_identity(compute: bool = False) -> bool

Return whether the transformation is the identity.

A transformation is the identity when its parameters are unset or when it is an Identity. With compute=True, the parameters of the matrix, vector and displacement types are inspected too.

A grid of coordinates (CartesianField) is the identity over itself. It is recognised as such with compute=True, but with compute=False only if its shape is unset, since a shape is a parameter. In neither case are the coordinates of the grid built. A grid that is the identity still defines where a sequence is sampled, so simplifying a sequence removes the grid only when it lies between two other transformations.

is_translation
is_translation(compute: bool = False) -> bool

Return whether the transformation is a translation.

A transformation is a translation when it is an instance of kinds.Translation or the identity. With compute=True, an affine matrix is checked for an identity linear part and a displacement field for a constant value.

is_scaling
is_scaling(compute: bool = False) -> bool

Return whether the transformation is a scaling.

A transformation is a scaling when it is an instance of kinds.Diagonal or the identity. With compute=True, a linear or affine matrix is checked to be diagonal.

is_permutation
is_permutation(compute: bool = False) -> bool

Return whether the transformation is a permutation.

A transformation is a permutation when it is an instance of kinds.Permutation or the identity. With compute=True, a linear or affine matrix is checked for a single one in each row and column.

is_rotation
is_rotation(compute: bool = False) -> bool

Return whether the transformation is a rotation.

A transformation is a rotation when it is an instance of kinds.SpecialOrthogonal or the identity. With compute=True, a linear or affine matrix is checked to be orthogonal with a positive determinant.

is_linear
is_linear(compute: bool = False) -> bool

Return whether the transformation is linear.

A transformation is linear when it is an instance of kinds.Linear or the identity. With compute=True, an affine matrix is checked for a zero translation.

is_affine
is_affine(compute: bool = False) -> bool

Return whether the transformation is affine.

A transformation is affine when it is an instance of kinds.Affine or the identity.

without
without(match: MatchLike) -> Transformation

Return the transformation with some parts replaced by the identity.

A caller uses this method to ignore a class of transformations, for example the displacement fields of a chain whose affine part it needs. Every part that the matcher selects becomes an Identity with the same input and output coordinate systems, so that the elements of a chain still connect and no bridge is guessed between them. The identities disappear when the result is computed.

The transformation is visited from the outside in. A selected node is replaced as a whole, and the method looks inside a sequence or an inverse only when the node itself is not selected. The inverse of a replaced part is replaced as well. The method does not look inside any other wrapper, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, so the matcher decides such a wrapper as a whole, and a part that it holds is not replaced on its own.

Parameters:

Name Type Description Default
match MatchLike

Parts to replace. A matcher is a kind or the name of a kind, such as "affine", a concrete class of transformation, a predicate that takes a transformation and returns a boolean, or a sequence of these values, which selects a part when any of its items selects it.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

with_only
with_only(match: MatchLike) -> Transformation

Return the transformation with only some parts kept.

This method is the complement of without: every part that the matcher does not select is replaced by an identity with the same coordinate systems. Because a kind can only describe the transformations that have a property, with_only("affine") is the way to remove everything that is not affine.

A node that the matcher selects is kept as a whole, so a chain that is affine as a whole is not split. The method looks inside a sequence or an inverse only when the node itself is not selected, and replaces any other node that is not selected. A wrapper other than a sequence or an inverse, such as a lazy square root (Sqrt), a Bijection or a SubspaceTransformation, is therefore kept or replaced as a whole, even when only a part that it holds is selected.

Parameters:

Name Type Description Default
match MatchLike

Parts to keep, in the same forms as for without.

required

Returns:

Type Description
Transformation

The filtered transformation, or the transformation itself when no part is replaced.

Raises:

Type Description
ValueError

If a part to replace changes the number of axes.

to_translation
to_translation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a translation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Translation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_scaling
to_scaling(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a scaling.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Scaling with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_permutation
to_permutation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a permutation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Permutation with to.

The result always has its data. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_rotation
to_rotation(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a rotation.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Rotation with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_linear
to_linear(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to a linear map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Linear with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

to_affine
to_affine(
    *,
    include: MatchLike | None = None,
    exclude: MatchLike | None = None,
    **kwargs,
) -> Transformation

Convert the transformation to an affine map.

The transformation is first filtered: the parts that include does not select are replaced by the identity, as by with_only(include), and then the parts that exclude selects are replaced, as by without(exclude). The filtered transformation is computed, because a chain must be composed before it can be converted, and the result is converted to a Affine with to.

The result always has its matrix. A result without it raises a ConversionError, because its dimension is unknown, as for an Identity(). Plain to makes no such check. The policy given as on_error= and on_loss= applies to the whole call, so that on_error=None returns None when the conversion fails.

For example, to_affine(on_error=None) returns None when the transformation is not affine, and to_affine(include="affine", on_error=None) returns the affine part of a chain whose other parts, such as fields, are dropped.

Parameters:

Name Type Description Default
include MatchLike

Parts to keep, as in with_only. By default, every part is kept.

None
exclude MatchLike

Parts to replace by the identity, as in without, after include is applied. By default, no part is replaced.

None
**kwargs Any

Keyword arguments of to, such as on_loss= and on_error=.

{}

Returns:

Type Description
Transformation

The converted transformation, or the value that the policy returns when the conversion fails.

bridge
bridge() -> Self

Reconcile the coordinate systems at every boundary of the chain.

Two neighbours in a chain share a coordinate system: the output system of one is the input system of the next. Where the two disagree, as when one works in millimetres and the next in voxels, or when the two name the same axes in a different order, a bridge is inserted between them. A bridge reads no parameter, so bridging costs nothing, and two opposite bridges cancel when the chain is simplified.

Bridging is also the only pass that lengthens a chain, which is why compute runs it before anything else: a bridge reads its neighbours, and a reversed array-index axis needs the extent of the adjacent grid, which composition may drop.

A nested sequence is bridged in place and stays nested, so a boundary that it hides is reconciled inside it. Call flatten afterwards for a flat chain. A sequence with a fixed shape, such as a geometry or a multiscale field, is left alone. A generic Inverse is replaced by the typed inverse of its forward transformation, so that the engine can compute it and cancellation can recognize it. No leaf has its endpoints rebuilt.

Returns:

Type Description
Sequence

The chain, with a bridge at each boundary that needed one.

Raises:

Type Description
AdaptationError

If a boundary cannot be bridged, because an axis that must be matched has no counterpart on the other side.

flatten
flatten(endpoints: bool = True) -> Self

Splice the nested sequences of the chain into the chain itself.

A chain whose elements are themselves chains applies exactly as the flat chain of their elements, so flattening changes nothing about what the transformation does. It is what lets the simplifier and the composers see two leaves as neighbours when a nesting boundary sits between them.

A nested child is asked to flatten itself, so a child with a shape of its own contributes what it chooses: a geometry contributes its grid and its transformation, and a multiscale field contributes the elements of its finest scale.

Parameters:

Name Type Description Default
endpoints bool

Whether to push the coordinate systems of the chain onto its first and last element, which is where the composers read them. A child with a shape of its own may contribute a sequence, so one level of nesting can survive this mode, and the next pass splices it. With endpoints=False, nesting is unwound all the way to the leaves in one pass, no leaf is rebuilt and each one stays the same object, so that a transformation still cancels with the lazy inverse that names it; a generic Inverse is then also replaced by the typed inverse of its forward transformation.

True

Returns:

Type Description
Sequence

The flattened chain.

consolidate
consolidate(
    *,
    inplace: bool = False,
    on_error: ErrorPolicy = UNSET,
    on_loss: ErrorAction = UNSET,
    **fields: Any,
) -> Self

Encode the object into the record that its file format writes.

An image, a transformation or the metadata of a file format holds the record of its file, such as the header of a NIfTI file, as it was read or as the object was last consolidated. When the object changes, the record no longer describes it, and the consolidation encodes the object into a copy of the record. Every write of the format consolidates the object first, and the method can also be called to see what a write would store. The options that each format takes, and the rules of its encoding, are those of the format.

What the record cannot hold, such as a field of the metadata that the format has no slot for, is reported as lost or approximated, and the error policy of the call decides what happens to the report: by default, the policy in effect warns (see metadata_loss_policy). A format that cannot encode the object at all raises a conversion error, to which the policy applies as well.

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

UNSET
**fields Any

Fields of the metadata to override before the encoding, by name, and the options of the format.

{}

Returns:

Type Description
Self

The consolidated copy, or this object with inplace=True, or the value that the policy returns in its place.

Raises:

Type Description
TypeError

If a keyword names neither a field of the metadata nor an option of the format.

MetadataLossError

If something is lost under the "raise" policy.

from_nibabel classmethod
from_nibabel(nifti: NiftiObject, **kwargs) -> Self

Build an object from a nibabel image or header.

The array of an image becomes rawdata, and a copy of its header becomes the record of the metadata. A header alone gives an object without an array. The array proxy of an image that nibabel read from a file is replaced by the lazy array that from_filename builds for that file, and any other array is kept as it is.

Parameters:

Name Type Description Default
nifti Nifti1Image or Nifti1Header

The nibabel image or header. NIfTI-2 images and headers are accepted too.

required
**kwargs Any

Other fields of the object.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
TypeError

If nifti is neither a NIfTI image nor a NIfTI header.

to_image
to_image() -> Any

Return the image that a file of this transformation holds.

The transformation is consolidated into a copy, as by [consolidate][], and the stored image of that copy is returned. The transformation itself is not changed.

Returns:

Type Description
Any

The image, of the class that IMAGE names, without pending data or transformations.

data
data() -> ArrayProtocol | None

The stored vectors as an (X, Y, Z, 3) array.

Vectors that are assigned are returned as they are, and stay pending until [consolidate][] or a write encodes them. Otherwise they are decoded from rawdata: NIfTI stores the field with shape (X, Y, Z, 1, 3), and the singleton axis is dropped. A file whose fourth axis is longer than one holds a field per volume, which is not supported yet, so reading its data raises ParserContentError. The vectors are the RAS displacements of the file, or its velocity with log. Assigning the data drops the chain decoded from the previous data.

from_image classmethod
from_image(image: NiftiImage, **options: Any) -> Self

Build a displacement field from the image that stores it.

The readers call this method, so the encoding options that they are given are checked here: steps is the number of squaring steps of a velocity, so it is refused without log.

Parameters:

Name Type Description Default
image NiftiImage

The image, which is consolidated first if it has pending data or transformations.

required
**options Any

The encoding options log and steps, and the other fields of the field.

{}

Returns:

Type Description
NiftiRASDisplacementField

The field.

Raises:

Type Description
TypeError

If the image is not a NiftiImage, or if steps is given without log.

score_header classmethod
score_header(header: NiftiObject) -> float

Score a header as a field of RAS displacements.

Only a DISPVECT image (1006) is claimed, with Confidence.CERTAIN. Other images may hold coordinates and are left to NiftiRASCoordinateField.

input
input() -> CoordinateSystem | None

The anatomical space that the field maps from, in RAS millimetres.

output
output() -> CoordinateSystem | None

The anatomical space that the field maps to, in RAS millimetres.

transformations
transformations() -> tuple[Transformation, ...]

The chain of transformations that the field encodes.

The chain is built lazily from the header and the data, and then cached. Assigning a chain overrides the derived one, which is how fields that do not come from a file are built. Since the slots name fixed positions, a copy with other slots is made with replace rather than by editing the chain in place.

to_nibabel
to_nibabel(
    like: Any = None, log: bool | None = None, **overrides
) -> Nifti1Image | Nifti2Image

Build the nibabel image of the displacement field.

The field is consolidated with the options, as by [consolidate][], into a copy, and the nibabel image holds the rawdata array and the header of that copy. The field itself is not changed.

Parameters:

Name Type Description Default
like path, nibabel image or header, or NIfTI object

Template whose header fields that do not encode the transformation are copied.

None
log bool

Whether to write the velocity rather than the displacements. It defaults to the log option of the field.

None
**overrides Any

Header fields that take precedence over the derived values and like.

{}

Returns:

Type Description
Nifti1Image or Nifti2Image

The encoded image.