Validation & guards¶
from medaugmentx import Guard, ValidationError, VolumeValidator
Aggressive augmentation can produce a volume that is no longer a plausible
image: intensities pushed to NaN, contrast collapsed to a constant, or a crop
that removed a labelled class entirely. VolumeValidator checks for those
conditions and Guard enforces the check inside a pipeline.
from medaugmentx import Compose, Guard
from medaugmentx.transforms import AnatomicCrop, RandomAffine
pipeline = Compose([
Guard(RandomAffine(rotation=30), on_fail="retry", retries=3),
Guard(AnatomicCrop(size=(128, 128)), on_fail="revert"),
], seed=0)
Some checks are comparative: they compare the augmented volume against the
volume as it was before the transform ran, and are skipped when no reference is
available. Guard supplies that reference automatically. Calling
validate() yourself only runs them if you
pass reference=.
Guard is itself a Transform, so it nests inside
containers and round-trips through serialisation along with the transform and
validator it wraps.
The validator¶
- class medaugmentx.VolumeValidator(*, require_finite=True, forbid_constant=True, check_mask_shape=True, intensity_bounds=None, strict_bounds=False, min_foreground_fraction=None, preserve_mask_labels=True, max_foreground_loss=None, max_intensity_shift=None, check_geometry=True, require_geometry=False, foreground_measure='physical')[source]¶
Bases:
objectCheck a
MedVolumefor clinical plausibility.Each option toggles or parameterises one rule. Rules that compare against the pre-augmentation volume (
preserve_mask_labels,max_foreground_loss,max_intensity_shift) are only evaluated when areferenceis passed tovalidate();Guardsupplies it automatically.- Parameters:
require_finite (bool) – Fail if the image contains
NaNor±Inf.forbid_constant (bool) – Fail if the image collapsed to a single value (a common symptom of a broken intensity transform).
check_mask_shape (bool) – Fail if a mask is present but no longer matches the image shape (guards against spatial ops that resize only one array).
intensity_bounds (tuple[float, float] | None) – Optional
(low, high). Warn if image values fall outside the expected range — useful for windowed CT or normalised inputs. Setstrict_bounds=Trueto make it an error instead.strict_bounds (bool) – Escalate
intensity_boundsviolations to errors.min_foreground_fraction (float | None) – Optional. Fail if the fraction of non-zero mask voxels drops below this absolute threshold.
preserve_mask_labels (bool) – When a reference is given, fail if any label value present in the reference mask has completely disappeared (a structure was augmented out of existence).
max_foreground_loss (float | None) – When a reference is given, fail if the mask foreground shrank by more than this fraction (e.g.
0.9allows up to a 90% reduction; a full wipe fails).Nonedisables the check.max_intensity_shift (float | None) – When a reference is given, warn if the image mean moved by more than this many reference standard deviations — a coarse distribution-drift signal.
check_geometry (bool) – Check finite targets, valid spacing, and affine coherence.
require_geometry (bool) – Fail when patient geometry is unknown.
foreground_measure (str) –
"physical"area/volume per label, or"voxels".
- validate(volume, reference=None)[source]¶
Run all enabled checks and return a
ValidationReport.The structure and finite-value checks cover every channel. Intensity range, constant-image, and intensity-drift rules use the primary image.
- Parameters:
- Returns:
A report;
report.okisTruewhen no errors were found.- Return type:
- to_dict()[source]¶
Return the validator’s configuration as a plain dict.
- Return type:
dict[str, Any]
The guard¶
- class medaugmentx.Guard(transform, validator=None, on_fail='raise', retries=1, p=1.0, seed=None, catch_errors=False)[source]¶
Bases:
TransformWrap a transform and validate its output on every call.
Guardruns the wrapped transform, validates the result against the input volume, and then acts on any failure according toon_fail:"raise"— raiseValidationError(fail loud; good for tests and one-off dataset audits)."warn"— emit aUserWarningand return the output anyway."revert"— discard the output and return the original volume unchanged (never inject a bad sample into training)."retry"— run the wrapped transform with fresh randomness for up toretriestotal attempts; if none pass, fall back to reverting.
Guardis itself aTransform, so it nests insideCompose/OneOf/SomeOfand serialises like any other step.- Parameters:
transform (Transform) – The transform or pipeline to guard.
validator (VolumeValidator | Mapping[str, Any] | None) – A
VolumeValidator, itsto_dict()mapping, orNonefor the default validator.on_fail (str) – One of
"raise","warn","revert","retry".retries (int) – Maximum total attempts in
"retry"mode, including the first draw (ignored otherwise). Each attempt receives an isolated input copy.p (float) – Probability of applying the wrapped transform at all.
seed (SeedLike) – Seed for the retry re-draw stream.
catch_errors (bool) – Convert ValueError/FloatingPointError to failed reports; other exceptions always propagate. False propagates all exceptions.
Results¶
A report is truthy when the volume passed — that is, when it carries no
error-severity issues — so if not report: is the idiomatic check.
- class medaugmentx.ValidationReport(issues=())[source]¶
Bases:
objectThe outcome of validating one volume.
A report is truthy when the volume passed (no error-severity issues), so
if report:reads naturally. Warnings never fail a report on their own.- issues: tuple[ValidationIssue, ...] = ()¶
- property errors: tuple[ValidationIssue, ...]¶
- property warnings: tuple[ValidationIssue, ...]¶
- property ok: bool¶
Truewhen there are no error-severity issues.
- class medaugmentx.ValidationIssue(check, severity, message)[source]¶
Bases:
objectA single problem found while validating a volume.
- Variables:
check (str) – Name of the rule that produced the issue (e.g.
"finite").severity (str) –
"error"(volume is unusable) or"warning"(volume is suspicious but not provably broken).message (str) – Human-readable description, safe to log.
- check: str¶
- severity: str¶
- message: str¶
- class medaugmentx.ValidationError(report)[source]¶
Bases:
RuntimeErrorRaised when a
Guardinon_fail="raise"mode sees an error.The failing
ValidationReportis attached asreport.
Held-out segmentation comparisons¶
- medaugmentx.compare_segmentation_policies(references, predictions, *, case_to_patient, train_patients, labels, validation_patients=(), baseline='baseline', bootstrap_replicates=1000, seed=0)[source]¶
Compare hard segmentation predictions on identical held-out patients.
Predictions use
policy name -> training seed -> case ID -> label array. Each policy must cover every case and have the same training seeds as the baseline. Arrays must be integer or Boolean 2D/3D maps on the reference grid. The caller supplies patient IDs for leakage checks across splits.Each requested label contributes Dice in [0, 1]. Two empty masks score 1, while a prediction or reference alone scores 0. Average cases within a patient, then weight patients, labels and training seeds equally. Paired intervals bootstrap patients after averaging across the matched seeds. These intervals describe holdout variation conditional on those trained runs and require at least two held-out patients. Use zero replicates to disable them. The report contains aggregate counts and scores.
- Parameters:
references (Mapping[str, ndarray]) – Ground-truth label maps keyed by held-out case ID.
predictions (Mapping[str, Mapping[int, Mapping[str, ndarray]]]) – Model label maps by policy, training seed and case ID.
case_to_patient (Mapping[str, str]) – Stable patient ID for every held-out case.
train_patients (Iterable[str]) – Patient IDs used to train any compared policy.
labels (Sequence[int]) – Distinct nonzero integer class IDs to evaluate.
validation_patients (Iterable[str]) – Patient IDs used for tuning or model selection.
baseline (str) – Name of the unaugmented policy in
predictions.bootstrap_replicates (int) – Number of patient bootstrap draws for 95% intervals.
seed (int) – Non-negative bootstrap RNG seed.
- Return type:
dict[str, Any]