Commit ·
3c8ce9d
1
Parent(s): 1087dfe
Initial commit: BNet-OT multimodal late fusion implementation
Browse files- .gitignore +7 -0
- README.md +139 -0
- examples/synthetic_demo.py +48 -0
- pyproject.toml +21 -0
- requirements.txt +4 -0
- scripts/evaluate.py +87 -0
- src/otfusion/__init__.py +53 -0
- src/otfusion/calibration.py +48 -0
- src/otfusion/dropout.py +69 -0
- src/otfusion/fusion.py +256 -0
- src/otfusion/metrics.py +191 -0
- src/otfusion/pipeline.py +236 -0
- src/otfusion/plots.py +96 -0
- src/otfusion/sinkhorn.py +112 -0
- tests/conftest.py +4 -0
- tests/test_evaluation.py +103 -0
- tests/test_fusion.py +145 -0
.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.egg-info/
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
results/
|
| 5 |
+
examples/demo_results/
|
| 6 |
+
*.npy
|
| 7 |
+
*.png
|
README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sinkhorn-Based Optimal Transport Late Fusion for Breast Cancer Diagnosis
|
| 2 |
+
|
| 3 |
+
> **This is a cleaned reimplementation of the method in Asiedu Asare et al. (2026).**
|
| 4 |
+
> The original notebooks, trained models, and intermediate outputs from the 2025 experiments were not retained, so results may not reproduce exactly.
|
| 5 |
+
|
| 6 |
+
Paper:
|
| 7 |
+
|
| 8 |
+
> Asiedu Asare M, Acquah I, Appiah Yeboah B, Owusu E. **Resilient Sinkhorn-Based Optimal Transport Late Fusion Framework for Breast Cancer Diagnosis.** *Cancer Informatics.* 2026;25:1–15. doi:[10.1177/11769351261420789](https://doi.org/10.1177/11769351261420789)
|
| 9 |
+
|
| 10 |
+
The framework combines two independently trained models, a histopathology image classifier (BreakHis) and a clinical risk-factor model (BCSC), at the level of their output probabilities. The fusion layer aligns the two predictions with entropy-regularized optimal transport and is designed to keep working when one modality is missing.
|
| 11 |
+
|
| 12 |
+
This repository implements the fusion layer and its evaluation as described in the paper. It does not include the two upstream models; it takes their predicted probabilities as input.
|
| 13 |
+
|
| 14 |
+
## What is implemented
|
| 15 |
+
|
| 16 |
+
| Paper | Code |
|
| 17 |
+
|---|---|
|
| 18 |
+
| Eq. 13: predictions as vectors in the probability simplex | `otfusion.fusion.to_distribution` |
|
| 19 |
+
| Eq. 14: modality mask m = [m_p, m_q] | `otfusion.fusion.modality_mask` (NaN = missing), or masks passed explicitly |
|
| 20 |
+
| Eq. 15: uniform substitution for a missing modality | `otfusion.fusion.substitute_missing` |
|
| 21 |
+
| Eq. 16: confidence-weighted fusion factor α | `otfusion.fusion.dynamic_alpha` |
|
| 22 |
+
| Eq. 17: cost matrix (divergence + clinical semantic penalty) | `otfusion.fusion.cost_matrix`, `semantic_cost` |
|
| 23 |
+
| Eq. 18: entropic OT, Sinkhorn-Knopp in the log domain | `otfusion.sinkhorn.sinkhorn_log` |
|
| 24 |
+
| Eq. 19: fused prediction from the row marginal of T*, outer-product fallback | `otfusion.fusion.sinkhorn_fusion` |
|
| 25 |
+
| Simulated modality dropout (Table 5) | `otfusion.dropout.simulate_dropout` |
|
| 26 |
+
| Calibrated fused output (Figs. 3–4) | `otfusion.calibration` (isotonic regression) |
|
| 27 |
+
| PR-AUC, recall, F1, Brier, 95% bootstrap CIs (1000 resamples), paired tests | `otfusion.metrics` |
|
| 28 |
+
| Decision curve analysis (Fig. 3) | `otfusion.metrics.net_benefit`, `otfusion.plots.plot_decision_curve` |
|
| 29 |
+
| Calibration curve, PR curve, average transport plan (Figs. 4–5) | `otfusion.plots` |
|
| 30 |
+
| Runtime per sample | recorded by `otfusion.pipeline.run_evaluation` |
|
| 31 |
+
|
| 32 |
+
## Default parameters
|
| 33 |
+
|
| 34 |
+
Defaults in `FusionConfig` are the values reported in the paper:
|
| 35 |
+
|
| 36 |
+
| Parameter | Value | Meaning |
|
| 37 |
+
|---|---|---|
|
| 38 |
+
| `fp_weight` (w_p) | 1.8 | Semantic cost, entry (0, 1) of C_semantic |
|
| 39 |
+
| `fn_weight` (w_n) | 1.2 | Semantic cost, entry (1, 0) of C_semantic |
|
| 40 |
+
| `alpha` | 0.1 | Blend between divergence and semantic cost; `"dynamic"` uses Eq. 16 |
|
| 41 |
+
| `reg` | 0.15 | Entropic regularization of the OT problem |
|
| 42 |
+
| `max_iter` | 5000 | Maximum Sinkhorn iterations |
|
| 43 |
+
| `stop_thr` | 1e-9 | Sinkhorn convergence threshold |
|
| 44 |
+
| `eps` | 1e-8 | Numerical stability constant in Eq. 16 |
|
| 45 |
+
|
| 46 |
+
## Installation
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
git clone <this repository>
|
| 50 |
+
cd bnet-ot-fusion
|
| 51 |
+
pip install -e . # or: pip install -r requirements.txt
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Python 3.10 or later. Dependencies: NumPy, SciPy, scikit-learn, matplotlib.
|
| 55 |
+
|
| 56 |
+
## Usage
|
| 57 |
+
|
| 58 |
+
### As a library
|
| 59 |
+
|
| 60 |
+
```python
|
| 61 |
+
import numpy as np
|
| 62 |
+
from otfusion import FusionConfig, sinkhorn_fusion
|
| 63 |
+
|
| 64 |
+
p_hist = np.array([0.92, 0.15, np.nan]) # histopathology P(malignant); NaN = missing
|
| 65 |
+
p_risk = np.array([0.40, 0.70, 0.65]) # clinical risk P(high risk)
|
| 66 |
+
|
| 67 |
+
result = sinkhorn_fusion(p_hist, p_risk, FusionConfig())
|
| 68 |
+
result.fused # (N, 2) fused probability vectors
|
| 69 |
+
result.plans # (N, 2, 2) transport plans
|
| 70 |
+
result.fallback # samples where the outer-product fallback was used
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### Full evaluation
|
| 74 |
+
|
| 75 |
+
Save each model's predictions as `.npy` files (positive-class probabilities of shape `(N,)` or two-class vectors of shape `(N, 2)`), then:
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
python scripts/evaluate.py \
|
| 79 |
+
--hist p_hist_test.npy --risk p_risk_test.npy --labels y_test.npy \
|
| 80 |
+
--calib-hist p_hist_val.npy --calib-risk p_risk_val.npy --calib-labels y_val.npy \
|
| 81 |
+
--out results/
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
This writes `results.json` (metrics with CIs for the fused model and baselines, paired comparisons, dropout results, runtime) and four figures to `results/`. Run `python scripts/evaluate.py --help` for all options.
|
| 85 |
+
|
| 86 |
+
### Demo on synthetic data
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
python examples/synthetic_demo.py
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Runs the whole pipeline on random synthetic predictions to show the inputs and outputs. The numbers it prints are unrelated to the paper.
|
| 93 |
+
|
| 94 |
+
## Implementation notes
|
| 95 |
+
|
| 96 |
+
The paper's description leaves a few choices open. This implementation resolves them as follows:
|
| 97 |
+
|
| 98 |
+
- **α (Eqs. 16–17).** Eq. 16 defines a per-sample, confidence-weighted α, while the training section reports a fixed blending factor α = 0.1. The default is the fixed value; set `alpha="dynamic"` for Eq. 16.
|
| 99 |
+
- **Regularization naming.** The paper uses ε both for the entropic regularization in Eq. 18 and for a 1e-8 stability constant. Here they are separate: `reg` (0.15) for Eq. 18 and `eps` (1e-8) for Eq. 16.
|
| 100 |
+
- **Sinkhorn solver.** A batched log-domain Sinkhorn-Knopp solver is implemented directly in NumPy/SciPy. The fallback plan p ⊗ q is used when the final marginal violation exceeds `fallback_tol` (1e-6).
|
| 101 |
+
- **Row marginal.** Because Eq. 18 constrains T 1 = p̃, the row marginal read out in Eq. 19 equals the (mask-substituted) histopathology vector p̃ whenever Sinkhorn converges. This is covered by `tests/test_fusion.py::test_eq19_row_marginal_equals_p_under_marginal_constraint`.
|
| 102 |
+
- **Calibration.** The paper reports calibrated fused probabilities. Here an isotonic calibrator is fitted on a separate calibration split when provided, and otherwise cross-fitted (5 folds), so that no sample is calibrated with its own label.
|
| 103 |
+
- **Dropout.** By default each affected sample loses one modality chosen at random ("randomly omitting 1 input source"). Modes `hist`, `risk` and `both` are also available.
|
| 104 |
+
- **Paired tests.** `paired_comparison` scores both models on the same bootstrap resamples and reports the difference with a 95% CI, a bootstrap p-value, and a paired t-test on the replicates (as reported in the paper). The t-test p-value depends on the number of resamples, so the CI is the more interpretable summary.
|
| 105 |
+
|
| 106 |
+
## Tests
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
pip install pytest
|
| 110 |
+
pytest
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
The tests check the Sinkhorn solution against a brute-force optimum, the marginal constraints, masking and uniform substitution, Eq. 16 limits, the cost matrix, the fallback, dropout masks, metrics against scikit-learn, decision-curve formulas, and an end-to-end pipeline run.
|
| 114 |
+
|
| 115 |
+
## Data
|
| 116 |
+
|
| 117 |
+
The datasets are publicly available from their owners and are not redistributed here:
|
| 118 |
+
|
| 119 |
+
- BreakHis: http://www.inf.ufpr.br/vri/databases/BreaKHis_v1.tar.gz
|
| 120 |
+
- BCSC Risk Factors: https://www.bcsc-research.org/index.php/datasets/rf/risk-factor-dataset-download
|
| 121 |
+
|
| 122 |
+
## Citation
|
| 123 |
+
|
| 124 |
+
```bibtex
|
| 125 |
+
@article{asieduasare2026sinkhorn,
|
| 126 |
+
title = {Resilient Sinkhorn-Based Optimal Transport Late Fusion Framework for Breast Cancer Diagnosis},
|
| 127 |
+
author = {Asiedu Asare, Michael and Acquah, Isaac and Appiah Yeboah, Benjamin and Owusu, Emmanuel},
|
| 128 |
+
journal = {Cancer Informatics},
|
| 129 |
+
volume = {25},
|
| 130 |
+
pages = {1--15},
|
| 131 |
+
year = {2026},
|
| 132 |
+
doi = {10.1177/11769351261420789}
|
| 133 |
+
}
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
## Contact
|
| 137 |
+
|
| 138 |
+
Michael Asiedu Asare, Biomedical Technologies Lab, Kwame Nkrumah University of Science and Technology.
|
| 139 |
+
Corresponding author: Isaac Acquah (iacquah.coe@knust.edu.gh).
|
examples/synthetic_demo.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the full pipeline on synthetic predictions.
|
| 2 |
+
|
| 3 |
+
This only demonstrates how the code is used. The synthetic data are random and
|
| 4 |
+
the numbers it prints have no relation to the results in the paper.
|
| 5 |
+
|
| 6 |
+
python examples/synthetic_demo.py
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
|
| 17 |
+
|
| 18 |
+
from otfusion import FusionConfig, format_summary, run_evaluation # noqa: E402
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def synthetic_predictions(n: int, prevalence: float, rng: np.random.Generator):
|
| 22 |
+
"""Labels plus two noisy, imperfect positive-class probability vectors."""
|
| 23 |
+
y = (rng.random(n) < prevalence).astype(int)
|
| 24 |
+
signal = 2.0 * y - 1.0
|
| 25 |
+
hist = 1.0 / (1.0 + np.exp(-(1.8 * signal + rng.normal(0, 1.2, n))))
|
| 26 |
+
risk = 1.0 / (1.0 + np.exp(-(0.6 * signal + rng.normal(0, 1.0, n))))
|
| 27 |
+
return hist, risk, y
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main() -> None:
|
| 31 |
+
rng = np.random.default_rng(0)
|
| 32 |
+
test = synthetic_predictions(313, 0.70, rng)
|
| 33 |
+
calibration = synthetic_predictions(312, 0.70, rng)
|
| 34 |
+
|
| 35 |
+
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "demo_results")
|
| 36 |
+
results = run_evaluation(
|
| 37 |
+
*test,
|
| 38 |
+
config=FusionConfig(),
|
| 39 |
+
calibration=calibration,
|
| 40 |
+
n_boot=200,
|
| 41 |
+
out_dir=out_dir,
|
| 42 |
+
)
|
| 43 |
+
print(format_summary(results))
|
| 44 |
+
print(f"\nFigures and results.json written to {out_dir}")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
main()
|
pyproject.toml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=64"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "otfusion"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "Sinkhorn-based optimal transport late fusion for breast cancer diagnosis (reimplementation of Asiedu Asare et al., 2026)"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.10"
|
| 11 |
+
authors = [{ name = "Michael Asiedu Asare" }]
|
| 12 |
+
dependencies = ["numpy>=1.24", "scipy>=1.10", "scikit-learn>=1.2", "matplotlib>=3.6"]
|
| 13 |
+
|
| 14 |
+
[project.optional-dependencies]
|
| 15 |
+
test = ["pytest"]
|
| 16 |
+
|
| 17 |
+
[tool.setuptools.packages.find]
|
| 18 |
+
where = ["src"]
|
| 19 |
+
|
| 20 |
+
[tool.pytest.ini_options]
|
| 21 |
+
testpaths = ["tests"]
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.24
|
| 2 |
+
scipy>=1.10
|
| 3 |
+
scikit-learn>=1.2
|
| 4 |
+
matplotlib>=3.6
|
scripts/evaluate.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate the fusion layer on saved model predictions.
|
| 2 |
+
|
| 3 |
+
Each input is a .npy file holding either positive-class probabilities, shape (N,),
|
| 4 |
+
or two-class probability vectors, shape (N, 2).
|
| 5 |
+
|
| 6 |
+
Example
|
| 7 |
+
-------
|
| 8 |
+
python scripts/evaluate.py \
|
| 9 |
+
--hist data/p_hist_test.npy --risk data/p_risk_test.npy --labels data/y_test.npy \
|
| 10 |
+
--calib-hist data/p_hist_val.npy --calib-risk data/p_risk_val.npy --calib-labels data/y_val.npy \
|
| 11 |
+
--out results/
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
|
| 23 |
+
|
| 24 |
+
from otfusion import FusionConfig, format_summary, run_evaluation # noqa: E402
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _alpha(value: str):
|
| 28 |
+
return value if value == "dynamic" else float(value)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main() -> None:
|
| 32 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 33 |
+
parser.add_argument("--hist", required=True, help="Histopathology model probabilities (.npy)")
|
| 34 |
+
parser.add_argument("--risk", required=True, help="Clinical risk model probabilities (.npy)")
|
| 35 |
+
parser.add_argument("--labels", required=True, help="Reference labels, 0/1 (.npy)")
|
| 36 |
+
parser.add_argument("--calib-hist", help="Calibration split: histopathology probabilities")
|
| 37 |
+
parser.add_argument("--calib-risk", help="Calibration split: risk probabilities")
|
| 38 |
+
parser.add_argument("--calib-labels", help="Calibration split: labels")
|
| 39 |
+
parser.add_argument("--out", default="results", help="Output directory")
|
| 40 |
+
|
| 41 |
+
defaults = FusionConfig()
|
| 42 |
+
parser.add_argument("--fp-weight", type=float, default=defaults.fp_weight)
|
| 43 |
+
parser.add_argument("--fn-weight", type=float, default=defaults.fn_weight)
|
| 44 |
+
parser.add_argument("--alpha", type=_alpha, default=defaults.alpha, help='float in [0, 1] or "dynamic"')
|
| 45 |
+
parser.add_argument("--reg", type=float, default=defaults.reg)
|
| 46 |
+
parser.add_argument("--max-iter", type=int, default=defaults.max_iter)
|
| 47 |
+
|
| 48 |
+
parser.add_argument("--dropout-rates", type=float, nargs="+", default=[0.0, 0.2, 0.5])
|
| 49 |
+
parser.add_argument("--dropout-mode", default="either", choices=["either", "hist", "risk", "both"])
|
| 50 |
+
parser.add_argument("--threshold", type=float, default=0.5)
|
| 51 |
+
parser.add_argument("--n-boot", type=int, default=1000)
|
| 52 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 53 |
+
parser.add_argument("--no-figures", action="store_true")
|
| 54 |
+
args = parser.parse_args()
|
| 55 |
+
|
| 56 |
+
calib_args = (args.calib_hist, args.calib_risk, args.calib_labels)
|
| 57 |
+
if any(calib_args) and not all(calib_args):
|
| 58 |
+
parser.error("--calib-hist, --calib-risk and --calib-labels must be given together")
|
| 59 |
+
calibration = tuple(np.load(path) for path in calib_args) if all(calib_args) else None
|
| 60 |
+
|
| 61 |
+
config = FusionConfig(
|
| 62 |
+
fp_weight=args.fp_weight,
|
| 63 |
+
fn_weight=args.fn_weight,
|
| 64 |
+
alpha=args.alpha,
|
| 65 |
+
reg=args.reg,
|
| 66 |
+
max_iter=args.max_iter,
|
| 67 |
+
)
|
| 68 |
+
results = run_evaluation(
|
| 69 |
+
np.load(args.hist),
|
| 70 |
+
np.load(args.risk),
|
| 71 |
+
np.load(args.labels),
|
| 72 |
+
config=config,
|
| 73 |
+
calibration=calibration,
|
| 74 |
+
dropout_rates=args.dropout_rates,
|
| 75 |
+
dropout_mode=args.dropout_mode,
|
| 76 |
+
threshold=args.threshold,
|
| 77 |
+
n_boot=args.n_boot,
|
| 78 |
+
seed=args.seed,
|
| 79 |
+
out_dir=args.out,
|
| 80 |
+
make_figures=not args.no_figures,
|
| 81 |
+
)
|
| 82 |
+
print(format_summary(results))
|
| 83 |
+
print(f"\nSaved results to {os.path.abspath(args.out)}")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|
src/otfusion/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sinkhorn-based optimal transport late fusion for breast cancer diagnosis.
|
| 2 |
+
|
| 3 |
+
Cleaned reimplementation of the method in Asiedu Asare et al., Cancer Informatics (2026).
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from .calibration import IsotonicCalibrator, cross_fitted_calibration
|
| 7 |
+
from .dropout import simulate_dropout
|
| 8 |
+
from .fusion import (
|
| 9 |
+
FusionConfig,
|
| 10 |
+
FusionResult,
|
| 11 |
+
cost_matrix,
|
| 12 |
+
dynamic_alpha,
|
| 13 |
+
modality_mask,
|
| 14 |
+
semantic_cost,
|
| 15 |
+
sinkhorn_fusion,
|
| 16 |
+
substitute_missing,
|
| 17 |
+
to_distribution,
|
| 18 |
+
)
|
| 19 |
+
from .metrics import (
|
| 20 |
+
binary_metrics,
|
| 21 |
+
bootstrap_metrics,
|
| 22 |
+
net_benefit,
|
| 23 |
+
net_benefit_treat_all,
|
| 24 |
+
paired_comparison,
|
| 25 |
+
)
|
| 26 |
+
from .pipeline import format_summary, run_evaluation
|
| 27 |
+
from .sinkhorn import SinkhornResult, sinkhorn_log
|
| 28 |
+
|
| 29 |
+
__version__ = "1.0.0"
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
"FusionConfig",
|
| 33 |
+
"FusionResult",
|
| 34 |
+
"IsotonicCalibrator",
|
| 35 |
+
"SinkhornResult",
|
| 36 |
+
"binary_metrics",
|
| 37 |
+
"bootstrap_metrics",
|
| 38 |
+
"cost_matrix",
|
| 39 |
+
"cross_fitted_calibration",
|
| 40 |
+
"dynamic_alpha",
|
| 41 |
+
"format_summary",
|
| 42 |
+
"modality_mask",
|
| 43 |
+
"net_benefit",
|
| 44 |
+
"net_benefit_treat_all",
|
| 45 |
+
"paired_comparison",
|
| 46 |
+
"run_evaluation",
|
| 47 |
+
"semantic_cost",
|
| 48 |
+
"simulate_dropout",
|
| 49 |
+
"sinkhorn_fusion",
|
| 50 |
+
"sinkhorn_log",
|
| 51 |
+
"substitute_missing",
|
| 52 |
+
"to_distribution",
|
| 53 |
+
]
|
src/otfusion/calibration.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Probability calibration of the fused output with isotonic regression.
|
| 2 |
+
|
| 3 |
+
The calibrator must be fitted on data that is not used for evaluation:
|
| 4 |
+
either a separate calibration split, or out-of-fold (cross-fitted) predictions.
|
| 5 |
+
Fitting and scoring on the same labels gives an optimistic picture of
|
| 6 |
+
calibration and of threshold-based metrics.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from sklearn.isotonic import IsotonicRegression
|
| 13 |
+
from sklearn.model_selection import StratifiedKFold
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class IsotonicCalibrator:
|
| 17 |
+
"""Thin wrapper around :class:`sklearn.isotonic.IsotonicRegression`."""
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self._iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
|
| 21 |
+
self.fitted = False
|
| 22 |
+
|
| 23 |
+
def fit(self, probs: np.ndarray, y: np.ndarray) -> "IsotonicCalibrator":
|
| 24 |
+
self._iso.fit(np.asarray(probs, dtype=np.float64), np.asarray(y, dtype=np.float64))
|
| 25 |
+
self.fitted = True
|
| 26 |
+
return self
|
| 27 |
+
|
| 28 |
+
def transform(self, probs: np.ndarray) -> np.ndarray:
|
| 29 |
+
if not self.fitted:
|
| 30 |
+
raise RuntimeError("call fit() before transform()")
|
| 31 |
+
return self._iso.transform(np.asarray(probs, dtype=np.float64))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def cross_fitted_calibration(
|
| 35 |
+
probs: np.ndarray, y: np.ndarray, n_splits: int = 5, seed: int = 0
|
| 36 |
+
) -> np.ndarray:
|
| 37 |
+
"""Calibrate every sample with a calibrator that never saw its label.
|
| 38 |
+
|
| 39 |
+
Use this when no separate calibration split is available.
|
| 40 |
+
"""
|
| 41 |
+
probs = np.asarray(probs, dtype=np.float64)
|
| 42 |
+
y = np.asarray(y).astype(int)
|
| 43 |
+
out = np.empty_like(probs)
|
| 44 |
+
folds = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)
|
| 45 |
+
for train_idx, test_idx in folds.split(probs.reshape(-1, 1), y):
|
| 46 |
+
cal = IsotonicCalibrator().fit(probs[train_idx], y[train_idx])
|
| 47 |
+
out[test_idx] = cal.transform(probs[test_idx])
|
| 48 |
+
return out
|
src/otfusion/dropout.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simulated modality dropout.
|
| 2 |
+
|
| 3 |
+
The paper evaluates robustness by randomly omitting one input source at
|
| 4 |
+
inference time, at dropout rates of 20% and 50%. A dropped modality is passed
|
| 5 |
+
to the fusion layer as missing (mask = 0), which substitutes the uniform
|
| 6 |
+
distribution (Eq. 15).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
MODES = ("either", "hist", "risk", "both")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def simulate_dropout(
|
| 19 |
+
n: int,
|
| 20 |
+
rate: float,
|
| 21 |
+
mode: str = "either",
|
| 22 |
+
rng: Optional[np.random.Generator] = None,
|
| 23 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 24 |
+
"""Draw modality masks (m_p, m_q) with a given dropout rate.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
n:
|
| 29 |
+
Number of samples.
|
| 30 |
+
rate:
|
| 31 |
+
Fraction of samples affected by dropout, in [0, 1].
|
| 32 |
+
mode:
|
| 33 |
+
``"either"`` (default) - each affected sample loses one modality, chosen
|
| 34 |
+
uniformly at random (this matches "randomly omitting 1 input source").
|
| 35 |
+
``"hist"`` - affected samples lose the histopathology input.
|
| 36 |
+
``"risk"`` - affected samples lose the clinical risk input.
|
| 37 |
+
``"both"`` - affected samples lose both inputs.
|
| 38 |
+
rng:
|
| 39 |
+
NumPy random generator, for reproducibility.
|
| 40 |
+
|
| 41 |
+
Returns
|
| 42 |
+
-------
|
| 43 |
+
(m_p, m_q):
|
| 44 |
+
Boolean presence masks, shape (n,). True means the modality is present.
|
| 45 |
+
"""
|
| 46 |
+
if not 0.0 <= rate <= 1.0:
|
| 47 |
+
raise ValueError("rate must lie in [0, 1]")
|
| 48 |
+
if mode not in MODES:
|
| 49 |
+
raise ValueError(f"mode must be one of {MODES}")
|
| 50 |
+
|
| 51 |
+
rng = rng if rng is not None else np.random.default_rng()
|
| 52 |
+
affected = rng.random(n) < rate
|
| 53 |
+
|
| 54 |
+
m_p = np.ones(n, dtype=bool)
|
| 55 |
+
m_q = np.ones(n, dtype=bool)
|
| 56 |
+
|
| 57 |
+
if mode == "hist":
|
| 58 |
+
m_p[affected] = False
|
| 59 |
+
elif mode == "risk":
|
| 60 |
+
m_q[affected] = False
|
| 61 |
+
elif mode == "both":
|
| 62 |
+
m_p[affected] = False
|
| 63 |
+
m_q[affected] = False
|
| 64 |
+
else: # either
|
| 65 |
+
drop_hist = rng.random(n) < 0.5
|
| 66 |
+
m_p[affected & drop_hist] = False
|
| 67 |
+
m_q[affected & ~drop_hist] = False
|
| 68 |
+
|
| 69 |
+
return m_p, m_q
|
src/otfusion/fusion.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sinkhorn-based optimal transport late fusion (Eqs. 13-19 of the paper).
|
| 2 |
+
|
| 3 |
+
Notation follows the paper:
|
| 4 |
+
|
| 5 |
+
* ``p`` - probability vector from the histopathology model, in the simplex Delta^2 (Eq. 13)
|
| 6 |
+
* ``q`` - probability vector from the clinical risk model, in Delta^2
|
| 7 |
+
* class index 0 = benign / low risk, class index 1 = malignant / high risk
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from typing import Optional, Union
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from .sinkhorn import sinkhorn_log
|
| 18 |
+
|
| 19 |
+
UNIFORM = np.array([0.5, 0.5])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class FusionConfig:
|
| 24 |
+
"""Hyperparameters of the fusion layer.
|
| 25 |
+
|
| 26 |
+
Defaults are the values reported in the paper.
|
| 27 |
+
|
| 28 |
+
Attributes
|
| 29 |
+
----------
|
| 30 |
+
fp_weight:
|
| 31 |
+
``w_p`` in Eq. 17, the semantic cost on the (0, 1) entry. Paper value: 1.8.
|
| 32 |
+
fn_weight:
|
| 33 |
+
``w_n`` in Eq. 17, the semantic cost on the (1, 0) entry. Paper value: 1.2.
|
| 34 |
+
alpha:
|
| 35 |
+
Blending factor between divergence cost and semantic cost in Eq. 17.
|
| 36 |
+
A float uses that fixed value for every sample (paper value: 0.1).
|
| 37 |
+
The string ``"dynamic"`` computes it per sample from model confidence (Eq. 16).
|
| 38 |
+
reg:
|
| 39 |
+
Entropic regularisation of the OT problem (Eq. 18). Paper value: 0.15.
|
| 40 |
+
max_iter:
|
| 41 |
+
Maximum Sinkhorn iterations. Paper value: 5000.
|
| 42 |
+
stop_thr:
|
| 43 |
+
Sinkhorn convergence threshold. Paper value: 1e-9.
|
| 44 |
+
fallback_tol:
|
| 45 |
+
If the final marginal violation exceeds this, the plan is replaced by the
|
| 46 |
+
outer product p (x) q (the fallback described after Eq. 19).
|
| 47 |
+
eps:
|
| 48 |
+
Small constant for numerical stability in Eq. 16.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
fp_weight: float = 1.8
|
| 52 |
+
fn_weight: float = 1.2
|
| 53 |
+
alpha: Union[float, str] = 0.1
|
| 54 |
+
reg: float = 0.15
|
| 55 |
+
max_iter: int = 5000
|
| 56 |
+
stop_thr: float = 1e-9
|
| 57 |
+
fallback_tol: float = 1e-6
|
| 58 |
+
eps: float = 1e-8
|
| 59 |
+
|
| 60 |
+
def __post_init__(self) -> None:
|
| 61 |
+
if isinstance(self.alpha, str):
|
| 62 |
+
if self.alpha != "dynamic":
|
| 63 |
+
raise ValueError('alpha must be a float in [0, 1] or "dynamic"')
|
| 64 |
+
elif not 0.0 <= float(self.alpha) <= 1.0:
|
| 65 |
+
raise ValueError("alpha must lie in [0, 1]")
|
| 66 |
+
if self.reg <= 0:
|
| 67 |
+
raise ValueError("reg must be positive")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass
|
| 71 |
+
class FusionResult:
|
| 72 |
+
"""Output of :func:`sinkhorn_fusion`.
|
| 73 |
+
|
| 74 |
+
Attributes
|
| 75 |
+
----------
|
| 76 |
+
fused:
|
| 77 |
+
Fused probability vectors z (Eq. 19), shape (N, 2).
|
| 78 |
+
plans:
|
| 79 |
+
Transport plans T* (after any fallback), shape (N, 2, 2).
|
| 80 |
+
costs:
|
| 81 |
+
Cost matrices C (Eq. 17), shape (N, 2, 2).
|
| 82 |
+
alpha:
|
| 83 |
+
Blending factor used for each sample, shape (N,).
|
| 84 |
+
p, q:
|
| 85 |
+
Modality-aware inputs after uniform substitution (Eq. 15), shape (N, 2).
|
| 86 |
+
errors:
|
| 87 |
+
Final Sinkhorn marginal violation per sample, shape (N,).
|
| 88 |
+
fallback:
|
| 89 |
+
True where the outer-product fallback plan was used, shape (N,).
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
fused: np.ndarray
|
| 93 |
+
plans: np.ndarray
|
| 94 |
+
costs: np.ndarray
|
| 95 |
+
alpha: np.ndarray
|
| 96 |
+
p: np.ndarray
|
| 97 |
+
q: np.ndarray
|
| 98 |
+
errors: np.ndarray
|
| 99 |
+
fallback: np.ndarray
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def prob_positive(self) -> np.ndarray:
|
| 103 |
+
"""Fused probability of the positive (malignant) class, shape (N,)."""
|
| 104 |
+
return self.fused[:, 1]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# ---------------------------------------------------------------------------
|
| 108 |
+
# Input handling
|
| 109 |
+
# ---------------------------------------------------------------------------
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def to_distribution(probs: np.ndarray) -> np.ndarray:
|
| 113 |
+
"""Convert model output to probability vectors in Delta^2 (Eq. 13).
|
| 114 |
+
|
| 115 |
+
Accepts positive-class probabilities of shape (N,) or (N, 1), or full
|
| 116 |
+
two-class vectors of shape (N, 2). NaN entries are preserved so that they
|
| 117 |
+
can be treated as a missing modality.
|
| 118 |
+
"""
|
| 119 |
+
probs = np.asarray(probs, dtype=np.float64)
|
| 120 |
+
if probs.ndim == 2 and probs.shape[1] == 2:
|
| 121 |
+
return probs.copy()
|
| 122 |
+
if probs.ndim == 2 and probs.shape[1] == 1:
|
| 123 |
+
probs = probs[:, 0]
|
| 124 |
+
if probs.ndim != 1:
|
| 125 |
+
raise ValueError("expected shape (N,), (N, 1) or (N, 2)")
|
| 126 |
+
return np.column_stack([1.0 - probs, probs])
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def modality_mask(p: np.ndarray, q: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 130 |
+
"""Binary modality mask m = [m_p, m_q] (Eq. 14), inferred from NaNs.
|
| 131 |
+
|
| 132 |
+
A modality is considered present for a sample when its probability vector
|
| 133 |
+
contains no NaN.
|
| 134 |
+
"""
|
| 135 |
+
m_p = ~np.isnan(p).any(axis=1)
|
| 136 |
+
m_q = ~np.isnan(q).any(axis=1)
|
| 137 |
+
return m_p, m_q
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def substitute_missing(
|
| 141 |
+
p: np.ndarray, q: np.ndarray, m_p: np.ndarray, m_q: np.ndarray
|
| 142 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 143 |
+
"""Replace missing modalities with the uniform distribution u = [0.5, 0.5] (Eq. 15)."""
|
| 144 |
+
m_p = np.asarray(m_p, dtype=bool)[:, None]
|
| 145 |
+
m_q = np.asarray(m_q, dtype=bool)[:, None]
|
| 146 |
+
p_tilde = np.where(m_p, np.nan_to_num(p), UNIFORM)
|
| 147 |
+
q_tilde = np.where(m_q, np.nan_to_num(q), UNIFORM)
|
| 148 |
+
return p_tilde, q_tilde
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ---------------------------------------------------------------------------
|
| 152 |
+
# Eqs. 16-17
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def dynamic_alpha(p: np.ndarray, q: np.ndarray, eps: float = 1e-8) -> np.ndarray:
|
| 157 |
+
"""Confidence-weighted fusion factor (Eq. 16).
|
| 158 |
+
|
| 159 |
+
alpha = 2|p_1 - 0.5| / (2|p_1 - 0.5| + 2|q_1 - 0.5| + eps)
|
| 160 |
+
|
| 161 |
+
Higher alpha means the histopathology prediction is the more confident one.
|
| 162 |
+
"""
|
| 163 |
+
conf_p = 2.0 * np.abs(p[:, 1] - 0.5)
|
| 164 |
+
conf_q = 2.0 * np.abs(q[:, 1] - 0.5)
|
| 165 |
+
return conf_p / (conf_p + conf_q + eps)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def semantic_cost(fp_weight: float, fn_weight: float) -> np.ndarray:
|
| 169 |
+
"""Clinical penalty matrix C_semantic = [[0, w_p], [w_n, 0]] (Eq. 17)."""
|
| 170 |
+
return np.array([[0.0, fp_weight], [fn_weight, 0.0]])
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def cost_matrix(
|
| 174 |
+
p: np.ndarray, q: np.ndarray, alpha: np.ndarray, fp_weight: float, fn_weight: float
|
| 175 |
+
) -> np.ndarray:
|
| 176 |
+
"""Per-sample cost matrix (Eq. 17).
|
| 177 |
+
|
| 178 |
+
C_ij = alpha * (p_i - q_j)^2 + (1 - alpha) * C_semantic_ij
|
| 179 |
+
"""
|
| 180 |
+
divergence = (p[:, :, None] - q[:, None, :]) ** 2
|
| 181 |
+
a = np.asarray(alpha, dtype=np.float64)[:, None, None]
|
| 182 |
+
return a * divergence + (1.0 - a) * semantic_cost(fp_weight, fn_weight)[None, :, :]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# ---------------------------------------------------------------------------
|
| 186 |
+
# Full fusion
|
| 187 |
+
# ---------------------------------------------------------------------------
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def sinkhorn_fusion(
|
| 191 |
+
p_hist: np.ndarray,
|
| 192 |
+
p_risk: np.ndarray,
|
| 193 |
+
config: Optional[FusionConfig] = None,
|
| 194 |
+
m_p: Optional[np.ndarray] = None,
|
| 195 |
+
m_q: Optional[np.ndarray] = None,
|
| 196 |
+
) -> FusionResult:
|
| 197 |
+
"""Fuse histopathology and clinical-risk predictions (Eqs. 13-19).
|
| 198 |
+
|
| 199 |
+
Parameters
|
| 200 |
+
----------
|
| 201 |
+
p_hist, p_risk:
|
| 202 |
+
Model outputs, shape (N,), (N, 1) or (N, 2). NaN marks a missing modality.
|
| 203 |
+
config:
|
| 204 |
+
Fusion hyperparameters. Defaults to the values reported in the paper.
|
| 205 |
+
m_p, m_q:
|
| 206 |
+
Optional explicit modality masks (Eq. 14). If omitted they are inferred
|
| 207 |
+
from NaNs. When given, they are combined with the NaN mask, so a NaN
|
| 208 |
+
input is always treated as missing.
|
| 209 |
+
|
| 210 |
+
Returns
|
| 211 |
+
-------
|
| 212 |
+
FusionResult
|
| 213 |
+
"""
|
| 214 |
+
cfg = config or FusionConfig()
|
| 215 |
+
|
| 216 |
+
p = to_distribution(p_hist)
|
| 217 |
+
q = to_distribution(p_risk)
|
| 218 |
+
if p.shape != q.shape:
|
| 219 |
+
raise ValueError("p_hist and p_risk must contain the same number of samples")
|
| 220 |
+
|
| 221 |
+
nan_p, nan_q = modality_mask(p, q)
|
| 222 |
+
m_p = nan_p if m_p is None else (np.asarray(m_p, dtype=bool) & nan_p)
|
| 223 |
+
m_q = nan_q if m_q is None else (np.asarray(m_q, dtype=bool) & nan_q)
|
| 224 |
+
|
| 225 |
+
p_tilde, q_tilde = substitute_missing(p, q, m_p, m_q)
|
| 226 |
+
|
| 227 |
+
if cfg.alpha == "dynamic":
|
| 228 |
+
alpha = dynamic_alpha(p_tilde, q_tilde, cfg.eps)
|
| 229 |
+
else:
|
| 230 |
+
alpha = np.full(p_tilde.shape[0], float(cfg.alpha))
|
| 231 |
+
|
| 232 |
+
costs = cost_matrix(p_tilde, q_tilde, alpha, cfg.fp_weight, cfg.fn_weight)
|
| 233 |
+
|
| 234 |
+
result = sinkhorn_log(
|
| 235 |
+
p_tilde, q_tilde, costs, reg=cfg.reg, max_iter=cfg.max_iter, stop_thr=cfg.stop_thr
|
| 236 |
+
)
|
| 237 |
+
plans = result.plans.copy()
|
| 238 |
+
|
| 239 |
+
fallback = ~np.isfinite(plans).all(axis=(1, 2)) | (result.errors > cfg.fallback_tol)
|
| 240 |
+
if fallback.any():
|
| 241 |
+
plans[fallback] = p_tilde[fallback, :, None] * q_tilde[fallback, None, :]
|
| 242 |
+
|
| 243 |
+
# Eq. 19: row marginal of the plan, normalised to the simplex
|
| 244 |
+
row = plans.sum(axis=2)
|
| 245 |
+
fused = row / row.sum(axis=1, keepdims=True)
|
| 246 |
+
|
| 247 |
+
return FusionResult(
|
| 248 |
+
fused=fused,
|
| 249 |
+
plans=plans,
|
| 250 |
+
costs=costs,
|
| 251 |
+
alpha=alpha,
|
| 252 |
+
p=p_tilde,
|
| 253 |
+
q=q_tilde,
|
| 254 |
+
errors=result.errors,
|
| 255 |
+
fallback=fallback,
|
| 256 |
+
)
|
src/otfusion/metrics.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation metrics, bootstrap confidence intervals, paired comparison and
|
| 2 |
+
decision curve analysis.
|
| 3 |
+
|
| 4 |
+
The paper reports PR-AUC, recall, F1 and Brier score with 95% bootstrap
|
| 5 |
+
confidence intervals (1000 resamples), paired t-tests between models, and
|
| 6 |
+
decision curve analysis (DCA).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import Callable, Dict, Optional, Sequence
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from scipy.stats import ttest_rel
|
| 15 |
+
from sklearn.metrics import (
|
| 16 |
+
average_precision_score,
|
| 17 |
+
brier_score_loss,
|
| 18 |
+
f1_score,
|
| 19 |
+
precision_score,
|
| 20 |
+
recall_score,
|
| 21 |
+
roc_auc_score,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
MetricFn = Callable[[np.ndarray, np.ndarray], float]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _threshold_metric(fn, threshold: float) -> MetricFn:
|
| 28 |
+
return lambda y, p: float(fn(y, (p >= threshold).astype(int), zero_division=0))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _specificity(threshold: float) -> MetricFn:
|
| 32 |
+
def spec(y: np.ndarray, p: np.ndarray) -> float:
|
| 33 |
+
pred = p >= threshold
|
| 34 |
+
neg = y == 0
|
| 35 |
+
return float((~pred & neg).sum() / neg.sum()) if neg.any() else float("nan")
|
| 36 |
+
|
| 37 |
+
return spec
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def metric_functions(threshold: float = 0.5) -> Dict[str, MetricFn]:
|
| 41 |
+
"""Metric name -> function(y_true, prob_positive)."""
|
| 42 |
+
return {
|
| 43 |
+
"pr_auc": lambda y, p: float(average_precision_score(y, p)),
|
| 44 |
+
"roc_auc": lambda y, p: float(roc_auc_score(y, p)),
|
| 45 |
+
"recall": _threshold_metric(recall_score, threshold),
|
| 46 |
+
"precision": _threshold_metric(precision_score, threshold),
|
| 47 |
+
"f1": _threshold_metric(f1_score, threshold),
|
| 48 |
+
"specificity": _specificity(threshold),
|
| 49 |
+
"brier": lambda y, p: float(brier_score_loss(y, p)),
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def binary_metrics(y: np.ndarray, p: np.ndarray, threshold: float = 0.5) -> Dict[str, float]:
|
| 54 |
+
"""Point estimates of all metrics for positive-class probabilities ``p``."""
|
| 55 |
+
y = np.asarray(y).astype(int)
|
| 56 |
+
p = np.asarray(p, dtype=np.float64)
|
| 57 |
+
return {name: fn(y, p) for name, fn in metric_functions(threshold).items()}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _bootstrap_indices(n: int, y: np.ndarray, n_boot: int, rng: np.random.Generator):
|
| 61 |
+
"""Yield bootstrap index arrays, skipping resamples that contain only one class."""
|
| 62 |
+
drawn = 0
|
| 63 |
+
while drawn < n_boot:
|
| 64 |
+
idx = rng.integers(0, n, n)
|
| 65 |
+
if np.unique(y[idx]).size < 2:
|
| 66 |
+
continue
|
| 67 |
+
drawn += 1
|
| 68 |
+
yield idx
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def bootstrap_metrics(
|
| 72 |
+
y: np.ndarray,
|
| 73 |
+
p: np.ndarray,
|
| 74 |
+
threshold: float = 0.5,
|
| 75 |
+
n_boot: int = 1000,
|
| 76 |
+
ci: float = 0.95,
|
| 77 |
+
seed: Optional[int] = 0,
|
| 78 |
+
) -> Dict[str, Dict[str, float]]:
|
| 79 |
+
"""Point estimate and percentile bootstrap CI for every metric.
|
| 80 |
+
|
| 81 |
+
Returns ``{metric: {"value", "ci_low", "ci_high"}}``.
|
| 82 |
+
"""
|
| 83 |
+
y = np.asarray(y).astype(int)
|
| 84 |
+
p = np.asarray(p, dtype=np.float64)
|
| 85 |
+
fns = metric_functions(threshold)
|
| 86 |
+
rng = np.random.default_rng(seed)
|
| 87 |
+
|
| 88 |
+
reps = {name: [] for name in fns}
|
| 89 |
+
for idx in _bootstrap_indices(len(y), y, n_boot, rng):
|
| 90 |
+
for name, fn in fns.items():
|
| 91 |
+
reps[name].append(fn(y[idx], p[idx]))
|
| 92 |
+
|
| 93 |
+
lo, hi = 100 * (1 - ci) / 2, 100 * (1 + ci) / 2
|
| 94 |
+
out = {}
|
| 95 |
+
for name, fn in fns.items():
|
| 96 |
+
values = np.asarray(reps[name])
|
| 97 |
+
out[name] = {
|
| 98 |
+
"value": fn(y, p),
|
| 99 |
+
"ci_low": float(np.nanpercentile(values, lo)),
|
| 100 |
+
"ci_high": float(np.nanpercentile(values, hi)),
|
| 101 |
+
}
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def paired_comparison(
|
| 106 |
+
y: np.ndarray,
|
| 107 |
+
p_a: np.ndarray,
|
| 108 |
+
p_b: np.ndarray,
|
| 109 |
+
metric: str = "pr_auc",
|
| 110 |
+
threshold: float = 0.5,
|
| 111 |
+
n_boot: int = 1000,
|
| 112 |
+
ci: float = 0.95,
|
| 113 |
+
seed: Optional[int] = 0,
|
| 114 |
+
) -> Dict[str, float]:
|
| 115 |
+
"""Compare two models evaluated on the same samples.
|
| 116 |
+
|
| 117 |
+
Both models are scored on the *same* bootstrap resamples, so the
|
| 118 |
+
replicates are paired.
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
dict with
|
| 123 |
+
``diff`` metric(a) - metric(b) on the full sample
|
| 124 |
+
``ci_low/ci_high`` percentile bootstrap CI of the difference
|
| 125 |
+
``p_bootstrap`` two-sided bootstrap p-value for "no difference"
|
| 126 |
+
``t_stat/p_ttest`` paired t-test on the bootstrap replicates
|
| 127 |
+
|
| 128 |
+
Note
|
| 129 |
+
----
|
| 130 |
+
The paired t-test is included because the paper reports paired t-tests.
|
| 131 |
+
Its p-value shrinks as ``n_boot`` grows, because the replicates are not
|
| 132 |
+
independent observations; the bootstrap CI and ``p_bootstrap`` are the
|
| 133 |
+
more interpretable summaries.
|
| 134 |
+
"""
|
| 135 |
+
y = np.asarray(y).astype(int)
|
| 136 |
+
p_a = np.asarray(p_a, dtype=np.float64)
|
| 137 |
+
p_b = np.asarray(p_b, dtype=np.float64)
|
| 138 |
+
fn = metric_functions(threshold)[metric]
|
| 139 |
+
rng = np.random.default_rng(seed)
|
| 140 |
+
|
| 141 |
+
a_reps, b_reps = [], []
|
| 142 |
+
for idx in _bootstrap_indices(len(y), y, n_boot, rng):
|
| 143 |
+
a_reps.append(fn(y[idx], p_a[idx]))
|
| 144 |
+
b_reps.append(fn(y[idx], p_b[idx]))
|
| 145 |
+
a_reps, b_reps = np.asarray(a_reps), np.asarray(b_reps)
|
| 146 |
+
diffs = a_reps - b_reps
|
| 147 |
+
|
| 148 |
+
lo, hi = 100 * (1 - ci) / 2, 100 * (1 + ci) / 2
|
| 149 |
+
p_boot = 2 * min(np.mean(diffs <= 0), np.mean(diffs >= 0))
|
| 150 |
+
t_stat, p_t = ttest_rel(a_reps, b_reps)
|
| 151 |
+
|
| 152 |
+
return {
|
| 153 |
+
"metric": metric,
|
| 154 |
+
"value_a": fn(y, p_a),
|
| 155 |
+
"value_b": fn(y, p_b),
|
| 156 |
+
"diff": fn(y, p_a) - fn(y, p_b),
|
| 157 |
+
"ci_low": float(np.percentile(diffs, lo)),
|
| 158 |
+
"ci_high": float(np.percentile(diffs, hi)),
|
| 159 |
+
"p_bootstrap": float(min(1.0, p_boot)),
|
| 160 |
+
"t_stat": float(t_stat),
|
| 161 |
+
"p_ttest": float(p_t),
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ---------------------------------------------------------------------------
|
| 166 |
+
# Decision curve analysis
|
| 167 |
+
# ---------------------------------------------------------------------------
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def net_benefit(y: np.ndarray, p: np.ndarray, thresholds: Sequence[float]) -> np.ndarray:
|
| 171 |
+
"""Net benefit of treating patients with ``p >= t`` at each threshold t.
|
| 172 |
+
|
| 173 |
+
NB(t) = TP/N - FP/N * t / (1 - t)
|
| 174 |
+
"""
|
| 175 |
+
y = np.asarray(y).astype(int)
|
| 176 |
+
p = np.asarray(p, dtype=np.float64)
|
| 177 |
+
n = len(y)
|
| 178 |
+
out = []
|
| 179 |
+
for t in thresholds:
|
| 180 |
+
treat = p >= t
|
| 181 |
+
tp = np.sum(treat & (y == 1))
|
| 182 |
+
fp = np.sum(treat & (y == 0))
|
| 183 |
+
out.append(tp / n - fp / n * t / (1 - t))
|
| 184 |
+
return np.asarray(out)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def net_benefit_treat_all(y: np.ndarray, thresholds: Sequence[float]) -> np.ndarray:
|
| 188 |
+
"""Net benefit of treating everyone: prevalence - (1 - prevalence) * t / (1 - t)."""
|
| 189 |
+
prev = float(np.mean(np.asarray(y).astype(int)))
|
| 190 |
+
t = np.asarray(thresholds, dtype=np.float64)
|
| 191 |
+
return prev - (1 - prev) * t / (1 - t)
|
src/otfusion/pipeline.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end evaluation of the fusion layer on saved model predictions.
|
| 2 |
+
|
| 3 |
+
Steps
|
| 4 |
+
-----
|
| 5 |
+
1. Fuse the test-set predictions (Eqs. 13-19).
|
| 6 |
+
2. Calibrate the fused probabilities with isotonic regression, fitted on a
|
| 7 |
+
separate calibration split if one is given, otherwise cross-fitted.
|
| 8 |
+
3. Score the fused model and the baselines (histopathology only, risk only,
|
| 9 |
+
simple average, max rule) with bootstrap CIs.
|
| 10 |
+
4. Compare the fused model against each baseline (paired bootstrap).
|
| 11 |
+
5. Repeat the fusion under simulated modality dropout.
|
| 12 |
+
6. Record runtime and save figures and a JSON summary.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
from dataclasses import asdict
|
| 21 |
+
from typing import Dict, Optional, Sequence, Tuple
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from .calibration import IsotonicCalibrator, cross_fitted_calibration
|
| 26 |
+
from .dropout import simulate_dropout
|
| 27 |
+
from .fusion import FusionConfig, sinkhorn_fusion, to_distribution
|
| 28 |
+
from .metrics import bootstrap_metrics, paired_comparison
|
| 29 |
+
|
| 30 |
+
CalibrationSet = Tuple[np.ndarray, np.ndarray, np.ndarray]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _positive(probs: np.ndarray) -> np.ndarray:
|
| 34 |
+
return to_distribution(probs)[:, 1]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class _Calibrate:
|
| 38 |
+
"""Applies a calibrator fitted on a calibration split, or cross-fits on the data itself."""
|
| 39 |
+
|
| 40 |
+
def __init__(self, cfg: FusionConfig, calibration: Optional[CalibrationSet], seed: int):
|
| 41 |
+
self.seed = seed
|
| 42 |
+
self.calibrator = None
|
| 43 |
+
if calibration is not None:
|
| 44 |
+
h_cal, r_cal, y_cal = calibration
|
| 45 |
+
fused_cal = sinkhorn_fusion(h_cal, r_cal, cfg).prob_positive
|
| 46 |
+
self.calibrator = IsotonicCalibrator().fit(fused_cal, y_cal)
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def method(self) -> str:
|
| 50 |
+
return "separate calibration split" if self.calibrator else "5-fold cross-fitting"
|
| 51 |
+
|
| 52 |
+
def __call__(self, probs: np.ndarray, y: np.ndarray) -> np.ndarray:
|
| 53 |
+
if self.calibrator is not None:
|
| 54 |
+
return self.calibrator.transform(probs)
|
| 55 |
+
return cross_fitted_calibration(probs, y, seed=self.seed)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def run_evaluation(
|
| 59 |
+
p_hist: np.ndarray,
|
| 60 |
+
p_risk: np.ndarray,
|
| 61 |
+
y: np.ndarray,
|
| 62 |
+
config: Optional[FusionConfig] = None,
|
| 63 |
+
calibration: Optional[CalibrationSet] = None,
|
| 64 |
+
dropout_rates: Sequence[float] = (0.0, 0.2, 0.5),
|
| 65 |
+
dropout_mode: str = "either",
|
| 66 |
+
threshold: float = 0.5,
|
| 67 |
+
n_boot: int = 1000,
|
| 68 |
+
seed: int = 42,
|
| 69 |
+
out_dir: Optional[str] = None,
|
| 70 |
+
make_figures: bool = True,
|
| 71 |
+
) -> Dict:
|
| 72 |
+
"""Run the full evaluation and return a results dictionary.
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
p_hist, p_risk, y:
|
| 77 |
+
Test-set predictions of each model and the reference labels.
|
| 78 |
+
config:
|
| 79 |
+
Fusion hyperparameters (paper defaults if omitted).
|
| 80 |
+
calibration:
|
| 81 |
+
Optional ``(p_hist_cal, p_risk_cal, y_cal)`` used only to fit the
|
| 82 |
+
isotonic calibrator. Without it, calibration is cross-fitted on the
|
| 83 |
+
test set.
|
| 84 |
+
dropout_rates, dropout_mode:
|
| 85 |
+
Modality dropout settings (see :func:`otfusion.dropout.simulate_dropout`).
|
| 86 |
+
threshold:
|
| 87 |
+
Decision threshold for recall, precision, F1 and specificity.
|
| 88 |
+
n_boot:
|
| 89 |
+
Bootstrap resamples for confidence intervals (1000 in the paper).
|
| 90 |
+
seed:
|
| 91 |
+
Seed for bootstrap, dropout masks and cross-fitting.
|
| 92 |
+
out_dir:
|
| 93 |
+
If given, ``results.json`` and figures are written here.
|
| 94 |
+
"""
|
| 95 |
+
cfg = config or FusionConfig()
|
| 96 |
+
y = np.asarray(y).astype(int)
|
| 97 |
+
calibrate = _Calibrate(cfg, calibration, seed)
|
| 98 |
+
|
| 99 |
+
# 1. Fusion -------------------------------------------------------------
|
| 100 |
+
t0 = time.perf_counter()
|
| 101 |
+
fusion = sinkhorn_fusion(p_hist, p_risk, cfg)
|
| 102 |
+
fusion_seconds = time.perf_counter() - t0
|
| 103 |
+
|
| 104 |
+
fused_raw = fusion.prob_positive
|
| 105 |
+
fused_cal = calibrate(fused_raw, y)
|
| 106 |
+
|
| 107 |
+
# 2. Models and baselines ----------------------------------------------
|
| 108 |
+
hist = _positive(p_hist)
|
| 109 |
+
risk = _positive(p_risk)
|
| 110 |
+
models = {
|
| 111 |
+
"sinkhorn_fusion_calibrated": fused_cal,
|
| 112 |
+
"sinkhorn_fusion_raw": fused_raw,
|
| 113 |
+
"histopathology_only": hist,
|
| 114 |
+
"risk_only": risk,
|
| 115 |
+
"average": 0.5 * (hist + risk),
|
| 116 |
+
"max_rule": np.maximum(hist, risk),
|
| 117 |
+
}
|
| 118 |
+
scores = {
|
| 119 |
+
name: bootstrap_metrics(y, p, threshold=threshold, n_boot=n_boot, seed=seed)
|
| 120 |
+
for name, p in models.items()
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
# 3. Paired comparisons -------------------------------------------------
|
| 124 |
+
comparisons = {}
|
| 125 |
+
for name in ("histopathology_only", "risk_only", "average", "max_rule"):
|
| 126 |
+
comparisons[f"sinkhorn_fusion_raw_vs_{name}"] = paired_comparison(
|
| 127 |
+
y, fused_raw, models[name], metric="pr_auc", threshold=threshold, n_boot=n_boot, seed=seed
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# 4. Modality dropout ---------------------------------------------------
|
| 131 |
+
rng = np.random.default_rng(seed)
|
| 132 |
+
dropout = {}
|
| 133 |
+
baseline_dropout = None
|
| 134 |
+
for rate in dropout_rates:
|
| 135 |
+
m_p, m_q = simulate_dropout(len(y), rate, mode=dropout_mode, rng=rng)
|
| 136 |
+
fused_d = calibrate(sinkhorn_fusion(p_hist, p_risk, cfg, m_p=m_p, m_q=m_q).prob_positive, y)
|
| 137 |
+
if baseline_dropout is None:
|
| 138 |
+
baseline_dropout = fused_d
|
| 139 |
+
entry = {
|
| 140 |
+
"rate": rate,
|
| 141 |
+
"n_hist_missing": int((~m_p).sum()),
|
| 142 |
+
"n_risk_missing": int((~m_q).sum()),
|
| 143 |
+
"metrics": bootstrap_metrics(y, fused_d, threshold=threshold, n_boot=n_boot, seed=seed),
|
| 144 |
+
}
|
| 145 |
+
if rate != dropout_rates[0]:
|
| 146 |
+
entry["vs_first_rate_pr_auc"] = paired_comparison(
|
| 147 |
+
y, fused_d, baseline_dropout, metric="pr_auc", threshold=threshold, n_boot=n_boot, seed=seed
|
| 148 |
+
)
|
| 149 |
+
dropout[f"{rate:g}"] = entry
|
| 150 |
+
|
| 151 |
+
# 5. Runtime ------------------------------------------------------------
|
| 152 |
+
t0 = time.perf_counter()
|
| 153 |
+
for i in range(min(100, len(y))):
|
| 154 |
+
sinkhorn_fusion(np.atleast_1d(hist[i]), np.atleast_1d(risk[i]), cfg)
|
| 155 |
+
single_ms = 1000 * (time.perf_counter() - t0) / max(1, min(100, len(y)))
|
| 156 |
+
|
| 157 |
+
results = {
|
| 158 |
+
"config": asdict(cfg),
|
| 159 |
+
"n_samples": int(len(y)),
|
| 160 |
+
"prevalence": float(y.mean()),
|
| 161 |
+
"threshold": threshold,
|
| 162 |
+
"calibration_method": calibrate.method,
|
| 163 |
+
"fusion_diagnostics": {
|
| 164 |
+
"mean_sinkhorn_error": float(np.mean(fusion.errors)),
|
| 165 |
+
"max_sinkhorn_error": float(np.max(fusion.errors)),
|
| 166 |
+
"n_fallback": int(fusion.fallback.sum()),
|
| 167 |
+
"average_transport_plan": np.mean(fusion.plans, axis=0).tolist(),
|
| 168 |
+
},
|
| 169 |
+
"metrics": scores,
|
| 170 |
+
"comparisons": comparisons,
|
| 171 |
+
"dropout": {"mode": dropout_mode, "results": dropout},
|
| 172 |
+
"runtime": {
|
| 173 |
+
"batch_fusion_seconds": fusion_seconds,
|
| 174 |
+
"batch_ms_per_sample": 1000 * fusion_seconds / len(y),
|
| 175 |
+
"single_sample_ms": single_ms,
|
| 176 |
+
},
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
if out_dir:
|
| 180 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 181 |
+
with open(os.path.join(out_dir, "results.json"), "w") as fh:
|
| 182 |
+
json.dump(results, fh, indent=2)
|
| 183 |
+
if make_figures:
|
| 184 |
+
from . import plots
|
| 185 |
+
|
| 186 |
+
plots.plot_calibration(
|
| 187 |
+
y,
|
| 188 |
+
{"Fusion (raw)": fused_raw, "Fusion (calibrated)": fused_cal},
|
| 189 |
+
save_path=os.path.join(out_dir, "calibration_curve.png"),
|
| 190 |
+
)
|
| 191 |
+
curves = {
|
| 192 |
+
"Fusion (calibrated)": fused_cal,
|
| 193 |
+
"Histopathology only": hist,
|
| 194 |
+
"Risk only": risk,
|
| 195 |
+
}
|
| 196 |
+
plots.plot_pr_curve(y, curves, save_path=os.path.join(out_dir, "pr_curve.png"))
|
| 197 |
+
plots.plot_decision_curve(y, curves, save_path=os.path.join(out_dir, "decision_curve.png"))
|
| 198 |
+
plots.plot_average_transport_plan(
|
| 199 |
+
fusion.plans, save_path=os.path.join(out_dir, "average_transport_plan.png")
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
return results
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def format_summary(results: Dict) -> str:
|
| 206 |
+
"""Short plain-text summary of a results dictionary."""
|
| 207 |
+
keys = ("pr_auc", "recall", "f1", "brier")
|
| 208 |
+
lines = [
|
| 209 |
+
f"Samples: {results['n_samples']} prevalence: {results['prevalence']:.3f} "
|
| 210 |
+
f"calibration: {results['calibration_method']}",
|
| 211 |
+
"",
|
| 212 |
+
f"{'model':30s}" + "".join(f"{k:>24s}" for k in keys),
|
| 213 |
+
]
|
| 214 |
+
for name, m in results["metrics"].items():
|
| 215 |
+
cells = "".join(
|
| 216 |
+
f"{m[k]['value']:>8.3f} [{m[k]['ci_low']:.3f}-{m[k]['ci_high']:.3f}]".rjust(24) for k in keys
|
| 217 |
+
)
|
| 218 |
+
lines.append(f"{name:30s}{cells}")
|
| 219 |
+
lines += ["", "Modality dropout (fused, calibrated):"]
|
| 220 |
+
for rate, entry in results["dropout"]["results"].items():
|
| 221 |
+
m = entry["metrics"]
|
| 222 |
+
line = (
|
| 223 |
+
f" rate {rate:>4s}: PR-AUC {m['pr_auc']['value']:.3f} "
|
| 224 |
+
f"[{m['pr_auc']['ci_low']:.3f}-{m['pr_auc']['ci_high']:.3f}] recall {m['recall']['value']:.3f}"
|
| 225 |
+
)
|
| 226 |
+
if "vs_first_rate_pr_auc" in entry:
|
| 227 |
+
c = entry["vs_first_rate_pr_auc"]
|
| 228 |
+
line += f" diff {c['diff']:+.3f} [{c['ci_low']:+.3f}, {c['ci_high']:+.3f}]"
|
| 229 |
+
lines.append(line)
|
| 230 |
+
rt = results["runtime"]
|
| 231 |
+
lines += [
|
| 232 |
+
"",
|
| 233 |
+
f"Runtime: {rt['batch_ms_per_sample']:.3f} ms/sample (batch), "
|
| 234 |
+
f"{rt['single_sample_ms']:.3f} ms (single sample)",
|
| 235 |
+
]
|
| 236 |
+
return "\n".join(lines)
|
src/otfusion/plots.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Figures: calibration curve, precision-recall curve, decision curve and
|
| 2 |
+
average transport plan. Each function returns the matplotlib Figure and
|
| 3 |
+
optionally saves it.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import Mapping, Optional, Sequence
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import matplotlib
|
| 12 |
+
|
| 13 |
+
matplotlib.use("Agg")
|
| 14 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 15 |
+
from sklearn.calibration import calibration_curve # noqa: E402
|
| 16 |
+
from sklearn.metrics import average_precision_score, precision_recall_curve # noqa: E402
|
| 17 |
+
|
| 18 |
+
from .metrics import net_benefit, net_benefit_treat_all # noqa: E402
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _finish(fig, save_path: Optional[str]):
|
| 22 |
+
fig.tight_layout()
|
| 23 |
+
if save_path:
|
| 24 |
+
fig.savefig(save_path, dpi=300)
|
| 25 |
+
return fig
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def plot_calibration(
|
| 29 |
+
y: np.ndarray,
|
| 30 |
+
probs: Mapping[str, np.ndarray],
|
| 31 |
+
n_bins: int = 10,
|
| 32 |
+
save_path: Optional[str] = None,
|
| 33 |
+
):
|
| 34 |
+
"""Reliability diagram for one or more models (``{label: prob_positive}``)."""
|
| 35 |
+
fig, ax = plt.subplots(figsize=(5, 5))
|
| 36 |
+
for label, p in probs.items():
|
| 37 |
+
frac_pos, mean_pred = calibration_curve(y, p, n_bins=n_bins)
|
| 38 |
+
ax.plot(mean_pred, frac_pos, "o-", label=label)
|
| 39 |
+
ax.plot([0, 1], [0, 1], "k--", label="Perfect calibration")
|
| 40 |
+
ax.set(xlabel="Predicted probability", ylabel="Observed frequency", title="Calibration curve")
|
| 41 |
+
ax.grid(True)
|
| 42 |
+
ax.legend()
|
| 43 |
+
return _finish(fig, save_path)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def plot_pr_curve(y: np.ndarray, probs: Mapping[str, np.ndarray], save_path: Optional[str] = None):
|
| 47 |
+
"""Precision-recall curves with PR-AUC in the legend."""
|
| 48 |
+
fig, ax = plt.subplots(figsize=(5, 5))
|
| 49 |
+
for label, p in probs.items():
|
| 50 |
+
precision, recall, _ = precision_recall_curve(y, p)
|
| 51 |
+
ax.plot(recall, precision, label=f"{label} (PR-AUC={average_precision_score(y, p):.3f})")
|
| 52 |
+
ax.axhline(np.mean(y), color="gray", linestyle=":", label="Prevalence")
|
| 53 |
+
ax.set(xlabel="Recall", ylabel="Precision", title="Precision-recall curve")
|
| 54 |
+
ax.grid(True)
|
| 55 |
+
ax.legend()
|
| 56 |
+
return _finish(fig, save_path)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def plot_decision_curve(
|
| 60 |
+
y: np.ndarray,
|
| 61 |
+
probs: Mapping[str, np.ndarray],
|
| 62 |
+
thresholds: Optional[Sequence[float]] = None,
|
| 63 |
+
save_path: Optional[str] = None,
|
| 64 |
+
):
|
| 65 |
+
"""Decision curve with treat-all and treat-none references."""
|
| 66 |
+
t = np.linspace(0.01, 0.99, 99) if thresholds is None else np.asarray(thresholds)
|
| 67 |
+
fig, ax = plt.subplots(figsize=(7, 5))
|
| 68 |
+
curves = []
|
| 69 |
+
for label, p in probs.items():
|
| 70 |
+
nb = net_benefit(y, p, t)
|
| 71 |
+
curves.append(nb)
|
| 72 |
+
ax.plot(t, nb, linewidth=2, label=label)
|
| 73 |
+
treat_all = net_benefit_treat_all(y, t)
|
| 74 |
+
ax.plot(t, treat_all, "--", label="Treat all")
|
| 75 |
+
ax.plot(t, np.zeros_like(t), "k--", label="Treat none")
|
| 76 |
+
top = max([np.max(c) for c in curves] + [np.max(treat_all)])
|
| 77 |
+
ax.set_ylim(-0.05, top + 0.05)
|
| 78 |
+
ax.set(xlabel="Threshold probability", ylabel="Net benefit", title="Decision curve analysis")
|
| 79 |
+
ax.grid(True)
|
| 80 |
+
ax.legend()
|
| 81 |
+
return _finish(fig, save_path)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def plot_average_transport_plan(plans: np.ndarray, save_path: Optional[str] = None):
|
| 85 |
+
"""Heatmap of the mean transport plan across samples (rows: histopathology, cols: risk)."""
|
| 86 |
+
avg = np.mean(plans, axis=0)
|
| 87 |
+
fig, ax = plt.subplots(figsize=(4.5, 4))
|
| 88 |
+
im = ax.imshow(avg, cmap="viridis")
|
| 89 |
+
for i in range(avg.shape[0]):
|
| 90 |
+
for j in range(avg.shape[1]):
|
| 91 |
+
ax.text(j, i, f"{avg[i, j]:.3f}", ha="center", va="center", color="w")
|
| 92 |
+
fig.colorbar(im, ax=ax, label="Average mass transported")
|
| 93 |
+
ax.set_xticks([0, 1], ["Benign / low", "Malignant / high"])
|
| 94 |
+
ax.set_yticks([0, 1], ["Benign", "Malignant"])
|
| 95 |
+
ax.set(xlabel="Risk model class", ylabel="Histopathology model class", title="Average transport plan")
|
| 96 |
+
return _finish(fig, save_path)
|
src/otfusion/sinkhorn.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Entropic optimal transport solved with the Sinkhorn-Knopp algorithm in the log domain.
|
| 2 |
+
|
| 3 |
+
Solves, for each sample independently (Eq. 18 of the paper):
|
| 4 |
+
|
| 5 |
+
T* = argmin_{T in U(p, q)} <T, C> - reg * H(T)
|
| 6 |
+
|
| 7 |
+
U(p, q) = { T >= 0 : T 1 = p, T^T 1 = q }
|
| 8 |
+
H(T) = -sum_ij T_ij log T_ij
|
| 9 |
+
|
| 10 |
+
The solver is vectorised over a batch of N small (k x k) problems.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from scipy.special import logsumexp
|
| 19 |
+
|
| 20 |
+
_FLOOR = 1e-12
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class SinkhornResult:
|
| 25 |
+
"""Output of :func:`sinkhorn_log`.
|
| 26 |
+
|
| 27 |
+
Attributes
|
| 28 |
+
----------
|
| 29 |
+
plans:
|
| 30 |
+
Transport plans, shape (N, k, k).
|
| 31 |
+
errors:
|
| 32 |
+
Final marginal violation per sample (L1 norm of both marginals), shape (N,).
|
| 33 |
+
converged:
|
| 34 |
+
Whether each sample reached ``stop_thr`` within ``max_iter`` iterations, shape (N,).
|
| 35 |
+
n_iter:
|
| 36 |
+
Number of iterations run (the batch stops when every sample has converged).
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
plans: np.ndarray
|
| 40 |
+
errors: np.ndarray
|
| 41 |
+
converged: np.ndarray
|
| 42 |
+
n_iter: int
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _as_batch(x: np.ndarray) -> np.ndarray:
|
| 46 |
+
x = np.asarray(x, dtype=np.float64)
|
| 47 |
+
return x[None, :] if x.ndim == 1 else x
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def sinkhorn_log(
|
| 51 |
+
a: np.ndarray,
|
| 52 |
+
b: np.ndarray,
|
| 53 |
+
cost: np.ndarray,
|
| 54 |
+
reg: float = 0.15,
|
| 55 |
+
max_iter: int = 5000,
|
| 56 |
+
stop_thr: float = 1e-9,
|
| 57 |
+
) -> SinkhornResult:
|
| 58 |
+
"""Batched log-domain Sinkhorn-Knopp.
|
| 59 |
+
|
| 60 |
+
Parameters
|
| 61 |
+
----------
|
| 62 |
+
a, b:
|
| 63 |
+
Source and target marginals, shape (N, k) or (k,). Rows must sum to 1.
|
| 64 |
+
Entries are floored at 1e-12 and renormalised to keep the logarithms finite.
|
| 65 |
+
cost:
|
| 66 |
+
Cost matrices, shape (N, k, k) or (k, k).
|
| 67 |
+
reg:
|
| 68 |
+
Entropic regularisation strength (``reg`` in the paper, 0.15 by default).
|
| 69 |
+
max_iter:
|
| 70 |
+
Maximum number of Sinkhorn iterations (5000 in the paper).
|
| 71 |
+
stop_thr:
|
| 72 |
+
Convergence threshold on the marginal violation (1e-9 in the paper).
|
| 73 |
+
"""
|
| 74 |
+
if reg <= 0:
|
| 75 |
+
raise ValueError("reg must be positive")
|
| 76 |
+
|
| 77 |
+
a = _as_batch(a)
|
| 78 |
+
b = _as_batch(b)
|
| 79 |
+
cost = np.asarray(cost, dtype=np.float64)
|
| 80 |
+
if cost.ndim == 2:
|
| 81 |
+
cost = np.broadcast_to(cost, (a.shape[0],) + cost.shape)
|
| 82 |
+
|
| 83 |
+
if not (a.shape[0] == b.shape[0] == cost.shape[0]):
|
| 84 |
+
raise ValueError("a, b and cost must have the same batch size")
|
| 85 |
+
if cost.shape[1:] != (a.shape[1], b.shape[1]):
|
| 86 |
+
raise ValueError("cost must have shape (N, len(a), len(b))")
|
| 87 |
+
|
| 88 |
+
a = np.maximum(a, _FLOOR)
|
| 89 |
+
b = np.maximum(b, _FLOOR)
|
| 90 |
+
a = a / a.sum(axis=1, keepdims=True)
|
| 91 |
+
b = b / b.sum(axis=1, keepdims=True)
|
| 92 |
+
log_a, log_b = np.log(a), np.log(b)
|
| 93 |
+
|
| 94 |
+
neg_c = -cost / reg # log of the Gibbs kernel
|
| 95 |
+
f = np.zeros_like(a) # dual potentials scaled by 1/reg
|
| 96 |
+
g = np.zeros_like(b)
|
| 97 |
+
|
| 98 |
+
errors = np.full(a.shape[0], np.inf)
|
| 99 |
+
n_iter = 0
|
| 100 |
+
for n_iter in range(1, max_iter + 1):
|
| 101 |
+
f = log_a - logsumexp(neg_c + g[:, None, :], axis=2)
|
| 102 |
+
g = log_b - logsumexp(neg_c + f[:, :, None], axis=1)
|
| 103 |
+
|
| 104 |
+
log_plan = neg_c + f[:, :, None] + g[:, None, :]
|
| 105 |
+
plan = np.exp(log_plan)
|
| 106 |
+
errors = np.abs(plan.sum(axis=2) - a).sum(axis=1) + np.abs(plan.sum(axis=1) - b).sum(axis=1)
|
| 107 |
+
if np.all(errors < stop_thr):
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
plans = np.exp(neg_c + f[:, :, None] + g[:, None, :])
|
| 111 |
+
converged = np.isfinite(plans).all(axis=(1, 2)) & (errors < stop_thr)
|
| 112 |
+
return SinkhornResult(plans=plans, errors=errors, converged=converged, n_iter=n_iter)
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
|
tests/test_evaluation.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
from sklearn.metrics import average_precision_score, f1_score, recall_score
|
| 6 |
+
|
| 7 |
+
from otfusion import (
|
| 8 |
+
binary_metrics,
|
| 9 |
+
bootstrap_metrics,
|
| 10 |
+
cross_fitted_calibration,
|
| 11 |
+
net_benefit,
|
| 12 |
+
net_benefit_treat_all,
|
| 13 |
+
paired_comparison,
|
| 14 |
+
run_evaluation,
|
| 15 |
+
simulate_dropout,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.fixture
|
| 20 |
+
def data():
|
| 21 |
+
rng = np.random.default_rng(0)
|
| 22 |
+
y = (rng.random(300) < 0.7).astype(int)
|
| 23 |
+
hist = np.clip(0.6 * y + rng.normal(0.2, 0.2, 300), 0.01, 0.99)
|
| 24 |
+
risk = np.clip(0.2 * y + rng.normal(0.4, 0.2, 300), 0.01, 0.99)
|
| 25 |
+
return hist, risk, y
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------------------
|
| 29 |
+
# Dropout
|
| 30 |
+
# ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_dropout_rates_and_modes():
|
| 34 |
+
rng = np.random.default_rng(0)
|
| 35 |
+
m_p, m_q = simulate_dropout(20000, 0.2, "either", rng)
|
| 36 |
+
assert (~m_p | ~m_q).mean() == pytest.approx(0.2, abs=0.01)
|
| 37 |
+
assert not (~m_p & ~m_q).any() # "either" never drops both
|
| 38 |
+
|
| 39 |
+
m_p, m_q = simulate_dropout(1000, 0.5, "hist", rng)
|
| 40 |
+
assert m_q.all() and (~m_p).any()
|
| 41 |
+
|
| 42 |
+
m_p, m_q = simulate_dropout(1000, 0.0, "either", rng)
|
| 43 |
+
assert m_p.all() and m_q.all()
|
| 44 |
+
|
| 45 |
+
with pytest.raises(ValueError):
|
| 46 |
+
simulate_dropout(10, 1.5)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ---------------------------------------------------------------------------
|
| 50 |
+
# Metrics
|
| 51 |
+
# ---------------------------------------------------------------------------
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_binary_metrics_match_sklearn(data):
|
| 55 |
+
hist, _, y = data
|
| 56 |
+
m = binary_metrics(y, hist)
|
| 57 |
+
assert m["pr_auc"] == pytest.approx(average_precision_score(y, hist))
|
| 58 |
+
assert m["recall"] == pytest.approx(recall_score(y, hist >= 0.5))
|
| 59 |
+
assert m["f1"] == pytest.approx(f1_score(y, hist >= 0.5))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_bootstrap_ci_contains_point_estimate(data):
|
| 63 |
+
hist, _, y = data
|
| 64 |
+
out = bootstrap_metrics(y, hist, n_boot=200, seed=0)
|
| 65 |
+
for v in out.values():
|
| 66 |
+
assert v["ci_low"] <= v["value"] <= v["ci_high"] + 1e-9
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_paired_comparison_of_identical_models_is_null(data):
|
| 70 |
+
hist, _, y = data
|
| 71 |
+
c = paired_comparison(y, hist, hist, n_boot=100)
|
| 72 |
+
assert c["diff"] == 0 and c["ci_low"] == 0 and c["ci_high"] == 0
|
| 73 |
+
assert c["p_bootstrap"] == 1.0
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_net_benefit_treat_all_matches_formula(data):
|
| 77 |
+
_, _, y = data
|
| 78 |
+
t = np.linspace(0.05, 0.9, 10)
|
| 79 |
+
np.testing.assert_allclose(net_benefit(y, np.ones_like(y, dtype=float), t), net_benefit_treat_all(y, t))
|
| 80 |
+
np.testing.assert_allclose(net_benefit(y, np.zeros_like(y, dtype=float), t), 0.0)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ---------------------------------------------------------------------------
|
| 84 |
+
# Calibration and pipeline
|
| 85 |
+
# ---------------------------------------------------------------------------
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_cross_fitted_calibration_range(data):
|
| 89 |
+
hist, _, y = data
|
| 90 |
+
cal = cross_fitted_calibration(hist, y)
|
| 91 |
+
assert cal.shape == hist.shape
|
| 92 |
+
assert ((cal >= 0) & (cal <= 1)).all()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_pipeline_runs_end_to_end(data, tmp_path):
|
| 96 |
+
hist, risk, y = data
|
| 97 |
+
results = run_evaluation(hist, risk, y, n_boot=50, out_dir=str(tmp_path), calibration=(hist, risk, y))
|
| 98 |
+
assert results["calibration_method"] == "separate calibration split"
|
| 99 |
+
assert set(results["dropout"]["results"]) == {"0", "0.2", "0.5"}
|
| 100 |
+
saved = json.loads((tmp_path / "results.json").read_text())
|
| 101 |
+
assert saved["n_samples"] == 300
|
| 102 |
+
for name in ("calibration_curve", "pr_curve", "decision_curve", "average_transport_plan"):
|
| 103 |
+
assert (tmp_path / f"{name}.png").exists()
|
tests/test_fusion.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from otfusion import (
|
| 5 |
+
FusionConfig,
|
| 6 |
+
cost_matrix,
|
| 7 |
+
dynamic_alpha,
|
| 8 |
+
semantic_cost,
|
| 9 |
+
sinkhorn_fusion,
|
| 10 |
+
sinkhorn_log,
|
| 11 |
+
substitute_missing,
|
| 12 |
+
to_distribution,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def random_simplex(n, rng):
|
| 17 |
+
x = rng.uniform(0.01, 0.99, n)
|
| 18 |
+
return np.column_stack([1 - x, x])
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ---------------------------------------------------------------------------
|
| 22 |
+
# Sinkhorn solver (Eq. 18)
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_sinkhorn_satisfies_marginals():
|
| 27 |
+
rng = np.random.default_rng(0)
|
| 28 |
+
a, b = random_simplex(50, rng), random_simplex(50, rng)
|
| 29 |
+
cost = rng.uniform(0, 2, (50, 2, 2))
|
| 30 |
+
res = sinkhorn_log(a, b, cost, reg=0.15)
|
| 31 |
+
assert res.converged.all()
|
| 32 |
+
np.testing.assert_allclose(res.plans.sum(axis=2), a, atol=1e-8)
|
| 33 |
+
np.testing.assert_allclose(res.plans.sum(axis=1), b, atol=1e-8)
|
| 34 |
+
assert (res.plans >= 0).all()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_sinkhorn_minimises_entropic_objective():
|
| 38 |
+
"""For 2x2 problems the feasible set is one-dimensional, so a grid search finds the optimum."""
|
| 39 |
+
a, b = np.array([0.3, 0.7]), np.array([0.6, 0.4])
|
| 40 |
+
cost = np.array([[0.0, 1.8], [1.2, 0.0]])
|
| 41 |
+
reg = 0.15
|
| 42 |
+
plan = sinkhorn_log(a, b, cost, reg=reg).plans[0]
|
| 43 |
+
|
| 44 |
+
lo, hi = max(0.0, a[0] - b[1]), min(a[0], b[0])
|
| 45 |
+
best, best_val = None, np.inf
|
| 46 |
+
for t in np.linspace(lo + 1e-9, hi - 1e-9, 200001):
|
| 47 |
+
T = np.array([[t, a[0] - t], [b[0] - t, a[1] - b[0] + t]])
|
| 48 |
+
val = np.sum(T * cost) + reg * np.sum(T * np.log(T))
|
| 49 |
+
if val < best_val:
|
| 50 |
+
best, best_val = T, val
|
| 51 |
+
np.testing.assert_allclose(plan, best, atol=1e-5)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_sinkhorn_rejects_bad_reg():
|
| 55 |
+
with pytest.raises(ValueError):
|
| 56 |
+
sinkhorn_log(np.array([0.5, 0.5]), np.array([0.5, 0.5]), np.zeros((2, 2)), reg=0)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# ---------------------------------------------------------------------------
|
| 60 |
+
# Inputs and masking (Eqs. 13-15)
|
| 61 |
+
# ---------------------------------------------------------------------------
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_to_distribution_shapes():
|
| 65 |
+
p = np.array([0.2, 0.9])
|
| 66 |
+
expected = np.array([[0.8, 0.2], [0.1, 0.9]])
|
| 67 |
+
np.testing.assert_allclose(to_distribution(p), expected)
|
| 68 |
+
np.testing.assert_allclose(to_distribution(p[:, None]), expected)
|
| 69 |
+
np.testing.assert_allclose(to_distribution(expected), expected)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_missing_modality_replaced_by_uniform():
|
| 73 |
+
p = np.array([[0.1, 0.9], [0.8, 0.2]])
|
| 74 |
+
q = np.array([[0.3, 0.7], [np.nan, np.nan]])
|
| 75 |
+
p_t, q_t = substitute_missing(p, q, np.array([False, True]), np.array([True, False]))
|
| 76 |
+
np.testing.assert_allclose(p_t, [[0.5, 0.5], [0.8, 0.2]])
|
| 77 |
+
np.testing.assert_allclose(q_t, [[0.3, 0.7], [0.5, 0.5]])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_nan_input_treated_as_missing():
|
| 81 |
+
res = sinkhorn_fusion(np.array([np.nan, 0.9]), np.array([0.8, 0.2]))
|
| 82 |
+
np.testing.assert_allclose(res.p[0], [0.5, 0.5])
|
| 83 |
+
assert np.isfinite(res.fused).all()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
# Alpha and cost matrix (Eqs. 16-17)
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_dynamic_alpha():
|
| 92 |
+
p = np.array([[0.05, 0.95], [0.5, 0.5], [0.3, 0.7]])
|
| 93 |
+
q = np.array([[0.5, 0.5], [0.05, 0.95], [0.3, 0.7]])
|
| 94 |
+
alpha = dynamic_alpha(p, q)
|
| 95 |
+
assert alpha[0] == pytest.approx(1.0, abs=1e-6) # only histopathology is confident
|
| 96 |
+
assert alpha[1] == pytest.approx(0.0, abs=1e-6) # only risk is confident
|
| 97 |
+
assert alpha[2] == pytest.approx(0.5, abs=1e-6) # equally confident
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_cost_matrix_limits():
|
| 101 |
+
p = np.array([[0.2, 0.8]])
|
| 102 |
+
q = np.array([[0.6, 0.4]])
|
| 103 |
+
sem = semantic_cost(fp_weight=1.8, fn_weight=1.2)
|
| 104 |
+
np.testing.assert_allclose(sem, [[0, 1.8], [1.2, 0]])
|
| 105 |
+
np.testing.assert_allclose(cost_matrix(p, q, np.array([0.0]), 1.8, 1.2)[0], sem)
|
| 106 |
+
divergence = (p[0][:, None] - q[0][None, :]) ** 2
|
| 107 |
+
np.testing.assert_allclose(cost_matrix(p, q, np.array([1.0]), 1.8, 1.2)[0], divergence)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_config_validation():
|
| 111 |
+
with pytest.raises(ValueError):
|
| 112 |
+
FusionConfig(alpha=1.5)
|
| 113 |
+
with pytest.raises(ValueError):
|
| 114 |
+
FusionConfig(alpha="adaptive")
|
| 115 |
+
assert FusionConfig(alpha="dynamic").alpha == "dynamic"
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ---------------------------------------------------------------------------
|
| 119 |
+
# Full fusion (Eq. 19 and fallback)
|
| 120 |
+
# ---------------------------------------------------------------------------
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_fusion_output_is_a_distribution():
|
| 124 |
+
rng = np.random.default_rng(1)
|
| 125 |
+
for alpha in (0.1, "dynamic"):
|
| 126 |
+
res = sinkhorn_fusion(rng.uniform(0, 1, 100), rng.uniform(0, 1, 100), FusionConfig(alpha=alpha))
|
| 127 |
+
assert res.fused.shape == (100, 2)
|
| 128 |
+
np.testing.assert_allclose(res.fused.sum(axis=1), 1.0)
|
| 129 |
+
assert (res.fused >= 0).all()
|
| 130 |
+
assert not res.fallback.any()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_eq19_row_marginal_equals_p_under_marginal_constraint():
|
| 134 |
+
"""Eq. 18 constrains T 1 = p, so the row marginal read out by Eq. 19 equals p."""
|
| 135 |
+
rng = np.random.default_rng(2)
|
| 136 |
+
res = sinkhorn_fusion(rng.uniform(0, 1, 100), rng.uniform(0, 1, 100))
|
| 137 |
+
np.testing.assert_allclose(res.fused, res.p, atol=1e-8)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_fallback_uses_outer_product():
|
| 141 |
+
cfg = FusionConfig(max_iter=1, fallback_tol=1e-12)
|
| 142 |
+
res = sinkhorn_fusion(np.array([0.9, 0.2]), np.array([0.3, 0.6]), cfg)
|
| 143 |
+
assert res.fallback.all()
|
| 144 |
+
expected = res.p[:, :, None] * res.q[:, None, :]
|
| 145 |
+
np.testing.assert_allclose(res.plans, expected)
|