Skip to content

brainhops.io.common.freesurfer

Volume geometry shared by the FreeSurfer formats.

MGH headers, LTA files and .m3z files all describe a volume by its shape, its voxel size in millimetres, the direction cosines x_ras, y_ras and z_ras (the columns of the rotation part of the voxel-to-RAS matrix), and the RAS coordinate c_ras of its centre.

Three coordinate systems are involved. Scanner RAS is the acquisition space (mri_info --vox2ras). Tkr RAS, where surfaces live (mri_info --vox2ras-tkr), has the same voxel sizes but conformed LIA axes and its origin at the centre of the volume. The physical space, used by LINEAR_PHYSVOX transforms, is the scaled voxel space shifted to the centre of the volume. The tkr RAS space of a volume is described by FreesurferTkrSystem, which the MGH images and the register.dat and LTA transformations share.

The centre of the volume

FreeSurfer puts the centre of the volume at voxel coordinate shape / 2, which lies half a voxel past the true centre along axes of even size. The functions follow this convention to match FreeSurfer and nibabel exactly.

All FreeSurfer formats derive from FreesurferFormat.

Classes

FreesurferFormat

Bases: FileFormat

Family of the FreeSurfer formats.

The family holds the MGH and MGZ images, and the LTA, M3Z and register.dat transformations. It owns a format registry, so that its load and sniff* methods choose among these formats. The hint "freesurfer" selects them all, and the hints of its formats, such as "mgh", "lta", "m3z" or "regdat", can also be reached as "freesurfer.mgh".

Attributes

EXTENSIONS class-attribute
EXTENSIONS: tuple[str, ...] = ()

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

Methods:

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Identify the registered format of a file or its content.

The result is the registered format that would read the input.

sniff_file classmethod
sniff_file(
    file: FileLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for a path or an open file.

sniff_filename classmethod
sniff_filename(
    filename: FilenameLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Identify the registered format that matches a path.

sniff_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for an open file object.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for text or binary content.

sniff_bytes classmethod
sniff_bytes(
    content: BinaryContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for binary content.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for text.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for lines of text.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> type | None

Same as sniff, for a single line.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

Read an object from a file or its content.

The input is read with the best-matching registered format. A SourceSpec is read with from_spec.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Read a structured source specification.

The specification's path is read with its hints and options.

from_file classmethod
from_file(file: FileLike, **kwargs) -> Self

Read an object from a path or an open file.

The file is read with the best-matching registered format.

from_filename classmethod
from_filename(filename: FilenameLike, **kwargs) -> Self

Same as from_file, for a path.

from_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

Same as from_file, for an open file object.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Same as from_file, for text or binary content.

from_bytes classmethod
from_bytes(content: BinaryContentLike, **kwargs) -> Self

Same as from_file, for binary content.

from_text classmethod
from_text(text: str, **kwargs) -> Self

Same as from_file, for text.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

Same as from_file, for lines of text.

from_line classmethod
from_line(line: str, **kwargs) -> Self

Same as from_file, for a single line.

FreesurferTkrSystem

Bases: SpatialCoordinateSystem3D, MillimetricCoordinateSystem

The tkregister RAS space of a volume, in which surfaces live.

FreeSurfer gives each volume a second RAS space beside scanner RAS, which it calls tkregister RAS, tkr RAS or surface RAS (mri_info --vox2ras-tkr). Surfaces are stored in this space, an MGH image maps its voxels to it, and a register.dat file maps the tkregister space of one volume to that of another. Its axes point towards the right, anterior and superior directions in millimetres, as those of scanner RAS do, but its voxel-to-RAS matrix uses the conformed LIA directions and puts the origin at the centre of the volume (MRIxfmCRS2XYZtkreg in utils/mri.cpp of FreeSurfer, commit 4f8728e). The space therefore depends only on the shape and the voxel size of the volume, and it differs from scanner RAS by a rotation and a translation that the geometry of the volume gives.

The space is not [RASmm][brainhops.datamodel.systems.RASmm], which stands for scanner RAS. A format that stores scanner RAS and checks the class of its systems, such as LTA, therefore refuses to write an affine from or to a tkregister space as an affine between scanner spaces.

A system may hold the geometry of its volume, a Geometry, which places the volume in scanner RAS. A system without a geometry stands for the tkregister space of a volume that is not known. The geometry must be that of a 3-D volume whose voxel-to-world transformation is an affine into an anatomical space in millimetres, such as RASmm or LPSmm, which FreeSurfer reads as scanner RAS. Any other geometry raises a ValueError when the system is built.

Attributes

geometry class-attribute instance-attribute
geometry: KwOnly[Geometry | None] = None

The geometry of the volume, or None when it is not known.

DISTINCT_ORIGIN class-attribute
DISTINCT_ORIGIN: bool = True

Whether the space differs from other spaces with the same axes.

A tkregister space has the axes of scanner RAS but another origin, so a conversion into a file format never bridges it to a system of another class by its axes alone (see [affine_between][brainhops.io.transformations.base._conversions.affine_between]).