A plain matrix file stores an affine transformation and nothing else: no
coordinate systems, no index base and no direction. brainhops has one
reader for each kind of container. Each reader is built on the generic
array parser of its container, from brainhops.io.common._arrays, and all
of them derive from the abstract MatrixAffine, which is never
registered itself.
| Class | Container | Extensions | Hints |
|---|---|---|---|
TxtMatrixAffine |
whitespace-separated text | .txt, .dat, .1D |
"matrix.txt" |
CsvMatrixAffine |
comma-separated text | .csv |
"matrix.csv" |
TsvMatrixAffine |
tab-separated text | .tsv |
"matrix.tsv" |
NpyMatrixAffine |
NumPy .npy |
.npy |
"matrix.npy" |
NpzMatrixAffine |
NumPy .npz |
.npz |
"matrix.npz" |
MatLegacyMatrixAffine |
MATLAB v4, v5-v7 (scipy) |
.mat |
"matrix.mat" |
Mat73MatrixAffine |
MATLAB v7.3 (h5py) |
.mat |
"matrix.mat", "mat.73", "matrix.mat.73" |
MatMatrixAffine (hint "matrix.mat") is the parent of the two
MATLAB readers. It is not registered, since its two variants are, but it
can be used directly: it reads a file of any MATLAB version and returns an
object of the matching variant. AFNI .1D files and generic .dat files
hold whitespace-separated columns with # comments, so they are read by
TxtMatrixAffine.
The hint "matrix" selects among all of these readers by content, while a
container hint such as "matrix.csv" selects one of them. Since the file
records nothing but the matrix, its conventions are given as keyword
arguments when it is read:
| Keyword | Default | Meaning |
|---|---|---|
vector |
"column" |
"row" if the file maps row vectors (y = x @ A); it is transposed. |
ndim |
None |
2 to read a (3, 3) matrix as a 2-D affine (else 3-D linear). |
direction |
"forward" |
"inverse" if the file maps output to input; it is inverted. |
input |
None |
"voxel", "ras", "lps", a CoordinateSystem, or unnamed. |
output |
None |
Same as input. |
index_base |
0 |
1 for 1-based voxel indices (MATLAB, SPM), or an (input, output) pair. |
source |
None |
Image whose voxel-to-world affine maps a voxel input to world. |
target |
None |
Image whose voxel-to-world affine maps a voxel output to world. |
variable |
None |
.npz key or .mat variable (alias key); by default the only 2-D numeric array. |
The images given as source and target may be nibabel images or
headers, or brainhops images. The conventions are applied in a fixed
order: transposition, then inversion, then the index shift, and finally
the placement in image space. The result is always an affine that maps
column vectors and uses 0-based indices, in which an integer index is the
centre of a voxel (see #201).
A plain matrix file is read in one pass. The matrix as it is stored, and
the conventions that it was read with, are kept in a
MatrixAffineRaw
record, which the metadata of the file holds. Each container has its own
metadata class, such as
TxtMatrixMetadata,
and the record of a text file also keeps the text of the file. The record
is read from xform.metadata.raw, whose fields matrix, variable,
vector, direction, index_base, ndim, source_to_world and
target_to_world replace the former attributes raw_matrix, variable,
vector, direction and index_base of the transformation. A matrix
that is assigned stays pending until consolidate() stores it in a new
record, in the conventions and the layout of the file. The readers
refuse an option that they do not know with TypeError, and a container
that holds a single array also refuses variable and key. These
formats read files and do not write them.
from brainhops import io
affine = io.transformations.load("affine.txt", input="ras", output="ras")
rows = io.transformations.load("rows.csv", hint="matrix", vector="row")
Any small numeric table can be read as a matrix, so these readers give
themselves a low score and never take a file away from a format that
recognises it positively, such as a FLIRT .mat (text) or an ITK .mat
(MATLAB v4), .tfm or .h5 file. The exception is a text matrix whose
file name has a text-array extension (.txt, .csv, .tsv, .dat or
.1D) that matches its separator: such a file is preferred to the FLIRT
reader. Without an informative name, text content is offered to one reader
only, chosen by its separator: commas select the CSV reader, tabs the TSV
reader, and anything else the whitespace reader. Files larger than 1 MiB
are not inspected at all. To force these readers, pass hint="matrix" or a
container hint.
brainhops.io.transformations.matrix
Plain affine matrices stored in text, NumPy or MATLAB files.
The file holds only numbers, so the caller states their meaning when the file
is read, as described in
MatrixAffine. Each
container has its own reader: TxtMatrixAffine, CsvMatrixAffine,
TsvMatrixAffine, NpyMatrixAffine, NpzMatrixAffine and
MatMatrixAffine, which hands the file to MatLegacyMatrixAffine or
Mat73MatrixAffine according to its MATLAB version.
A plain matrix file is short and is read in one pass. Its matrix, and
the conventions that the caller stated when the file was read, are held
as a MatrixAffineRaw record by the metadata of the file, such as
TxtMatrixMetadata or NpzMatrixMetadata, and the
transformation decodes its matrix and its coordinate systems from that
record. These formats read files and do not write them.
Reading a 1-based voxel-to-voxel matrix saved by MATLAB
Classes
CsvMatrixMetadata
magic
CsvMatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: CsvArrayReader, MatrixMetadata
Metadata of a comma-separated .csv matrix file.
The record keeps the text of the file. See MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, or None for metadata without a record.
NAMED_CONFIDENCE
class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY
The minimum score of a text array whose file has an extension of this reader.
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
Sniff binary content as text.
Compressed content is decompressed first. The content is decoded
with the encoding keyword, UTF-8 by default, and passed to
sniff_text. Content that does not decode scores
Confidence.NO, or raises SnifferContentError if error is
set.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_text
classmethod
from_text(text: str, **options) -> CsvMatrixMetadata
Read the metadata from the text of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
CsvMatrixMetadata
|
The metadata, which holds the record of the file. |
from_lines
classmethod
from_lines(
lines: Iterable[str], **options
) -> CsvMatrixMetadata
Read the metadata from the lines of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
iterable of str
|
The lines of the file. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
CsvMatrixMetadata
|
The metadata, which holds the record of the file. |
Mat73MatrixMetadata
magic
Mat73MatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: Mat73ArrayReader, MatrixMetadata
Metadata of a MATLAB v7.3 (HDF5) .mat matrix file.
The file is read with h5py, and MATLAB stores arrays transposed,
which the reader undoes. The variable is selected with variable or
key, and defaults to the only 2-D numeric array. The record keeps
its name. See MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, or None for metadata without a record.
VARIANTS
class-attribute
VARIANTS: tuple[type, ...] = ()
The readers dispatched to: MATLAB v4 to v7, then v7.3.
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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_fileobj
classmethod
from_fileobj(file: IO, **options) -> Mat73MatrixMetadata
Read the metadata from a binary file object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**options
|
Any
|
The conventions of the matrix, and |
{}
|
Returns:
| Type | Description |
|---|---|
Mat73MatrixMetadata
|
The metadata, which holds the record of the file. |
from_bytes
classmethod
from_bytes(
content: bytes, **options
) -> Mat73MatrixMetadata
Read the metadata from the content of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix, and |
{}
|
Returns:
| Type | Description |
|---|---|
Mat73MatrixMetadata
|
The metadata, which holds the record of the file. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is not a convention, |
ParserContentError
|
If the content is not a MATLAB v7.3 file, or holds no single variable that reads as an affine matrix. |
ImportError
|
If h5py is not installed. |
MatLegacyMatrixMetadata
magic
MatLegacyMatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: MatLegacyArrayReader, MatrixMetadata
Metadata of a MATLAB v4 or v5 to v7 .mat matrix file.
The file is read with scipy.io. The variable is selected with
variable or key, and defaults to the only 2-D numeric array. The
record keeps its name. See MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, or None for metadata without a record.
VARIANTS
class-attribute
VARIANTS: tuple[type, ...] = ()
The readers dispatched to: MATLAB v4 to v7, then v7.3.
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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_fileobj
classmethod
from_fileobj(
file: IO, **options
) -> MatLegacyMatrixMetadata
Read the metadata from a binary file object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**options
|
Any
|
The conventions of the matrix, and |
{}
|
Returns:
| Type | Description |
|---|---|
MatLegacyMatrixMetadata
|
The metadata, which holds the record of the file. |
from_bytes
classmethod
from_bytes(
content: bytes, **options
) -> MatLegacyMatrixMetadata
Read the metadata from the content of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix, and |
{}
|
Returns:
| Type | Description |
|---|---|
MatLegacyMatrixMetadata
|
The metadata, which holds the record of the file. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is not a convention, |
ParserContentError
|
If the content is not a MATLAB v4 to v7 file, or holds no single variable that reads as an affine matrix. |
MatrixMetadata
magic
MatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: ArrayReader, MetadataFormat
Metadata of a plain matrix file, which holds the file as a record.
A plain matrix file holds a small matrix and nothing else, so it is
read in one pass, and its record, a MatrixAffineRaw, holds the
whole file together with the conventions that the caller stated when
the file was read. The data of a plain matrix format, such as a
TxtMatrixAffine,
therefore lives in the record of its metadata, and reading the
metadata of a file reads the same content as reading the
transformation. The metadata keeps no open file.
This class is the abstract base of the metadata of each container,
which is registered, and it is not registered itself. The readers
take the conventions of the matrix as options, and the readers of
.npz and .mat files also take variable (or its alias key).
Any other option raises TypeError. The metadata cannot be written,
because the plain matrix formats have no writer.
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[MatrixAffineRaw | None]
|
The content of the file, 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
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.
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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_fileobj
classmethod
Read an object from a file object open for reading.
The default implementation reads the whole stream and passes it to
from_content, and from_bytes decompresses binary content
that is compressed. A parser that needs only part of the stream,
such as a header, should override this method. from_bytes
then wraps binary content in a stream and reads it with the
override. An override receives the stream as the caller gave it,
compressed or not, and decompresses it itself, because a lazy array
that keeps the stream must read it from the position where the
file starts.
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. |
NpyMatrixMetadata
magic
NpyMatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: NpyArrayReader, MatrixMetadata
Metadata of a NumPy .npy matrix file, read without unpickling.
See MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_fileobj
classmethod
from_fileobj(file: IO, **options) -> NpyMatrixMetadata
Read the metadata from a binary file object.
The whole stream is read, because the file holds nothing but the matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
NpyMatrixMetadata
|
The metadata, which holds the record of the file. |
from_bytes
classmethod
from_bytes(content: bytes, **options) -> NpyMatrixMetadata
Read the metadata from the content of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
NpyMatrixMetadata
|
The metadata, which holds the record of the file. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is not a convention, such as |
ParserContentError
|
If the content is not a |
NpzMatrixMetadata
magic
NpzMatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: NpzArrayReader, MatrixMetadata
Metadata of a NumPy .npz matrix file, read without unpickling.
The array is selected with variable or key, and defaults to the
only 2-D numeric array. The record keeps its name. See
MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_fileobj
classmethod
from_fileobj(file: IO, **options) -> NpzMatrixMetadata
Read the metadata from a binary file object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**options
|
Any
|
The conventions of the matrix, and |
{}
|
Returns:
| Type | Description |
|---|---|
NpzMatrixMetadata
|
The metadata, which holds the record of the file. |
from_bytes
classmethod
from_bytes(content: bytes, **options) -> NpzMatrixMetadata
Read the metadata from the content of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix, and |
{}
|
Returns:
| Type | Description |
|---|---|
NpzMatrixMetadata
|
The metadata, which holds the record of the file. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is not a convention, |
ParserContentError
|
If the content is not a |
TsvMatrixMetadata
magic
TsvMatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: TsvArrayReader, MatrixMetadata
Metadata of a tab-separated .tsv matrix file.
The record keeps the text of the file. See MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, or None for metadata without a record.
NAMED_CONFIDENCE
class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY
The minimum score of a text array whose file has an extension of this reader.
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
Sniff binary content as text.
Compressed content is decompressed first. The content is decoded
with the encoding keyword, UTF-8 by default, and passed to
sniff_text. Content that does not decode scores
Confidence.NO, or raises SnifferContentError if error is
set.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_text
classmethod
from_text(text: str, **options) -> TsvMatrixMetadata
Read the metadata from the text of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
TsvMatrixMetadata
|
The metadata, which holds the record of the file. |
from_lines
classmethod
from_lines(
lines: Iterable[str], **options
) -> TsvMatrixMetadata
Read the metadata from the lines of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
iterable of str
|
The lines of the file. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
TsvMatrixMetadata
|
The metadata, which holds the record of the file. |
TxtMatrixMetadata
magic
TxtMatrixMetadata(
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[MatrixAffineRaw | None] = None,
*,
extra: dict[str, Any] = Factory(),
)
Bases: TxtArrayReader, MatrixMetadata
Metadata of a whitespace-separated text matrix file.
This covers .txt, .dat and AFNI .1D files. The record keeps the
text of the file. See MatrixMetadata.
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[MatrixAffineRaw | None]
|
The content of the file, 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
raw: NoRepr[MatrixAffineRaw | None] = None
The content of the file, or None for metadata without a record.
NAMED_CONFIDENCE
class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY
The minimum score of a text array whose file has an extension of this reader.
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
Sniff binary content as text.
Compressed content is decompressed first. The content is decoded
with the encoding keyword, UTF-8 by default, and passed to
sniff_text. Content that does not decode scores
Confidence.NO, or raises SnifferContentError if error is
set.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
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. |
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_text
classmethod
from_text(text: str, **options) -> TxtMatrixMetadata
Read the metadata from the text of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The content of the file. |
required |
**options
|
Any
|
The conventions of the matrix, as
|
{}
|
Returns:
| Type | Description |
|---|---|
TxtMatrixMetadata
|
The metadata, which holds the record of the file. |
from_lines
classmethod
from_lines(
lines: Iterable[str], **options
) -> TxtMatrixMetadata
Read the metadata from the lines of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
iterable of str
|
The lines of the file. |
required |
**options
|
Any
|
The conventions of the matrix. |
{}
|
Returns:
| Type | Description |
|---|---|
TxtMatrixMetadata
|
The metadata, which holds the record of the file. |
MatrixAffineRaw
magic
MatrixAffineRaw(
matrix: _Matrix = (),
text: NoRepr[str | None] = None,
variable: str | None = None,
ndim: int = 3,
vector: str = "column",
direction: str = "forward",
index_base: tuple[int, int] = (0, 0),
source_to_world: _Matrix | None = None,
target_to_world: _Matrix | None = None,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: Raw
Record of a plain matrix file, and of the conventions it was read in.
A plain matrix file holds a small matrix and nothing else, so it is
read in one pass, and the record holds the whole file: the matrix as
it is stored, and, for a text file, the text that it was read from.
The file records nothing of what the matrix means, so the caller
states its conventions when the file is read, as described in
MatrixAffine,
and the record keeps them in the form that decodes the matrix. The
metadata of every plain matrix format, such as
TxtMatrixMetadata
or
NpzMatrixMetadata,
holds a record of this type, and a plain matrix format reads its
matrix and its coordinate systems from that record. A record is never
changed in place, so that several objects can share it.
The record of a file that is read describes the file. The record of a transformation that is consolidated holds the matrix of the transformation, stored in the conventions and the layout of the record that it replaces, and no text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
_Matrix
|
The matrix as the file stores it, as a tuple of rows of floats. The matrix may be of shape (3, 3), (3, 4) or (4, 4) in 3-D, or (2, 3) or (3, 3) in 2-D, or the transpose of one of these for row vectors. |
()
|
text
|
NoRepr[str | None]
|
The text of a text file, as it was read. It is |
None
|
variable
|
str | None
|
The |
None
|
ndim
|
int
|
The number of spatial dimensions that the matrix acts on, 2 or 3. |
3
|
vector
|
str
|
|
'column'
|
direction
|
str
|
|
'forward'
|
index_base
|
tuple[int, int]
|
The index base of the input and of the output, each 0 or 1. |
(0, 0)
|
source_to_world
|
_Matrix | None
|
The voxel-to-world matrix of the source image, or |
None
|
target_to_world
|
_Matrix | None
|
The voxel-to-world matrix of the target image, or |
None
|
input
|
CoordinateSystem | None
|
The input coordinate system of the affine that the record holds. |
None
|
output
|
CoordinateSystem | None
|
The output coordinate system of the affine that the record holds. |
None
|
Attributes
matrix
class-attribute
instance-attribute
The matrix as the file stores it, as a tuple of rows of floats.
The matrix may be of shape (3, 3), (3, 4) or (4, 4) in 3-D, or (2, 3) or (3, 3) in 2-D, or the transpose of one of these for row vectors.
text
class-attribute
instance-attribute
The text of a text file, as it was read.
It is None for a binary container and for a record that was encoded
from a matrix.
variable
class-attribute
instance-attribute
variable: str | None = None
The .npz key or the .mat variable that holds the matrix.
It is None for a container that holds a single array.
ndim
class-attribute
instance-attribute
ndim: int = 3
The number of spatial dimensions that the matrix acts on, 2 or 3.
vector
class-attribute
instance-attribute
vector: str = 'column'
"column", or "row" when the stored matrix is applied as x @ A.
direction
class-attribute
instance-attribute
direction: str = 'forward'
"forward", or "inverse" when the matrix maps output to input.
index_base
class-attribute
instance-attribute
The index base of the input and of the output, each 0 or 1.
source_to_world
class-attribute
instance-attribute
The voxel-to-world matrix of the source image, or None.
When it is given, the voxel input of the stored matrix is placed in the world space of the source image.
target_to_world
class-attribute
instance-attribute
The voxel-to-world matrix of the target image, or None.
When it is given, the voxel output of the stored matrix is placed in the world space of the target image.
input
class-attribute
instance-attribute
The input coordinate system of the affine that the record holds.
output
class-attribute
instance-attribute
The output coordinate system of the affine that the record holds.
Methods:
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 |
from_array
classmethod
from_array(
array: Any,
*,
text: str | None = None,
variable: str | None = None,
**conventions,
) -> MatrixAffineRaw
Build the record of a matrix read from a file, in its conventions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
array_like
|
The two-dimensional matrix that the file stores. |
required |
text
|
str
|
The text of a text file, which the record keeps. |
None
|
variable
|
str
|
The name of the matrix in a container of several arrays. |
None
|
**conventions
|
Any
|
The conventions of the matrix: |
{}
|
Returns:
| Type | Description |
|---|---|
MatrixAffineRaw
|
The record. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an option is not a convention. |
ParserContentError
|
If the matrix is not the matrix of an affine, or if the conventions contradict each other. |
affine
affine() -> ndarray
Return the homogeneous matrix of the affine that the record holds.
The conventions of the record are applied to its matrix, in the
order described in
MatrixAffine.
Returns:
| Type | Description |
|---|---|
ndarray
|
The |
CsvMatrixAffine
magic
CsvMatrixAffine(
metadata: NoRepr[CsvMatrixMetadata | None] = Inherit(
"metadata", default=None
),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: CsvArrayReader, MatrixAffine
Affine stored in a comma-separated .csv file.
The record keeps the text of the file. See MatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[CsvMatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
NAMED_CONFIDENCE
class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY
The minimum score of a text array whose file has an extension of this reader.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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
Sniff binary content as text.
Compressed content is decompressed first. The content is decoded
with the encoding keyword, UTF-8 by default, and passed to
sniff_text. Content that does not decode scores
Confidence.NO, or raises SnifferContentError if error is
set.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_text
classmethod
Build a transformation from the text of a file.
The text is read by CsvMatrixMetadata.from_text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_lines
classmethod
Build a transformation from the lines of a file.
The lines are read by CsvMatrixMetadata.from_lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
iterable of str
|
The lines of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |
Mat73MatrixAffine
magic
Mat73MatrixAffine(
metadata: NoRepr[Mat73MatrixMetadata | None] = Inherit(
"metadata", default=None
),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: Mat73ArrayReader, MatMatrixAffine
Affine stored in a MATLAB v7.3 (HDF5) .mat file, read with h5py.
MATLAB v7.3 stores arrays transposed, which the reader undoes. The
record keeps the name of the variable. See MatMatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[Mat73MatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
VARIANTS
class-attribute
VARIANTS: tuple[type, ...] = ()
The readers dispatched to: MATLAB v4 to v7, then v7.3.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_fileobj
classmethod
Build a transformation from a binary file object.
The file is read by Mat73MatrixMetadata.from_fileobj.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_bytes
classmethod
Build a transformation from the content of a file.
The content is read by Mat73MatrixMetadata.from_bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |
MatLegacyMatrixAffine
magic
MatLegacyMatrixAffine(
metadata: NoRepr[
MatLegacyMatrixMetadata | None
] = Inherit("metadata", default=None),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: MatLegacyArrayReader, MatMatrixAffine
Affine stored in a MATLAB v4 or v5 to v7 .mat file, read with scipy.io.
The record keeps the name of the variable. See MatMatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[MatLegacyMatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
VARIANTS
class-attribute
VARIANTS: tuple[type, ...] = ()
The readers dispatched to: MATLAB v4 to v7, then v7.3.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_fileobj
classmethod
Build a transformation from a binary file object.
The file is read by MatLegacyMatrixMetadata.from_fileobj.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_bytes
classmethod
Build a transformation from the content of a file.
The content is read by MatLegacyMatrixMetadata.from_bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |
MatMatrixAffine
magic
MatMatrixAffine(
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
metadata: NoRepr[Metadata | None] = None,
)
Bases: MatArrayReader, MatrixAffine
Affine stored in a MATLAB .mat file of any version.
The variable is selected with variable=, and defaults to the only 2-D
numeric array. The file is dispatched by content to
MatLegacyMatrixAffine or Mat73MatrixAffine, which returns an
object of that class. Only these variants are registered, so that this
class does not compete with them, and only they hold metadata. See
MatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
metadata
|
NoRepr[Metadata | None]
|
What describes the transformation beyond its parameters, or |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
metadata
class-attribute
instance-attribute
What describes the transformation beyond its parameters, or None.
The metadata holds the common vocabulary of
Metadata, such as a
description or the images of a registration. A transformation built
from parameters has none unless it is given some. A file format takes
the field over to hold the metadata of its own class, which also
holds the header of the file, and converts the metadata it is given
into that class. The field is keyword-only and is left out of the
representation of the transformation.
VARIANTS
class-attribute
VARIANTS: tuple[type, ...] = ()
The readers dispatched to: MATLAB v4 to v7, then v7.3.
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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_fileobj
classmethod
Read an object from a file object open for reading.
The default implementation reads the whole stream and passes it to
from_content, and from_bytes decompresses binary content
that is compressed. A parser that needs only part of the stream,
such as a header, should override this method. from_bytes
then wraps binary content in a stream and reads it with the
override. An override receives the stream as the caller gave it,
compressed or not, and decompresses it itself, because a lazy array
that keeps the stream must read it from the position where the
file starts.
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
from_any
classmethod
Build an object from a file, a transformation or any other value.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. Anything else is read or built as
[FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A file and a transformation that is converted take keyword options only. |
()
|
**kwargs
|
Any
|
Options of the reader or of the conversion, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a file or a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
Each container reads its own records, so the abstract classes refuse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of a file. |
required |
**kwargs
|
Any
|
Field values. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In an abstract class. |
MatrixAffine
magic
MatrixAffine(
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
metadata: NoRepr[Metadata | None] = None,
)
Bases: ArrayReader, AffineTransformationFormat, Affine, TransformationFormat
Affine transformation stored as a bare matrix in a generic array container.
The file holds a (3, 3), (3, 4) or (4, 4) matrix, or a (2, 3) or (3, 3)
matrix in 2-D, and nothing else, so the caller gives its conventions as
keyword arguments to load or from_file. This class is abstract, and
each container has a registered subclass that mixes in its
[ArrayReader][brainhops.io.common._internal_api.ArrayReader]:
TxtMatrixAffine: whitespace-separated text (.txt,.dat,.1D), hint"matrix.txt";CsvMatrixAffine:.csv, hint"matrix.csv";TsvMatrixAffine:.tsv, hint"matrix.tsv";NpyMatrixAffine:.npy, hint"matrix.npy";NpzMatrixAffine:.npz, hint"matrix.npz";MatLegacyMatrixAffine: MATLAB v4 to v7.mat, read withscipy.io, hint"matrix.mat";Mat73MatrixAffine: MATLAB v7.3.mat, read withh5py, hints"matrix.mat","mat.73"and"matrix.mat.73".
MatMatrixAffine reads a MATLAB file of any version by dispatching to
the last two. Every reader answers to hint="matrix", in which case the
container is recognized from the content. In a container that holds several
arrays, the matrix is selected with variable= (or key=), and defaults
to the only 2-D numeric array. A container that holds a single array
refuses variable= and key= with TypeError, and so does every
reader for an option that it does not know.
Conventions
The conventions below are applied in order: transposition, inversion, index shift and image placement.
vector="column": with"row", the matrix is applied asy = x @ Aand is transposed.ndim=None: only used for a (3, 3) matrix, which is 3-D linear unlessndim=2makes it a 2-D homogeneous affine.direction="forward": with"inverse", the file stores the map from output to input, and the matrix is inverted.input=None,output=None: the spaces of the forward matrix, as"voxel"(or"pixel","index"),"ras","lps"or a coordinate system.Nonestands for a generic unnamed space.index_base=0: 1 when voxel indices are 1-based, as in MATLAB and SPM, or an(input, output)pair. A 1-based voxel endpoint is shifted to 0-based indices, in which an integer is the centre of a voxel. A single value applies to every voxel endpoint and requires at least one.source=None,target=None: anibabelimage or header, or a brainhops image. The voxel input or output is mapped to the world space of that image through its voxel-to-world affine, and passing an image makes that endpoint default to"voxel".
Record
A plain matrix file is read in one pass. Its matrix, and the
conventions that it was read in, are held as a MatrixAffineRaw
record by the metadata of the transformation, such as a
TxtMatrixMetadata, and the matrix and the coordinate systems of
the transformation is decoded from that record. The record of a text
file also keeps the text of the file. The coordinate systems of the
record are given to the transformation when it is read, as its own
input and output, so that a copy into another class keeps them. A
matrix that is assigned, and an input or output that is not the
system of the record, are pending: they win over the record until
consolidate() encodes them into a new record, in the conventions
and the layout of the record that it replaces. A transformation
without a record, such as one built from data alone, holds its matrix
as any affine does and has no metadata.
These formats read files but do not write them, so a plain matrix is saved through another format, such as NIfTI or LTA.
Dispatch
Any small numeric table reads as a matrix, so this reader scores
Confidence.WEAK and loses to every positively recognized format, such as
FLIRT or ITK. A text matrix whose file extension matches its separator
scores higher, so that it is not read as a FLIRT matrix. Files larger than
1 MiB are not sniffed. hint="matrix", or a container hint, selects this
reader explicitly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
metadata
|
NoRepr[Metadata | None]
|
What describes the transformation beyond its parameters, or |
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
metadata
class-attribute
instance-attribute
What describes the transformation beyond its parameters, or None.
The metadata holds the common vocabulary of
Metadata, such as a
description or the images of a registration. A transformation built
from parameters has none unless it is given some. A file format takes
the field over to hold the metadata of its own class, which also
holds the header of the file, and converts the metadata it is given
into that class. The field is keyword-only and is left out of the
representation of the transformation.
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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_fileobj
classmethod
Read an object from a file object open for reading.
The default implementation reads the whole stream and passes it to
from_content, and from_bytes decompresses binary content
that is compressed. A parser that needs only part of the stream,
such as a header, should override this method. from_bytes
then wraps binary content in a stream and reads it with the
override. An override receives the stream as the caller gave it,
compressed or not, and decompresses it itself, because a lazy array
that keeps the stream must read it from the position where the
file starts.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
from_any
classmethod
Build an object from a file, a transformation or any other value.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. Anything else is read or built as
[FileFormat.from_any][brainhops.io.base.FileFormat.from_any] does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A file and a transformation that is converted take keyword options only. |
()
|
**kwargs
|
Any
|
Options of the reader or of the conversion, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a file or a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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_array
classmethod
Build an object from the array of the container.
The format class implements this method.
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
Each container reads its own records, so the abstract classes refuse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of a file. |
required |
**kwargs
|
Any
|
Field values. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
Raises:
| Type | Description |
|---|---|
ParserNotImplementedError
|
In an abstract class. |
NpyMatrixAffine
magic
NpyMatrixAffine(
metadata: NoRepr[NpyMatrixMetadata | None] = Inherit(
"metadata", default=None
),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: NpyArrayReader, MatrixAffine
Affine stored in a NumPy .npy file, read without unpickling.
The file holds a single array, so the reader refuses variable= and
key=. See MatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[NpyMatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_fileobj
classmethod
Build a transformation from a binary file object.
The file is read by NpyMatrixMetadata.from_fileobj.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_bytes
classmethod
Build a transformation from the content of a file.
The content is read by NpyMatrixMetadata.from_bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |
NpzMatrixAffine
magic
NpzMatrixAffine(
metadata: NoRepr[NpzMatrixMetadata | None] = Inherit(
"metadata", default=None
),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: NpzArrayReader, MatrixAffine
Affine stored in a NumPy .npz file, read without unpickling.
The array is selected with variable= or key=, and defaults to the only
2-D numeric array. The record keeps its name. See MatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[NpzMatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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_fileobj
classmethod
Score an open file, reading at most SNIFF_LIMIT bytes.
sniff_content
classmethod
sniff_content(
content: ContentLike,
error: bool | Type[Exception] = False,
**kwargs,
) -> float
Same as sniff, for bytes, text, or lines.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
from_text
classmethod
Read an object from text.
The text is split into lines and passed to from_lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_fileobj
classmethod
Build a transformation from a binary file object.
The file is read by NpzMatrixMetadata.from_fileobj.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
file object
|
The file, open for binary reading. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_bytes
classmethod
Build a transformation from the content of a file.
The content is read by NpzMatrixMetadata.from_bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, the options of the container, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |
TsvMatrixAffine
magic
TsvMatrixAffine(
metadata: NoRepr[TsvMatrixMetadata | None] = Inherit(
"metadata", default=None
),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: TsvArrayReader, MatrixAffine
Affine stored in a tab-separated .tsv file.
The record keeps the text of the file. See MatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[TsvMatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
NAMED_CONFIDENCE
class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY
The minimum score of a text array whose file has an extension of this reader.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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
Sniff binary content as text.
Compressed content is decompressed first. The content is decoded
with the encoding keyword, UTF-8 by default, and passed to
sniff_text. Content that does not decode scores
Confidence.NO, or raises SnifferContentError if error is
set.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_text
classmethod
Build a transformation from the text of a file.
The text is read by TsvMatrixMetadata.from_text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_lines
classmethod
Build a transformation from the lines of a file.
The lines are read by TsvMatrixMetadata.from_lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
iterable of str
|
The lines of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |
TxtMatrixAffine
magic
TxtMatrixAffine(
metadata: NoRepr[TxtMatrixMetadata | None] = Inherit(
"metadata", default=None
),
data: npmatrix[Real] | None = None,
log: bool = False,
matrix: npmatrix[Real] | None = None,
homogeneous_matrix: npmatrix[Real] | None = None,
*,
input: CoordinateSystem | None = None,
output: CoordinateSystem | None = None,
)
Bases: TxtArrayReader, MatrixAffine
Affine stored in a whitespace-separated text file.
This covers .txt, .dat and AFNI .1D files, with one matrix row per
line. Comments start with #, and blank lines are skipped. The record
keeps the text of the file. See MatrixAffine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
NoRepr[TxtMatrixMetadata | None]
|
|
Inherit('metadata', default=None)
|
data
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
log
|
bool
|
Whether |
False
|
matrix
|
npmatrix[Real] | None
|
Matrix of shape |
None
|
homogeneous_matrix
|
npmatrix[Real] | None
|
Homogeneous matrix of shape |
None
|
input
|
CoordinateSystem | None
|
Input coordinate system, which may be inferred from context if unset. |
None
|
output
|
CoordinateSystem | None
|
Output coordinate system, which may be inferred from context if unset. |
None
|
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.
mutually_exclusive_fields
class-attribute
mutually_exclusive_fields: tuple[str, ...] | None = None
Constructor arguments that may not be given together.
A view is another name under which the stored parameter can be given, such
as matrix for the data of an affine transformation. The default,
None, makes the stored parameter and all of its views mutually exclusive,
so the group is data_fields followed by derived_fields. This default
applies only to a class with at most one data field. A class with several
independent data fields has no group unless it declares one.
NAMED_CONFIDENCE
class-attribute
NAMED_CONFIDENCE: float = Confidence.LIKELY
The minimum score of a text array whose file has an extension of this reader.
metadata
class-attribute
instance-attribute
The metadata of the file, which holds the file as a record.
A transformation built from data alone has no metadata. Assigning other metadata drops the matrix decoded from the old record, and a matrix that was assigned stays pending. The systems of the transformation are kept, and they are pending unless they are those of the new 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
Sniff binary content as text.
Compressed content is decompressed first. The content is decoded
with the encoding keyword, UTF-8 by default, and passed to
sniff_text. Content that does not decode scores
Confidence.NO, or raises SnifferContentError if error is
set.
sniff_text
classmethod
Same as sniff, for text.
The text is split into lines and passed to sniff_lines.
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_filename
classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self
Read an object from a path.
The file is opened in the read mode of the class, and a compressed file is decompressed as it is read.
Raises:
| Type | Description |
|---|---|
ParserExistsError
|
If the file does not exist. |
from_content
classmethod
from_content(content: ContentLike, **kwargs) -> Self
Read an object from bytes, text, or lines.
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
Copy an instance, or convert a transformation to this format.
A transformation that is not of this format is converted exactly as
other.to(cls) converts it. An instance of this format is copied
as
[FileFormat.from_instance][brainhops.io.base.FileFormat.from_instance]
copies it, except that a format that stores its data in the
private field _data passes the stored value on. That value is
None unless the data were assigned, so the copy decodes the
same record as other, and a record that was not decoded stays
so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The instance to copy or convert. |
required |
*args
|
Any
|
Constructor arguments. A transformation that is converted takes keyword options only. |
()
|
**kwargs
|
Any
|
Options of the conversion, or field values of the copy. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If positional arguments accompany a transformation that is converted. |
ConversionError
|
If the format cannot hold the transformation. |
to
to(
cls: Type[Self] | None = None,
*,
on_loss: ErrorAction = UNSET,
on_error: ErrorPolicy = UNSET,
copy: bool = False,
**kwargs,
) -> Self
Convert the transformation to another type or encoding.
The conversion takes one of three forms:
- between types:
linear.to(Affine); or - within a type:
displacement.to(store="coefficients"); or - both:
coords.to(DisplacementField, store="values").
A conversion that would lose information raises a
LossyConversionError,
which carries the lossy result. A conversion that cannot be
made raises a ConversionError. An error policy decides
what happens to these errors (see
ErrorPolicy). Its scope is
(ConversionError,), so that a single action applies to these
errors only, and any other error is raised unless a mapping
names it. The policy that the call applies is
{LossyConversionError: on_loss, **on_error}, so that
on_loss="ignore" returns the lossy result. Without
on_loss=, a loss falls under on_error=, so that
on_error="ignore" alone also returns the lossy result. A loss
of metadata, in the conversions of metadata that the conversion
triggers, follows the same policy, because a
MetadataLossError
is a lossy conversion error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type of Transformation
|
Type to convert to. By default, the type is normally kept. |
None
|
on_loss
|
ErrorAction
|
What to do with a conversion that loses information, with
the same values as a single action of |
UNSET
|
on_error
|
ErrorPolicy
|
What to do when the conversion fails. One action applies to
a |
UNSET
|
copy
|
bool
|
Whether to return a new object when the conversion has nothing to change. By default, a transformation converted to its own class without any field is returned itself. |
False
|
**kwargs
|
Any
|
Attributes of the converted transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or what the policy returns in its place. |
Examples:
to_backend
to_backend(
backend: BackendLike | None = None,
*,
device: DeviceLike | None = None,
) -> ArrayProtocol | None
Return the data as a bare array of the backend of a setting.
The object does not change. Small parameters, such as the matrix
of an affine transformation, are converted too, since the caller
asks for them. An object without data, such as the identity,
gives None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | module
|
The setting. By default, the current setting is used. |
None
|
device
|
str | int
|
The device for converted arrays. The backend supplies its default. |
None
|
Returns:
| Type | Description |
|---|---|
array | None
|
The data. |
to_cupy
Return the data as a CuPy array on the GPU.
to_dask
Return the data as a Dask array, without reading them.
as_numpy
Return the object with its data as NumPy arrays.
On an object read from a file, as_numpy(inplace=True) reads the
file once and keeps its values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_cupy
Return the object with its data as CuPy arrays on the GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
as_dask
Return the object with its data as Dask arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | int | None
|
The device, such as |
None
|
inplace
|
bool
|
Whether this object holds the converted data and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
object
|
An object of the same class. |
compute
compute(
mode: ModeLike = True,
*,
simplify: SimplifyLike = "analytic",
factor: bool = False,
) -> Self
Convert the transformation to the cheapest type that represents it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ModeLike
|
Kinds of transformation that may be composed, used only when
|
True
|
simplify
|
SimplifyLike
|
How much effort to spend on simplification. |
"analytic"
|
factor
|
bool
|
Whether to split the transformation into independent factors, one for each group of axes that transform together. To do so, the transformation is computed as a sequence of one element. A diagonal affine transformation, for example, splits into one factor per axis. |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
simplify
simplify(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Self
Simplify the transformation, without composing it unless asked.
t.simplify(policy, compute=mode) is
t.compute(mode, simplify=policy). By default nothing is composed: no
matrix is multiplied, no field is sampled and no lazy inverse is
evaluated. Each concrete transformation is only converted to the
cheapest type that still represents it, as far as policy can tell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How hard to simplify, with the values accepted by the |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed, with the values
accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The simplified transformation. |
factor
factor(
policy: SimplifyLike = "analytic",
*,
compute: ModeLike | bool | None = False,
) -> Transformation
Rewrite the transformation as one factor per group of axes.
The axes of a transformation often fall into groups that never
interact, as with a diagonal matrix, whose axes each scale on
their own. Factoring finds those groups and gives each one a
factor that acts on its axes alone, which lets a resampler work
group by group rather than over the whole grid. The
transformation is factored as a chain of one element, so that,
under the numeric policy, a diagonal affine splits into one
factor per axis. See Sequence.factor for the normal form
that the pass produces and for what is left unfactored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
SimplifyLike
|
How closely the transformation may be read, with the values
and the meaning of the policy of |
"analytic"
|
compute
|
ModeLike or bool or None
|
Kinds of transformation that may be composed inside a group,
with the values accepted by the |
False
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The factored transformation, or |
restrict
restrict(
input_axes: AxisReferences,
output_axes: AxisReferences,
at: InputValues | None = None,
) -> Transformation
Return the transformation restricted to some of its axes.
A restriction keeps a part of a transformation, such as the
spatial part of a map of space and time, or the map of one
volume of a time series. It is lazy, like inverse. The
result is a Sequence of three elements: a
Projection
that creates the inputs that input_axes leaves out, the
transformation itself, and a projection that drops the outputs
that output_axes leaves out. Nothing is computed until
compute is called, and simplify then removes the
axes that are not needed. When both sides keep every axis, the
transformation itself is returned.
A removed input takes the value that at gives it, which
selects the section of the transformation at that value. A
removed input that at does not name is free, which means that
the kept outputs must not read it. compute raises a
RestrictionError when a kept output reads a free input,
whereas restrict and simplify never raise for that
reason. With one affine per volume of a time series, for
example, the spatial outputs read the time axis, so the
restriction to the spatial axes needs a value of time, which
selects one volume.
Each side is a list of references, or a single reference. A
reference is a position, the name of an axis, or any other query
of [AxisQuery][brainhops.datamodel.axes.AxisQuery], such as an
axis class. It is resolved against the input or the output
system of the transformation, as
[AxisSequence.restrict][brainhops.datamodel.axes.AxisSequence.restrict]
resolves it, so a query never matches the unknown axes that the
... of an open system stands for. A name must designate
exactly one axis, and any other query must designate at least
one. Each side is a set of axes, so the order of the references
does not matter: the kept axes stay in the order that they have
in the transformation, and an axis must not be designated twice.
Positions also work on a transformation without systems,
or with open systems, provided that its numbers of axes are
known, for example from the shape of its matrix. The systems of
the result are the systems of the transformation restricted to
the kept axes.
A subspace transformation, an instance of
SubspaceTransformation,
often does not know how many axes it passes through, which a
restriction needs. When it is restricted to the axes that it
acts on, however, the result is the transformation that it
wraps, whatever that number is, and this result is returned. A
subspace that lists its axes in another order than the full
space gives the wrapped transformation between two permutations,
which put its axes in the order of the full space. A geometry,
an instance of
Geometry, restricts
its grid as well when it can, as its own method describes.
Example
>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> xyt = CoordinateSystem(axes=[x, y, TimeAxis(name="t")])
>>> matrix = [[2, 0, 0.5, 1], [0, 3, 0, 2], [0, 0, 1, 0]]
>>> t = Affine(matrix=matrix, input=xyt, output=xyt)
>>> part = t.restrict(SpaceAxis, SpaceAxis, at={"t": 4})
>>> part.compute().matrix
array([[2., 0., 3.],
[0., 3., 2.]])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Input axes to keep, given by position, by name or by query. |
required |
output_axes
|
AxisQuery or iterable of (int or AxisQuery)
|
Output axes to keep, given by position, by name or by query. |
required |
at
|
mapping of (int or AxisQuery) to float
|
Values of some of the removed inputs. Each key designates
input axes as an item of |
None
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The lazy restriction, or the transformation itself when both sides keep every axis. |
Raises:
| Type | Description |
|---|---|
RestrictionError
|
If the number of input or output axes of the transformation is unknown, because the axes to remove are then unknown. |
KeyError
|
If no axis has a name that a reference gives. |
IndexError
|
If a position lies outside the axes of the transformation. |
ValueError
|
If a query matches no axis, a name is shared by several
axes, an axis is designated twice, or |
TypeError
|
If a reference is neither a position nor a query, or if |
square
square(compute: bool = False, **kwargs) -> Transformation
Return the transformation composed with itself.
The square is the Sequence [self, self], which is composed when
it is computed. It is defined only for a transformation that maps a
space to itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compute
|
bool
|
Whether to compute the square now rather than return the sequence. |
False
|
**kwargs
|
Any
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The square. |
Raises:
| Type | Description |
|---|---|
DomainError
|
If the transformation does not map a space to itself. |
is_kind
Return whether the transformation is of a given kind.
A transformation is of a kind when it is an instance of the kind, possibly a virtual one, or when its parameters are compatible with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
type of Kind
|
Kind to test, from |
required |
compute
|
bool
|
Whether to read the values of the parameters rather than only the structure of the types. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether the transformation is of the kind. |
is_identity
Return whether the transformation is the identity.
A transformation is the identity when its parameters are unset or when
it is an Identity.
With compute=True, the parameters of the matrix, vector and
displacement types are inspected too.
A grid of coordinates
(CartesianField)
is the identity over itself. It is recognised as such with
compute=True, but with compute=False only if its shape is unset,
since a shape is a parameter. In neither case are the coordinates of
the grid built. A grid that is the identity still defines where a
sequence is sampled, so simplifying a sequence removes the grid only
when it lies between two other transformations.
is_translation
Return whether the transformation is a translation.
A transformation is a translation when it is an instance of
kinds.Translation or the
identity. With compute=True, an affine matrix is checked for an
identity linear part and a displacement field for a constant value.
is_scaling
Return whether the transformation is a scaling.
A transformation is a scaling when it is an instance of
kinds.Diagonal or the identity.
With compute=True, a linear or affine matrix is checked to be
diagonal.
is_permutation
Return whether the transformation is a permutation.
A transformation is a permutation when it is an instance of
kinds.Permutation or the
identity. With compute=True, a linear or affine matrix is checked for
a single one in each row and column.
is_rotation
Return whether the transformation is a rotation.
A transformation is a rotation when it is an instance of
kinds.SpecialOrthogonal
or the identity. With compute=True, a linear or affine matrix is
checked to be orthogonal with a positive determinant.
is_linear
Return whether the transformation is linear.
A transformation is linear when it is an instance of
kinds.Linear or the identity.
With compute=True, an affine matrix is checked for a zero
translation.
is_affine
Return whether the transformation is affine.
A transformation is affine when it is an instance of
kinds.Affine or the identity.
without
without(match: MatchLike) -> Transformation
Return the transformation with some parts replaced by the identity.
A caller uses this method to ignore a class of transformations,
for example the displacement fields of a chain whose affine part
it needs. Every part that the matcher selects becomes an
Identity with
the same input and output coordinate systems, so that the
elements of a chain still connect and no bridge is guessed
between them. The identities disappear when the result is
computed.
The transformation is visited from the outside in. A selected
node is replaced as a whole, and the method looks inside a
sequence or an inverse only when the node itself is not
selected. The inverse of a replaced part is replaced as well.
The method does not look inside any other wrapper, such as a
lazy square root (Sqrt), a Bijection or a
SubspaceTransformation, so the matcher decides such a wrapper
as a whole, and a part that it holds is not replaced on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to replace. A matcher is a kind or the name of a kind,
such as |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
with_only
with_only(match: MatchLike) -> Transformation
Return the transformation with only some parts kept.
This method is the complement of
without:
every part that the matcher does not select is replaced by an
identity with the same coordinate systems. Because a kind can
only describe the transformations that have a property,
with_only("affine") is the way to remove everything that is not
affine.
A node that the matcher selects is kept as a whole, so a chain
that is affine as a whole is not split. The method looks inside
a sequence or an inverse only when the node itself is not
selected, and replaces any other node that is not selected. A
wrapper other than a sequence or an inverse, such as a lazy
square root (Sqrt), a Bijection or a
SubspaceTransformation, is therefore kept or replaced as a
whole, even when only a part that it holds is selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
MatchLike
|
Parts to keep, in the same forms as for |
required |
Returns:
| Type | Description |
|---|---|
Transformation
|
The filtered transformation, or the transformation itself when no part is replaced. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a part to replace changes the number of axes. |
to_translation
to_translation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a translation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Translation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_scaling
to_scaling(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a scaling.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Scaling with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_permutation
to_permutation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a permutation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Permutation with
to.
The result always has its data. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_rotation
to_rotation(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a rotation.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Rotation with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_linear
to_linear(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to a linear map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Linear with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
to_affine
to_affine(
*,
include: MatchLike | None = None,
exclude: MatchLike | None = None,
**kwargs,
) -> Transformation
Convert the transformation to an affine map.
The transformation is first filtered: the parts that include
does not select are replaced by the identity, as by
with_only(include), and then the parts that exclude selects
are replaced, as by without(exclude). The filtered
transformation is computed, because a chain must be composed
before it can be converted, and the result is converted to a
Affine with
to.
The result always has its matrix. A result without it raises
a ConversionError, because its dimension is unknown, as for
an Identity(). Plain to makes no such check. The policy given
as on_error= and on_loss= applies to the whole call, so that
on_error=None returns None when the conversion fails.
For example, to_affine(on_error=None) returns None when
the transformation is not affine, and
to_affine(include="affine", on_error=None) returns the affine
part of a chain whose other parts, such as fields, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
MatchLike
|
Parts to keep, as in |
None
|
exclude
|
MatchLike
|
Parts to replace by the identity, as in |
None
|
**kwargs
|
Any
|
Keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
Transformation
|
The converted transformation, or the value that the policy returns when the conversion fails. |
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 |
data
data() -> ndarray | None
The (N, N + 1) affine matrix, which the matrix view reads.
A matrix that is assigned is returned as it is, and stays pending
until the transformation is consolidated. Otherwise the matrix is
decoded from the record in its conventions, without its last row,
and is read-only, or None without a record.
from_array
classmethod
Build an object from the array of the container.
The format class implements this method.
from_raw
classmethod
from_raw(raw: MatrixAffineRaw, **kwargs) -> Self
Build a transformation from an already parsed record.
The record is held by new metadata, without a copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
MatrixAffineRaw
|
The record of the file. |
required |
**kwargs
|
Any
|
Field values, which go to the constructor and override the record. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_text
classmethod
Build a transformation from the text of a file.
The text is read by TxtMatrixMetadata.from_text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The content of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_lines
classmethod
Build a transformation from the lines of a file.
The lines are read by TxtMatrixMetadata.from_lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
iterable of str
|
The lines of the file. |
required |
**kwargs
|
Any
|
The conventions of the matrix, and field values, which go to the constructor and override the file. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The transformation. |
from_any
classmethod
Build a transformation from a record, a file or a data model.
A MatrixAffineRaw is read with from_raw, and any other
value as the bases read it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A record, a file, its content, a transformation, a mapping, or an instance of a similar class. |
required |
*args
|
Any
|
Constructor arguments. A record and a file take keyword arguments only. |
()
|
**kwargs
|
Any
|
Options of the reader, and field values otherwise. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The new transformation. |