Visualization Module¶
Publication-quality figure generation for Foundation PLR.
Overview¶
The viz module provides Python-based visualization functions for generating figures. For R-based figures, see src/r/.
Computation vs Visualization
The viz module only visualizes data from DuckDB. All metric computation happens during extraction (see scripts/extract_all_configs_to_duckdb.py).
Key Modules¶
| Module | Description |
|---|---|
plot_config |
Style setup, colors, save functions |
calibration_plot |
STRATOS calibration curves |
dca_plot |
Decision curve analysis |
cd_diagram |
Critical difference diagrams |
factorial_matrix |
Factorial design heatmaps |
featurization_comparison |
Handcrafted vs embeddings |
API Reference¶
plot_config
¶
Plot Configuration for Foundation PLR Figures
Style: Neue Haas Grotesk / Helvetica Neue inspired typography Clean, professional academic visualization aesthetic
Usage: from src.viz.plot_config import setup_style, save_figure, COLORS setup_style() # Call before creating figures
AIDEV-NOTE: This module provides styling and export functionality.¶
All viz modules should call setup_style() before creating figures.¶
COLORS
module-attribute
¶
COLORS = {
"primary": "#2E5090",
"secondary": "#D64045",
"tertiary": "#45B29D",
"quaternary": "#F5A623",
"quinary": "#7B68EE",
"positive": "#45B29D",
"negative": "#D64045",
"neutral": "#4A4A4A",
"reference": "#D64045",
"background": "#FAFAFA",
"grid": "#E0E0E0",
"moment": "#2E5090",
"units": "#45B29D",
"traditional": "#7B68EE",
"ensemble": "#F5A623",
"ground_truth": "#666666",
"foundation_model": "#0072B2",
"deep_learning": "#009E73",
"handcrafted": "#2E5090",
"embeddings": "#D64045",
"catboost": "#2E5090",
"tabpfn": "#45B29D",
"xgboost": "#D64045",
"logreg": "#7B68EE",
"good": "#45B29D",
"bad": "#D64045",
"accent": "#F5A623",
"highlight": "#F5A623",
"glaucoma": "#E74C3C",
"control": "#3498DB",
"blue_stimulus": "#1f77b4",
"red_stimulus": "#d62728",
"background_light": "#f0f0f0",
"blue_zone": "#cce5ff",
"red_zone": "#ffcccc",
"cd_rank1": "#2ecc71",
"cd_rank2": "#3498db",
"cd_rank3": "#e74c3c",
"cd_rank4": "#9b59b6",
"cd_rank5": "#f39c12",
"text_primary": "#333333",
"text_secondary": "#666666",
"background_neutral": "#F5F5F5",
"grid_lines": "#CCCCCC",
"decomp_component_1": "#E69F00",
"decomp_component_2": "#56B4E9",
"decomp_component_3": "#009E73",
"decomp_mean_waveform": "#888888",
"cycle_brown": "#8B4513",
"cycle_seagreen": "#20B2AA",
}
save_figure
¶
save_figure(
fig: Figure,
name: str,
data: Optional[Dict[str, Any]] = None,
formats: List[str] = None,
output_dir: Optional[Path] = None,
synthetic: Optional[bool] = None,
) -> Path
Save figure to multiple formats and optionally save accompanying JSON data.
Part of the 4-gate isolation architecture. Synthetic figures are automatically routed to figures/synthetic/ when synthetic=True or when is_synthetic_mode().
| PARAMETER | DESCRIPTION |
|---|---|
fig
|
The figure to save
TYPE:
|
name
|
Base name for the output file (without extension)
TYPE:
|
data
|
Data dictionary to save as JSON for reproducibility. If synthetic, adds _synthetic_warning=True to the data.
TYPE:
|
formats
|
Output formats. Default loads from config or uses ['png', 'svg']. SVG preferred over PDF for vector graphics (infinite scalability).
TYPE:
|
output_dir
|
Output directory (default: figures/generated/ or figures/synthetic/). Auto-detected from data mode if not specified.
TYPE:
|
synthetic
|
If True, route to synthetic directory. If None, auto-detect from is_synthetic_mode() environment variable.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Path
|
Path to the primary output file (PNG) |
Source code in src/viz/plot_config.py
708 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 | |
get_combo_color
¶
Get the color for a specific combo from config.
Resolves via plot_hyperparam_combos.yaml: combo.color_ref → color_definitions.
| PARAMETER | DESCRIPTION |
|---|---|
combo_id
|
Combo identifier (e.g., 'ground_truth', 'best_single_fm')
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Hex color string |
Source code in src/viz/plot_config.py
calibration_plot
¶
Calibration plot visualization module.
Implements STRATOS-compliant smoothed calibration curves with LOESS smoothing. Based on Van Calster et al. 2024 guidelines.
COMPUTATION DECOUPLING: This module performs visualization ONLY. - LOESS smoothing and bootstrap CI are visualization rendering (acceptable). - Calibration metrics (slope, intercept, Brier, O:E) come from DuckDB. - The *_from_db functions read pre-computed metrics from DuckDB. - NO sklearn imports. NO src.stats imports.
compute_loess_calibration
¶
compute_loess_calibration(
y_true: ndarray,
y_prob: ndarray,
frac: float = 0.3,
n_points: int = 100,
) -> Tuple[ndarray, ndarray]
Compute LOESS-smoothed calibration curve.
This is visualization rendering (smoothing for display), NOT metric computation.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
frac
|
Fraction of data used for LOESS smoothing (default 0.3)
TYPE:
|
n_points
|
Number of points for output curve
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
x_smooth
|
Sorted probability values
TYPE:
|
y_smooth
|
Smoothed calibration values (observed frequencies)
TYPE:
|
Source code in src/viz/calibration_plot.py
compute_calibration_ci
¶
compute_calibration_ci(
y_true: ndarray,
y_prob: ndarray,
n_bootstrap: int = 200,
frac: float = 0.3,
alpha: float = 0.05,
) -> Tuple[ndarray, ndarray, ndarray]
Compute bootstrap confidence intervals for calibration curve.
This is visualization rendering (CI bands for display), NOT metric computation.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
n_bootstrap
|
Number of bootstrap iterations
TYPE:
|
frac
|
LOESS smoothing fraction
TYPE:
|
alpha
|
Significance level for CI (default 0.05 for 95% CI)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
x_vals
|
Common x-axis values
TYPE:
|
y_lower
|
Lower confidence bound
TYPE:
|
y_upper
|
Upper confidence bound
TYPE:
|
Source code in src/viz/calibration_plot.py
plot_calibration_curve
¶
plot_calibration_curve(
y_true: ndarray,
y_prob: ndarray,
ax: Optional[Axes] = None,
label: Optional[str] = None,
color: Optional[str] = None,
show_ci: bool = True,
show_rug: bool = True,
show_metrics: bool = True,
metrics: Optional[Dict[str, float]] = None,
frac: float = 0.3,
ci_alpha: float = 0.2,
n_bootstrap: int = 200,
save_path: Optional[str] = None,
) -> Tuple[Figure, Axes]
Plot smoothed calibration curve with LOESS.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
ax
|
Axes to plot on
TYPE:
|
label
|
Legend label for the model
TYPE:
|
color
|
Line color
TYPE:
|
show_ci
|
Whether to show confidence intervals
TYPE:
|
show_rug
|
Whether to show histogram rug at bottom
TYPE:
|
show_metrics
|
Whether to annotate with calibration metrics
TYPE:
|
metrics
|
Pre-computed calibration metrics from DuckDB. Expected keys: 'calibration_slope' (or 'slope'), 'calibration_intercept' (or 'intercept'). If show_metrics is True and metrics is None, the annotation is skipped.
TYPE:
|
frac
|
LOESS smoothing fraction
TYPE:
|
ci_alpha
|
Alpha for CI shading
TYPE:
|
n_bootstrap
|
Number of bootstrap samples for CI
TYPE:
|
save_path
|
If provided, saves JSON data for reproducibility
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig, ax : matplotlib Figure and Axes
|
|
Source code in src/viz/calibration_plot.py
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 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 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 | |
plot_calibration_multi_model
¶
plot_calibration_multi_model(
models_data: Dict[str, Dict],
ax: Optional[Axes] = None,
show_ci: bool = False,
colors: Optional[List[str]] = None,
) -> Tuple[Figure, Axes]
Plot calibration curves for multiple models.
| PARAMETER | DESCRIPTION |
|---|---|
models_data
|
Dictionary mapping model names to {'y_true': ..., 'y_prob': ...}
TYPE:
|
ax
|
TYPE:
|
show_ci
|
Whether to show confidence intervals
TYPE:
|
colors
|
Colors for each model
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
(fig, ax)
|
|
Source code in src/viz/calibration_plot.py
save_calibration_extended_json_from_db
¶
save_calibration_extended_json_from_db(
run_id: str,
output_path: str,
db_path: Optional[str] = None,
) -> dict
Save extended calibration metrics to JSON by reading from DuckDB.
CRITICAL: This function reads PRE-COMPUTED metrics from DuckDB. It does NOT compute metrics - all computation happens during extraction.
| PARAMETER | DESCRIPTION |
|---|---|
run_id
|
Run ID to load metrics for
TYPE:
|
output_path
|
Path to save JSON file
TYPE:
|
db_path
|
Path to DuckDB file
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
The JSON data structure |
Source code in src/viz/calibration_plot.py
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 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 | |
save_calibration_multi_combo_json_from_db
¶
save_calibration_multi_combo_json_from_db(
run_ids: List[str],
output_path: str,
db_path: Optional[str] = None,
) -> dict
Save calibration metrics for multiple runs to single JSON.
CRITICAL: Reads from DuckDB, does NOT compute metrics.
| PARAMETER | DESCRIPTION |
|---|---|
run_ids
|
Run IDs to include
TYPE:
|
output_path
|
Path to save JSON file
TYPE:
|
db_path
|
Path to DuckDB file
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
The JSON data structure with all combos |
Source code in src/viz/calibration_plot.py
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 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 | |
generate_calibration_figure
¶
generate_calibration_figure(
y_true: ndarray,
y_prob: ndarray,
metrics: Optional[Dict[str, float]] = None,
output_dir: Optional[Path] = None,
filename: str = "fig_calibration_smoothed",
) -> Tuple[str, str]
Generate calibration plot and save to file.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
metrics
|
Pre-computed calibration metrics from DuckDB (e.g. calibration_slope, calibration_intercept). If None, metrics annotation is skipped.
TYPE:
|
output_dir
|
Output directory (default: uses save_figure default)
TYPE:
|
filename
|
Base filename (without extension)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
png_path, json_path : paths to generated files
|
|
Source code in src/viz/calibration_plot.py
dca_plot
¶
Decision Curve Analysis (DCA) visualization module.
Implements STRATOS-compliant DCA plots for clinical utility assessment. Based on Vickers & Elkin 2006 and Van Calster et al. 2024 guidelines.
Architecture (CRITICAL-FAILURE-003 compliant):
- Pure-math net benefit formulas (compute_net_benefit, compute_treat_all_nb, compute_treat_none_nb, compute_dca_curves) are ACCEPTABLE: they are simple TP/FP arithmetic with NO sklearn or src.stats imports.
- DCA curve data for production figures is loaded from DuckDB via load_dca_curves_from_db(). All metric computation happens in extraction.
- NO imports from src.stats. NO sklearn imports.
See: https://github.com/petteriTeikari/foundation_PLR/issues/13
compute_net_benefit
¶
Compute net benefit at a given threshold probability.
Net Benefit = TP/n - FP/n * (pt / (1-pt))
Where pt is the threshold probability.
This is a pure-math formula (no sklearn, no src.stats). Acceptable in viz.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels (0 or 1)
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
threshold
|
Decision threshold probability
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Net benefit at the given threshold |
Source code in src/viz/dca_plot.py
compute_treat_all_nb
¶
Compute net benefit for treat-all strategy.
NB(treat-all) = prevalence - (1 - prevalence) * (pt / (1-pt))
| PARAMETER | DESCRIPTION |
|---|---|
prevalence
|
Disease prevalence in the population
TYPE:
|
threshold
|
Decision threshold probability
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Net benefit for treat-all strategy |
Source code in src/viz/dca_plot.py
compute_treat_none_nb
¶
Compute net benefit for treat-none strategy.
NB(treat-none) = 0 (always)
| PARAMETER | DESCRIPTION |
|---|---|
threshold
|
Decision threshold probability (unused, for interface consistency)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Always returns 0.0 |
Source code in src/viz/dca_plot.py
compute_dca_curves
¶
compute_dca_curves(
y_true: ndarray,
y_prob: ndarray,
thresholds: Optional[ndarray] = None,
threshold_range: Tuple[float, float] = (0.01, 0.3),
n_thresholds: int = 50,
) -> Dict[str, ndarray]
Compute DCA curves for model, treat-all, and treat-none strategies.
Uses only pure-math net benefit formulas (no sklearn, no src.stats).
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
thresholds
|
Specific thresholds to evaluate. If None, uses threshold_range.
TYPE:
|
threshold_range
|
(min, max) threshold range (default: 1-30% for glaucoma)
TYPE:
|
n_thresholds
|
Number of threshold points to evaluate
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict with keys:
|
|
Source code in src/viz/dca_plot.py
load_dca_curves_from_db
¶
load_dca_curves_from_db(
db_path: str, combo_ids: Optional[List[str]] = None
) -> Dict[str, Dict[str, ndarray]]
Load pre-computed DCA curves from DuckDB.
Supports two DuckDB schemas: 1. Streaming schema (config_id + per-row thresholds): joins essential_metrics to find matching configs by outlier/imputation/classifier. 2. Curve extraction schema (run_id + JSON arrays): joins essential_metrics by run_id to resolve combo matching.
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to DuckDB database
TYPE:
|
combo_ids
|
Specific combo IDs to load. If None, loads standard combos from config.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Maps combo_id to dict with keys: - thresholds: np.ndarray of threshold values - nb_model: np.ndarray of model net benefits - nb_all: np.ndarray of treat-all net benefits - nb_none: np.ndarray of treat-none net benefits |
Source code in src/viz/dca_plot.py
plot_dca
¶
plot_dca(
y_true: ndarray,
y_prob: ndarray,
ax: Optional[Axes] = None,
threshold_range: Tuple[float, float] = (0.01, 0.3),
n_thresholds: int = 50,
model_label: str = "Model",
model_color: Optional[str] = None,
show_treat_all: bool = True,
show_treat_none: bool = True,
save_json_path: Optional[str] = None,
) -> Tuple[Figure, Axes]
Plot Decision Curve Analysis from raw predictions.
Uses pure-math compute_dca_curves (no sklearn, no src.stats).
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
ax
|
Axes to plot on
TYPE:
|
threshold_range
|
(min, max) threshold range (default: 1-30% for glaucoma screening)
TYPE:
|
n_thresholds
|
Number of threshold points
TYPE:
|
model_label
|
Label for model in legend
TYPE:
|
model_color
|
Color for model line
TYPE:
|
show_treat_all
|
Whether to show treat-all reference line
TYPE:
|
show_treat_none
|
Whether to show treat-none reference line
TYPE:
|
save_json_path
|
If provided, saves JSON data for reproducibility
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig, ax : matplotlib Figure and Axes
|
|
Source code in src/viz/dca_plot.py
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 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 | |
plot_dca_multi_model
¶
plot_dca_multi_model(
models_data: Dict[str, Dict],
ax: Optional[Axes] = None,
threshold_range: Tuple[float, float] = (0.01, 0.3),
n_thresholds: int = 50,
colors: Optional[List[str]] = None,
) -> Tuple[Figure, Axes]
Plot DCA for multiple models on same axes from raw predictions.
Uses pure-math compute_net_benefit (no sklearn, no src.stats).
| PARAMETER | DESCRIPTION |
|---|---|
models_data
|
Dictionary mapping model names to {'y_true': ..., 'y_prob': ...}
TYPE:
|
ax
|
TYPE:
|
threshold_range
|
(min, max) threshold range
TYPE:
|
n_thresholds
|
Number of threshold points
TYPE:
|
colors
|
Colors for each model
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
(fig, ax)
|
|
Source code in src/viz/dca_plot.py
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 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 | |
plot_dca_from_db
¶
plot_dca_from_db(
db_path: str,
combo_ids: Optional[List[str]] = None,
ax: Optional[Axes] = None,
output_dir: Optional[Path] = None,
filename: str = "fig_dca_curves",
) -> Tuple[Figure, Axes]
Plot DCA curves from pre-computed data in DuckDB.
This is the PREFERRED method for production figures. Reads pre-computed DCA curves from the database (no on-the-fly computation).
| PARAMETER | DESCRIPTION |
|---|---|
db_path
|
Path to DuckDB database
TYPE:
|
combo_ids
|
Specific combo IDs to plot. If None, loads standard combos.
TYPE:
|
ax
|
Axes to plot on
TYPE:
|
output_dir
|
Output directory for saving figure
TYPE:
|
filename
|
Base filename for saving
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig, ax : matplotlib Figure and Axes
|
|
Source code in src/viz/dca_plot.py
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 707 708 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 | |
generate_dca_figure
¶
generate_dca_figure(
y_true: ndarray,
y_prob: ndarray,
output_dir: Optional[Path] = None,
filename: str = "fig_dca_curves",
threshold_range: Tuple[float, float] = (0.01, 0.3),
) -> Tuple[str, str]
Generate DCA plot from raw predictions and save to file.
For production figures, prefer plot_dca_from_db() which reads pre-computed data from DuckDB.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True binary labels
TYPE:
|
y_prob
|
Predicted probabilities
TYPE:
|
output_dir
|
Output directory (default: uses save_figure default)
TYPE:
|
filename
|
Base filename (without extension)
TYPE:
|
threshold_range
|
(min, max) threshold range
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
png_path, json_path : paths to generated files
|
|
Source code in src/viz/dca_plot.py
cd_diagram
¶
Critical Difference Diagram for statistical method comparison.
Implements Demšar (2006) CD diagrams using Friedman test + Nemenyi post-hoc.
Cross-references: - planning/remaining-duckdb-stats-viz-tasks-plan.md (Figs 8-11)
References: - Demšar (2006). Statistical comparisons of classifiers. - Nemenyi (1963). Distribution-free multiple comparisons.
The diagram shows: 1. Methods ranked by average performance 2. Cliques (groups) of methods NOT significantly different 3. Critical Difference (CD) bar showing minimum significant difference
friedman_nemenyi_test
¶
Perform Friedman test with Nemenyi post-hoc analysis.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
DataFrame with rows as "datasets" (e.g., preprocessing configs) and columns as "methods" (e.g., classifiers). Values are performance metrics (e.g., AUROC).
TYPE:
|
alpha
|
Significance level
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Contains: - friedman_statistic: Chi-square statistic - friedman_pvalue: p-value for Friedman test - average_ranks: Dict of method -> average rank - critical_difference: CD value for Nemenyi test - pairwise_significant: Dict of (method1, method2) -> bool - cliques: List of sets of methods NOT significantly different |
Examples:
>>> # Rows = configs, columns = classifiers
>>> data = pd.DataFrame({
... 'CatBoost': [0.91, 0.89, 0.93],
... 'XGBoost': [0.88, 0.87, 0.90],
... 'LogReg': [0.82, 0.81, 0.84]
... })
>>> result = friedman_nemenyi_test(data)
>>> print(f"Friedman p={result['friedman_pvalue']:.4f}")
Source code in src/viz/cd_diagram.py
compute_critical_difference
¶
Compute Nemenyi critical difference.
CD = q_α × sqrt(k(k+1) / (6N))
where: - q_α: critical value from Studentized range distribution - k: number of methods - N: number of datasets
| PARAMETER | DESCRIPTION |
|---|---|
n_methods
|
Number of methods being compared (k)
TYPE:
|
n_datasets
|
Number of datasets/configurations (N)
TYPE:
|
alpha
|
Significance level
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Critical difference value |
Source code in src/viz/cd_diagram.py
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 199 200 201 202 203 204 205 | |
identify_cliques
¶
Identify cliques (groups of methods not significantly different).
A clique is a maximal set of methods where all pairs differ by < CD.
| PARAMETER | DESCRIPTION |
|---|---|
average_ranks
|
Method -> average rank mapping
TYPE:
|
cd
|
Critical difference
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of lists
|
Each inner list is a clique of method names |
Source code in src/viz/cd_diagram.py
draw_cd_diagram
¶
draw_cd_diagram(
data: Union[DataFrame, Dict],
title: str = "Critical Difference Diagram",
output_path: Optional[str] = None,
save_data_path: Optional[str] = None,
figure_id: Optional[str] = None,
alpha: float = 0.05,
figsize: Tuple[float, float] = (10, 5),
text_fontsize: int = 10,
line_width: float = 2.5,
marker_size: int = 100,
highlight_best: bool = True,
) -> Tuple[Figure, Axes]
Draw a Critical Difference diagram.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
If DataFrame: rows = datasets, columns = methods, values = metrics If dict: output from friedman_nemenyi_test()
TYPE:
|
title
|
Plot title
TYPE:
|
output_path
|
If provided, save figure to this path
TYPE:
|
save_data_path
|
If provided, save underlying data as JSON to this path
TYPE:
|
figure_id
|
Figure identifier for data export (e.g., "fig08")
TYPE:
|
alpha
|
Significance level for Nemenyi test
TYPE:
|
figsize
|
Figure size (width, height)
TYPE:
|
text_fontsize
|
Font size for method names
TYPE:
|
line_width
|
Width of clique bars
TYPE:
|
marker_size
|
Size of rank markers
TYPE:
|
highlight_best
|
Whether to highlight the best method
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
fig, ax : matplotlib figure and axes
|
|
Source code in src/viz/cd_diagram.py
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 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 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 | |
prepare_cd_data
¶
Prepare data for CD diagram from long-format DataFrame.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Long-format data with config, method, and value columns
TYPE:
|
config_col
|
Column name for configuration/dataset identifier
TYPE:
|
method_col
|
Column name for method identifier
TYPE:
|
value_col
|
Column name for performance metric
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Wide-format DataFrame suitable for friedman_nemenyi_test |
Examples:
>>> df = pd.DataFrame({
... 'config': ['A', 'A', 'B', 'B'],
... 'classifier': ['Cat', 'XGB', 'Cat', 'XGB'],
... 'auroc': [0.9, 0.85, 0.88, 0.83]
... })
>>> wide_df = prepare_cd_data(df, 'config', 'classifier', 'auroc')
Source code in src/viz/cd_diagram.py
factorial_matrix
¶
factorial_matrix.py - Figure M3: Factorial Design Matrix
Visualizes the factorial experimental design structure: - 2 featurization methods - 7+ outlier detection methods (including ensembles) - 5+ imputation methods (including ensembles) - 5 classifiers
Total: 407 unique configurations
Usage: python src/viz/factorial_matrix.py
fetch_factorial_counts
¶
Fetch counts of configurations per factor combination.
Source code in src/viz/factorial_matrix.py
create_figure
¶
Create the factorial design visualization.
Source code in src/viz/factorial_matrix.py
62 63 64 65 66 67 68 69 70 71 72 73 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 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 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 | |
main
¶
Generate and save the figure.
Source code in src/viz/factorial_matrix.py
Usage Example¶
from src.viz.plot_config import setup_style, save_figure, COLORS
# Always setup style first
setup_style()
# Create figure using semantic colors
fig, ax = plt.subplots()
ax.plot(x, y, color=COLORS["ground_truth"])
# Save with JSON data for reproducibility
save_figure(fig, "fig_my_analysis", data={"x": x, "y": y})
Color System¶
Colors are loaded from configs/VISUALIZATION/combos.yaml:
from src.viz.plot_config import COLORS
# Available colors
COLORS["ground_truth"] # #2E5B8C
COLORS["best_ensemble"] # #932834
COLORS["traditional"] # #666666
See Also¶
- R Figure System - R/ggplot2 figures
- Figure Registry - Figure specifications