Porting DecompTCR to R, and finding out what a clonal trajectory model can actually tell you.
A transplant patient gives blood on day 3, day 14, day 30, and whenever clinic falls after that. Each draw yields a T cell receptor repertoire. Lining the draws up, every clone becomes a short, ragged time series. Some clones flare and vanish within two weeks. Some arrive late and never leave. Most flicker at the edge of detection. One patient carries tens of thousands of these series, sampled on days nobody chose for an analyst’s convenience.
The natural question is whether those series fall into a few recognizable behaviors and whether the behaviors mean anything clinically. The obvious tools all break. Binning visits into windows makes the bin edges the answer. Fitting a growth curve to each clone overfits five points. Clustering raw vectors reveals that no two patients share a time grid.
This fall a paper solved that problem cleanly. I have spent weeks since porting its method to R and finding where it bends. This post covers the original work, what changed in the rebuild, and what the model can actually identify. That last part turned out to be the interesting half.
The inspiration#
In September, Lingting Shi, Ajna Uzuni, Ximi Wang and colleagues in the Azizi and Reshef labs published a resource on graft-versus-host disease (GVHD) in Nature Immunology. The design is the asset. They fingerprinted alloreactive donor T cell clones before transplant, with a mixed lymphocyte reaction and TCRβ sequencing, then followed those clones in patient blood for up to two years. That gives a prospective, antigen-agnostic definition of a pathogenic clone. Nobody had to guess which clones mattered after the patient got sick. The cohort holds 57,062 alloreactive clones from 25 reactions, with a median of 8.5 time points per person. Few datasets in transplant immunology come close.
The paper carries several results I keep coming back to. Severe GVHD tracks how long alloreactive clones persist, not how high they peak. Post-transplant cyclophosphamide removes alloreactive clones only when they proliferated early, so a slow start is an escape route rather than a reassurance. In gut tissue, donor CD8 effector clones acquire a Hobit⁺PRDM1⁺ resident program as they move into the epithelium.
The computational centerpiece is DecompTCR, which adapts Decipher, a latent model from co-author Achille Nazaret. Its idea fits in one sentence. Keep the logic of non-negative matrix factorization, but make the time axis continuous.
$$\mu_i(t) = \sum_{k=1}^{K} \beta_{ik}\, b_k(t)$$Every clone’s trajectory \(\mu_i(t)\) is a weighted blend of the same small library of curves \(b_k(t)\). Picture the immune response as a DJ at a mixing desk with a handful of backing tracks. Every clone is a song mixed from those tracks and nothing else. The weights \(\beta_i\) are the fader positions, and they sum to one, so they encode shape rather than volume. Each track is a function of real time, so the model reads irregular visits where they fall.
The payoff is the figure the paper is built around. DecompTCR never saw a clinical label. Yet clones heavy on fast-contracting tracks came from patients who never developed GVHD, and clones heavy on tracks that step up around day 50 and stay up came from patients with severe disease. Then the authors also compared CDR3 biophysics two ways:
- Grouped by learned track, severe-pattern clones had shorter, less hydrophobic CDR3s.
- Grouped by clinical grade, the hydrophobicity difference disappeared.
That contrast is the best internal evidence that the decomposition sees something grading alone does not.
Why port it#
Three reasons, in order of how much they mattered.
- There was no way in from R. DecompTCR ships as Pyro and PyTorch notebooks in a reproducibility repository, which suits a resource paper. Our lab’s tools are R. Someone holding a scRepertoire object had no path to this analysis.
- Our first cohort looks nothing like theirs. The kidney transplant cohort has 327 repertoires from 54 recipients, and the deepest sample holds 4,753 times as many templates as the shallowest. A Gaussian likelihood on rescaled frequencies is reasonable when depth is comparable across samples. At a 4,753-fold spread it is not, because a clone missing from a 3,000-template sample and one missing from a 300,000-template sample are different observations.
- B cells. Somatic hypermutation fragments one lineage into many exact-sequence clones. A B cell trajectory has to follow the lineage, and the published method had no reason to handle that.
Two engines, one interface#
immSterna puts two engines behind one function. The first, decomptcr, reproduces the published code path. Its objective and gradient match the original implementation to machine precision at fixed parameters. It exists so anyone can check a published number against the published model. That check comes before changing anything.
The second engine, sterna, is the rebuild. Each change answers a need of our data, not a mistake in theirs.
Counts, not frequencies. A negative binomial likelihood on raw counts, with each sample’s depth as a log offset. An observed zero for a clone at a true frequency of \(2 \times 10^{-4}\) costs 0.59 log-likelihood units in a 3,000-template sample and 27.7 in a 300,000-template sample. The model weighs an absence by how hard anyone looked. Nothing gets bolted on.
A smaller basis. The paper used a small neural network per track, which suits the bursty dynamics of alloreactive clones. On a single time axis, a penalized spline with about 23 coefficients carries the same shapes with far fewer ways to land on them.
Shape and size, separated. An explicit amplitude \(s_i\) per clone, so the model becomes \(\mu_i(t) = s_i \sum_k \beta_{ik} b_k(t)\). Weights then compare across refits.
A stated rule for K. The paper fixed ten tracks, a sensible choice for exploration. immSterna picks the number by how well each candidate predicts clones from groups it never saw.
Subject-level tests. Enrichment tests permute the condition label across subjects, not clones. The function refuses to run until you name the nesting unit.
What the model can identify#
Porting took a few weeks. Finding what the model can identify took longer, and every result worth writing about came from that. Three stand out.
The trajectories recover. The tracks do not.#
On simulated cohorts with a known basis, fitted trajectories correlate with the truth from 0.93 to 0.98. Clone amplitudes recover from 0.96 to 0.97. The worst-matched individual track recovers from −0.14 to 0.80.
The cause is geometry. Many different track libraries reproduce every clone’s trajectory exactly as long as each clone sits inside the convex hull the tracks span. The equivalence stops only where non-negativity does. Two bases that correlate at 0.995 can produce trajectories agreeing to machine precision.
The practical reading is simple. Quote fitted trajectories and amplitudes with confidence. Treat any track as one of several equivalent descriptions. Match tracks across refits by correlation, never by index. In one cohort, two fits that read a correlation of −0.96 under their labels read +1.00 after a swap.
Visits limit the vocabulary, not cohort size#
With four sampling days, the clone-by-time mean matrix has rank at most four. Telling three tracks from two sits near that ceiling no matter how many patients you enroll. In simulation, selection called the right number of tracks in 7 of 12 settings at four sampling days and 11 of 12 at six. Every miss at four days was an under-call.
More subjects buy power. More clones per subject buy much less. More visits raise the ceiling. For anyone designing a longitudinal repertoire study, that ordering matters more than any modeling choice.
The unit of a test is the subject#
Clones from one patient share that patient. They share a conditioning regimen, an HLA type, an immunosuppression schedule, and a sampling calendar. Treating each clone as an independent observation is a common default in repertoire analysis, and it makes tests far too eager.
We measured how eager. Fifty-four simulated subjects, with 200 clones each; subjects differed at random, and the condition label was assigned at random. A clone-level Mann-Whitney test rejected at 0.805 against a nominal 0.05. A permutation of the label across subjects rejected at 0.068. The subject-level test gave up almost nothing. It detected a real shift on 93 percent of replicates at the largest effect we simulated, within 0.010 of a test on subject averages at every effect size.
This does not undo the GVHD paper’s biology. The hydrophobicity contrast compares two groupings of the same clones, so shared nesting cannot manufacture it. It does mean the next round of clone-dynamics papers, ours included, should lead with subject-level evidence.
Where next#
The first application we tested was a transplant cohort, with status at three months (stable, borderline, or rejecting) as the outcome. That cohort exposes the current wall. At 198,634 clones and ten tracks, a fit holds 15.7 GB in memory, and the cohort carries 150,000 to 750,000 trajectories. A hand-written derivative for the inner solve cuts memory 68-fold in testing.
Three directions follow.
- Depletion therapies. The cyclophosphamide result has a general shape. A drug that kills cycling cells cannot see a clone that has not divided. Antithymocyte globulin in kidney transplant raises the same question, and trajectory shape is the readout it needs.
- B cell lineages. immSterna builds trajectories on clonal lineages. On a simulated repertoire, lineage calling recovers the truth at an adjusted Rand index of 1.000, where exact-sequence matching reaches 0.065. That path goes live with the next scRepertoire release.
- One clone, three tissues. The transplant cohort sampled blood, kidney, and urine. Whether a model that knows one clone lives in three compartments earns its complexity is a question for the manuscript.
The GVHD paper showed that clones have temporal personalities, and that those personalities carry information no clinical grade captures. immSterna’s job is to make that question askable in any cohort, at any depth, with tests that hold their level. The tracks are shared.
Related reading: Shi et al. 2026, Spatiotemporal single-cell profiling reveals T cell clonal dynamics and phenotypic plasticity in human graft-versus-host disease, the paper and method this post builds on. The R package lives at BorchLab/immSterna.