TomoJAX

tomojax.io.api

Expert IO helpers: acquisition readers, NXtomo containers, inspection and JSON.

The dataset entry points users call are exported by tomojax.io; raw frames are read with tomojax.load_frames.

NameSummary
JsonValue
LoadedNXTomoTyped NXtomo payload returned by load_nxtomo().
LocatedFramesLocated HDF5 frames with optional frame labels and rotation angles.
NXTomoMetadataPortable metadata bundle for NXtomo persistence.
convert_datasetConvert between supported TomoJAX dataset container formats.
format_inspection_reportFormat an inspection report for terminal output.
inspect_datasetInspect a measured projection dataset before reconstruction.
load_anglesLoad a nonempty, finite FP32 angle vector in degrees without reordering.
load_nxtomoLoad an NXtomo dataset and TomoJAX extras.
locate_framesFind the stack of frames in an HDF5 file, and its image_key and angles.
normalize_jsonConvert common runtime objects into strict JSON-compatible values.
projection_statsReturn finite-value projection statistics and nonfinite counts for a frame stack.
read_acquisitionRecognize a vendor acquisition by content and read its raw metadata/stacks.
read_calibration_framesRead a lazy calibration stack from HDF5, TIFF or Zeiss Xradia images.
read_hdf5_arrayRead an array without changing its dtype, axes, filters or file contents.
read_json_objectRead a JSON file that must contain an object.
read_tiff_framesGrayscale TIFF pages as (frames, rows, columns) in the files' dtype.
save_nxtomoWrite a dataset to an HDF5 file using NXtomo + TomoJAX extras.
save_projection_quicklookSave a percentile-scaled central projection PNG.
validate_nxtomoCheck the lightweight NXtomo schema and report any issues.

JsonValue

JsonValue = None | bool | int | float | str | list['JsonValue'] | dict[str, 'JsonValue']
Defined in src/tomojax/_json.py:15

LoadedNXTomo

class LoadedNXTomo(
    projections: np.ndarray | Hdf5Frames,
    metadata: NXTomoMetadata,
    source: SourceInfo | None = None,
    disk_volume_axes_order: str | None = None,
    volume_axes_source: str | None = None,
)
Defined in src/tomojax/_data/_io_types.py:188

Typed NXtomo payload returned by load_nxtomo().

Parameters

  • projections (numpy.ndarray or lazy HDF5 stack): Projection or detector-frame stack in (view, v, u) order.
  • metadata (NXTomoMetadata): Persisted acquisition and reconstruction metadata.
  • source (dict or None, optional): Radiation source metadata.
  • disk_volume_axes_order (str or None, optional): Original on-disk volume axis order.
  • volume_axes_source (str or None, optional): Origin of the volume-axis convention, recorded during loading.

LoadedNXTomo.from_dataset

@classmethod
from_dataset(data: Mapping[str, DatasetValue]) -> LoadedNXTomo

Build a loaded payload from a generic dataset mapping.

Parameters

  • data (mapping): Loaded dataset fields and metadata.

Returns

  • LoadedNXTomo: Typed dataset metadata or payload with copied array metadata.

Raises

  • KeyError: If projections are absent.

LoadedNXTomo.get

get(key: str, default: DatasetValue | None = None) -> DatasetValue | None

Return a metadata or payload value by mapping-style key.

Parameters

  • key (str): Payload, metadata or additional geometry key.
  • default (object, optional): Value for an absent metadata or geometry key; defaults to None.

Returns

  • object: Stored value, or the default when that metadata key is absent.

LoadedNXTomo.to_dataset_dict

to_dataset_dict() -> LoadedDataset

Return this payload as a generic dataset mapping.

Returns

  • dict: Dataset mapping with projections materialized and typed geometry converted to mappings.

LoadedNXTomo.copy_metadata

copy_metadata() -> NXTomoMetadata

Return a writable metadata copy suitable for save/update workflows.

Returns

  • NXTomoMetadata: Writable persistence metadata with copied array fields.

LoadedNXTomo.geometry_inputs

geometry_inputs() -> dict[str, DatasetValue]

Return the subset of metadata needed to materialize geometry.

Returns

  • dict: Detector, angles, grid and additional geometry metadata for reconstruction.

Raises

  • ValueError: If detector metadata or rotation angles are absent.

LocatedFrames

class LocatedFrames(
    stack: Hdf5Frames,
    image_key: np.ndarray | None,
    angles: np.ndarray | None,
    flats: Hdf5Frames | None = None,
    darks: Hdf5Frames | None = None,
    acquisition: dict[str, str] | None = None,
    image_key_path: str | None = None,
    angles_path: str | None = None,
)
Defined in src/tomojax/_data/_io_frames.py:218

Located HDF5 frames with optional frame labels and rotation angles.

flats and darks are stacks of their own beside the frames, as in APS Data Exchange (data_white, data_dark), when the file keeps them apart rather than marking them in image_key.

Parameters

  • stack (lazy HDF5 stack): Located detector-frame stack, read only as indexed.
  • image_key (numpy.ndarray or None): Frame labels when present: sample, flat, dark or other.
  • angles (numpy.ndarray or None): One angle per frame, in degrees, when present.
  • flats (lazy HDF5 stack or None, optional): Separate open-beam frames, when not interleaved with the sample.
  • darks (lazy HDF5 stack or None, optional): Separate beam-off frames.
  • acquisition (dict or None, optional): Discovered acquisition paths and unit corrections.
  • image_key_path (str or None, optional): HDF5 path the frame labels were read from, when present.
  • angles_path (str or None, optional): HDF5 path the rotation angles were read from, when present.

LocatedFrames.raw

@property
raw: bool

Whether the file holds flat or dark frames: its frames are detector counts.

Returns

  • bool: True when flat or dark frames mark the data as detector counts.

NXTomoMetadata

class NXTomoMetadata(
    angles: np.ndarray | None = None,
    image_key: np.ndarray | None = None,
    grid: Grid | GridDict | None = None,
    detector: Detector | DetectorDict | None = None,
    geometry_type: str = 'parallel',
    geometry_meta: JsonObject | None = None,
    volume: np.ndarray | jax.Array | None = None,
    align_params: np.ndarray | None = None,
    align_gauge: JsonObject | None = None,
    geometry_calibration: JsonObject | None = None,
    angle_offset_deg: np.ndarray | None = None,
    misalign_spec: JsonObject | None = None,
    simulation_artefacts: JsonObject | None = None,
    frame: str | None = None,
    sample_name: str | None = 'sample',
    source_name: str | None = 'TomoJAX source',
    source_type: str | None = None,
    source_probe: str | None = 'x-ray',
    volume_axes_order: str = DISK_VOLUME_AXES,
)
Defined in src/tomojax/_data/_io_types.py:55

Portable metadata bundle for NXtomo persistence.

Parameters

  • angles (numpy.ndarray or None, optional): Per-frame rotation angles in degrees.
  • image_key (numpy.ndarray or None, optional): Frame labels: 0 sample, 1 flat, 2 dark, 3 other.
  • grid (Grid, dict or None, optional): Reconstruction voxel grid in physical units.
  • detector (Detector, dict or None, optional): Detector dimensions, pitches and physical centre.
  • geometry_type (str, optional): Geometry family; defaults to parallel.
  • geometry_meta (dict or None, optional): Additional geometry and acquisition metadata.
  • volume (numpy.ndarray, jax.Array or None, optional): Reconstructed volume in internal (x, y, z) order.
  • align_params (numpy.ndarray or None, optional): Saved per-view alignment parameters.
  • align_gauge (dict or None, optional): Gauge and frame conventions for alignment parameters.
  • geometry_calibration (dict or None, optional): Calibration state and provenance.
  • angle_offset_deg (numpy.ndarray or None, optional): Saved per-view angle corrections in degrees.
  • misalign_spec (dict or None, optional): Simulation misalignment metadata.
  • simulation_artefacts (dict or None, optional): Simulation artefact settings and provenance.
  • frame (str or None, optional): Coordinate-frame label.
  • sample_name (str or None, optional): Sample name; defaults to sample.
  • source_name (str or None, optional): Radiation source name; defaults to TomoJAX source.
  • source_type (str or None, optional): Radiation source type.
  • source_probe (str or None, optional): Probe label; defaults to x-ray.
  • volume_axes_order (str, optional): Axis permutation for on-disk volume storage; defaults to zyx.

NXTomoMetadata.from_dataset

@classmethod
from_dataset(data: Mapping[str, DatasetValue]) -> NXTomoMetadata

Build metadata from a generic loaded dataset mapping.

Parameters

  • data (mapping): Loaded dataset fields and metadata.

Returns

  • NXTomoMetadata: Typed dataset metadata or payload with copied array metadata.

convert_dataset

convert_dataset(input_path: PathLike, output_path: PathLike) -> None
Defined in src/tomojax/io/_datasets.py:446

Convert between supported TomoJAX dataset container formats.

Parameters

  • input_path (str or pathlib.Path): Input NXtomo/HDF5 or NPZ container.
  • output_path (str or pathlib.Path): Output container of the other format.

Returns

  • None: Write the converted dataset with its metadata.

Raises

  • ValueError: If the conversion is not NPZ to HDF5 or HDF5 to NPZ.
  • OSError: If a file cannot be read or written.

format_inspection_report

format_inspection_report(report: InspectionReport) -> str
Defined in src/tomojax/io/_inspection_format.py:21

Format an inspection report for terminal output.

Parameters

  • report (InspectionReport): Structured dataset inspection report.

Returns

  • str: Human-readable multiline summary for terminal output.

inspect_dataset

inspect_dataset(path: PathLike) -> InspectionReport
Defined in src/tomojax/io/_inspection.py:588

Inspect a measured projection dataset before reconstruction.

Parameters

  • path (str or pathlib.Path): HDF5/NXtomo dataset or recognized vendor acquisition file or folder.

Returns

  • InspectionReport: Projection, acquisition, geometry and estimated memory report.

Raises

  • ValueError: If projections or acquisition metadata have invalid dimensions.
  • KeyError: If projection data cannot be found.
  • OSError: If the input cannot be opened.

load_angles

load_angles(path: str | Path) -> np.ndarray
Defined in src/tomojax/io/_angles.py:10

Load a nonempty, finite FP32 angle vector in degrees without reordering.

Accept a one-dimensional .npy array or text/CSV with the angle in the first column. Blank lines, # comments, and leading header lines are skipped. Once numeric data starts, a malformed row raises ValueError with its line number. The caller must check the number of projection views.

Parameters

  • path (str or pathlib.Path): NPY, text or CSV sidecar with angles in its first column.

Returns

  • numpy.ndarray: Finite nonempty float32 angles in degrees, in acquisition order.

Raises

  • ValueError: If angles are empty, nonfinite, not a vector or contain malformed data rows.
  • OSError: If the file cannot be read.

load_nxtomo

load_nxtomo(path: str, *, lazy: bool = False) -> LoadedNXTomo
Defined in src/tomojax/_data/_io_nxtomo.py:372

Load an NXtomo dataset and TomoJAX extras.

Returns a LoadedNXTomo payload with typed accessors for projections and persisted metadata. grid is present only when the file stores grid metadata; a saved volume does not establish physical voxels. Volumes are returned in internal xyz order. With lazy the projections are an Hdf5Frames, read only as indexed.

Parameters

  • path (str): NXtomo/HDF5 input file.
  • lazy (bool, optional): Keep projections lazy rather than materializing them; defaults to False.

Returns

  • LoadedNXTomo: Projection payload and metadata, with any saved volume in internal xyz order.

Raises

  • KeyError: If required NXtomo groups or projection data are absent.
  • ValueError: If per-frame metadata or volume-axis conventions are invalid.
  • OSError: If the input cannot be opened.

locate_frames

locate_frames(
    path: str,
    *,
    data_path: str | None = None,
    image_key_path: str | None = None,
    angles_path: str | None = None,
) -> LocatedFrames
Defined in src/tomojax/_data/_io_frames.py:268

Find the stack of frames in an HDF5 file, and its image_key and angles.

Each is read from the path given, else the NXtomo (or Data Exchange) path, else the file's only dataset of that name (data of two or three dimensions, image_key, rotation_angle) with one entry per frame. A uniquely named key or angle dataset with the wrong shape is rejected, not treated as missing. Flats and darks kept beside the frames (data_white, data_dark) are found when image_key marks none of that kind, and so are angles there (theta). Angles in radians (a units attribute) are converted to degrees.

Parameters

  • path (str): HDF5 acquisition file.
  • data_path (str or None, optional): Explicit frame dataset path; None uses discovery.
  • image_key_path (str or None, optional): Explicit frame-label dataset path; None uses discovery.
  • angles_path (str or None, optional): Explicit rotation-angle dataset path; None uses discovery.

Returns

  • LocatedFrames: Lazy frame stacks plus frame labels, angles and acquisition metadata.

Raises

  • KeyError: If frames or an explicitly requested dataset cannot be found.
  • ValueError: If discovery is ambiguous or per-frame metadata are malformed.
  • OSError: If the file cannot be opened.

normalize_json

normalize_json(
    value: object,
    *,
    namespace: bool = False,
    sort_mapping_keys: bool = False,
    catch_to_dict_errors: bool = False,
) -> JsonValue
Defined in src/tomojax/_json.py:18

Convert common runtime objects into strict JSON-compatible values.

Parameters

  • value (object): Runtime value, including mappings, dataclasses, paths and NumPy/JAX arrays.
  • namespace (bool, optional): Convert argparse namespaces to mappings; defaults to False.
  • sort_mapping_keys (bool, optional): Sort mapping keys by their string representation.
  • catch_to_dict_errors (bool, optional): Fall back to text if an object's to_dict method fails.

Returns

  • JSON-compatible value: Normalized value; nonfinite floats and otherwise unsupported objects become strings.

Raises

  • TypeError: If a NumPy or JAX value cannot be materialized as JSON data.

Examples

import numpy as np
from tomojax.io.api import normalize_json
normalize_json({"angles": np.array([0.0, 90.0]), "missing": float("nan")})
# {'angles': [0.0, 90.0], 'missing': 'nan'}

projection_stats

projection_stats(
    dataset: _ProjectionStack,
) -> tuple[ProjectionStatsReport, NonfiniteReport]
Defined in src/tomojax/io/_inspection.py:147

Return finite-value projection statistics and nonfinite counts for a frame stack.

Parameters

  • dataset (array-like): HDF5 dataset, NumPy array or lazily indexed projection stack, summarized in bounded view blocks.

Returns

  • tuple of dict: Projection statistics and nonfinite-value counts.

read_acquisition

read_acquisition(
    path: str | PathLike[str],
    *,
    data_path: str | None = None,
    image_key_path: str | None = None,
    angles_path: str | None = None,
) -> RawAcquisition | None
Defined in src/tomojax/io/_acquisition.py:56

Recognize a vendor acquisition by content and read its raw metadata/stacks.

None means this is not a recognized acquisition, so the caller can try ordinary datasets or TIFF stacks. Recognized but incomplete or ambiguous inputs raise rather than silently becoming an unrelated format. Readers own format-specific discovery; this function owns their dispatch order.

Parameters

  • path (str or os.PathLike): Acquisition file or folder.
  • data_path (str or None, optional): Explicit dataset path for formats that hold several candidate stacks.
  • image_key_path (str or None, optional): Explicit frame-label dataset for external HDF5 acquisitions.
  • angles_path (str or None, optional): Explicit rotation-angle dataset for external HDF5 acquisitions.

Returns

  • RawAcquisition or None: The reader's geometry record and raw stacks, or None if no reader recognizes the input.

Raises

  • ValueError: If a recognized acquisition is incomplete or ambiguous.

read_calibration_frames

read_calibration_frames(path: str | Path) -> FrameStack
Defined in src/tomojax/io/_calibration.py:11

Read a lazy calibration stack from HDF5, TIFF or Zeiss Xradia images.

No sample-view geometry is required. Every image contributes to the flat or dark mean.

Parameters

  • path (str or pathlib.Path): HDF5 stack, TIFF file or folder, or Zeiss image container. Zeiss content is recognised independently of the filename.

Returns

  • FrameStack: Lazy images in (frame, row, column) order, with their stored dtype.

Raises

  • ValueError: If image dimensions, type or format are unsupported.
  • OSError: If the input cannot be read.

read_hdf5_array

read_hdf5_array(
    dataset: h5py.Dataset,
    selection: tuple[slice, ...] | None = None,
) -> np.ndarray
Defined in src/tomojax/io/_hdf5_array.py:15

Read an array without changing its dtype, axes, filters or file contents.

dataset remains owned by the caller and must stay open until this call returns. Large, unit-stride slices of read-only, fixed-size gzip chunks use two decode workers; HDF5 access itself stays on the calling thread. A bounded four-job queue avoids allocating any full-sized temporary stack. Other layouts, filters and slices use the ordinary HDF5 reader.

Parameters

  • dataset (h5py.Dataset): Open dataset to read from.
  • selection (tuple of slice or None, optional): Index of the region to read; None reads the whole dataset.

Returns

  • numpy.ndarray: The selected values, in the dataset's dtype and axis order.

read_json_object

read_json_object(path: Path) -> dict[str, JsonValue]
Defined in src/tomojax/_json.py:130

Read a JSON file that must contain an object.

Parameters

  • path (pathlib.Path): JSON file containing an object.

Returns

  • dict: Parsed JSON object.

Raises

  • FileNotFoundError: If the path does not exist.
  • ValueError: If the content is invalid JSON or not an object.

read_tiff_frames

read_tiff_frames(path: Path | str, *, lazy: bool = False) -> np.ndarray | TiffFrames
Defined in src/tomojax/io/_tiff.py:215

Grayscale TIFF pages as (frames, rows, columns) in the files' dtype.

Files in a folder are naturally sorted, then every top-level page is read in file order. Every page must be a 2-D image of the first page's size and dtype; colour images are rejected rather than read as extra view axes. lazy=True checks the headers and returns a stack read only as indexed (np.asarray reads it all); windows read only their mapped pixels or intersecting compressed strips/tiles.

Parameters

  • path (str or pathlib.Path): Grayscale multipage TIFF or folder of TIFF files.
  • lazy (bool, optional): Inspect headers now and read pixels only when indexed; defaults to False.

Returns

  • numpy.ndarray or lazy TIFF stack: Frames in (frame, row, column) order and the files' dtype.

Raises

  • ValueError: If pages are not consistent two-dimensional grayscale frames.
  • FileNotFoundError: If the input contains no TIFF frames.

save_nxtomo

save_nxtomo(
    path: str,
    projections: np.ndarray,
    *,
    metadata: NXTomoMetadata | None = None,
    compression: str = 'lzf',
    overwrite: bool = True,
) -> None
Defined in src/tomojax/_data/_io_nxtomo.py:45

Write a dataset to an HDF5 file using NXtomo + TomoJAX extras.

metadata owns the persistence contract: geometry, detector/grid definitions, optional reconstructed volume, and TomoJAX-specific extras. Volume inputs in metadata.volume are always expected in internal xyz order; set metadata.volume_axes_order to control how that internal volume is serialized on disk.

Parameters

  • path (str): NXtomo output file; parent directories are created.
  • projections (numpy.ndarray): Projection stack in (view, v, u) order.
  • metadata (NXTomoMetadata or None, optional): Acquisition and reconstruction metadata; absent angles stay absent. None writes projections without detector or angular calibration.
  • compression (str, optional): HDF5 dataset compression filter; defaults to lzf.
  • overwrite (bool, optional): Replace an existing file; False requires a new path.

Returns

  • None: Write projections and metadata to the NXtomo container.

Raises

  • ValueError: If projection shape or volume-axis metadata are invalid.
  • OSError: If output cannot be written or already exists with overwrite=False.

save_projection_quicklook

save_projection_quicklook(input_path: PathLike, output_path: PathLike) -> Path
Defined in src/tomojax/io/_quicklook.py:29

Save a percentile-scaled central projection PNG.

Parameters

  • input_path (str or pathlib.Path): HDF5 projection dataset.
  • output_path (str or pathlib.Path): PNG output path; parent directories are created.

Returns

  • pathlib.Path: Written preview path.

Raises

  • KeyError: If projection data cannot be found.
  • ValueError: If projections are not a three-dimensional stack.
  • OSError: If input or output cannot be accessed.

validate_nxtomo

validate_nxtomo(path: str) -> ValidationReport
Defined in src/tomojax/_data/_io_nxtomo.py:484

Check the lightweight NXtomo schema and report any issues.

Parameters

  • path (str): NXtomo file to check.

Returns

  • dict: Schema report; an empty issues list means no problems were found.

On this page