brainhops.io.common.afni
Reading and writing of AFNI datasets.
This module holds what all AFNI formats, images and transformations
alike, share: the header, the geometry, and the decoding and encoding of
voxel values. All of these formats derive from AfniFormat. The
conventions follow the AFNI sources (README.attributes, 3ddata.h).
A dataset is a pair of files. prefix+view.HEAD holds text attributes
and prefix+view.BRIK holds the voxel values, possibly compressed. The
view is orig (scanner space), acpc, or tlrc (Talairach or any
other template). The NIML (XML) variant of the header is not
supported.
The BRIK stores DATASET_RANK[1] sub-bricks (time points, statistics
or warp components) one after the other, with x varying fastest,
which gives a Fortran-ordered (nx, ny, nz, nvals) array. Each
sub-brick has its own type (BRICK_TYPES) and, optionally, a scale
factor (BRICK_FLOAT_FACS).
The world space is DICOM space, that is LPS in millimetres. The
ORIENT_SPECIFIC, ORIGIN and DELTA attributes define a signed
permutation from voxels to DICOM coordinates, the cardinal matrix, which
is recomputed on read rather than taken from IJK_TO_DICOM. An oblique
dataset also stores its true matrix in IJK_TO_DICOM_REAL. AFNI
programs compute on the cardinal grid, while 3dAFNItoNIFTI stores the
true matrix as the NIfTI sform.
The header of a dataset is held as an AfniRaw record, and
AfniMetadata reads and writes that record without the voxels.
AfniImage holds such metadata
and a lazy array of the voxels. The record keeps the text of the header
as well as its attributes, so that a dataset that is read and written
again without changes keeps the bytes of both of its files.
Classes
AfniFormat
Bases: FileFormat
Family of the AFNI formats, images and transformations alike.
The family owns a format registry, so that its load and sniff*
methods choose among every AFNI format. It answers to the hint
"afni", and the hints of its formats, such as "brik", can also be
reached as "afni.brik".
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.
AfniMetadata
magic
AfniMetadata(
name: str | None = None,
description: str | None = None,
history: tuple[str, ...] | None = None,
generated_by: tuple[GeneratedBy, ...] | None = None,
creation_time: datetime | None = None,
sources: tuple[str, ...] | None = None,
space: SpaceEnum | str | None = None,
intent: IntentEnum | str | None = None,
repetition_time: float | None = None,
echo_time: float | None = None,
inversion_time: float | None = None,
flip_angle: float | None = None,
magnetic_field_strength: float | None = None,
manufacturer: Manufacturer | str | None = None,
manufacturers_model_name: str | None = None,
institution_name: str | None = None,
acquisition_time: datetime | None = None,
phase_encoding_direction: EncodingDirection
| None = None,
total_readout_time: float | None = None,
effective_echo_spacing: float | None = None,
slice_encoding_direction: EncodingDirection
| None = None,
slice_timing: tuple[float, ...] | None = None,
multiband_acceleration_factor: int | None = None,
bvalues: tuple[float, ...] | None = None,
bvectors: tuple[tuple[float, float, float], ...]
| None = None,
display_range: tuple[float, float] | None = None,
channels: tuple[Channel, ...] | None = None,
data_unit: Unit | str | None = None,
dtype: dtype | None = None,
scale_slope: float | None = None,
scale_intercept: float | None = None,
objective_magnification: float | None = None,
objective_numerical_aperture: float | None = None,
illumination_type: IlluminationType | str | None = None,
contrast_method: ContrastMethod | str | None = None,
moving: str | None = None,
fixed: str | None = None,
input_space: SpaceEnum | str | None = None,
output_space: SpaceEnum | str | None = None,
raw: NoRepr[AfniRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: BinaryFileReader, BinaryFileWriter, MetadataFormat
Metadata of an AFNI dataset, which is its .HEAD file.
The metadata of an AFNI dataset is the whole header, held as an
AfniRaw record. AfniImage
uses that record as the base of the header that it writes. Reading
the metadata reads the .HEAD file alone, whichever file of the
dataset a path names, so the .BRIK file is neither read nor needed.
The metadata keeps no open file.
A dataset is read through the record: from_fileobj and
from_filename read an AfniRaw, check that it describes a
dataset, and wrap it. Writing the metadata writes the .HEAD file of
the dataset that a path names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
A short name for the data. |
None
|
description
|
str | None
|
A free-text description. |
None
|
history
|
tuple[str, ...] | None
|
The commands that produced the data, oldest first. |
None
|
generated_by
|
tuple[GeneratedBy, ...] | None
|
The programs that produced the data. |
None
|
creation_time
|
datetime | None
|
When the file was created. |
None
|
sources
|
tuple[str, ...] | None
|
Files the data was derived from (BIDS provenance). |
None
|
space
|
SpaceEnum | str | None
|
The label of the world space ( |
None
|
intent
|
IntentEnum | str | None
|
What the values are, as a NIfTI intent name (a known one is an |
None
|
repetition_time
|
float | None
|
Repetition time, in seconds. |
None
|
echo_time
|
float | None
|
Echo time, in seconds. |
None
|
inversion_time
|
float | None
|
Inversion time, in seconds. |
None
|
flip_angle
|
float | None
|
Flip angle, in degrees. |
None
|
magnetic_field_strength
|
float | None
|
Nominal field strength, in tesla. |
None
|
manufacturer
|
Manufacturer | str | None
|
Manufacturer of the equipment (a known one is a |
None
|
manufacturers_model_name
|
str | None
|
Model name of the equipment. |
None
|
institution_name
|
str | None
|
Institution responsible for the equipment. |
None
|
acquisition_time
|
datetime | None
|
When the acquisition started. |
None
|
phase_encoding_direction
|
EncodingDirection | None
|
Phase-encoding direction: a unit vector. By default in voxel axes (BIDS |
None
|
total_readout_time
|
float | None
|
Total readout time, in seconds. |
None
|
effective_echo_spacing
|
float | None
|
Effective echo spacing, in seconds. |
None
|
slice_encoding_direction
|
EncodingDirection | None
|
Slice-encoding direction: a unit vector, by default in voxel axes (BIDS |
None
|
slice_timing
|
tuple[float, ...] | None
|
Acquisition time of each slice, in seconds, along the slice encoding direction. |
None
|
multiband_acceleration_factor
|
int | None
|
Multiband acceleration factor. |
None
|
bvalues
|
tuple[float, ...] | None
|
One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2." |
None
|
bvectors
|
tuple[tuple[float, float, float], ...] | None
|
One unit gradient direction per index along the time axis, in world (RAS) coordinates." |
None
|
display_range
|
tuple[float, float] | None
|
Display window |
None
|
channels
|
tuple[Channel, ...] | None
|
One description per channel. The descriptions run along the axes of type |
None
|
data_unit
|
Unit | str | None
|
Unit of the data values: a |
None
|
dtype
|
dtype | None
|
The element type of the data as stored, in native byte order. It may differ from the type of the loaded array: a scaled integer file loads as floating-point values. An override given to |
None
|
scale_slope
|
float | None
|
The slope of the intensity scaling: a value is |
None
|
scale_intercept
|
float | None
|
The intercept of the intensity scaling (see |
None
|
objective_magnification
|
float | None
|
Nominal magnification of the objective. |
None
|
objective_numerical_aperture
|
float | None
|
Numerical aperture of the objective. |
None
|
illumination_type
|
IlluminationType | str | None
|
Illumination type (a known one is an |
None
|
contrast_method
|
ContrastMethod | str | None
|
Contrast method (a known one is a |
None
|
moving
|
str | None
|
The moving image of a registration (file reference). |
None
|
fixed
|
str | None
|
The fixed image of a registration (file reference). |
None
|
input_space
|
SpaceEnum | str | None
|
Label of the space a transformation maps from. |
None
|
output_space
|
SpaceEnum | str | None
|
Label of the space a transformation maps to. |
None
|
raw
|
NoRepr[AfniRaw | None]
|
The record of the dataset, or |
None
|
extra
|
dict[str, Any]
|
Free-form keys the vocabulary does not cover, copied into any free-form store a format has." |
Factory()
|
Attributes
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.
name
class-attribute
instance-attribute
A short name for the data.
description
class-attribute
instance-attribute
A free-text description.
history
class-attribute
instance-attribute
The commands that produced the data, oldest first.
generated_by
class-attribute
instance-attribute
generated_by: Annotated[
tuple[GeneratedBy, ...] | None,
Bids(GeneratedBy),
Scoped(FILE),
] = None
The programs that produced the data.
creation_time
class-attribute
instance-attribute
When the file was created.
sources
class-attribute
instance-attribute
Files the data was derived from (BIDS provenance).
space
class-attribute
instance-attribute
The label of the world space ('MNI152NLin6Asym', 'scanner', ...;
a known one is a SpaceEnum); the space itself is geometry.
intent
class-attribute
instance-attribute
intent: Annotated[IntentEnum | str | None, Scoped(FILE)] = (
None
)
What the values are, as a NIfTI intent name
(a known one is an IntentEnum).
repetition_time
class-attribute
instance-attribute
Repetition time, in seconds.
echo_time
class-attribute
instance-attribute
Echo time, in seconds.
inversion_time
class-attribute
instance-attribute
Inversion time, in seconds.
flip_angle
class-attribute
instance-attribute
Flip angle, in degrees.
magnetic_field_strength
class-attribute
instance-attribute
magnetic_field_strength: Annotated[
float | None,
Bids(MagneticFieldStrength),
Scoped(ACQUISITION),
] = None
Nominal field strength, in tesla.
manufacturer
class-attribute
instance-attribute
manufacturer: Annotated[
Manufacturer | str | None,
Bids(Manufacturer),
Scoped(ACQUISITION),
] = None
Manufacturer of the equipment (a known one is a Manufacturer).
manufacturers_model_name
class-attribute
instance-attribute
manufacturers_model_name: Annotated[
str | None,
Bids(ManufacturersModelName),
Scoped(ACQUISITION),
] = None
Model name of the equipment.
institution_name
class-attribute
instance-attribute
Institution responsible for the equipment.
acquisition_time
class-attribute
instance-attribute
When the acquisition started.
phase_encoding_direction
class-attribute
instance-attribute
phase_encoding_direction: Annotated[
EncodingDirection | None,
Bids(PhaseEncodingDirection),
Scoped(SPATIAL),
ConvertTo(direction),
] = None
Phase-encoding direction: a unit vector.
By default in voxel axes (BIDS 'j-' is accepted).
total_readout_time
class-attribute
instance-attribute
Total readout time, in seconds.
effective_echo_spacing
class-attribute
instance-attribute
effective_echo_spacing: Annotated[
float | None,
Bids(EffectiveEchoSpacing),
Scoped(ACQUISITION),
] = None
Effective echo spacing, in seconds.
slice_encoding_direction
class-attribute
instance-attribute
slice_encoding_direction: Annotated[
EncodingDirection | None,
Bids(SliceEncodingDirection),
Scoped(SPATIAL),
ConvertTo(direction),
] = None
Slice-encoding direction: a unit vector, by default in voxel axes
(BIDS 'k' is accepted)."
slice_timing
class-attribute
instance-attribute
Acquisition time of each slice, in seconds, along the slice encoding direction.
multiband_acceleration_factor
class-attribute
instance-attribute
multiband_acceleration_factor: Annotated[
int | None,
Bids(MultibandAccelerationFactor),
Scoped(ACQUISITION),
] = None
Multiband acceleration factor.
bvalues
class-attribute
instance-attribute
One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."
bvectors
class-attribute
instance-attribute
One unit gradient direction per index along the time axis, in world (RAS) coordinates."
display_range
class-attribute
instance-attribute
Display window (min, max).
channels
class-attribute
instance-attribute
One description per channel. The descriptions run along the axes of
type channel only. The entries of a component axis, such as a
vector or a tensor axis, are described by the type, the valence,
the layout and the frame of that axis, so a change of frame, which
only re-expresses the values of component axes, keeps these
descriptions.
data_unit
class-attribute
instance-attribute
Unit of the data values: a Unit whenever the units module parses
the name ('a.u.', 'mm/s', 'HU'), and the name itself, as a
string, when it does not, so that a file with an odd unit still reads.
Formats write it as its symbol (Unit.symbol), which parses back to
the same unit.
dtype
class-attribute
instance-attribute
The element type of the data as stored, in native byte order.
It may differ from the type of the loaded array: a scaled integer
file loads as floating-point values. An override given to save or
to consolidate takes precedence over it.
scale_slope
class-attribute
instance-attribute
The slope of the intensity scaling:
a value is stored * scale_slope + scale_intercept.
None means no scaling.
scale_intercept
class-attribute
instance-attribute
The intercept of the intensity scaling (see scale_slope).
None means no intercept.
objective_magnification
class-attribute
instance-attribute
Nominal magnification of the objective.
objective_numerical_aperture
class-attribute
instance-attribute
Numerical aperture of the objective.
illumination_type
class-attribute
instance-attribute
illumination_type: Annotated[
IlluminationType | str | None, Scoped(ACQUISITION)
] = None
Illumination type (a known one is an IlluminationType).
contrast_method
class-attribute
instance-attribute
contrast_method: Annotated[
ContrastMethod | str | None, Scoped(ACQUISITION)
] = None
Contrast method (a known one is a ContrastMethod).
moving
class-attribute
instance-attribute
The moving image of a registration (file reference).
fixed
class-attribute
instance-attribute
The fixed image of a registration (file reference).
input_space
class-attribute
instance-attribute
Label of the space a transformation maps from.
output_space
class-attribute
instance-attribute
Label of the space a transformation maps to.
extra
class-attribute
instance-attribute
Free-form keys the vocabulary does not cover, copied into any free-form store a format has."
SUPPORTED_FIELDS
class-attribute
SUPPORTED_FIELDS: tuple[str, ...] = ()
The fields of the metadata that the format can store.
The names are those of the vocabulary, and "extra" when the format
has a free-form store. A field that is not listed is decoded as
None, and its value is reported as lost when the metadata is
consolidated. A conversion into the format reads this list to
report a lower bound of what a write would lose. The base class
lists no field.
RAW
class-attribute
RAW: type | None = None
The class of the record of the format, or None.
When the record class of a format can read or write a file, the
format sets this constant to it and lists
MetadataReader or
MetadataWriter among its
bases. These classes pass every input to the record class and every
output to the record, so the record class decides how each input is
read and which options it takes. A format that reads or writes its
header in another way leaves this constant at None and uses the
readers and writers of io/base/parsers.py instead.
raw
class-attribute
instance-attribute
The record of the dataset, or None for metadata without a record.
Methods:
sniff
classmethod
sniff(
file: FileOrContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Score how confidently a file or its content is of this type.
A path is sniffed with sniff_filename, an open file with
sniff_fileobj, and binary content with sniff_bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileOrContentLike
|
The file or its content. |
required |
error
|
bool or type of Exception
|
If not false, raise when the input cannot be sniffed: |
False
|
**kwargs
|
Any
|
Parser options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. An unsupported input scores zero. |
sniff_file
classmethod
Same as sniff, for a path or an open file.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_bytes
classmethod
sniff_bytes(
content: BinaryContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for binary content.
Compressed content is decompressed first. The content is then
wrapped in an io.BytesIO and scored with sniff_fileobj, so
that a class that scores a stream also scores bytes. If that
method only reads the stream back into bytes, as the default
does, the content would come back to this method, which then
raises instead.
Raises:
| Type | Description |
|---|---|
SnifferNotImplementedError
|
If neither this method nor |
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
sniff_lines
classmethod
Same as sniff, for an iterable of lines.
The first line is passed to sniff_line.
sniff_line
classmethod
Same as sniff, for a single line.
Raises:
| Type | Description |
|---|---|
SnifferNotImplementedError
|
In the base class, which cannot sniff a line. |
load
classmethod
load(other: FileOrContentLike, **kwargs) -> Self
Read an object from a path, an open file, or binary content.
Paths and open files are read with from_file, binary content
with from_bytes, and a SourceSpec with from_spec.
A str is always a path, whether or not the file exists, so text
held in memory must be read with from_text or
from_content. The default from_filename,
from_fileobj and from_bytes decompress a file or
content that gzip, bzip2 or xz compresses, so that a format that
does not override them reads compressed files too.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the path names a file that does not exist. |
ParserTypeError
|
If the input is of another type. |
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Read the file named by a specification without hints or options.
Raises:
| Type | Description |
|---|---|
TypeError
|
If the specification has hints or options, which only a dispatcher can apply. |
from_file
classmethod
Read an object from a path or an open file.
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_bytes
classmethod
from_bytes(content: BinaryContentLike, **kwargs) -> Self
Read an object from binary content.
Compressed content is decompressed first. If the class implements
from_fileobj itself, the content is
wrapped in an io.BytesIO and read with that method. Otherwise, this
method raises, because the default from_fileobj would pass the
content back to from_bytes and the fallback would recurse. An
override that only forwards to super().from_fileobj should be marked
with passthrough_from_fileobj. If such an override is not marked,
the loop is still detected when this method is entered again for the
same class.
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
If neither this method nor |
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
from_lines
classmethod
Read an object from an iterable of lines.
The first line is passed to from_line.
from_line
classmethod
Read an object from a single line.
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In the base class, which cannot read a line. |
from_dict
classmethod
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 |
from_instance
classmethod
from_instance(
other: Any,
*args: Any,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
**kwargs: Any,
) -> Self
Copy metadata into this format, field by field.
Every field of the vocabulary and extra are copied by name,
including those that this format cannot store, which are dropped
and reported only when the metadata is consolidated. The record
of another format means nothing to this one, so it is copied only
from metadata of this class. The fields that are set and that
SUPPORTED_FIELDS does not list are reported here as lost,
because a write will drop them, so the report is a lower bound of
what a write loses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The metadata to copy. |
required |
*args
|
Any
|
Constructor arguments, which take precedence over the fields
of |
()
|
on_loss
|
ErrorAction
|
What to do with the fields that this format cannot store:
|
UNSET
|
on_error
|
ErrorPolicy
|
What to do with a conversion error of the copy, including a
loss (see |
UNSET
|
**kwargs
|
Any
|
Fields to set on the result. |
{}
|
Returns:
| Type | Description |
|---|---|
MetadataFormat
|
The copy. |
Raises:
| Type | Description |
|---|---|
MetadataLossError
|
If a field is reported under the |
from_any
classmethod
Build metadata from a file, from other metadata, or from a value.
Metadata of any class, generic or of another format, is copied
field by field with from_instance. A file is read as
FileBasedModelMixin.from_any reads it, and any other value is
passed to the data model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A file, its content, metadata, or a mapping of fields. |
required |
*args
|
Any
|
Constructor arguments. |
()
|
**kwargs
|
Any
|
Fields of the metadata, or the options of the reader for a file. |
{}
|
Returns:
| Type | Description |
|---|---|
MetadataFormat
|
The metadata. |
to
to(
cls: Type[Metadata] | None = None,
*,
copy: bool = False,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
**values: Any,
) -> Metadata
Convert this metadata into another class.
This is the metadata counterpart of to on images and
transformations. Each field is copied by name. The record of a
file format means nothing to another format, so it is copied
only into the same class. A file format that has no slot for a
field that is set still receives the value, and reports it as
lost, because its next consolidation will drop it. The report is
acted on by the action that on_loss or on_error takes for a
MetadataLossError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The metadata class to convert into, such as |
None
|
copy
|
bool
|
Whether to return new metadata when nothing changes. By default, metadata converted to its own class without any field is returned itself. |
False
|
on_loss
|
ErrorAction
|
What to do with the fields that |
UNSET
|
on_error
|
ErrorPolicy
|
What to do with a conversion error, including a loss (see
|
UNSET
|
**values
|
Any
|
Fields to set on the result. |
{}
|
Returns:
| Type | Description |
|---|---|
Metadata
|
The converted metadata. |
Raises:
| Type | Description |
|---|---|
MetadataLossError
|
If a field is reported under the |
Examples:
derive
derive(
operation: Indexed | Resampled | None = None,
*,
history: str | Sequence[str] | None = None,
) -> Self
Return the metadata of an image computed from this one.
The fields follow
Metadata.derive,
which records the derivation in history and generated_by.
Those two fields keep their value when the format has no slot
for them, so that a derived image of the format is not reported
to lose a provenance that only the derivation added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
Indexed or Resampled
|
What the image operation did to the axes of the image. |
None
|
history
|
str or sequence of str
|
The steps of the derivation, appended to |
None
|
Returns:
| Type | Description |
|---|---|
MetadataFormat
|
New metadata, of the same class, which shares the record. |
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
|
UNSET
|
on_loss
|
ErrorAction
|
What to do with a loss, with the same values as a single
action of |
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 |
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 |
from_raw
classmethod
Build the metadata that holds a record.
A reader calls this method once it has parsed the header of a file. The record is held as it is given, without a copy. The format decodes the fields of the vocabulary from the record here, and the base class, which knows no record, decodes none.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
object
|
The header of a file, in the representation of the format. |
required |
**kwargs
|
Any
|
Other fields of the metadata, which take precedence over the decoded values. |
{}
|
Returns:
| Type | Description |
|---|---|
MetadataFormat
|
The metadata. |
save
save(file: FileLike, **kwargs) -> None
Write the object to a path or an open file.
The method is named save rather than to because the data models
that parsers are mixed into already use to for conversion, as in
Transformation.to, which would shadow the writer.
to_file
to_file(file: FileLike, **kwargs) -> None
Write the object to a path or a file object.
A file object needs a write method.
Raises:
| Type | Description |
|---|---|
ParserTypeError
|
If |
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the object to a file object open for writing.
A binary format writes the result of to_bytes. A text
format writes the result of to_text to a text stream, such
as a file opened with "w" or an io.StringIO, and the result
of to_bytes to any other stream, such as a file opened with
"wb" or an io.BytesIO.
to_text
to_text(**kwargs) -> str
Return the text of the file.
The text is made of the lines of to_lines, each followed by
a newline.
to_lines
Return the lines of the file, without terminators.
The default implementation yields the result of to_line as the
only line.
to_line
to_line(**kwargs) -> str
Return the single line that represents the object.
Raises:
| Type | Description |
|---|---|
WriterNotImplementedError
|
In the base class, which cannot write a line. |
sniff_fileobj
classmethod
Return the confidence that a stream holds an AFNI header.
The stream is tested with AfniRaw.sniff_fileobj.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The stream, whose position is restored. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the stream holds no AFNI header. |
False
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Return the confidence that a path names an AFNI dataset.
The path is tested with AfniRaw.sniff_filename, which reads
the .HEAD file of the dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
Any file of the dataset, or the bare dataset name. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the path names no AFNI dataset. |
False
|
**kwargs
|
Any
|
Options of the reader, which are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
from_fileobj
classmethod
from_fileobj(file: BinaryIO, **kwargs) -> AfniMetadata
Read the metadata from an open .HEAD or .BRIK file.
The record is read with AfniRaw.from_fileobj and validated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
BinaryIO
|
The open |
required |
**kwargs
|
Any
|
Options of |
{}
|
Returns:
| Type | Description |
|---|---|
AfniMetadata
|
The metadata, which holds the record of the header. |
Raises:
| Type | Description |
|---|---|
ParserContentError
|
If the stream holds no valid header, or is a BRIK without a file name. |
from_filename
classmethod
from_filename(
filename: FilenameLike, **kwargs
) -> AfniMetadata
Read the metadata from the path of a dataset.
The record is read from the .HEAD file with
AfniRaw.from_filename and validated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
Any file of the dataset, or the bare dataset name. |
required |
**kwargs
|
Any
|
Options of |
{}
|
Returns:
| Type | Description |
|---|---|
AfniMetadata
|
The metadata, which holds the record of the header. |
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the |
ParserContentError
|
If the header is invalid. |
to_bytes
to_bytes(**kwargs) -> bytes
Return the content of the .HEAD file.
Metadata without a record is written as an empty header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Options of |
{}
|
Returns:
| Type | Description |
|---|---|
bytes
|
The content of the |
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the .HEAD file of the dataset that a path names.
The path may name the .HEAD file, the .BRIK file or the bare
dataset, and no BRIK is written.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
Any file of the dataset, or the bare dataset name. |
required |
**kwargs
|
Any
|
Options of |
{}
|
AfniRaw
magic
Bases: Raw, BinaryFileReader, BinaryFileWriter
The attributes of an AFNI .HEAD file, as the file stores them.
An AFNI dataset is a text header, the .HEAD file, and a file of
voxel values, the .BRIK file. The record holds the whole header:
every attribute by name, and the text that it was read from. String
attributes are strings, with substrings separated by NUL, and numeric
attributes are tuples. The properties decode the attributes that
describe the voxels and the geometry, and the other attributes, such
as HISTORY_NOTE or BRICK_LABS, are written back unchanged.
The record knows where the voxels lie and how they are stored, but
it never reads them. It is held by
AfniMetadata, which never
changes it in place: a writer works on the copy that copy
returns, or builds a new record with replace.
A record compares by identity. Two records hold the same header when
their attributes are equal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attributes
|
dict[str, _Value]
|
All attributes by name, in file order. |
required |
text
|
NoRepr[str | None]
|
The text of the |
None
|
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.
text
class-attribute
instance-attribute
The text of the .HEAD file that the attributes were read from.
The text is written back as it is while it still describes the
attributes, so that a header that is read and written again keeps
its bytes, whichever program wrote it. Otherwise, and for a record
built from attributes alone, the attributes are formatted as AFNI
writes them. The text is None for a record built from attributes.
brick_types
property
brick_types: tuple[int, ...]
The BRICK_TYPES code of each sub-brick (int16 when absent; a short
list repeats its last code).
byteorder
property
byteorder: str
The byte order of the BRIK: "<", ">", or "=" (native) when the
header does not give one.
float_facs
property
float_facs: tuple[float, ...]
The scale factor of each sub-brick, 0 for an unscaled sub-brick.
real_matrix
property
real_matrix: ndarray | None
The IJK_TO_DICOM_REAL matrix, or None if absent or singular.
origin
property
The DICOM coordinate of the first voxel centre along each axis.
cardinal_matrix
property
cardinal_matrix: ndarray
The cardinal voxel-to-DICOM matrix, the grid AFNI computes on.
voxel_to_dicom
property
voxel_to_dicom: ndarray
The true voxel-to-DICOM matrix: the real matrix if any, else the cardinal one.
taxis
property
The repetition time and its unit, or None without a time axis.
The unit is "millisecond", "second", "hertz", or None.
Methods:
save
save(file: FileLike, **kwargs) -> None
Write the object to a path or an open file.
The method is named save rather than to because the data models
that parsers are mixed into already use to for conversion, as in
Transformation.to, which would shadow the writer.
to_file
to_file(file: FileLike, **kwargs) -> None
Write the object to a path or a file object.
A file object needs a write method.
Raises:
| Type | Description |
|---|---|
ParserTypeError
|
If |
to_filename
to_filename(filename: FilenameLike, **kwargs) -> None
Write the object to a path, always as bytes.
The content is encoded before the target changes, so that an
error while it is encoded leaves the target as it was. A local
file is written next to its target, which it then replaces at
once. A remote file is written once the whole content is
encoded. A text format is written with to_bytes, so that
its line endings are written as they are, on every system. A
binary format is written with to_fileobj, which a local
file receives as it is written and a remote file receives once
it is complete. A name that ends with .gz, .bz2 or .xz
compresses the file, whatever the format.
to_fileobj
to_fileobj(file: IO, **kwargs) -> None
Write the object to a file object open for writing.
A binary format writes the result of to_bytes. A text
format writes the result of to_text to a text stream, such
as a file opened with "w" or an io.StringIO, and the result
of to_bytes to any other stream, such as a file opened with
"wb" or an io.BytesIO.
to_lines
Return the lines of the file, without terminators.
The default implementation yields the result of to_line as the
only line.
to_line
to_line(**kwargs) -> str
Return the single line that represents the object.
Raises:
| Type | Description |
|---|---|
WriterNotImplementedError
|
In the base class, which cannot write a line. |
sniff
classmethod
sniff(
file: FileOrContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Score how confidently a file or its content is of this type.
A path is sniffed with sniff_filename, an open file with
sniff_fileobj, and binary content with sniff_bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
FileOrContentLike
|
The file or its content. |
required |
error
|
bool or type of Exception
|
If not false, raise when the input cannot be sniffed: |
False
|
**kwargs
|
Any
|
Parser options. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. An unsupported input scores zero. |
sniff_file
classmethod
Same as sniff, for a path or an open file.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_bytes
classmethod
sniff_bytes(
content: BinaryContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for binary content.
Compressed content is decompressed first. The content is then
wrapped in an io.BytesIO and scored with sniff_fileobj, so
that a class that scores a stream also scores bytes. If that
method only reads the stream back into bytes, as the default
does, the content would come back to this method, which then
raises instead.
Raises:
| Type | Description |
|---|---|
SnifferNotImplementedError
|
If neither this method nor |
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
sniff_lines
classmethod
Same as sniff, for an iterable of lines.
The first line is passed to sniff_line.
sniff_line
classmethod
Same as sniff, for a single line.
Raises:
| Type | Description |
|---|---|
SnifferNotImplementedError
|
In the base class, which cannot sniff a line. |
load
classmethod
load(other: FileOrContentLike, **kwargs) -> Self
Read an object from a path, an open file, or binary content.
Paths and open files are read with from_file, binary content
with from_bytes, and a SourceSpec with from_spec.
A str is always a path, whether or not the file exists, so text
held in memory must be read with from_text or
from_content. The default from_filename,
from_fileobj and from_bytes decompress a file or
content that gzip, bzip2 or xz compresses, so that a format that
does not override them reads compressed files too.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the path names a file that does not exist. |
ParserTypeError
|
If the input is of another type. |
from_spec
classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self
Read the file named by a specification without hints or options.
Raises:
| Type | Description |
|---|---|
TypeError
|
If the specification has hints or options, which only a dispatcher can apply. |
from_file
classmethod
Read an object from a path or an open file.
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_lines
classmethod
Read an object from an iterable of lines.
The first line is passed to from_line.
from_line
classmethod
Read an object from a single line.
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In the base class, which cannot read a line. |
from_dict
classmethod
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 |
from_instance
classmethod
Build an instance from an instance of a related data model.
Two classes are related when:
- one of them is a parent of the other, or
- when both belong to the same polymorphic family, or
- when they represent the same "data model".
In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.
Note
- Only attributes that name keyword arguments are used.
- An attribute that is
Noneleaves the default of the class in place. - Extra arguments (
*argsand**kwargs) are passed to the constructor and take precedence. - Unless
otheris already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value. - In genemost casesral,
cls.from_instance(other)is equivalent toother.to(cls, copy=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
DataModelBase
|
The instance to copy. |
required |
*args
|
Any
|
Constructor arguments, which take precedence over the fields
of |
()
|
**kwargs
|
Any
|
Constructor arguments, which take precedence over the fields
of |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ConversionError
|
If the class of |
ValueError
|
If a fixed field of |
from_any
classmethod
Build an instance from a mapping, a data model or an argument.
This constructors dispatches to from_dict, from_instance
or the constructor, depending on the type of other.
Raises:
| Type | Description |
|---|---|
TypeError
|
If a mapping has a key that names no field. Unlike
|
to
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 |
Raises:
| Type | Description |
|---|---|
ConversionError
|
If |
copy
copy() -> Self
get
Return the value of an attribute, or default if it is absent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the attribute, such as |
required |
default
|
Any
|
The value returned when the record has no such attribute. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value of the attribute: a string, or a tuple of numbers. |
validate
validate() -> AfniRaw
Check that the header describes a readable, non-empty dataset.
Returns:
| Type | Description |
|---|---|
AfniRaw
|
The record itself, so that the check can be chained. |
Raises:
| Type | Description |
|---|---|
ParserContentError
|
If a mandatory attribute is missing or invalid. |
replace
replace(**attributes: _Value | None) -> AfniRaw
Return a record with attributes set, or removed when given None.
The new record has no text, so it is formatted from its attributes when it is written.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**attributes
|
str or tuple of numbers
|
The attributes to set, by name. An attribute given |
{}
|
Returns:
| Type | Description |
|---|---|
AfniRaw
|
The new record. This record is not changed. |
from_text
classmethod
Parse the text of a .HEAD file, which the record keeps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text of the file. |
required |
**kwargs
|
Any
|
Refused, since the record has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
AfniRaw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given, since the record has none. |
ParserContentError
|
If the text is not an AFNI header. |
from_bytes
classmethod
Parse the content of a .HEAD file.
The content is decoded as Latin-1, as AFNI reads it. An option is
refused with TypeError, since the record has none.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
Refused, since the record has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
AfniRaw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given, since the record has none. |
ParserContentError
|
If the content is not an AFNI header. |
from_fileobj
classmethod
Read the record from an open .HEAD or .BRIK file.
A .HEAD stream is read whole. A stream of any other content is
taken to be the BRIK of a dataset, which is not read beyond its
start, and the header is found from the name of the stream. The
position of the stream is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The stream, open in binary mode. |
required |
**kwargs
|
Any
|
Refused, since the record has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
AfniRaw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given, since the record has none. |
ParserContentError
|
If the stream is not a header and has no file name, or if the header is not valid. |
from_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> AfniRaw
Read the record from the path of a dataset.
The path may name the .HEAD file, the .BRIK file or the bare
dataset, and only the .HEAD file is read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The path of the |
required |
**kwargs
|
Any
|
Refused, since the record has no option. |
{}
|
Returns:
| Type | Description |
|---|---|
AfniRaw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is given, since the record has none. |
ParserExistsError
|
If the |
ParserContentError
|
If the file is not an AFNI header. |
sniff_fileobj
classmethod
Return the confidence that a stream holds a valid AFNI header.
Only the start of a stream that does not look like a header is read, and the position of the stream is restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The stream to test, open in binary mode. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the stream holds no valid
header. With |
False
|
**kwargs
|
Any
|
Ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
SnifferContentError
|
If the stream holds no valid header and |
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Return the confidence that a path names an AFNI dataset.
The .HEAD file of the dataset is tested, whichever file of the
dataset the path names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The path of the |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the path names no valid
dataset, as in |
False
|
**kwargs
|
Any
|
Ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
SnifferContentError
|
If the path names no valid dataset and |
to_text
to_text(**kwargs) -> str
Return the text of the .HEAD file.
The text that the record was read from is returned while it still describes the attributes. Otherwise, the attributes are formatted as AFNI writes them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The text of the file. |