Metadata-Version: 2.5
Name: tcr-pmhc-analyzer
Version: 0.3.1
Summary: Analyzer for TCR-pMHC binding predictor outputs
Project-URL: Homepage, https://github.com/qbic-pipelines/tcr-pmhc-analyzer
Project-URL: Repository, https://github.com/qbic-pipelines/tcr-pmhc-analyzer.git
Project-URL: Issues, https://github.com/qbic-pipelines/tcr-pmhc-analyzer/issues
Author: Mark Polster
License-Expression: MIT
License-File: LICENSE
Keywords: analysis,peptide,tcr,tcr-pMHC,tcr-peptide,tcr-pmhc
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.11
Requires-Dist: matplotlib>=3.8.0
Requires-Dist: pandas>=3.0.0
Requires-Dist: rich-click>=1.9.6
Requires-Dist: scikit-learn>=1.4.0
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff==0.14.14; extra == 'dev'
Description-Content-Type: text/markdown

# tcr-pmhc-analyzer

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![PyPI version](https://img.shields.io/pypi/v/tcr-pmhc-analyzer.svg)](https://pypi.org/project/tcr-pmhc-analyzer/)

Analyzer for TCR-pMHC binding predictor outputs. Merges predictions from multiple models into a unified table, detects data leakage against each model's training set (downloaded from the authors' repositories on first use), identifies seen/unseen peptides, and benchmarks model performance via ROC curves.

## Installation

```bash
pip install tcr-pmhc-analyzer
```

For development:

```bash
git clone https://github.com/qbic-pipelines/tcr-pmhc-analyzer.git
cd tcr-pmhc-analyzer
pip install -e ".[dev]"
python -m pytest tests/                       # full suite; downloads the training data
python -m pytest tests/ -m "not gated_data"   # what CI runs: skips tests needing licence-gated data
```

Tests marked `gated_data` use the NetTCR, MixTCRpred, TCRen or TABR-BERT training data, whose licences do not allow downloading it on public CI runners.

## Input format

Both commands accept a TSV configuration file with two required columns (`model`, `file`) and one optional column (`training_data`):

| Column          | Required | Description                                                                                  |
|-----------------|----------|----------------------------------------------------------------------------------------------|
| `model`         | Yes      | Name of the prediction model                                                                 |
| `file`          | Yes      | Path to the model's prediction output                                                        |
| `training_data` | No       | Path to a training-data file, used for leakage and seen-peptide detection. **Required** for every **custom** (non-built-in) model row; ignored on built-in rows, which always use their built-in training data (see [Training data](#training-data)). Omit the column entirely when using only built-in models. See [Custom models](#custom-models). |

Example `input.tsv`:

```tsv
model	file
ergo2	results/ergo2_predictions.csv
mixtcrpred	results/mixtcrpred_predictions.csv
mixtcrpred-pan	results/mixtcrpred_pan_predictions.csv
t2pmhc-gcn	results/t2pmhc_gcn_predictions.csv
```

Each prediction file must contain the following columns:

| Column         | Description                                      |
|----------------|--------------------------------------------------|
| `identifier`   | Unique sample identifier (used for merging)       |
| `binding_score` | Model's predicted binding score                  |
| `binder`       | Ground truth label (0/1), required for benchmarking |
| `peptide`      | Peptide sequence                                  |
| `cdr3a`        | CDR3 alpha chain sequence                         |
| `cdr3b`        | CDR3 beta chain sequence                          |
| `va`, `vb`     | V gene alpha/beta                                 |
| `ja`, `jb`     | J gene alpha/beta                                 |
| `mhc`          | MHC allele                                        |
| `organism`     | Source organism                                   |
| `mhc_class`    | MHC class                                         |

## Commands

### `create-analyzer-table`

Merges predictions from multiple models into a single table with data leakage annotations and seen-peptide flags.

```bash
tcr-pmhc-analyzer create-analyzer-table [OPTIONS]
```

| Option              | Short | Required | Description                                                 |
|---------------------|-------|----------|-------------------------------------------------------------|
| `--input PATH`      | `-i`  | Yes      | Path to TSV config file with `model` and `file` columns     |
| `--output PATH`     | `-o`  | Yes      | Output file path (`.csv` or `.tsv`)                         |
| `--ergo-version`    |       | If ergo2 | ERGO training data version: `vdjdb`, `mcpas`, or `both`     |
| `--strict-leakage`  |       | No       | Fail instead of warn when a model's leakage match collapses to a key set with no TCR chain column. See [Degenerate leakage keys](#degenerate-leakage-keys). |
| `--training-data-dir DIR` |  | No | Directory of raw upstream training files (see [`fetch-training-data`](#fetch-training-data)). Files are verified by sha256 and nothing is downloaded. Default: download on first use into the cache. See [Training data](#training-data). |
| `--accept-nettcr-license` |  | For `nettcr-*` | Confirm you have read the [NetTCR-2.2 licence](https://github.com/mnielLab/nettcr-2.2/blob/7cead3fe6dcb539ff8e2d9121586dafca1e059c2/academic_software_license_agreement.pdf) and that your use complies. See [Licence acceptance](#licence-acceptance). |
| `--accept-mixtcrpred-license` |  | For `mixtcrpred` and `mixtcrpred-pan` | Confirm you have read the [MixTCRpred licence](https://github.com/GfellerLab/MixTCRpred/blob/acd6f57444bde675840890207c74ca3b0c7ffac2/LICENSE.md) and that your use complies. |
| `--accept-tcren-license` |  | For `tcren` | Confirm you have read the [TCRen licence](https://github.com/antigenomics/tcren/blob/cf1e1f0fd562fda1fc9f33c4385f9cffe5536413/LICENSE) and that your use complies. |
| `--accept-tabr-bert-license` |  | For `tabr-bert` | Confirm you have read the [TABR-BERT licence](https://github.com/Freshwind-Bioinformatics/TABR-BERT/blob/d0fe4a72cac53e8d83e4b576ce7aba1d40658e56/LICENSE) and that your use complies. |

**Example:**

```bash
tcr-pmhc-analyzer create-analyzer-table \
  -i input.tsv \
  -o analyzer_table.csv \
  --ergo-version vdjdb
```

**Output columns added:**
- `binding_score_{model}`: raw binding score per model
- `sample_in_train_{model}`: `True` if the sample appears in the model's training data (data leakage)
- `seen_in_{model}`: `True` if the peptide was seen in the model's training data

### `benchmark`

Generates ROC curve plots comparing model performance, split by seen vs unseen peptides. Data leakage samples are automatically removed before analysis.

```bash
tcr-pmhc-analyzer benchmark [OPTIONS]
```

| Option              | Short | Required | Description                                                        |
|---------------------|-------|----------|--------------------------------------------------------------------|
| `--input PATH`      | `-i`  | *        | Path to TSV config file with `model` and `file` columns            |
| `--table PATH`      |       | *        | Path to a pre-created analyzer table (alternative to `--input`)    |
| `--output PATH`     | `-o`  | Yes      | Output directory for ROC curve plots                               |
| `--ergo-version`    |       | If ergo2 | ERGO training data version: `vdjdb`, `mcpas`, or `both`             |
| `--models`          | `-m`  | No       | Space-separated list of models to benchmark (default: all available)|
| `--training-data-dir DIR` |  | No (only with `--input`) | Directory of raw upstream training files (see [`fetch-training-data`](#fetch-training-data)). Files are verified by sha256 and nothing is downloaded. Default: download on first use into the cache. See [Training data](#training-data). |
| `--accept-nettcr-license` |  | For `nettcr-*` with `--input` | Confirm you have read the [NetTCR-2.2 licence](https://github.com/mnielLab/nettcr-2.2/blob/7cead3fe6dcb539ff8e2d9121586dafca1e059c2/academic_software_license_agreement.pdf) and that your use complies. See [Licence acceptance](#licence-acceptance). |
| `--accept-mixtcrpred-license` |  | For `mixtcrpred` and `mixtcrpred-pan` with `--input` | Confirm you have read the [MixTCRpred licence](https://github.com/GfellerLab/MixTCRpred/blob/acd6f57444bde675840890207c74ca3b0c7ffac2/LICENSE.md) and that your use complies. |
| `--accept-tcren-license` |  | For `tcren` with `--input` | Confirm you have read the [TCRen licence](https://github.com/antigenomics/tcren/blob/cf1e1f0fd562fda1fc9f33c4385f9cffe5536413/LICENSE) and that your use complies. |
| `--accept-tabr-bert-license` |  | For `tabr-bert` with `--input` | Confirm you have read the [TABR-BERT licence](https://github.com/Freshwind-Bioinformatics/TABR-BERT/blob/d0fe4a72cac53e8d83e4b576ce7aba1d40658e56/LICENSE) and that your use complies. |

\* Either `--input` or `--table` must be provided.

**Examples:**

```bash
# Benchmark from raw predictions
tcr-pmhc-analyzer benchmark -i input.tsv -o results/

# Benchmark from a pre-created analyzer table
tcr-pmhc-analyzer benchmark --table analyzer_table.csv -o results/

# Benchmark specific models only
tcr-pmhc-analyzer benchmark -i input.tsv -o results/ -m "ergo2 mixtcrpred tabr-bert"
```

**Output files:**
- `roc_curve_unseen.png`: ROC curves for peptides unseen by all selected models
- `roc_curve_seen.png`: ROC curves for peptides seen by all selected models

### `fetch-training-data`

Downloads and verifies the raw upstream training files of the built-in models. **Optional**: `create-analyzer-table` and `benchmark --input` download missing files themselves. Use it to pre-fill the cache, or to fill a directory for an offline machine and pass that directory with `--training-data-dir`.

```bash
tcr-pmhc-analyzer fetch-training-data [OPTIONS]
```

| Option              | Short | Required | Description                                                 |
|---------------------|-------|----------|-------------------------------------------------------------|
| `--dir DIR`         |       | No       | Directory to fill with the raw upstream files (default: the cache, see [Training data](#training-data)) |
| `--models`          | `-m`  | No       | Space-separated list of built-in models; `ergo2` fetches both ERGO-II variants. Default: every model whose licence needs no flag, plus every licence-gated model whose flag is set; skipped gated models are listed with the flag they need |
| `--accept-nettcr-license` |  | For `nettcr-*` | As for `create-analyzer-table`. See [Licence acceptance](#licence-acceptance). |
| `--accept-mixtcrpred-license` |  | For `mixtcrpred` and `mixtcrpred-pan` | As for `create-analyzer-table`. |
| `--accept-tcren-license` |  | For `tcren` | As for `create-analyzer-table`. |
| `--accept-tabr-bert-license` |  | For `tabr-bert` | As for `create-analyzer-table`. |

Files already present with the right sha256 are not downloaded again. The command ends by printing the `--training-data-dir` argument to use.

**Example (offline machine):**

```bash
# On a machine with network access
tcr-pmhc-analyzer fetch-training-data --dir tcr_training_data --accept-nettcr-license
# Copy tcr_training_data/ to the offline machine, then
tcr-pmhc-analyzer create-analyzer-table -i input.tsv -o table.csv \
  --training-data-dir tcr_training_data --accept-nettcr-license
```

### `create-dashboard`

Builds a single self-contained, **offline** interactive HTML dashboard from a directory of analyzer tables. Each `.csv`/`.tsv` in the directory becomes one selectable dataset; toggle models, switch filter regimes, and inspect a **dataset overview** (positive/negative/peptide counts, split into seen/unseen), **per-model ROC** and **per-peptide AUC**, and a **dataset composition & filtering** section (positive/negative and leakage-removed rows per peptide, plus a peptide-attrition funnel), all recomputed live in the browser. Plotly and the full tables are inlined, so the HTML opens with no external requests (no CDN, works air-gapped).

```bash
tcr-pmhc-analyzer create-dashboard [OPTIONS]
```

| Option              | Short | Required | Description                                                                        |
|---------------------|-------|----------|------------------------------------------------------------------------------------|
| `--analyzer_dir PATH` |     | Yes      | Directory of analyzer-table files (`*.csv` / `*.tsv`); one dataset per file         |
| `--dashboard_path PATH` |   | No       | Output HTML file path (default: `dashboard.html`)                                  |
| `--models`          | `-m`  | No       | Space-separated models to include (default: every model with data on any dataset)  |
| `--colors`          |       | No       | Per-model color overrides as space-separated `model=hex` pairs (e.g. `'ergo2=#123456'`) |

The command consumes the same analyzer tables produced by `create-analyzer-table` (it reads the `binding_score_{model}`, `sample_in_train_{model}`, and `seen_in_{model}` columns). Custom and arbitrarily-named models are supported: the model set is auto-detected across all files and unknown names are assigned fallback colors. A dataset that has no results for a given model simply omits that model from its plots. Files named `<id>_analyzer_table.tsv` (as emitted by the upstream `tcrpmhcbinding` pipeline) appear in the dropdown as `<id>`.

**Examples:**

```bash
# Build a dashboard from every analyzer table in a directory
tcr-pmhc-analyzer create-dashboard --analyzer_dir analyzer_tables/ --dashboard_path dashboard.html

# Restrict to specific models
tcr-pmhc-analyzer create-dashboard --analyzer_dir analyzer_tables/ -m "ergo2 mixtcrpred"
```

> **Note:** each `dashboard.html` inlines `plotly.min.js` (~4.85 MB) plus the full tables as JSON, so expect multi-megabyte output that grows with dataset size.

## Licence acceptance

The training data of some models comes from tools distributed under restrictive licences, and downloading and using it makes you subject to those licences. Each licence restricts use (see the table below), generally to academic, non-commercial or non-profit use. Read the licence of each model you want to analyse, then set its flag to confirm that you have read it and that your use complies. Without the flag the command fails before reading or downloading any file and lists every missing flag.

| Model                          | Flag                          | Licence |
| ------------------------------ | ----------------------------- | ------- |
| `nettcr-pan`, `nettcr-peptide` | `--accept-nettcr-license`     | [DTU Health Tech Academic Software License Agreement](https://github.com/mnielLab/nettcr-2.2/blob/7cead3fe6dcb539ff8e2d9121586dafca1e059c2/academic_software_license_agreement.pdf), at the pinned commit |
| `mixtcrpred`, `mixtcrpred-pan` | `--accept-mixtcrpred-license` | [MixTCRpred licence](https://github.com/GfellerLab/MixTCRpred/blob/acd6f57444bde675840890207c74ca3b0c7ffac2/LICENSE.md), at the pinned commit. Commercial applications require buying the MixTCRpred licence. |
| `tcren`                        | `--accept-tcren-license`      | [TCRen licence](https://github.com/antigenomics/tcren/blob/cf1e1f0fd562fda1fc9f33c4385f9cffe5536413/LICENSE), at the pinned commit: educational, research and non-profit use by non-profit institutions only. |
| `tabr-bert`                    | `--accept-tabr-bert-license`  | [TABR-BERT licence](https://github.com/Freshwind-Bioinformatics/TABR-BERT/blob/d0fe4a72cac53e8d83e4b576ce7aba1d40658e56/LICENSE), at the pinned commit |

The flags apply to `create-analyzer-table`, `benchmark --input` and `fetch-training-data`, the commands that download or load training data. `benchmark --table` and `create-dashboard` read an existing analyzer table and need no flag. Other models and [custom models](#custom-models) need no flag.

The full text of every licence is shipped with the package in [`src/tcr_pmhc_analyzer/data/licenses/`](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/src/tcr_pmhc_analyzer/data/licenses/).

**Cite every model you use**, see [Citations](#citations). In particular, **you must cite NetTCR-2.2 when using the `nettcr-*` models.** After the licences are accepted, the command prints the citation of every licence-gated tool it used.

```bash
tcr-pmhc-analyzer create-analyzer-table -i input.tsv -o analyzer_table.csv \
  --accept-nettcr-license --accept-tcren-license
```

## Supported models

| Model          | Training data                          |
|----------------|----------------------------------------|
| `ergo2`        | mcpas or vdjdb (specify with `--ergo-version vdjdb\|mcpas`) |
| `ergo2-vdjdb`  | vdjdb (use with `--ergo-version both`, alongside `ergo2-mcpas`) |
| `ergo2-mcpas`  | mcpas (use with `--ergo-version both`, alongside `ergo2-vdjdb`) |
| `mixtcrpred`   | 146 pMHC training set                  |
| `mixtcrpred-pan` | 146 pMHC training set (shares mixtcrpred's training set and `--accept-mixtcrpred-license`; single pan-epitope checkpoint instead of 146 epitope-specific models) |
| `t2pmhc-gcn`   | t2pmhc core training set               |
| `t2pmhc-gat`   | t2pmhc core training set               |
| `tabr-bert`    | TCR-pMHC training set                  |
| `tulip-tcr`    | TULIP training set                     |
| `atm-tcr`      | ATM-TCR training set                   |
| `nettcr-peptide` | NetTCR-2.2 training set (peptide-specific strategy) |
| `nettcr-pan`   | NetTCR-2.2 training set (pan-specific strategy)      |
| `tcren`        | TCRen PDB-based structural training set |
| `stag-llm`     | STAG-LLM structural training set (`final_dataset_modeled.csv`) |

> **Note on score direction.** Most models output `binding_score` such that
> higher = more likely binder. `tcren` is the exception: lower (more negative)
> score = more likely binder. `binding_score_{model}` is always written to the
> analyzer table exactly as the model reported it, so `binding_score_tcren` stays
> inverted there. Both consumers correct for it in memory instead: `benchmark`
> negates the scores before computing ROC/PR curves, and `create-dashboard`
> negates them when serializing the table into the HTML. AUC/AUPRC are therefore
> directly comparable across all models, but code reading the table itself has to
> account for the direction.

> **Note on the `stag-llm` training set.** STAG-LLM trains in two stages: a
> self-supervised ESM-2 masked-language-model pretraining on a large
> sequence-only corpus (`full_seq_df_new.csv`, binders only, no labels), then
> the supervised binding classifier (the deployed checkpoint) trained with
> labels only on the structurally-modeled set (`final_dataset_modeled.csv`,
> 46,201 pairs). The `stag-llm` training data is that **supervised
> structural** set, since binding-benchmark leakage means the labeled pairs the
> model actually learned; the MLM pretraining corpus is treated like ESM-2's own
> pretraining and is **not** counted as label leakage. To experiment with the
> full sequence corpus later, add a row under a **distinct** model name (e.g.
> `stag-llm-mlm`) with `training_data` pointing at that file, see
> [Custom models](#custom-models). Setting `training_data` on the `stag-llm` row
> itself has no effect: the samplesheet override is only read for custom models.

### ERGO-II "both" variant mode

The upstream [`tcrpmhcbinding`](https://github.com/qbic-pipelines/tcrpmhcbinding) Nextflow pipeline can run ERGO-II against both training-database variants (`vdjdb` and `mcpas`) in a single run by passing `--ergo2_variant both`. In that mode the pipeline emits two prediction columns labelled `ergo2-vdjdb` and `ergo2-mcpas` instead of the single `ergo2` column.

When you pass that predictions TSV to this tool, use `--ergo-version both`:

```bash
tcr-pmhc-analyzer create-analyzer-table \
  -i input.tsv \
  -o analyzer_table.csv \
  --ergo-version both
```

Each ERGO column is then checked against its respective training set:
- `sample_in_train_ergo2-vdjdb` and `seen_in_ergo2-vdjdb` are computed against the vdjdb training data.
- `sample_in_train_ergo2-mcpas` and `seen_in_ergo2-mcpas` are computed against the mcpas training data.

`--ergo-version both` requires the input config to contain both `ergo2-vdjdb` and `ergo2-mcpas` model rows. Single-variant inputs continue to use `--ergo-version vdjdb` or `--ergo-version mcpas` with the legacy `ergo2` model name; that path is unchanged.

## Training data

Leakage and seen-peptide detection compare each prediction against the training set of each built-in model. The analyzer does not ship these training sets. On first use it downloads each model's raw training file from the authors' own repository at a pinned commit or tag, verifies it against a stored sha256, and converts it in memory to the column names the analyzer uses. A file that fails its checksum is never used: the command stops with an error naming the file, its URL and the affected models.

| Model(s) | Upstream file (pinned) | Size | Conversion applied at runtime |
| -------- | ---------------------- | ---- | ----------------------------- |
| `ergo2` (`--ergo-version mcpas`), `ergo2-mcpas` | [IdoSpringer/ERGO-II](https://github.com/IdoSpringer/ERGO-II) `85d320a`, `Samples/mcpas_train_samples.pickle` | 5.4 MB | Pickle flattened to a table (loaded with an unpickler that refuses every class reference); `UNK` becomes empty; the cells containing the Unicode replacement character U+FFFD (garbled V/J/MHC strings already present upstream) become empty |
| `ergo2` (`--ergo-version vdjdb`), `ergo2-vdjdb` | same repository, `Samples/vdjdb_no10x_train_samples.pickle` | 6.4 MB | Pickle flattened to a table; `UNK` becomes empty |
| `mixtcrpred`, `mixtcrpred-pan` | [GfellerLab/MixTCRpred](https://github.com/GfellerLab/MixTCRpred) tag `v1.0`, `full_training_set_146pmhc.csv` | 1.7 MB | Header renamed |
| `nettcr-peptide`, `nettcr-pan` | [mnielLab/NetTCR-2.2](https://github.com/mnielLab/NetTCR-2.2) `7cead3f`, `data/nettcr_2_2_limited_dataset.csv` | 4.5 MB | Header renamed |
| `t2pmhc-gcn`, `t2pmhc-gat` | [qbic-pipelines/t2pmhc](https://github.com/qbic-pipelines/t2pmhc) tag `v1.1.4`, `data/t2pmhc_train.tsv` | 8.2 MB | None |
| `tabr-bert` | [Freshwind-Bioinformatics/TABR-BERT](https://github.com/Freshwind-Bioinformatics/TABR-BERT) `d0fe4a7`, `data/train_tcr_pmhc.csv` | 3.0 MB | Header renamed |
| `tulip-tcr` | [barthelemymp/TULIP-TCR](https://github.com/barthelemymp/TULIP-TCR) `798fab9`, `data/SeenPeptides.zip` and `data/UnseenPeptides.zip` | 58.3 MB | Three CSVs from the two zips concatenated and deduplicated; `<MIS>` becomes empty |
| `atm-tcr` | [Lee-CBG/ATM-TCR](https://github.com/Lee-CBG/ATM-TCR) `a1e02e1`, `data/combined_dataset.csv` | 7.4 MB | Header line added |
| `tcren` | [antigenomics/tcren](https://github.com/antigenomics/tcren) `cf1e1f0`, `data/summary_PDB_structures.csv` | 18 KB | Header renamed |
| `stag-llm` | `final_dataset_modeled.csv` from the [STAG-LLM Rice Box folder](https://rice.box.com/s/xin5ogk1gfwm4wu9i96wsx0497vz0plz) (unversioned, pinned by sha256 only) | 20.9 MB | Columns `peptide`, `CDR3a`, `CDR3b` kept and renamed |

Only the files of the models in your samplesheet are downloaded.

**Negatives count as seen.** Several upstream files contain the negative (non-binding) pairs the model was trained on: ERGO-II, ATM-TCR, NetTCR-2.2, t2pmhc and STAG-LLM. They are kept, so a prediction matching a training negative is flagged in `sample_in_train_{model}` and its peptide counts in `seen_in_{model}`, since the model saw that pair during training.

**Cache.** Downloaded files are stored unchanged in `$TCR_PMHC_ANALYZER_CACHE` if set, else `$XDG_CACHE_HOME/tcr-pmhc-analyzer`, else `~/.cache/tcr-pmhc-analyzer`. Each file is verified on every use; a corrupt cached file is downloaded again once. A download is written to a temporary `.part` file and moved into place only after its checksum matches. Downloads time out after 60 s and are retried once.

**Offline use.** Run [`fetch-training-data --dir DIR`](#fetch-training-data) on a machine with network access, copy `DIR`, and pass `--training-data-dir DIR` to `create-analyzer-table` or `benchmark`. With `--training-data-dir` nothing is downloaded: a missing file or a checksum mismatch is an error.

**Library use.** The licence flags are checked by the CLI commands. Calling `Analyzer.read_training_data` or `tcr_pmhc_analyzer.training_data.load_training_source` directly from Python downloads without a licence check; you are still bound by the licences listed under [Licence acceptance](#licence-acceptance).

## Custom models

Both commands support models beyond the [built-in list](#supported-models): any `model` name in the samplesheet works, as long as you point it at a training-data file. This section covers that path end to end: the samplesheet contract, the prediction-file requirement, what the training-data file needs to contain, how leakage detection behaves for a model with no per-model matcher, and where the sharp edges are.

### When you need a custom model

Any `model` name in the samplesheet that isn't in the [Supported models](#supported-models) table (and isn't `ergo2`, `ergo2-vdjdb`, or `ergo2-mcpas`) is a **custom model**. It's detected automatically: there's no registration step to add a new model name.

A custom model gets exactly the same treatment as a built-in one:

- Merged into the analyzer table on `identifier`, like every other model
- `sample_in_train_{model}`: data-leakage flag
- `seen_in_{model}`: seen-peptide flag
- Full support in `benchmark` (ROC/PR curves) and `create-dashboard`

The one thing you must supply that built-in models get for free is a training-data file, via the `training_data` column.

### Samplesheet

`training_data` is required for custom rows. It may be blank or omitted entirely for built-in rows, so a single samplesheet can mix both:

```tsv
model	file	training_data
ergo2	results/ergo2_predictions.csv
my_model	results/my_model_predictions.csv	results/my_model_train.csv
```

> **Missing `training_data`.** If a custom model's `training_data` cell is missing, blank, or NaN, `create-analyzer-table` fails immediately with: `Custom model '{model}' requires a 'training_data' column with a valid file path in the input samplesheet.`

> **`training_data` on a built-in row is currently ignored.** `load_model_results()` only reads the `training_data` cell when the row's model is custom, so putting a path on a built-in row (e.g. `ergo2`) has no effect, and that model still uses its built-in training data with no warning.

There's no limit on the number of custom rows; each needs its own `training_data` entry:

```tsv
model	file	training_data
my_model_1	results/my_model_1_predictions.tsv	training/model1_train.tsv
my_model_2	results/my_model_2_predictions.tsv	training/model2_train.tsv
```

### Prediction file

A custom model's `file` must contain the same columns required for every model, see the table under [Input format](#input-format). All of those columns are mandatory verbatim; the analyzer keeps only them and drops everything else, so extra columns are harmless. A missing one raises a raw pandas `KeyError` at load time.

### Training-data file

Built-in models get their training data automatically (see [Training data](#training-data)); custom models must provide it here. It feeds both `sample_in_train_{model}` (data leakage) and `seen_in_{model}` (seen-peptide) detection.

**Format.** The file is read by extension: lowercase `.csv` (comma-separated) or `.tsv` (tab-separated) only.

**Peptide column.** `seen_in_{model}` needs a peptide column.

**Leakage match keys.** Custom models always go through the same default matcher used for `t2pmhc-gcn`, `t2pmhc-gat`, `tabr-bert`, `atm-tcr`, and `stag-llm` (see [Data leakage detection](#data-leakage-detection)). The candidate keys are `peptide, cdr3a, cdr3b, va, vb, ja, jb, mhc`; any key absent from either the prediction table or your training file is silently dropped from the merge, so your training file's columns determine the effective match rule:

| Columns your training file ships             | Resulting match rule                           | Same as                                    |
|------------------------------------------------|--------------------------------------------------|----------------------------------------------|
| `peptide, cdr3a, cdr3b, va, vb, ja, jb, mhc`    | `(peptide, cdr3a, cdr3b, va, vb, ja, jb, mhc)`    | `t2pmhc-gcn`, `t2pmhc-gat`                    |
| `peptide, cdr3b, mhc` (β-only)                  | `(peptide, cdr3b, mhc)`                           | `tabr-bert`                                   |
| `peptide, cdr3a, cdr3b` (no MHC)                | `(peptide, cdr3a, cdr3b)`                         | `stag-llm`                                    |
| `peptide, cdr3b` (β-only, no MHC)               | `(peptide, cdr3b)`                                | `atm-tcr`                                     |
| `peptide, mhc` only                             | `(peptide, mhc)`, triggers the [degenerate-key warning](#degenerate-leakage-keys) | none of the current built-ins |

Surviving keys are compared with `fillna("").astype(str).str.strip().str.upper()` on both sides: case-insensitive, whitespace-stripped, exact string match. Training rows where every key column is empty are dropped before merging. The match itself is an inner merge; a test row matching one or more training rows is flagged `True`.

**No samplesheet equivalent for `MODEL_MATCH_COLS`.** `nettcr-peptide` and `nettcr-pan` are matched on `anarcii_cdr3a`/`anarcii_cdr3b` instead of the default key set (see [Data leakage detection](#data-leakage-detection)), via a built-in-only registry (`MODEL_MATCH_COLS` in `Analyzer.py`) that has no samplesheet knob. If your custom training file exposes the TCR under non-standard column names, rename them to the standard `cdr3a`/`cdr3b`/`va`/`vb`/`ja`/`jb` before pointing `training_data` at it; otherwise the default matcher won't see them and you risk the degenerate-key warning below.

**MHC normalization.** If `mhc` survives as a match key, both sides are passed through `normalize_mhc()` first: it strips an `HLA-` prefix, expands short forms, and collapses to 2-field `GENE*NN:NN`:

| Input               | Normalized   |
|----------------------|--------------|
| `HLA-A*02:01:01:03`  | `A*02:01`    |
| `A2`                 | `A*02`       |
| `HLA-A*02:01`        | `A*02:01`    |

#### Degenerate leakage keys

If the surviving key set (after auto-dropping columns absent from either side) contains none of `cdr3a`, `cdr3b`, `va`, `vb`, `ja`, `jb`, or a model-specific chain column registered in `MODEL_MATCH_COLS`, it cannot distinguish two different TCRs against the same pMHC. The resulting `sample_in_train_{model}` is a peptide/MHC-level flag, not sample-level leakage, and the same guard catches the total-collapse case (zero of the 8 candidate keys shared, flag comes back all-`False`).

By default this is logged as a warning naming the model and the surviving keys. Pass `--strict-leakage` to `create-analyzer-table` to turn it into a hard error (exit code 2) instead. No built-in model currently trips this guard.

### Benchmarking and dashboards

`benchmark` and `create-dashboard` have no model allowlist and no registration step: both auto-discover models from `binding_score_{model}` columns (`_get_available_models` in `benchmark.py`), so a custom model is fully benchmarkable and appears in the dashboard automatically, alongside built-in ones. `create-dashboard` in particular treats it exactly like [it documents for any unrecognized name](#create-dashboard), included in the auto-detected model set, assigned a fallback color unless you set one with `--colors`. The one constraint is ordering: `benchmark` requires `sample_in_train_{model}` and `seen_in_{model}` to already exist in its input, so `create-analyzer-table` must run first (or pass `benchmark --table` pointed at its output).

### Limitations

> - **Score direction isn't configurable.** Only the hardcoded `tcren` is treated as lower-is-better (see the [note on score direction](#supported-models)); there's no samplesheet or CLI flag to mark a custom model the same way. If your model's raw score is lower-is-better, negate it before feeding it in, or the ROC/PR curves and the dashboard plots will come out inverted.
> - **A mis-named or malformed training file degrades leakage detection down to a peptide/MHC-level flag, or an all-`False` one**, rather than raising an error by default. See [Degenerate leakage keys](#degenerate-leakage-keys). Pass `--strict-leakage` if you want it to fail instead of warn.
> - **A missing peptide column raises a raw `KeyError: 'epitope'`** rather than a helpful message.
> - **A wrong file extension fails confusingly.** Only lowercase `.csv`/`.tsv` are recognized; any other extension returns a string instead of raising, which surfaces downstream as an unrelated `TypeError`/`AttributeError`.
> - **`training_data` is silently ignored on built-in rows.** The samplesheet override is only read for custom models, so a path on a built-in row is dropped without warning. Use a distinct model name to force the custom path.
> - **Reserved names collide with built-in special-casing.** Naming a custom model exactly `mixtcrpred`, `mixtcrpred-pan`, `tulip-tcr`, `tcren`, `ergo2_vdjdb`, or `ergo2_mcpas` makes it silently use that built-in's special-cased matcher instead of the default rule described above.

### End-to-end worked example

```tsv
model	file	training_data
ergo2	predictions/ergo2_predictions.csv
my_model	predictions/my_model_predictions.csv	training/my_model_train.csv
```

```bash
tcr-pmhc-analyzer create-analyzer-table \
  -i input.tsv \
  -o analyzer_table.csv \
  --ergo-version vdjdb

tcr-pmhc-analyzer benchmark \
  --table analyzer_table.csv \
  -o results/ \
  -m "ergo2 my_model"
```

For `my_model`, `analyzer_table.csv` gains three new columns:

- `binding_score_my_model`: raw score from `predictions/my_model_predictions.csv`
- `sample_in_train_my_model`: `True`/`False` from the leakage matcher, using whichever key columns `training/my_model_train.csv` and the prediction file both carry (see the table above)
- `seen_in_my_model`: `True`/`False` from whether the row's `peptide` appears in `training/my_model_train.csv`'s peptide column

**Walkthrough.** Say `training/my_model_train.csv` ships only `peptide` and `cdr3b` (a β-only training set). Per the match-key table above, that reduces `sample_in_train_my_model` to `(peptide, cdr3b)`, the same rule `atm-tcr` gets. A prediction row is flagged `True` if its `(peptide, cdr3b)` pair, compared case-insensitively and whitespace-stripped, appears anywhere in the training file; `mhc`, `cdr3a`, `va`/`vb`/`ja`/`jb` are ignored entirely because the training file doesn't have them. `seen_in_my_model` doesn't depend on the match-key table at all: it's `True` whenever the row's `peptide` alone is present in the training file's peptide column.

These three columns are exactly what `benchmark -m "ergo2 my_model"` above consumes, and what `create-dashboard` would pick up automatically from the same `analyzer_table.csv` if you also ran that command on it, same as any built-in model.

## How it works

1. **Merge**: Prediction outputs from multiple models are merged on the `identifier` column into a single DataFrame.
2. **Data leakage detection**: Each sample is checked against each model's training data (see [Training data](#training-data)) to flag samples that appear in a model's training set. The match rule is **per-model** because each training file exposes the TCR-pMHC tuple at a different granularity (see [Data leakage detection](#data-leakage-detection) below for the per-model rules).
3. **Seen peptide detection**: Each peptide is checked against training data to identify whether it was seen during model training.
4. **Benchmarking**: ROC curves are generated after removing leaked samples, separately for seen and unseen peptides.

### Data leakage detection

`sample_in_train_{model}` is computed by a per-model matcher in
`Analyzer._find_leakage_<model>`. Each function does its own normalization
(V/J `*NN` allele stripping, MHC field truncation, etc.) and its own
`pd.merge`. The rules are derived from what each training file
actually ships (column presence, NaN rates, MHC notation), not from the
underlying model paper, so the leakage check reflects the granularity the
training file was actually curated at.

| model                          | match keys                                                                                   | notes                                                                                                                                                                  |
|--------------------------------|----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `t2pmhc-gcn`, `t2pmhc-gat`     | `(peptide, cdr3a, cdr3b, va, vb, ja, jb, mhc)` with 2-field MHC                              | Default rule. Training is complete and clean (100% non-NaN, V/J carry the `*` allele).                                                                                 |
| `mixtcrpred`                   | as above, **with `*NN` stripped from V/J** on both sides                                     | Training file is internally mixed on the V/J allele suffix (~95.5% stripped, ~4.5% retained). Mirrors `benchmarker.translate_mixtcrpred`.                              |
| `mixtcrpred-pan`               | identical to `mixtcrpred`                                                                     | Pan-epitope retrain of MixTCRpred (one epitope-aware checkpoint vs. mixtcrpred's 146 epitope-specific models); shares mixtcrpred's training file, so it routes through the same matcher. |
| `ergo2_vdjdb`                  | full-chain **OR** TRB-only `(peptide, cdr3b, vb, jb, mhc)`; MHC at first colon field          | 82.7% of vdjdb training rows have NaN α-side fields. The TRB-only union catches them. MHC first-field handles the mix of `HLA-X*NN` and `HLA-X*NN:NN`.                  |
| `ergo2_mcpas`                  | as `ergo2_vdjdb`, **with `*NN` stripped from V/J**                                           | mcpas stores V/J at gene level (<3% have the allele suffix) and uses short-form MHC (`HLA-A2`). Without the strip the merge produces zero matches.                     |
| `tabr-bert`                    | `(peptide, cdr3b, mhc)` with 2-field MHC                                                     | β-only training. Default rule auto-drops the absent α-side / V/J columns.                                                                                              |
| `tulip-tcr`                    | `(peptide, cdr3b)` **OR** `(peptide, cdr3a)`. **MHC excluded.**                              | Training `mhc` column is ~40% non-allele text (cell lines, free text, malformed alleles); MHC-conditioned matching would over-reject. Lossy on MHC, high recall on TCR. |
| `atm-tcr`                      | `(peptide, cdr3b)`                                                                            | atm-tcr training has no MHC column and no α-side. Default rule auto-drops everything except these two.                                                                 |
| `tcren`                        | `(peptide, cdr3a, cdr3b)` **OR** `(peptide, cdr3b)`. **MHC excluded.**                       | Training stores only `mhc_class` ("MHCI"/"MHCII"), too coarse to discriminate. The fallback group handles the 1.4% of training rows with NaN cdr3a.                    |
| `stag-llm`                     | `(peptide, cdr3a, cdr3b)`. **MHC excluded.**                                                 | Default rule. Training ships only those three columns (source MHC is a raw ~180 aa sequence, dropped upstream), so the 8 default keys auto-drop to the triple. Equivalent to the tcren rule; no `(peptide, cdr3b)` fallback is needed (no NaN cdr3a). |
| `nettcr-peptide`, `nettcr-pan` | `(peptide, anarcii_cdr3a, anarcii_cdr3b, mhc)` with 2-field MHC                              | NetTCR-2.2's training file stores the TCR as anarcii-numbered CDRs and ships no plain `cdr3a`/`cdr3b`/V/J, so the default 8-column rule would auto-drop to `(peptide, mhc)`: a peptide/MHC-level match, not sample-level. Instead, the `anarcii_cdr3a`/`anarcii_cdr3b` pair is read from the *prediction* file (via the `MODEL_MATCH_COLS` registry in `Analyzer.py`) and carried into the merge in memory only; it is never written to the analyzer table. No longer advisory only. |
| *any other/custom model*      | `(peptide, cdr3a, cdr3b, va, vb, ja, jb, mhc)`, auto-dropped to whatever columns the training file ships | Default rule. Applies to every [custom model](#custom-models), see there for the full column → match-key breakdown.                                                   |

Several of these rules mirror the reference implementations in `benchmarker.find_leakage_*` (from the t2pmhc revisions benchmark pipeline at `t2pmhc_revisions/benchmark_m3/benchmarker.py`); the others are derived directly from the training-file profile.

**Known limitation: anarcii numbering drift.** The `anarcii_cdr3a`/`anarcii_cdr3b` columns in the NetTCR training file and in a NetTCR prediction file come from two separate anarcii runs. If the two runs' numbering schemes disagree, the CDR3 boundaries shift and the match silently under-counts true leakage. The [degenerate-key guard](#degenerate-leakage-keys) cannot detect this, since both columns are present; it only catches the case where a chain column is missing entirely.

**Regeneration note.** Per-model rules changed in `[0.2.1]`, see [CHANGELOG.md](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/CHANGELOG.md). Analyzer tables generated before that change have stale `sample_in_train_*` columns for `mixtcrpred`, `ergo2_vdjdb`, `ergo2_mcpas`, `tulip-tcr`, and `tcren`, and should be regenerated.

**Regeneration note: NetTCR sample-level leakage was over-reported.** Before this change, `sample_in_train_nettcr_peptide`/`sample_in_train_nettcr_pan` (now `sample_in_train_nettcr-peptide`/`sample_in_train_nettcr-pan`, note the rename below) were bit-for-bit identical to `seen_in_*` on every analyzer table ever produced, because the match collapsed to `(peptide, mhc)`. Any analyzer table with NetTCR columns must be regenerated, and **any `benchmark` output or dashboard built from it must be rebuilt too**, since the leakage-filtered ROC/PR regime removed far too many rows. The model rename (`nettcr_peptide` to `nettcr-peptide`, `nettcr_pan` to `nettcr-pan`) also changes every affected column name; update samplesheets and any downstream code that reads these columns by name.

## Citations

If you use tcr-pmhc-analyzer in your research, please cite the underlying prediction models:

- [MixTCRpred](https://doi.org/10.1038/s41467-024-47461-8)

  > Croce G, Bobisse S, Moreno DL, Schmidt J, Guillame P, Harari A, Gfeller D. Deep learning predictions of TCR-epitope interactions reveal epitope-specific chains in dual alpha T cells. Nature Communications. 2024;15:3211. doi: 10.1038/s41467-024-47461-8

  > Licence: https://github.com/GfellerLab/MixTCRpred/blob/acd6f57444bde675840890207c74ca3b0c7ffac2/LICENSE.md

  > Run as `mixtcrpred` and, with a pan-epitope checkpoint retrained by the user, as `mixtcrpred-pan`.

- [ERGO-II](https://doi.org/10.3389/fimmu.2021.664514)

  > Springer I, Tickotsky N, Louzoun Y. Contribution of T Cell Receptor Alpha and Beta CDR3, MHC Typing, V and J Genes to Peptide Binding Prediction. Frontiers in Immunology. 2021;12:664514. doi: 10.3389/fimmu.2021.664514

- [TABR-BERT](https://doi.org/10.1093/bib/bbad436)

  > Zhang J, Ma W, Yao H. Accurate TCR-pMHC interaction prediction using a BERT-based transfer learning method. Briefings in Bioinformatics. 2024;25(1):bbad436. doi: 10.1093/bib/bbad436

  > Licence: https://github.com/Freshwind-Bioinformatics/TABR-BERT/blob/d0fe4a72cac53e8d83e4b576ce7aba1d40658e56/LICENSE

- [TULIP-TCR](https://doi.org/10.1073/pnas.2316401121)

  > Meynard-Piganeau B, Feinauer C, Weigt M, Walczak AM, Mora T. TULIP: A transformer-based unsupervised language model for interacting peptides and T cell receptors that generalizes to unseen epitopes. Proceedings of the National Academy of Sciences. 2024;121(24):e2316401121. doi: 10.1073/pnas.2316401121

- [ATM-TCR](https://doi.org/10.3389/fimmu.2022.893247)

  > Cai M, Bang S, Zhang P, Lee H. ATM-TCR: TCR-Epitope Binding Affinity Prediction Using a Multi-Head Self-Attention Model. Frontiers in Immunology. 2022;13:893247. doi: 10.3389/fimmu.2022.893247

- [t2pmhc](https://doi.org/10.64898/2026.02.27.708137)

  > Polster M, Stadelmaier J, Ball E, Scheid J, Bauer J, Nelde A, Claassen M, Dubbelaar ML, Walz JS, Nahnsen S. t2pmhc: A Structure-Informed Graph Neural Network to predict TCR-pMHC Binding. bioRxiv. 2026. doi: 10.64898/2026.02.27.708137

  > Run in its `t2pmhc-gcn` and `t2pmhc-gat` variants.

- [TCRen](https://doi.org/10.1038/s43588-024-00653-0)

  > Karnaukhov VK, Shcherbinin DS, Chugunov AO, Chudakov DM, Efremov RG, Zvyagin IV, Shugay M. Structure-based prediction of T cell receptor recognition of unseen epitopes using TCRen. Nature Computational Science. 2024;4:510-521. doi: 10.1038/s43588-024-00653-0

  > Licence: https://github.com/antigenomics/tcren/blob/cf1e1f0fd562fda1fc9f33c4385f9cffe5536413/LICENSE

- [STAG-LLM](https://doi.org/10.1016/j.csbj.2025.09.004)

  > Slone JK, Zhang M, Jiang P, Montoya A, Bontekoe E, Rausseo BN, Reuben A, Kavraki LE. STAG-LLM: Predicting TCR-pHLA binding with protein language models and computationally generated 3D structures. Computational and Structural Biotechnology Journal. 2025;27:3885-3896. doi: 10.1016/j.csbj.2025.09.004

- [NetTCR-2.2](https://doi.org/10.7554/eLife.93934.3)

  > Jensen MF, Nielsen M. Enhancing TCR specificity predictions by combined pan- and peptide-specific training, loss-scaling, and sequence similarity integration. eLife. 2024;12:RP93934. doi: 10.7554/eLife.93934.3

  > Licence: DTU Health Tech Academic Software License Agreement, https://github.com/mnielLab/nettcr-2.2/blob/7cead3fe6dcb539ff8e2d9121586dafca1e059c2/academic_software_license_agreement.pdf

## License

The **code** of tcr-pmhc-analyzer is released under the [MIT licence](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/LICENSE).

The **training data** of the built-in models is **not** MIT licensed. It is downloaded from the upstream tools (see [Training data](#training-data)) and is under their licences, several of which are restrictive (academic or non-commercial use only), as listed below. The full licence texts are shipped verbatim in [`src/tcr_pmhc_analyzer/data/licenses/`](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/src/tcr_pmhc_analyzer/data/licenses/), whose [README](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/src/tcr_pmhc_analyzer/data/licenses/README.md) maps each licence to its models, training file and pinned source URL.

| Model(s) | Training data licensed under | Use |
| -------- | ---------------------------- | --- |
| `nettcr-pan`, `nettcr-peptide` | DTU Health Tech Academic Software License Agreement | Publicly funded academic, educational or research institutions only, for internal research; no commercialisation. Requires `--accept-nettcr-license`; cite NetTCR-2.2. |
| `mixtcrpred`, `mixtcrpred-pan` | MixTCRpred academic non-commercial licence | Academic non-commercial research only; commercial applications require buying the MixTCRpred licence. Requires `--accept-mixtcrpred-license`. |
| `tcren` | [TCRen licence](https://github.com/antigenomics/tcren/blob/cf1e1f0fd562fda1fc9f33c4385f9cffe5536413/LICENSE). Training data derived from [antigenomics/tcren](https://github.com/antigenomics/tcren); `mhc.class` column renamed to `mhc_class`, see the [licences README](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/src/tcr_pmhc_analyzer/data/licenses/README.md). | Educational, research and non-profit use by non-profit institutions only. Requires `--accept-tcren-license`. Cite the TCRen repository. |
| `tabr-bert` | TABR-BERT licence (Apache 2.0 text with non-commercial terms) | Non-commercial only. Requires `--accept-tabr-bert-license`. |
| `ergo2`, `ergo2-vdjdb`, `ergo2-mcpas` | MIT | See licence text. |
| `atm-tcr` | [CC BY 4.0](https://github.com/Lee-CBG/ATM-TCR/blob/a1e02e17d657626d3aa091bf0c92fc7ca8c9c924/LICENSE.md) | Attribution required. The training data is `data/combined_dataset.csv` of [Lee-CBG/ATM-TCR](https://github.com/Lee-CBG/ATM-TCR) ([Cai et al. 2022](https://doi.org/10.3389/fimmu.2022.893247)) with one header line added at runtime; the data rows are unchanged. |
| `tulip-tcr` | GPL 3.0 | See licence text. |
| `stag-llm` | MIT | See licence text. |
| `t2pmhc-gcn`, `t2pmhc-gat` | MIT | See licence text. |

The first four rows are the licence-gated models, see [Licence acceptance](#licence-acceptance). Each licence restricts use differently, as stated in its row; read it before use.