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
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.
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
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
Parse the segment of this operation.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the segment gives the operation a 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
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
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.
Functions:
format_registry
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 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 |
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
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 |
format_hints
Return the plain and dotted hints of a format.
For example, a format may answer to itk and itk.displacements.
parser_for
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.