brainhops.io.common.analyze
Reading of Analyze 7.5 images.
Analyze 7.5 is the format from which NIfTI-1 descends. Old data sets,
and the files that SPM99 and SPM2 write, still use it. An image is a
pair of files with the same name: a header file (.hdr) of 348 bytes,
and an image file (.img) that holds the voxels, with the first axis
varying fastest. A header whose magic number is that of NIfTI-1 (ni1)
belongs to a NIfTI pair, which the NIfTI readers handle, so the Analyze
readers refuse it.
The header is held as an AnalyzeRaw record, and
AnalyzeMetadata reads that record without the voxels.
AnalyzeImage holds such
metadata and a lazy array of the voxels. That lazy array is the one that
reads the voxels of NIfTI files, because both formats store their voxels
in the same way.
An Analyze header stores no orientation. The voxel-to-world matrix is built from the voxel sizes and from the origin that SPM stores in the header, with the first axis running from right to left, as SPM and nibabel build it. The fields that SPM uses as a scale factor and as an intercept scale the voxels, as nibabel scales them. Analyze files are only read, and an image is saved to another format, such as NIfTI.
Classes
AnalyzeMetadata
magic
AnalyzeMetadata(
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[AnalyzeRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: MetadataReader, MetadataFormat
Metadata of an Analyze 7.5 image, which is its header.
The metadata of an Analyze image is read from its header file alone,
and held as an AnalyzeRaw record, so the image file is never
read. The metadata keeps no open file. Analyze files cannot be
written, so the metadata cannot be written either, and no field of
the vocabulary is decoded from the header yet.
A file is read through the record: [from_fileobj][] reads an
AnalyzeRaw and wraps it.
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[AnalyzeRaw | None]
|
The header of the image, 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
instance-attribute
raw: NoRepr[AnalyzeRaw | None] = None
The header of the image, 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_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Score a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The path of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the file is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_fileobj
classmethod
Score an open file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The open file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the file is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
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
Score the content of a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the content is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_text
classmethod
Score the text of a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the text is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_lines
classmethod
Score the lines of a file, as the record class scores them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
The lines of the file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the lines are not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
sniff_line
classmethod
Score the first line of a file, as the record class scores it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The line. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the line is not of the format. |
False
|
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read the metadata from a path, through the record class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The path of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_fileobj
classmethod
Read the metadata from an open file, through the record class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
IO
|
The open file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
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 the metadata from the content of a file.
The content is read by the record class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_text
classmethod
Read the metadata from the text of a file, through the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_lines
classmethod
Read the metadata from the lines of a file, through the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
The lines of the file. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
from_line
classmethod
Read the metadata from a single line, through the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The line. |
required |
**kwargs
|
Any
|
Options of the reader of the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The metadata. |
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. |
AnalyzeRaw
magic
Bases: Raw, BinaryFileReader
Header of an Analyze 7.5 image, as the header file stores it.
An Analyze 7.5 image is a pair of files: a header file (.hdr) of
348 bytes, and an image file (.img) that holds the voxels. NIfTI-1
descends from this format and keeps the same header size, so a
header that carries the NIfTI-1 magic number is a NIfTI header and
is refused here. The record holds the header as nibabel parses it
with the SPM2 interpretation of its unused fields
(nibabel.Spm2AnalyzeHeader), which is also what nibabel.load
uses for such a pair. Under that interpretation, the field
funused1 is a scale factor, funused2 is an intercept, and the
field originator holds the origin of the image in voxels.
A record is read from the header file alone, so the voxels are never
read. It is held by
AnalyzeMetadata.
Analyze files cannot be written, so a record is never written
either.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
header
|
Spm2AnalyzeHeader
|
The header, as nibabel parses it. A new record holds an empty header. |
Spm2AnalyzeHeader()
|
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.
header
instance-attribute
The header, as nibabel parses it.
A new record holds an empty header.
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
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
Return a copy of the record that can be changed freely.
Returns:
| Type | Description |
|---|---|
AnalyzeRaw
|
The copy, whose header is a copy of this header. |
sniff_filename
classmethod
sniff_filename(
filename: FilenameLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Return the confidence that a path names an Analyze image.
The header file of the pair is tested, whichever file of the pair the path names, so that a path to the image file is recognized too. A path that names neither file of a pair is tested as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The path of the header file or of the image file. |
required |
error
|
bool or type[Exception]
|
Whether to raise an error when the path names no Analyze
image. With |
False
|
**kwargs
|
Any
|
Ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
The confidence, between 0 and 1. |
from_filename
classmethod
from_filename(
filename: FilenameLike, **kwargs
) -> AnalyzeRaw
Read the header of the Analyze image that a path names.
The header file of the pair is read, whichever file of the pair the path names. A path that names neither file of a pair is read as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
path - like
|
The path of the header file or of the image file. |
required |
**kwargs
|
Any
|
The options of |
{}
|
Returns:
| Type | Description |
|---|---|
AnalyzeRaw
|
The record. |
sniff_fileobj
classmethod
Return the confidence that a stream holds an Analyze header.
A stream that starts with the header size of Analyze, in either byte order, followed by a header that nibabel can parse and whose dimensions are valid, is very likely an Analyze header. A stream with the NIfTI-1 magic number is declined, because the NIfTI readers handle it. The stream may be compressed with gzip, and its position 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 Analyze
header. With |
False
|
**kwargs
|
Any
|
Ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
SnifferContentError
|
If the stream holds no Analyze header and |
from_fileobj
classmethod
from_fileobj(
file: BinaryIO, check: bool = True, **kwargs
) -> AnalyzeRaw
Read the header at the start of an Analyze header stream.
The stream may be compressed with gzip, and its position is restored. Only the 348 bytes of the header are read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The stream, open in binary mode. |
required |
check
|
bool
|
Whether nibabel checks the header, and fixes the fields that it can fix, such as a voxel size of zero. |
True
|
**kwargs
|
Any
|
Refused, since the record has no other option. |
{}
|
Returns:
| Type | Description |
|---|---|
AnalyzeRaw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If another option is given. |
ParserContentError
|
If the stream holds a NIfTI-1 header, or holds less than a header. |