Public surface & semantics¶
What is covered by compatibility guarantees, and the behaviour that spans more than one class and therefore has no single docstring to live in.
Signatures, parameters, and defaults are not on this page. They are generated from the source, so they always match the version you have installed:
Transform catalog — every augmentation, what it simulates, its knobs, and whether it moves annotations.
API reference — full docstrings for every public class and function.
What is public¶
Prefer these import paths in applications, papers, tutorials, and commercial code. Version 1 follows semantic versioning for these public imports. Internal module paths may change.
from medaugmentx import ( # core data model and pipelines
MedVolume, Transform, Compose, OneOf, SomeOf, PerChannel,
PipelineStep, iter_pipeline, pipeline_summary,
VolumeValidator, Guard, ValidationReport, ValidationIssue, ValidationError,
)
from medaugmentx.transforms import ... # all augmentations, flat namespace
from medaugmentx.presets import ... # mri_pipeline, ct_pipeline, dxr_pipeline, dbt_pipeline
from medaugmentx.serialization import ...# REGISTRY, register_transform, to_json, from_json, to_yaml, from_yaml
from medaugmentx.interop import ... # SampleTransform, TorchTransform, MonaiMapTransform, TorchIOTransform
from medaugmentx.io import ... # load_dicom_series, load_nifti, save_nifti
from medaugmentx.phantoms import ... # mri_phantom, ct_phantom, xray_phantom, dbt_phantom
from medaugmentx.studio import ... # launch, StudioServer, StudioSession (Policy Studio)
The medaugmentx console script (medaugmentx studio) is public as well; see
Policy Studio.
One exception is medaugmentx.core.geometry, which is public for authors of
custom spatial transforms — see Geometric targets.
MedVolume’s (image, mask, spacing, metadata) positional signature is
unchanged from earlier releases. The target fields were appended after it, so
existing positional callers keep working.
volume.index_to_world(points) maps (N, ndim) array coordinates to (N, 3)
RAS coordinates in millimetres. volume.world_to_index(points) performs the
inverse and returns continuous, unclipped array indices. Both require an
affine. For 2D images, world points must be on the actual image plane within
tolerance_mm (default 1e-5); off-plane coordinates raise.
Geometric targets¶
MedVolume can carry keypoints and bboxes alongside the image and mask.
This is the one piece of behaviour every spatial transform shares, so it is
specified here rather than repeated in each docstring.
Layout. Coordinates are stored in array-index order and float dtype —
(z, y, x) for 3D and (y, x) for 2D, the same order used to index image.
Boxes are (M, 2*ndim), laid out low corner first: [min_axis0, …, max_axis0, …].
Mapping. Spatial transforms warp targets in lockstep with the pixels:
Transform |
Effect on targets |
|---|---|
|
Reflect coordinates along the flipped axes |
|
Forward affine map about the volume centre, plus translation |
|
Iteratively invert the pixel pull field at each point; raise if inversion does not converge |
|
Shift by the crop origin (may go negative) |
|
Shift by the patch origin, accounting for any padding |
|
Shift by the pad width |
|
Preserve voxel extent: |
|
Preserve world coordinates on a centre-aligned grid with exact requested spacing; rounded dimensions can change voxel extent |
|
Move targets into an explicit reference grid while preserving patient coordinates |
|
Translate along the slice axis |
|
Scale about the volume centre on the compression axis |
|
Unchanged (pass through) |
The catalog’s Targets column is generated from the code. Delegating wrappers also map targets, even when their own module does not import geometry helpers.
Boxes under rotation. A box is mapped through its 2**ndim corners and
re-bounded to an axis-aligned box, so it stays valid but may grow. Elastic transforms default to conservative global displacement bounds that
enclose interior points but can be loose. Corner-only nonlinear boxes remain an
explicit approximation option.
Targets that leave the frame. Transforms map targets faithfully and never
drop them, because only the caller knows whether a partly-visible object should
survive. After a crop, call
volume.remove_out_of_bounds_targets(min_visibility=0.0) to drop off-frame
keypoints and clip or discard boxes, keeping labels aligned.
Writing your own. medaugmentx.core.geometry exposes the point maps
(flip_map, affine_map, translate_map, scale_map, displacement_map) and
the mappers (map_keypoints, map_bboxes). Build a point map, hand it to
MedVolume.warp with the resampled image, and targets are carried for you.
Shape versus spacing¶
Resize(size) preserves the full voxel extent and derives the spacing from the
requested shape. ResampleToSpacing(spacing) sets exact millimetres along each
existing grid axis, preserving grid directions, shear and the physical centre.
Its output size on each axis is max(1, floor(old_size * old_spacing / new_spacing + 0.5)). Integer rounding changes the voxel extent by at most half
an output voxel per axis, except when a minimum dimension of one is required.
It does not reorient scans, remove shear or register images.
The image uses configurable spline interpolation with optional antialiasing
before downsampling; the mask always uses nearest-neighbour without smoothing.
Both use nearest-edge extension at boundaries. clip_output=True clamps spline
overshoot. Output images are float32; masks retain their dtype. Landmarks and
boxes are mapped continuously and never implicitly clipped or dropped. Unknown
patient geometry stays unknown; declared spacing still determines resampling.
Output shapes depend on input spacing and dimensions. Use Pad and CenterCrop
afterwards when batching requires a fixed shape. max_voxels optionally rejects
an oversized output before interpolation or smoothing; it bounds the output
voxel count, not peak working memory. This setting is saved in policy JSON/YAML.
Matching a reference grid¶
Use ResampleToGrid(reference.shape, reference.affine, cval=...) when the output
must use a specific shape, origin, spacing and orientation. The source and
reference must already share the same patient coordinate system. In 2D,
the target grid must lie in the source plane within 1e-4 mm across its
field of view.
The image uses spline interpolation against cval outside the source field.
The mask uses nearest-neighbour with label 0 outside the source voxel extent.
Put categorical IDs in the mask rather than the image to preserve their
dtype and exact values. Images are sampled in float32, and grid downsampling
applies no antialiasing. When returning predictions to a native grid, the
target affine restores their spatial frame and shape. Interpolation cannot
recover values discarded earlier by cropping or downsampling.
Fixed-size training patches¶
ClassBalancedCrop(size, foreground_prob=0.5, labels=None) returns one patch
per applied call. The foreground branch samples a class uniformly from the
eligible nonzero labels present in the mask. It samples a voxel uniformly from
that class, then samples an origin uniformly among origins that include the
voxel. A missing mask, a missing eligible class, or the alternate probability
branch yields an unrestricted spatially uniform origin. Use labels to
exclude ignore IDs. A patch may also contain other classes.
Use p=1 to guarantee the requested shape. Short axes retain every original
voxel and split the extra padding across both sides, with an odd extra voxel
at the high end. Padded images use float32 and cval in the current intensity
units. Masks retain their dtype and use label 0 for padding. Spacing and
patient coordinates are preserved. For detection, call
remove_out_of_bounds_targets after patch extraction if your task needs target
pruning or clipping.
Synchronized image channels¶
MedVolume.with_channels({"flair": flair_volume}) verifies equal shape and a
known, matching patient grid. To attach arrays already checked by your loader,
pass channels={"flair": flair_array} when constructing the primary volume.
The primary image determines spacing, geometry, and the associated mask and
targets. Channel names are preserved through the policy. stack_channels()
puts the primary image first, then the additional names in insertion order.
Pass the names explicitly to select channels and pin their order.
Spatial transforms and coarse or slice dropout share one set of sampled
parameters for all images. Intensity and appearance transforms operate on the
primary image. Wrap them in PerChannel to augment the channels too, within
the same policy:
PerChannel(Compose([BiasField(alpha=0.3), GaussianNoise(std=0.02)]))
PerChannel(GammaCorrection(), channels=["flair"], include_primary=False)
PerChannel(BrightnessContrast(), shared=True) # one draw reused per image
By default each image gets its own draw, in the order primary image, then the
selected channels (channels=None selects all, in insertion order). Use
shared=True when channels share an intensity scale and should change
together. The wrapped transform must leave shape, mask, geometry, and targets
unchanged, so spatial transforms raise ValueError; place them outside the
wrapper, where they already move every channel together. Metadata is taken from
the primary image’s result. PerChannel serialises, inspects, and replays like
Guard. A spatial transform’s image padding or fill is shared across
channels, so choose it for their common intensity scale. A custom spatial
transform can pass image_map= to MedVolume.warp to reuse one sampled mapping.
Named channels flow through Compose, Guard, per-sample seeding, and replay.
The existing tensor and dictionary adapters still accept single-channel image
fields. Construct a MedVolume directly for synchronized channels and stack
its output for the model. Use select_channel("flair") or select_channel()
to export a single image via NIfTI.
Randomness and reproducibility¶
Every transform accepts seed, and every container derives an independent
stream per child rather than sharing one — so two identically-seeded transforms
in the same Compose do not draw identical numbers.
A serialised integer seed restarts the original draw sequence; it does not capture the RNG state at the moment of saving. Reloading a pipeline mid-run therefore replays that stream from the beginning rather than continuing it. For multi-worker data loaders and full replay, see the research guide.
Validation severity¶
VolumeValidator rules fall into two groups:
Absolute rules look at the augmented volume alone: finiteness, collapse to a constant, mask shape, intensity bounds, minimum foreground fraction.
Comparative rules need the pre-augmentation volume — label preservation, foreground loss, intensity drift. They are skipped unless you pass
reference=tovalidate().Guardsupplies it automatically.
A ValidationReport is truthy when the volume passed, meaning it carries no
error-severity issues. Bounds violations are warnings by default and become
errors under strict_bounds=True. In on_fail="raise" mode Guard raises
ValidationError, which carries the failing report on .report.
Serialisation limits¶
Pipelines round-trip through JSON and YAML so the exact augmentation policy can be committed next to a set of results. Loading enforces hard limits: at most 1,000,000 characters of text, 64 levels of nesting, and 10,000 transforms. Malformed structures are rejected rather than partially constructed.
Only classes present in REGISTRY are ever instantiated. Registering a custom
transform makes its constructor reachable by name from any document you load —
custom registrations are trusted Python code, so treat pipeline files from
outside your project as executable input. See the
security policy.
Framework interop¶
The adapters accept the sample shapes each framework uses and return the same kind they were given:
Input |
Output |
|---|---|
|
|
|
Same array or tensor kind |
|
Same tuple or list kind |
Mapping with |
Shallow-copied mapping |
TorchIO |
|
The framework adapters accept single-channel 2D and 3D image fields. channel_dim — None,
"auto", "first", "last", or an integer axis — says where the adapter
should expect a singleton channel dimension; it is stripped before augmentation
and restored afterwards. "auto" treats a leading (or else trailing) singleton
axis of a 3D or 4D array as the channel, so a single-slice 3D volume shaped
(1, H, W) becomes 2D. Pass channel_dim=None for such volumes. With
preserve_image_dtype=True, floating results are rounded to the nearest integer
before integer dtypes are restored.
TorchIO adapters require their configured image and optional label keys. Additional images are rejected because they would not receive the sampled warp. Native XYZ axes and current affines are converted explicitly.
Importing an adapter never imports its framework. Torch, MONAI, and TorchIO are touched only when a sample of that kind actually passes through.
Optional extras¶
The core install is NumPy and SciPy only. Everything else is opt-in:
Extra |
Installs |
Needed for |
|---|---|---|
|
|
|
|
|
|
|
|
Both readers |
|
|
Local image/mask QA montage |
|
|
|
|
|
|
|
|
MONAI dictionary pipelines |
|
|
|
|
|
All three |
|
|
Running the tutorials |
|
|
Building this site |
Version 1 geometry, seeding and inspection¶
See migration contracts for the authoritative affine convention,
NIfTI/DICOM support, preset domains and framework limitations. Public helpers
apply_for_sample, seed_for_sample, record_augmentation, replay_augmentation,
preview_augmentation, volume_summary, model_card and list_model_cards
are available from medaugmentx. Preview requires the viz extra.