Metadata-Version: 2.2
Name: tcren
Version: 4.4.3
Summary: TCR-pMHC ranking with contact potentials, interface confidence and contact enrichment
Keywords: TCR,immunology,structural-biology,epitope,MHC,bioinformatics
Author-Email: ISALGO laboratory <mikhail.shugay@gmail.com>
License: ISALGO LAB Academic and Non-Commercial Research License
         Version 1.0
         
         Copyright (c) 2026 ISALGO LAB. All rights reserved.
         
         0. DEFINITIONS
         
            "Software" means the software, source code, scripts, models, trained
            parameters, and associated documentation files distributed under this
            license, together with any Modification thereof.
         
            "Modification" means any change to, adaptation of, translation of, or work
            derived from the Software, in whole or in part.
         
            "Output" means any data produced by running the Software, including
            predictions, scores, embeddings, annotations, labels, rankings, alignments,
            simulated or synthetic data, and any file derived from them.
         
            "Model" means any machine-learning or statistical system whose parameters
            are fitted from data, including neural networks, gradient-boosted trees,
            regression models, and any set of trained parameters, whether or not
            distributed together with code.
         
            "You" means the individual or legal entity exercising the rights granted
            below.
         
            "Non-Commercial Use" means use for academic, educational, or scientific
            research purposes from which no commercial advantage or monetary
            compensation is sought or obtained, whether directly or indirectly.
         
            "Commercial Use" means any use that is not Non-Commercial Use, including
            without limitation: (a) use in or to develop a product, service, or
            pipeline that is sold, licensed, rented, or otherwise monetized;
            (b) use by a for-profit entity in connection with its business operations,
            including internal evaluation, benchmarking, or research and development;
            (c) use to provide services to third parties for a fee, including
            consulting, contract research, or hosted or cloud-based provision of the
            Software's functionality; (d) use in research performed under contract for,
            or funded directly by, a for-profit entity for that entity's proprietary
            benefit; and (e) any use described in Section 3.
         
         1. GRANT OF RIGHTS
         
            Permission is hereby granted, free of charge, to any person obtaining a
            copy of the Software, to use, copy, modify, merge, publish, and distribute
            the Software for Non-Commercial Use only, subject to all conditions below.
            No rights are granted other than those expressly stated here; all rights
            not expressly granted are reserved by the copyright holder.
         
         2. PROHIBITED USE
         
            Commercial Use of the Software is prohibited without a separate written
            license signed by the copyright holder.
         
         3. MACHINE-LEARNING AND MODEL TRAINING
         
            3.1 The following are permitted under this license only when the resulting
                Model and its Outputs are themselves put to Non-Commercial Use:
         
                (a) training, fine-tuning, pre-training, continued training, or
                    retraining any Model on the Software, on its source code, or on
                    its Output;
                (b) using the Output as training data, labels, targets, weak
                    supervision, reward or preference signal, validation data, or test
                    data for any Model;
                (c) using the Software or its Output to filter, clean, augment, score,
                    rank, deduplicate, or otherwise curate a data set used to train
                    any Model;
                (d) distilling, pruning, quantizing, compressing, or otherwise
                    deriving a second Model from any Model distributed as part of the
                    Software, or from that Model's Output;
                (e) using the Software or its Output to benchmark, evaluate, validate,
                    tune hyperparameters of, or select among Models;
                (f) embedding the Software, or a Model trained in any of the ways
                    above, in an automated or agent-driven pipeline.
         
            3.2 Each activity listed in Section 3.1 is Commercial Use, and therefore
                prohibited without a separate written license, whenever the resulting
                Model, its Outputs, its parameters, or any system containing it is:
                sold, licensed, rented, hosted, or otherwise monetized; used by or on
                behalf of a for-profit entity in connection with its business
                operations; used to provide services to third parties for a fee; or
                used to support an application for, prosecution of, or exploitation of
                a patent or other proprietary right held by a for-profit entity.
         
            3.3 A Model is subject to this Section regardless of how much of the
                Software or its Output contributed to that Model, and regardless of
                whether the Software or its Output can be recovered from the trained
                parameters. Intermediate steps do not remove a Model from the scope of
                this Section: a Model trained on a data set that was itself produced,
                curated, or filtered using the Software remains subject to it.
         
            3.4 Where a Model is trained partly on the Software or its Output and
                partly on other material, Section 3.2 applies to that Model in full.
         
            3.5 Publication of research results, including trained parameters released
                for Non-Commercial Use under terms no less restrictive than this
                license, is permitted and encouraged.
         
         4. REDISTRIBUTION
         
            You may distribute the Software, with or without Modification, provided
            that You:
         
            (a) retain this license in full, including the copyright notice of
                Section 0 and the disclaimer of Section 9, in all copies and in all
                Modifications;
            (b) do not sublicense the Software or impose any additional or different
                terms, so that every recipient receives exactly the rights and
                restrictions granted here and no more;
            (c) mark each Modification with a prominent notice stating that the file
                has been changed, by whom, and on what date;
            (d) charge no fee for the Software itself, beyond the actual cost of
                physical media or transmission.
         
         5. ATTRIBUTION
         
            Any publication, presentation, preprint, poster, or derived work that makes
            use of the Software must cite this repository, or the corresponding
            publication where one is specified in the repository. Any released Model
            covered by Section 3 must state in its accompanying documentation that the
            Software was used in its construction.
         
         6. NO TRADEMARK OR PATENT RIGHTS
         
            This license grants no right to use the names, trademarks, or logos of
            ISALGO LAB, the copyright holder, or any contributor, whether to endorse or
            promote any work or otherwise, without prior written permission. This
            license grants no patent rights, express or implied, under any patent owned
            or controlled by the copyright holder.
         
         7. TERM AND TERMINATION
         
            The rights granted here apply for as long as You comply with this license
            and terminate automatically, without notice, upon any breach. Rights may be
            reinstated in writing by the copyright holder. Sections 2, 3, 6, 8, and 9
            survive termination. Upon termination You must cease all use of the
            Software and destroy all copies in Your possession, except copies retained
            solely for archival purposes required by law or institutional policy.
         
         8. COMMERCIAL AND TRIAL LICENSING
         
            Parties seeking Commercial Use, use of the Software or its Output in
            training a Model for Commercial Use, an evaluation or trial license, or any
            rights beyond those granted here should contact ISALGO LAB. Such licenses are
            granted only in writing.
         
         9. DISCLAIMER OF WARRANTY AND LIMITATION OF LIABILITY
         
            THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
            THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
            LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
            FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
            DEALINGS IN THE SOFTWARE.
         
            The Software is a research tool. It is not validated for clinical,
            diagnostic, therapeutic, or any other use on which health, safety, or
            financial decisions depend.
         
         10. SEVERABILITY
         
            If any provision of this license is held unenforceable, that provision
            shall be modified to the minimum extent necessary to make it enforceable,
            and the remaining provisions shall remain in full effect.
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: C++
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Project-URL: Homepage, https://github.com/antigenomics/tcren
Project-URL: Repository, https://github.com/antigenomics/tcren
Project-URL: Documentation, https://docs.isalgo.dev/tcren/
Requires-Python: >=3.10
Requires-Dist: biopython>=1.84
Requires-Dist: scipy>=1.11
Requires-Dist: numpy>=1.26
Requires-Dist: threadpoolctl>=3.1
Requires-Dist: polars>=1.0
Requires-Dist: typer>=0.12
Requires-Dist: requests>=2.31
Requires-Dist: huggingface_hub>=0.20
Requires-Dist: arda-mapper>=2.38.4
Requires-Dist: scikit-learn>=1.3
Requires-Dist: rapidfuzz>=3.0
Provides-Extra: topology
Requires-Dist: gudhi<4,>=3.10; extra == "topology"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.8; extra == "viz"
Requires-Dist: py3Dmol>=2.0; extra == "viz"
Requires-Dist: pillow>=10; extra == "viz"
Provides-Extra: marimo
Requires-Dist: marimo>=0.16; extra == "marimo"
Requires-Dist: matplotlib>=3.8; extra == "marimo"
Requires-Dist: py3Dmol>=2.0; extra == "marimo"
Requires-Dist: pillow>=10; extra == "marimo"
Provides-Extra: docs
Requires-Dist: sphinx; extra == "docs"
Requires-Dist: pydata-sphinx-theme; extra == "docs"
Requires-Dist: nbsphinx; extra == "docs"
Requires-Dist: myst-parser; extra == "docs"
Requires-Dist: ipython; extra == "docs"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: matplotlib>=3.8; extra == "test"
Provides-Extra: dev
Requires-Dist: ruff<0.16,>=0.15; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: pybind11<4,>=2.12; extra == "dev"
Provides-Extra: notebooks
Requires-Dist: jupyter; extra == "notebooks"
Requires-Dist: ipykernel; extra == "notebooks"
Requires-Dist: nbconvert; extra == "notebooks"
Requires-Dist: matplotlib>=3.8; extra == "notebooks"
Requires-Dist: rapidfuzz>=3.0; extra == "notebooks"
Requires-Dist: scikit-learn>=1.3; extra == "notebooks"
Requires-Dist: logomaker>=0.8; extra == "notebooks"
Requires-Dist: biotite>=1.0; extra == "notebooks"
Description-Content-Type: text/markdown

# TCRen — structural evidence for T-cell recognition

[![PyPI](https://img.shields.io/pypi/v/tcren)](https://pypi.org/project/tcren/)
[![Tests](https://github.com/antigenomics/tcren/actions/workflows/tests.yml/badge.svg)](https://github.com/antigenomics/tcren/actions/workflows/tests.yml)
[![Documentation](https://github.com/antigenomics/tcren/actions/workflows/docs.yml/badge.svg)](https://docs.isalgo.dev/tcren/)
![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)

[Get started](https://docs.isalgo.dev/tcren/getting-started.html) · [Guides](https://docs.isalgo.dev/tcren/) · [Screening](https://docs.isalgo.dev/tcren/screening.html) · [API](https://docs.isalgo.dev/tcren/modules.html) · [Gallery](https://docs.isalgo.dev/tcren/gallery.html)

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/antigenomics/tcren/master/docs/_static/tcren-splash-dark.svg">
  <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/antigenomics/tcren/master/docs/_static/tcren-splash-light.svg">
  <img alt="TCRen contact graphs branch into a statistical-potential route for peptide ranking and measured affinity, response and kinetic associations, and an ipTM–Betti–enrichment route for binder/non-binder and binder/mock ranking. Geometry, visualization and statistics support both routes." src="https://raw.githubusercontent.com/antigenomics/tcren/master/docs/_static/tcren-splash.png" width="100%">
</picture>

TCRen turns TCR–peptide–MHC structures into **contact-based scores, receptor
rankings and interpretable structural readouts**. It brings two approaches into
one Python library and command-line toolkit:

- **Residue statistical potentials** rank candidate epitopes for a fixed TCR and
  support studies of measured binding affinity, response magnitude and kinetics.
  Contact energies, structural alanine references and mechanical readouts retain
  their separate definitions.
- **ipTM + Betti fraction + contact enrichment** rank candidate receptors against
  one pMHC, including binder/non-binder and binder/mock comparisons. The default
  combines generator confidence with global contact organisation and local
  evidence calibrated against frozen mock structures.

Geometry, surface chemistry, contact attribution, molecular visualization and
matched statistics help explain both routes.

## Start with your question

| Question | Route | Worked guide |
|---|---|---|
| Rank epitopes for one receptor | `score` for fixed-template threading; `screen --task epitope` for separately modelled poses | [Epitope ranking](https://docs.isalgo.dev/tcren/ranking.html) |
| Rank a cohort of modelled receptors for one pMHC | `screen --task tcr`: ipTM, Betti fraction and enrichment | [Receptor screening](https://docs.isalgo.dev/tcren/screening.html) |
| Rank paired receptor sequence candidates on a fixed template | `score-receptors`: fixed-contact CDR3 or observed-junction threading | [Candidate receptor scoring](https://docs.isalgo.dev/tcren/prediction.html) |
| How do structural scores relate to affinity or response magnitude? | Join measured endpoints, then `evaluate --kind continuous` | [Matched evaluation](https://docs.isalgo.dev/tcren/evaluation.html) |
| How do contacts and mechanics relate to kinetics? | `md`, `mechanics`, then matched endpoint evaluation | [Dynamics and kinetics](https://docs.isalgo.dev/tcren/md-validation.html) |
| Explore contacts, their contributions and enrichment | `contacts`, `export`, frozen motif readouts and residue-level attribution | [Contact evidence](https://docs.isalgo.dev/tcren/motif-confidence.html) |
| Why does a model receive this score? | `features`, `surface`, `superimpose` and geometry diagnostics | [Inspect a model](https://docs.isalgo.dev/tcren/kit.html) |
| How can I render or compare the evidence? | PyMOL scenes, contact maps, `associate`, `evaluate` | [Visualization gallery](https://docs.isalgo.dev/tcren/gallery.html) |

## Install and rank a receptor cohort

```sh
pip install tcren

tcren screen -s models.tar.gz --task tcr \
  --confidence confidence.tsv -o scores.tsv
```

Native Windows is supported without WSL. Install with `python -m pip install tcren`;
ARDA automatically prepares its Windows MMseqs2 runtime on first annotation.
Source builds require the Microsoft C++ Build Tools. The Windows CI job builds
the source stack and checks annotation and contacts on the bundled 1AO7 fixture.

Bundled source snapshots build the compact two-field MHC protein reference offline. Use
`tcren build-mhc-ref --all-alleles` only for explicit full-vocabulary fine mapping.

Supply separately modelled candidate receptors for **one peptide and MHC
background**. `confidence.tsv` contains unique `complex.id`, `iptm` on [0,1] and
`plddt` on [0,100]; IDs match the structure stems. TCRen reads generator
confidence from metadata or this table. Annotation is batched internally, and
`-t 0` selects the allocated CPU budget by default.

Wheels include five native extensions. [ARDA](https://github.com/antigenomics/arda)
provides TCR annotation and its first-use reference/search setup; the compact MHC
reference is built offline from packaged source snapshots. The [installation tutorial](https://docs.isalgo.dev/tcren/getting-started.html)
covers raw structures, input formats and first-run setup.

For peptides threaded onto one fixed template:

```sh
tcren score -s template.pdb -c peptides.txt --potential tcren2 -o energies.csv
```

For separately modelled peptides, use `screen --task epitope`. Its structural
alanine reference truncates peptide side chains in three dimensions and rebuilds
contacts before combining the energy difference with ipTM. Fixed-template
threading and separately modelled poses are different protocols.

## Read the receptor score

```text
S = (1 - 0.41*q - 0.22*(1-q))*ipTM + 0.41*q*B + 0.22*(1-q)*M
```

| Component | Structural meaning |
|---|---|
| `ipTM` | Generator interface confidence |
| `B` | Recognition graph cycle fraction, β₁/E, over CDR:peptide, peptide:MHC and CDR:MHC contacts |
| `M` | All-six-CDR/peptide local contact-cycle evidence, calibrated against 2,056 whole mock graphs |
| `q` | Inclusive percentile of unlabelled cohort-mean pLDDT against five frozen reference means |

For local enrichment, `r` indexes a tested CDR or peptide residue. Its statistic
is `c_r = m_r - k_r`: physical atom-pair contacts minus distinct partner residues.
`a_r` separately counts distinct contacted atoms. The default includes observed
backbone and side-chain heavy atoms; side-chain-only counting is available for
separate contact diagnostics.
The diagram sketches two contacted side-chain atoms making four contacts to two
peptide residues. The three inspection insets reuse public 1AO7 examples.

The weights are shared across a cohort: `q = F_ref(mean(plddt)/100)`, using
the frozen five-cohort confidence CDF. Individual ipTM, Betti and enrichment
values still vary between models. The weights are nonnegative and sum to one. Mock histograms and compressed
whole-control calibration ship with the package; scoring fits no new parameters.
Missing active values use flagged frozen training imputation. Read `screen_score`,
component values, weights, missingness and availability reasons together.

**Cohort mean remains the default.** Models without TCR:peptide contacts receive
score **0**, `no_interface=true`, a retained reason and a CLI warning. Never replace
this zero with raw ipTM. They do not count towards the default 30-model
floor. For one structure, explicitly select a representative confidence context:

```sh
tcren screen -s model.pdb --task tcr --confidence confidence.tsv \
  --confidence-context nearest-plddt --min-cohort 1 -o score.tsv
```

`nearest-mean-plddt` uses a small same-pMHC set's observed mean. Both alternatives
report support and distance to the selected frozen representative. See
[confidence contexts](https://docs.isalgo.dev/tcren/motif-confidence.html).
Supplied MHC names retain their declared resolution, separately from sequence
representatives; exact allele identity is not a term in the default score.

**Interpretation.** These are structural rankings and measured-endpoint
associations. Statistical contact energy is not physical binding free energy;
the combined receptor score is development-selected and is not a calibrated
binding probability. Representative confidence bins approximate cohort context.
Keep matched populations, component readouts and every cohort gain or loss visible.
[Score definitions](https://docs.isalgo.dev/tcren/screening.html) and
[reference dependencies](https://docs.isalgo.dev/tcren/fit-free.html) give the full contracts.

## Explore an application or reproduce a comparison

| Example | What you can reproduce |
|---|---|
| [Confidence-motif score notebook](https://github.com/antigenomics/tcren/blob/master/notebooks/confidence_motif_score.ipynb) | Self-contained frozen-score example, components and confidence contexts |
| [TCRvdb frozen-score reproduction](https://github.com/antigenomics/tcren/blob/master/notebooks/tcrvdb_frozen_score_reproduction.ipynb) | Accepted-score replay and matched comparisons from a supplied retained input bundle |
| [TTD contact exploration](https://github.com/antigenomics/tcren/blob/master/notebooks/ttd_contact_exploration.ipynb) | Inspect supplied TTDPSFLGRY models: contact chemistry, energy attribution and frozen enrichment |
| [Contacts and interaction types](https://github.com/antigenomics/tcren/blob/master/notebooks/contact_thresholds_and_bondtypes.ipynb) | Atom/residue contacts and chemical interaction labels |
| [Canonical molecular figures](https://github.com/antigenomics/tcren/blob/master/notebooks/pymol_canonical_figures.ipynb) | Reusable PyMOL scenes and canonical views |
| [Surface topology](https://github.com/antigenomics/tcren/blob/master/notebooks/surface_topology.ipynb) | Geometry and receptor-free pMHC surface readouts |
| [CLI reproduction guide](https://docs.isalgo.dev/tcren/reproduction.html) | Raw coordinates → exported components → matched binary or continuous evaluation |

The TCRvdb input bundle is supplied separately and is not distributed with the
package. Frozen-feature replay and raw-coordinate reproduction are distinct
checks. Public structure notebooks document their reference-data prerequisites;
PyMOL examples additionally need the PyMOL executable. For scientific comparisons,
pin the installed artifact and reference identities, preserve original labels and
report exact membership alongside the metrics. [SOURCES](https://github.com/antigenomics/tcren/blob/master/SOURCES)
records the bundled parameter provenance.

## Runtime and batching

One public 1AO7 structure (4,848 coordinate records), exporting 143 feature
columns on an Apple M3 Max with one compute CPU and existing annotation
references, took **7.70 seconds**. The matched pre-optimization observation took
8.65 seconds; outputs were byte-identical. Each timing is one unprofiled run.
Sampled process-tree RSS was 1.12 GB after the change and can double-count shared
pages. [Recorded workload and reference hashes](https://github.com/antigenomics/tcren/blob/master/docs/_static/runtime-1ao7.json)
make the scope explicit.

Pass a whole cohort in one command. Annotation searches and coarse descriptor
workers use separate bounded phases; avoid an outer pool of all-core commands.
Reference acquisition/index construction is separate setup work. See
[performance](https://docs.isalgo.dev/tcren/performance.html) for CPU budgets,
measurement and memory guidance; this single-structure example does not estimate
cohort throughput.

## Documentation and development

- **Learn:** [installation and first run](https://docs.isalgo.dev/tcren/getting-started.html),
  [worked score notebook](https://docs.isalgo.dev/tcren/notebooks/confidence_motif_score.html).
- **Do a task:** [ranking](https://docs.isalgo.dev/tcren/ranking.html),
  [inspection](https://docs.isalgo.dev/tcren/kit.html), [reproduction](https://docs.isalgo.dev/tcren/reproduction.html).
- **Look up a definition:** [score contract](https://docs.isalgo.dev/tcren/screening.html),
  [features](https://docs.isalgo.dev/tcren/features.html), [API](https://docs.isalgo.dev/tcren/modules.html).
- **Understand the evidence:** [reference dependencies](https://docs.isalgo.dev/tcren/fit-free.html),
  [confidence contexts](https://docs.isalgo.dev/tcren/motif-confidence.html).

```sh
./setup.sh --tests
uv pip install -e ".[dev,docs]"
.venv/bin/ruff check src tests
source .venv/bin/activate
make -C docs html SPHINXOPTS=-W
```

[Changelog](https://github.com/antigenomics/tcren/blob/master/docs/CHANGELOG.md) ·
[API skill](https://github.com/antigenomics/tcren/blob/master/skills/tcren/SKILL.md) ·
[Editable splash source](https://github.com/antigenomics/tcren/blob/master/docs/_static/tcren-splash.tex)

## CPU budgets

`threads=0` selects the available physical cores, constrained by CPU affinity,
scheduler allocation and container quota. On a fully allocated 20-core/40-thread
host, automatic selection uses 20 workers. Use `1` for serial work; an explicit
positive count may use logical CPUs within the allocation.

## License

TCRen is distributed under the [ISALGO LAB Academic and Non-Commercial Research License, version 1.0](https://github.com/antigenomics/tcren/blob/master/LICENSE).
