Precursor frequency for an epitope#
Let \(C_e\) be the junctions that recognise epitope \(e\), and \(\pi(j)\) the probability of junction \(j\) in the chosen naive-chain population. The ideal frequency is
The complete set is unknown. This tutorial uses published human TRB observations to illustrate three quantities: raw generation mass of the catalogued junctions, mass in their overlapping Hamming neighborhoods, and predicted frequency after applying an explicit selection multiplier. A separate capture model illustrates extrapolation from re-reported observations. These calculations describe precursor modeling; they do not run vX annotation.
[1]:
# Environment: record the versions every number below depends on.
import os
from importlib.metadata import version
os.environ["POLARS_MAX_THREADS"] = "1"
THREADS = 4
import polars as pl
import vdjmatch
from vdjmatch import db, precursor as P
SEED = 0 # nothing here samples, but the VDJdb release pin is the reproducibility knob
VDJDB_TAG = "2026-06-11-ZENODO"
for pkg in ("vdjmatch", "vdjtools", "seqtree", "polars"):
print(f"{pkg:10s} {version(pkg)}")
vdjmatch 0.1.2
vdjtools 3.9.3
seqtree 0.7.0
polars 1.41.2
1. Load a cognate set#
CDR3 is not junction. VDJdb’s column is named cdr3 but holds junctions — Cys104 and Phe118/Trp included — which is what the recombination model wants. An anchor-stripped IMGT CDR3 scores exactly 0.0 with no error, so check_junctions exists to make that failure loud.
[2]:
# One well-sampled HLA-A*02:01 epitope: influenza A M1 58-66.
EPITOPE = "GILGFVFTL"
reference = db.fetch_hf(tag=VDJDB_TAG, asset="slim")
vdj = db.load(reference, species="HomoSapiens")
beta = vdj.filter((pl.col("gene") == "TRB") & (pl.col("epitope") == EPITOPE))
junctions, suspect = P.check_junctions(beta["cdr3"].unique().to_list())
junctions = sorted(set(junctions))
print(f"{EPITOPE}: {beta.height:,} records, {len(junctions):,} distinct junctions, "
f"{len(suspect)} failed the anchor check")
GILGFVFTL: 6,629 records, 6,627 distinct junctions, 2 failed the anchor check
2. Inspect generation probability#
observed_mass sums the recombination model’s generation probability over distinct recorded junctions. It gives a lower bound on the generation mass of the full cognate set if every recorded junction is cognate. Comparing it with a post-selection frequency requires a selection model. More readily generated junctions can be overrepresented in the catalogued set.
[3]:
# Per-junction Pgen, then how far apart the values are and how concentrated their sum is.
import numpy as np
model = P.load_model("TRB")
pg = np.array(P.pgen(model, junctions, threads=THREADS))
nz = np.sort(pg[pg > 0])[::-1]
print(f"observed_mass {P.observed_mass(model, junctions, threads=THREADS):.3e}")
print(f"median Pgen {np.median(nz):.3e}")
print(f"spread {np.log10(nz[0] / nz[-1]):.1f} orders of magnitude")
print(f"top-1 share of sum {nz[0] / nz.sum():.3f}")
print(f"top-10 share of sum {nz[:10].sum() / nz.sum():.3f}")
print(f"Pgen == 0 under model {(pg == 0).sum()}")
observed_mass 3.305e-04
median Pgen 1.724e-09
spread 30.0 orders of magnitude
top-1 share of sum 0.010
top-10 share of sum 0.080
Pgen == 0 under model 3
3. Count each neighborhood member once#
The example uses one substitution. Let \(B_r(a)\) be the Hamming ball of radius \(r\) around observed junction \(a\). Write \(m(B)\) for the sum of \(P_{\rm gen}\) over distinct junctions in set \(B\). For each junction \(x\), \(c(x)\) counts the balls that contain it. Then
The correction removes the extra copies of each multiply covered member. Only centers at distance at most \(2r\) can share a member, so the correction can work within the connected components of their overlap graph.
[4]:
# The exact union, and the double-counting a naive sum would have invented.
import time
t0 = time.perf_counter()
u = P.union_mass(model, junctions, r=1, threads=THREADS)
dt = time.perf_counter() - t0
print(f"naive per-sequence sum {u['naive_sum']:.3e}")
print(f"exact union {u['union']:.3e}")
print(f"double-counting avoided {u['overlap']:.1%}")
print(f"components {u['n_components']:,} "
f"({u['n_clustered']:,} of {u['n_seqs']:,} junctions have a close neighbour)")
print(f"Pgen calls for the correction: {u['n_multiply_covered']:,} "
f"(the union itself holds {u['n_union']:,}) [{dt:.1f}s]")
naive per-sequence sum 1.257e-02
exact union 7.432e-03
double-counting avoided 40.9%
components 2,968 (3,897 of 6,627 junctions have a close neighbour)
Pgen calls for the correction: 42,928 (the union itself holds 1,709,201) [39.5s]
[5]:
# Regression against the oracle: enumerate the union and score every member. Slow, and exact.
small = junctions[:150]
fast, oracle = P.union_mass(model, small, r=1, threads=THREADS), P.ball_mass(model, small, r=1, threads=THREADS)
rel = abs(fast["union"] - oracle["union"]) / oracle["union"]
print(f"union_mass {fast['union']:.9e}\nball_mass {oracle['union']:.9e}\nrelative {rel:.2e}")
union_mass 2.278723889e-04
ball_mass 2.278723889e-04
relative 1.19e-16
4. Weight substitutions by assumed cognacy retention#
A junction at minimum Hamming distance \(k\) from the recorded set contributes \(\alpha^k\) of its generation probability. The example uses the package’s per-edit retention convention, \(\alpha=0.1\), motivated by the measurements in Mayer and Callan. Successive union masses give exact mass in each minimum-distance shell. The overlap correction becomes expensive when many center neighborhoods intersect, particularly as the radius grows.
[6]:
# Shell-resolved mass with cognacy retention alpha = 0.1 per edit, at the recommended radius.
prof = P.shell_profile(model, junctions, r=1, alpha=0.1, threads=THREADS)
for s in prof["shells"]:
print(f" shell r={s['r']} weight {s['alpha']:.3f} n {s['n']:>9,} mass {s['mass']:.3e}")
print(f"\nraw union (alpha=1) {prof['union']:.3e}")
print(f"retained (alpha=0.1) {prof['retained']:.3e}")
print(f"observed bound {P.observed_mass(model, junctions, threads=THREADS):.3e}")
# Radius 2 on the whole set hits the component ceiling. That is the documented behaviour, not a
# crash: components are independent, so their union masses add exactly and splitting loses nothing.
try:
P.shell_profile(model, junctions, r=2, alpha=0.1, threads=THREADS)
except MemoryError as e:
print(f"\nr=2 on all {len(junctions):,} junctions ->\n {e}")
# On a subset small enough to fit, the radius-2 profile runs and shell 2 is the dominant volume.
prof2 = P.shell_profile(model, junctions[:200], r=2, alpha=0.1, threads=THREADS)
print("\nradius-2 profile on 200 of them:")
for s in prof2["shells"]:
print(f" shell r={s['r']} weight {s['alpha']:.3f} n {s['n']:>9,} mass {s['mass']:.3e}")
print(f" retained {prof2['retained']:.3e} against a raw union of {prof2['union']:.3e}")
shell r=0 weight 1.000 n 6,627 mass 3.305e-04
shell r=1 weight 0.100 n 1,702,574 mass 7.101e-03
raw union (alpha=1) 7.432e-03
retained (alpha=0.1) 1.041e-03
observed bound 3.305e-04
r=2 on all 6,627 junctions ->
one connected component of 1199 junctions has a radius-2 union of 43,726,919 sequences (~8.3 GB as Python strings), above max_members=20,000,000. Raise max_members if you have the memory, split this group, or lower r; components are independent, so their union masses add exactly and splitting by component loses nothing.
radius-2 profile on 200 of them:
shell r=0 weight 1.000 n 200 mass 8.251e-06
shell r=1 weight 0.100 n 53,380 mass 3.327e-04
shell r=2 weight 0.010 n 6,707,831 mass 4.134e-03
retained 8.287e-05 against a raw union of 4.475e-03
5. Estimate uncatalogued junctions#
The ball census counts how many union members are absent from the input set and how much model generation probability they carry. The capture estimator instead models repeated reporting across studies. It fits a capture scale \(\theta\) from the number of studies reporting each junction and uses inclusion probability \(1-\exp(-N\theta p_j)\), where \(N\) is the number of capture units and \(p_j=P_{\rm gen}(j)\). A re-reported junction counts once per study. The model assumes independent capture units and a shared scale.
Horvitz–Thompson mass and richness use weights \(p_j/[1-\exp(-N\theta p_j)]\) and \(1/[1-\exp(-N\theta p_j)]\), respectively. The mass weight has a finite limit at small \(p_j\); the richness weight grows without bound. Check degenerate and richness_reliable before reporting the result. The two estimates address different quantities.
[7]:
# Capture units: how many distinct studies re-reported each junction for this epitope.
mult = (beta.group_by("cdr3").agg(pl.col("reference_id").n_unique().alias("m"))
.filter(pl.col("cdr3").is_in(junctions)))
un = P.unseen_junctions(model, mult["cdr3"].to_list(), mult["m"].to_list(),
n_units=beta["reference_id"].n_unique(), threads=THREADS)
print(f"ball census: {u['n_union'] - u['n_seqs']:,} uncatalogued candidates "
f"carrying mass {prof['union'] - P.observed_mass(model, junctions, threads=THREADS):.3e}")
if un["degenerate"]:
print(f"Horvitz-Thompson: declined -- {un['reason']}")
else:
print(f"Horvitz-Thompson: {un['n_unseen']:,.0f} unseen carrying {un['unseen_mass']:.3e}; "
f"an average unseen junction is {un['rarity_ratio']:,.0f}x rarer than an observed one")
print(f" richness_reliable = {un['richness_reliable']} "
f"(min inclusion {un['min_inclusion']:.3g})")
ball census: 1,702,574 uncatalogued candidates carrying mass 7.101e-03
Horvitz-Thompson: declined -- every junction is a singleton: the capture curve is unidentified (theta -> 0, the Horvitz-Thompson sum diverges)
6. Convert model frequency to cells and occupancy#
The frequency estimate is \(\widehat F(e)=q\sum_{k=0}^r\alpha^k m_k\), where \(m_k\) is the generation mass of the minimum-distance shell \(k\). The multiplier \(q\) defaults to 1, the raw model scale. The example explicitly uses the published ALICE TRB factor, 9.41. The expected cell count is \(N_{\rm cells}c\widehat F(e)\), where \(c\) is the compartment fraction. For \(N_{\rm eff}\) independent rearrangements, the example reports Poisson occupancy with mean \(N_{\rm eff}\widehat F(e)\).
[8]:
# CD8 compartment of a 1e11-cell pool, and precursor probabilities at a realistic clonotype count.
out = P.precursor_frequency(model, junctions, r=1, q=P.ALICE_Q,
n_cells=1e11, compartment=0.3, n_eff=1e8, threads=THREADS)
print(f"F(e) {out['F']:.3e} (q = {out['q']}, alpha = {out['alpha']})")
print(f"expected cells {out['cells']:,.0f} of 1e11 x 0.3 CD8")
print(f"lambda {out['lambda']:.3g}")
print(f"P(>= 1 precursor) {out['p_ge_1']:.4f}")
print(f"P(>= 10) {out['p_ge_10']:.4f}")
F(e) 9.792e-03 (q = 9.41, alpha = 0.1)
expected cells 293,772,385 of 1e11 x 0.3 CD8
lambda 9.79e+05
P(>= 1 precursor) 1.0000
P(>= 10) 1.0000
7. Run the same estimator from the command line#
$ vdjmatch precursor --vdjdb --mhc-class MHCI --min-junctions 10 --q 9.41 -o precursor.tsv
VDJdb mode groups output by peptide and chain. For your own reference table, supply the path and use --group-by and --chain-col to identify groups.
The model estimates frequency, expected cells and occupancy under their declared assumptions. A response also depends on priming, help and tolerance. When comparing peptides, report their reference depths because the input sets directly affect their observed and neighborhood masses.