Utils API¶
Utility functions for visualization, compliance checking, and data processing.
utils ¶
Utilities for batch processing, multi-level analysis, and publication-quality plotting.
Functions¶
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
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
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 | |
quality_index ¶
quality_index(dose: Dose, structure: Structure, constraint_type: str, constraint_level: float) -> float
Compute the quality index of a dose distribution relative to a constraint.
Quality index interpretation: - Positive values: Constraint is met (higher is better, 1.0 is ideal) - Negative values: Constraint is violated (magnitude indicates severity)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dose
|
Dose
|
Dose distribution object |
required |
structure
|
Structure
|
Structure to evaluate |
required |
constraint_type
|
str
|
Type of constraint ('max', 'mean', or 'min') |
required |
constraint_level
|
float
|
Constraint value in Gy |
required |
Returns:
| Type | Description |
|---|---|
float
|
Quality index (-1 to 1) |
Examples:
>>> from dosemetrics.dose import Dose
>>> from dosemetrics.utils.compliance import quality_index
>>>
>>> dose = Dose.from_dicom("rtdose.dcm")
>>> brainstem = structures.get_structure("Brainstem")
>>>
>>> # Check max dose constraint
>>> qi = quality_index(dose, brainstem, "max", 54.0)
>>> if qi < 0:
... print("Constraint violated!")
Source code in src/dosemetrics/utils/compliance.py
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 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 | |
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.compute_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
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.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 = StructureSet.from_dicom('rtstruct.dcm')
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
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 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 | |
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
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 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 | |
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
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 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 | |
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
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)) -> 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 to analyze 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
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
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
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 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 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 | |
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
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 525 526 527 528 529 530 531 532 533 534 535 | |
plot_dose_slice ¶
plot_dose_slice(dose: Dose, slice_idx: Optional[int] = None, axis: int = 2, structures: Optional[StructureSet] = None, structure_names: Optional[List[str]] = None, vmin: Optional[float] = None, vmax: Optional[float] = None, cmap: str = 'viridis', 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 (default: middle slice) axis : int Axis to slice along (0=sagittal, 1=coronal, 2=axial) 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 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
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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 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 | |
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'])