Skip to content

brainhops.io.common.bdv

Reading and writing of BigDataViewer datasets.

BigDataViewer is the Fiji viewer of large, multi-view and multi-scale images, and BigStitcher, the Fiji plugin that stitches and registers light-sheet acquisitions, stores its results in the same dataset. A dataset is an XML file, usually dataset.xml, and an HDF5 file that holds the voxels. This package reads and writes the XML file, as a BdvRaw record held by BdvMetadata. The images of a dataset are read by brainhops.io.images.bdv, and the registration of a view is read and written by brainhops.io.transformations.bdv.

The conventions below were checked against the source code of the Java libraries that write these datasets, at the commits below, and the sections that follow name the class or the method that each convention comes from.

  • bigdataviewer-core, commit dfe1a66: XmlIoSpimDataMinimal, the classes of bdv/img/hdf5 (Hdf5ImageLoader, XmlIoHdf5ImageLoader, Util, Partition and HDF5Access), WriteSequenceToHdf5 and HDF5Access of bdv/export, MipmapTransforms and ScaleBarOverlayRenderer;
  • spimdata, commit 84728ff: XmlKeys, XmlHelpers, XmlIoAbstractSpimData, XmlIoAbstractSequenceDescription, XmlIoBasicViewSetup, XmlIoTimePoints, IntegerPattern, XmlIoMissingViews, ViewRegistration, ViewTransformAffine, XmlIoViewRegistration, XmlIoViewRegistrations and XmlIoViewTransform;
  • imglib2-realtransform, commit ca9039d: AffineTransform3D;
  • bigdataviewer_fiji, commit c154fb2: ExportImagePlusPlugIn;
  • multiview-reconstruction, the library of BigStitcher, commit 60243ba: DatasetCreationUtils;
  • n5, commit 7ba6b14: DataType;
  • jdom, commit c6065f6: Format and LineSeparator.

The XML file

<SpimData version="0.2">
  <BasePath type="relative">.</BasePath>
  <SequenceDescription>
    <ImageLoader format="bdv.hdf5">
      <hdf5 type="relative">dataset.h5</hdf5>
    </ImageLoader>
    <ViewSetups>
      <ViewSetup>
        <id>0</id>
        <name>0</name>
        <size>1024 1024 200</size>          x, y, z
        <voxelSize>
          <unit>µm</unit>
          <size>0.4 0.4 2.0</size>          x, y, z
        </voxelSize>
      </ViewSetup>
    </ViewSetups>
    <Timepoints type="range">               or "list", or "pattern"
      <first>0</first>
      <last>0</last>
    </Timepoints>
    <MissingViews/>                         optional
  </SequenceDescription>
  <ViewRegistrations>
    <ViewRegistration timepoint="0" setup="0">
      <ViewTransform type="affine">
        <Name>calibration</Name>            optional
        <affine>1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 5.0 0.0</affine>
      </ViewTransform>
    </ViewRegistration>
  </ViewRegistrations>
</SpimData>

A view is one setup (a channel, an angle, an illumination or a tile) at one time point. The tags are those of XmlKeys.java in spimdata. A path is relative only when its type attribute is "relative" (XmlHelpers.loadPath): <BasePath> is then relative to the directory of the XML file, and <hdf5> to the base path. BigDataViewer writes the file with JDOM's pretty format, which indents by two spaces and ends its lines with CRLF.

Registrations

Each <ViewTransform> of type affine holds twelve values, the first three rows of a 3D affine matrix, row after row (XmlHelpers.getAffineTransform3D and AffineTransform3D.set in imglib2-realtransform). A transform of type generic names a Java class that reads its own content, and brainhops keeps it without reading it.

The transforms of a view map the coordinates of its voxels to the global coordinates of the dataset. ViewRegistration.updateModel concatenates them in the order of the file, and AffineTransform3D.concatenate(b) sets a = a * b, so the map is T0 * T1 * ... * Tn: the last transform of the file is applied first, and the first one last. BigStitcher adds a transform at the front of the list with preconcatenateTransform, so its first transform, named calibration, ends up last.

Voxel coordinates are in the order x, y, z, and an integer coordinate is the center of a voxel, which is the convention of ImgLib2. The default transform of a coarser level (MipmapTransforms.getMipmapTransformDefault) confirms it: it places voxel i of a level downsampled by f at f * i + (f - 1) / 2 in full-resolution voxels, which is the center of the block of voxels that it averages.

Units and the global space

The voxel size and its unit are given by each setup. The global space has no unit of its own. A dataset exported by the Fiji plugin "Export Current Image as XML/HDF5" has a single transform, the voxel size (ExportImagePlusPlugIn), so its global space is in the unit of the voxel size. BigStitcher instead stores as calibration the voxel size divided by the smallest voxel size of the dataset (DatasetCreationUtils.createViewRegistrations), so its global space is in units of that smallest voxel size. BigDataViewer itself measures the global space through the voxel size of the source along x and the scale of its transform along x (ScaleBarOverlayRenderer). Brainhops therefore gives the global space no unit.

The HDF5 file

/s00/resolutions        (levels, 3) float64: downsampling of each level,
                        x, y, z
/s00/subdivisions       (levels, 3) int32: chunk shape of each level,
                        x, y, z
/s00 attrs: dataType    "uint8", "int16", "float32", ...; absent in older
                        files
/t00000/s00/0/cells     the voxels of time point 0, setup 0, level 0,
                        stored z, y, x

The group names follow bdv/img/hdf5/Util.java: s%02d for a setup and t%05d/s%02d/%d/cells for a level of a view. The arrays of shapes and chunks are reversed from the order x, y, z of ImgLib2 into the order of HDF5 (Util.reorder). A file without the dataType attribute stores 16-bit unsigned voxels as signed 16-bit integers, which BigDataViewer reads back with the same bits as unsigned values (Hdf5ImageLoader.createSetupImgLoader). A dataset split into partitions has a main file whose cells datasets are external links to the partition files (WriteSequenceToHdf5.writeHdf5PartitionLinkFile), and BigDataViewer, like brainhops, reads the main file only.

Classes

BdvMetadata magic

BdvMetadata(
    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[BdvRaw | None] = None,
    *,
    extra: dict[str, Any] = Factory(),
)

Bases: MetadataReader, MetadataWriter, MetadataFormat

Metadata of a BigDataViewer dataset, which holds its XML file as a BdvRaw.

The XML file of a dataset describes its views and their registrations, so the metadata of the file is the whole file. Reading the metadata reads the XML file only, never the HDF5 file that holds the voxels. An image read from the dataset adds to its record what the HDF5 file says about the resolution levels (see BdvRaw.pyramids).

The file is read and written as bytes, so that its line separators, which are CRLF in the files that BigDataViewer writes, are kept. The file is read and written by the record, through MetadataReader and MetadataWriter, and metadata without a record has no file to write, since a dataset needs at least its setups and time points. The metadata keeps no open file.

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 ('MNI152NLin6Asym', 'scanner', ...; a known one is a SpaceEnum); the space itself is geometry.

None
intent IntentEnum | str | None

What the values are, as a NIfTI intent name (a known one is an IntentEnum).

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 Manufacturer).

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 'j-' is accepted).

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 'k' is accepted)."

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 (min, max).

None
channels tuple[Channel, ...] | None

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.

None
data_unit Unit | str | None

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.

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 save or to consolidate takes precedence over it.

None
scale_slope float | None

The slope of the intensity scaling: a value is stored * scale_slope + scale_intercept. None means no scaling.

None
scale_intercept float | None

The intercept of the intensity scaling (see scale_slope). None means no intercept.

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 IlluminationType).

None
contrast_method ContrastMethod | str | None

Contrast method (a known one is a ContrastMethod).

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[BdvRaw | None]

The content of the file, or None for metadata without a record.

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
name: Annotated[str | None, Scoped(FILE)] = None

A short name for the data.

description class-attribute instance-attribute
description: Annotated[
    str | None, Bids(Description), Scoped(FILE)
] = None

A free-text description.

history class-attribute instance-attribute
history: Annotated[tuple[str, ...] | None, Scoped(FILE)] = (
    None
)

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
creation_time: Annotated[datetime | None, Scoped(FILE)] = (
    None
)

When the file was created.

sources class-attribute instance-attribute
sources: Annotated[
    tuple[str, ...] | None, Bids(Sources), Scoped(FILE)
] = None

Files the data was derived from (BIDS provenance).

space class-attribute instance-attribute
space: Annotated[
    SpaceEnum | str | None,
    Bids(SpatialReference),
    Scoped(FILE),
] = None

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: Annotated[
    float | None, Bids(RepetitionTime), Scoped(ACQUISITION)
] = None

Repetition time, in seconds.

echo_time class-attribute instance-attribute
echo_time: Annotated[
    float | None, Bids(EchoTime), Scoped(ACQUISITION)
] = None

Echo time, in seconds.

inversion_time class-attribute instance-attribute
inversion_time: Annotated[
    float | None, Bids(InversionTime), Scoped(ACQUISITION)
] = None

Inversion time, in seconds.

flip_angle class-attribute instance-attribute
flip_angle: Annotated[
    float | None, Bids(FlipAngle), Scoped(ACQUISITION)
] = None

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_name: Annotated[
    str | None, Bids(InstitutionName), Scoped(ACQUISITION)
] = None

Institution responsible for the equipment.

acquisition_time class-attribute instance-attribute
acquisition_time: Annotated[
    datetime | None,
    Bids(AcquisitionTime),
    Scoped(ACQUISITION),
] = None

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: Annotated[
    float | None,
    Bids(TotalReadoutTime),
    Scoped(ACQUISITION),
] = None

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
slice_timing: Annotated[
    tuple[float, ...] | None,
    Bids(SliceTiming),
    Scoped(SPATIAL),
] = None

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
bvalues: Annotated[
    tuple[float, ...] | None, Along(time)
] = None

One b-value per index along the time axis (the volumes of a diffusion series), in s/mm^2."

bvectors class-attribute instance-attribute
bvectors: Annotated[
    tuple[tuple[float, float, float], ...] | None,
    Along(time),
] = None

One unit gradient direction per index along the time axis, in world (RAS) coordinates."

display_range class-attribute instance-attribute
display_range: Annotated[
    tuple[float, float] | None, Scoped(VALUES)
] = None

Display window (min, max).

channels class-attribute instance-attribute
channels: Annotated[
    tuple[Channel, ...] | None, Along(channel)
] = None

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
data_unit: Annotated[
    Unit | str | None, Scoped(VALUES), ConvertTo(unit)
] = None

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
dtype: Annotated[
    dtype | None, Scoped(VALUES), ConvertTo(to_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 save or to consolidate takes precedence over it.

scale_slope class-attribute instance-attribute
scale_slope: Annotated[float | None, Scoped(VALUES)] = None

The slope of the intensity scaling: a value is stored * scale_slope + scale_intercept. None means no scaling.

scale_intercept class-attribute instance-attribute
scale_intercept: Annotated[float | None, Scoped(VALUES)] = (
    None
)

The intercept of the intensity scaling (see scale_slope). None means no intercept.

objective_magnification class-attribute instance-attribute
objective_magnification: Annotated[
    float | None, Scoped(ACQUISITION)
] = None

Nominal magnification of the objective.

objective_numerical_aperture class-attribute instance-attribute
objective_numerical_aperture: Annotated[
    float | None, Scoped(ACQUISITION)
] = None

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
moving: Annotated[str | None, Scoped(FILE)] = None

The moving image of a registration (file reference).

fixed class-attribute instance-attribute
fixed: Annotated[str | None, Scoped(FILE)] = None

The fixed image of a registration (file reference).

input_space class-attribute instance-attribute
input_space: Annotated[
    SpaceEnum | str | None, Scoped(FILE)
] = None

Label of the space a transformation maps from.

output_space class-attribute instance-attribute
output_space: Annotated[
    SpaceEnum | str | None, Scoped(FILE)
] = None

Label of the space a transformation maps to.

extra class-attribute instance-attribute
extra: Annotated[
    dict[str, Any], Scoped(FILE), HideIf(not_)
] = Factory()

Free-form keys the vocabulary does not cover, copied into any free-form store a format has."

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

The fields of the metadata that the format can store.

The names are those of the vocabulary, and "extra" when the format has a free-form store. A field that is not listed is decoded as None, and its value is reported as lost when the metadata is consolidated. A conversion into the format reads this list to report a lower bound of what a write would lose. The base class lists no field.

raw class-attribute instance-attribute
raw: NoRepr[BdvRaw | 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: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

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

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

Score a file, as the record class scores it.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
error bool or type[Exception]

Whether to raise an error when the file is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score an open file, as the record class scores it.

Parameters:

Name Type Description Default
file IO

The open file.

required
error bool or type[Exception]

Whether to raise an error when the file is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Same as sniff, for bytes, text, or lines.

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

Score the content of a file, as the record class scores it.

Parameters:

Name Type Description Default
content bytes

The content of the file.

required
error bool or type[Exception]

Whether to raise an error when the content is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score the text of a file, as the record class scores it.

Parameters:

Name Type Description Default
text str

The text of the file.

required
error bool or type[Exception]

Whether to raise an error when the text is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score the lines of a file, as the record class scores them.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines of the file.

required
error bool or type[Exception]

Whether to raise an error when the lines are not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Score the first line of a file, as the record class scores it.

Parameters:

Name Type Description Default
line str

The line.

required
error bool or type[Exception]

Whether to raise an error when the line is not of the format.

False
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
float

The confidence, between 0 and 1.

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

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

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

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

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

Read an object from a path or an open file.

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

Read the metadata from a path, through the record class.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from an open file, through the record class.

Parameters:

Name Type Description Default
file IO

The open file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read an object from bytes, text, or lines.

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

Read the metadata from the content of a file.

The content is read by the record class.

Parameters:

Name Type Description Default
content bytes

The content of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from the text of a file, through the record.

Parameters:

Name Type Description Default
text str

The text of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from the lines of a file, through the record.

Parameters:

Name Type Description Default
lines Iterable[str]

The lines of the file.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

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

Read the metadata from a single line, through the record.

Parameters:

Name Type Description Default
line str

The line.

required
**kwargs Any

Options of the reader of the record.

{}

Returns:

Type Description
Self

The metadata.

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

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 None or the value that the class fixes.

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 other.

()
on_loss ErrorAction

What to do with the fields that this format cannot store: "ignore" accepts the loss, "warn" warns about it, "raise" raises, and a report is filled instead of warning or raising. By default, the action of on_error, or else the policy in effect (see metadata_loss_policy).

UNSET
on_error ErrorPolicy

What to do with a conversion error of the copy, including a loss (see ErrorPolicy). A mapping may also name other errors. An entry for a loss in on_error takes precedence over on_loss. By default, an error is raised.

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 "raise" policy.

from_any classmethod
from_any(other: Any, *args, **kwargs) -> Self

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 Metadata or NiftiMetadata. By default, the class of this metadata.

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 cls has no slot for: "ignore" accepts the loss, "warn" warns about it, "raise" raises, and a report, ConversionReport, is filled instead of warning or raising. By default, the action of on_error, or else the policy in effect (see metadata_loss_policy).

UNSET
on_error ErrorPolicy

What to do with a conversion error, including a loss (see ErrorPolicy). A mapping may also name other errors. An entry for a loss in on_error takes precedence over on_loss. By default, an error is raised.

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 "raise" policy.

Examples:

report = ConversionReport()
mgh = metadata.to(MghMetadata, on_loss=report)
report.lost  # the fields MGH has no slot for
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 history.

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 ErrorPolicy). A mapping may also name other errors. By default, an error is raised, and a loss follows the policy in effect.

UNSET
on_loss ErrorAction

What to do with a loss, with the same values as a single action of on_error. An entry for a loss in on_error takes precedence over it. By default, a loss falls under on_error.

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 inplace=True, or the value that the policy returns in its place.

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 "raise" policy.

from_raw classmethod
from_raw(raw: Any, **kwargs) -> Self

Build the metadata that holds a record.

A reader calls this method once it has parsed the header of a file. The record is held as it is given, without a copy. The format decodes the fields of the vocabulary from the record here, and the base class, which knows no record, decodes none.

Parameters:

Name Type Description Default
raw object

The header of a file, in the representation of the format.

required
**kwargs Any

Other fields of the metadata, which take precedence over the decoded values.

{}

Returns:

Type Description
MetadataFormat

The metadata.

save
save(file: FileLike, **kwargs) -> None

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

to_file
to_file(file: FileLike, **kwargs) -> None

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

to_filename
to_filename(filename: FilenameLike, **kwargs) -> None

Write the object to a path, always as bytes.

The content is encoded before the target changes, so that an error while it is encoded leaves the target as it was. A local file is written next to its target, which it then replaces at once. A remote file is written once the whole content is encoded. A text format is written with to_bytes, so that its line endings are written as they are, on every system. A binary format is written with to_fileobj, which a local file receives as it is written and a remote file receives once it is complete. A name that ends with .gz, .bz2 or .xz compresses the file, whatever the format.

to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the file of the record to an open file.

Parameters:

Name Type Description Default
file IO

The open file.

required
**kwargs Any

Options of the writer of the record.

{}
to_bytes
to_bytes(**kwargs) -> bytes

Return the content of the file of the record.

Parameters:

Name Type Description Default
**kwargs Any

Options of the writer of the record.

{}

Returns:

Type Description
bytes

The content of the file.

to_text
to_text(**kwargs) -> str

Return the text of the file of the record.

Parameters:

Name Type Description Default
**kwargs Any

Options of the writer of the record.

{}

Returns:

Type Description
str

The text of the file.

to_lines
to_lines(**kwargs) -> Iterator[str]

Return the lines of the file of the record.

Parameters:

Name Type Description Default
**kwargs Any

Options of the writer of the record.

{}

Returns:

Type Description
Iterator[str]

The lines of the file, without line endings.

to_line
to_line(**kwargs) -> str

Return the single line of the file of the record.

Parameters:

Name Type Description Default
**kwargs Any

Options of the writer of the record.

{}

Returns:

Type Description
str

The line.

BdvRaw magic

BdvRaw(
    stored: NoRepr[bytes] = b"",
    version: str | None = None,
    base_path: str = ".",
    base_path_relative: bool = True,
    loader: str | None = None,
    hdf5: str | None = None,
    hdf5_relative: bool = False,
    setups: tuple[Setup, ...] = (),
    timepoints: _Ints = (),
    missing: tuple[_Ints, ...] = (),
    registrations: tuple[Registration, ...] = (),
    pyramids: tuple[Pyramid, ...] | None = None,
)

Bases: Raw, BinaryFileReader, BinaryFileWriter

Record of a BigDataViewer dataset, which holds its XML file.

A BigDataViewer dataset is an XML file, often named dataset.xml, that describes the views of an acquisition and how they are placed in a common space, and an HDF5 file that holds their voxels. BigStitcher keeps its registrations in the same XML file. The record holds the bytes of the XML file, so that a file that was read and not changed is written back byte for byte, and what brainhops reads from it: the setups, the time points, the missing views, where the HDF5 file is, and the registration of each view. The layout is described in brainhops.io.common.bdv.

The record is held by BdvMetadata. A record is frozen and never changed in place. Changing the registration of a view gives a new record, by with_registration, whose bytes differ from the old ones in that <ViewRegistration> element only.

An image read from the dataset also needs what the HDF5 file says about the resolution levels of each setup. The image reader reads it and stores it in pyramids, which is None in a record that was read from the XML file alone.

Parameters:

Name Type Description Default
stored NoRepr[bytes]

The bytes of the XML file, as read or as last encoded.

b''
version str | None

The version attribute of the root element.

None
base_path str

The text of <BasePath>, against which the HDF5 path resolves.

'.'
base_path_relative bool

Whether <BasePath> is relative to the directory of the XML file.

True
loader str | None

The format attribute of <ImageLoader>, such as "bdv.hdf5".

None
hdf5 str | None

The text of the <hdf5> child of <ImageLoader>, if any.

None
hdf5_relative bool

Whether the HDF5 path is relative to the base path.

False
setups tuple[Setup, ...]

The setups, in the order of the file.

()
timepoints _Ints

The ids of the time points, in increasing order.

()
missing tuple[_Ints, ...]

The views that have no data, as pairs of time point and setup.

()
registrations tuple[Registration, ...]

The registrations of the views, in the order of the file.

()
pyramids tuple[Pyramid, ...] | None

The resolution levels of each setup, read from the HDF5 file. It is None when only the XML file was read.

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.

stored class-attribute instance-attribute
stored: NoRepr[bytes] = b''

The bytes of the XML file, as read or as last encoded.

version class-attribute instance-attribute
version: str | None = None

The version attribute of the root element.

base_path class-attribute instance-attribute
base_path: str = '.'

The text of <BasePath>, against which the HDF5 path resolves.

base_path_relative class-attribute instance-attribute
base_path_relative: bool = True

Whether <BasePath> is relative to the directory of the XML file.

loader class-attribute instance-attribute
loader: str | None = None

The format attribute of <ImageLoader>, such as "bdv.hdf5".

hdf5 class-attribute instance-attribute
hdf5: str | None = None

The text of the <hdf5> child of <ImageLoader>, if any.

hdf5_relative class-attribute instance-attribute
hdf5_relative: bool = False

Whether the HDF5 path is relative to the base path.

setups class-attribute instance-attribute
setups: tuple[Setup, ...] = ()

The setups, in the order of the file.

timepoints class-attribute instance-attribute
timepoints: _Ints = ()

The ids of the time points, in increasing order.

missing class-attribute instance-attribute
missing: tuple[_Ints, ...] = ()

The views that have no data, as pairs of time point and setup.

registrations class-attribute instance-attribute
registrations: tuple[Registration, ...] = ()

The registrations of the views, in the order of the file.

pyramids class-attribute instance-attribute
pyramids: tuple[Pyramid, ...] | None = None

The resolution levels of each setup, read from the HDF5 file.

It is None when only the XML file was read.

Classes

Setup magic
Setup(
    id: int,
    name: str | None = None,
    size: _Ints | None = None,
    voxel_size: _Floats | None = None,
    unit: str | None = None,
)

Bases: Magic

One <ViewSetup>: a channel, an angle or a tile of the acquisition.

Parameters:

Name Type Description Default
id int

The id of the setup, which the views and the HDF5 groups use.

required
name str | None

The name of the setup, if the file gives one.

None
size _Ints | None

The size of the full-resolution image, in the order x, y, z.

None
voxel_size _Floats | None

The size of a voxel along x, y and z, in unit.

None
unit str | None

The unit of the voxel size, as the file writes it.

None
Attributes
id instance-attribute
id: int

The id of the setup, which the views and the HDF5 groups use.

name class-attribute instance-attribute
name: str | None = None

The name of the setup, if the file gives one.

size class-attribute instance-attribute
size: _Ints | None = None

The size of the full-resolution image, in the order x, y, z.

voxel_size class-attribute instance-attribute
voxel_size: _Floats | None = None

The size of a voxel along x, y and z, in unit.

unit class-attribute instance-attribute
unit: str | None = None

The unit of the voxel size, as the file writes it.

Methods:
Transform magic
Transform(
    type: str = "affine",
    name: str | None = None,
    affine: _Floats | None = _IDENTITY,
    span: _Ints | None = None,
)

Bases: Magic

One <ViewTransform> of a view registration.

Parameters:

Name Type Description Default
type str

The type of the transform: "affine" or "generic".

'affine'
name str | None

The text of the <Name> child, such as "calibration".

None
affine _Floats | None

The first three rows of the affine matrix, row after row. It is None for a generic transform, which a Java class reads and which brainhops cannot read.

_IDENTITY
span _Ints | None

Where the element lies in the bytes of the record. It is the offset of its first byte and the offset just after its last byte, or None for a transform that is not read from a file.

None
Attributes
type class-attribute instance-attribute
type: str = 'affine'

The type of the transform: "affine" or "generic".

name class-attribute instance-attribute
name: str | None = None

The text of the <Name> child, such as "calibration".

affine class-attribute instance-attribute
affine: _Floats | None = _IDENTITY

The first three rows of the affine matrix, row after row.

It is None for a generic transform, which a Java class reads and which brainhops cannot read.

span class-attribute instance-attribute
span: _Ints | None = None

Where the element lies in the bytes of the record.

It is the offset of its first byte and the offset just after its last byte, or None for a transform that is not read from a file.

Methods:
Registration magic
Registration(
    timepoint: int,
    setup: int,
    transforms: tuple[Transform, ...] = (),
    span: _Ints | None = None,
)

Bases: Magic

One <ViewRegistration>: the transforms of one view.

Parameters:

Name Type Description Default
timepoint int

The id of the time point of the view.

required
setup int

The id of the setup of the view.

required
transforms tuple[Transform, ...]

The transforms, in the order of the file. The last transform is applied first, so the map from the voxels of the view to the global space is the product of their matrices in this order.

()
span _Ints | None

Where the element lies in the bytes of the record.

None
Attributes
timepoint instance-attribute
timepoint: int

The id of the time point of the view.

setup instance-attribute
setup: int

The id of the setup of the view.

transforms class-attribute instance-attribute
transforms: tuple[Transform, ...] = ()

The transforms, in the order of the file.

The last transform is applied first, so the map from the voxels of the view to the global space is the product of their matrices in this order.

span class-attribute instance-attribute
span: _Ints | None = None

Where the element lies in the bytes of the record.

Methods:
Pyramid magic
Pyramid(
    setup: int,
    resolutions: tuple[_Floats, ...] = (),
    subdivisions: tuple[_Ints, ...] = (),
    data_type: str | None = None,
)

Bases: Magic

The resolution levels of one setup, as the HDF5 file gives them.

Parameters:

Name Type Description Default
setup int

The id of the setup.

required
resolutions tuple[_Floats, ...]

The downsampling factors of each level along x, y and z.

()
subdivisions tuple[_Ints, ...]

The chunk shape of each level along x, y and z.

()
data_type str | None

The dataType attribute of the setup group, such as "uint8". It is None in a file written before the attribute existed, whose voxels are 16-bit unsigned integers stored as signed ones.

None
Attributes
setup instance-attribute
setup: int

The id of the setup.

resolutions class-attribute instance-attribute
resolutions: tuple[_Floats, ...] = ()

The downsampling factors of each level along x, y and z.

subdivisions class-attribute instance-attribute
subdivisions: tuple[_Ints, ...] = ()

The chunk shape of each level along x, y and z.

data_type class-attribute instance-attribute
data_type: str | None = None

The dataType attribute of the setup group, such as "uint8".

It is None in a file written before the attribute existed, whose voxels are 16-bit unsigned integers stored as signed ones.

Methods:

Methods:

save
save(file: FileLike, **kwargs) -> None

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

to_file
to_file(file: FileLike, **kwargs) -> None

Write the object to a path or a file object.

A file object needs a write method.

Raises:

Type Description
ParserTypeError

If file is of another type.

to_filename
to_filename(filename: FilenameLike, **kwargs) -> None

Write the object to a path, always as bytes.

The content is encoded before the target changes, so that an error while it is encoded leaves the target as it was. A local file is written next to its target, which it then replaces at once. A remote file is written once the whole content is encoded. A text format is written with to_bytes, so that its line endings are written as they are, on every system. A binary format is written with to_fileobj, which a local file receives as it is written and a remote file receives once it is complete. A name that ends with .gz, .bz2 or .xz compresses the file, whatever the format.

to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file object open for writing.

A binary format writes the result of to_bytes. A text format writes the result of to_text to a text stream, such as a file opened with "w" or an io.StringIO, and the result of to_bytes to any other stream, such as a file opened with "wb" or an io.BytesIO.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

to_lines
to_lines(**kwargs) -> Iterator[str]

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

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

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

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

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

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

Same as sniff, for a path.

A missing file scores Confidence.NO, or raises SnifferExistsError if error is set. A compressed file is decompressed as it is read.

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
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

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

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

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

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
from_file(file: FileLike, **kwargs) -> Self

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_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_fileobj is implemented.

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

Read an object from text.

The text is split into lines and passed to from_lines.

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

Read an object from an iterable of lines.

The first line is passed to from_line.

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

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

from_dict classmethod
from_dict(other: Mapping, *args, **kwargs) -> Self

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 None or the value that the class fixes.

from_instance classmethod
from_instance(other: Any, *args, **kwargs) -> Self

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 None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is 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 to other.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 other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod
from_any(other: Any, *args, **kwargs) -> Self

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 from_dict, this method catches misspelled keys.

to
to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

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 cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

copy
copy() -> Self

Return a copy of the object.

Returns:

Type Description
self

The copy.

setup
setup(setup: int) -> Setup

Return the setup of a given id.

Parameters:

Name Type Description Default
setup int

The id of the setup.

required

Returns:

Type Description
Setup

The setup.

Raises:

Type Description
ParserContentError

If the dataset has no setup of that id.

registration
registration(timepoint: int, setup: int) -> Registration

Return the registration of a view.

Parameters:

Name Type Description Default
timepoint int

The id of the time point of the view.

required
setup int

The id of the setup of the view.

required

Returns:

Type Description
Registration

The registration.

Raises:

Type Description
ParserContentError

If the dataset has no registration for that view.

pyramid
pyramid(setup: int) -> Pyramid

Return the resolution levels of a setup.

Parameters:

Name Type Description Default
setup int

The id of the setup.

required

Returns:

Type Description
Pyramid

The resolution levels.

Raises:

Type Description
ParserContentError

If the record holds no levels for that setup, because the HDF5 file was not read or does not describe the setup.

view
view(
    setup: int | None = None, timepoint: int | None = None
) -> _Ints

Return the ids of the setup and of the time point of a view.

A setup or a time point that is not given is the first one, in the order of the ids, which is setup 0 and time point 0 in a dataset that BigDataViewer or BigStitcher wrote.

Parameters:

Name Type Description Default
setup int

The id of the setup.

None
timepoint int

The id of the time point.

None

Returns:

Name Type Description
setup int

The id of the setup.

timepoint int

The id of the time point.

Raises:

Type Description
ParserContentError

If the dataset has no such setup or time point, or none at all.

hdf5_filename
hdf5_filename(xml_filename: FilenameLike) -> Path

Return the path of the HDF5 file of the dataset.

The path resolves as BigDataViewer resolves it (XmlIoAbstractSpimData.loadBasePathURI and XmlIoHdf5ImageLoader.fromXml): <BasePath> against the directory of the XML file when it is relative, and the <hdf5> path against the base path when it is relative. A path is relative only when its type attribute says "relative".

Parameters:

Name Type Description Default
xml_filename path - like

The path of the XML file.

required

Returns:

Type Description
Path

The path of the HDF5 file.

Raises:

Type Description
ParserContentError

If the dataset does not name an HDF5 file.

with_registration
with_registration(
    timepoint: int,
    setup: int,
    transforms: Sequence[Transform],
) -> BdvRaw

Return a record whose view has other transforms.

The new bytes are the bytes of this record, in which the <ViewRegistration> element of the view is written again, so everything else in the file is kept byte for byte. A transform that has a span is a transform of this record, and its element is copied as it is, with its name and the exact text of its values. Any other transform is written in the layout of BigDataViewer, with the indentation and the line separator of the file. A record without bytes, such as a new record, is written as a new file with that single view.

Parameters:

Name Type Description Default
timepoint int

The id of the time point of the view.

required
setup int

The id of the setup of the view.

required
transforms sequence of BdvRaw.Transform

The transforms, in the order of the file.

required

Returns:

Type Description
BdvRaw

The new record, which keeps the pyramids of this record.

Raises:

Type Description
WriterError

If the bytes of the file do not start like an XML file in an encoding based on ASCII, or if the view has no registration.

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

Score a stream from the root element of its XML.

Parameters:

Name Type Description Default
file IO

The binary stream, whose position is restored.

required
error bool or type[Exception]

Whether to raise an error when the stream is not a BigDataViewer XML file.

False
**kwargs Any

Options of the reader, which are ignored.

{}

Returns:

Type Description
float

CERTAIN when the root element is <SpimData>, and NO otherwise.

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

Score bytes from the root element of their XML.

Parameters:

Name Type Description Default
content bytes

The content of a file, or its first bytes.

required
error bool or type[Exception]

Whether to raise an error when the bytes are not a BigDataViewer XML file.

False
**kwargs Any

Options of the reader, which are ignored.

{}

Returns:

Type Description
float

CERTAIN when the root element is <SpimData>, and NO otherwise.

from_fileobj classmethod
from_fileobj(file: BinaryIO, **kwargs) -> BdvRaw

Read the record from a binary stream of an XML file.

Parameters:

Name Type Description Default
file BinaryIO

The stream, read from its position to its end, which is restored.

required
**kwargs Any

Options of the reader, which are refused.

{}

Returns:

Type Description
BdvRaw

The record.

Raises:

Type Description
TypeError

If an option is given.

ParserContentError

If the content is not a BigDataViewer XML file.

to_bytes
to_bytes(**kwargs) -> bytes

Return the bytes of the XML file.

Parameters:

Name Type Description Default
**kwargs Any

Options of the writer, which are refused.

{}

Returns:

Type Description
bytes

The bytes that the record holds.

Raises:

Type Description
TypeError

If an option is given.