Skip to content

brainhops.io.base

Format-independent machinery shared by every kind of file-based object.

Classes

FileFormat

Bases: FileNamesMixin

Dispatch between the formats registered under a dispatcher.

On a class decorated with format_registry, the sniff* methods identify the registered format that matches the input, and load and the from_* methods choose a format and delegate to it.

A concrete format lists its reader and its writer before this class, as in class NiftiImage(BinaryFileReader, BinaryFileWriter, ImageFormat, SingleScaleImage), so that its sniff*, load and from_* methods are those of its reader. The methods of this class therefore only ever run on a dispatcher, and they raise TypeError on any other class. This class does not inherit FileReader, whose sniff* methods return a confidence rather than a class.

This class owns the root registry used by generic loading and saving. A standalone family, such as metadata, uses @format_registry(isolated=True) to keep its formats out of ancestor registries while retaining the same dispatch API.

sniff* means something different on a dispatcher

A concrete format returns its confidence, between 0 and 1, that the input is in its format. A dispatcher has already compared those confidences, so it returns which format matched, or None. That format can be asked to score the input itself.

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.

ImageSpec magic

ImageSpec(path: ConvertTo[Path], hints: tuple[str, ...] = (), options: dict[str, str | SourceSpec])

Bases: SourceSpec

Source specification of an image.

Parameters:

Name Type Description Default
path ConvertTo[Path]
required
hints tuple[str, ...]
()
options dict[str, str | SourceSpec]
required

Methods:

from_arg classmethod
from_arg(text: str) -> Self

Parse a source argument written as path|hint|key:value.

The segments after the path are format hints, options, or operations that the class declares. Hints may also be given as hint:a,b. An option value written in brackets, as in key:[path|hint], is a nested specification. Colons have a special meaning only in the segments after the path, and only the first colon of a segment separates the option name from its value, so a URI scheme in the path or in a value is kept intact. A literal pipe is written %7C.

Raises:

Type Description
ValueError

If the path is missing, a segment is empty, or an option is unnamed or repeated.

OperationSpec magic

OperationSpec(name: str)

Bases: Magic

A named operation applied to a loaded source.

Parameters:

Name Type Description Default
name str
required

Methods:

from_arg classmethod
from_arg(text: str) -> Self

Parse the segment of this operation.

Raises:

Type Description
ValueError

If the segment gives the operation a value.

apply
apply(value: Any) -> Any

Apply the operation to a loaded value.

Parser magic

Parser(value: Any)

Bases: Magic

Annotation metadata choosing the parser of a field.

A field annotated as Annotated[T, Parser(value)] converts its option string with value instead of the parser registered for T. The value is either a parser or a target registered with register_parser, in which case the parser registered for that target is used.

Parameters:

Name Type Description Default
value Any
required

Methods:

SourceSpec magic

SourceSpec(path: ConvertTo[Path], hints: tuple[str, ...] = (), options: dict[str, str | SourceSpec])

Bases: Magic

An immutable source path with format hints and named options.

A source specification names a file to read. Its format hints restrict the formats that may read the file, and its options set fields of the format that reads it. Option values are strings or nested specifications.

Parameters:

Name Type Description Default
path ConvertTo[Path]
required
hints tuple[str, ...]
()
options dict[str, str | SourceSpec]
required

Methods:

from_arg classmethod
from_arg(text: str) -> Self

Parse a source argument written as path|hint|key:value.

The segments after the path are format hints, options, or operations that the class declares. Hints may also be given as hint:a,b. An option value written in brackets, as in key:[path|hint], is a nested specification. Colons have a special meaning only in the segments after the path, and only the first colon of a segment separates the option name from its value, so a URI scheme in the path or in a value is kept intact. A literal pipe is written %7C.

Raises:

Type Description
ValueError

If the path is missing, a segment is empty, or an option is unnamed or repeated.

TransformationSpec magic

TransformationSpec(path: ConvertTo[Path], hints: tuple[str, ...] = (), options: dict[str, str | SourceSpec], operations: tuple[OperationSpec, ...] = ())

Bases: SourceSpec

Source specification of a transformation, with optional operations.

The hint svf is shorthand for displacements|log:true, which reads a displacement field as the stationary velocity field of the transformation, as in warp.nii.gz|svf|steps:6. Operations such as inv are applied to the loaded transformation in the order in which they are written.

Parameters:

Name Type Description Default
path ConvertTo[Path]
required
hints tuple[str, ...]
()
options dict[str, str | SourceSpec]
required
operations tuple[OperationSpec, ...]
()

Methods:

from_arg classmethod
from_arg(text: str) -> Self

Parse a source argument, expanding the svf alias.

The syntax is that of SourceSpec.from_arg.

register_operation classmethod
register_operation(
    name: str,
) -> Callable[[Type[OperationSpec]], Type[OperationSpec]]

Register an operation under name for this class and subclasses.

Each class keeps its own registry, which is created the first time an operation is registered on that class. An operation registered on a subclass is therefore not recognised by its parent classes or by its sibling classes.

apply_operations
apply_operations(value: Any) -> Any

Apply the operations in the order in which they were written.

Functions:

format_registry

format_registry(
    cls: Type[_T] | None = None, *, isolated: bool = False
) -> Any

Give a class its own format registry, which makes it a dispatcher.

A dispatcher is a class that does not read a format itself but chooses among the formats registered under it. Its sniff* methods return the best-scoring registered format, and its load and from_* methods choose that format and delegate to it. The decorator is applied to the root FileFormat and to the base class of each kind of object, such as ImageFormat and TransformationFormat. A dispatcher is never added to the registries of its ancestors; only classes decorated with register_format are.

Set isolated=True for a standalone family such as metadata. Its concrete formats register within that family and nested registries, but registration stops before reaching its ancestors.

register_format

register_format(cls: Type[_T]) -> Type[_T]

Register a concrete format into ancestor registries up to isolation.

A format such as NiftiImage is thereby found both by images.load and by the generic load. Registration is idempotent, so re-importing a module is harmless.

Dispatchers are not formats

Registries are flat. A format is in the registry of every ancestor, whereas a dispatcher is in no registry at all, so each format is tried once per load. If a dispatcher were registered, its formats would be tried twice, once directly and once through the dispatcher, and FileFormat.load would recurse into itself.

Order does not matter

A registry is an unordered set, because registration follows import order, which is not stable. Dispatch never relies on registration order: candidates that cannot be told apart raise AmbiguousFormatError.

Raises:

Type Description
TypeError

If cls owns a registry.

load

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

Read an object from a file, whatever its kind and format.

The file is read by the registered format that best matches its content. For example, a NIfTI file that holds a displacement field is read as a transformation, whereas a plain NIfTI file is read as an image.

Prefer the scoped entry points when the kind is known

images.load and transformations.load consider only their own kind, which is faster and unambiguous.

Parameters:

Name Type Description Default
filelike FileOrContentLike

The file or its content.

required
brute bool

Whether to try every registered reader when no format recognizes the input.

False

sniff

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

Predict which format load would use, without reading the file.

Returns:

Type Description
type or None

The best match among all registered formats, or None if no single format stands out.

save

save(
    obj: Any,
    file: FileLike,
    hint: str | Iterable[str] | None = None,
    *,
    on_loss: ErrorAction = UNSET,
    on_error: ErrorPolicy = UNSET,
    conversion: Mapping[str, Any] | None = None,
    **kwargs,
) -> Any

Write an object to a file in the format that the file name calls for.

The format is chosen from the registered writable formats, in four steps.

  1. The file name. The formats that declare the longest of the extensions the name ends with are the candidates, so a.ome.zarr asks for OME-Zarr and a.zarr for any Zarr format. A format that requires a prefix is a candidate only when the name has one of its prefixes. With a hint, only the formats that answer to it are candidates, as for reading, and when none of them claims the name, they are all candidates, so that a.json can be written with hint="neuroglancer.affine".
  2. The object's own format. If obj already is of one of the candidates, it is written as it is.
  3. A format that can hold the object as it is. Otherwise, an object that is not a transformation is written in a candidate that is a file-backed version of the very data model obj is an instance of, and takes every field that data model has (NiftiImage and ZarrImage are file-backed SingleScaleImages). obj is converted to it, which neither loses nor changes anything. A SingleScaleImage that no candidate holds as it is, because no candidate stores a single image, becomes the finest level of a pyramid in a candidate that is a file-backed MultiScaleImage, as obj.to(OmeZarrImage) converts it. A format that builds its scales, as OME-Zarr does, builds the coarser levels as with_scales() builds them, unless nscales=1 asks for the single level. A name that ends with .ome.zarr therefore writes an image as an OME-Zarr pyramid, while a name that ends with .zarr still asks for a plain Zarr array, which refuses an image that has a geometry.
  4. A format a transformation converts to. A transformation is instead converted to every candidate, with the same converters as obj.to(Format, **conversion). A converter returns the map obj is, with its endpoints bridged to the format's (an affine to LPS is flipped into RAS), an approximation of it, or refuses: a general Affine is written as the voxel-to-RAS affine of a NIfTI file only when that is what it maps, or when its coordinate systems are not known. An approximation, such as a field interpolated with cubic splines that a NIfTI file stores as linearly interpolated values, is kept only when on_loss accepts it.

In step 3, the candidates are tried from the most specific, by the rules reading uses: the longest prefix, then the narrowest declaration, then PRIORITY. Two that are equally specific and can both hold obj are an ambiguity, and nothing is written.

In step 4, the conversions are ranked. The extension and the prefix of the name come first, so that a y_ prefix asks for an SPM deformation. An exact conversion then comes before a lossy one, and a format that takes every option of conversion before one that does not, so that the images given for an FSL file select it. Then comes the conversion that keeps more of what obj holds: a field of the same kind (displacements, coordinates or a velocity), and the known endpoints of obj, so that a field between LPS spaces is written as an ITK field rather than as a NIfTI field between RAS spaces. The narrowest declaration and PRIORITY come last. Two conversions that rank first together are an ambiguity, and nothing is written.

A candidate that refuses obj gives way to the next, in step 3 and then in step 4, until one writes it. A candidate refuses when obj cannot be converted to it, or when its writer cannot write what was built from obj and raises a ConversionError or a WriterError, such as UnrepresentableTransformationError: a register.dat file refuses an affine between scanner RAS spaces without the geometries of both volumes. An OSError, as when the file cannot be written, is raised at once, as is any other error of a writer, and no other candidate is tried.

Approximations are opted into

A transformation is written in a format that holds it only approximately when on_loss accepts the loss, and a format that holds it exactly is still preferred. Without it, one that no candidate holds exactly is refused with each candidate's reason.

One pass for a transformation

Some formats have no exact converter yet (#312), and hold a transformation only by relabelling it, that is, by being rebuilt from its parameters, when the coordinate systems allow it. Step 4 relabels a transformation only into a format that is a file-backed version of its data model, so that the formats that would only relabel it do not make the choice ambiguous. Every candidate, including such a format, is given the options of the conversion, so that an LTA file or a register.dat file receives the geometries of its volumes.

Parameters:

Name Type Description Default
obj object

The object to write.

required
file FileLike

A path, or a file object opened for writing. An object without a name, such as a buffer, gives no name to choose from, so obj must already be a writable format.

required
hint str or iterable of str

Hints that name the formats to choose from, such as "neuroglancer.affine", as for load. A file without a name is written by obj itself, and the hint is not used.

None
on_loss ErrorAction

What to do with a loss, as for a conversion (see ErrorPolicy). A transformation that a format holds only approximately, such as a field interpolated with cubic splines written as the linearly interpolated values of a NIfTI file, is a loss: "ignore" keeps such a format among the candidates, ranked after those that hold the transformation exactly, "warn" keeps it and warns when it is chosen, and a report keeps it and records the loss of the one that is chosen. Any other action drops such a format, and a value to return, or an exception to raise, takes the place of the error when only such formats remain. The action also applies to the metadata that the file cannot hold. By default, such a format is dropped, and a loss of metadata follows on_error, or else the policy in effect.

UNSET
on_error ErrorPolicy

An error policy (see ErrorPolicy), whose action for a MetadataLossError decides what happens to the metadata that the file cannot hold, such as "ignore", "warn", "raise", or a ConversionReport to fill. An object that is converted, then written, is acted on once, after the file is written, with one report of what the conversion and the write lose. An object that is already of the chosen format is written by its own save under the policy. The metadata of a format that does not hold metadata is not written, and its fields are reported as lost. on_loss takes precedence over on_error for a loss, as in a conversion. The WriterError that save raises when no format can hold obj is not a conversion error, so it is outside the scope of a single action, and it is raised even under on_error=None. The OSError of a write that fails is raised as well. By default, an error is raised, and a loss of metadata follows the policy in effect.

UNSET
conversion mapping

Options of the conversion of a transformation to the chosen format, as obj.to(Format, **conversion) takes them. A format that needs the geometry of an image, such as an FSL warp, takes it there, as in conversion={"reference": image}.

None
**kwargs Any

Options passed to the save method of the chosen format. An option named after a field of the metadata, such as dtype, overrides that field (see the consolidate method of the format). The options that build the scales of a pyramid, nscales=, factor=, mode=, align=, min_size= and strict=, are taken out first and given to the conversion, for an image as for a transformation, so that io.save(image, "image.ome.zarr", nscales=1) writes a single level. They are those of Multiscale.with_scales. A single scale saved to OME-Zarr is the exception: the writer takes these options, writes the finest level, and builds each coarser level from the levels that it has written, read back from the store, so that the finest level is read once and the memory stays bounded by a few chunks (#638). A pyramid built in memory is written as it is, so that image.to(OmeZarrImage, nscales=4).save(path) computes its levels from one Dask graph, while io.save(image, path, nscales=4) reads each level back. The values are the same, except that a level of an integer type that a mode averages is computed from the level before it once rounded, which may change a value by one.

{}

Returns:

Type Description
Any

None, or the value that the error policy returns in place of a refused loss.

Raises:

Type Description
AmbiguousFormatError

If several equally specific formats can hold obj.

WriterError

If no format claims the file name, or if every one that does refuses obj, with the reason of each. If obj already is of one of these formats, the error of its own writer is raised. If a hint is given, no writable format answers to it, or none of those that do can hold obj, or the chosen format cannot write it.

OSError

If the file cannot be written, or the data of obj cannot be read.

MetadataLossError

If metadata is lost under the "raise" policy.

format_hints

format_hints(cls: type) -> FrozenSet[str]

Return the plain and dotted hints of a format.

For example, a format may answer to itk and itk.displacements.

parser_for

parser_for(annotation: Any) -> Any | None

Return the explicit or registered parser for an annotation, or None.

For a union, the parser of its members is used when the members that have a parser all share the same one.

register_parser

register_parser(target: Hashable) -> Callable[[Any], Any]

Register a decorated parser as the default for target.