Metadata-Version: 2.4
Name: risk-bridge
Version: 1.0.5
Summary: Risk Bridging through Constrained MLE
Author: Risk Bridge contributors
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/SaehwanPark/risk-bridge
Project-URL: Repository, https://github.com/SaehwanPark/risk-bridge
Project-URL: Documentation, https://saehwanpark.github.io/risk-bridge/
Project-URL: Issues, https://github.com/SaehwanPark/risk-bridge/issues
Keywords: risk-modeling,calibration,constrained-optimization,maximum-likelihood,biostatistics
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: comp-builders>=1.0.0
Requires-Dist: numpy>=2.4.2
Requires-Dist: pandas>=3.0.1
Requires-Dist: polars>=1.38.1
Requires-Dist: rdata>=1.0.0
Requires-Dist: scikit-learn>=1.8.0
Requires-Dist: scipy>=1.17.1
Dynamic: license-file

<p align="center">
  <img src="assets/risk-bridge-banner.png" alt="Risk Bridge banner" width="100%">
</p>

# Risk Bridge

[![Documentation](https://img.shields.io/badge/docs-GitHub_Pages-blue.svg)](https://saehwanpark.github.io/risk-bridge/)
[![CI](https://github.com/SaehwanPark/risk-bridge/actions/workflows/ci.yml/badge.svg)](https://github.com/SaehwanPark/risk-bridge/actions)
[![PyPI version](https://img.shields.io/pypi/v/risk-bridge.svg)](https://pypi.org/project/risk-bridge/)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)

Risk Bridge is a Python package for estimating transportable binary-risk prediction models when the available cohorts do not share identical covariate support or when observational clinic data is subject to selection bias and calibration drift.

It combines propensity-score matching, reference-cohort calibration, joint maximum likelihood estimation, and constrained maximum likelihood estimation (cMLE) into reproducible simulation and user-data workflows.

Package title: **Risk Bridging through Constrained MLE**.

📖 **Documentation Website**: [https://saehwanpark.github.io/risk-bridge/](https://saehwanpark.github.io/risk-bridge/)

---

## Motivation

In clinical risk prediction, models fitted on specialized clinic registries or electronic health record (EHR) databases often fail when deployed to external target populations. This calibration breakdown occurs because:
- Covariate distributions $P(X)$ drift across health systems.
- High-value intermediate risk markers $Z$ (e.g. imaging, biopsies, or genomic scores) are measured in the source study but missing in the broader target registry.
- Clinic cohorts reflect non-random testing, referral enrichment, and selection bias.

Standard unconstrained Maximum Likelihood Estimation (MLE) on source data leads to miscalibrated risk predictions in the target cohort. Risk Bridge provides a principled way to constrain model fitting using calibration information from a representative external reference study, restoring well-calibrated probabilities.

---

## Foundation Papers

- > **Cao, Y., Ma, W., Zhao, G., McCarthy, A. M., & Chen, J. (2024)**. *A constrained maximum likelihood approach to developing well-calibrated models for predicting binary outcomes.* Lifetime Data Analysis, 30(3), 624–648. [DOI: 10.1007/s10985-024-09623-6](https://doi.org/10.1007/s10985-024-09623-6)
- > **Wang, L., & Chen, J. (2026)**. *Developing Accurate Risk Prediction Using Biased Electronic Health Record Data.* Manuscript in preparation.

---

## Key Features

- **Simulated & Applied Workflows**: Built-in Scenario 1–3 data generators for methodological experiments and a streamlined pipeline for prepared user CSV datasets.
- **Dual Analysis Paths**: Evaluates Propensity Score Matched (PSM) source samples alongside unadjusted Random Sampling (RS) baselines.
- **Hierarchical Solver Ladder**: Warm starts from unconstrained BFGS, transitions to interior-point constrained optimization (`trust-constr`) with analytic gradients and constraint Jacobians, and falls back to `SLSQP` when needed.
- **Rigorous Calibration Diagnostics**: Exports Calibration-in-the-Large (CITL), calibration slope, observed-to-expected (O/E) ratio, Brier score, and stratum-specific moment residuals.
- **Reproducible Output Contract**: Strict, versioned tabular output contract (`schema_version=1.1.0`) with comprehensive execution metadata and an `environment.json` sidecar.
- **Public Python API & CLI**: High-level typed configurations (`UserDataRunConfig`, `RunConfig`) and the `risk-bridge` command-line tool.

---

## Installation

### From PyPI (Standard Installation)

```bash
uv add risk-bridge
# or: pip install risk-bridge
```

The public-safe reproduction case runners are included in the wheel and source distribution. After installation, invoke them directly with `python -m cases.<case>.<runner>`.

### From Source Repository

```bash
git clone https://github.com/SaehwanPark/risk-bridge.git
cd risk-bridge
uv sync --locked
```

Run the test suite and verify typing:

```bash
uv run pytest
uv run basedpyright
```

---

## Quickstart

### 1. Simulated Scenario Run (CLI)

```bash
uv run risk-bridge \
  --mode simulated \
  --scenario 1 \
  --nsim 2 \
  --n-target 1000 \
  --n-source 500 \
  --n-reference 1000 \
  --sample-size 100 \
  --output-root data \
  --run-label quickstart
```

### 2. User-Data Cohort Run (CLI)

```bash
uv run risk-bridge \
  --mode user-data \
  --target-csv examples/target.csv \
  --source-csv examples/source.csv \
  --reference-csv examples/reference.csv \
  --x-cols X1,X2,X3,X4 \
  --y-col caseY \
  --z-origin-col zOrigin \
  --z-cat-col zCat \
  --sample-size 500 \
  --nsim 1 \
  --output-root data \
  --run-label user_data
```

For a five-minute walkthrough, see [QUICKSTART.md](QUICKSTART.md) or the [Online Quickstart Tutorial](https://saehwanpark.github.io/risk-bridge/getting-started/quickstart/).

---

## Library Usage

```python
from pathlib import Path
import polars as pl
from risk_bridge import UserDataRunConfig, UserDataSchema, run_user_data

target_df = pl.read_csv("examples/target.csv")
source_df = pl.read_csv("examples/source.csv")
reference_df = pl.read_csv("examples/reference.csv")

schema = UserDataSchema(
    x_cols=("X1", "X2", "X3", "X4"),
    y_col="caseY",
    z_origin_col="zOrigin",
    z_cat_col="zCat",
)

config = UserDataRunConfig(
    target_df=target_df,
    source_df=source_df,
    reference_df=reference_df,
    schema=schema,
    sample_size=500,
    output_root="data",
    run_label="applied_run",
)

output_dir: Path = run_user_data(config)
print(f"Results written to: {output_dir}")
```

---

## Outputs

Each run writes a timestamped directory under `output_root` containing:

- `final/run_metadata.csv`: Full configuration parameters, seeds, and schema version (`1.1.0`).
- `final/fit_diagnostics.csv`: Optimizer convergence status, objective values, and feasibility violations.
- `final/est_cml_psm.csv`: cMLE parameter estimates ($\alpha, \beta_X, \beta_Z, \gamma_0, \gamma_X, \sigma$).
- `final/calibration_metrics.csv`: Target cohort CITL, slope, O/E ratio, and Brier score.
- `final/calibration_residuals.csv`: Stratum-specific post-fit calibration residuals.
- `final/roc_metrics.csv`: Area under the ROC curve (AUC).
- `final/accuracy_metrics.csv`: Sensitivity, specificity, and precision at target FPR.
- `final/environment.json`: Reproducibility metadata and numerical tolerance contract.

---

## Replication Cases

Risk Bridge ships with four privacy-safe reproduction case studies:

- `python -m cases.numerical_validation.run_suite`
- `python -m cases.external_calibration_validation.run_suite --profile smoke --condition matched`
- `python -m cases.synthetic_transport_example.run_case`
- `python -m cases.runtime_support_scaling.run_scaling --profile smoke`

See [REPRODUCTION.md](REPRODUCTION.md) and the [Online Reproduction Runbook](https://saehwanpark.github.io/risk-bridge/replication/reproduction-runbook/) for instructions.

---

## Documentation Links

- [Documentation Website](https://saehwanpark.github.io/risk-bridge/) — Full online user guide, mathematical derivations, and tutorials
- [Quickstart Guide](QUICKSTART.md) — Fast setup and verification
- [User Guide](USER_GUIDE.md) — Comprehensive guide to cohorts, schemas, and CLI options
- [API Reference](API_REFERENCE.md) — Python library API reference
- [Example Workflows](examples/README.md) — Datasets and runnable scripts
- [Architecture Overview](ARCHITECTURE.md) — Module map and data flow
- [Contributing](CONTRIBUTING.md) — Development setup and contribution standards
- [Changelog](CHANGELOG.md) — Version release history
- [Citation](CITATION.cff) — Software and methodology citation info
- [License](LICENSE) — Apache License 2.0
