Skip to content

brainhops.io.transformations

Readers and writers of transformation file formats.

The entry points are load, which reads a transformation from a file and detects its format, and sniff, which predicts that format without parsing the file.

Classes

TransformationFormat

Bases: FileBasedModelMixin, DataModelBase, FileFormat

Format dispatcher and common base for stored transformations.

Loading a file through this class selects the concrete format that matches the file and delegates the reading to it. A reader of a concrete format derives from the class and opts in with the @register_format decorator, after which load can select that reader.

A format builds itself from another transformation by converting it, so that Format.from_any(t), Format.from_instance(t) and t.to(Format) are one conversion. The conversion runs the exact converter of the format when it has one. A format without one either registers a converter that relabels a transformation as the format (see [relabel][brainhops.io.transformations.base._converters.relabel]), or is rebuilt by the converters of the data model. A file, a mapping and an instance of the format itself are read or copied as the bases of this class read or copy them.

The consolidate method of a transformation 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.

Attributes

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

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

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

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

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

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

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

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

Methods:

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 | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

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

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

Parameters:

Name Type Description Default
cls type

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

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

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

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

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

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

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

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

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

Parameters:

Name Type Description Default
inplace bool

Whether to change this object rather than a copy.

False
on_error ErrorPolicy

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

UNSET
on_loss ErrorAction

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

UNSET
**fields Any

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

{}

Returns:

Type Description
Self

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

Raises:

Type Description
TypeError

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

MetadataLossError

If something is lost under the "raise" policy.

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

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

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

Parameters:

Name Type Description Default
other object

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

required
*args Any

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

()
**kwargs Any

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

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

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

ConversionError

If the format cannot hold the transformation.

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

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

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

Parameters:

Name Type Description Default
other object

The instance to copy or convert.

required
*args Any

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

()
**kwargs Any

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

{}

Returns:

Type Description
Self

The new object.

Raises:

Type Description
TypeError

If positional arguments accompany a transformation that is converted.

ConversionError

If the format cannot hold the transformation.

Functions:

load

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

Read a transformation from a file, detecting its format.

Parameters:

Name Type Description Default
filelike FileOrContentLike

The file, or its content.

required
brute bool

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

False
**kwargs Any

Format-specific options.

{}

Returns:

Type Description
TransformationFormat

The transformation read from the file.

sniff

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

Predict which format class would read a file, without parsing it.

The result only predicts the class that load would choose, and it does not guarantee that reading succeeds.

Parameters:

Name Type Description Default
filelike FileOrContentLike

The file, or its content.

required
**kwargs Any

Format-specific options, as in load.

{}

Returns:

Type Description
type or None

The format class, or None when no single format is the best match.