Skip to content

brainhops.io

Transformations, images, meshes and streamlines stored in files.

Each file format also implements the generic interface of the object it holds, whether the file is on a local disk or in a cloud store, so a file-backed object can be used wherever the generic object is expected.

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.

Functions:

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

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.

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.