Scoring a Mesh-Stage Model Against Images
A mm error against the surfaces a registration produced says how well the
network reproduces that registration. WorkflowEvaluateMovement asks the
other question: how close are the size and shape of the inferred anatomy to the
anatomy that was actually imaged, structure by structure. See Tutorial 11 in
Tutorials.
For every gated time point it carries the reference frame’s labelmap into that time point with the network’s own deformation, and compares the result to the labelmap of the frame that was acquired: volume difference, Dice and surface RMSE per lung lobe or per heart chamber.
Per-structure scoring
- class monai_physio.WorkflowEvaluateMovement(movement_workflow, cohort=None, label_names=None, log_level=20)[source]
Bases:
MONAIPhysioBaseScore inferred motion per anatomical structure against acquired frames.
- Parameters:
movement_workflow (
WorkflowInferMovement) – The displacement decoder whose predictions are scored.cohort (
Optional[EvaluateMovementBase]) – The cohort being scored —monai_physio.EvaluateMovementLung,monai_physio.EvaluateMovementDukeHeartor anothermonai_physio.EvaluateMovementBase. It supplies the structures to score and this cohort’s defaults, and itsassemble_ground_truth()produces whatprocess()scores against. The workflow never learns which cohort it holds, which is what keeps it free of anatomy branches.label_names (
Optional[dict[int,str]]) – Structures to score,{label_id: name}, for a caller with no cohort. Ids the reference frame does not contain are dropped with a warning; ids a single acquired frame does not contain are skipped for that frame alone, since a structure can leave the field of view.log_level (
int|str) – Logging level. Default:logging.INFO.
- __init__(movement_workflow, cohort=None, label_names=None, log_level=20)[source]
Initialize the base class with logging configuration.
- Parameters:
class_name – Name for the class (used in log messages). If None, uses the class name. Default: None
log_level (
int|str) – Lowest level this object logs at. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).set_log_level()sets a floor for every object at once. Default: logging.INFOlog_to_file – Optional file path to write all MONAI Physio logs to as well; only the first object’s value is used. Default: None
- set_smoothing_sigma_mm(smoothing_sigma_mm)[source]
Set the sigma that spreads the network’s surface-shell deformation.
- Parameters:
smoothing_sigma_mm (
Optional[float]) – Gaussian sigma in millimeters;Nonetakes the cohort’s own value. Default: None- Raises:
ValueError – If it is not positive.
- Return type:
- set_evaluation_spacing_mm(evaluation_spacing_mm)[source]
Set the isotropic pitch every metric is measured on.
It sets both the voxel volume the Dice and volume figures are quantized to and the resolution of the deformation fields, whose memory grows with its cube.
- Parameters:
evaluation_spacing_mm (
Optional[float]) – Pitch in millimeters;Nonetakes the cohort’s own value. Default: None- Raises:
ValueError – If it is not positive.
- Return type:
- set_report_dice(report_dice)[source]
Report the Dice overlap.
Turn it off for a structure whose motion is small against its own size: Dice is an overlap fraction, so a lung lobe scores over 0.96 undeformed and the column says more about the organ’s bulk than about the motion. The volume and surface figures still resolve it.
- set_report_displacement_data(report_displacement_data)[source]
Write
displacement_per_point.csv.One row per mesh point per stage, carrying that point’s predicted and true displacement and the error between them.
- set_include_predicted_displacements(include_predicted_displacements)[source]
Carry
predicted_displacement_mmon every stage’s predicted surface.
- set_include_true_displacements(include_true_displacements)[source]
Carry
true_displacement_mmon every stage’s predicted surface.
- set_include_displacement_error(include_displacement_error)[source]
Measure and report the point-by-point displacement error.
Carries
displacement_error_mm, the distance between the predicted and the true position, as point data on every stage’s predicted surface, and reports that error’s RMS, 95th percentile and maximum — per structure on every metric row and in the report, and pooled over every point and stage in the report and the returned dict. It is the one metric here measured point by point, so a displacement predicted in the wrong direction cannot cancel against another. A shape-model point is attributed to the structure its own per-cellSegmentationLabelIdsnames, or, on a model carrying no such ids, to the structure whose reference-frame surface is nearest — the same nearest-label partition the labelmap metrics are already scored under.
- process(case_id, shape_parameters, fitted_reference_mesh, ground_truth, output_directory)[source]
Score every gated time point of one case.
The smoothing, grid, Dice and displacement options come from this workflow’s
set_*methods.- Parameters:
case_id (
str) – Name of the case being scored, recorded in every output.shape_parameters (
Path) – JSON file with the case’s PCA coefficient vector.fitted_reference_mesh (
Path) – The case’s fitted reference-frame SSM surface, as produced bymonai_physio.WorkflowFitStatisticalModelToPatient. The predicted displacements are added to its points, and its extent defines the evaluation grid.ground_truth (
MovementGroundTruth) – What this case is scored against — the acquired labelmap per stage, the reference frame’s labelmap, and the per-stage fits the point-by-point error is measured against — as assembled bymonai_physio.EvaluateMovementBase.assemble_ground_truth().output_directory (
Path) – Directory the report, the CSV and the per-stage geometry are written to.
- Return type:
- Returns:
Dict with
rows(every metric row),csv_file,report_file,volume_plot_file,predicted_surfaces,warped_labelmaps,displacement_data_file,displacement_statistics(one entry per stage, empty unlessinclude_displacement_error) and that error pooled over every point and stage asdisplacement_rms_mm,displacement_95th_mmanddisplacement_max_mm. The movement workflow’s smoothing sigma is set to this one’s for the call.- Raises:
ValueError – If
ground_truth.labelmapsis empty, any stage it carries a labelmap for has no entry inground_truth.meshes— checked whether or not an option needing the true displacement was requested — none of the requested labels are in the reference frame, or no label survives scoring because the acquired frames contain none of them.
- static dice(truth, predicted, label)[source]
Dice overlap of one label.
nanwhen neither volume contains it.- Return type:
- static volume_mm3(labels, label, voxel_volume_mm3)[source]
Volume of one label, in cubic millimeters.
- Return type:
- static surface_rmse_mm(truth, predicted)[source]
Symmetric point-to-surface RMSE, in millimeters.
Both directions are pooled before the root-mean-square. A one-sided RMSE misses a prediction that covers the truth everywhere but also bulges somewhere the truth does not reach.
- Return type:
- static pool_displacement_error(stage_errors)[source]
RMS, 95th percentile and maximum over every point of every stage.
The errors themselves are pooled rather than their per-stage summaries: a percentile of percentiles is not the percentile of the whole. Every value is
nanwhen no stage was scored point by point.
Ground truth and cohorts
- class monai_physio.MovementGroundTruth(labelmaps, reference_labelmap, reference_stage, meshes)[source]
Bases:
objectOne case’s acquired frames and the fits its prediction is scored against.
- labelmaps
Acquired labelmap per stage, keyed by the normalized stage in
[0, 1]. Every volume and overlap figure is measured against these.
- reference_labelmap
Labelmap of the frame every predicted deformation starts from, the anatomy carried into every other stage.
- reference_stage
Which stage that frame is.
- meshes
The case’s fitted surface per stage, keyed the same way and sharing the fitted reference mesh’s topology and point ordering. The acquired labelmaps carry no point correspondence, so these are the only source of a true per-point displacement.
- __init__(labelmaps, reference_labelmap, reference_stage, meshes)
- class monai_physio.EvaluateMovementBase(log_level=20)[source]
Bases:
MONAIPhysioBaseA cohort of subjects and the ground truth its movement is scored against.
Not instantiated directly – use
monai_physio.EvaluateMovementLungormonai_physio.EvaluateMovementDukeHeart. Subclasses set the class attributes below and implementstage_from_filename()andassemble_ground_truth();display_name()is an optional hook.- segmenter_class
Segmenter whose taxonomy names this cohort’s structures. Instantiated for its taxonomy alone, which downloads and loads nothing.
- label_ids
The structures to score, in report order.
- report_dice
Whether Dice belongs in this cohort’s report. Off for a structure whose motion is small against its own size: Dice is an overlap fraction, so a lung lobe scores over 0.96 undeformed.
- evaluation_spacing_mm
Isotropic pitch every metric is measured on.
- smoothing_sigma_mm
Gaussian sigma, in millimeters, that turns the network’s surface-shell deformation into a continuous field.
- __init__(log_level=20)[source]
Initialize the base class with logging configuration.
- Parameters:
class_name – Name for the class (used in log messages). If None, uses the class name. Default: None
log_level (
int|str) – Lowest level this object logs at. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).set_log_level()sets a floor for every object at once. Default: logging.INFOlog_to_file – Optional file path to write all MONAI Physio logs to as well; only the first object’s value is used. Default: None
- label_names()[source]
The structures this cohort scores,
{label id: report name}.Read from
segmenter_class’s taxonomy and passed throughdisplay_name(), so a cohort never restates names the segmenter already knows.- Raises:
NotImplementedError – On a cohort that names no segmenter.
- Return type:
- display_name(label_id, taxonomy_name)[source]
The report name of one structure. The base reports the taxonomy’s own.
Overridden by a cohort whose taxonomy name would mislead a reader of the report.
- Return type:
- stage_from_filename(path)[source]
The normalized stage in
[0, 1]this frame was acquired at.- Raises:
NotImplementedError – Implemented by subclasses.
- Return type:
- assemble_ground_truth(case_id, frame_directory, fit_directory, cache_directory=None)[source]
Gather one case’s acquired frames and its per-stage fits.
- Parameters:
case_id (
str) – The case being scored.frame_directory (
Path) – Where that case’s acquired frames live.fit_directory (
Path) – Where its per-stage*_ssm_surface.vtpfits live – Tutorial 8’s case directory, or one leave-one-out fold’s own fits, which is what makes a fold’s score honest.cache_directory (
Optional[Path]) – Where a cohort that has to derive its labelmaps writes them and reads them back. A cohort whose labelmaps ship with the data ignores it.
- Raises:
NotImplementedError – Implemented by subclasses.
- Return type:
- class monai_physio.EvaluateMovementLung(reference_phase='g070', log_level=20)[source]
Bases:
EvaluateMovementBaseThe five lung lobes, scored against per-phase segmentations of gated CT.
- Parameters:
- segmenter_class
alias of
SegmentNVSegmentCTMRI
- __init__(reference_phase='g070', log_level=20)[source]
Initialize the base class with logging configuration.
- Parameters:
class_name – Name for the class (used in log messages). If None, uses the class name. Default: None
log_level (
int|str) – Lowest level this object logs at. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).set_log_level()sets a floor for every object at once. Default: logging.INFOlog_to_file – Optional file path to write all MONAI Physio logs to as well; only the first object’s value is used. Default: None
- stage_from_filename(path)[source]
Read the normalized respiratory stage from a
g{PPP}filename stem.- Return type:
- assemble_ground_truth(case_id, frame_directory, fit_directory, cache_directory=None)[source]
Segment every gated frame of one case, then read its per-phase fits.
cache_directoryis required: a segmentation pass per phase is the expensive part of an evaluation, so it is written once and reused. A caller that has already produced those labelmaps under the same names – a leave-one-out study building a shared cache, say – gets them read straight back and pays nothing.- Raises:
ValueError – If
cache_directoryis not given.FileNotFoundError – If the case has no gated frames, no per-phase fits, or no frame at
reference_phase.
- Return type:
- class monai_physio.EvaluateMovementDukeHeart(log_level=20)[source]
Bases:
EvaluateMovementBaseThe heart chambers, scored against the labelmaps the cohort ships.
- segmenter_class
- labelmap_suffix = '_labelmap.nii.gz'
- phase_surface_pattern = '*_g[0-9][0-9][0-9]_*_ssm_surface.vtp'
- display_name(label_id, taxonomy_name)[source]
Report the taxonomy’s “heart” as “heart muscle”.
The taxonomy’s
heartis the whole heart minus its chamber cavities – the muscle the shape model represents – and a report that listed it beside four chambers under the bare name “heart” would read as if it were their sum.- Return type:
- stage_from_filename(path)[source]
Read the normalized cardiac stage from a
g{PPP}filename.Matched against the full name rather than the stem, since
.nii.gzis a double suffix thatPath.stemonly half removes.- Return type:
- assemble_ground_truth(case_id, frame_directory, fit_directory, cache_directory=None)[source]
Read one case’s gated labelmaps and its per-frame fits.
cache_directoryis ignored: these labelmaps are acquired, not derived, so there is nothing to cache.- Raises:
FileNotFoundError – If the case has no gated labelmaps, no frame marked
*_ref, or no per-frame fits.- Return type:
- class monai_physio.ReportEvaluateMovement(log_level=20)[source]
Bases:
MONAIPhysioBaseWrite the CSV, the volume plot and the markdown report of one evaluation.
- __init__(log_level=20)[source]
Initialize the base class with logging configuration.
- Parameters:
class_name – Name for the class (used in log messages). If None, uses the class name. Default: None
log_level (
int|str) – Lowest level this object logs at. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).set_log_level()sets a floor for every object at once. Default: logging.INFOlog_to_file – Optional file path to write all MONAI Physio logs to as well; only the first object’s value is used. Default: None
- report(rows, provenance, stages, smoothing_sigma_mm, evaluation_spacing_mm, displacement_statistics, pooled, output_directory)[source]
Write every artifact of one evaluation and return their paths.
- Parameters:
rows (
list[dict[str,Any]]) – One metric row per stage and structure, as scored bymonai_physio.WorkflowEvaluateMovement.process().provenance (
dict[str,Any]) – Case name, shape parameters and network weights.smoothing_sigma_mm (
float) – Recorded in the report’s run section.evaluation_spacing_mm (
float) – Recorded in the report’s run section.displacement_statistics (
list[dict[str,Any]]) – One entry per stage, empty when the point-by-point error was not measured.pooled (
dict[str,float]) – That error over every point and stage.output_directory (
Path) – Directory the artifacts are written to.
- Return type:
- Returns:
Dict with
csv_file,volume_plot_fileandreport_file.
Example
from monai_physio import (
MovementGroundTruth,
WorkflowEvaluateMovement,
WorkflowInferMovement,
WorkflowInferPhysicsNeMo,
)
evaluate = WorkflowEvaluateMovement(
movement_workflow=WorkflowInferMovement(
WorkflowInferPhysicsNeMo(model_directory=model_dir)
),
label_names={28: "lung_upper_lobe_left", 29: "lung_lower_lobe_left"},
)
ground_truth = MovementGroundTruth(
labelmaps={0.0: frame_00, 0.1: frame_10},
reference_labelmap=frame_00,
reference_stage=0.0,
meshes={0.0: fitted_mesh_00_file, 0.1: fitted_mesh_10_file},
)
result = evaluate.process(
case_id="103_HM10395",
shape_parameters=pca_coefficients_file,
fitted_reference_mesh=fitted_reference_mesh_file,
ground_truth=ground_truth,
output_directory=out_dir,
)
print(result["report_file"], result["csv_file"])
Notes
Why labelmaps rather than the model’s surface. The lung shape model carries its five lobes as per-cell labels, but the heart model is a single structure — the whole heart minus its chamber cavities — so its chambers exist only in the acquired labelmaps. Warping those labelmaps scores every structure the acquisition contains, whether or not the shape model represents it separately.
The evaluation grid. Everything is measured on one isotropic grid built around the reference anatomy, so a case whose gated frames carry different slice pitches is still scored on a single, stated voxel volume. Its pitch sets both that voxel volume and the memory the per-stage deformation fields take, which grows with its cube.