Metadata-Version: 2.4
Name: ResPredAI
Version: 1.10.0
Summary: Antimicrobial Resistance predictions via AI models
Author-email: Ettore Rocchi <ettore.rocchi3@unibo.it>
Maintainer-email: Ettore Rocchi <ettore.rocchi3@unibo.it>
License: MIT
Project-URL: Homepage, https://github.com/EttoreRocchi/ResPredAI
Project-URL: Bug Reports, https://github.com/EttoreRocchi/ResPredAI/issues
Project-URL: Source, https://github.com/EttoreRocchi/ResPredAI
Project-URL: Documentation, https://ettorerocchi.github.io/ResPredAI/
Keywords: machine-learning,antimicrobial-resistance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<3.0.0,>=1.24.0
Requires-Dist: pandas<3.0.0,>=2.0.0
Requires-Dist: matplotlib<4.0.0,>=3.7.0
Requires-Dist: seaborn<1.0.0,>=0.12.0
Requires-Dist: scikit-learn<2.0.0,>=1.5.0
Requires-Dist: scipy<2.0.0,>=1.8.0
Requires-Dist: xgboost<3.0.0,>=2.0.0
Requires-Dist: catboost<2.0.0,>=1.2.0
Requires-Dist: typer<1.0.0,>=0.9.0
Requires-Dist: rich<14.0.0,>=13.0.0
Requires-Dist: shap<1.0.0,>=0.45.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: ruff>=0.14.0; extra == "dev"
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=7.0.0; extra == "docs"
Requires-Dist: pydata-sphinx-theme>=0.15.0; extra == "docs"
Requires-Dist: myst-parser>=3.0.0; extra == "docs"
Provides-Extra: tabpfn
Requires-Dist: tabpfn<9.0.0,>=8.0.0; extra == "tabpfn"
Dynamic: license-file

# ResPredAI

## Antimicrobial resistance predictions via artificial intelligence models

[![PyPI](https://img.shields.io/pypi/v/respredai)](https://pypi.org/project/respredai/)
[![Python Version](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
![CI](https://github.com/EttoreRocchi/ResPredAI/actions/workflows/ci.yaml/badge.svg)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![DOI](https://img.shields.io/badge/DOI-10.1038%2Fs41746--025--01696--x-blue)](https://doi.org/10.1038/s41746-025-01696-x)

Implementation of the pipeline described in:

> Bonazzetti, C., Rocchi, E., Toschi, A. _et al._ Artificial Intelligence model to predict resistances in Gram-negative bloodstream infections. _npj Digit. Med._ **8**, 319 (2025). https://doi.org/10.1038/s41746-025-01696-x

<p align="center">
  <img src="https://raw.githubusercontent.com/EttoreRocchi/ResPredAI/main/docs/assets/logo_ResPredAI.png" alt="ResPredAI Logo" width="350"/>
</p>

<p align="center">
  <strong><a href="https://ettorerocchi.github.io/respredai-website/">Website</a></strong> |
  <strong><a href="https://ettorerocchi.github.io/ResPredAI/">Documentation</a></strong> |
  <strong><a href="#installation">Installation</a></strong> |
  <strong><a href="#quick-start">Quick Start</a></strong> |
  <strong><a href="#pipeline-overview">Pipeline Overview</a></strong> |
  <strong><a href="#cli-commands">CLI Commands</a></strong> |
  <strong><a href="#citation">Citation</a></strong>
</p>

<p align="center">
  <em>A reproducible machine learning framework designed to accelerate clinical decision-making by predicting antimicrobial resistance patterns from patient data.</em>
</p>

## Highlights

- **Leakage-safe nested cross-validation**: one-hot encoding, imputation and scaling are fitted inside each training fold, a `group_column` keeps every patient on one side of each split, and repeated or temporal (prospective-style) validation is one setting away
- **Nine models, one configuration file**: logistic regression, random forest, XGBoost, CatBoost, MLP, two SVMs, KNN and TabPFN (optional extra), each tuned in an inner CV
- **Metrics that matter for resistance prediction**: very major and major errors (VME, ME) next to AUROC, MCC, balanced accuracy, Brier score and ECE, with the decision threshold tuned for Youden, F1, F2 or VME/ME costs
- **Honest uncertainty**: bootstrap confidence intervals on the pooled out-of-fold predictions, resampling whole patients when a `group_column` is set, and split-conformal prediction sets with per-class coverage
- **Calibrated probabilities**: Platt or isotonic calibration, with reliability curves per fold
- **Interpretability and subgroups**: signed coefficients, native importances or SHAP, and performance tables per subgroup (e.g. ward, sex)
- **From study to deployment**: `train` fits the final models on the whole cohort and `evaluate` scores them on an external one
- **Reproducible by default**: one HTML report per run and a manifest with package versions, seed, git commit and data hash

<p align="center">
  <img src="https://raw.githubusercontent.com/EttoreRocchi/ResPredAI/main/docs/assets/report_preview.png" alt="Excerpt of the ResPredAI HTML report" width="800"/>
  <br/>
  <em>Excerpt of the HTML report written by <code>respredai run</code> on the bundled example data.</em>
</p>

## Installation

```bash
pip install respredai
respredai --version  # check the installation
```

Or install from source:

```bash
git clone https://github.com/EttoreRocchi/ResPredAI.git
cd ResPredAI
# For development (includes pytest)
pip install -e ".[dev]"
```

### Optional: TabPFN support

TabPFN is shipped as an optional extra to keep the base install lean:

```bash
pip install "respredai[tabpfn]"
```

TabPFN v3 also requires a [PriorLabs API token](https://priorlabs.ai/docs). Export it before running any pipeline that includes `TabPFN` in `[Pipeline] models`:

```bash
export TABPFN_TOKEN="your-token-here"
```

If `TabPFN` is requested without the extra installed or without the token set, ResPredAI fails at the start of the run.

## Quick Start

### 1. Create a configuration file

```bash
respredai create-config my_config.ini
```

The template is commented and comes with sensible defaults. A minimal valid configuration looks like this:

```ini
[Data]
data_path = ./data/my_data.csv
targets = Target1,Target2
continuous_features = Feature1,Feature2,Feature3

[Pipeline]
models = LR,RF,XGB,CatBoost
outer_folds = 5
inner_folds = 3

[Reproducibility]
seed = 42

[Log]
verbosity = 1
log_basename = respredai.log

[Resources]
n_jobs = -1

[Output]
out_folder = ./output/
```

The optional sections (`[Metadata]` for patient grouping, temporal and subgroup columns, `[Uncertainty]`, `[Validation]`, `[Imputation]`, `[ModelSaving]`, ...) are described in the [configuration reference](https://ettorerocchi.github.io/ResPredAI/cli-reference/run-command.html#configuration-file).

### 2. Check the configuration and run the pipeline

```bash
respredai validate-config my_config.ini --check-data
respredai run --config my_config.ini
```

### 3. Open the report

All results end up in `out_folder`; start from `report.html`.

## Pipeline Overview

<p align="center">
  <img src="https://raw.githubusercontent.com/EttoreRocchi/ResPredAI/main/docs/assets/pipeline_run.svg" alt="ResPredAI pipeline: split the data, fit on each training set, aggregate across folds and write the report; train and evaluate for deployment" width="100%"/>
</p>

Every model and target goes through the same steps; the amber ones are switched on in the configuration.

## CLI Commands

| Command | What it does |
|---|---|
| [`run`](https://ettorerocchi.github.io/ResPredAI/cli-reference/run-command.html) | Nested CV and/or temporal validation for every model and target, with metrics, plots and the HTML report |
| [`train`](https://ettorerocchi.github.io/ResPredAI/cli-reference/train-command.html) | Fits the final models on the whole dataset and saves them with their threshold and conformal calibration |
| [`evaluate`](https://ettorerocchi.github.io/ResPredAI/cli-reference/evaluate-command.html) | Scores saved models on a new labelled dataset, with bootstrap CIs and conformal prediction sets |
| [`feature-importance`](https://ettorerocchi.github.io/ResPredAI/cli-reference/feature-importance-command.html) | Coefficients, native importances or SHAP across the outer folds (needs `[ModelSaving] enable = true`) |
| [`create-config`](https://ettorerocchi.github.io/ResPredAI/cli-reference/create-config-command.html) | Writes a commented template configuration |
| [`validate-config`](https://ettorerocchi.github.io/ResPredAI/cli-reference/validate-config-command.html) | Checks a configuration, and optionally the dataset, without running anything |
| `list-models` | Lists the available models and their codes |
| `info` | Shows the version and how to cite ResPredAI |

```bash
respredai run --config my_config.ini [--models LR,RF] [--targets Target1] [--output ./out/] [--seed 0] [--validation-strategy both] [--quiet]
respredai train --config my_config.ini [--models LR,RF] [--output ./trained/]
respredai evaluate --models-dir ./output/trained_models --data new_data.csv --output ./eval/
respredai feature-importance --output ./output/ --model LR --target Target1 [--top-n 20] [--direction]
```

Command-line options override the configuration file. Each command page lists all its options.

## Output

`respredai run` writes everything to `out_folder`:

- `report.html`: self-contained report with metrics and their confidence intervals, confusion matrices, calibration diagnostics and subgroup tables
- `metrics/`: one CSV per model and target with the fold mean, std and Nadeau-Bengio SE, the pooled out-of-fold estimate with its bootstrap CI (the uncertainty of this cohort's estimate with the fold models held fixed) and the conformal diagnostics, plus summaries across models
- `confusion_matrices/`, `calibration/`: heatmaps and reliability curves
- `subgroup_analysis/`: descriptive per-subgroup metrics, with CIs and a flag for small subgroups (if `subgroup_columns` is set)
- `models/`: fold models used to resume interrupted runs and to extract feature importance (if model saving is enabled)
- `reproducibility.json`: package versions, seed, `n_jobs`, git commit and data hash

The full layout, including the temporal-validation files, is in the [output reference](https://ettorerocchi.github.io/ResPredAI/cli-reference/run-command.html#output-files).

## Notes

> [!IMPORTANT]
> **Intended use:** ResPredAI is a research software project developed for retrospective data analysis and experimentation with machine learning models for antimicrobial resistance prediction.
> The software is provided for research and educational purposes only.

> [!NOTE]
> **Input validation:** ResPredAI fails fast on common data problems. Targets must be binary (encoded as 0/1) with both classes present, declared `continuous_features` must exist in the data, and group/temporal columns must not contain missing values.

> [!NOTE]
> **Reproducibility:** For bit-for-bit reproduction, recreate the environment from the package versions recorded in `reproducibility.json` and set `n_jobs = 1`, since parallel reductions and BLAS threading can perturb low-order floating-point bits.


## Changelog

See the full history of changes in the [CHANGELOG.md](CHANGELOG.md) file.

## Citation

If you use `ResPredAI` in your research, please cite:

```bibtex
@article{Bonazzetti2025,
  author = {Bonazzetti, Cecilia and Rocchi, Ettore and Toschi, Alice and Derus, Nicolas Riccardo and Sala, Claudia and Pascale, Renato and Rinaldi, Matteo and Campoli, Caterina and Pasquini, Zeno Adrien Igor and Tazza, Beatrice and Amicucci, Armando and Gatti, Milo and Ambretti, Simone and Viale, Pierluigi and Castellani, Gastone and Giannella, Maddalena},
  title = {Artificial Intelligence model to predict resistances in Gram-negative bloodstream infections},
  journal = {npj Digital Medicine},
  volume = {8},
  pages = {319},
  year = {2025},
  doi = {10.1038/s41746-025-01696-x},
  url = {https://doi.org/10.1038/s41746-025-01696-x}
}
```

## Funding

This research was supported by EU funding within the NextGenerationEU-MUR PNRR Extended Partnership initiative on Emerging Infectious Diseases (Project no. PE00000007, INF-ACT).

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on setting up a development environment, running tests, and submitting pull requests.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
