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: MONAIPhysioBase

Score inferred motion per anatomical structure against acquired frames.

Parameters:
__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.INFO

  • log_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; None takes the cohort’s own value. Default: None

Raises:

ValueError – If it is not positive.

Return type:

None

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; None takes the cohort’s own value. Default: None

Raises:

ValueError – If it is not positive.

Return type:

None

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.

Parameters:

report_dice (Optional[bool]) – Whether to report it; None takes the cohort’s own value. Default: None

Return type:

None

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.

Parameters:

report_displacement_data (bool) – Whether to write it. Default: False

Return type:

None

set_include_predicted_displacements(include_predicted_displacements)[source]

Carry predicted_displacement_mm on every stage’s predicted surface.

Parameters:

include_predicted_displacements (bool) – Whether to. Default: False

Return type:

None

set_include_true_displacements(include_true_displacements)[source]

Carry true_displacement_mm on every stage’s predicted surface.

Parameters:

include_true_displacements (bool) – Whether to. Default: False

Return type:

None

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-cell SegmentationLabelIds names, 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.

Parameters:

include_displacement_error (bool) – Whether to. Default: False

Return type:

None

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 by monai_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 by monai_physio.EvaluateMovementBase.assemble_ground_truth().

  • output_directory (Path) – Directory the report, the CSV and the per-stage geometry are written to.

Return type:

dict[str, Any]

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 unless include_displacement_error) and that error pooled over every point and stage as displacement_rms_mm, displacement_95th_mm and displacement_max_mm. The movement workflow’s smoothing sigma is set to this one’s for the call.

Raises:

ValueError – If ground_truth.labelmaps is empty, any stage it carries a labelmap for has no entry in ground_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. nan when neither volume contains it.

Return type:

float

static volume_mm3(labels, label, voxel_volume_mm3)[source]

Volume of one label, in cubic millimeters.

Return type:

float

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:

float

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 nan when no stage was scored point by point.

Return type:

dict[str, float]

static displacement_error_row(case_id, stage, differences, errors)[source]

One stage’s displacement error, summarized over the mesh points.

Parameters:
  • case_id (str) – Case being scored.

  • stage (float) – Normalized stage.

  • differences (ndarray) – (n_points, 3) predicted minus true position.

  • errors (ndarray) – (n_points,) Euclidean norm of those differences, computed once by the caller rather than again here.

Return type:

dict

Ground truth and cohorts

class monai_physio.MovementGroundTruth(labelmaps, reference_labelmap, reference_stage, meshes)[source]

Bases: object

One 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: MONAIPhysioBase

A cohort of subjects and the ground truth its movement is scored against.

Not instantiated directly – use monai_physio.EvaluateMovementLung or monai_physio.EvaluateMovementDukeHeart. Subclasses set the class attributes below and implement stage_from_filename() and assemble_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.

Parameters:

log_level (int | str) – Logging level. Default: logging.INFO.

__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.INFO

  • log_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 through display_name(), so a cohort never restates names the segmenter already knows.

Raises:

NotImplementedError – On a cohort that names no segmenter.

Return type:

dict[int, str]

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:

str

stage_from_filename(path)[source]

The normalized stage in [0, 1] this frame was acquired at.

Raises:

NotImplementedError – Implemented by subclasses.

Return type:

float

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.vtp fits 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:

MovementGroundTruth

class monai_physio.EvaluateMovementLung(reference_phase='g070', log_level=20)[source]

Bases: EvaluateMovementBase

The five lung lobes, scored against per-phase segmentations of gated CT.

Parameters:
  • reference_phase (str) – The phase the shape model was fitted to, and therefore the one whose anatomy the predicted deformations carry into every other phase. Default: "g070".

  • log_level (int | str) – Logging level. Default: logging.INFO.

segmenter_class

alias of SegmentNVSegmentCTMRI

label_ids: tuple[int, ...] = (28, 29, 30, 31, 32)
report_dice: bool = False
evaluation_spacing_mm: float = 2.0
__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.INFO

  • log_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:

float

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_directory is 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_directory is not given.

  • FileNotFoundError – If the case has no gated frames, no per-phase fits, or no frame at reference_phase.

Return type:

MovementGroundTruth

class monai_physio.EvaluateMovementDukeHeart(log_level=20)[source]

Bases: EvaluateMovementBase

The heart chambers, scored against the labelmaps the cohort ships.

Parameters:

log_level (int | str) – Logging level. Default: logging.INFO.

segmenter_class

alias of SegmentHeartSimplewareTrimmedBranches

label_ids: tuple[int, ...] = (1, 2, 3, 4, 5, 6)
report_dice: bool = True
evaluation_spacing_mm: float = 1.0
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 heart is 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:

str

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.gz is a double suffix that Path.stem only half removes.

Return type:

float

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_directory is 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:

MovementGroundTruth

class monai_physio.ReportEvaluateMovement(log_level=20)[source]

Bases: MONAIPhysioBase

Write the CSV, the volume plot and the markdown report of one evaluation.

Parameters:

log_level (int | str) – Logging level. Default: logging.INFO.

__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.INFO

  • log_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 by monai_physio.WorkflowEvaluateMovement.process().

  • provenance (dict[str, Any]) – Case name, shape parameters and network weights.

  • stages (list[float]) – Every stage scored, in order.

  • 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:

dict[str, Path]

Returns:

Dict with csv_file, volume_plot_file and report_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.

See Also