Metadata-Version: 2.5
Name: tcr-pmhc-analyzer
Version: 0.5.0
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

`create-analyzer-table` and `benchmark --input` 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 when you use 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 of a built-in model must contain the following columns.
A custom model needs only four of them. See [Prediction file](#prediction-file).

| Column                     | Description |
|----------------------------|-------------|
| `identifier`               | Unique sample identifier (used for merging). Each identifier must appear once per prediction file. The command does not check this, and a repeated identifier gives an extra table row. |
| `binding_score`            | Model's predicted binding score |
| `binder`                   | Ground truth label (0/1). `benchmark` needs it. |
| `peptide_sequence_aa`      | Peptide sequence |
| `junction_aa_tra`          | CDR3 alpha chain sequence |
| `junction_aa_trb`          | CDR3 beta chain sequence |
| `v_call_tra`, `v_call_trb` | V gene alpha/beta |
| `j_call_tra`, `j_call_trb` | J gene alpha/beta |
| `mhc_allele_1`             | MHC allele |
| `species`                  | Source species |
| `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       | Stop with an error when a leakage check is skipped. Default: log a warning. See [`--strict-leakage`](#--strict-leakage). |
| `--training-data-dir DIR` | | No       | Directory of raw upstream training files (see [`fetch-training-data`](#fetch-training-data)). The command verifies each file by sha256 and downloads nothing. Default: download on first use into the cache. See [Training data](#training-data). |
| `--accept-nettcr-license` | | For `nettcr-*` | Confirm the [NetTCR-2.2 licence](#licence-acceptance). |
| `--accept-mixtcrpred-license` | | For `mixtcrpred` and `mixtcrpred-pan` | Confirm the [MixTCRpred licence](#licence-acceptance). |
| `--accept-tcren-license` | | For `tcren` | Confirm the [TCRen licence](#licence-acceptance). |
| `--accept-tabr-bert-license` | | For `tabr-bert` | Confirm the [TABR-BERT licence](#licence-acceptance). |

Each `--accept-*-license` flag confirms that you have read the licence and that your use complies. See [Licence acceptance](#licence-acceptance).

**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 a training row of the model matches the sample (data leakage). `False` if the sample was checked and no training row matches. Empty if the sample could not be checked. Empty does not mean clean. See [Data leakage detection](#data-leakage-detection)
- `seen_in_{model}`: `True` if the peptide was seen in the model's training data

The command prints a leakage summary with three counts per model. The percentage is the share of flagged rows among the checked rows:

```text
sample_in_train_m: 1 flagged, 1 clean, 1 unchecked (50.0% of the 2 checked rows flagged)
```

When no row was checked, the brackets read `(no row was checked)` instead of a percentage.

**Reasons file:** the command also writes `<output without extension>.reasons.tsv` next to the table. Example: `-o out/public_set_analyzer_table.tsv` also writes `out/public_set_analyzer_table.reasons.tsv`. The file has one row per model with unchecked rows:

| Column | Content |
|--------|---------|
| `model` | Model name |
| `unchecked_rows` | Number of rows with an empty `sample_in_train_{model}` cell |
| `total_rows` | Number of rows in the table |
| `reason` | The reason sentence of the warning (see [The three values](#the-three-values-of-sample_in_train_model)) |

A file with only the header means that every row of every model was checked. [`create-dashboard`](#create-dashboard) shows the reasons.

### `benchmark`

Generates ROC curve plots comparing model performance, split by seen vs unseen peptides. Samples that are flagged or unchecked for data leakage are removed from the leakage-removed curves.

```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) |
| `--strict-leakage`  |       | No       | Stop with an error when a leakage check is skipped. With `--table`, an empty `sample_in_train_{model}` cell is an unchecked row. The check runs before any plot. See [`--strict-leakage`](#--strict-leakage). |
| `--training-data-dir DIR` | | No (only with `--input`) | As for `create-analyzer-table`. |
| `--accept-nettcr-license` | | For `nettcr-*` with `--input` | As for `create-analyzer-table`. |
| `--accept-mixtcrpred-license` | | For `mixtcrpred` and `mixtcrpred-pan` with `--input` | As for `create-analyzer-table`. |
| `--accept-tcren-license` | | For `tcren` with `--input` | As for `create-analyzer-table`. |
| `--accept-tabr-bert-license` | | For `tabr-bert` with `--input` | As for `create-analyzer-table`. |

\* 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"
```

**Leakage in the benchmark.** Every leakage-removed curve drops the flagged rows (`True`) and the unchecked rows (empty) of the model. An unchecked row could be a leak, so the clean curve must not keep it. Exception: a row that a custom model did not score is not dropped from the curves of the other models (see [How a custom model is compared](#how-a-custom-model-is-compared)). The log reports both counts per model. A model whose whole `sample_in_train_{model}` column is empty has no curve in the leakage-removed regimes. The other models keep their curves. The model stays in `entire_dataset/` and `seen_unseen/`. See [Data leakage detection](#data-leakage-detection).

**Labels in the benchmark.** The curves need the `binder` labels. This applies to built-in and custom models. `benchmark` skips a model with a warning when `binder` is empty in every row that the model scored. It stops with an error when `binder` is empty in every row of the table.

**Output files:** the command writes ROC and PR curves for four regimes. Each regime has its own subdirectory of `--output`. Files carry the prefix `ROC_` or `PR_`.

| Subdirectory               | Files                                                                | Samples in the curve |
|----------------------------|----------------------------------------------------------------------|----------------------|
| `entire_dataset/`          | `ROC_curve.png`, `PR_curve.png`                                      | All samples. No leakage removal. Seen and unseen peptides are mixed. |
| `seen_unseen/`             | `ROC_curve_seen.png`, `ROC_curve_unseen.png`, and the `PR_` pair     | Each model on the peptides it has seen or not seen. No leakage removal. |
| `seen_unseen_no_leakage/`  | the same four file names                                             | As `seen_unseen/`. Each model also drops its own flagged and unchecked rows. A model that cannot be checked has no curve. |
| `shared_seen_unseen/`      | the same four file names                                             | One shared sample set for all models. The peptide must be seen (or unseen) by all models. Flagged and unchecked rows of any model are dropped. |

The "leakage-removed" regimes are `seen_unseen_no_leakage/` and `shared_seen_unseen/`.

### `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. The command lists skipped gated models with the flag they need. |
| `--accept-nettcr-license` | | For `nettcr-*` | As for `create-analyzer-table`. |
| `--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`. |

The command does not download files that are already present with the right sha256. It 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 one self-contained, **offline** interactive HTML dashboard from a directory of analyzer tables. Each `.csv` or `.tsv` file in the directory becomes one selectable dataset. The browser recomputes everything live. The dashboard offers:

- a model toggle and filter regimes
- a **dataset overview**: positive, negative and peptide counts, split into seen and unseen
- a **per-model overview**: seen and unseen rows and peptides, and leaked, clean and not checked rows. An **Unchecked leakage reasons** table below it gives the reason for each model with not checked rows
- **per-model ROC** and **per-peptide AUC**
- a **dataset composition & filtering** section: positive/negative and leakage-removed rows per peptide, and a peptide-attrition funnel

The HTML inlines Plotly and the full tables. It makes no external requests (no CDN) and 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 reads the analyzer tables that `create-analyzer-table` produces. It uses the `binding_score_{model}`, `sample_in_train_{model}` and `seen_in_{model}` columns.

- Custom and arbitrarily named models work. The command detects the model set across all files and gives unknown names fallback colors.
- A dataset with no results for a model omits that model from its plots.
- A file named `<id>_analyzer_table.tsv` (as the upstream `tcrpmhcbinding` pipeline emits it) appears in the dropdown as `<id>`.
- A row with an empty `sample_in_train_{model}` flag shows as `Not checked`. The strict leakage-removed regimes (`Seen/Unseen + leaked and unchecked removed (per model)` and `Shared Seen/Unseen`) exclude that row. They leave a model with no checked row out.
- The regime `Seen/Unseen + leaked removed, unchecked kept (per model)` removes only the leaked rows of each model. Example: a model with 10 leaked, 60 clean and 30 not checked rows keeps 90 rows in this regime and 60 rows in the strict per-model regime. A model with no checked row takes part. The shared regime has no such variant.
- A `<table>.reasons.tsv` file next to a table (written by [`create-analyzer-table`](#create-analyzer-table)) is not a dataset. The dashboard shows its reason sentences in the **Unchecked leakage reasons** table. Without the file, the table reads "No reason recorded".

**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 under restrictive licences. When you download and use it, you are subject to those licences. Each licence restricts use, 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 it reads or downloads 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 package ships the full text of every licence 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. The analyzer table holds `binding_score_{model}` exactly as the model reported it, so `binding_score_tcren` stays inverted there. Both consumers correct for it in memory. `benchmark` negates the scores before it computes ROC and PR curves. `create-dashboard` negates them when it serializes the table into the HTML. AUC and AUPRC are therefore directly comparable across all models. Code that reads the table itself must account for the direction.

> **Note on the `stag-llm` training set.** STAG-LLM trains in two stages. First, a self-supervised ESM-2 masked-language-model pretraining on a large sequence-only corpus (`full_seq_df_new.csv`, binders only, no labels). Second, 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, because it holds the labeled pairs that the model actually learned. The analyzer treats the MLM pretraining corpus like ESM-2's own pretraining and does **not** count it as label leakage. To experiment with the full sequence corpus, 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 one run with `--ergo2_variant both`. The pipeline then emits two prediction columns, `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 checked against its own training set:
- `sample_in_train_ergo2-vdjdb` and `seen_in_ergo2-vdjdb` use the vdjdb training data.
- `sample_in_train_ergo2-mcpas` and `seen_in_ergo2-mcpas` use 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. It verifies the file against a stored sha256 and converts it in memory to the column names that the analyzer uses. A file that fails its checksum is never used: the command stops with an error that names 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; V/J/MHC cells garbled upstream with U+FFFD are kept; a garbled V/J cell is cut at U+FFFD and compared by gene family (`TRBV06-` + U+FFFD reads as `TRBV6`) or as a gene without allele, and only a garbled MHC cell (`H-2Db` + U+FFFD) is a wildcard |
| `ergo2` (`--ergo-version vdjdb`), `ergo2-vdjdb` | same repository, `Samples/vdjdb_train_samples.pickle` | 12.5 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 |

The command downloads only the files of the models in your samplesheet.

**Negatives count as seen.** Several upstream files contain the negative (non-binding) pairs that the model trained on: ERGO-II, ATM-TCR, NetTCR-2.2, t2pmhc and STAG-LLM. The analyzer keeps them. A prediction that matches a training negative is flagged in `sample_in_train_{model}`, and its peptide counts in `seen_in_{model}`, because the model saw that pair during training.

**Cache.** The analyzer stores downloaded files unchanged in `$TCR_PMHC_ANALYZER_CACHE` if set, else `$XDG_CACHE_HOME/tcr-pmhc-analyzer`, else `~/.cache/tcr-pmhc-analyzer`. It verifies each file on every use and downloads a corrupt cached file again once. A download goes to a temporary `.part` file and moves 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 CLI commands check the licence flags. `Analyzer.read_training_data` and `tcr_pmhc_analyzer.training_data.load_training_source` download without a licence check when you call them directly from Python. The licences under [Licence acceptance](#licence-acceptance) still bind you.

## Custom models

Any `model` name that is not in the [Supported models](#supported-models) table is a custom model. This section covers what is specific to custom models. For the matching rules of built-in models, see [Data leakage detection](#data-leakage-detection). For custom models, see [How a custom model is compared](#how-a-custom-model-is-compared).

### When you need a custom model

A `model` name in the samplesheet is a **custom model** when it is not in the [Supported models](#supported-models) table and is not `ergo2`, `ergo2-vdjdb` or `ergo2-mcpas`. The analyzer detects it automatically. No registration step exists.

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

- It merges into the analyzer table on `identifier`, like every other model. It sets the shared columns only for rows that no built-in or earlier custom file holds.
- `sample_in_train_{model}` holds the data-leakage flag (`True`, `False`, or empty when the row could not be checked).
- `seen_in_{model}` holds the seen-peptide flag.
- `benchmark` and `create-dashboard` support it fully.

You must supply one thing that built-in models get for free: a training-data file, in the `training_data` column.

### Samplesheet

`training_data` is required for custom rows. It may be blank or omitted for built-in rows, so one samplesheet can mix both. Each custom row needs its own `training_data` entry. The number of custom rows has no limit.

```tsv
model	file	training_data
ergo2	results/ergo2_predictions.csv
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
```

> **Missing `training_data`.** If the `training_data` cell of a custom model 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()` reads the `training_data` cell only when the row's model is custom. 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. Use a distinct model name to force the custom path.

### Prediction file

The `file` of a custom model must hold four columns of the [Input format](#input-format): `identifier`, `binding_score`, `peptide_sequence_aa` and `binder`. A missing required column stops the command with an error that names it.

The other nine columns are optional: `species`, `mhc_class`, `mhc_allele_1`, `v_call_tra`, `j_call_tra`, `junction_aa_tra`, `v_call_trb`, `j_call_trb` and `junction_aa_trb`. A custom file without them loads. The command logs one warning that names the model, the file and the missing columns. Their cells stay empty in the analyzer table for rows that only this model holds. A built-in model must still hold all 13 columns.

Extra columns are allowed.

`benchmark` needs the `binder` labels. It skips a model with a warning when `binder` is empty in every row that the model scored. It stops with an error when `binder` is empty in every row of the table.

The leakage check also reads every other leakage column that the file holds, for example `anarcii_cdr3b`. The names are in `src/tcr_pmhc_analyzer/data/leakage_columns.tsv`.

Write the values that your model received. Write a missing value as an empty cell. To leave a column out of the check, leave it out of the training file. Only the columns that both files hold are compared. See [How a custom model is compared](#how-a-custom-model-is-compared).

### Training-data file

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

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

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

**Leakage match keys.** A custom model uses the `__custom__` row of `src/tcr_pmhc_analyzer/data/leakage_keys.tsv`. That row lists every candidate column. A column takes part in the match only when the prediction file and your training file both hold it. A value is usable when it is not empty. A junction value must also be an amino-acid string. The columns of your training file therefore decide the effective match rule. The rules per column are in [How a custom model is compared](#how-a-custom-model-is-compared).

| Columns your training file ships | Resulting match rule | Same columns as |
|----------------------------------|----------------------|-----------------|
| `peptide_sequence_aa, junction_aa_tra, junction_aa_trb, v_call_tra, v_call_trb, j_call_tra, j_call_trb, mhc_allele_1` | all eight columns | `t2pmhc-gcn`, `t2pmhc-gat` |
| `peptide_sequence_aa, junction_aa_trb, mhc_allele_1` (beta only) | `(peptide_sequence_aa, junction_aa_trb, mhc_allele_1)` | `tabr-bert` |
| `peptide_sequence_aa, junction_aa_tra, junction_aa_trb` (no MHC) | `(peptide_sequence_aa, junction_aa_tra, junction_aa_trb)` | `stag-llm` |
| `peptide_sequence_aa, junction_aa_trb` (beta only, no MHC) | `(peptide_sequence_aa, junction_aa_trb)` | `atm-tcr` |
| `peptide_sequence_aa, mhc_allele_1` only | no anchor column: every row stays unchecked and `sample_in_train_{model}` is empty | none |

Every other column of `leakage_columns.tsv` also takes part when both files hold it, for example `mhc_class` and `anarcii_cdr3b`. An absent optional column is dropped from the match without a warning. An empty value in a present column is a wildcard for that row.

A training file with none of the anchor columns that the prediction file holds leaves every row unchecked. The anchor columns are `junction_aa_tra`, `junction_aa_trb`, `anarcii_cdr3a` and `anarcii_cdr3b`. The warning names the column to rename. With `--strict-leakage`, the command stops instead.

**Column names.** The training file must use the AIRR names `peptide_sequence_aa`, `junction_aa_tra`, `junction_aa_trb`, `v_call_tra`, `v_call_trb`, `j_call_tra` and `j_call_trb`. The matcher does not see a column with another name. A training file with no `peptide_sequence_aa` column stops the run with an error. Rename the columns before you set `training_data`.

**No samplesheet equivalent for `MODEL_MATCH_COLS`.** A custom model needs none. It reads the `anarcii_*` columns, and every other catalogue column, from its own results file. See [Step 2](#step-2-the-model-keys).

### How a custom model is compared

A custom model is checked on its own results file against its own training file. A built-in model keeps the rules of [Data leakage detection](#data-leakage-detection).

**Compared columns.** A column is compared when both files hold it and `leakage_columns.tsv` lists it. To exclude a column, remove it from the training file. A column that is empty in the whole results file is not compared.

**Match rule.** Two values match when they are the same text. Case and surrounding whitespace do not count. In a junction, a leading `C` and a trailing `F` or `W` do not count. An empty cell matches every value.

**Format.** Gene names and alleles are not parsed. Write them in the same format in both files.

| Results file | Training file | Flag |
|---|---|---|
| `A0201` | `A0201` | True |
| `A0201` | `A2402` | False |
| `HLA-A*02:01` | `A0201` | False |

The table assumes that peptide `GILGFVFTL` and junction `CASSIRSSYEQYF` match in both files.

**Placeholders.** In a junction column, a value that is not an amino-acid string counts as an empty cell. Examples: `unknown`, `<MIS>` and `CASSXRSSYEQYF` (it contains `X`). In every other column, a placeholder is a value. Two `<MIS>` cells in `mhc_allele_1` match. A row with no usable anchor value stays unchecked.

**Rows without a score.** A row with an empty `binding_score` is not checked. A row that the results file lacks is not checked either. Its `sample_in_train_{model}` cell stays empty. The leakage summary counts the cell as unchecked. `benchmark` and `--strict-leakage` ignore the cell.

Example: the table has 5 rows, and `my_model` scores 3 of them. The summary shows `2 unchecked`. `--strict-leakage` does not stop, and `benchmark` does not drop the 2 rows from the other models.

**Gate.** The [canonical pattern gate](#step-1-the-canonical-pattern-gate) does not run.

The table lists the rules per column. The built-in column shows the rules of [Data leakage detection](#data-leakage-detection).

| Column | Custom model | Built-in model |
|---|---|---|
| `peptide_sequence_aa` | exact | exact. The gate makes a non-amino-acid cell a wildcard. |
| `junction_aa_tra`, `junction_aa_trb` | junction rule. A value that is not an amino-acid string is a wildcard. | The same rule. The gate makes a non-amino-acid cell a wildcard. |
| `anarcii_cdr1a` to `anarcii_cdr3b` | exact | exact |
| `v_call_*`, `j_call_*` | exact text. `TRBV19` does not match `TRBV19*01`. | Gene rule. Compare the allele when both sides have one, else the gene. An unreadable value is a wildcard. |
| `mhc_allele_1` | exact text. `A2` does not match `A*02`. | MHC rule. Strip `HLA-`, expand `A2` to `A*02`, compare the first `n` fields (`n` = smaller field count). An unreadable value is a wildcard. |
| `mhc_class` | exact | exact. Only `MHC-I`, `MHC-II` and `MHC-nonclassical` are readable. |
| Empty cell | wildcard | wildcard |
| Canonical gate | does not run | runs on the test side only. A non-canonical cell is a wildcard for its row, with a warning. |

### Benchmarking and dashboards

`benchmark` and `create-dashboard` have no model allowlist and no registration step. Both discover models from `binding_score_{model}` columns (`_get_available_models` in `benchmark.py`). A custom model is therefore fully benchmarkable and appears in the dashboard next to the built-in models. `create-dashboard` gives it a fallback color unless you set one with `--colors` (see [`create-dashboard`](#create-dashboard)).

One ordering constraint exists. `benchmark` requires `sample_in_train_{model}` and `seen_in_{model}` in its input. Run `create-analyzer-table` first, or pass `benchmark --table` with its output.

### Limitations

- **Score direction is not configurable.** The analyzer treats only the hardcoded `tcren` as lower-is-better (see the [note on score direction](#supported-models)). No samplesheet or CLI flag marks a custom model the same way. If the raw score of your model is lower-is-better, negate it before you feed it in. Otherwise the ROC/PR curves and the dashboard plots come out inverted.
- **A missing peptide column fails differently in the two checks.** The leakage check leaves every row unchecked. The seen-peptide check raises a raw `KeyError: 'epitope'` instead of a helpful message.
- **A wrong file extension fails confusingly.** Only lowercase `.csv` and `.tsv` are recognized. Any other extension returns a string instead of raising an error. This surfaces downstream as an unrelated `TypeError` or `AttributeError`.
- **A built-in model name is never custom.** A model named like an entry of the Supported models table loads the built-in training data and its `leakage_keys.tsv` row. A `training_data` cell on that row is ignored.

### 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` or empty from the leakage matcher. It uses the key columns that `training/my_model_train.csv` and the prediction file both carry (see the table above). Empty means the row could not be checked.
- `seen_in_my_model`: `True` or `False`, from whether the `peptide_sequence_aa` of the row appears in the peptide column of `training/my_model_train.csv`

**Walkthrough.** Assume `training/my_model_train.csv` ships only `peptide_sequence_aa` and `junction_aa_trb` (a beta-only training set). Per the match-key table, `sample_in_train_my_model` then uses `(peptide_sequence_aa, junction_aa_trb)`, the same columns as `atm-tcr`.

- A prediction row is `True` when its peptide equals a training peptide and its beta junction matches the junction of that training row. See the junction rule in [Step 4](#step-4-the-comparison).
- The analyzer ignores `mhc_allele_1`, `junction_aa_tra` and the V/J columns, because the training file does not have them.
- A prediction row with no beta junction and no other usable anchor value is not checked. Its flag is empty.
- Example: a row has peptide `GILGFVFTL`, no beta junction, and alpha junction `CAVRDSNYQLIW`. The training file has no alpha column, so the alpha junction cannot be compared. The flag is empty when `GILGFVFTL` is in the training file. The flag is `False` when it is not.
- A built-in model differs. The key of `atm-tcr` holds no alpha junction, so a row with no beta junction is always empty.
- `seen_in_my_model` does not depend on the match-key table. It is `True` whenever the `peptide_sequence_aa` of the row alone is present in the peptide column of the training file.

The `benchmark -m "ergo2 my_model"` command above consumes these three columns. `create-dashboard` picks them up automatically from the same `analyzer_table.csv`, as for any built-in model.

## How it works

1. **Merge**: The analyzer merges prediction outputs from multiple models on the `identifier` column into a single DataFrame.
2. **Data leakage detection**: The analyzer checks each sample against the training data of each model (see [Training data](#training-data)) and flags samples that appear in a training set. One matcher serves every model. A sample that cannot be checked gets an empty flag. See [Data leakage detection](#data-leakage-detection).
3. **Seen peptide detection**: The analyzer checks each peptide against the training data to identify whether the model saw it during training.
4. **Benchmarking**: The analyzer generates ROC curves after it removes leaked samples, separately for seen and unseen peptides.

### Data leakage detection

`sample_in_train_{model}` says whether a training row of the model matches a test row. One matcher serves every model. Two data files decide which columns each model uses: the pattern file (Step 1) and the key file (Step 2).

Terms in this section:

- **Test table**: the merged analyzer table. It has one row per sample.
- **Training table**: the converted training data of one model.
- **Key**: the set of columns that a model was trained on.
- **Anchor column**: one of `junction_aa_tra`, `junction_aa_trb`, `anarcii_cdr3a` and `anarcii_cdr3b`. These columns identify the clonotype.

#### The three values of `sample_in_train_{model}`

| Value   | Meaning |
|---------|---------|
| `True`  | At least one training row matches the sample. The sample is a leak. |
| `False` | The sample was checked and no training row matches. |
| empty   | The sample could not be checked. **Empty does not mean clean.** |

A plain sum over the column hides the empty rows. Count `True`, `False` and empty rows separately. A written CSV or TSV file holds an empty cell for each unchecked row. The commands treat the empty rows as follows:

- `create-analyzer-table` prints a count of each value per model (see [`create-analyzer-table`](#create-analyzer-table)).
- `benchmark` drops flagged and unchecked rows from every leakage-removed curve (see [`benchmark`](#benchmark)).
- `create-dashboard` shows an unchecked row as `Not checked`. It excludes the row from the strict leakage-removed regimes and keeps it in the per-model regime `leaked removed, unchecked kept` (see [`create-dashboard`](#create-dashboard)).

A row stays empty for one of these reasons:

1. The model key has no `peptide_sequence_aa` column, or no anchor column. Nothing can be compared.
2. The row has no usable `peptide_sequence_aa` value. Or the row has no usable value in any anchor column of the key. A non-canonical cell is not usable, see [Step 1](#step-1-the-canonical-pattern-gate).
3. The training table cannot answer the question. It has no `peptide_sequence_aa` column, no anchor column of the key, no rows, or no usable peptide.
4. The training table holds a chain in an anchor column that the prediction table does not have, and a training row fills only that column. The matcher never compared that row against the prediction row.
5. The row holds a non-canonical value in an anchor column, and a training row of the same peptide holds its chain only in that column. The matcher never compared that row either.
6. A custom model did not score the row, or its results file does not hold the row. `benchmark` and `--strict-leakage` ignore this cell, see [How a custom model is compared](#how-a-custom-model-is-compared).

The warning gives the reason as a sentence. `create-analyzer-table` also saves it in the [reasons file](#create-analyzer-table). For reason 3, it names the column to rename. For reason 4, it names the column to add to the prediction file. For reason 5, it names the column to repair. For reason 6, it gives the count of rows that the results file lacks or did not score.

Reasons 4 and 5 ask the question inside the peptide group. A training row with a different peptide can never match, so it never makes a row unchecked.

A training table can have only some of the anchor columns of the key. The matcher then keeps every `True` flag. A `False` flag becomes empty for a row only when some training row has no usable value in any anchor column that both tables hold and the test row fills. That training row may hold its TCR in the missing column. Every other `False` flag stays `False`. Example: a custom model with a beta-only training file. A row with a beta junction stays `False` when every training row has a beta junction.

#### Step 1: the canonical pattern gate

The gate does not run for a custom model. See [How a custom model is compared](#how-a-custom-model-is-compared).

The analyzer checks every cell of a candidate column of the test table against a canonical pattern before it matches. A candidate column is any column in at least one model key. The patterns are in `src/tcr_pmhc_analyzer/data/leakage_columns.tsv`. In an installed package, run `python -c "import tcr_pmhc_analyzer, pathlib; print(pathlib.Path(tcr_pmhc_analyzer.__file__).parent / 'data')"` to find the `data` directory.

That file is the catalogue of every leakage column. Each row gives one column its `role` (`peptide`, `anchor` or `context`), its `comparator`, its `readable` rule, its canonical `pattern` and its `chain_name`. An empty `pattern` means the gate does not check that column. The six `anarcii_*` columns have an empty pattern. The patterns mirror the rows of the pipeline's `assets/input_rules.tsv` that leakage uses, except the junction patterns. They accept any amino acid string, so a trimmed CDR3 is checked.

| Column                | Pattern                                      | Passes             | Fails                                    |
|-----------------------|----------------------------------------------|--------------------|------------------------------------------|
| `mhc_allele_1`        | `^HLA-[A-Z0-9]+\*\d{2,3}:\d{2,3}$`            | `HLA-A*02:01`      | `HLA-A*02:01:01`, `A*02:01`, `HLA-A*02`  |
| `peptide_sequence_aa` | `^[ACDEFGHIKLMNPQRSTVWY]+$`                  | `GILGFVFTL`        | `GILGFVFTLX`, `GIL GFV`                  |
| `junction_aa_tra`     | `^[ACDEFGHIKLMNPQRSTVWY]+$`                  | `CAASGGGSQGNLIF`   | `CAASGG-GSQGNLIF`                        |
| `junction_aa_trb`     | `^[ACDEFGHIKLMNPQRSTVWY]+$`                  | `ASSIRSSYEQY`      | `CASS IRSSYEQYF`                         |
| `v_call_tra`          | `^TRAV\d+(-\d+)?(/DV\d+)?\*\d{2}$`            | `TRAV29/DV5*01`    | `TRAV29/DV5` (no `*NN`)                  |
| `j_call_tra`          | `^TRAJ\d+\*\d{2}$`                          | `TRAJ42*01`        | `TRAJ42`                                 |
| `v_call_trb`          | `^TRBV\d+(-\d+)?\*\d{2}$`                    | `TRBV20-1*01`      | `TRBV20-1`                               |
| `j_call_trb`          | `^TRBJ\d-\d\*\d{2}$`                         | `TRBJ2-7*01`       | `TRBJ2-7`                                |
| `mhc_class`           | `^(MHC-I\|MHC-II\|MHC-nonclassical)$`          | `MHC-I`            | `MHCI`, `I`                              |

The six `anarcii_*` columns have no pattern. They always pass.

- The check ignores case and surrounding whitespace. It ignores empty values.
- The check is per cell. A bad cell is a wildcard for its own row only. Every other row keeps its value in that column.
- The warning names the column, the number of bad cells, the first three bad values with their identifiers, and the models whose key uses the column. Use them to repair the input.
- Example: `A*02:01` without the `HLA-` prefix fails `mhc_allele_1`.
- Test values must be in the pipeline format. A value outside its pattern, such as `A*02:01` without `HLA-` or `TRBV19` without an allele, is ignored for its own row.
- Training values are parsed tolerantly by the comparison rules in [Step 4](#step-4-the-comparison). The gate does not check them.

A bad cell differs from an empty cell in one way. An empty junction means the row has no such chain. A bad junction means a chain the analyzer cannot read.

| Bad cell | Effect on its row |
|---|---|
| context column, such as `mhc_allele_1` | Matches any value, so the match of that row is wider. |
| anchor column | Matches any value. If a training row of the same peptide holds its chain only in that column, the row is unchecked instead of clean. |
| `peptide_sequence_aa` | The row is unchecked. |

The unchecked-rows warning that follows names the model and its reason.

#### Step 2: the model keys

The file `src/tcr_pmhc_analyzer/data/leakage_keys.tsv` holds the keys. It is in the same `data` directory as the pattern file. It has one row per training key. The columns are `training_key` and `key_columns` (comma-separated). A model with no row uses the `__custom__` row. The hyphenated ERGO-II names use the underscored training key (`ergo2-vdjdb` uses `ergo2_vdjdb`).

| Model                                                                        | Key                                                                         |
|------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| `ergo2_mcpas`, `ergo2_vdjdb`                                                 | peptide, both junctions, V and J of both chains, MHC allele, `mhc_class`    |
| `mixtcrpred`, `mixtcrpred-pan`, `t2pmhc-gcn`, `t2pmhc-gat`, `tcren`, `stag-llm` | peptide, both junctions, V and J of both chains, MHC allele              |
| `tulip-tcr`                                                                  | peptide, both junctions, MHC allele                                         |
| `tabr-bert`                                                                  | peptide, beta junction, MHC allele                                          |
| `atm-tcr`                                                                    | peptide, beta junction                                                      |
| `nettcr-peptide`, `nettcr-pan`                                               | peptide, MHC allele, the six `anarcii_*` loops                              |
| custom models (`__custom__`)                                                 | every candidate column                                                      |

To change a model key, edit its row in `leakage_keys.tsv`. To add a built-in model, add a row. Use only column names that have a row in `leakage_columns.tsv`. To use a new column, add its row there first. The analyzer reads the file once per run and checks every row. A bad row raises an error that names the file and the line. The `__custom__` row must stay. The file is package data. Edit it in the source tree, and reinstall unless you use an editable install. An edit to the copy in an installed package also works, but the next reinstall overwrites it.

`nettcr-peptide` and `nettcr-pan` read their six `anarcii_*` loops from the prediction file. The analyzer derives that list from `leakage_keys.tsv`: it is the key columns of the model that are not analyzer table columns. The analyzer carries them in memory and never writes them to the analyzer table. The registry is built-in only and has no samplesheet knob.

#### Step 3: the row check

The matcher checks each test row once per model before it reads a training row.

1. The row must have a non-empty `peptide_sequence_aa`.
2. The row must have a non-empty value in at least one anchor column of the key.

A row that fails stays empty. Example: a row with no beta junction cannot be checked for `atm-tcr`. The `atm-tcr` key holds only the peptide and the beta junction.

#### Step 4: the comparison

The matcher compares one test row with one training row as follows.

1. Start from the model key. A non-canonical test cell is empty for this comparison.
2. Keep a column only when both values are usable. A value is unusable when it is empty. It is also unusable when its rule cannot read it. Example: a free-text `mhc_allele_1` such as a cell line name, or a V or J value that no rule can read. An unusable value is a wildcard.
3. The peptide must survive. At least one anchor column must survive. Otherwise the training row does not match.
4. Compare each surviving column with the rule for its type.
5. The training row matches when all surviving columns agree.

Every rule strips whitespace and ignores case first.

| Column type                             | Rule |
|-----------------------------------------|------|
| peptide, `mhc_class`, `anarcii_*` loops | Exact match. |
| junction                                | The sets of variants must intersect. A variant is the value, the value without a leading `C`, without a trailing `F` or `W`, or without both. The rule removes at most one trailing residue. `CASSIRSSYEQYF` matches `CASSIRSSYEQYW`. |
| V and J gene                            | Split the call into gene and allele. The allele follows `*` or `:`, so `TRBJ2-7:01` reads as `TRBJ2-7*01`. Leading zeros in a gene number are removed, so `TRBV06-05` reads as `TRBV6-5`. Compare gene and allele when both values have an allele. Otherwise compare the gene. A list such as `TRBV6-1/6-5` or `TRBV12-3,12-4` matches when any of its calls matches. A garbled value is read up to the first U+FFFD: `TRBV06-` compares at gene family (`TRBV6`), `TRAV12-2` as the gene. A value that no rule can read, such as `TRBJ1-1/2`, is a wildcard. |
| `mhc_allele_1`                          | Strip `HLA-`. Expand `A2` to `A*02`. Split on `:`. Compare the first `n` fields, where `n` is the smaller field count. A bare locus such as `HLA-A` is a wildcard. |

The rule never pads a missing field. `A*02` does not become `A*02:01`, because that would invent a field.

The analyzer compares a V or J call at allele level when both sides carry an allele. `TRBV19*01` and `TRBV19*02` are different alleles, so they do not match. The old `mixtcrpred` matcher stripped the suffix and treated them as the same call. The new rule is stricter on purpose. The `mixtcrpred` and `mixtcrpred-pan` training file is the one that mixes calls with and without the suffix, so this is where the change is visible.

#### `--strict-leakage`

The flag exists on `create-analyzer-table` and on `benchmark`. It turns every skip into an error. A skip is a non-canonical cell in a key column or an unchecked row. Without the flag, each skip is a warning. With the flag, the command stops with exit code 2.

`benchmark --table` reads the flags from the file. An empty `sample_in_train_{model}` cell counts as an unchecked row. The `benchmark` check runs before any plot, so a strict run leaves no partial output.

#### Known limitations

- **Anarcii numbering drift.** The six `anarcii_*` columns in the NetTCR training file and in a NetTCR prediction file come from two separate anarcii runs. If the numbering schemes of the two runs disagree, the loop boundaries shift and the match silently under-counts true leakage. The [canonical pattern gate](#step-1-the-canonical-pattern-gate) cannot detect this, because the `anarcii_*` columns have no pattern.
- **Column name and content of `junction_aa_*`.** The name `junction_aa_tra`/`junction_aa_trb` states that the value is a junction (with anchors). Some training sources store the trimmed CDR3 without anchors, and `tabr-bert` is mixed. The converter still writes these values to `junction_aa_*`, so the column name does not match the content for these sources. The junction rule tolerates a missing leading `C` or trailing `F` or `W`, so the match still works.
- **Leakage uses the original input values.** For a built-in model, leakage is matched on the values in your input file. It does not use the values each model received. The pipeline parser changes some values. It applies `normalize_hla` to the MHC for ERGO-II, TABR-BERT and TULIP-TCR. It center-crops the CDRs for NetTCR (A3 maximum 22, B3 maximum 23). The analyzer matches NetTCR on the six uncropped `anarcii_*` loops. A custom model uses the values of its own results file instead. See [How a custom model is compared](#how-a-custom-model-is-compared).

## 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. The analyzer downloads it from the upstream tools (see [Training data](#training-data)), and it is under their licences. Several of these licences are restrictive (academic or non-commercial use only), as the table below lists. The package ships the full licence texts verbatim in [`src/tcr_pmhc_analyzer/data/licenses/`](https://github.com/qbic-pipelines/tcr-pmhc-analyzer/blob/main/src/tcr_pmhc_analyzer/data/licenses/). Its [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. |
