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
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
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
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
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
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
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_lines
classmethod
Same as from_file, for lines of text.
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.
- The file name. The formats that declare the longest of the
extensions the name ends with are the candidates, so
a.ome.zarrasks for OME-Zarr anda.zarrfor any Zarr format. A format that requires a prefix is a candidate only when the name has one of its prefixes. With ahint, 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 thata.jsoncan be written withhint="neuroglancer.affine". - The object's own format. If
objalready is of one of the candidates, it is written as it is. - 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
objis an instance of, and takes every field that data model has (NiftiImageandZarrImageare file-backedSingleScaleImages).objis converted to it, which neither loses nor changes anything. ASingleScaleImagethat 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-backedMultiScaleImage, asobj.to(OmeZarrImage)converts it. A format that builds its scales, as OME-Zarr does, builds the coarser levels aswith_scales()builds them, unlessnscales=1asks for the single level. A name that ends with.ome.zarrtherefore writes an image as an OME-Zarr pyramid, while a name that ends with.zarrstill asks for a plain Zarr array, which refuses an image that has a geometry. - 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 mapobjis, with its endpoints bridged to the format's (an affine to LPS is flipped into RAS), an approximation of it, or refuses: a generalAffineis 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 whenon_lossaccepts 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 |
required |
hint
|
str or iterable of str
|
Hints that name the formats to choose from, such as
|
None
|
on_loss
|
ErrorAction
|
What to do with a loss, as for a conversion (see
|
UNSET
|
on_error
|
ErrorPolicy
|
An error policy (see
|
UNSET
|
conversion
|
mapping
|
Options of the conversion of a transformation to the chosen
format, as |
None
|
**kwargs
|
Any
|
Options passed to the |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
AmbiguousFormatError
|
If several equally specific formats can hold |
WriterError
|
If no format claims the file name, or if every one that does
refuses |
OSError
|
If the file cannot be written, or the data of |
MetadataLossError
|
If metadata is lost under the |
sniff
sniff(filelike: FileOrContentLike, **kwargs) -> type | None