Presets, serialisation & inspection¶
Everything for turning a pipeline into something you can record, reload, and read back months later.
Modality presets¶
from medaugmentx.presets import ct_pipeline, dbt_pipeline, dxr_pipeline, mri_pipeline
Each factory returns a plain Compose. They are starting
points chosen to be conservative, not tuned policies — inspect one, then adjust
it for your data.
Pre-built augmentation pipelines for common medical imaging modalities.
Each factory returns a Compose pipeline
configured with clinically-motivated defaults. They are starting points —
tune parameters to your dataset rather than treating them as ground truth.
Available presets:
from medaugmentx.presets import mri_pipeline, ct_pipeline, dxr_pipeline, dbt_pipeline
pipeline = mri_pipeline(seed=42)
augmented = pipeline(volume)
All pipelines are serialisable via medaugmentx.serialization.
- medaugmentx.presets.mri_pipeline(seed=None, *, allow_flip=False, normalize=False)[source]¶
Standard MRI augmentation pipeline.
Applies a representative mix of spatial deformations, intensity perturbations, and MRI-specific artifacts:
Random flip along the array column axis (task/orientation dependent).
Random affine — small rotations and scaling.
Elastic deformation — simulate tissue deformability.
Bias field — RF coil / B0 inhomogeneity.
Rician noise — a single-complex-signal magnitude-noise approximation.
Gamma correction — scanner contrast variation.
One of: ghosting artifact, k-space line dropout, or motion blur.
- medaugmentx.presets.ct_pipeline(seed=None, *, allow_flip=False, normalize_output=False)[source]¶
Standard CT augmentation pipeline.
Combines spatial augmentations with CT-specific intensity transforms:
Random flip along the array column axis (task/orientation dependent).
Random affine — small rotations and scaling.
Elastic deformation.
Window / level variation — simulates protocol differences across sites.
Gaussian noise — additive CT quantum noise.
Gamma correction — contrast variation.
Beam hardening (cupping artifact) — applied occasionally.
Metal streak artifact — implant/clip simulation, applied rarely.
Expects native HU-scale CT input and keeps that intensity scale throughout: windowing clips without normalising, so the noise sigma remains in HU. Apply deterministic windowing/normalisation after this preset if needed. Augmented values are synthetic and no longer calibrated measurements.
- Parameters:
seed (SeedLike) – Top-level RNG seed for reproducibility.
allow_flip (bool) – Opt in only when the dataset/task permits laterality reversal.
normalize_output (bool) – Append deterministic window normalization after HU-domain effects.
- Returns:
A seeded
Composepipeline.- Return type:
- medaugmentx.presets.dxr_pipeline(seed=None, *, allow_flip=False, normalize=False)[source]¶
Augmentation pipeline for digital X-ray (chest X-ray / DXR).
Applies 2-D-safe transforms only:
Horizontal flip (requires a task that tolerates laterality reversal).
Slight affine — small rotation (patient positioning variation).
Gaussian blur — simulates detector resolution variation.
Brightness/contrast — exposure variation between scanners.
Gamma correction — film/detector response variation.
CLAHE — adaptive contrast equalisation (standard CXR pre-processing).
Simulate low resolution — cross-site resolution augmentation.
One of: scatter (veiling glare) or anti-scatter grid lines.
- medaugmentx.presets.dbt_pipeline(seed=None, *, allow_flip=False, normalize=False)[source]¶
Augmentation pipeline for Digital Breast Tomosynthesis (DBT).
DBT volumes are strongly anisotropic (thin slices, wide in-plane FOV). This pipeline combines the Phase-1 DBT-specific transforms with the new Phase-2 intensity transforms:
Random flip — horizontal axis only (breast anatomy).
Affine — in-plane rotation only (
axes_enabled=("z",)).Anisotropic elastic deformation — larger XY alpha, small Z.
Compression variation — breast-paddle compression differences.
Slab shift — reconstruction centre variation.
Limited-angle blur — arc-angle-dependent Z blur.
Recon streak — limited-angle out-of-plane parallax replicas.
Slice dropout — robustness to missing reconstruction slices.
Bias field — detector gain non-uniformity.
Gamma correction — scatter / beam hardening contrast variation.
Serialisation¶
from medaugmentx.serialization import from_json, from_yaml, to_json, to_yaml
A pipeline round-trips through JSON or YAML, which makes the exact augmentation
policy an artifact you can commit next to a set of results. Reconstruction only
ever instantiates registered Transform subclasses, and rejects oversized or
deeply nested documents.
Warning
A saved integer seed restarts the original draw sequence — it does not capture the RNG state at the moment of saving. Reloading mid-run therefore replays from the beginning of that stream rather than continuing.
Registering a custom transform makes its constructor reachable by name from any document you load, so treat pipeline files from outside your project the way you would treat any other executable input. See the security policy.
Pipeline serialisation — JSON round-trip and optional YAML support.
Usage:
from medaugmentx import Compose
from medaugmentx.transforms import GaussianNoise, GammaCorrection
from medaugmentx.serialization import to_json, from_json
pipeline = Compose([GaussianNoise(std=0.05), GammaCorrection()], seed=42)
json_str = to_json(pipeline)
pipeline2 = from_json(json_str)
Optional YAML support requires pip install pyyaml. All other functions
use only the Python standard library.
Registry¶
REGISTRY maps class names to classes. Custom transforms must be
registered before deserialisation. The recommended way is the
register_transform() decorator, which validates the class and guards
against silently clobbering a built-in:
from medaugmentx.core import Transform
from medaugmentx.serialization import register_transform
@register_transform
class MyTransform(Transform):
...
Direct assignment (REGISTRY["MyTransform"] = MyTransform) still works for
backward compatibility.
- medaugmentx.serialization.register_transform(cls: T) T[source]¶
- medaugmentx.serialization.register_transform(cls: None = None, *, name: str | None = None, override: bool = False) Callable[[T], T]
Register a custom
Transformfor serialisation.Usable bare or with arguments:
@register_transform class MyTransform(Transform): ... @register_transform(name="LegacyName") class MyTransform(Transform): ...
The class is added to
REGISTRYundername(defaulting to the class’s own__name__) and returned unchanged, so it can be used as a decorator. To round-trip cleanly the class must implementto_dictand accept itsto_dictparamsback through__init__.- Parameters:
cls – The transform class (supplied automatically when used bare).
name – Registry key. Defaults to
cls.__name__. Must match the"name"field the class emits fromto_dictfor round-trips to work.override – Allow replacing an existing registry entry. Defaults to
Falseso a name collision with a built-in (or another custom transform) raises instead of silently shadowing it.
- Returns:
The class itself (bare form) or a decorator (parametrised form).
- Raises:
TypeError – If
clsis not a subclass ofTransform.KeyError – If
nameis already registered to a different class andoverrideisFalse.
- medaugmentx.serialization.from_dict(d)[source]¶
Reconstruct a
Transformfrom its dict form.The dict must have the structure produced by
Transform.to_dict():{"name": "GaussianNoise", "params": {"std": 0.05, "p": 1.0}}
Container transforms (
Compose,OneOf,SomeOf) nest child dicts underparams["transforms"]; theGuardandPerChannelwrappers nest one underparams["transform"]. Both are rebuilt recursively.
- medaugmentx.serialization.to_json(transform, indent=2)[source]¶
Serialise a transform (or pipeline) to a JSON string.
- Parameters:
- Returns:
A JSON string that can be saved to disk and passed to
from_json()to reconstruct the pipeline.- Return type:
str
- medaugmentx.serialization.from_json(s)[source]¶
Reconstruct a transform from a JSON string produced by
to_json().
- medaugmentx.serialization.to_yaml(transform)[source]¶
Serialise a transform to a YAML string.
Requires
pip install pyyaml.
- medaugmentx.serialization.from_yaml(s)[source]¶
Reconstruct a transform from a YAML string produced by
to_yaml().Requires
pip install pyyaml.
- medaugmentx.serialization.REGISTRY¶
Mapping of transform class name to class, consulted by
from_dict(). Every shipped transform is registered at import time. Custom classes are normally added with theregister_transform()decorator, which validates the class and refuses to silently replace an existing name; assigning into the mapping directly also works.
Inspection¶
from medaugmentx import iter_pipeline, pipeline_summary
pipeline_summary renders a nested pipeline as a stable, readable tree —
useful in experiment logs and review notes. iter_pipeline exposes the same
traversal programmatically, for instance to assert in a test that no
mask-destroying transform ended up in a segmentation pipeline.
Helpers for inspecting transforms and nested augmentation pipelines.
- class medaugmentx.inspection.PipelineStep(path, name, params, depth)[source]¶
Bases:
objectOne node in a transform or pipeline tree.
- Variables:
path (tuple[int, ...]) – Tuple of child indices from the root. The root step uses
(); the first child of the root uses(0,); nested children use paths such as(1, 0).name (str) – Transform class name from
transform.to_dict()["name"].params (collections.abc.Mapping[str, Any]) – Parameters for this step, excluding nested
transforms.depth (int) – Nesting depth, equal to
len(path).
- path: tuple[int, ...]¶
- name: str¶
- params: Mapping[str, Any]¶
- depth: int¶
- medaugmentx.inspection.iter_pipeline(transform)[source]¶
Yield a depth-first view of a transform or nested pipeline.
The iterator is backed by each transform’s public
to_dict()output, so it mirrors the same structure used for JSON/YAML serialisation.- Parameters:
transform (Transform) – Any MedAugmentX
Transformor pipeline container.- Yields:
PipelineStepobjects in pre-order traversal.- Raises:
TypeError – If
transformis not aTransform.ValueError – If
transform.to_dict()does not expose a transform name.
- Return type:
Iterator[PipelineStep]
- medaugmentx.inspection.pipeline_summary(transform, *, max_value_length=72)[source]¶
Return a compact multi-line summary of a transform or pipeline.
- Parameters:
transform (Transform) – Any MedAugmentX
Transformor nested pipeline.max_value_length (int) – Maximum rendered length for each parameter value.
- Returns:
A stable, human-readable tree suitable for logs, experiment notes, and README snippets.
- Return type:
str
Per-sample seeding and exact replay¶
Per-sample seeding and exact same-environment execution records.
- medaugmentx.reproducibility.seed_for_sample(seed, sample_id, *, epoch=0, augmentation_index=0)[source]¶
Stable seed independent of worker assignment, rank, and processing order.
The same sample identifier/epoch/index deliberately yields the same draw on every worker. Use a distinct augmentation_index for independent replicas. Sample identifiers are hashed locally and are not written to a record.
- Return type:
int
- medaugmentx.reproducibility.apply_for_sample(transform, volume, *, seed, sample_id, epoch=0, augmentation_index=0)[source]¶
Apply an isolated policy copy with stable per-sample seeding.
Does not advance the original transform. Copying large histogram references can be expensive; create worker-local policies for throughput-sensitive code.
- Return type:
- medaugmentx.reproducibility.record_augmentation(transform, volume)[source]¶
Execute and record RNG checkpoints, branch decisions, policy, and hashes.
Records do not embed image data or volume metadata. Policy parameters such as histogram references may contain data; inspect records before sharing. Checkpoints replay numerical random draws rather than transcribing every draw as a separate scalar parameter. Version/environment equality is required.
- Return type:
tuple[MedVolume, dict[str, Any]]
Preview and model cards¶
Local augmentation inspection; plotting remains an optional dependency.
- medaugmentx.qa.volume_summary(volume, reference=None)[source]¶
Describe intensities, labels and targets without identifiers or source paths.
- Return type:
dict[str, Any]
- medaugmentx.qa.preview_augmentation(transform, volume, path, *, samples=6, seed=0)[source]¶
Save a local image/mask montage and return a machine-readable QA report.
Requires the
vizextra. Uses a copied policy, common image display limits, and middle array-axis slices for 3D. This is structural visual inspection, not a clinical plausibility test. The PNG contains image data; store it with the same access controls as the source images.- Return type:
dict[str, Any]
Model assumptions and validation scope for every shipped leaf transform.