Skip to content

Metadata for format authors

The public names of brainhops.datamodel.metadata and brainhops.io.metadata are those that a user of the library needs. The names below are for whoever adds the vocabulary to the metadata of a file format, and the format author's guide explains how they fit together. They are imported from the private modules that define them.

brainhops.datamodel.metadata._vocabulary

The common vocabulary: its scopes, its annotations and its groups.

Attributes

GROUPS module-attribute

GROUPS: dict[type, tuple[str, ...]] = {
    group: tuple(field.name for field in fields(group))
    for group in (
        ProvenanceVocabulary,
        MRIVocabulary,
        DiffusionVocabulary,
        DisplayVocabulary,
        StorageVocabulary,
        MicroscopyVocabulary,
        TransformVocabulary,
    )
}

Each vocabulary group class, and the names of its fields.

VOCABULARY module-attribute

VOCABULARY: tuple[str, ...] = tuple(
    itertools.chain.from_iterable(GROUPS.values())
)

The names of the common vocabulary fields, group by group. extra is not one (it is the free-form store next to them). bagof lists the fields of a class with several bases in reverse MRO order, so this is the order to iterate in, never fields(Metadata).

FIELDS module-attribute

FIELDS: tuple[str, ...] = ('extra',) + VOCABULARY

The fields of the metadata: extra, then the vocabulary. They are the names that consolidate takes as overrides, in the order reports list them.

BIDS_KEYS module-attribute

BIDS_KEYS: dict[str, str] = {
    field.name: field.metadata["bids"]
    for group in GROUPS
    for field in fields(group)
    if "bids" in (field.metadata or {})
}

The BIDS sidecar key of each vocabulary field that BIDS has a key for, as Bids(...) declares it.

SCOPES module-attribute

SCOPES: dict[str, Scope] = {
    field.name: (field.metadata or {}).get(
        "scope", Scope.FILE
    )
    for group in GROUPS
    for field in fields(group)
}

The propagation scope of each vocabulary field (Scoped or Along).

ALONG module-attribute

ALONG: dict[str, AxisType] = {
    field.name: field.metadata["along"]
    for group in GROUPS
    for field in fields(group)
    if "along" in (field.metadata or {})
}

The type of the axis that the entries of each field in the AXIS scope run along, as Along declares it.

Classes

Scope

Bases: StrEnum

How a vocabulary field propagates when an image is derived from another one (see Metadata.derive).

Member

Value

Meaning

FILE

"file"

The field is about the file or
about the data as a whole. It
is kept.

ACQUISITION


"acquisition"


The field describes the
acquisition, and does not
change under a resampling. It
is kept.

SPATIAL


"spatial"


The field is tied to the
spatial sampling. It is cleared
when the spatial axes change,
or mapped along with them.

AXIS





"axis"





The field has one entry per
index along one non-spatial
axis (see Along). It is
indexed when that axis changes,
and cleared when the values
along that axis are
re-expressed in another frame.

VALUES





"values"





The field describes the values
of the data, such as their unit
or their display range. It is
kept when the values are moved
or resampled, and cleared when
they are re-expressed in
another frame.

Bids

Bids(key: str)

Bases: Field

The annotation that gives a vocabulary field its BIDS sidecar key.

The key lands in the metadata of the field, under "bids", where the sidecar codec reads it.

Examples:

repetition_time: tx.Annotated[
    tx.Optional[float], Bids("RepetitionTime")
] = None

Parameters:

Name Type Description Default
key str

The BIDS key, such as "RepetitionTime".

required

Methods:

Scoped

Scoped(scope: Scope | str)

Bases: Field

The annotation that gives a vocabulary field its Scope.

The scope lands in the metadata of the field, under "scope". A field without a scope is in the FILE scope. A field in the AXIS scope is declared with Along instead, which also names its axis.

Examples:

echo_time: tx.Annotated[
    tx.Optional[float], Scoped(Scope.ACQUISITION)
] = None

Parameters:

Name Type Description Default
scope Scope or str

The scope of the field.

required

Raises:

Type Description
ValueError

If scope is not a scope, or is AXIS (use Along).

Methods:

Along

Along(axis: AxisType | str)

Bases: Field

The annotation of a vocabulary field that has one entry per index along one non-spatial axis of an image.

The field is in the AXIS scope, and its entries run along the axes of the given type. NIfTI and OME-Zarr both map their time and channel dimensions to brainhops axis types, so the b-values of a diffusion image run along the time axis (NIfTI dimension 4), and the descriptions of the channels run along the channel axis.

The axis type lands in the metadata of the field, under "along", next to the scope.

Examples:

channels: tx.Annotated[
    tx.Optional[tx.Tuple[Channel, ...]], Along(AxisType.channel)
] = None

Parameters:

Name Type Description Default
axis AxisType or str

The type of the axis the entries run along. It cannot be space: a field tied to the spatial axes is in the SPATIAL scope.

required

Raises:

Type Description
ValueError

If axis is not an axis type, or is space.

Methods:

Vocabulary

Bases: DataModelBase

The base class of the vocabulary groups.

A vocabulary group declares a few fields of the common vocabulary, and nothing else. Metadata inherits every group, and so does the metadata of every file format, so that each group is one page of the documentation with the fields of one topic. A group is not meant to be instantiated. The groups convert their fields (convert=True), and hide from repr a field that holds None, because the fields of a base class keep the options of the class that declares them.

Methods:

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.

ProvenanceVocabulary magic

ProvenanceVocabulary(
    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,
)

Bases: Vocabulary

Vocabulary group: what the data is and where it comes from (file scope). Not meant to be instantiated; see Metadata.

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

Attributes

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

Methods:

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.

MRIVocabulary magic

MRIVocabulary(
    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,
)

Bases: Vocabulary

Vocabulary group: MRI acquisition parameters. They are in the ACQUISITION scope, except the encoding directions and the slice timing, which are tied to the spatial sampling (SPATIAL scope). Not meant to be instantiated; see Metadata.

Parameters:

Name Type Description Default
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

Attributes

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.

Methods:

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.

DiffusionVocabulary magic

DiffusionVocabulary(
    bvalues: tuple[float, ...] | None = None,
    bvectors: tuple[tuple[float, float, float], ...]
    | None = None,
)

Bases: Vocabulary

Vocabulary group: the diffusion gradient table, one entry per index along the time axis (AXIS scope). BIDS stores it in .bval and .bvec files, not in the sidecar. Not meant to be instantiated; see Metadata.

Parameters:

Name Type Description Default
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

Attributes

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

Methods:

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.

DisplayVocabulary magic

DisplayVocabulary(
    display_range: tuple[float, float] | None = None,
    channels: tuple[Channel, ...] | None = None,
    data_unit: Unit | str | None = None,
)

Bases: Vocabulary

Vocabulary group: how the values are shown and what they are. The channels run along the channel axis (AXIS scope); the display range and the unit apply to every value (VALUES scope). Not meant to be instantiated; see Metadata.

Parameters:

Name Type Description Default
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

Attributes

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.

Methods:

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.

StorageVocabulary magic

StorageVocabulary(
    dtype: dtype | None = None,
    scale_slope: float | None = None,
    scale_intercept: float | None = None,
)

Bases: Vocabulary

Vocabulary group: how the values of the data are stored in the file (values scope). Not meant to be instantiated; see Metadata.

The loaded array always holds the values themselves. A file that stores integers with an intensity scaling (NIfTI scl_slope and scl_inter) loads as floating-point values, which are stored * scale_slope + scale_intercept. When an image is written, its values are stored as dtype, so that a label map read as uint8 is written as uint8 again, even after a computation that gave int64 values. An override given to save or to consolidate takes precedence over dtype, and the type of the data is used only when neither is given.

Parameters:

Name Type Description Default
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

Attributes

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.

Methods:

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.

MicroscopyVocabulary magic

MicroscopyVocabulary(
    objective_magnification: float | None = None,
    objective_numerical_aperture: float | None = None,
    illumination_type: IlluminationType | str | None = None,
    contrast_method: ContrastMethod | str | None = None,
)

Bases: Vocabulary

Vocabulary group: microscopy acquisition (acquisition scope). Not meant to be instantiated; see Metadata.

Parameters:

Name Type Description Default
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

Attributes

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

Methods:

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.

TransformVocabulary magic

TransformVocabulary(
    moving: str | None = None,
    fixed: str | None = None,
    input_space: SpaceEnum | str | None = None,
    output_space: SpaceEnum | str | None = None,
)

Bases: Vocabulary

Vocabulary group: what a transformation relates (file scope). Not meant to be instantiated; see Metadata.

Parameters:

Name Type Description Default
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

Attributes

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.

Methods:

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.

brainhops.datamodel.metadata._derive

What an image operation did to the axes of an image, and how each field of the metadata follows it.

An image operation that changes axes or values describes what it did with one of three records: image[index] builds an Indexed, image.reslice(...) builds a Resampled, and image.reframe(...) builds a Reframed. The image hands the record to Metadata.derive, which applies the rule of the scope of each field, in one loop. The functions of this module are the steps of that loop that need a computation: the entries of a field along an axis, and an encoding direction mapped through the voxels.

This module imports neither the transformations nor the geometry at the top, because the transformations import the metadata. The two computations that need them import them when they run.

Classes

Indexed magic

Indexed(
    index: tuple,
    shape: tuple[int, ...],
    system: CoordinateSystem | None = None,
)

Bases: DataModelBase

An image indexed as its data array is, image[index].

The image builds this record and passes it to Metadata.derive. The index is expanded once, on construction, into one component per axis of the data (expanded), and the type of each voxel axis is read from the coordinate system (axes).

Parameters:

Name Type Description Default
index tuple

The full index, as given to image[index].

required
shape tuple[int, ...]

The shape of the indexed image.

required
system CoordinateSystem | None

The coordinate system of the voxels of the image (the input of its grid), which gives the type of each axis; None when it is not known.

None

Attributes

index instance-attribute
index: Annotated[tuple, Field(convert=False)]

The full index, as given to image[index].

shape instance-attribute
shape: tuple[int, ...]

The shape of the indexed image.

system class-attribute instance-attribute
system: Annotated[
    CoordinateSystem | None, Field(convert=False)
] = None

The coordinate system of the voxels of the image (the input of its grid), which gives the type of each axis; None when it is not known.

expanded property
expanded: tuple[Any, ...]

The index, with its ... replaced by full slices and filled.

axes property
axes: tuple[AxisType | None, ...]

The type of each axis of the image, None where it is not known.

moves_space property
moves_space: bool

Whether the index changes a spatial axis, or an axis of unknown type, or moves one to another position (an integer or a None before it).

voxel_map property
voxel_map: ndarray | None

The linear part of the map from the old voxels to the new ones, with a zero column for each axis an integer dropped, or None for an index other than integers, slices and None.

Methods:

positions
positions(axis: AxisType) -> ndarray | None

Return the positions that the index keeps along an axis of a type.

Parameters:

Name Type Description Default
axis AxisType

The type of the axis. When the image has several axes of this type, the first one is read.

required

Returns:

Type Description
ndarray or None

The kept positions, in order: the full range when the axis is untouched. None when the index drops the axis (an integer), when it keeps a selection that is not 1-D, when it is out of the range of the axis, or when the image has no axis of this type.

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.

Resampled magic

Resampled(
    transformation: Transformation = Field(convert=False),
    geometry: Geometry | None = Field(
        default=None, convert=False
    ),
)

Bases: DataModelBase

An image resampled onto a new geometry, image.reslice(geometry).

The image builds this record and passes it to Metadata.derive.

Parameters:

Name Type Description Default
transformation Transformation

The map from the new voxel coordinates to the old ones, without the grid of the new geometry.

Field(convert=False)
geometry Geometry | None

The geometry the image is resampled onto, or None when it is not known (a level of a pyramid, whose shape is not known until its data is read).

Field(default=None, convert=False)

Attributes

transformation class-attribute instance-attribute
transformation: Transformation = Field(convert=False)

The map from the new voxel coordinates to the old ones, without the grid of the new geometry.

geometry class-attribute instance-attribute
geometry: Geometry | None = Field(
    default=None, convert=False
)

The geometry the image is resampled onto, or None when it is not known (a level of a pyramid, whose shape is not known until its data is read).

moves_space property
moves_space: bool

Always True, because a resampling moves the spatial axes.

voxel_map property
voxel_map: ndarray | None

The linear part of the inverse of transformation, from the old voxels to the new ones, or None when it does not reduce to an affine.

Methods:

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.

Reframed magic

Reframed(axes: tuple[AxisType, ...] = ())

Bases: DataModelBase

The values of an image re-expressed in another frame, image.reframe(...).

The entries along a component axis (a point, vector, displacement, coordinate or tensor axis) are the components of one vector or tensor, and the image re-expressed them in another coordinate system. No voxel moves, but the numbers in the data change, so the fields that describe the values (the VALUES scope) no longer apply. Neither do the fields with one entry per index along a re-expressed axis, which described the components in the old frame and which may no longer match the length of the axis, because a tensor stored with only some of its components is stored with all of them afterwards. The image builds this record and passes it to Metadata.derive.

Parameters:

Name Type Description Default
axes tuple[AxisType, ...]

The type of each axis whose values were re-expressed.

()

Attributes

axes class-attribute instance-attribute
axes: tuple[AxisType, ...] = ()

The type of each axis whose values were re-expressed.

moves_space property
moves_space: bool

Always False, because no voxel moves.

Methods:

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.

brainhops.datamodel.metadata._report

Loss reports, and the loss policy.

Attributes

LossPolicy module-attribute

LossPolicy: TypeAlias = Literal['ignore', 'warn', 'raise']

A loss policy: ignore a loss, warn about it, or raise. Each of the three values is also an action of an error policy (see ErrorPolicy).

OnLoss module-attribute

The values that the on_loss= argument of the metadata methods took before it became the loss half of an error policy: a LossPolicy, or a ConversionReport to fill with what is lost, instead of warning or raising. These values are still actions of an error policy, and on_loss= now takes any action (see ErrorPolicy).

Classes

ConversionReport magic

ConversionReport(
    source: str | None = None,
    target: str | None = None,
    lost: dict[str, Any] = Factory(),
    approximated: dict[str, str] = Factory(),
    errors: list[Exception] = Factory(),
)

Bases: DataModelBase

The record of what a conversion or a consolidation could not carry over.

Consolidating the metadata of a file format, which every write of that format does, fills a report with what the format could not store: a field whose value was dropped is listed in lost, with the value, and a field whose value was stored, but not exactly, is listed in approximated, with a short description of the change (such as "truncated to 80 bytes"). A conversion into the metadata of a format fills a report with the fields that the format declares no slot for, which is a lower bound of what a write loses.

A report is also an action of an error policy (see ErrorPolicy), so that it can record what any conversion loses. A conversion given on_loss=report, or a policy that maps an exception class to the report, records each error that the policy catches with record and returns its result: a loss of metadata adds its fields to lost and approximated, and any other error, such as the LossyConversionError of a transformation, is appended to errors.

The loss policy decides what happens to a report that is not empty (see metadata_loss_policy).

Parameters:

Name Type Description Default
source str | None

The format converted from.

None
target str | None

The format converted to.

None
lost dict[str, Any]

The value that was dropped, for each field name.

Factory()
approximated dict[str, str]

What changed in the stored value, for each field name.

Factory()
errors list[Exception]

The errors recorded by an error policy, other than losses of metadata.

Factory()

Attributes

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

The format converted from.

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

The format converted to.

lost class-attribute instance-attribute
lost: dict[str, Any] = Factory()

The value that was dropped, for each field name.

approximated class-attribute instance-attribute
approximated: dict[str, str] = Factory()

What changed in the stored value, for each field name.

errors class-attribute instance-attribute
errors: list[Exception] = Factory()

The errors recorded by an error policy, other than losses of metadata.

lossy property
lossy: bool

Whether the report lists a field as lost or approximated, or records a lossy conversion.

Methods:

merge
merge(other: Self) -> Self

Add the entries of another report to this report, in place.

Parameters:

Name Type Description Default
other ConversionReport

The report whose entries are added. An entry of other replaces the entry of this report for the same field, and the errors of other are appended to those of this report.

required

Returns:

Type Description
ConversionReport

This report.

record
record(error: Exception) -> Self

Add an error that an error policy caught to this report.

A MetadataLossError adds the entries of its own report, as merge adds them, and gives this report its source and target when it has none yet. Any other error is appended to errors.

Parameters:

Name Type Description Default
error Exception

The error to record.

required

Returns:

Type Description
ConversionReport

This report.

raise_if_lossy
raise_if_lossy() -> None

Raise an error when anything was lost or approximated.

Raises:

Type Description
MetadataLossError

If the report lists a field as lost or approximated.

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.

MetadataLossWarning

MetadataLossWarning(report: ConversionReport)

Bases: ConversionWarning

The warning issued when some metadata could not be carried over.

The report attribute holds the ConversionReport that says what was lost or approximated.

Parameters:

Name Type Description Default
report ConversionReport

What was lost or approximated.

required

Methods:

MetadataLossError

MetadataLossError(
    report: ConversionReport,
    *,
    result: DataModelBase | None = None,
)

Bases: LossyConversionError

The error raised, under the "raise" policy, when some metadata could not be carried over.

The report attribute holds the ConversionReport that says what was lost or approximated. The error is a LossyConversionError, so that on_loss= and on_error= treat a loss of metadata as they treat any other loss (see ErrorPolicy). It is therefore also a TypeError. The field converters of the data model turn a TypeError into a conversion error of their own, but they let a LossyConversionError through unchanged, so that a refused loss surfaces as itself.

The metadata methods raise the error before they build their result, so its result attribute is usually None.

Parameters:

Name Type Description Default
report ConversionReport

What was lost or approximated.

required
result DataModelBase

The object that the conversion would have returned, when it is known.

None

Methods:

Functions:

metadata_loss_policy

metadata_loss_policy(policy: OnLoss) -> Iterator[None]

Set the loss policy of the conversions and writes made in a block.

The policy in effect governs every conversion and every consolidation that takes no on_error= argument, or one that has no entry for a loss of metadata, in particular the implicit conversions that field converters trigger. Outside of any block, the policy is "warn". A report given as the policy collects what the block loses, and nothing is warned or raised, so that a caller such as io.save, which converts an object and then writes it, acts once on one report.

Parameters:

Name Type Description Default
policy (ignore, warn, 'raise')

The policy: ignore a loss, warn about it, or raise MetadataLossError, or a report to fill.

"ignore"

Yields:

Type Description
None

Raises:

Type Description
ValueError

If policy is not one of the three policies.

Examples:

with metadata_loss_policy("raise"):
    # Raises if MGH has no slot for a field that is set.
    mgh = metadata.to(MghMetadata)

apply_loss_policy

apply_loss_policy(
    report: ConversionReport, *, stacklevel: int = 2
) -> ConversionReport

Act on a report, according to the loss policy in effect.

The body of a conversion or of a consolidation calls this function with the report of what it could not carry over. The action is the policy in effect (see metadata_loss_policy), which the call that received on_error= and on_loss= sets while its body runs (see call_under_policy). Under the "ignore" action nothing happens, under "warn" a MetadataLossWarning is issued, and under "raise" a MetadataLossError is raised, which that call hands to its policy. A report that lists nothing as lost or approximated is silent under every action.

When the action is itself a report, the entries of report are added to it, whether anything was lost or not, and nothing is warned or raised: the caller acts on the report it passed. Its source and target are set from report when it has none yet.

Parameters:

Name Type Description Default
report ConversionReport

The report to act on.

required
stacklevel int

The lowest stack level of the warning, counted from the caller of this function. The warning points at the first frame at or above it that is outside brainhops, which is the code that called the conversion.

2

Returns:

Type Description
ConversionReport

report itself.

Raises:

Type Description
MetadataLossError

If the action is "raise" and the report is lossy.

call_under_policy

call_under_policy(
    call: Callable[[], Any],
    on_error: ErrorPolicy = UNSET,
    *,
    on_loss: ErrorAction = UNSET,
    scope: tuple[
        Type[BaseException], ...
    ] = _CONVERSION_ERRORS,
    stacklevel: int = 2,
) -> Any

Call a conversion, and apply an error policy to what it raises.

Every method that takes on_error= and on_loss= applies them with this function, and passes no policy on to the calls that its body makes. The function merges the two keywords into one policy, in which a single action of on_error applies to the classes of scope (see ErrorPolicy). While call runs, the action that the policy takes for a loss of metadata becomes the policy in effect (see metadata_loss_policy), so that every consolidation and every conversion of metadata that call makes follows it, and acts on what it loses with apply_loss_policy. An action that the body can take where the loss happens, which is "ignore", "warn", "raise" or a report, is set as it is. Any other action, such as a value to return or an exception to raise, is set as "raise", so that the body raises a MetadataLossError. An error that call raises is then handed to the policy, which raises it unchanged unless the policy has an entry for it, and the value that the policy returns takes the place of the result.

A call with no policy calls call as it is, under the policy in effect. A method called without on_error= and on_loss= from the body of another one therefore follows the policy of the outer call, and only the outermost call returns a value in place of a result.

Parameters:

Name Type Description Default
call callable

The conversion, called without arguments.

required
on_error ErrorPolicy

The policy. By default, every error is raised, and a loss of metadata follows the policy in effect.

UNSET
on_loss ErrorAction

The action for a loss. The policy that the call applies is {LossyConversionError: on_loss, **on_error}, so that an entry for a loss in on_error takes precedence over on_loss.

UNSET
scope tuple of type

The exception classes that call raises on purpose, to which a single action of on_error applies.

(ConversionError,)
stacklevel int

The lowest stack level of a warning, counted from the caller of this function. The warning points at the first frame at or above it that is outside brainhops.

2

Returns:

Type Description
Any

What call returns, or what the policy returns in its place.

takes_error_policy

takes_error_policy(method: Callable) -> Callable

Give a method the keywords on_error= and on_loss= of a policy.

The writers of the file formats use this decorator. It is written above each entry point of a writer, such as to_bytes or save, both in their common base, WriterMixin, and in each format that defines or overrides one. The wrapper removes on_error= and on_loss= from the keyword arguments and calls the method with call_under_policy, so that the body of the method never receives a policy and passes none on. A single action of on_error= applies to a ConversionError, which covers a loss of metadata, and never to an OSError. The method itself declares neither keyword and does not document them.

An override that calls the method of its base class through super() passes no policy, so the inner call runs under the policy of the outer one, and only the outer call returns a value in place of a result. A method that is already decorated is returned as it is, so that it is never wrapped twice.

A generator function, such as a to_lines method, runs its body only while its result is iterated. The wrapper of such a method returns a generator that sets the policy in effect for a loss while it asks the body for each item, and not while the caller handles that item. An error that the body raises during the iteration is handed to the policy. When the policy does not raise, the iteration ends there, and the value that the policy returns is dropped, because the generator has no result that the value could replace. The policy itself is checked when the method is called.

Parameters:

Name Type Description Default
method callable

The method.

required

Returns:

Type Description
callable

The decorated method.

brainhops.io.metadata._base

The base of the metadata of file formats, and its consolidation.

Classes

MetadataFormat magic

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

Bases: FileBasedModelMixin, Metadata, FileFormat

Format dispatcher and common base for the metadata of files.

The metadata of a file is what its header records beside the data. Each file format that has a header defines a subclass named after the format, such as NiftiMetadata, which holds the header in raw as the format stores it. MetadataFormat.load reads the header of a file in any registered format, and the same method of a subclass reads a file of its own format. In both cases, the data that follows the header is not read.

The header held in raw is called the record of the file. The record describes the file as it was read, or as the object that holds it was last consolidated. A record is never changed in place: an object that encodes a new header, with its consolidate method or when it is written, encodes it into a copy and holds that copy in new metadata. Metadata keeps no open file and no reference to the data, so it is cheap to copy and it can be pickled.

The metadata of a format also holds the common vocabulary of Metadata. A format decodes every field that it can store from the record when the metadata is built with from_raw, and a field that the format has no slot for holds None. The fields that a format can store are listed in its constant SUPPORTED_FIELDS. A field can be assigned whatever the format supports: consolidate encodes into a copy of the record the fields that differ from a fresh decode of the record, and reports those that the format could not store.

Images and transformations share their metadata with their copies, and metadata can be changed in place, so a change made through one copy is seen by the others. To change the metadata of one copy only, assign it new metadata, such as image.metadata = replace(image.metadata, description="smoothed"). Metadata compares by identity.

The metadata registry is separate from the registry of FileFormat, so that load never returns metadata when it reads an image or a transformation. A concrete subclass is added to the metadata registry with @register_format.

The consolidate method of the metadata of a format, and each method that writes a file, take an error policy as their on_error= and on_loss= keywords (see ErrorPolicy), which decides what happens to what the file cannot hold. A format overrides the hook _consolidate, around which the base class applies the policy, and puts the decorator takes_error_policy above each writer that it defines, which applies the policy around the writer. Neither the hook nor a writer declares these keywords.

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[Any]

The header of the file as the format stores it, or None. The type of the record depends on the format, and only the format reads it. The record is hidden from the representation of the metadata, because a header is usually long.

None
extra dict[str, Any]

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

Factory()

Attributes

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
RAW: type | None = None

The class of the record of the format, or None.

When the record class of a format can read or write a file, the format sets this constant to it and lists MetadataReader or MetadataWriter among its bases. These classes pass every input to the record class and every output to the record, so the record class decides how each input is read and which options it takes. A format that reads or writes its header in another way leaves this constant at None and uses the readers and writers of io/base/parsers.py instead.

raw class-attribute instance-attribute
raw: NoRepr[Any] = None

The header of the file as the format stores it, or None.

The type of the record depends on the format, and only the format reads it. The record is hidden from the representation of the metadata, because a header is usually long.

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.

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

Methods:

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.

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.

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.

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.

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

Identify the registered format of a file or its content.

The result is the registered format that would read the input.

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

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

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

Identify the registered format that matches a path.

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

Same as sniff, for an open file object.

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

Same as sniff, for text or binary content.

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

Same as sniff, for binary content.

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

Same as sniff, for text.

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

Same as sniff, for lines of text.

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

Same as sniff, for a single line.

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

Read an object from a file or its content.

The input is read with the best-matching registered format. A SourceSpec is read with from_spec.

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

Read a structured source specification.

The specification's path is read with its hints and options.

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

Read an object from a path or an open file.

The file is read with the best-matching registered format.

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

Same as from_file, for a path.

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

Same as from_file, for an open file object.

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

Same as from_file, for text or binary content.

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

Same as from_file, for binary content.

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

Same as from_file, for text.

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

Same as from_file, for lines of text.

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

Same as from_file, for a single 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.

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.

Functions:

consolidated

consolidated(
    metadata: MetadataFormat,
    encode: _Encoder | None,
    new_record: Callable[[], Any] | None,
    *,
    inplace: bool,
    fields: Mapping[str, Any],
) -> Any

Return metadata whose record holds its fields.

This function is the body of _consolidate for every metadata format, which passes its own encoder. It follows the contract of consolidation of the format records.

  1. The fields given in fields replace those of the metadata.
  2. The fields that differ from a fresh decode of the record (the metadata that from_raw builds from it) are the changes. With none, the result shares the record, and metadata without a record and without a field set stays without a record.
  3. The changes are encoded into a copy of the record, or into a new, empty record when there is none. The encoder takes the name of each change that it writes, and the changes that are left are reported as lost. A change that the record holds only approximately is reported as approximated.
  4. The result is decoded afresh from the new record, so a second consolidation changes nothing.

Parameters:

Name Type Description Default
metadata MetadataFormat

The metadata to consolidate.

required
encode callable

The encoder of the format, encode(record, changed, report). It writes into record, which is a copy, the changes that the format can store, pops each of them from changed, reports what it stores approximately, and returns the record. None stores nothing.

required
new_record callable

A function that returns an empty record of the format, for metadata without a record. With None, such metadata stores nothing.

required
inplace bool

Whether to change metadata rather than a copy.

required
fields mapping

Fields to override before the encoding.

required

Returns:

Type Description
MetadataFormat

The consolidated copy, or metadata itself with inplace=True.

Raises:

Type Description
TypeError

If fields names no field of the metadata.

MetadataLossError

If something is reported under the "raise" policy.

lost_fields

lost_fields(
    remaining: Mapping[str, Any], report: ConversionReport
) -> ConversionReport

Report as lost the changes that no slot of a record took.

Parameters:

Name Type Description Default
remaining mapping

The changes that the encoder of a format left: field name to the value that it could not store.

required
report ConversionReport

The report to fill.

required

Returns:

Type Description
ConversionReport

report itself.

unsupported_values

unsupported_values(
    cls: Type[MetadataFormat], metadata: Metadata
) -> dict[str, Any]

Return the fields of metadata that a format declares no slot for.

This function is the one reader of SUPPORTED_FIELDS. A field counts when its value is set, which means not None, and not empty for extra.

Parameters:

Name Type Description Default
cls type

The metadata class of a format.

required
metadata Metadata

The metadata to check.

required

Returns:

Type Description
dict

Field name to value, for each field that is set and that cls.SUPPORTED_FIELDS does not list.

metadata_options

metadata_options(
    kwargs: Mapping[str, Any],
) -> tuple[dict[str, Any], dict[str, Any]]

Split the options of a writer into those of the metadata and the rest.

A writer that writes the record of a consolidated copy gives the fields of the vocabulary to consolidate, and the other options to the writer of the record. The error policy of the write never reaches the writer, which runs under it (see the WriterMixin class of brainhops.io.base.parsers).

Parameters:

Name Type Description Default
kwargs mapping

The keyword arguments given to a writer.

required

Returns:

Name Type Description
metadata dict

The fields of the metadata among kwargs.

others dict

The other options.

metadata_to_write

metadata_to_write(
    metadata: MetadataFormat | None,
    cls: Type[MetadataFormat],
    fields: Mapping[str, Any],
    report: ConversionReport,
) -> MetadataFormat | None

Return the consolidated metadata that an object encodes over.

This is step 2 of the precedence on write. An image or a transformation of a format calls it from its consolidate, before it encodes its geometry and its data over the record of the result. The fields given override those of the metadata, and the metadata is consolidated with report as its loss policy, so that the caller acts once on what the whole write lost. An object without metadata gets metadata of cls when a field is given, and none otherwise.

Parameters:

Name Type Description Default
metadata MetadataFormat

The metadata of the object.

required
cls type

The metadata class of the format, for an object without metadata.

required
fields mapping

Fields to override, by name.

required
report ConversionReport

The report of the write, which receives what the metadata loses.

required

Returns:

Type Description
MetadataFormat or None

The consolidated metadata, or None for an object without metadata to which no field is given.

Raises:

Type Description
TypeError

If fields names no field of the metadata.

requested_fields

requested_fields(
    metadata: MetadataFormat | None,
    fields: Mapping[str, Any],
) -> dict[str, Any]

Return the fields that a write is asked to store.

They are the fields given as overrides, and the fields of the metadata that differ from a fresh decode of its record, with the value that the write should store. A format object compares them with the metadata decoded from the record that it wrote, with overruled_fields, to report the fields that its model owns.

Parameters:

Name Type Description Default
metadata MetadataFormat

The metadata of the object, before its consolidation.

required
fields mapping

The fields given as overrides.

required

Returns:

Type Description
dict

Field name to the value asked for.

overruled_fields

overruled_fields(
    requested: Mapping[str, Any],
    written: Metadata | None,
    report: ConversionReport,
) -> ConversionReport

Report the requested fields that a written record does not hold.

The model of an image or a transformation owns some slots of a record, such as the time step of a NIfTI image, which is also its repetition time, or the codes of its forms, which name its world space. A field that the metadata stored in such a slot is then encoded over by the geometry, and is reported here as approximated. A field already reported by the consolidation of the metadata is left as it is.

Parameters:

Name Type Description Default
requested mapping

The fields asked for, from requested_fields.

required
written Metadata

The metadata decoded from the record that was written.

required
report ConversionReport

The report of the write.

required

Returns:

Type Description
ConversionReport

report itself.

brainhops.io.metadata._json

The vocabulary as a flat JSON object: the codec that BIDS sidecars (_bids) and the JSON stores of formats (the Metadata of an X5 node) share.

A vocabulary field is stored under its sidecar key: its BIDS key ("RepetitionTime"), or, when BIDS has none, its name in CamelCase (display_range as "DisplayRange"). Every other key of the object is extra. GeneratedBy is the BIDS list of objects (Name, Version, Description, CodeURL), and channels a list of objects with the CamelCase names of the Channel fields. Times are ISO 8601 strings. An encoding direction is its BIDS string ("j-"), or, when it has none, an object (Vector, Space). A known term (a SpaceEnum, an IntentEnum, ...) is its string, a data_unit its unit symbol ("ms", "a.u."), a dtype its numpy name ("int16").

Functions:

sidecar_key

sidecar_key(name: str) -> str

The key of a vocabulary field in a JSON object.

Parameters:

Name Type Description Default
name str

The name of the vocabulary field.

required

Returns:

Type Description
str

The BIDS key of the field, or its name in CamelCase when BIDS has no key for it.

decode_object

decode_object(
    obj: Mapping[str, Any], names: Iterable[str]
) -> tuple[dict[str, Any], dict[str, Any]]

Split a JSON object into vocabulary values and other keys.

Parameters:

Name Type Description Default
obj mapping

The JSON object.

required
names iterable of str

The vocabulary fields to read, each from its key (see sidecar_key).

required

Returns:

Name Type Description
values dict

Field name to decoded value, for the fields found in obj.

others dict

The other keys of obj, with their values as they are.

encode_changes

encode_changes(
    obj: dict[str, Any],
    changed: Mapping[str, Any],
    *,
    report: ConversionReport,
) -> None

Write changed vocabulary values into a JSON object, in place.

A value that JSON cannot hold (an encoding direction in a coordinate system without a name) is not written: its key is removed, so that the object does not keep a stale value, and the value is reported as lost.

Parameters:

Name Type Description Default
obj dict

The JSON object to edit.

required
changed mapping

Field name to new value. Each value is written under the key of its field (see sidecar_key), and a None value removes the key.

required
report ConversionReport

The report to fill with the values that were not written.

required

encode_extra

encode_extra(
    obj: dict[str, Any],
    extra: Mapping[str, Any],
    names: Iterable[str],
    *,
    report: ConversionReport,
    reserved: Collection[str] = (),
) -> None

Replace the free-form keys of a JSON object with extra, in place.

The free-form keys of the object are those that hold no vocabulary field, which decode_object decodes as extra. They are removed, and each key of extra is written as JSON. A key that the format keeps for its own use, or that holds a vocabulary field, is not written, and is reported as lost.

Parameters:

Name Type Description Default
obj dict

The JSON object to edit.

required
extra mapping

The new free-form keys and their values.

required
names iterable of str

The vocabulary fields that the object stores, whose keys are not free-form (see sidecar_key).

required
report ConversionReport

The report to fill with the keys that were refused.

required
reserved collection of str

The keys the format keeps for its own use.

()

from_json

from_json(name: str, value: Any) -> Any

Decode the JSON form of a vocabulary value.

Parameters:

Name Type Description Default
name str

The name of the vocabulary field.

required
value object

The value, as JSON holds it.

required

Returns:

Type Description
object

The value, ready to be assigned to the field, which converts it further.

to_json

to_json(name: str, value: Any) -> Any

Encode a vocabulary value, or a value of extra, as JSON.

GeneratedBy and Channel entries become objects with keys in the BIDS style. An encoding direction becomes its BIDS string, or, when BIDS cannot write it, an object with the keys Vector and Space; a space that is a CoordinateSystem is written as its name.

Parameters:

Name Type Description Default
name str

The name of the vocabulary field, or "extra".

required
value object

The value to encode.

required

Returns:

Type Description
object

A value that can be serialised to JSON.

Raises:

Type Description
ValueError

If value is an encoding direction in a coordinate system without a name, which JSON cannot hold.

jsonable

jsonable(value: Any) -> Any

Make a value serialisable to JSON.

Times become ISO 8601 strings, known terms become their strings, a data type becomes its name, a unit becomes its symbol, and tuples and arrays become lists.

Parameters:

Name Type Description Default
value object

The value to convert.

required

Returns:

Type Description
object

A value that can be serialised to JSON.

brainhops.io.metadata._storage

The element type, and the intensity scaling, that a writer stores an array with.

Functions:

preferred_storage

preferred_storage(
    metadata: Metadata | None,
    data: Any,
    *,
    report: ConversionReport | None = None,
) -> tuple[dtype, float | None, float | None]

Choose how a writer stores an array: its element type and its scaling.

The element type is metadata.dtype, and the type of the data when the metadata gives none. An override given to save or to consolidate is a field of the metadata by the time a writer calls this function, so it takes precedence over the type that the file was read with. A label map read as uint8 and computed on as int64 is therefore written as uint8 again.

The metadata describes the scaling of the file with scale_slope and scale_intercept. The scaling is kept when the element type is an integer type and every value of the array is, up to a thousandth of a step, stored * scale_slope + scale_intercept for an integer stored that the type can hold, so a scaled integer file that was read and left unchanged is written back exactly as it was. Otherwise the array is stored without a scaling, and the scaling is reported as approximated.

Parameters:

Name Type Description Default
metadata Metadata

The metadata of the image being written.

required
data array - like

The values to write. They are read only when a scaling has to be checked.

required
report ConversionReport

The report of the write, which receives the scaling that could not be kept.

None

Returns:

Name Type Description
dtype dtype

The element type to store the array as.

slope float or None

The slope of the scaling, or None for none.

intercept float or None

The intercept of the scaling, or None for none. With a scaling, the writer stores (value - intercept) / slope as dtype (see stored_values).

stored_values

stored_values(
    data: Any,
    dtype: Any,
    slope: float | None = None,
    intercept: float | None = None,
) -> ndarray

Return the values that a writer stores, with a type and a scaling.

Each value is stored as (value - intercept) / slope, rounded to the nearest integer only when dtype is an integer type, then cast to dtype.

Parameters:

Name Type Description Default
data array - like

The values to write.

required
dtype dtype - like

The element type to store them as.

required
slope float

The slope of the scaling, or None for a slope of 1.

None
intercept float

The intercept of the scaling, or None for an intercept of 0.

None

Returns:

Type Description
ndarray

The stored values, of type dtype.