Skip to content

brainhops.io.common.mrtrix

Reading and writing of MRtrix images.

This module holds what the MRtrix formats share: the header, and the decoding and encoding of voxel data. An MRtrix image is a text header followed by raw voxel values, either in one file (.mif, or .mif.gz gzipped) or in two (a .mih header and the data file it names). The header is a list of key: value lines between mrtrix image and END, where # starts a comment:

mrtrix image
dim: 64,64,32,7
vox: 2,2,2.5,nan
layout: -0,-1,+2,+3
datatype: Float32LE
transform: 0.996, 0.087, 0, -61.2
transform: -0.087, 0.996, 0, -70.5
transform: 0, 0, 1, -40
scaling: 0,1
dw_scheme: 0,0,1,0
dw_scheme: 0,1,0,1000
file: . 552
END

layout gives the storage rank and direction of each axis (see [parse_layout][]). transform maps voxel coordinates multiplied by the voxel sizes, not voxel indices, to scanner RAS millimetres; without one, MRtrix centres the field of view on the origin rather than assuming the identity. scaling gives offset,scale, by which a stored value v means offset + scale * v. file names the data file and an offset, where . means the header file itself. The conventions follow the MRtrix3 sources.

The header is held as an MrtrixRaw record, and MrtrixMetadata reads and writes that record without the voxels. MrtrixImage holds such metadata and a lazy array of the voxels. The record keeps the bytes of the header as well as its keys, so that an image that is read and written again without changes keeps its bytes.

Classes

MrtrixMetadata magic

MrtrixMetadata(
    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[MrtrixRaw | None] = None,
    *,
    extra: dict[str, Any] = Factory(),
)

Bases: MetadataReader, BinaryFileWriter, MetadataFormat

Metadata of an MRtrix image, which is its header.

The metadata of an MRtrix image is its header, held as an MrtrixRaw record. MrtrixImage uses that record as the base of the header that it writes. Reading the metadata never reads the voxels, and a file cut after its header can still be read. The metadata keeps no open file.

A file is read through the record: [from_fileobj][] reads an MrtrixRaw and wraps it. Writing the metadata writes the header alone, as the file stores it, up to the first voxel of a single-file image.

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[MrtrixRaw | None]

The record of the image, 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, ...] = ()

The fields of the metadata that the format can store.

The names are those of the vocabulary, and "extra" when the format has a free-form store. A field that is not listed is decoded as None, and its value is reported as lost when the metadata is consolidated. A conversion into the format reads this list to report a lower bound of what a write would lose. The base class lists no field.

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

The record of the image, 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
derive
derive(
    operation: Indexed | Resampled | None = None,
    *,
    history: str | Sequence[str] | None = None,
) -> Self

Return the metadata of an image computed from this one.

The fields follow Metadata.derive, which records the derivation in history and generated_by. Those two fields keep their value when the format has no slot for them, so that a derived image of the format is not reported to lose a provenance that only the derivation added.

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
MetadataFormat

New metadata, of the same class, which shares the record.

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_raw classmethod
from_raw(raw: Any, **kwargs) -> Self

Build the metadata that holds a record.

A reader calls this method once it has parsed the header of a file. The record is held as it is given, without a copy. The format decodes the fields of the vocabulary from the record here, and the base class, which knows no record, decodes none.

Parameters:

Name Type Description Default
raw object

The header of a file, in the representation of the format.

required
**kwargs Any

Other fields of the metadata, which take precedence over the decoded values.

{}

Returns:

Type Description
MetadataFormat

The metadata.

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.

to_bytes
to_bytes(**kwargs) -> bytes

Return the header of the record as the file stores it.

Metadata without a record is written as an empty header.

Parameters:

Name Type Description Default
**kwargs Any

Options of MrtrixRaw.to_bytes.

{}

Returns:

Type Description
bytes

The header.

MrtrixRaw

MrtrixRaw(
    dim: Sequence[int] = (),
    vox: Sequence[float] | None = None,
    layout: Sequence[int] | None = None,
    datatype: str = "Float32LE",
    transform: Any | None = None,
    scaling: Sequence[float] | None = None,
    file: tuple[str, int] | None = None,
    keyval: Mapping[str, str] | None = None,
    stored: bytes | None = None,
)

Bases: BinaryFileReader, BinaryFileWriter

The header of an MRtrix image, as the file stores it.

An MRtrix image is a text header followed by the voxel values, in one file (.mif, or .mif.gz gzipped) or in two (a .mih header and the data file that it names). The record holds the header: the keys that describe the voxels and the geometry as attributes, and every other key in keyval, in order and with the lines of a repeated key joined by newlines. It also keeps the bytes that the header was read from, so that a header that is read and written again keeps its bytes.

The record knows where the voxels lie and how they are stored, but it never reads them. It is held by MrtrixMetadata, which never changes it in place: a writer works on the copy that copy returns. Two records are equal when they format to the same text.

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.

dim instance-attribute
dim = tuple(int(d) for d in dim)

The size of each axis.

vox instance-attribute
vox = tuple(float(v) for v in vox)

The voxel size of each axis, as stored (possibly fewer entries than axes, possibly nan).

layout instance-attribute
layout = tuple(int(s) for s in layout)

The signed one-based symbolic strides (see parse_layout).

datatype instance-attribute
datatype = str(datatype)

The MRtrix data type, as spelled in the header.

transform instance-attribute
transform = transform

The (3, 4) stored transform, or None when there is none.

scaling instance-attribute
scaling = scaling

(offset, scale), or None when there is none.

file instance-attribute
file = file

(name, offset) of the data, or None when not known.

keyval instance-attribute
keyval = OrderedDict(keyval or {})

Every other key, with its lines joined by newlines.

stored instance-attribute
stored = stored

The bytes that the header was read from, or None.

For a single-file image, the bytes run from the start of the file to the first voxel, padding included. They are written back as they are while they still describe the record, whichever program wrote them, and the record is formatted as the writer spells it otherwise.

ndim property
ndim: int

The number of axes.

dtype property
dtype: dtype | None

The NumPy dtype of the stored values, or None for Bit.

is_bit property
is_bit: bool

Whether the values are packed bits.

count property
count: int

The number of voxels.

nbytes property
nbytes: int

The number of bytes the voxel data take in the file.

spacing property
spacing: tuple[float, ...]

The voxel size of each axis, as MRtrix uses it.

Missing sizes are nan, and a non-finite spatial size is replaced by the mean of the finite ones (or 1).

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

default_transform
default_transform() -> ndarray

Return the (3, 4) transform MRtrix assumes when the header has none.

The rotation is the identity, and the field of view is centred on the origin.

Returns:

Type Description
array, shape `(3, 4)`

The rotation and the translation, in millimetres.

voxel_to_scanner
voxel_to_scanner() -> ndarray

Return the (4, 4) matrix from voxel indices to scanner RAS.

The matrix is transform @ diag(vox[0], vox[1], vox[2], 1), with default_transform replacing a missing or non-finite transform.

Returns:

Type Description
array, shape `(4, 4)`

The homogeneous matrix.

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

Parse the header lines from mrtrix image to END.

Lines after END are ignored. Detached headers may end at EOF.

Parameters:

Name Type Description Default
lines iterable of str

The lines of the header, without their line breaks.

required
**kwargs Any

Ignored.

{}

Returns:

Type Description
MrtrixRaw

The record.

Raises:

Type Description
ParserContentError

If the first line is wrong, if dim, vox or datatype is missing, if an embedded header has no END, or if an entry is malformed.

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

Parse a header from text.

Parameters:

Name Type Description Default
text str

The text of the header.

required
**kwargs Any

Refused, since the record has no option.

{}

Returns:

Type Description
MrtrixRaw

The record.

Raises:

Type Description
TypeError

If an option is given, since the record has none.

ParserContentError

If the text is not an MRtrix header.

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

Read the header of an MRtrix stream, gzipped or not.

The voxels are not read. The header of a single-file image is read up to the first voxel, so that its padding is kept, and the position of the stream is restored. The record has no options.

Parameters:

Name Type Description Default
file file object

The stream, open in binary mode.

required
**kwargs Any

Refused, since the record has no option.

{}

Returns:

Type Description
MrtrixRaw

The record.

Raises:

Type Description
TypeError

If an option is given.

ParserContentError

If the stream does not hold an MRtrix header.

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

Return the confidence that a stream holds an MRtrix header.

The stream may be gzipped, 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 header. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Ignored.

{}

Returns:

Type Description
float

Confidence.LIKELY or Confidence.NO.

Raises:

Type Description
SnifferContentError

If the stream holds no header and error is True.

to_bytes
to_bytes(**kwargs) -> bytes

Return the header as the file stores it.

The bytes that the header was read from are returned while they still describe the record. Otherwise, the header of a single-file image is padded up to its first voxel by embedded, and any other header is its text.

Parameters:

Name Type Description Default
**kwargs Any

Ignored.

{}

Returns:

Type Description
bytes

The header.

to_lines
to_lines(
    file: tuple[str, int | None] | None = None,
) -> list[str]

Return the header lines, from mrtrix image to END.

The file argument, which defaults to the file of the header, is the (name, offset) of the file: line; an offset of None is omitted.

Parameters:

Name Type Description Default
file tuple of str and int

The name of the data file and the offset of the data in it.

None

Returns:

Type Description
list of str

The lines, without their line breaks.

to_text
to_text(*args, **kwargs) -> str

Return the header text, terminated by a newline.

Parameters:

Name Type Description Default
*args Any

The arguments of to_lines.

()
**kwargs Any

The arguments of to_lines.

{}

Returns:

Type Description
str

The text of the header.

embedded
embedded(align: int = 4) -> bytes

Return the header of a single-file image, padded up to its data.

The data offset is aligned on align bytes. Since the offset is part of the header it measures, it is found by iteration.

Parameters:

Name Type Description Default
align int

The alignment of the data offset, in bytes.

4

Returns:

Type Description
bytes

The header, padded with zeros up to the data offset.

copy
copy() -> MrtrixRaw

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

The bytes that the header was read from are kept, since to_bytes writes them only while they still describe the record.

Returns:

Type Description
MrtrixRaw

The copy.