Utilities API¶
The public utility package is organized into five implementation modules.
Functions exported from dosemetrics.utils are defined by
dosemetrics.utils.__all__; module-level reference below also documents
specialized helpers that are intentionally accessed through their module.
compliance¶
compliance ¶
Compliance checking for dose constraints.
Functions:¶
parse_dose_at_volume_cc ¶
Return the volume in cc if this is a D_Xcc constraint, else None.
:param constraint_type: Candidate constraint type, e.g. "D0.03cc".
Examples:
Source code in src/dosemetrics/utils/compliance.py
get_custom_constraints ¶
GET_CUSTOM_CONSTRAINTS: Get custom constraints for common structures. :return: DataFrame with custom constraints for common structures.
Source code in src/dosemetrics/utils/compliance.py
get_default_constraints ¶
GET_DEFAULT_CONSTRAINTS: Get default constraints for common structures. :return: DataFrame with default constraints for common structures.
Source code in src/dosemetrics/utils/compliance.py
constraint_metric ¶
Return the dose statistic a constraint type is evaluated against.
:param constraint_type: One of "max", "min", "mean" or "nmean". :return: Column name in a dose statistics table, e.g. "Max Dose". :raises ValueError: If the constraint type is not supported.
Source code in src/dosemetrics/utils/compliance.py
evaluate_constraint ¶
Evaluate a single dose value against a single constraint.
This is the scalar kernel behind :func:check_compliance. It is exposed
separately so that callers evaluating many hypothetical values against one
constraint -- for example a family of DVH curves derived from contour
variations -- do not have to re-implement the constraint semantics.
:param value: Dose statistic to test (Gy), e.g. a max or mean dose. :param constraint_type: One of "max", "min", "mean" or "nmean". :param level: Constraint level in Gy. :return: Tuple of (is_compliant, human-readable reason). :raises ValueError: If the constraint type is not supported.
Examples:
>>> evaluate_constraint(60.0, "max", 54.0)[0]
False
>>> evaluate_constraint(45.0, "max", 54.0)[0]
True
Source code in src/dosemetrics/utils/compliance.py
check_compliance ¶
CHECK_COMPLIANCE: Check compliance of dose metrics with constraints. :param df: DataFrame with dose metrics including columns for max-dose, mean-dose, ... :param constraint: DataFrame constructed using get_default_constraints(). :return: DataFrame with compliance status and failure reason for each structure.
Source code in src/dosemetrics/utils/compliance.py
batch¶
batch ¶
Batch processing utilities for dosemetrics.
This module provides high-level functions for processing multiple subjects, datasets, and performing batch dosimetric analysis across entire cohorts.
Classes¶
Functions:¶
load_dataset ¶
load_dataset(root_path: Union[str, Path], subject_pattern: str = '*', dose_pattern: str = 'dose*', structures_pattern: str = '*.nii.gz', auto_detect: bool = True) -> Dict[str, Dict[str, Union[Dose, StructureSet]]]
Load an entire dataset with multiple subjects.
Automatically detects folder structure and loads all doses and structure sets. Supports both DICOM and NIfTI formats with automatic detection.
Parameters¶
root_path : str or Path Root directory containing subject folders subject_pattern : str Glob pattern for subject folder names (default: "*") dose_pattern : str Pattern to identify dose files/folders structures_pattern : str Pattern to identify structure files auto_detect : bool Automatically detect DICOM vs NIfTI format
Returns¶
dataset : Dict[str, Dict[str, Union[Dose, StructureSet]]] Nested dictionary: {subject_id: {'dose': Dose, 'structures': StructureSet}}
Examples¶
dataset = load_dataset('/data/clinical_study') for subject_id, data in dataset.items(): ... dose = data['dose'] ... structures = data['structures'] ... print(f"Subject {subject_id}: {len(structures)} structures")
Source code in src/dosemetrics/utils/batch.py
load_multiple_doses ¶
load_multiple_doses(folder_paths: List[Union[str, Path]], dose_names: Optional[List[str]] = None) -> Dict[str, Dose]
Load multiple dose distributions from different folders.
Useful for comparing different treatment plans (e.g., TPS vs predicted).
Parameters¶
folder_paths : List[str or Path] List of folders, each containing a dose distribution dose_names : List[str], optional Names for each dose (default: uses folder names)
Returns¶
doses : Dict[str, Dose] Dictionary mapping dose names to Dose objects
Examples¶
doses = load_multiple_doses([ ... '/data/subject01/tps', ... '/data/subject01/predicted' ... ], dose_names=['TPS', 'Predicted'])
Source code in src/dosemetrics/utils/batch.py
process_dataset_with_metric ¶
process_dataset_with_metric(dataset: Dict[str, Dict[str, Union[Dose, StructureSet]]], metric_func: Callable, structure_names: Optional[List[str]] = None, **metric_kwargs) -> pd.DataFrame
Apply a metric function across an entire dataset.
Computes metrics for all subjects and all structures, returning results in a structured DataFrame.
Parameters¶
dataset : Dict Dataset dictionary from load_dataset() metric_func : Callable Metric function that takes (dose, structure) and returns a value or dict structure_names : List[str], optional Specific structures to analyze (default: all structures) **metric_kwargs Additional keyword arguments passed to metric_func
Returns¶
results : pd.DataFrame DataFrame with columns: subject_id, structure_name, metric values
Examples¶
from dosemetrics.metrics import dvh dataset = load_dataset('/data/study') results = process_dataset_with_metric( ... dataset, ... dvh.compute_mean_dose, ... structure_names=['PTV', 'Heart'] ... )
Source code in src/dosemetrics/utils/batch.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
batch_compute_dvh ¶
batch_compute_dvh(dataset: Dict[str, Dict[str, Union[Dose, StructureSet]]], structure_names: Optional[List[str]] = None, max_dose: Optional[float] = None, step_size: float = 0.1) -> Dict[str, Dict[str, Tuple[np.ndarray, np.ndarray]]]
Compute DVHs for all subjects and structures in a dataset.
Parameters¶
dataset : Dict Dataset dictionary from load_dataset() structure_names : List[str], optional Specific structures to analyze max_dose : float, optional Maximum dose for DVH bins step_size : float DVH bin width in Gy
Returns¶
dvhs : Dict[str, Dict[str, Tuple]] Nested dict: {subject_id: {structure_name: (dose_bins, volumes)}}
Examples¶
from dosemetrics.utils import batch dataset = batch.load_dataset('/data/study') dvhs = batch.batch_compute_dvh(dataset, structure_names=['PTV', 'Heart'])
Source code in src/dosemetrics/utils/batch.py
compare_doses_batch ¶
compare_doses_batch(dataset1: Dict[str, Dict[str, Union[Dose, StructureSet]]], dataset2: Dict[str, Dict[str, Union[Dose, StructureSet]]], comparison_func: Callable, structure_names: Optional[List[str]] = None, **kwargs) -> pd.DataFrame
Compare two datasets (e.g., TPS vs predicted doses).
Parameters¶
dataset1, dataset2 : Dict Dataset dictionaries to compare comparison_func : Callable Function that takes (dose1, dose2, structure) and returns metrics structure_names : List[str], optional Specific structures to compare **kwargs Additional arguments for comparison_func
Returns¶
comparison : pd.DataFrame Comparison results for all subjects and structures
Examples¶
from dosemetrics.metrics import dose_comparison tps_data = load_dataset('/data/tps') pred_data = load_dataset('/data/predicted') comparison = compare_doses_batch( ... tps_data, pred_data, ... dose_comparison.compare_mae ... )
Source code in src/dosemetrics/utils/batch.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | |
aggregate_results ¶
aggregate_results(results: DataFrame, group_by: Union[str, List[str]] = 'structure', agg_funcs: Optional[Dict[str, Union[str, List[str]]]] = None) -> pd.DataFrame
Aggregate batch processing results.
Compute summary statistics across subjects, structures, or other groupings.
Parameters¶
results : pd.DataFrame Results from process_dataset_with_metric or similar group_by : str or List[str] Column(s) to group by (e.g., 'structure', 'subject_id') agg_funcs : Dict, optional Aggregation functions for each column Default: {'value': ['mean', 'std', 'min', 'max']}
Returns¶
summary : pd.DataFrame Aggregated statistics
Examples¶
results = process_dataset_with_metric(dataset, compute_mean_dose) summary = aggregate_results(results, group_by='structure') print(summary) # Mean dose statistics per structure
Source code in src/dosemetrics/utils/batch.py
export_batch_results ¶
export_batch_results(results: DataFrame, output_path: Union[str, Path], format: str = 'csv', **kwargs) -> None
Export batch processing results to file.
Parameters¶
results : pd.DataFrame Results dataframe to export output_path : str or Path Output file path format : str Output format: 'csv', 'excel', 'json', 'parquet' **kwargs Additional arguments for the export function
Examples¶
results = process_dataset_with_metric(dataset, compute_mean_dose) export_batch_results(results, 'results/mean_dose.csv')
Source code in src/dosemetrics/utils/batch.py
analysis¶
analysis ¶
Multi-level analysis utilities for dosemetrics.
This module provides functions to analyze dosimetric data at different levels:
- By structure: Analyze a single structure across subjects
- By subject: Analyze all structures for a single subject
- By dataset: Analyze entire cohorts with summary statistics
- By subset: Filter and analyze specific groups
Classes¶
Functions:¶
dose_statistics_table ¶
dose_statistics_table(dose: Dose, structures: StructureSet, structure_names: Optional[List[str]] = None) -> pd.DataFrame
Return common dose statistics for several structures.
The result is ready for display or CSV export and avoids repeating the same metric loop in interactive analyses.
Source code in src/dosemetrics/utils/analysis.py
compare_dose_statistics ¶
compare_dose_statistics(reference_dose: Dose, evaluated_dose: Dose, reference_structures: StructureSet, evaluated_structures: Optional[StructureSet] = None, structure_names: Optional[List[str]] = None, labels: Tuple[str, str] = ('Reference', 'Evaluated')) -> pd.DataFrame
Compare common dose statistics between two aligned studies.
Source code in src/dosemetrics/utils/analysis.py
compare_structure_geometry ¶
compare_structure_geometry(reference_structures: StructureSet, evaluated_structures: StructureSet, structure_names: Optional[List[str]] = None) -> pd.DataFrame
Compare overlap and volume for structures with matching names.
Source code in src/dosemetrics/utils/analysis.py
analyze_by_structure ¶
analyze_by_structure(dataset: Dict[str, Dict[str, Union[Dose, StructureSet]]], structure_name: str, metrics: Dict[str, callable]) -> pd.DataFrame
Analyze a single structure across all subjects.
Computes specified metrics for one structure across the entire dataset, useful for population-level structure analysis (e.g., PTV coverage across cohort).
Parameters¶
dataset : Dict Dataset dictionary from batch.load_dataset() structure_name : str Name of structure to analyze metrics : Dict[str, callable] Dictionary of {metric_name: metric_function} Each function should take (dose, structure) and return a value
Returns¶
results : pd.DataFrame DataFrame with subject_id and computed metrics
Examples¶
from dosemetrics.metrics import dvh from dosemetrics.io import load_structure_set from dosemetrics.utils import analysis
metrics = { ... 'mean_dose': dvh.compute_mean_dose, ... 'max_dose': dvh.compute_max_dose, ... 'D95': lambda d, s: dvh.compute_dose_at_volume(d, s, 95) ... } results = analysis.analyze_by_structure(dataset, 'PTV', metrics) print(results.describe()) # Summary statistics for PTV across subjects
Source code in src/dosemetrics/utils/analysis.py
analyze_by_subject ¶
analyze_by_subject(dose: Dose, structures: StructureSet, metrics: Dict[str, callable], structure_names: Optional[List[str]] = None) -> pd.DataFrame
Analyze all structures for a single subject.
Computes metrics for all (or selected) structures in a single subject's dataset.
Parameters¶
dose : Dose Subject's dose distribution structures : StructureSet Subject's structure set metrics : Dict[str, callable] Dictionary of {metric_name: metric_function} structure_names : List[str], optional Specific structures to analyze (default: all)
Returns¶
results : pd.DataFrame DataFrame with structure names and computed metrics
Examples¶
from dosemetrics.metrics import dvh from dosemetrics.utils import analysis
dose = Dose.from_dicom('rtdose.dcm') structures = load_structure_set('dicom-folder', format='dicom')
metrics = { ... 'mean_dose': dvh.compute_mean_dose, ... 'V20': lambda d, s: dvh.compute_volume_at_dose(d, s, 20) ... } results = analysis.analyze_by_subject(dose, structures, metrics)
Source code in src/dosemetrics/utils/analysis.py
analyze_by_dataset ¶
analyze_by_dataset(dataset: Dict[str, Dict[str, Union[Dose, StructureSet]]], metrics: Dict[str, callable], structure_names: Optional[List[str]] = None, summary_stats: bool = True) -> Union[pd.DataFrame, Tuple[pd.DataFrame, pd.DataFrame]]
Analyze entire dataset with population-level statistics.
Computes metrics across all subjects and structures, with optional summary statistics grouped by structure.
Parameters¶
dataset : Dict Dataset dictionary metrics : Dict[str, callable] Metrics to compute structure_names : List[str], optional Specific structures to analyze summary_stats : bool If True, return both detailed and summary dataframes
Returns¶
results : pd.DataFrame or Tuple[pd.DataFrame, pd.DataFrame] If summary_stats=False: detailed results If summary_stats=True: (detailed_results, summary_stats)
Examples¶
from dosemetrics.metrics import dvh from dosemetrics.utils import analysis
metrics = { ... 'mean_dose': dvh.compute_mean_dose, ... 'D95': lambda d, s: dvh.compute_dose_at_volume(d, s, 95) ... } detailed, summary = analysis.analyze_by_dataset( ... dataset, metrics, structure_names=['PTV', 'Heart', 'Lung_L'] ... ) print(summary) # Mean ± std for each metric per structure
Source code in src/dosemetrics/utils/analysis.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
analyze_subset ¶
analyze_subset(dataset: Dict[str, Dict[str, Union[Dose, StructureSet]]], metrics: Dict[str, callable], subject_filter: Optional[callable] = None, structure_filter: Optional[callable] = None, **filter_kwargs) -> pd.DataFrame
Analyze a filtered subset of the dataset.
Apply custom filters to subjects and/or structures before analysis.
Parameters¶
dataset : Dict Dataset dictionary metrics : Dict[str, callable] Metrics to compute subject_filter : callable, optional Function that takes (subject_id, data) and returns bool structure_filter : callable, optional Function that takes (structure) and returns bool **filter_kwargs Additional filter parameters
Returns¶
results : pd.DataFrame Analysis results for filtered subset
Examples¶
Analyze only target structures¶
def target_only(structure): ... return structure.structure_type == StructureType.TARGET
results = analysis.analyze_subset( ... dataset, ... metrics={'mean_dose': compute_mean_dose}, ... structure_filter=target_only ... )
Source code in src/dosemetrics/utils/analysis.py
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
compute_cohort_statistics ¶
compute_cohort_statistics(results: DataFrame, metric_cols: Optional[List[str]] = None, group_by: str = 'structure') -> pd.DataFrame
Compute cohort-level summary statistics.
Parameters¶
results : pd.DataFrame Results from analyze_by_dataset or similar metric_cols : List[str], optional Columns to summarize (default: all numeric) group_by : str Column to group by (default: 'structure')
Returns¶
statistics : pd.DataFrame Summary statistics (mean, std, CI, etc.)
Examples¶
results = analyze_by_dataset(dataset, metrics) stats = compute_cohort_statistics(results[0]) print(stats) # Population statistics per structure
Source code in src/dosemetrics/utils/analysis.py
compare_cohorts ¶
compare_cohorts(results1: DataFrame, results2: DataFrame, metric_cols: Optional[List[str]] = None, cohort_names: Tuple[str, str] = ('Cohort1', 'Cohort2')) -> pd.DataFrame
Compare two cohorts statistically.
Performs t-tests and computes effect sizes between two groups.
Parameters¶
results1, results2 : pd.DataFrame Results from two different cohorts metric_cols : List[str], optional Metrics to compare cohort_names : Tuple[str, str] Names for the cohorts
Returns¶
comparison : pd.DataFrame Statistical comparison results
Examples¶
pre_treatment = analyze_by_dataset(pre_data, metrics) post_treatment = analyze_by_dataset(post_data, metrics) comparison = compare_cohorts( ... pre_treatment[0], post_treatment[0], ... cohort_names=('Pre', 'Post') ... )
Source code in src/dosemetrics/utils/analysis.py
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | |
plot¶
plot ¶
Publication-quality plotting utilities for dosemetrics.
This module provides functions for creating publication-ready plots at different levels: - Structure-level: Plot data for individual structures (DVH, metrics box plots) - Subject-level: Plot all structures for one subject - Dataset-level: Population-level plots (DVH bands, violin plots, comparisons)
Classes¶
Functions:¶
plot_dvh ¶
plot_dvh(dose: Dose, structure: Structure, bins: int = 1000, relative_volume: bool = True, ax: Optional[Axes] = None, label: Optional[str] = None, color: Optional[str] = None, **plot_kwargs) -> plt.Axes
Plot dose-volume histogram for a single structure.
Parameters¶
dose : Dose Dose distribution structure : Structure Structure to plot DVH for bins : int Number of bins for DVH computation relative_volume : bool If True, plot relative volume (%), else absolute volume (cc) ax : plt.Axes, optional Axis to plot on (creates new if None) label : str, optional Label for the curve (default: structure name) color : str, optional Color for the curve **plot_kwargs Additional arguments passed to plt.plot()
Returns¶
ax : plt.Axes The plot axis
Examples¶
import matplotlib.pyplot as plt from dosemetrics.utils import plot
fig, ax = plt.subplots() plot.plot_dvh(dose, ptv, ax=ax, label='PTV', color='red') plot.plot_dvh(dose, heart, ax=ax, label='Heart', color='blue') plt.legend() plt.show()
Source code in src/dosemetrics/utils/plot.py
plot_subject_dvhs ¶
plot_subject_dvhs(dose: Dose, structures: StructureSet, structure_names: Optional[List[str]] = None, bins: int = 1000, relative_volume: bool = True, color_by_type: bool = True, figsize: Tuple[float, float] = (10, 7)) -> Tuple[plt.Figure, plt.Axes]
Plot DVHs for all structures of a subject.
Parameters¶
dose : Dose Dose distribution structures : StructureSet Structure set structure_names : List[str], optional Specific structures to plot (default: all) bins : int Number of bins relative_volume : bool Plot relative vs absolute volume color_by_type : bool Use different colors for targets vs OARs figsize : Tuple[float, float] Figure size
Returns¶
fig, ax : Figure and Axes
Examples¶
from dosemetrics.utils import plot fig, ax = plot.plot_subject_dvhs(dose, structures) plt.savefig('subject_dvhs.png', dpi=300, bbox_inches='tight')
Source code in src/dosemetrics/utils/plot.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
plot_dvh_comparison ¶
plot_dvh_comparison(dose1: Dose, dose2: Dose, structure: Structure, labels: Tuple[str, str] = ('Dose 1', 'Dose 2'), bins: int = 1000, relative_volume: bool = True, figsize: Tuple[float, float] = (8, 6), evaluated_structure: Optional[Structure] = None) -> Tuple[plt.Figure, plt.Axes]
Compare DVHs from two different dose distributions.
Useful for comparing TPS vs predicted, or different treatment plans.
Parameters¶
dose1, dose2 : Dose
Dose distributions to compare
structure : Structure
Structure on the first dose grid
labels : Tuple[str, str]
Labels for the two doses
bins : int
Number of bins
relative_volume : bool
Plot relative vs absolute volume
figsize : Tuple[float, float]
Figure size
evaluated_structure : Structure, optional
Corresponding structure on the second dose grid. Defaults to
structure when both doses share the same grid.
Returns¶
fig, ax : Figure and Axes
Examples¶
fig, ax = plot.plot_dvh_comparison( ... tps_dose, pred_dose, ptv, ... labels=('TPS', 'Predicted') ... )
Source code in src/dosemetrics/utils/plot.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
plot_dvh_band ¶
plot_dvh_band(dataset: Dict[str, Dict[str, Union[Dose, StructureSet]]], structure_name: str, bins: int = 1000, relative_volume: bool = True, percentiles: Tuple[float, float] = (25, 75), show_median: bool = True, show_individual: bool = False, ax: Optional[Axes] = None, color: Optional[str] = None, label: Optional[str] = None) -> plt.Axes
Plot DVH band showing population statistics.
Creates a band plot showing median and interquartile range across multiple subjects for a single structure.
Parameters¶
dataset : Dict Dataset dictionary from batch.load_dataset() structure_name : str Structure to plot bins : int Number of bins relative_volume : bool Plot relative vs absolute volume percentiles : Tuple[float, float] Lower and upper percentiles for band show_median : bool Whether to show median curve show_individual : bool Whether to show individual DVHs with transparency ax : plt.Axes, optional Axis to plot on color : str, optional Color for the band label : str, optional Label for the legend
Returns¶
ax : plt.Axes
Examples¶
fig, ax = plt.subplots() plot.plot_dvh_band(dataset, 'PTV', ax=ax, color='red', label='PTV') plot.plot_dvh_band(dataset, 'Heart', ax=ax, color='blue', label='Heart') plt.legend()
Source code in src/dosemetrics/utils/plot.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
plot_dvh_band_from_curves ¶
plot_dvh_band_from_curves(dose_bins: ndarray, dvh_curves: ndarray, relative_volume: bool = True, percentiles: Tuple[float, float] = (25, 75), show_median: bool = True, show_individual: bool = False, show_envelope: bool = False, ax: Optional[Axes] = None, color: Optional[str] = None, label: Optional[str] = None, band_label: Optional[str] = None, median_label: Optional[str] = None) -> plt.Axes
Plot a DVH band from an already-computed ensemble of DVH curves.
This is the plotting primitive behind :func:plot_dvh_band. It takes the
curves directly rather than a dataset, so it can be reused for any ensemble
of DVHs sharing one dose axis -- across subjects, across plans, or across a
family of contour variations of a single structure.
Parameters¶
dose_bins : np.ndarray Shared dose axis of shape (n_bins,), in Gy. dvh_curves : np.ndarray Ensemble of shape (n_curves, n_bins). Volume in % or cc. relative_volume : bool Label and scale the y axis as relative volume (%) rather than cc. percentiles : Tuple[float, float] Lower and upper percentiles bounding the shaded band. show_median : bool Whether to draw the median curve. show_individual : bool Whether to draw every member curve faintly behind the band. show_envelope : bool Whether to outline the full min/max envelope of the ensemble. ax : plt.Axes, optional Axis to plot on color : str, optional Color for the band label : str, optional Base name used for legend entries when band/median labels are omitted. band_label : str, optional Explicit legend label for the shaded band. median_label : str, optional Explicit legend label for the median curve.
Returns¶
ax : plt.Axes
Examples¶
bins = np.linspace(0, 60, 601) curves = np.array([100 * np.exp(-bins / s) for s in (18, 20, 22)]) ax = plot_dvh_band_from_curves(bins, curves, label="BrainStem")
Source code in src/dosemetrics/utils/plot.py
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
plot_metric_boxplot ¶
plot_metric_boxplot(results: DataFrame, metric: str, group_by: str = 'structure', figsize: Tuple[float, float] = (10, 6), show_points: bool = True, horizontal: bool = False) -> Tuple[plt.Figure, plt.Axes]
Create box plot for a metric across structures or subjects.
Parameters¶
results : pd.DataFrame Results from analysis functions metric : str Metric column to plot group_by : str Column to group by ('structure' or 'subject_id') figsize : Tuple[float, float] Figure size show_points : bool Whether to show individual data points horizontal : bool Whether to make horizontal box plot
Returns¶
fig, ax : Figure and Axes
Examples¶
from dosemetrics.utils import analysis, plot results = analysis.analyze_by_dataset(dataset, metrics) fig, ax = plot.plot_metric_boxplot(results[0], 'mean_dose')
Source code in src/dosemetrics/utils/plot.py
plot_metric_comparison ¶
plot_metric_comparison(results1: DataFrame, results2: DataFrame, metric: str, cohort_names: Tuple[str, str] = ('Cohort 1', 'Cohort 2'), structure_names: Optional[List[str]] = None, figsize: Tuple[float, float] = (12, 6)) -> Tuple[plt.Figure, plt.Axes]
Compare a metric between two cohorts.
Creates side-by-side box plots for comparison.
Parameters¶
results1, results2 : pd.DataFrame Results from two cohorts metric : str Metric to compare cohort_names : Tuple[str, str] Names for the cohorts structure_names : List[str], optional Specific structures to include figsize : Tuple[float, float] Figure size
Returns¶
fig, ax : Figure and Axes
Examples¶
fig, ax = plot.plot_metric_comparison( ... pre_results, post_results, 'mean_dose', ... cohort_names=('Pre-treatment', 'Post-treatment') ... )
Source code in src/dosemetrics/utils/plot.py
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 | |
plot_dose_slice ¶
plot_dose_slice(dose: Dose, slice_idx: Optional[int] = None, axis: int = 0, structures: Optional[StructureSet] = None, structure_names: Optional[List[str]] = None, vmin: Optional[float] = None, vmax: Optional[float] = None, cmap: str = 'viridis', background: Optional[ndarray] = None, background_window: Optional[Tuple[float, float]] = None, min_dose: Optional[float] = None, prescription_dose: Optional[float] = None, contour_colors: Optional[Mapping[str, str]] = None, alpha: float = 0.82, show_colorbar: bool = True, figsize: Tuple[float, float] = (10, 8)) -> Tuple[plt.Figure, plt.Axes]
Plot a 2D slice of dose distribution with optional structure contours.
Parameters¶
dose : Dose Dose distribution slice_idx : int, optional Slice index. By default, use the slice with the largest cross-section of the first selected structure, or the middle slice without structures. axis : int Array axis to slice along (default: 0, axial for dosemetrics arrays) structures : StructureSet, optional Structures to overlay structure_names : List[str], optional Specific structures to show vmin, vmax : float, optional Dose value range for colormap cmap : str Colormap name background : np.ndarray, optional Image volume to draw beneath the dose colorwash background_window : Tuple[float, float], optional Lower and upper display limits for the background image min_dose : float, optional Hide dose values below this threshold. Defaults to 5% of maximum dose when a background is supplied and zero otherwise. prescription_dose : float, optional Draw this isodose as a magenta contour contour_colors : Mapping[str, str], optional Per-structure contour colors alpha : float Dose colorwash opacity when a background is supplied show_colorbar : bool Whether to show colorbar figsize : Tuple[float, float] Figure size
Returns¶
fig, ax : Figure and Axes
Examples¶
fig, ax = plot.plot_dose_slice( ... dose, structures=structures, ... structure_names=['PTV', 'Heart'] ... )
Source code in src/dosemetrics/utils/plot.py
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 | |
plot_metric_values ¶
plot_metric_values(values: Mapping[str, float], title: str = 'Metric values', ylabel: str = 'Value', ylim: Optional[Tuple[float, float]] = None, horizontal: bool = False, figsize: Tuple[float, float] = (9, 5)) -> Tuple[plt.Figure, plt.Axes]
Plot a small mapping of scalar metric names to values.
This convenience function keeps routine metric visualization free of notebook-specific pandas and Matplotlib setup.
Source code in src/dosemetrics/utils/plot.py
plot_dose_difference ¶
plot_dose_difference(reference: Dose, evaluated: Dose, structures: Optional[StructureSet] = None, structure_names: Optional[List[str]] = None, slice_idx: Optional[int] = None, axis: int = 0, percentile: float = 99.0, figsize: Tuple[float, float] = (9, 7)) -> Tuple[plt.Figure, plt.Axes]
Plot an evaluated-minus-reference dose slice on a symmetric scale.
Source code in src/dosemetrics/utils/plot.py
save_figure ¶
save_figure(fig: Figure, filepath: Union[str, Path], dpi: int = 300, formats: List[str] = ['png'], **savefig_kwargs) -> None
Save figure in multiple formats with publication-quality settings.
Parameters¶
fig : plt.Figure Figure to save filepath : str or Path Output path (without extension) dpi : int Resolution for raster formats formats : List[str] Formats to save (e.g., ['png', 'pdf', 'svg']) **savefig_kwargs Additional arguments for fig.savefig()
Examples¶
fig, ax = plot.plot_dvh(dose, structure) plot.save_figure(fig, 'figures/ptv_dvh', formats=['png', 'pdf'])
Source code in src/dosemetrics/utils/plot.py
plot_dvh_score_breakdown ¶
plot_dvh_score_breakdown(dose_reference: Dose, dose_evaluated: Dose, structure: Structure, labels: Tuple[str, str] = ('Reference', 'Evaluated'), bins: int = 500, figsize: Tuple[float, float] = (9, 6)) -> Tuple[plt.Figure, plt.Axes]
Plot DVH comparison with D1, D95, and D99 markers for both distributions.
Visualises the DVH Score metric by overlaying the three key dose points (D1, D95, D99) on paired DVH curves, making it easy to identify where the distributions diverge clinically.
Parameters¶
dose_reference : Dose Reference dose distribution. dose_evaluated : Dose Evaluated (e.g., predicted) dose distribution. structure : Structure Structure to restrict DVH computation to. labels : Tuple[str, str] Display labels for reference and evaluated curves. bins : int Number of dose bins for DVH computation. figsize : Tuple[float, float] Figure size.
Returns¶
fig, ax : Figure and Axes
Examples¶
fig, ax = plot.plot_dvh_score_breakdown( ... tps_dose, predicted_dose, ptv, ... labels=('TPS', 'Predicted') ... ) plt.show()
Source code in src/dosemetrics/utils/plot.py
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 | |
plot_dvh_auc ¶
plot_dvh_auc(dose: Dose, structure: Structure, bins: int = 500, normalize: bool = True, ax: Optional[Axes] = None, color: Optional[str] = None, label: Optional[str] = None, figsize: Tuple[float, float] = (8, 6)) -> plt.Axes
Plot DVH with the area under the curve filled and the AUC annotated.
Parameters¶
dose : Dose Dose distribution. structure : Structure Structure for DVH computation. bins : int Number of dose bins. normalize : bool If True, normalise AUC to [0, 1]. ax : matplotlib.axes.Axes, optional Axes to plot on. Creates new figure if None. color : str, optional Fill and line colour (defaults to target red). label : str, optional Curve label (defaults to structure name). figsize : Tuple[float, float] Figure size when creating a new figure.
Returns¶
ax : matplotlib.axes.Axes
Examples¶
ax = plot.plot_dvh_auc(dose, ptv) plt.show()
Source code in src/dosemetrics/utils/plot.py
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 | |
data¶
data ¶
Small data-loading workflows used in tutorials and interactive analyses.
Classes¶
Functions:¶
download_example_data ¶
Download the public example dataset and return a cached local path.
Parameters¶
relative_path : str or Path, optional
A path inside the dataset, such as "test_subject".
Source code in src/dosemetrics/utils/data.py
load_example_study ¶
load_example_study(relative_path: Union[str, Path] = 'test_subject', dose_filename: str = 'Dose.nii.gz') -> Tuple[Dose, StructureSet]
Load an aligned NIfTI dose and structure set from the example dataset.
Source code in src/dosemetrics/utils/data.py
load_dicom_study ¶
load_dicom_study(directory: Union[str, Path], dose_file: Optional[Union[str, Path]] = None) -> Tuple[Dose, StructureSet]
Load RTDOSE and rasterize RTSTRUCT contours on its native dose grid.
This high-level loader ensures that every returned structure is directly compatible with the returned dose distribution.
Source code in src/dosemetrics/utils/data.py
load_dicom_ct_on_dose_grid ¶
Load a DICOM CT series and resample it onto a dose grid for display.